instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'connectToCable' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: connectToCable(): Promise<Cable>; } References: - src/common/action_cable.test.ts:32 - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54
You are a code assistant
Definition of 'AI_MESSAGES_QUERY' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp
Definition: 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 'connectToCable' in file src/common/api.ts in project gitlab-lsp
Definition: 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: - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54 - src/common/action_cable.test.ts:32
You are a code assistant
Definition of 'FastFibonacciSolver' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp
Definition: export class FastFibonacciSolver implements FibonacciSolver { #memo: Map<number, number> = new Map(); #lastComputedIndex: number = 1; constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } solve(index: number): number { if (index < 0) { throw NegativeIndexError; } if (this.#memo.has(index)) { return this.#memo.get(index) as number; } let a = this.#memo.get(this.#lastComputedIndex - 1) as number; let b = this.#memo.get(this.#lastComputedIndex) as number; for (let i = this.#lastComputedIndex + 1; i <= index; i++) { const nextValue = a + b; a = b; b = nextValue; this.#memo.set(i, nextValue); } this.#lastComputedIndex = index; return this.#memo.get(index) as number; } } References: - packages/lib-pkg-2/src/fast_fibonacci_solver.test.ts:4 - packages/webview-chat/src/app/index.ts:11 - packages/lib-pkg-2/src/fast_fibonacci_solver.test.ts:7
You are a code assistant
Definition of 'RepositoryUri' in file src/common/git/repository.ts in project gitlab-lsp
Definition: type RepositoryUri = URI; export type RepositoryFile = { uri: RepoFileUri; repositoryUri: RepositoryUri; isIgnored: boolean; workspaceFolder: WorkspaceFolder; }; export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map<string, RepositoryFile>; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise<void> { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } 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: - src/common/git/repository.ts:11 - src/common/git/repository.ts:34
You are a code assistant
Definition of 'Entries' in file src/common/utils/get_entries.ts in project gitlab-lsp
Definition: type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][]; export const getEntries = <T extends { [s: string]: unknown }>(obj: T): Entries<T> => Object.entries(obj) as Entries<T>; References:
You are a code assistant
Definition of 'isSocketRequestMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp
Definition: export function isSocketRequestMessage(message: unknown): message is SocketIoRequestMessage { return ( typeof message === 'object' && message !== null && 'requestId' in message && typeof message.requestId === 'string' && 'type' in message && typeof message.type === 'string' ); } export function isSocketResponseMessage(message: unknown): message is SocketResponseMessage { return ( typeof message === 'object' && message !== null && 'requestId' in message && typeof message.requestId === 'string' ); } References: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:83
You are a code assistant
Definition of 'TextDocumentChangeListener' in file src/common/document_service.ts in project gitlab-lsp
Definition: export interface TextDocumentChangeListener { (event: TextDocumentChangeEvent<TextDocument>, handlerType: TextDocumentChangeListenerType): void; } export interface DocumentService { onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId<DocumentService>('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification<DidChangeDocumentInActiveEditorParams> { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments<TextDocument>; constructor(documents: TextDocuments<TextDocument>) { this.#documents = documents; this.#subscriptions.push( documents.onDidOpen(this.#createMediatorListener(TextDocumentChangeListenerType.onDidOpen)), ); documents.onDidChangeContent( this.#createMediatorListener(TextDocumentChangeListenerType.onDidChangeContent), ); documents.onDidClose(this.#createMediatorListener(TextDocumentChangeListenerType.onDidClose)); documents.onDidSave(this.#createMediatorListener(TextDocumentChangeListenerType.onDidSave)); } notificationHandler = (param: DidChangeDocumentInActiveEditorParams) => { const document = isTextDocument(param) ? param : this.#documents.get(param); if (!document) { log.error(`Active editor document cannot be retrieved by URL: ${param}`); return; } const event: TextDocumentChangeEvent<TextDocument> = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent<TextDocument>) => { this.#emitter.emit(DOCUMENT_CHANGE_EVENT_NAME, event, type); }; onDocumentChange(listener: TextDocumentChangeListener) { this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener), }; } } References: - src/common/feature_state/project_duo_acces_check.test.ts:18 - src/common/feature_state/supported_language_check.test.ts:25 - src/common/advanced_context/advanced_context_service.test.ts:23 - src/common/document_service.ts:19 - src/common/document_service.ts:73
You are a code assistant
Definition of 'FeatureStateCheck' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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 'MessagesToServer' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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 'StateCheckId' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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: - src/common/feature_state/state_check.ts:5 - src/common/feature_state/state_check.ts:11 - src/common/feature_state/feature_state_management_types.ts:21
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp
Definition: func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf("Hello %s\n", g.name) } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'WORKFLOW_EXECUTOR_VERSION' in file src/common/constants.ts in project gitlab-lsp
Definition: export const WORKFLOW_EXECUTOR_VERSION = 'v0.0.5'; export const SUGGESTIONS_DEBOUNCE_INTERVAL_MS = 250; export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`; References:
You are a code assistant
Definition of 'TokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp
Definition: export const TokenCheckNotifier = createInterfaceId<TokenCheckNotifier>('TokenCheckNotifier'); @Injectable(TokenCheckNotifier, [GitLabApiClient]) export class DefaultTokenCheckNotifier implements TokenCheckNotifier { #notify: NotifyFn<TokenCheckNotificationParams> | undefined; constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn<TokenCheckNotificationParams>) { this.#notify = callback; } } References: - src/common/core/handlers/token_check_notifier.test.ts:8 - src/common/connection_service.ts:61
You are a code assistant
Definition of 'DefaultSecurityDiagnosticsPublisher' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp
Definition: export class DefaultSecurityDiagnosticsPublisher implements SecurityDiagnosticsPublisher { #publish: DiagnosticsPublisherFn | undefined; #opts?: ISecurityScannerOptions; #featureFlagService: FeatureFlagService; constructor( featureFlagService: FeatureFlagService, configService: ConfigService, documentService: DocumentService, ) { this.#featureFlagService = featureFlagService; configService.onConfigChange((config: IConfig) => { this.#opts = config.client.securityScannerOptions; }); documentService.onDocumentChange( async ( event: TextDocumentChangeEvent<TextDocument>, handlerType: TextDocumentChangeListenerType, ) => { if (handlerType === TextDocumentChangeListenerType.onDidSave) { await this.#runSecurityScan(event.document); } }, ); } init(callback: DiagnosticsPublisherFn): void { this.#publish = callback; } async #runSecurityScan(document: TextDocument) { try { if (!this.#publish) { throw new Error('The DefaultSecurityService has not been initialized. Call init first.'); } if (!this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.RemoteSecurityScans)) { return; } if (!this.#opts?.enabled) { return; } if (!this.#opts) { return; } const url = this.#opts.serviceUrl ?? DEFAULT_SCANNER_SERVICE_URL; if (url === '') { return; } const content = document.getText(); const fileName = UriUtils.basename(URI.parse(document.uri)); const formData = new FormData(); const blob = new Blob([content]); formData.append('file', blob, fileName); const request = { method: 'POST', headers: { Accept: 'application/json', }, body: formData, }; log.debug(`Executing request to url="${url}" with contents of "${fileName}"`); const response = await fetch(url, request); await handleFetchError(response, 'security scan'); const json = await response.json(); const { vulnerabilities: vulns } = json; if (vulns == null || !Array.isArray(vulns)) { return; } const diagnostics: Diagnostic[] = vulns.map((vuln: Vulnerability) => { let message = `${vuln.name}\n\n${vuln.description.substring(0, 200)}`; if (vuln.description.length > 200) { message += '...'; } const severity = vuln.severity === 'high' ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning; // TODO: Use a more precise range when it's available from the service. return { message, range: { start: { line: vuln.location.start_line - 1, character: 0, }, end: { line: vuln.location.end_line, character: 0, }, }, severity, source: 'gitlab_security_scan', }; }); await this.#publish({ uri: document.uri, diagnostics, }); } catch (error) { log.warn('SecurityScan: failed to run security scan', error); } } } References: - src/common/security_diagnostics_publisher.test.ts:55
You are a code assistant
Definition of 'fsPathToUri' in file src/common/services/fs/utils.ts in project gitlab-lsp
Definition: export const fsPathToUri = (fsPath: string): URI => { return URI.file(fsPath); }; export const parseURIString = (uri: string): URI => { return URI.parse(uri); }; References: - src/common/services/duo_access/project_access_cache.test.ts:114 - src/common/services/duo_access/project_access_cache.test.ts:43 - src/common/services/duo_access/project_access_cache.test.ts:113 - src/common/services/duo_access/project_access_cache.test.ts:42 - src/tests/unit/tree_sitter/test_utils.ts:41 - src/common/services/duo_access/project_access_cache.test.ts:45 - src/node/services/fs/dir.ts:43 - src/common/services/duo_access/project_access_cache.test.ts:80 - src/common/services/duo_access/project_access_cache.test.ts:147 - src/common/services/duo_access/project_access_cache.test.ts:148 - src/common/services/fs/virtual_file_service.ts:51 - src/common/git/repository_service.ts:267
You are a code assistant
Definition of 'constructor' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'MessagePayload' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type MessagePayload = unknown | undefined; export type KeysWithOptionalValues<T> = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record<Method, MessagePayload>} NotificationMap */ export type NotificationMap = Record<Method, MessagePayload>; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher<TNotifications extends NotificationMap> { sendNotification<T extends KeysWithOptionalValues<TNotifications>>(type: T): void; sendNotification<T extends keyof TNotifications>(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References: - packages/lib_message_bus/src/types/bus.ts:61 - packages/lib_message_bus/src/types/bus.ts:62
You are a code assistant
Definition of 'getContext' in file src/common/document_transformer_service.ts in project gitlab-lsp
Definition: 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 'hasbinSomeSync' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/["]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } export function fileExists(filePath: string, done: (result: boolean) => void) { stat(filePath, function (error, stat) { if (error) { return done(false); } done(stat.isFile()); }); } export function fileExistsSync(filePath: string) { try { return statSync(filePath).isFile(); } catch (error) { return false; } } References:
You are a code assistant
Definition of 'NotificationCall' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts in project gitlab-lsp
Definition: type NotificationCall = [string, (message: unknown) => void]; return (connection.onNotification.mock.calls as unknown as NotificationCall[]).find( ([notificationMethod]) => notificationMethod === method, )?.[1]; } References:
You are a code assistant
Definition of 'instantiate' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'chatWebviewPlugin' in file packages/webview-chat/src/plugin/index.ts in project gitlab-lsp
Definition: export const chatWebviewPlugin: WebviewPlugin<ChatMessages> = { id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview }) => { webview.onInstanceConnected((_webviewInstanceId, messageBus) => { messageBus.sendNotification('newUserPrompt', { prompt: 'This is a new prompt', }); }); }, }; References:
You are a code assistant
Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp
Definition: constructor( manager: GitLabPlatformManagerForChat, webviewMessageBus: DuoChatWebviewMessageBus, extensionMessageBus: DuoChatExtensionMessageBus, ) { this.#api = new GitLabChatApi(manager); this.chatHistory = []; this.#webviewMessageBus = webviewMessageBus; this.#extensionMessageBus = extensionMessageBus; this.#setupMessageHandlers.bind(this)(); } dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References:
You are a code assistant
Definition of 'GitLabAPI' in file src/common/api.ts in project gitlab-lsp
Definition: 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: - src/common/api.test.ts:39 - src/common/api.test.ts:486 - src/common/api.test.ts:83
You are a code assistant
Definition of 'stop' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp
Definition: async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:
You are a code assistant
Definition of 'HandlerNotFoundError' in file packages/lib_handler_registry/src/errors/handler_not_found_error.ts in project gitlab-lsp
Definition: export class HandlerNotFoundError extends Error { readonly type = 'HandlerNotFoundError'; constructor(key: string) { const message = `Handler not found for key ${key}`; super(message); } } References: - packages/lib_handler_registry/src/registry/simple_registry.ts:32
You are a code assistant
Definition of 'InstanceFeatureFlags' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: export enum InstanceFeatureFlags { EditorAdvancedContext = 'advanced_context_resolver', CodeSuggestionsContext = 'code_suggestions_context', } export const INSTANCE_FEATURE_FLAG_QUERY = gql` query featureFlagsEnabled($name: String!) { featureFlagEnabled(name: $name) } `; export const FeatureFlagService = createInterfaceId<FeatureFlagService>('FeatureFlagService'); export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map<string, boolean> = new Map(); 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: - src/common/feature_flags.ts:32 - src/common/feature_flags.ts:107
You are a code assistant
Definition of 'SuggestionOption' in file src/common/api_types.ts in project gitlab-lsp
Definition: export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References: - src/common/utils/suggestion_mapper.test.ts:59 - src/common/utils/suggestion_mapper.test.ts:51 - src/common/utils/suggestion_mappers.ts:37 - src/common/utils/suggestion_mapper.test.ts:12
You are a code assistant
Definition of 'HtmlTransformPlugin' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp
Definition: export const HtmlTransformPlugin = { name: 'html-transform', transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default ""'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default "data:image/svg+xml;base64,${base64Data}"`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:
You are a code assistant
Definition of 'isWebviewAddress' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp
Definition: export const isWebviewAddress: MessageValidator<WebviewAddress> = ( message: unknown, ): message is WebviewAddress => typeof message === 'object' && message !== null && 'webviewId' in message && 'webviewInstanceId' in message; export const isWebviewInstanceCreatedEventData: MessageValidator< WebviewInstanceCreatedEventData > = (message: unknown): message is WebviewInstanceCreatedEventData => isWebviewAddress(message); export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References: - packages/lib_webview_transport/src/utils/message_validators.ts:24 - packages/lib_webview_transport/src/utils/message_validators.ts:29 - packages/lib_webview_transport/src/utils/message_validators.ts:20
You are a code assistant
Definition of 'getProjectGqlId' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: async getProjectGqlId(): Promise<string | undefined> { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise<GitLabEnvironment> { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:
You are a code assistant
Definition of 'DuoChatExtensionMessageBus' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp
Definition: export type DuoChatExtensionMessageBus = MessageBus<{ inbound: Messages['extensionToPlugin']; outbound: Messages['pluginToExtension']; }>; /** * These types are copied from ./src/common/api_types.ts * TODO: move these types to a common package */ // why: `_TReturnType` helps encapsulate the full request type when used with `fetchFromApi` /* eslint @typescript-eslint/no-unused-vars: ["error", { "varsIgnorePattern": "TReturnType" }] */ /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'POST'; body?: unknown; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record<string, string>; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>; connectToCable(): Promise<Cable>; } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:13 - packages/webview_duo_chat/src/plugin/chat_controller.ts:22
You are a code assistant
Definition of 'CreateMessageMap' in file packages/lib_message_bus/src/types/utils.ts in project gitlab-lsp
Definition: export type CreateMessageMap<T extends PartialDeep<MessageMap>> = MessageMap< CreateMessageDefinitions<T['inbound']>, CreateMessageDefinitions<T['outbound']> >; References:
You are a code assistant
Definition of 'AiContextProvider' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp
Definition: export interface AiContextProvider { getProviderItems( query: string, workspaceFolder: WorkspaceFolder[], ): Promise<AiContextProviderItem[]>; } References:
You are a code assistant
Definition of 'CompletionRequest' in file src/common/message_handler.ts in project gitlab-lsp
Definition: 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:389 - src/common/suggestion/suggestion_service.ts:324 - src/common/suggestion/suggestion_service.ts:193
You are a code assistant
Definition of 'SupportedLanguagesService' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp
Definition: export interface SupportedLanguagesService { isLanguageEnabled(languageId: string): boolean; isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set<string>; #supportedLanguages: Set<string>; #configService: ConfigService; #eventEmitter = new EventEmitter(); constructor(configService: ConfigService) { this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); this.#configService = configService; this.#configService.onConfigChange(() => this.#update()); } #getConfiguredLanguages() { const languages: SupportedLanguagesUpdateParam = {}; const additionalLanguages = this.#configService.get( 'client.codeCompletion.additionalLanguages', ); if (Array.isArray(additionalLanguages)) { languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier); } else { log.warn( 'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.', ); } const disabledSupportedLanguages = this.#configService.get( 'client.codeCompletion.disabledSupportedLanguages', ); if (Array.isArray(disabledSupportedLanguages)) { languages.deny = disabledSupportedLanguages; } else { log.warn( 'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.', ); } return languages; } #update() { const { allow = [], deny = [] } = this.#getConfiguredLanguages(); const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES); for (const language of allow) { newSet.add(language.trim()); } for (const language of deny) { newSet.delete(language); } if (newSet.size === 0) { log.warn('All languages have been disabled for Code Suggestions.'); } const previousEnabledLanguages = this.#enabledLanguages; this.#enabledLanguages = newSet; if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) { this.#triggerChange(); } } isLanguageSupported(languageId: string) { return this.#supportedLanguages.has(languageId); } isLanguageEnabled(languageId: string) { return this.#enabledLanguages.has(languageId); } onLanguageChange(listener: () => void): Disposable { this.#eventEmitter.on('languageChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('languageChange'); } #normalizeLanguageIdentifier(language: string) { return language.trim().toLowerCase().replace(/^\./, ''); } } References: - src/common/advanced_context/advanced_context_service.ts:30 - src/common/feature_state/supported_language_check.ts:24 - src/common/feature_state/supported_language_check.ts:32 - src/common/advanced_context/advanced_context_service.ts:37
You are a code assistant
Definition of 'dispose' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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 'postBuildVscCodeYalcPublish' in file scripts/watcher/watch.ts in project gitlab-lsp
Definition: async function postBuildVscCodeYalcPublish(vsCodePath: string) { const commandCwd = resolvePath(cwd(), vsCodePath); await runScript('npx [email protected] publish'); console.log(successColor, 'Pushed to yalc'); await runScript('npx [email protected] add @gitlab-org/gitlab-lsp', commandCwd); } /** * additionally copy to desktop assets so the developer * does not need to restart the extension host */ async function postBuildVSCodeCopyFiles(vsCodePath: string) { const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`; try { await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir); console.log(successColor, 'Copied files to vscode extension'); } catch (error) { console.error(errorColor, 'Whoops, something went wrong...'); console.error(error); } } 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:55
You are a code assistant
Definition of 'MessageDefinitions' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References: - packages/lib_webview_plugin/src/webview_plugin.ts:13 - packages/lib_webview_plugin/src/webview_plugin.ts:14 - packages/lib_webview_plugin/src/webview_plugin.ts:15 - packages/lib_webview_plugin/src/webview_plugin.ts:12
You are a code assistant
Definition of 'getProjectsForWorkspaceFolder' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise<void>; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map<WorkspaceFolderUri, DuoProject[]>; #eventEmitter = new EventEmitter(); 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 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp
Definition: setup(build) { build.onLoad({ filter: treeSitterLanguagesRegex }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( "path.join(__dirname, '../../../vendor/grammars", "path.join(__dirname, '../vendor/grammars", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; const fixWebviewPathPlugin = { name: 'fixWebviewPath', setup(build) { console.log('[fixWebviewPath] plugin initialized'); build.onLoad({ filter: /.*[/\\]webview[/\\]constants\.ts/ }, ({ path: filePath }) => { console.log('[fixWebviewPath] File load attempt:', filePath); if (!filePath.match(/.*[/\\]?node_modules[/\\].*?/)) { console.log('[fixWebviewPath] Modifying file:', filePath); let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( "WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/');", "WEBVIEW_BASE_PATH = path.join(__dirname, '../webviews/');", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } else { console.log('[fixWebviewPath] Skipping file:', filePath); } return null; }); }, } satisfies Plugin; const setLanguageServerVersionPlugin = { name: 'setLanguageServerVersion', setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197
You are a code assistant
Definition of 'generateUniqueTrackingId' in file src/common/tracking/utils.ts in project gitlab-lsp
Definition: export const generateUniqueTrackingId = (): string => { return uuidv4(); }; References: - src/common/suggestion/suggestion_service.ts:328 - src/common/tracking/instance_tracker.test.ts:38 - src/common/tracking/snowplow_tracker.test.ts:83 - src/common/suggestion/suggestion_service.ts:298 - src/common/tracking/snowplow_tracker.test.ts:722 - src/common/tracking/instance_tracker.test.ts:286 - src/common/suggestion/suggestions_cache.ts:169 - src/common/tracking/snowplow_tracker.test.ts:746 - src/common/tracking/instance_tracker.test.ts:277 - src/common/suggestion/streaming_handler.test.ts:25
You are a code assistant
Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'createMockFastifyReply' in file src/node/webview/test-utils/mock_fastify_reply.ts in project gitlab-lsp
Definition: export const createMockFastifyReply = (): MockFastifyReply & FastifyReply => { const reply: Partial<MockFastifyReply> = {}; reply.send = jest.fn().mockReturnThis(); reply.status = jest.fn().mockReturnThis(); reply.redirect = jest.fn().mockReturnThis(); reply.sendFile = jest.fn().mockReturnThis(); reply.code = jest.fn().mockReturnThis(); reply.header = jest.fn().mockReturnThis(); reply.type = jest.fn().mockReturnThis(); return reply as MockFastifyReply & FastifyReply; }; References: - src/node/webview/handlers/webview_handler.test.ts:39 - src/node/webview/handlers/webview_handler.test.ts:53 - src/node/webview/handlers/webview_handler.test.ts:20 - src/node/webview/routes/webview_routes.test.ts:65 - src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:12
You are a code assistant
Definition of 'fetchFromApi' in file src/common/api.ts in project gitlab-lsp
Definition: 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: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10
You are a code assistant
Definition of 'getForActiveAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp
Definition: 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 'TestCompletionProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: class TestCompletionProcessor 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} 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:71
You are a code assistant
Definition of 'destroy' in file src/node/fetch.ts in project gitlab-lsp
Definition: async destroy(): Promise<void> { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { if (!this.#initialized) { throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.'); } try { return await this.#fetchLogged(input, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS), ...init, agent: this.#getAgent(input), }); } catch (e) { if (hasName(e) && e.name === 'AbortError') { throw new TimeoutError(input); } throw e; } } updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void { let fileOptions = {}; try { fileOptions = { ...(ca ? { ca: fs.readFileSync(ca) } : {}), ...(cert ? { cert: fs.readFileSync(cert) } : {}), ...(certKey ? { key: fs.readFileSync(certKey) } : {}), }; } catch (err) { log.error('Error reading https agent options from file', err); } const newOptions: LsAgentOptions = { rejectUnauthorized: !ignoreCertificateErrors, ...fileOptions, }; if (isEqual(newOptions, this.#agentOptions)) { // new and old options are the same, nothing to do return; } this.#agentOptions = newOptions; this.#httpsAgent = this.#createHttpsAgent(); if (this.#proxy) { this.#proxy = this.#createProxyAgent(); } } async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator<string, void, void> { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream<Uint8Array>, ): AsyncGenerator<string, void, void> { for await (const chunk of stream) { buffer += decoder.decode(chunk); yield buffer; } } const response: Response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Code Suggestions Streaming'); if (response.body) { // Note: Using (node:stream).ReadableStream as it supports async iterators yield* readStream(response.body as ReadableStream); } } #createHttpsAgent(): https.Agent { const agentOptions = { ...this.#agentOptions, keepAlive: true, }; log.debug( `fetch: https agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(agentOptions), )}.`, ); return new https.Agent(agentOptions); } #createProxyAgent(): ProxyAgent { log.debug( `fetch: proxy agent with options initialized ${JSON.stringify( this.#sanitizeAgentOptions(this.#agentOptions), )}.`, ); return new ProxyAgent(this.#agentOptions); } async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> { const start = Date.now(); const url = this.#extractURL(input); if (init.agent === httpAgent) { log.debug(`fetch: request for ${url} made with http agent.`); } else { const type = init.agent === this.#proxy ? 'proxy' : 'https'; log.debug(`fetch: request for ${url} made with ${type} agent.`); } try { const resp = await fetch(input, init); const duration = Date.now() - start; log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`); return resp; } catch (e) { const duration = Date.now() - start; log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`); log.error(`fetch: request to ${url} failed with:`, e); throw e; } } #getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent { if (this.#proxy) { return this.#proxy; } if (input.toString().startsWith('https://')) { return this.#httpsAgent; } return httpAgent; } #extractURL(input: RequestInfo | URL): string { if (input instanceof URL) { return input.toString(); } if (typeof input === 'string') { return input; } return input.url; } #sanitizeAgentOptions(agentOptions: LsAgentOptions) { const { ca, cert, key, ...options } = agentOptions; return { ...options, ...(ca ? { ca: '<hidden>' } : {}), ...(cert ? { cert: '<hidden>' } : {}), ...(key ? { key: '<hidden>' } : {}), }; } } References:
You are a code assistant
Definition of 'constructor' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp
Definition: constructor(accessInfoProviders: WebviewLocationService, plugins: Set<WebviewPlugin>) { this.#accessInfoProviders = accessInfoProviders; this.#plugins = plugins; } getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References:
You are a code assistant
Definition of 'findFilesForDirectory' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: findFilesForDirectory(_args: DirectoryToSearch): Promise<URI[]>; setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId<DirectoryWalker>('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise<URI[]> { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:
You are a code assistant
Definition of 'CHECKS_PER_FEATURE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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 'isClientFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: isClientFlagEnabled(name: ClientFeatureFlags): boolean { const value = this.#configService.get('client.featureFlags')?.[name]; return value ?? false; } } References:
You are a code assistant
Definition of 'GetRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: 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 'constructor' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp
Definition: constructor(api: GitLabApiClient, configService: ConfigService) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; } #reconfigure(config: IConfig) { const { baseUrl } = config.client; const enabled = config.client.telemetry?.enabled; const actions = config.client.telemetry?.actions; if (typeof enabled !== 'undefined') { this.#options.enabled = enabled; if (enabled === false) { log.warn(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; } if (actions) { this.#options.actions = actions; } } isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // Only auto-reject if client is set up to track accepted and not rejected events. if ( canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) && !canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED) ) { this.rejectOpenedSuggestions(); } setTimeout(() => { if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) { this.#codeSuggestionsContextMap.delete(uniqueTrackingId); this.#codeSuggestionStates.delete(uniqueTrackingId); } }, GC_TIME); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`, ); // Allow state to update to ACCEPTED despite 'allowed transitions' constraint. if (newState !== TRACKING_EVENTS.ACCEPTED) { return; } log.debug( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:
You are a code assistant
Definition of 'runBuild' in file scripts/watcher/watch.ts in project gitlab-lsp
Definition: async function runBuild() { try { await runScript('npm run build'); } catch (e) { console.error(errorColor, 'Script execution failed'); console.error(e); return false; } console.log(successColor, 'Compiled successfully'); return true; } /** * Publish to yalc so the vscode extension can consume the language * server changes. */ async function postBuildVscCodeYalcPublish(vsCodePath: string) { const commandCwd = resolvePath(cwd(), vsCodePath); await runScript('npx [email protected] publish'); console.log(successColor, 'Pushed to yalc'); await runScript('npx [email protected] add @gitlab-org/gitlab-lsp', commandCwd); } /** * additionally copy to desktop assets so the developer * does not need to restart the extension host */ async function postBuildVSCodeCopyFiles(vsCodePath: string) { const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`; try { await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir); console.log(successColor, 'Copied files to vscode extension'); } catch (error) { console.error(errorColor, 'Whoops, something went wrong...'); console.error(error); } } 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:65
You are a code assistant
Definition of 'dispose' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp
Definition: dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References:
You are a code assistant
Definition of 'streamFetch' in file src/common/fetch.ts in project gitlab-lsp
Definition: 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 'Messages' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp
Definition: export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array<string> | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:
You are a code assistant
Definition of 'constructor' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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 'register' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp
Definition: register(key: TKey, handler: THandler): Disposable { const hash = this.#hashFunc(key); return this.#basicRegistry.register(hash, handler); } has(key: TKey): boolean { const hash = this.#hashFunc(key); return this.#basicRegistry.has(hash); } async handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:
You are a code assistant
Definition of 'getFile' in file src/common/git/repository.ts in project gitlab-lsp
Definition: 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 'DetailedError' in file src/common/fetch_error.ts in project gitlab-lsp
Definition: export interface DetailedError extends Error { readonly details: Record<string, unknown>; } export function isDetailedError(object: unknown): object is DetailedError { return Boolean((object as DetailedError).details); } export function isFetchError(object: unknown): object is FetchError { return object instanceof FetchError; } export const stackToArray = (stack: string | undefined): string[] => (stack ?? '').split('\n'); export interface ResponseError extends Error { status: number; body?: unknown; } const getErrorType = (body: string): string | unknown => { try { const parsedBody = JSON.parse(body); return parsedBody?.error; } catch { return undefined; } }; const isInvalidTokenError = (response: Response, body?: string) => Boolean(response.status === 401 && body && getErrorType(body) === 'invalid_token'); const isInvalidRefresh = (response: Response, body?: string) => Boolean(response.status === 400 && body && getErrorType(body) === 'invalid_grant'); export class FetchError extends Error implements ResponseError, DetailedError { response: Response; #body?: string; 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 'initializeHttpServer' in file src/node/setup_http.ts in project gitlab-lsp
Definition: async function initializeHttpServer(webviewIds: WebviewId[], logger: Logger) { const { shutdown: fastifyShutdown, server } = await createFastifyHttpServer({ plugins: [ createFastifySocketIoPlugin(), createWebviewPlugin({ webviewIds, }), { plugin: async (app) => { app.get('/', () => { return { message: 'Hello, world!' }; }); }, }, ], logger, }); const handleGracefulShutdown = async (signal: string) => { logger.info(`Received ${signal}. Shutting down...`); server.io.close(); await fastifyShutdown(); logger.info('Shutdown complete. Exiting process.'); process.exit(0); }; process.on('SIGTERM', handleGracefulShutdown); process.on('SIGINT', handleGracefulShutdown); return server; } References: - src/node/setup_http.ts:15
You are a code assistant
Definition of 'withKnownWebview' in file src/node/webview/handlers/webview_handler.ts in project gitlab-lsp
Definition: export const withKnownWebview = ( webviewIds: WebviewId[], handler: RouteHandlerMethod, ): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { const { webviewId } = request.params as { webviewId: WebviewId }; if (!webviewIds.includes(webviewId)) { return reply.status(404).send(`Unknown webview: ${webviewId}`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/handlers/webview_handler.ts:10
You are a code assistant
Definition of 'ExtensionMessageHandlerRegistry' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp
Definition: export class ExtensionMessageHandlerRegistry extends HashedRegistry<ExtensionMessageHandlerKey> { constructor() { super((key) => `${key.webviewId}:${key.type}`); } } References: - src/common/webview/extension/types.ts:9 - src/common/webview/extension/extension_connection_message_bus_provider.ts:56 - src/common/webview/extension/extension_connection_message_bus_provider.ts:55 - src/common/webview/extension/extension_connection_message_bus.test.ts:25 - src/common/webview/extension/extension_connection_message_bus_provider.ts:36 - src/common/webview/extension/types.ts:10 - src/common/webview/extension/extension_connection_message_bus.test.ts:24 - src/common/webview/extension/extension_connection_message_bus.test.ts:16 - src/common/webview/extension/handlers/handle_notification_message.ts:6 - src/common/webview/extension/extension_connection_message_bus.test.ts:15 - src/common/webview/extension/handlers/handle_request_message.ts:6 - src/common/webview/extension/extension_connection_message_bus_provider.ts:34
You are a code assistant
Definition of 'SocketEvents' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp
Definition: 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: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:178
You are a code assistant
Definition of 'getSuggestions' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp
Definition: getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType<SuggestionClientFn>; References:
You are a code assistant
Definition of 'isOpen' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: 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 'Messages' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: export type Messages = { 'webview:connect': WebviewAddress; 'webview:disconnect': WebviewAddress; 'webview:notification': NotificationMessage; 'webview:request': RequestMessage; 'webview:response': ResponseMessage; 'plugin:notification': NotificationMessage; 'plugin:request': RequestMessage; 'plugin:response': ResponseMessage; }; export class WebviewRuntimeMessageBus extends MessageBus<Messages> {} References:
You are a code assistant
Definition of 'TelemetryRequest' in file src/common/api_types.ts in project gitlab-lsp
Definition: export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:
You are a code assistant
Definition of 'StreamWithId' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp
Definition: export interface StreamWithId { /** unique stream ID */ id: string; } export interface StreamingCompletionResponse { /** stream ID taken from the request, all stream responses for one request will have the request's stream ID */ id: string; /** most up-to-date generated suggestion, each time LS receives a chunk from LLM, it adds it to this string -> the client doesn't have to join the stream */ completion?: string; done: boolean; } export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse'; export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming'; export const StreamingCompletionResponse = new NotificationType<StreamingCompletionResponse>( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType<StreamWithId>( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion/streaming_handler.test.ts:343 - src/common/suggestion/streaming_handler.test.ts:395 - src/common/suggestion/streaming_handler.test.ts:212
You are a code assistant
Definition of 'B' in file packages/lib_di/src/index.test.ts in project gitlab-lsp
Definition: 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:40 - packages/lib_di/src/index.test.ts:42
You are a code assistant
Definition of 'createIsManagedFunc' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp
Definition: export const createIsManagedFunc = (managedInstances: ManagedInstances): IsManagedEventFilter => <TEvent extends { webviewInstanceId: WebviewInstanceId }>(event: TEvent) => managedInstances.has(event.webviewInstanceId); References: - packages/lib_webview/src/setup/transport/setup_transport.ts:15
You are a code assistant
Definition of 'ChatPlatformManager' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp
Definition: export class ChatPlatformManager implements GitLabPlatformManager { #client: GitLabApiClient; constructor(client: GitLabApiClient) { this.#client = client; } async getForActiveProject(): Promise<GitLabPlatformForProject | undefined> { // return new ChatPlatformForProject(this.#client); return undefined; } 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: - packages/webview_duo_chat/src/plugin/index.ts:18
You are a code assistant
Definition of 'FEATURE_STATE_CHANGE' in file src/common/notifications.ts in project gitlab-lsp
Definition: export const FEATURE_STATE_CHANGE = '$/gitlab/featureStateChange'; 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 'DuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp
Definition: export const DuoProjectPolicy = createInterfaceId<DuoProjectPolicy>('AiFileContextProvider'); @Injectable(DuoProjectPolicy, [DuoProjectAccessChecker]) export class DefaultDuoProjectPolicy implements AiContextPolicy { constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string }> { const { providerType } = aiProviderItem; switch (providerType) { case 'file': { const { repositoryFile } = aiProviderItem; if (!repositoryFile) { return Promise.resolve({ allowed: true }); } const duoProjectStatus = this.duoProjectAccessChecker.checkProjectStatus( repositoryFile.uri.toString(), repositoryFile.workspaceFolder, ); const enabled = duoProjectStatus === DuoProjectStatus.DuoEnabled || duoProjectStatus === DuoProjectStatus.NonGitlabProject; if (!enabled) { return Promise.resolve({ allowed: false, reason: 'Duo is not enabled for this project' }); } return Promise.resolve({ allowed: true }); } default: { throw new Error(`Unknown provider type ${providerType}`); } } } } References: - src/common/ai_context_management_2/ai_policy_management.ts:24
You are a code assistant
Definition of 'greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp
Definition: 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:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1 - src/tests/fixtures/intent/ruby_comments.rb:21
You are a code assistant
Definition of 'SetupWebviewRoutesOptions' in file src/node/webview/routes/webview_routes.ts in project gitlab-lsp
Definition: type SetupWebviewRoutesOptions = { webviewIds: WebviewId[]; getWebviewResourcePath: (webviewId: WebviewId) => string; }; export const setupWebviewRoutes = async ( fastify: FastifyInstance, { webviewIds, getWebviewResourcePath }: SetupWebviewRoutesOptions, ): Promise<void> => { await fastify.register( async (instance) => { instance.get('/', buildWebviewCollectionMetadataRequestHandler(webviewIds)); instance.get('/:webviewId', buildWebviewRequestHandler(webviewIds, getWebviewResourcePath)); // registering static resources across multiple webviews should not be done in parallel since we need to ensure that the fastify instance has been modified by the static files plugin for (const webviewId of webviewIds) { // eslint-disable-next-line no-await-in-loop await registerStaticPluginSafely(instance, { root: getWebviewResourcePath(webviewId), prefix: `/${webviewId}/`, }); } }, { prefix: '/webview' }, ); }; References: - src/node/webview/routes/webview_routes.ts:16
You are a code assistant
Definition of 'InterfaceId' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: export type InterfaceId<T> = string & { __type: T }; const getRandomString = () => Math.random().toString(36).substring(2, 15); /** * Creates a runtime identifier of an interface used for dependency injection. * * Every call to this function produces unique identifier, you can't call this method twice for the same Type! */ 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:
You are a code assistant
Definition of 'StartStreamOption' in file src/common/api.ts in project gitlab-lsp
Definition: 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: - src/common/utils/suggestion_mapper.test.ts:95
You are a code assistant
Definition of 'DefaultAiFileContextProvider' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp
Definition: export class DefaultAiFileContextProvider implements AiContextProvider { #repositoryService: DefaultRepositoryService; constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise<AiContextProviderItem[]> { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise<AiContextProviderItem[]> { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise<AiContextProviderItem[]> { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References:
You are a code assistant
Definition of 'CodeSuggestionRequestCurrentFile' in file src/common/api.ts in project gitlab-lsp
Definition: 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: - src/common/api.ts:45
You are a code assistant
Definition of 'SPECIAL_MESSAGES' in file packages/webview_duo_chat/src/app/constants.ts in project gitlab-lsp
Definition: export const SPECIAL_MESSAGES = { CLEAN: '/clean', CLEAR: '/clear', RESET: '/reset', }; References:
You are a code assistant
Definition of 'AiContextQuery' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp
Definition: export type AiContextQuery = { query: string; providerType: 'file'; textDocument?: TextDocument; workspaceFolders: WorkspaceFolder[]; }; @Injectable(AiContextPolicyManager, [DuoProjectPolicy]) 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: - src/common/ai_context_management_2/ai_context_aggregator.ts:36 - src/common/connection_service.ts:105
You are a code assistant
Definition of 'onNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'MessageBus' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp
Definition: 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: - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:4 - src/common/graphql/workflow/service.ts:45 - src/common/graphql/workflow/service.test.ts:17 - packages/webview_duo_workflow/src/plugin/index.ts:9
You are a code assistant
Definition of 'constructor' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise<void> { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise<WorkspaceFolder | undefined> { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:
You are a code assistant
Definition of 'NO_LICENSE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: export const NO_LICENSE = 'code-suggestions-no-license' as const; export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; 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 'NotificationListener' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: export interface NotificationListener<TNotifications extends NotificationMap> { onNotification<T extends KeysWithOptionalValues<TNotifications>>( type: T, handler: () => void, ): Disposable; onNotification<T extends keyof TNotifications & string>( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record<Method, {params: MessagePayload; result: MessagePayload;}>} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams<R extends RequestMap> = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher<TRequests extends RequestMap> { sendRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, ): Promise<ExtractRequestResult<TRequests[T]>>; sendRequest<T extends keyof TRequests>( type: T, payload: TRequests[T]['params'], ): Promise<ExtractRequestResult<TRequests[T]>>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener<TRequests extends RequestMap> { onRequest<T extends KeysWithOptionalParams<TRequests>>( type: T, handler: () => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; onRequest<T extends keyof TRequests>( type: T, handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus<T extends MessageMap = MessageMap> extends NotificationPublisher<T['outbound']['notifications']>, NotificationListener<T['inbound']['notifications']>, RequestPublisher<T['outbound']['requests']>, RequestListener<T['inbound']['requests']> {} References:
You are a code assistant
Definition of 'isWebviewInstanceMessageEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp
Definition: export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:
You are a code assistant
Definition of 'setUris' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp
Definition: setUris(webviewId: WebviewId, uris: string[]) { this.#uriMap.set(webviewId, uris); } resolveUris(webviewId: WebviewId): string[] { return this.#uriMap.get(webviewId) || []; } } describe('WebviewMetadataProvider', () => { let accessInfoProviders: MockWebviewLocationService; let plugins: Set<WebviewPlugin>; let provider: WebviewMetadataProvider; beforeEach(() => { accessInfoProviders = new MockWebviewLocationService(); plugins = new Set<WebviewPlugin>(); provider = new WebviewMetadataProvider(accessInfoProviders, plugins); }); describe('getMetadata', () => { it('should return an empty array if no plugins are registered', () => { const metadata = provider.getMetadata(); expect(metadata).toEqual([]); }); it('should return metadata for registered plugins', () => { // write test const plugin1: WebviewPlugin = { id: 'plugin1' as WebviewId, title: 'Plugin 1', setup: () => {}, }; const plugin2: WebviewPlugin = { id: 'plugin2' as WebviewId, title: 'Plugin 2', setup: () => {}, }; plugins.add(plugin1); plugins.add(plugin2); accessInfoProviders.setUris(plugin1.id, ['uri1', 'uri2']); accessInfoProviders.setUris(plugin2.id, ['uri3', 'uri4']); const metadata = provider.getMetadata(); expect(metadata).toEqual([ { id: 'plugin1', title: 'Plugin 1', uris: ['uri1', 'uri2'], }, { id: 'plugin2', title: 'Plugin 2', uris: ['uri3', 'uri4'], }, ]); }); }); }); References:
You are a code assistant
Definition of 'getUri' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp
Definition: getUri(webviewId: WebviewId): string { return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`; } } References:
You are a code assistant
Definition of 'WEBVIEW_ID' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp
Definition: export const WEBVIEW_ID = 'duo-workflow' as WebviewId; export const WEBVIEW_TITLE = 'GitLab Duo Workflow'; 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 'DefaultDidChangeWorkspaceFoldersHandler' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp
Definition: 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:19
You are a code assistant
Definition of 'TreeSitterParser' in file src/common/tree_sitter/parser.ts in project gitlab-lsp
Definition: 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/connection.ts:29 - src/common/tree_sitter/parser.test.ts:28 - src/common/suggestion/suggestion_service.ts:133 - src/common/suggestion_client/tree_sitter_middleware.ts:10 - src/common/suggestion/streaming_handler.test.ts:32 - src/common/suggestion/streaming_handler.ts:40 - src/common/suggestion/suggestion_service.ts:82 - src/common/suggestion_client/tree_sitter_middleware.test.ts:20
You are a code assistant
Definition of 'publish' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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 'GitLabEnvironment' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp
Definition: export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise<string | undefined> { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise<GitLabEnvironment> { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References: - packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts:42
You are a code assistant
Definition of 'MAX_ERRORS_BEFORE_CIRCUIT_BREAK' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp
Definition: export const MAX_ERRORS_BEFORE_CIRCUIT_BREAK = 4; export const API_ERROR_NOTIFICATION = '$/gitlab/api/error'; export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered'; export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:
You are a code assistant
Definition of 'getMessageBusFromProviderSafe' in file packages/lib_webview_client/src/bus/resolve_message_bus.ts in project gitlab-lsp
Definition: function getMessageBusFromProviderSafe<TMessages extends MessageMap>( webviewId: string, provider: MessageBusProvider, logger: Logger, ): MessageBus<TMessages> | null { try { logger.debug(`Trying to resolve message bus from provider: ${provider.name}`); const bus = provider.getMessageBus<TMessages>(webviewId); logger.debug(`Message bus resolved from provider: ${provider.name}`); return bus; } catch (error) { logger.debug('Failed to resolve message bus', error as Error); return null; } } References: - packages/lib_webview_client/src/bus/resolve_message_bus.ts:19