instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'GitLabChatApi' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise<AiActionResponseType> { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise<AiMessage> { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise<AiActionResponseType> { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> { const request: GraphQLRequest<AiMessagesResponseType> = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise<AiActionResponseType> { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest<AiActionResponseType> = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise<ChatInputTemplate> { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:87 - packages/webview_duo_chat/src/plugin/chat_controller.ts:11 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:52 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:118 - packages/webview_duo_chat/src/plugin/chat_controller.ts:24
You are a code assistant
Definition of 'FakeRequestHandler' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts in project gitlab-lsp
Definition: export interface FakeRequestHandler<T> { request: ApiRequest<T>; response: T; } export const createFakeFetchFromApi = (...handlers: FakeRequestHandler<unknown>[]): fetchFromApi => async <T>(request: ApiRequest<T>) => { const handler = handlers.find((h) => isEqual(h.request, request)); if (!handler) { throw new Error(`No fake handler to handle request: ${JSON.stringify(request)}`); } return handler.response as T; }; References:
You are a code assistant
Definition of 'GitLabChatFileContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts in project gitlab-lsp
Definition: export type GitLabChatFileContext = { fileName: string; selectedText: string; contentAboveCursor: string | null; contentBelowCursor: string | null; }; export const getActiveFileContext = (): GitLabChatFileContext | undefined => { const selectedText = getSelectedText(); const fileName = getActiveFileName(); if (!selectedText || !fileName) { return undefined; } return { selectedText, fileName, contentAboveCursor: getTextBeforeSelected(), contentBelowCursor: getTextAfterSelected(), }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:159 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts:4
You are a code assistant
Definition of 'onInstanceConnected' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp
Definition: onInstanceConnected(handler: WebviewMessageBusManagerHandler<T>) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:
You are a code assistant
Definition of 'AiMessageResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise<AiActionResponseType> { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise<AiMessage> { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise<AiActionResponseType> { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> { const request: GraphQLRequest<AiMessagesResponseType> = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise<AiActionResponseType> { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest<AiActionResponseType> = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise<ChatInputTemplate> { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:133
You are a code assistant
Definition of 'GitLabRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp
Definition: export interface GitLabRemote { host: string; /** * Namespace is the group(s) or user to whom the project belongs: https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-org/security` in the `gitlab-org/security/gitlab-vscode-extension` project */ namespace: string; /** * Path is the "project slug": https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-vscode-extension` in the `gitlab-org/gitlab-vscode-extension` project */ projectPath: string; /** * Namespace with path is the full project identifier: https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-org/gitlab-vscode-extension` */ namespaceWithPath: string; } // returns path without the trailing slash or empty string if there is no path const getInstancePath = (instanceUrl: string) => { const { pathname } = tryParseUrl(instanceUrl) || {}; return pathname ? pathname.replace(/\/$/, '') : ''; }; const escapeForRegExp = (str: string) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); function normalizeSshRemote(remote: string): string { // Regex to match git SSH remotes with custom port. // Example: [[email protected]:7999]:group/repo_name.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/309 const sshRemoteWithCustomPort = remote.match(`^\\[([a-zA-Z0-9_-]+@.*?):\\d+\\](.*)$`); if (sshRemoteWithCustomPort) { return `ssh://${sshRemoteWithCustomPort[1]}/${sshRemoteWithCustomPort[2]}`; } // Regex to match git SSH remotes with URL scheme and a custom port // Example: ssh://[email protected]:2222/fatihacet/gitlab-vscode-extension.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/644 const sshRemoteWithSchemeAndCustomPort = remote.match(`^ssh://([a-zA-Z0-9_-]+@.*?):\\d+(.*)$`); if (sshRemoteWithSchemeAndCustomPort) { return `ssh://${sshRemoteWithSchemeAndCustomPort[1]}${sshRemoteWithSchemeAndCustomPort[2]}`; } // Regex to match git SSH remotes without URL scheme and no custom port // Example: [email protected]:2222/fatihacet/gitlab-vscode-extension.git // For more information see this comment: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/611#note_1154175809 const sshRemoteWithPath = remote.match(`([a-zA-Z0-9_-]+@.*?):(.*)`); if (sshRemoteWithPath) { return `ssh://${sshRemoteWithPath[1]}/${sshRemoteWithPath[2]}`; } if (remote.match(`^[a-zA-Z0-9_-]+@`)) { // Regex to match gitlab potential starting names for ssh remotes. return `ssh://${remote}`; } return remote; } export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined { const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {}; if (!host || !pathname) { return undefined; } // The instance url might have a custom route, i.e. www.company.com/gitlab. This route is // optional in the remote url. This regex extracts namespace and project from the remote // url while ignoring any custom route, if present. For more information see: // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11 // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103 const pathRegExp = instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : ''; const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`); if (!match) { return undefined; } const [namespace, projectPath] = match.slice(1, 3); const namespaceWithPath = `${namespace}/${projectPath}`; return { host, namespace, projectPath, namespaceWithPath }; } References:
You are a code assistant
Definition of 'COMPLETION_PARAMS' in file src/common/test_utils/mocks.ts in project gitlab-lsp
Definition: export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:
You are a code assistant
Definition of 'createTreeSitterMiddleware' in file src/common/suggestion_client/tree_sitter_middleware.ts in project gitlab-lsp
Definition: export const createTreeSitterMiddleware = ({ treeSitterParser, getIntentFn, }: { treeSitterParser: TreeSitterParser; getIntentFn: typeof getIntent; }): SuggestionClientMiddleware => async (context, next) => { if (context.intent) { return next(context); } let treeAndLanguage: TreeAndLanguage | undefined; try { treeAndLanguage = await treeSitterParser.parseFile(context.document); } catch (err) { log.warn('Error determining user intent for code suggestion request.', err); } if (!treeAndLanguage) { return next(context); } const { intent } = await getIntentFn({ treeAndLanguage, position: context.document.position, prefix: context.document.prefix, suffix: context.document.suffix, }); return next({ ...context, intent }); }; References: - src/common/suggestion/suggestion_service.ts:167 - src/common/suggestion_client/tree_sitter_middleware.test.ts:38
You are a code assistant
Definition of 'DEFAULT_BACKOFF_MULTIPLIER' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'checkToken' in file src/common/api.ts in project gitlab-lsp
Definition: checkToken(token: string | undefined): Promise<TokenCheckResponse>; getCodeSuggestions(request: CodeSuggestionRequest): Promise<CodeSuggestionResponse | undefined>; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator<string, void, void>; fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<ActionCableCable>; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId<GitLabApiClient>('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise<TokenCheckResponse> { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise<TokenCheckResponse> { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise<CodeSuggestionResponse | undefined> { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator<string, void, void> { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`); } } async connectToCable(): Promise<ActionCableCable> { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest<T = unknown, V extends Variables = Variables>( document: RequestDocument, variables?: V, ): Promise<T> { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise<Response> => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch<T>( apiResourcePath: string, query: Record<string, QueryValue> = {}, resourceName = 'resource', headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise<T>; } async #postFetch<T>( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record<string, string>, ): Promise<T> { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise<T>; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise<string> { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:
You are a code assistant
Definition of 'FileSet' in file src/common/workspace/workspace_service.ts in project gitlab-lsp
Definition: type FileSet = Map<string, URI>; type WorkspaceService = typeof DefaultWorkspaceService.prototype; export const WorkspaceService = createInterfaceId<WorkspaceService>('WorkspaceService'); @Injectable(WorkspaceService, [VirtualFileSystemService]) export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map<string, FileSet>(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References: - src/common/workspace/workspace_service.ts:47
You are a code assistant
Definition of 'SOCKET_NOTIFICATION_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: export const SOCKET_NOTIFICATION_CHANNEL = 'notification'; export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus<TMessages extends MessageMap> implements MessageBus<TMessages> { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification<T extends keyof TMessages['outbound']['notifications']>( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise<void> { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest<T extends keyof TMessages['outbound']['requests'] & string>( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise<ExtractRequestResult<TMessages['outbound']['requests'][T]>> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult<TMessages['outbound']['requests'][T]>) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification<T extends keyof TMessages['inbound']['notifications'] & string>( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest<T extends keyof TMessages['inbound']['requests'] & string>( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise<ExtractRequestResult<TMessages['inbound']['requests'][T]>>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:
You are a code assistant
Definition of 'ITelemetryNotificationParams' in file src/common/message_handler.ts in project gitlab-lsp
Definition: export interface ITelemetryNotificationParams { category: 'code_suggestions'; action: TRACKING_EVENTS; context: { trackingId: string; optionId?: number; }; } export interface IStartWorkflowParams { goal: string; image: string; } export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class MessageHandler { #configService: ConfigService; #tracker: TelemetryTracker; #connection: Connection; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #duoProjectAccessCache: DuoProjectAccessCache; #featureFlagService: FeatureFlagService; #workflowAPI: WorkflowAPI | undefined; #virtualFileSystemService: VirtualFileSystemService; constructor({ telemetryTracker, configService, connection, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI = undefined, }: MessageHandlerOptions) { this.#configService = configService; this.#tracker = telemetryTracker; this.#connection = connection; this.#featureFlagService = featureFlagService; this.#workflowAPI = workflowAPI; this.#subscribeToCircuitBreakerEvents(); this.#virtualFileSystemService = virtualFileSystemService; this.#duoProjectAccessCache = duoProjectAccessCache; } didChangeConfigurationHandler = async ( { settings }: ChangeConfigOptions = { settings: {} }, ): Promise<void> => { this.#configService.merge({ client: settings, }); // update Duo project access cache await this.#duoProjectAccessCache.updateCache({ baseUrl: this.#configService.get('client.baseUrl') ?? '', workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [], }); await this.#virtualFileSystemService.initialize( this.#configService.get('client.workspaceFolders') ?? [], ); }; telemetryNotificationHandler = async ({ category, action, context, }: ITelemetryNotificationParams) => { if (category === CODE_SUGGESTIONS_CATEGORY) { const { trackingId, optionId } = context; if ( trackingId && canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action) ) { switch (action) { case TRACKING_EVENTS.ACCEPTED: if (optionId) { this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId }); } this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED); break; case TRACKING_EVENTS.REJECTED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED); break; case TRACKING_EVENTS.CANCELLED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED); break; case TRACKING_EVENTS.SHOWN: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN); break; case TRACKING_EVENTS.NOT_PROVIDED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED); break; default: break; } } } }; onShutdownHandler = () => { this.#subscriptions.forEach((subscription) => subscription?.dispose()); }; #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } async #sendWorkflowErrorNotification(message: string) { await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, { message, type: 'error', }); } startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => { const duoWorkflow = this.#featureFlagService.isClientFlagEnabled( ClientFeatureFlags.DuoWorkflow, ); if (!duoWorkflow) { await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`); return; } if (!this.#workflowAPI) { await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP'); return; } try { await this.#workflowAPI?.runWorkflow(goal, image); } catch (e) { log.error('Error in running workflow', e); await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`); } }; } References: - src/common/message_handler.ts:131
You are a code assistant
Definition of 'fetchBase' in file src/common/fetch.ts in project gitlab-lsp
Definition: fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>; } export const LsFetch = createInterfaceId<LsFetch>('LsFetch'); export class FetchBase implements LsFetch { updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'DuoWorkflowMessages' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp
Definition: export type DuoWorkflowMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { startWorkflow: { goal: string; image: string; }; stopWorkflow: []; openUrl: { url: string; }; }; }; pluginToWebview: { notifications: { workflowCheckpoints: LangGraphCheckpoint[]; workflowError: string; workflowStarted: string; workflowStatus: string; }; }; }>; References:
You are a code assistant
Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) { this.#documents = documents; this.#transformers.push(secretRedactor); } get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References:
You are a code assistant
Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References:
You are a code assistant
Definition of 'FileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp
Definition: export interface FileResolver { readFile(_args: ReadFile): Promise<string>; } export const FileResolver = createInterfaceId<FileResolver>('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise<string> { return Promise.resolve(''); } } References: - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:17 - src/common/services/duo_access/project_access_cache.ts:93
You are a code assistant
Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References:
You are a code assistant
Definition of 'createV2Request' in file src/common/suggestion_client/create_v2_request.ts in project gitlab-lsp
Definition: export const createV2Request = ( suggestionContext: SuggestionContext, modelDetails?: IDirectConnectionModelDetails, ): CodeSuggestionRequest => ({ prompt_version: 1, project_path: suggestionContext.projectPath ?? '', project_id: -1, current_file: { content_above_cursor: suggestionContext.document.prefix, content_below_cursor: suggestionContext.document.suffix, file_name: suggestionContext.document.fileRelativePath, }, choices_count: suggestionContext.optionsCount, ...(suggestionContext.intent && { intent: suggestionContext.intent }), ...(suggestionContext?.additionalContexts?.length && { context: suggestionContext.additionalContexts, }), ...(modelDetails || {}), }); References: - src/common/suggestion_client/default_suggestion_client.ts:15 - src/common/suggestion_client/create_v2_request.test.ts:27 - src/common/suggestion_client/direct_connection_client.ts:148
You are a code assistant
Definition of 'constructor' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp
Definition: constructor(timeInterval: number, maxItems: number, callback: SendEventCallback) { this.#maxItems = maxItems; this.#timeInterval = timeInterval; this.#callback = callback; this.#currentState = EmitterState.STOPPED; } add(data: PayloadBuilder) { this.#trackingQueue.push(data); if (this.#trackingQueue.length >= this.#maxItems) { this.#drainQueue().catch(() => {}); } } async #drainQueue(): Promise<void> { if (this.#trackingQueue.length > 0) { const copyOfTrackingQueue = this.#trackingQueue.map((e) => e); this.#trackingQueue = []; await this.#callback(copyOfTrackingQueue); } } start() { this.#timeout = setTimeout(async () => { await this.#drainQueue(); if (this.#currentState !== EmitterState.STOPPING) { this.start(); } }, this.#timeInterval); this.#currentState = EmitterState.STARTED; } async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References:
You are a code assistant
Definition of 'WebviewRequestInfo' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: export type WebviewRequestInfo = { requestId: string; }; export type WebviewEventInfo = { type: string; payload?: unknown; }; export type WebviewInstanceCreatedEventData = WebviewAddress; export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler<T> { (payload: T): void; } export interface TransportListener { on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable; } export interface TransportPublisher { publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>; } export interface Transport extends TransportListener, TransportPublisher {} References:
You are a code assistant
Definition of 'SuggestionClientFn' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References: - src/common/suggestion_client/tree_sitter_middleware.test.ts:18 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:40 - src/common/suggestion_client/suggestion_client.ts:47 - src/common/suggestion_client/suggestion_client_pipeline.ts:12
You are a code assistant
Definition of 'TreeAndLanguage' in file src/common/tree_sitter/parser.ts in project gitlab-lsp
Definition: export type TreeAndLanguage = { tree: Parser.Tree; languageInfo: TreeSitterLanguageInfo; language: Language; }; export abstract class TreeSitterParser { protected loadState: TreeSitterParserLoadState; protected languages: Map<string, TreeSitterLanguageInfo>; protected readonly parsers = new Map<TreeSitterLanguageName, Parser>(); abstract init(): Promise<void>; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> { const init = await this.#handleInit(); if (!init) { return undefined; } const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath); if (!languageInfo) { return undefined; } const parser = await this.getParser(languageInfo); if (!parser) { log.debug( 'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.', ); return undefined; } const tree = parser.parse(`${context.prefix}${context.suffix}`); return { tree, language: parser.getLanguage(), languageInfo, }; } async #handleInit(): Promise<boolean> { try { await this.init(); return true; } catch (err) { log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err); this.loadState = TreeSitterParserLoadState.ERRORED; } return false; } getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined { return this.getLanguageInfoForFile(filename)?.name; } async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> { if (this.parsers.has(languageInfo.name)) { return this.parsers.get(languageInfo.name) as Parser; } try { const parser = new Parser(); const language = await Parser.Language.load(languageInfo.wasmPath); parser.setLanguage(language); this.parsers.set(languageInfo.name, parser); log.debug( `TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`, ); return parser; } catch (err) { this.loadState = TreeSitterParserLoadState.ERRORED; // NOTE: We validate the below is not present in generation.test.ts integration test. // Make sure to update the test appropriately if changing the error. log.warn( 'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.', err, ); return undefined; } } getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined { const ext = filename.split('.').pop(); return this.languages.get(`.${ext}`); } buildTreeSitterInfoByExtMap( languages: TreeSitterLanguageInfo[], ): Map<string, TreeSitterLanguageInfo> { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map<string, TreeSitterLanguageInfo>()); } } References: - src/common/tree_sitter/intent_resolver.test.ts:32 - src/common/tree_sitter/intent_resolver.ts:31
You are a code assistant
Definition of 'onConfigChange' in file src/common/config_service.ts in project gitlab-lsp
Definition: onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:
You are a code assistant
Definition of 'setupWebviewPlugins' in file packages/lib_webview/src/setup/plugin/setup_plugins.ts in project gitlab-lsp
Definition: export function setupWebviewPlugins({ plugins, extensionMessageBusProvider, logger, runtimeMessageBus, }: setupWebviewPluginsProps) { logger.debug(`Setting up (${plugins.length}) plugins`); const compositeDisposable = new CompositeDisposable(); for (const plugin of plugins) { logger.debug(`Setting up plugin: ${plugin.id}`); const extensionMessageBus = extensionMessageBusProvider.getMessageBus(plugin.id); const webviewInstanceMessageBusFactory = (address: WebviewAddress) => { return new WebviewInstanceMessageBus(address, runtimeMessageBus, logger); }; const webviewController = new WebviewController( plugin.id, runtimeMessageBus, webviewInstanceMessageBusFactory, logger, ); const disposable = plugin.setup({ webview: webviewController, extension: extensionMessageBus, }); if (isDisposable(disposable)) { compositeDisposable.add(disposable); } } logger.debug('All plugins were set up successfully'); return compositeDisposable; } References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:24
You are a code assistant
Definition of 'ChatPlatform' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp
Definition: export class ChatPlatform implements GitLabPlatformBase { #client: GitLabApiClient; constructor(client: GitLabApiClient) { this.#client = client; } account: Account = { id: 'https://gitlab.com|16918910', instanceUrl: 'https://gitlab.com', } as Partial<Account> as Account; fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> { return this.#client.fetchFromApi(request); } connectToCable(): Promise<Cable> { return this.#client.connectToCable(); } getUserAgentHeader(): Record<string, string> { return {}; } } export class ChatPlatformForAccount extends ChatPlatform implements GitLabPlatformForAccount { readonly type = 'account' as const; project: undefined; } export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject { readonly type = 'project' as const; project: GitLabProject = { gqlId: 'gid://gitlab/Project/123456', restId: 0, name: '', description: '', namespaceWithPath: '', webUrl: '', }; } References:
You are a code assistant
Definition of 'DefaultAiPolicyManager' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp
Definition: export class DefaultAiPolicyManager { #policies: AiContextPolicy[] = []; constructor(duoProjectPolicy: DuoProjectPolicy) { this.#policies.push(duoProjectPolicy); } async runPolicies(aiContextProviderItem: AiContextProviderItem) { const results = await Promise.all( this.#policies.map(async (policy) => { return policy.isAllowed(aiContextProviderItem); }), ); const disallowedResults = results.filter((result) => !result.allowed); if (disallowedResults.length > 0) { const reasons = disallowedResults.map((result) => result.reason).filter(Boolean); return { allowed: false, reasons: reasons as string[] }; } return { allowed: true }; } } References:
You are a code assistant
Definition of 'DidChangeWorkspaceFoldersHandler' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp
Definition: export interface DidChangeWorkspaceFoldersHandler extends HandlesNotification<WorkspaceFoldersChangeEvent> {} export const DidChangeWorkspaceFoldersHandler = createInterfaceId<DidChangeWorkspaceFoldersHandler>('InitializeHandler'); @Injectable(DidChangeWorkspaceFoldersHandler, [ConfigService]) export class DefaultDidChangeWorkspaceFoldersHandler implements DidChangeWorkspaceFoldersHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler<WorkspaceFoldersChangeEvent> = ( params: WorkspaceFoldersChangeEvent, ): void => { const { added, removed } = params; const removedKeys = removed.map(({ name }) => name); const currentWorkspaceFolders = this.#configService.get('client.workspaceFolders') || []; const afterRemoved = currentWorkspaceFolders.filter((f) => !removedKeys.includes(f.name)); const afterAdded = [...afterRemoved, ...(added || [])]; this.#configService.set('client.workspaceFolders', afterAdded); }; } References: - src/common/core/handlers/did_change_workspace_folders_handler.test.ts:14 - src/common/connection_service.ts:63
You are a code assistant
Definition of 'WebviewTransportEventEmitterMessages' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp
Definition: export type WebviewTransportEventEmitterMessages = { [K in keyof MessagesToServer]: (payload: MessagesToServer[K]) => void; }; export type WebviewTransportEventEmitter = TypedEmitter<WebviewTransportEventEmitterMessages>; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References:
You are a code assistant
Definition of 'constructor' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise<DuoProject[]> { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise<GitlabRemoteAndFileUri[]> { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce<string[]>((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:
You are a code assistant
Definition of 'constructor' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: constructor(response: Response, resourceName: string, body?: string) { let message = `Fetching ${resourceName} from ${response.url} failed`; if (isInvalidTokenError(response, body)) { message = `Request for ${resourceName} failed because the token is expired or revoked.`; } if (isInvalidRefresh(response, body)) { message = `Request to refresh token failed, because it's revoked or already refreshed.`; } super(message); this.response = response; this.#body = body; } get status() { return this.response.status; } isInvalidToken(): boolean { return ( isInvalidTokenError(this.response, this.#body) || isInvalidRefresh(this.response, this.#body) ); } get details() { const { message, stack } = this; return { message, stack: stackToArray(stack), response: { status: this.response.status, headers: this.response.headers, body: this.#body, }, }; } } export class TimeoutError extends Error { constructor(url: URL | RequestInfo) { const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000); super( `Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`, ); } } export class InvalidInstanceVersionError extends Error {} References:
You are a code assistant
Definition of 'constructor' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map<WorkspaceFolderUri, RepositoryMap> = new Map(); #workspaceRepositoryTries: Map<WorkspaceFolderUri, RepositoryTrie> = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:
You are a code assistant
Definition of 'debug' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'UNSUPPORTED_GITLAB_VERSION' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:
You are a code assistant
Definition of 'generateRequestId' in file packages/lib_webview_client/src/generate_request_id.ts in project gitlab-lsp
Definition: export const generateRequestId = () => v4(); References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:43 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:104
You are a code assistant
Definition of 'Processor2' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:117 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:163
You are a code assistant
Definition of 'isCommentEmpty' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:
You are a code assistant
Definition of 'TypedSetter' in file src/common/utils/type_utils.d.ts in project gitlab-lsp
Definition: export interface TypedSetter<T> { <K1 extends keyof T>(key: `${K1 extends string ? K1 : never}`, value: T[K1]): void; /* * from 2nd level down, we need to qualify the values with `NonNullable` utility. * without doing that, we could possibly end up with a type `never` * as long as any key in the string concatenation is `never`, the concatenated type becomes `never` * and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T */ <K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`, value: T[K1][K2]): void; <K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>, K3 extends keyof NonNullable<NonNullable<T[K1]>[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`, value: T[K1][K2][K3]): void; } References:
You are a code assistant
Definition of 'dispose' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp
Definition: dispose(): void; } References:
You are a code assistant
Definition of 'constructor' in file src/common/secret_redaction/index.ts in project gitlab-lsp
Definition: constructor(configService: ConfigService) { this.#rules = rules.map((rule) => ({ ...rule, compiledRegex: new RegExp(convertToJavaScriptRegex(rule.regex), 'gmi'), })); this.#configService = configService; } transform(context: IDocContext): IDocContext { if (this.#configService.get('client.codeCompletion.enableSecretRedaction')) { return { prefix: this.redactSecrets(context.prefix), suffix: this.redactSecrets(context.suffix), fileRelativePath: context.fileRelativePath, position: context.position, uri: context.uri, languageId: context.languageId, workspaceFolder: context.workspaceFolder, }; } return context; } redactSecrets(raw: string): string { return this.#rules.reduce((redacted: string, rule: IGitleaksRule) => { return this.#redactRuleSecret(redacted, rule); }, raw); } #redactRuleSecret(str: string, rule: IGitleaksRule): string { if (!rule.compiledRegex) return str; if (!this.#keywordHit(rule, str)) { return str; } const matches = [...str.matchAll(rule.compiledRegex)]; return matches.reduce((redacted: string, match: RegExpMatchArray) => { const secret = match[rule.secretGroup ?? 0]; return redacted.replace(secret, '*'.repeat(secret.length)); }, str); } #keywordHit(rule: IGitleaksRule, raw: string) { if (!rule.keywords?.length) { return true; } for (const keyword of rule.keywords) { if (raw.toLowerCase().includes(keyword)) { return true; } } return false; } } References:
You are a code assistant
Definition of 'COMMAND_FETCH_BUFFER_FROM_API' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`; // Return type from `COMMAND_FETCH_BUFFER_FROM_API` export interface VSCodeBuffer { readonly buffer: Uint8Array; } // region: Shared configuration ---------------------------------------- export interface InteropConfig { projectPath: string; gitlabUrl: string; } // region: API types --------------------------------------------------- /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ export interface PostRequest<_TReturnType> { type: 'rest'; method: 'POST'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; body?: unknown; headers?: Record<string, string>; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ interface GetRequestBase<_TReturnType> { method: 'GET'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; searchParams?: Record<string, string>; headers?: Record<string, string>; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase<Uint8Array> { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchFromApi = <_TReturnType>( request: ApiRequest<_TReturnType>, ) => Promise<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>; /* API exposed by the Web IDE extension * See https://code.visualstudio.com/api/references/vscode-api#extensions */ export interface WebIDEExtension { isTelemetryEnabled: () => boolean; projectPath: string; gitlabUrl: string; } export interface ResponseError extends Error { status: number; body?: unknown; } References:
You are a code assistant
Definition of 'getActiveEditorText' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp
Definition: export const getActiveEditorText = (): string | null => { return ''; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return editor.document.getText(); }; export const getSelectedText = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection } = editor; // const selectionRange = new vscode.Range( // selection.start.line, // selection.start.character, // selection.end.line, // selection.end.character, // ); // return editor.document.getText(selectionRange); }; export const getActiveFileName = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return vscode.workspace.asRelativePath(editor.document.uri); }; export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References:
You are a code assistant
Definition of 'CreateHttpServerResult' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp
Definition: type CreateHttpServerResult = { address: URL; server: FastifyInstance; shutdown: () => Promise<void>; }; export const createFastifyHttpServer = async ( props: Partial<CreateFastifyServerProps>, ): Promise<CreateHttpServerResult> => { const { port = 0, plugins = [] } = props; const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:'); const server = fastify({ forceCloseConnections: true, ignoreTrailingSlash: true, logger: createFastifyLogger(logger), }); try { await registerPlugins(server, plugins, logger); const address = await startFastifyServer(server, port, logger); await server.ready(); logger?.info(`server listening on ${address}`); return { address, server, shutdown: async () => { try { await server.close(); logger?.info('server shutdown'); } catch (err) { logger?.error('error during server shutdown', err as Error); } }, }; } catch (err) { logger?.error('error during server setup', err as Error); throw err; } }; const registerPlugins = async ( server: FastifyInstance, plugins: FastifyPluginRegistration[], logger?: ILog, ) => { await Promise.all( plugins.map(async ({ plugin, options }) => { try { await server.register(plugin, options); } catch (err) { logger?.error('Error during plugin registration', err as Error); throw err; } }), ); }; const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise<URL> => new Promise((resolve, reject) => { try { server.listen({ port, host: '127.0.0.1' }, (err, address) => { if (err) { logger?.error(err); reject(err); return; } resolve(new URL(address)); }); } catch (error) { reject(error); } }); const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined => logger ? pino(createLoggerTransport(logger)) : undefined; References:
You are a code assistant
Definition of 'getForActiveProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp
Definition: getForActiveProject(userInitiated: boolean): Promise<GitLabPlatformForProject | undefined>; /** * Returns a GitLabPlatform for the active account * * This is how we decide what is "active account": * - If the user has signed in to a single GitLab account, it will return that account. * - If the user has signed in to multiple GitLab accounts, a UI picker will request the user to choose the desired account. */ getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined>; /** * onAccountChange indicates that any of the GitLab accounts in the extension has changed. * This can mean account was removed, added or the account token has been changed. */ // onAccountChange: vscode.Event<void>; getForAllAccounts(): Promise<GitLabPlatformForAccount[]>; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>; } References:
You are a code assistant
Definition of 'isAtOrNearEndOfLine' in file src/common/suggestion/suggestion_filter.ts in project gitlab-lsp
Definition: export function isAtOrNearEndOfLine(suffix: string) { const match = suffix.match(/\r?\n/); const lineSuffix = match ? suffix.substring(0, match.index) : suffix; // Remainder of line only contains characters within the allowed set // The reasoning for this regex is documented here: // https://gitlab.com/gitlab-org/editor-extensions/gitlab-language-server-for-code-suggestions/-/merge_requests/61#note_1608564289 const allowedCharactersPastCursorRegExp = /^\s*[)}\]"'`]*\s*[:{;,]?\s*$/; return allowedCharactersPastCursorRegExp.test(lineSuffix); } /** * Returns true when context.selectedCompletionInfo.range property represents a text * range in the document that doesn't match the text contained in context.selectedCompletionInfo.text. * * This scenario may occur in autocomplete dropdown widgets, for example VSCode's IntelliSense. * In such a case, it will not display the inline completion so we should not request the suggestion. * * @param context * @param document * @returns */ export function shouldRejectCompletionWithSelectedCompletionTextMismatch( context: InlineCompletionContext, document?: TextDocument, ): boolean { if (!context.selectedCompletionInfo || !document) { return false; } const currentText = document.getText(sanitizeRange(context.selectedCompletionInfo.range)); const selectedText = context.selectedCompletionInfo.text; return !selectedText.startsWith(currentText); } References: - src/common/suggestion/suggestion_service.ts:413 - src/common/suggestion/suggestion_filter.test.ts:25
You are a code assistant
Definition of 'constructor' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: constructor(api: GitLabApiClient, configService: ConfigService) { this.#api = api; this.#featureFlags = new Map(); this.#configService = configService; this.#api.onApiReconfigured(async ({ isInValidState }) => { if (!isInValidState) return; await this.#updateInstanceFeatureFlags(); }); } /** * Fetches the feature flags from the gitlab instance * and updates the internal state. */ async #fetchFeatureFlag(name: string): Promise<boolean> { try { const result = await this.#api.fetchFromApi<{ featureFlagEnabled: boolean }>({ type: 'graphql', query: INSTANCE_FEATURE_FLAG_QUERY, variables: { name }, }); log.debug(`FeatureFlagService: feature flag ${name} is ${result.featureFlagEnabled}`); return result.featureFlagEnabled; } catch (e) { // FIXME: we need to properly handle graphql errors // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/250 if (e instanceof ClientError) { const fieldDoesntExistError = e.message.match(/field '([^']+)' doesn't exist on type/i); if (fieldDoesntExistError) { // we expect graphql-request to throw an error when the query doesn't exist (eg. GitLab 16.9) // so we debug to reduce noise log.debug(`FeatureFlagService: query doesn't exist`, e.message); } else { log.error(`FeatureFlagService: error fetching feature flag ${name}`, e); } } return false; } } /** * Fetches the feature flags from the gitlab instance * and updates the internal state. */ async #updateInstanceFeatureFlags(): Promise<void> { log.debug('FeatureFlagService: populating feature flags'); for (const flag of Object.values(InstanceFeatureFlags)) { // eslint-disable-next-line no-await-in-loop this.#featureFlags.set(flag, await this.#fetchFeatureFlag(flag)); } } /** * Checks if a feature flag is enabled on the GitLab instance. * @see `GitLabApiClient` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean { return this.#featureFlags.get(name) ?? false; } /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean { const value = this.#configService.get('client.featureFlags')?.[name]; return value ?? false; } } References:
You are a code assistant
Definition of 'OpenTabsResolver' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp
Definition: export class OpenTabsResolver extends AdvancedContextResolver { static #instance: OpenTabsResolver | undefined; public static getInstance(): OpenTabsResolver { if (!OpenTabsResolver.#instance) { log.debug('OpenTabsResolver: initializing'); OpenTabsResolver.#instance = new OpenTabsResolver(); } return OpenTabsResolver.#instance; } public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator<ContextResolution> { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References: - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:9 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:13 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:13 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:10
You are a code assistant
Definition of 'FakeParser' in file src/common/tree_sitter/parser.test.ts in project gitlab-lsp
Definition: class FakeParser { setLanguage = jest.fn(); } jest.mocked(Parser).mockImplementation(() => createFakePartial<Parser>(new FakeParser())); const loadSpy = jest.spyOn(Parser.Language, 'load'); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(loadSpy).toHaveBeenCalledWith('/path/to/tree-sitter-typescript.wasm'); expect(result).toBeInstanceOf(FakeParser); }); it('should handle parser loading error', async () => { (Parser.Language.load as jest.Mock).mockRejectedValue(new Error('Loading error')); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); expect(result).toBeUndefined(); }); }); describe('getLanguageNameForFile', () => { it('should return the language name for a given file', () => { const result = treeSitterParser.getLanguageNameForFile('test.ts'); expect(result).toBe('typescript'); }); it('should return undefined when no language is found for a file', () => { const result = treeSitterParser.getLanguageNameForFile('test.txt'); expect(result).toBeUndefined(); }); }); describe('buildTreeSitterInfoByExtMap', () => { it('should build the language info map by extension', () => { const result = treeSitterParser.buildTreeSitterInfoByExtMap(languages); expect(result).toEqual( new Map([ ['.ts', languages[0]], ['.js', languages[1]], ]), ); }); }); }); References: - src/common/tree_sitter/parser.test.ts:127
You are a code assistant
Definition of 'WorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp
Definition: export const WorkspaceService = createInterfaceId<WorkspaceService>('WorkspaceService'); @Injectable(WorkspaceService, [VirtualFileSystemService]) export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map<string, FileSet>(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:
You are a code assistant
Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: constructor() { globCount++; } a = () => this.counter.toString(); } container.instantiate(Counter); container.instantiate(BImpl); expect(container.get(A).a()).toBe('0'); }); }); describe('get', () => { it('returns an instance of the interfaceId', () => { container.instantiate(AImpl); expect(container.get(A)).toBeInstanceOf(AImpl); }); it('throws an error for missing dependency', () => { container.instantiate(); expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/); }); }); }); References:
You are a code assistant
Definition of 'GitLabChatRecord' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp
Definition: export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial<GitLabChatRecordAttributes>) { const convertedAttributes = attributes as Partial<GitLabChatRecord>; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:49 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:82 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:19 - packages/webview_duo_chat/src/plugin/chat_controller.ts:111 - packages/webview_duo_chat/src/plugin/chat_controller.ts:66 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:34 - packages/webview_duo_chat/src/plugin/chat_controller.ts:127 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:13 - packages/webview_duo_chat/src/plugin/chat_controller.ts:106 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:35 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:81 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:10
You are a code assistant
Definition of 'WORKFLOW_MESSAGE_NOTIFICATION' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: export const WORKFLOW_MESSAGE_NOTIFICATION = '$/gitlab/workflowMessage'; export interface SuggestionServiceOptions { telemetryTracker: TelemetryTracker; configService: ConfigService; api: GitLabApiClient; connection: Connection; documentTransformerService: DocumentTransformerService; treeSitterParser: TreeSitterParser; featureFlagService: FeatureFlagService; duoProjectAccessChecker: DuoProjectAccessChecker; } export interface ITelemetryNotificationParams { category: 'code_suggestions'; action: TRACKING_EVENTS; context: { trackingId: string; optionId?: number; }; } export interface IStartWorkflowParams { goal: string; image: string; } export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class DefaultSuggestionService { readonly #suggestionClientPipeline: SuggestionClientPipeline; #configService: ConfigService; #api: GitLabApiClient; #tracker: TelemetryTracker; #connection: Connection; #documentTransformerService: DocumentTransformerService; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #suggestionsCache: SuggestionsCache; #treeSitterParser: TreeSitterParser; #duoProjectAccessChecker: DuoProjectAccessChecker; #featureFlagService: FeatureFlagService; #postProcessorPipeline = new PostProcessorPipeline(); constructor({ telemetryTracker, configService, api, connection, documentTransformerService, featureFlagService, treeSitterParser, duoProjectAccessChecker, }: SuggestionServiceOptions) { this.#configService = configService; this.#api = api; this.#tracker = telemetryTracker; this.#connection = connection; this.#documentTransformerService = documentTransformerService; this.#suggestionsCache = new SuggestionsCache(this.#configService); this.#treeSitterParser = treeSitterParser; this.#featureFlagService = featureFlagService; const suggestionClient = new FallbackClient( new DirectConnectionClient(this.#api, this.#configService), new DefaultSuggestionClient(this.#api), ); this.#suggestionClientPipeline = new SuggestionClientPipeline([ clientToMiddleware(suggestionClient), createTreeSitterMiddleware({ treeSitterParser, getIntentFn: getIntent, }), ]); this.#subscribeToCircuitBreakerEvents(); this.#duoProjectAccessChecker = duoProjectAccessChecker; } completionHandler = async ( { textDocument, position }: CompletionParams, token: CancellationToken, ): Promise<CompletionItem[]> => { log.debug('Completion requested'); const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token }); if (suggestionOptions.find(isStream)) { log.warn( `Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`, ); } return completionOptionMapper(suggestionOptions.filter(isTextSuggestion)); }; #getSuggestionOptions = async ( request: CompletionRequest, ): Promise<SuggestionOptionOrStream[]> => { const { textDocument, position, token, inlineCompletionContext: context } = request; const suggestionContext = this.#documentTransformerService.getContext( textDocument.uri, position, this.#configService.get('client.workspaceFolders') ?? [], context, ); if (!suggestionContext) { return []; } const cachedSuggestions = this.#useAndTrackCachedSuggestions( textDocument, position, suggestionContext, context?.triggerKind, ); if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) { const options = await this.#handleNonStreamingCompletion(request, suggestionContext); options.unshift(...(cachedSuggestions ?? [])); (cachedSuggestions ?? []).forEach((cs) => this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, { optionsCount: options.length, }), ); return options; } if (cachedSuggestions) { return cachedSuggestions; } // debounce await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS); if (token.isCancellationRequested) { log.debug('Debounce triggered for completion'); return []; } if ( context && shouldRejectCompletionWithSelectedCompletionTextMismatch( context, this.#documentTransformerService.get(textDocument.uri), ) ) { return []; } const additionalContexts = await this.#getAdditionalContexts(suggestionContext); // right now we only support streaming for inlineCompletion // if the context is present, we know we are handling inline completion if ( context && this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations) ) { const intentResolution = await this.#getIntent(suggestionContext); if (intentResolution?.intent === 'generation') { return this.#handleStreamingInlineCompletion( suggestionContext, intentResolution.commentForCursor?.content, intentResolution.generationType, additionalContexts, ); } } return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts); }; inlineCompletionHandler = async ( params: InlineCompletionParams, token: CancellationToken, ): Promise<InlineCompletionList> => { log.debug('Inline completion requested'); const options = await this.#getSuggestionOptions({ textDocument: params.textDocument, position: params.position, token, inlineCompletionContext: params.context, }); return inlineCompletionOptionMapper(params, options); }; async #handleStreamingInlineCompletion( context: IDocContext, userInstruction?: string, generationType?: GenerationType, additionalContexts?: AdditionalContext[], ): Promise<StartStreamOption[]> { if (this.#circuitBreaker.isOpen()) { log.warn('Stream was not started as the circuit breaker is open.'); return []; } const streamId = uniqueId('code-suggestion-stream-'); const uniqueTrackingId = generateUniqueTrackingId(); setTimeout(() => { log.debug(`Starting to stream (id: ${streamId})`); const streamingHandler = new DefaultStreamingHandler({ api: this.#api, circuitBreaker: this.#circuitBreaker, connection: this.#connection, documentContext: context, parser: this.#treeSitterParser, postProcessorPipeline: this.#postProcessorPipeline, streamId, tracker: this.#tracker, uniqueTrackingId, userInstruction, generationType, additionalContexts, }); streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e)); }, 0); return [{ streamId, uniqueTrackingId }]; } async #handleNonStreamingCompletion( request: CompletionRequest, documentContext: IDocContext, additionalContexts?: AdditionalContext[], ): Promise<SuggestionOption[]> { const uniqueTrackingId: string = generateUniqueTrackingId(); try { return await this.#getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }); } catch (e) { if (isFetchError(e)) { this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status }); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); this.#circuitBreaker.error(); log.error('Failed to get code suggestions!', e); return []; } } /** * FIXME: unify how we get code completion and generation * so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`) * */ async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> { try { const treeAndLanguage = await this.#treeSitterParser.parseFile(context); if (!treeAndLanguage) { return undefined; } return await getIntent({ treeAndLanguage, position: context.position, prefix: context.prefix, suffix: context.suffix, }); } catch (error) { log.error('Failed to parse with tree sitter', error); return undefined; } } #trackShowIfNeeded(uniqueTrackingId: string) { if ( !canClientTrackEvent( this.#configService.get('client.telemetry.actions'), TRACKING_EVENTS.SHOWN, ) ) { /* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server. Otherwise the server will assume that returned suggestions are shown and tracks the event */ this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); } } async #getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }: { request: CompletionRequest; uniqueTrackingId: string; documentContext: IDocContext; additionalContexts?: AdditionalContext[]; }): Promise<SuggestionOption[]> { const { textDocument, position, token } = request; const triggerKind = request.inlineCompletionContext?.triggerKind; log.info('Suggestion requested.'); if (this.#circuitBreaker.isOpen()) { log.warn('Code suggestions were not requested as the circuit breaker is open.'); return []; } if (!this.#configService.get('client.token')) { return []; } // Do not send a suggestion if content is less than 10 characters const contentLength = (documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0); if (contentLength < 10) { return []; } if (!isAtOrNearEndOfLine(documentContext.suffix)) { return []; } // Creates the suggestion and tracks suggestion_requested this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, triggerKind, additionalContexts, }); /** how many suggestion options should we request from the API */ const optionsCount: OptionsCount = triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1; const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({ document: documentContext, projectPath: this.#configService.get('client.projectPath'), optionsCount, additionalContexts, }); this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { model: suggestionsResponse?.model, status: suggestionsResponse?.status, optionsCount: suggestionsResponse?.choices?.length, isDirectConnection: suggestionsResponse?.isDirectConnection, }); if (suggestionsResponse?.error) { throw new Error(suggestionsResponse.error); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#circuitBreaker.success(); const areSuggestionsNotProvided = !suggestionsResponse?.choices?.length || suggestionsResponse?.choices.every(({ text }) => !text?.length); const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({ ...choice, index, uniqueTrackingId, lang: suggestionsResponse?.model?.lang, })); const processedChoices = await this.#postProcessorPipeline.run({ documentContext, input: suggestionOptions, type: 'completion', }); this.#suggestionsCache.addToSuggestionCache({ request: { document: textDocument, position, context: documentContext, additionalContexts, }, suggestions: processedChoices, }); if (token.isCancellationRequested) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); return []; } if (areSuggestionsNotProvided) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); return []; } this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions }); this.#trackShowIfNeeded(uniqueTrackingId); return processedChoices; } dispose() { this.#subscriptions.forEach((subscription) => subscription?.dispose()); } #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } #useAndTrackCachedSuggestions( textDocument: TextDocumentIdentifier, position: Position, documentContext: IDocContext, triggerKind?: InlineCompletionTriggerKind, ): SuggestionOption[] | undefined { const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({ document: textDocument, position, context: documentContext, }); if (suggestionsCache?.options?.length) { const { uniqueTrackingId, lang } = suggestionsCache.options[0]; const { additionalContexts } = suggestionsCache; this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, source: SuggestionSource.cache, triggerKind, suggestionOptions: suggestionsCache?.options, language: lang, additionalContexts, }); this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#trackShowIfNeeded(uniqueTrackingId); return suggestionsCache.options.map((option, index) => ({ ...option, index })); } return undefined; } async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> { let additionalContexts: AdditionalContext[] = []; const advancedContextEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextEnabled) { const advancedContext = await getAdvancedContext({ documentContext, dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker }, }); additionalContexts = advancedContextToRequestBody(advancedContext); } return additionalContexts; } } References:
You are a code assistant
Definition of 'WebviewMessageBusManagerHandler' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp
Definition: export type WebviewMessageBusManagerHandler<T extends MessageMap> = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection<T extends MessageMap> { broadcast: <TMethod extends keyof T['outbound']['notifications'] & string>( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler<T>) => void; } References:
You are a code assistant
Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: transform(context: IDocContext): IDocContext; } const getMatchingWorkspaceFolder = ( fileUri: DocumentUri, workspaceFolders: WorkspaceFolder[], ): WorkspaceFolder | undefined => workspaceFolders.find((wf) => fileUri.startsWith(wf.uri)); const getRelativePath = (fileUri: DocumentUri, workspaceFolder?: WorkspaceFolder): string => { if (!workspaceFolder) { // splitting a string will produce at least one item and so the pop can't return undefined // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fileUri.split(/[\\/]/).pop()!; } return fileUri.slice(workspaceFolder.uri.length).replace(/^\//, ''); }; export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) { this.#documents = documents; this.#transformers.push(secretRedactor); } get(uri: string) { return this.#documents.get(uri); } getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined { const doc = this.get(uri); if (doc === undefined) { return undefined; } return this.transform(getDocContext(doc, position, workspaceFolders, completionContext)); } transform(context: IDocContext): IDocContext { return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context); } } export function getDocContext( document: TextDocument, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext { let prefix: string; if (completionContext?.selectedCompletionInfo) { const { selectedCompletionInfo } = completionContext; const range = sanitizeRange(selectedCompletionInfo.range); prefix = `${document.getText({ start: document.positionAt(0), end: range.start, })}${selectedCompletionInfo.text}`; } else { prefix = document.getText({ start: document.positionAt(0), end: position }); } const suffix = document.getText({ start: position, end: document.positionAt(document.getText().length), }); const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders); const fileRelativePath = getRelativePath(document.uri, workspaceFolder); return { prefix, suffix, fileRelativePath, position, uri: document.uri, languageId: document.languageId, workspaceFolder, }; } References:
You are a code assistant
Definition of 'createInterfaceId' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: export const createInterfaceId = <T>(id: string): InterfaceId<T> => `${id}-${getRandomString()}` as InterfaceId<T>; /* * Takes an array of InterfaceIDs with unknown type and turn them into an array of the types that the InterfaceIds wrap * * e.g. `UnwrapInterfaceIds<[InterfaceId<string>, InterfaceId<number>]>` equals to `[string, number]` * * this type is used to enforce dependency types in the constructor of the injected class */ type UnwrapInterfaceIds<T extends InterfaceId<unknown>[]> = { [K in keyof T]: T[K] extends InterfaceId<infer U> ? U : never; }; interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap<object, Metadata>(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable<I, TDependencies extends InterfaceId<unknown>[]>( id: InterfaceId<I>, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function <T extends { new (...args: UnwrapInterfaceIds<TDependencies>): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set<string>(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map<string, ClassWithDependencies>): ClassWithDependencies[] => { const visited = new Set<string>(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance<T extends object> = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = <T extends object>( id: InterfaceId<T>, instance: T, ): BrandedInstance<T> => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map<string, unknown>(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been "branded" by the `brandInstance` method */ addInstances(...instances: BrandedInstance<object>[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map<string, ClassWithDependencies>(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get<T>(id: InterfaceId<T>): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.test.ts:57 - src/common/core/handlers/did_change_workspace_folders_handler.ts:10 - src/common/document_service.ts:23 - src/common/services/fs/dir.ts:38 - src/common/ai_context_management_2/ai_policy_management.ts:11 - src/common/connection_service.ts:31 - src/common/external_interfaces.ts:9 - src/common/ai_context_management_2/policies/duo_project_policy.ts:9 - src/common/api.ts:36 - src/common/suggestion/supported_languages_service.ts:24 - src/common/config_service.ts:108 - src/common/core/handlers/initialize_handler.ts:15 - src/common/graphql/workflow/service.ts:10 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:12 - src/common/core/handlers/token_check_notifier.ts:8 - packages/lib_di/src/index.test.ts:17 - src/common/services/fs/file.ts:11 - src/common/feature_state/supported_language_check.ts:14 - src/common/secret_redaction/index.ts:11 - src/common/fetch.ts:28 - src/node/duo_workflow/desktop_workflow_runner.ts:39 - src/common/feature_state/project_duo_acces_check.ts:17 - src/common/services/fs/virtual_file_service.ts:36 - src/common/services/duo_access/project_access_checker.ts:16 - src/common/feature_state/feature_state_manager.ts:17 - src/common/security_diagnostics_publisher.ts:27 - packages/lib_di/src/index.test.ts:18 - src/common/graphql/workflow/service.ts:9 - src/common/services/duo_access/project_access_cache.ts:83 - packages/lib_di/src/index.test.ts:16 - src/common/external_interfaces.ts:6 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:17 - src/common/advanced_context/advanced_context_service.ts:16 - src/common/tracking/tracking_types.ts:88 - src/common/ai_context_management_2/ai_context_manager.ts:9 - src/common/workspace/workspace_service.ts:16 - src/common/ai_context_management_2/ai_context_aggregator.ts:13 - src/common/feature_flags.ts:24 - src/common/document_transformer_service.ts:72 - src/common/git/repository_service.ts:24
You are a code assistant
Definition of 'dispose' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References:
You are a code assistant
Definition of 'JsonRpcConnectionTransport' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp
Definition: export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on<K extends keyof MessagesToServer>( type: K, callback: TransportMessageHandler<MessagesToServer[K]>, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void> { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - src/node/main.ts:186 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:19 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:8
You are a code assistant
Definition of 'constructor' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp
Definition: constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler<WorkspaceFoldersChangeEvent> = ( params: WorkspaceFoldersChangeEvent, ): void => { const { added, removed } = params; const removedKeys = removed.map(({ name }) => name); const currentWorkspaceFolders = this.#configService.get('client.workspaceFolders') || []; const afterRemoved = currentWorkspaceFolders.filter((f) => !removedKeys.includes(f.name)); const afterAdded = [...afterRemoved, ...(added || [])]; this.#configService.set('client.workspaceFolders', afterAdded); }; } References:
You are a code assistant
Definition of 'handleNotificationMessage' in file src/common/webview/extension/handlers/handle_notification_message.ts in project gitlab-lsp
Definition: export const handleNotificationMessage = (handlerRegistry: ExtensionMessageHandlerRegistry, logger: Logger) => async (message: unknown) => { if (!isExtensionMessage(message)) { logger.debug(`Received invalid request message: ${JSON.stringify(message)}`); return; } const { webviewId, type, payload } = message; try { await handlerRegistry.handle({ webviewId, type }, payload); } catch (error) { logger.error( `Failed to handle reuest for webviewId: ${webviewId}, type: ${type}, payload: ${JSON.stringify(payload)}`, error as Error, ); } }; References: - src/common/webview/extension/extension_connection_message_bus_provider.ts:79
You are a code assistant
Definition of 'runPolicies' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp
Definition: async runPolicies(aiContextProviderItem: AiContextProviderItem) { const results = await Promise.all( this.#policies.map(async (policy) => { return policy.isAllowed(aiContextProviderItem); }), ); const disallowedResults = results.filter((result) => !result.allowed); if (disallowedResults.length > 0) { const reasons = disallowedResults.map((result) => result.reason).filter(Boolean); return { allowed: false, reasons: reasons as string[] }; } return { allowed: true }; } } References:
You are a code assistant
Definition of 'FileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp
Definition: export const FileResolver = createInterfaceId<FileResolver>('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise<string> { return Promise.resolve(''); } } References: - src/common/services/duo_access/project_access_cache.ts:93 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:17
You are a code assistant
Definition of 'CHAT_MODEL_ROLES' in file packages/webview_duo_chat/src/app/constants.ts in project gitlab-lsp
Definition: export const CHAT_MODEL_ROLES = { user: 'user', system: 'system', assistant: 'assistant', }; export const SPECIAL_MESSAGES = { CLEAN: '/clean', CLEAR: '/clear', RESET: '/reset', }; References:
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References:
You are a code assistant
Definition of 'post' in file src/common/fetch.ts in project gitlab-lsp
Definition: async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'waitMs' in file src/common/message_handler.ts in project gitlab-lsp
Definition: export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class MessageHandler { #configService: ConfigService; #tracker: TelemetryTracker; #connection: Connection; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #duoProjectAccessCache: DuoProjectAccessCache; #featureFlagService: FeatureFlagService; #workflowAPI: WorkflowAPI | undefined; #virtualFileSystemService: VirtualFileSystemService; constructor({ telemetryTracker, configService, connection, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI = undefined, }: MessageHandlerOptions) { this.#configService = configService; this.#tracker = telemetryTracker; this.#connection = connection; this.#featureFlagService = featureFlagService; this.#workflowAPI = workflowAPI; this.#subscribeToCircuitBreakerEvents(); this.#virtualFileSystemService = virtualFileSystemService; this.#duoProjectAccessCache = duoProjectAccessCache; } didChangeConfigurationHandler = async ( { settings }: ChangeConfigOptions = { settings: {} }, ): Promise<void> => { this.#configService.merge({ client: settings, }); // update Duo project access cache await this.#duoProjectAccessCache.updateCache({ baseUrl: this.#configService.get('client.baseUrl') ?? '', workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [], }); await this.#virtualFileSystemService.initialize( this.#configService.get('client.workspaceFolders') ?? [], ); }; telemetryNotificationHandler = async ({ category, action, context, }: ITelemetryNotificationParams) => { if (category === CODE_SUGGESTIONS_CATEGORY) { const { trackingId, optionId } = context; if ( trackingId && canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action) ) { switch (action) { case TRACKING_EVENTS.ACCEPTED: if (optionId) { this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId }); } this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED); break; case TRACKING_EVENTS.REJECTED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED); break; case TRACKING_EVENTS.CANCELLED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED); break; case TRACKING_EVENTS.SHOWN: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN); break; case TRACKING_EVENTS.NOT_PROVIDED: this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED); break; default: break; } } } }; onShutdownHandler = () => { this.#subscriptions.forEach((subscription) => subscription?.dispose()); }; #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } async #sendWorkflowErrorNotification(message: string) { await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, { message, type: 'error', }); } startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => { const duoWorkflow = this.#featureFlagService.isClientFlagEnabled( ClientFeatureFlags.DuoWorkflow, ); if (!duoWorkflow) { await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`); return; } if (!this.#workflowAPI) { await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP'); return; } try { await this.#workflowAPI?.runWorkflow(goal, image); } catch (e) { log.error('Error in running workflow', e); await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`); } }; } References: - src/common/suggestion/suggestion_service.ts:232
You are a code assistant
Definition of 'LsConnection' in file src/common/external_interfaces.ts in project gitlab-lsp
Definition: export const LsConnection = createInterfaceId<LsConnection>('LsConnection'); export type LsTextDocuments = TextDocuments<TextDocument>; export const LsTextDocuments = createInterfaceId<LsTextDocuments>('LsTextDocuments'); References: - src/common/connection_service.ts:60 - src/common/connection_service.ts:53 - src/common/connection_service.ts:34 - src/common/connection_service.ts:38 - src/common/advanced_context/advanced_context_service.ts:34
You are a code assistant
Definition of 'greet5' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp
Definition: const greet5 = (name) => {}; const greet6 = (name) => { console.log(name); }; class Greet { constructor(name) {} greet() {} } class Greet2 { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:12
You are a code assistant
Definition of 'WEBVIEW_TITLE' in file packages/webview-chat/src/constants.ts in project gitlab-lsp
Definition: export const WEBVIEW_TITLE = 'GitLab: Duo Chat'; References:
You are a code assistant
Definition of 'dispose' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp
Definition: dispose() { this.#messageEmitter.removeAllListeners(); for (const connection of this.#connections.values()) { connection.disconnect(); } this.#connections.clear(); } } References:
You are a code assistant
Definition of 'getCommitsInMr' in file scripts/commit-lint/lint.js in project gitlab-lsp
Definition: async function getCommitsInMr() { const diffBaseSha = CI_MERGE_REQUEST_DIFF_BASE_SHA; const sourceBranchSha = LAST_MR_COMMIT; const messages = await read({ from: diffBaseSha, to: sourceBranchSha }); return messages; } const messageMatcher = (r) => r.test.bind(r); async function isConventional(message) { return lint( message, { ...config.rules, ...customRules }, { defaultIgnores: false, ignores: [ messageMatcher(/^[Rr]evert .*/), messageMatcher(/^(?:fixup|squash)!/), messageMatcher(/^Merge branch/), messageMatcher(/^\d+\.\d+\.\d+/), ], }, ); } async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } async function run() { if (!CI) { console.error('This script can only run in GitLab CI.'); process.exit(1); } if (!LAST_MR_COMMIT) { console.error( 'LAST_MR_COMMIT environment variable is not present. Make sure this script is run from `lint.sh`', ); process.exit(1); } const results = await lintMr(); console.error(format({ results }, { helpUrl: urlSemanticRelease })); const numOfErrors = results.reduce((acc, result) => acc + result.errors.length, 0); if (numOfErrors !== 0) { process.exit(1); } } run().catch((err) => { console.error(err); process.exit(1); }); References: - scripts/commit-lint/lint.js:54
You are a code assistant
Definition of 'CreatePluginMessageMap' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp
Definition: export type CreatePluginMessageMap<T extends PartialDeep<PluginMessageMap>> = { extensionToPlugin: CreateMessageDefinitions<T['extensionToPlugin']>; pluginToExtension: CreateMessageDefinitions<T['pluginToExtension']>; webviewToPlugin: CreateMessageDefinitions<T['webviewToPlugin']>; pluginToWebview: CreateMessageDefinitions<T['pluginToWebview']>; }; type WebviewPluginSetupParams<T extends PluginMessageMap> = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc<T extends PluginMessageMap> = ( context: WebviewPluginSetupParams<T>, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>; }; References:
You are a code assistant
Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp
Definition: processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise<SuggestionOption[]> { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run<T extends ProcessorType>({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise<ProcessorInputMap[T]> { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise<ProcessorInputMap[T]>; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise<ProcessorInputMap[T]>; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise<ProcessorInputMap[T]>, ); } } References:
You are a code assistant
Definition of 'megaError' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:
You are a code assistant
Definition of 'ISnowplowTrackerOptions' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record<string, boolean>; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:71 - src/common/utils/headers_to_snowplow_options.ts:8
You are a code assistant
Definition of 'pollWorkflowEvents' in file src/common/graphql/workflow/service.ts in project gitlab-lsp
Definition: async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void> { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise<void> => { try { const checkpoints: LangGraphCheckpoint[] = await this.getWorkflowEvents(workflowId); messageBus.sendNotification('workflowCheckpoints', checkpoints); const status = this.getStatus(checkpoints); messageBus.sendNotification('workflowStatus', status); // If the status is Completed, we dont call the next setTimeout and polling stops if (status !== 'Completed') { timeout = setTimeout(poll, 3000); } else { clearTimeout(timeout); } } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } }; await poll(); } async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> { try { const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({ type: 'graphql', query: GET_WORKFLOW_EVENTS_QUERY, variables: { workflowId: id }, }); return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []); } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } } } References:
You are a code assistant
Definition of 'LogLevel' in file src/common/log_types.ts in project gitlab-lsp
Definition: export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References: - src/common/log.ts:25 - src/common/config_service.ts:68 - src/common/log.ts:53 - src/common/log.test.ts:9 - src/common/log.ts:76
You are a code assistant
Definition of 'receive' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp
Definition: receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:
You are a code assistant
Definition of 'setFile' in file src/common/git/repository.ts in project gitlab-lsp
Definition: setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map<string, RepositoryFile> { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:
You are a code assistant
Definition of 'render' in file packages/webview_duo_chat/src/app/main.ts in project gitlab-lsp
Definition: render(createElement) { return createElement(App); }, }).$mount(); } References:
You are a code assistant
Definition of 'updateRequestInit' in file src/common/fetch.ts in project gitlab-lsp
Definition: updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'createFakeContext' in file src/common/advanced_context/lru_cache.test.ts in project gitlab-lsp
Definition: export function createFakeContext(overrides: Partial<IDocContext> = {}): IDocContext { return { prefix: '', suffix: '', fileRelativePath: 'file:///test.ts', position: { line: 0, character: 0 }, uri: 'file:///test.ts', languageId: 'typescript', workspaceFolder: { uri: 'file:///workspace', name: 'test-workspace', }, ...overrides, }; } describe('LruCache', () => { let lruCache: LruCache; beforeEach(() => { lruCache = LruCache.getInstance(TEST_BYTE_LIMIT); }); afterEach(() => { LruCache.destroyInstance(); }); describe('getInstance', () => { it('should return a singleton instance of LruCache', () => { const cache1 = LruCache.getInstance(TEST_BYTE_LIMIT); const cache2 = LruCache.getInstance(TEST_BYTE_LIMIT); expect(cache1).toBe(cache2); expect(cache1).toBeInstanceOf(LruCache); }); }); describe('updateFile', () => { it('should add a new file to the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context.uri)).toEqual(context); }); it('should update an existing file in the cache', () => { const context1 = createFakeContext(); const context2 = { ...context1, text: 'Updated text' }; lruCache.updateFile(context1); lruCache.updateFile(context2); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context1.uri)).toEqual(context2); }); }); describe('deleteFile', () => { it('should remove a file from the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile(context.uri); expect(lruCache.openFiles.size).toBe(0); expect(isDeleted).toBe(true); }); it(`should not remove a file that doesn't exist`, () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile('fake/uri/that/does/not.exist'); expect(lruCache.openFiles.size).toBe(1); expect(isDeleted).toBe(false); }); it('should return correct order of files after deletion', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.deleteFile(context2.uri); expect(lruCache.mostRecentFiles({ context: context1 })).toEqual([context3, context1]); }); }); describe('mostRecentFiles', () => { it('should return ordered files', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result).toEqual([context2, context3, context1]); }); it('should return the most recently accessed files in the same workspace', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const otherWorkspaceFolder = { uri: 'file:///other', name: 'other-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); const context4 = createFakeContext({ uri: 'file:///other/file4.ts', workspaceFolder: otherWorkspaceFolder, }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context4); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result.find((file) => file.uri === context4.uri)).toBeUndefined(); }); it('should include the current file if includeCurrentFile is true', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: true }); expect(result).toEqual([context2, context1]); }); it('should not include the current file if includeCurrentFile is false', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: false }); expect(result).toEqual([context1]); }); it('should return an empty array if no files match the criteria', () => { const context = createFakeContext(); const result = lruCache.mostRecentFiles({ context }); expect(result).toEqual([]); }); }); describe('updateFile with size limit', () => { it('should evict least recently used items when limit is reached', () => { const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', prefix: largeString, // 400 bytes suffix: '', }); const context4 = createFakeContext({ uri: 'file:///workspace/file4.ts', prefix: extraSmallString, // 50 bytes suffix: extraSmallString, // 50 bytes }); expect(lruCache.updateFile(context1)).toBeTruthy(); expect(lruCache.updateFile(context2)).toBeTruthy(); expect(lruCache.updateFile(context3)).toBeTruthy(); expect(lruCache.updateFile(context4)).toBeTruthy(); // The least recently used item (context1) should have been evicted expect(lruCache.openFiles.size).toBe(3); expect(lruCache.openFiles.has(context1.uri)).toBe(false); expect(lruCache.openFiles.has(context2.uri)).toBe(true); expect(lruCache.openFiles.has(context3.uri)).toBe(true); expect(lruCache.openFiles.has(context4.uri)).toBe(true); }); }); }); References: - src/common/advanced_context/lru_cache.test.ts:123 - src/common/advanced_context/lru_cache.test.ts:84 - src/common/advanced_context/lru_cache.test.ts:106 - src/common/advanced_context/lru_cache.test.ts:139 - src/common/advanced_context/lru_cache.test.ts:140 - src/common/advanced_context/lru_cache.test.ts:124 - src/common/advanced_context/lru_cache.test.ts:71 - src/common/advanced_context/lru_cache.test.ts:62 - src/common/advanced_context/lru_cache.test.ts:105 - src/common/advanced_context/lru_cache.test.ts:183 - src/common/advanced_context/lru_cache.test.ts:193 - src/common/advanced_context/lru_cache.test.ts:171 - src/common/advanced_context/lru_cache.test.ts:94 - src/common/advanced_context/lru_cache.test.ts:142 - src/common/advanced_context/lru_cache.test.ts:159 - src/common/advanced_context/lru_cache.test.ts:172 - src/common/advanced_context/lru_cache.test.ts:208 - src/common/advanced_context/lru_cache.test.ts:107 - src/common/advanced_context/lru_cache.test.ts:198 - src/common/advanced_context/lru_cache.test.ts:141 - src/common/advanced_context/lru_cache.test.ts:158 - src/common/advanced_context/lru_cache.test.ts:122 - src/common/advanced_context/lru_cache.test.ts:203
You are a code assistant
Definition of 'FakeResponseOptions' in file src/common/test_utils/create_fake_response.ts in project gitlab-lsp
Definition: interface FakeResponseOptions { status?: number; text?: string; json?: unknown; url?: string; headers?: Record<string, string>; } export const createFakeResponse = ({ status = 200, text = '', json = {}, url = '', headers = {}, }: FakeResponseOptions): Response => { return createFakePartial<Response>({ ok: status >= 200 && status < 400, status, url, text: () => Promise.resolve(text), json: () => Promise.resolve(json), headers: new Headers(headers), body: new ReadableStream({ start(controller) { // Add text (as Uint8Array) to the stream controller.enqueue(new TextEncoder().encode(text)); }, }), }); }; References: - src/common/test_utils/create_fake_response.ts:17
You are a code assistant
Definition of 'SocketIoMessageBusProvider' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts in project gitlab-lsp
Definition: export class SocketIoMessageBusProvider implements MessageBusProvider { readonly name = 'SocketIoMessageBusProvider'; getMessageBus<TMessages extends MessageMap>(webviewId: string): MessageBus<TMessages> | null { if (!webviewId) { return null; } const socketUri = getSocketUri(webviewId); const socket = io(socketUri); const bus = new SocketIoMessageBus<TMessages>(socket); return bus; } } References: - packages/lib_webview_client/src/bus/provider/get_default_providers.ts:6
You are a code assistant
Definition of 'locateFile' in file src/browser/tree_sitter/index.ts in project gitlab-lsp
Definition: locateFile(scriptName: string) { return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl); }, }); log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:
You are a code assistant
Definition of 'info' in file src/common/log_types.ts in project gitlab-lsp
Definition: info(e: Error): void; info(message: string, e?: Error): void; warn(e: Error): void; warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } export const LOG_LEVEL = { DEBUG: 'debug', INFO: 'info', WARNING: 'warning', ERROR: 'error', } as const; export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References:
You are a code assistant
Definition of 'createFakeCable' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp
Definition: export const createFakeCable = () => createFakePartial<Cable>({ subscribe: jest.fn(), disconnect: jest.fn(), }); export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:85 - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:26
You are a code assistant
Definition of 'MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: export const MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION = '17.3.0'; export const CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId } ) { requestId errors } } `, defaultVariables: {}, }; export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String $platformOrigin: String! ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId platformOrigin: $platformOrigin } ) { requestId errors } } `, defaultVariables: { platformOrigin: PLATFORM_ORIGIN, }, }; export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise<AiActionResponseType> { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise<AiMessage> { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise<AiActionResponseType> { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> { const request: GraphQLRequest<AiMessagesResponseType> = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise<AiActionResponseType> { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest<AiActionResponseType> = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise<ChatInputTemplate> { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:
You are a code assistant
Definition of 'FeatureStateNotificationParams' in file src/common/notifications.ts in project gitlab-lsp
Definition: export type FeatureStateNotificationParams = FeatureState[]; export const FeatureStateChangeNotificationType = new NotificationType<FeatureStateNotificationParams>(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType<TokenCheckNotificationParams>( TOKEN_CHECK_NOTIFICATION, ); // TODO: once the following clients are updated: // // - JetBrains: https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/main/src/main/kotlin/com/gitlab/plugin/lsp/GitLabLanguageServer.kt#L16 // // We should remove the `TextDocument` type from the parameter since it's deprecated export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri; export const DidChangeDocumentInActiveEditor = new NotificationType<DidChangeDocumentInActiveEditorParams>( '$/gitlab/didChangeDocumentInActiveEditor', ); References:
You are a code assistant
Definition of 'getActiveFileContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts in project gitlab-lsp
Definition: export const getActiveFileContext = (): GitLabChatFileContext | undefined => { const selectedText = getSelectedText(); const fileName = getActiveFileName(); if (!selectedText || !fileName) { return undefined; } return { selectedText, fileName, contentAboveCursor: getTextBeforeSelected(), contentBelowCursor: getTextAfterSelected(), }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts:8 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:23 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:17 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:30
You are a code assistant
Definition of 'DuoWorkflowEvents' in file packages/webview_duo_workflow/src/types.ts in project gitlab-lsp
Definition: export type DuoWorkflowEvents = { nodes: LangGraphCheckpoint[]; }; export type DuoWorkflowEventConnectionType = { duoWorkflowEvents: DuoWorkflowEvents; }; References: - packages/webview_duo_workflow/src/types.ts:10 - src/common/graphql/workflow/types.ts:10
You are a code assistant
Definition of 'generateWorkflowID' in file src/common/graphql/workflow/service.ts in project gitlab-lsp
Definition: generateWorkflowID(id: string): string { return `gid://gitlab/Ai::DuoWorkflows::Workflow/${id}`; } sortCheckpoints(checkpoints: LangGraphCheckpoint[]) { return [...checkpoints].sort((a: LangGraphCheckpoint, b: LangGraphCheckpoint) => { const parsedCheckpointA = JSON.parse(a.checkpoint); const parsedCheckpointB = JSON.parse(b.checkpoint); return new Date(parsedCheckpointA.ts).getTime() - new Date(parsedCheckpointB.ts).getTime(); }); } getStatus(checkpoints: LangGraphCheckpoint[]): string { const startingCheckpoint: LangGraphCheckpoint = { checkpoint: '{ "channel_values": { "status": "Starting" }}', }; const lastCheckpoint = checkpoints.at(-1) || startingCheckpoint; const checkpoint = JSON.parse(lastCheckpoint.checkpoint); return checkpoint?.channel_values?.status; } async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void> { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise<void> => { try { const checkpoints: LangGraphCheckpoint[] = await this.getWorkflowEvents(workflowId); messageBus.sendNotification('workflowCheckpoints', checkpoints); const status = this.getStatus(checkpoints); messageBus.sendNotification('workflowStatus', status); // If the status is Completed, we dont call the next setTimeout and polling stops if (status !== 'Completed') { timeout = setTimeout(poll, 3000); } else { clearTimeout(timeout); } } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } }; await poll(); } async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> { try { const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({ type: 'graphql', query: GET_WORKFLOW_EVENTS_QUERY, variables: { workflowId: id }, }); return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []); } catch (e) { const error = e as Error; this.#logger.error(error.message); throw new Error(error.message); } } } References:
You are a code assistant
Definition of 'pullAiMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: async pullAiMessage(requestId: string, role: string): Promise<AiMessage> { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise<AiActionResponseType> { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> { const request: GraphQLRequest<AiMessagesResponseType> = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise<AiActionResponseType> { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest<AiActionResponseType> = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise<ChatInputTemplate> { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:
You are a code assistant
Definition of 'postBuild' in file scripts/watcher/watch.ts in project gitlab-lsp
Definition: function postBuild() { const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1]; if (editor === 'vscode') { const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension'; return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)]; } console.warn('No editor specified, skipping post-build steps'); return [new Promise<void>((resolve) => resolve())]; } async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); References: - scripts/watcher/watch.ts:67
You are a code assistant
Definition of 'LanguageServerLanguageId' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp
Definition: export type LanguageServerLanguageId = | (typeof BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES)[number] | 'yaml'; /** * Use this function to get the path of a fixture file. * Pulls from the `src/tests/fixtures` directory. */ export const getFixturePath = (category: Category, filePath: string) => resolve(cwd(), 'src', 'tests', 'fixtures', category, filePath); /** * Use this function to get the test file and tree for a given fixture file * to be used for Tree Sitter testing purposes. */ export const getTreeAndTestFile = async ({ fixturePath, position, languageId, }: { fixturePath: string; position: Position; languageId: LanguageServerLanguageId; }) => { const parser = new DesktopTreeSitterParser(); const fullText = await readFile(fixturePath, 'utf8'); const { prefix, suffix } = splitTextFileForPosition(fullText, position); const documentContext = { uri: fsPathToUri(fixturePath), prefix, suffix, position, languageId, fileRelativePath: resolve(cwd(), fixturePath), workspaceFolder: { uri: 'file:///', name: 'test', }, } satisfies IDocContext; const treeAndLanguage = await parser.parseFile(documentContext); if (!treeAndLanguage) { throw new Error('Failed to parse file'); } return { prefix, suffix, fullText, treeAndLanguage }; }; /** * Mimics the "prefix" and "suffix" according * to the position in the text file. */ export const splitTextFileForPosition = (text: string, position: Position) => { const lines = text.split('\n'); // Ensure the position is within bounds const maxRow = lines.length - 1; const row = Math.min(position.line, maxRow); const maxColumn = lines[row]?.length || 0; const column = Math.min(position.character, maxColumn); // Get the part of the current line before the cursor and after the cursor const prefixLine = lines[row].slice(0, column); const suffixLine = lines[row].slice(column); // Combine lines before the current row for the prefix const prefixLines = lines.slice(0, row).concat(prefixLine); const prefix = prefixLines.join('\n'); // Combine lines after the current row for the suffix const suffixLines = [suffixLine].concat(lines.slice(row + 1)); const suffix = suffixLines.join('\n'); return { prefix, suffix }; }; References: - src/tests/unit/tree_sitter/test_utils.ts:35
You are a code assistant
Definition of 'parseGitLabRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp
Definition: export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined { const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {}; if (!host || !pathname) { return undefined; } // The instance url might have a custom route, i.e. www.company.com/gitlab. This route is // optional in the remote url. This regex extracts namespace and project from the remote // url while ignoring any custom route, if present. For more information see: // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11 // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103 const pathRegExp = instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : ''; const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`); if (!match) { return undefined; } const [namespace, projectPath] = match.slice(1, 3); const namespaceWithPath = `${namespace}/${projectPath}`; return { host, namespace, projectPath, namespaceWithPath }; } References: - src/common/services/duo_access/project_access_cache.ts:191 - src/common/services/git/git_remote_parser.test.ts:121 - src/common/services/git/git_remote_parser.test.ts:104 - src/common/services/git/git_remote_parser.test.ts:90 - src/common/services/git/git_remote_parser.test.ts:79 - src/common/services/git/git_remote_parser.test.ts:117
You are a code assistant
Definition of 'getForActiveAccount' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp
Definition: async getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined> { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise<GitLabPlatformForAccount[]> { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined> { return new ChatPlatformForAccount(this.#client); } } References:
You are a code assistant
Definition of 'A' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: interface A { a(): string; } interface B { b(): string; } interface C { c(): string; } const A = createInterfaceId<A>('A'); const B = createInterfaceId<B>('B'); const C = createInterfaceId<C>('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId<object>('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl, AImpl2)).toThrow( /The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/, ); }); it('detects duplicate id with pre-existing instance', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/); }); it('detects missing dependencies', () => { expect(() => container.instantiate(BImpl)).toThrow( /Class BImpl \(interface B\) depends on interfaces \[A]/, ); }); it('it uses existing instances as dependencies', () => { const aInstance = new AImpl(); const a = brandInstance(A, aInstance); container.addInstances(a); container.instantiate(BImpl); expect(container.get(B).b()).toBe('B(a)'); }); it("detects classes what aren't decorated with @Injectable", () => { class AImpl2 implements A { a = () => 'hello'; } expect(() => container.instantiate(AImpl2)).toThrow( /Classes \[AImpl2] are not decorated with @Injectable/, ); }); it('detects circular dependencies', () => { @Injectable(A, [C]) class ACircular implements A { a = () => 'hello'; constructor(c: C) { // eslint-disable-next-line no-unused-expressions c; } } expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow( /Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./, ); }); // this test ensures that we don't store any references to the classes and we instantiate them only once it('does not instantiate classes from previous instantiate call', () => { let globCount = 0; @Injectable(A, []) class Counter implements A { counter = globCount; constructor() { globCount++; } a = () => this.counter.toString(); } container.instantiate(Counter); container.instantiate(BImpl); expect(container.get(A).a()).toBe('0'); }); }); describe('get', () => { it('returns an instance of the interfaceId', () => { container.instantiate(AImpl); expect(container.get(A)).toBeInstanceOf(AImpl); }); it('throws an error for missing dependency', () => { container.instantiate(); expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/); }); }); }); References: - packages/lib_di/src/index.test.ts:29 - packages/lib_di/src/index.test.ts:27 - packages/lib_di/src/index.test.ts:38 - packages/lib_di/src/index.test.ts:42
You are a code assistant
Definition of 'FilterFunction' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: type FilterFunction<T> = (data: T) => boolean; interface Subscription<T> { listener: Listener<T>; filter?: FilterFunction<T>; } export class MessageBus<TMessageMap extends Record<string, unknown>> implements Disposable { #subscriptions = new Map<keyof TMessageMap, Set<Subscription<unknown>>>(); public subscribe<K extends keyof TMessageMap>( messageType: K, listener: Listener<TMessageMap[K]>, filter?: FilterFunction<TMessageMap[K]>, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set<Subscription<unknown>>(); const subscription: Subscription<unknown> = { listener: listener as Listener<unknown>, filter: filter as FilterFunction<unknown> | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish<K extends keyof TMessageMap>(messageType: K, data: TMessageMap[K]): void { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { Array.from(targetSubscriptions).forEach((subscription) => { const { listener, filter } = subscription as Subscription<TMessageMap[K]>; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners<K extends keyof TMessageMap>(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount<K extends keyof TMessageMap>(messageType: K): number { return this.#subscriptions.get(messageType)?.size ?? 0; } public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References:
You are a code assistant
Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestProcessor()); const invalidInput = { invalid: 'input' }; await expect( pipeline.run({ documentContext: mockContext, input: invalidInput as unknown as StreamingCompletionResponse, type: 'invalid' as 'stream', }), ).rejects.toThrow('Unexpected type in pipeline processing'); }); }); References: