instruction
stringclasses
1 value
input
stringlengths
67
168
output
stringlengths
46
67k
You are a code assistant
Definition of 'onRequest' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp
Definition: onRequest<T extends keyof TMessageMap['inbound']['requests'] & string>( type: T, handler: ( payload: TMessageMap['inbound']['requests'][T]['params'], ) => Promise<ExtractRequestResult<TMessageMap['inbound']['requests'][T]>>, ): Disposable { return this.#handlers.request.register({ webviewId: this.#webviewId, type }, handler); } onNotification<T extends keyof TMessageMap['inbound']['notifications'] & string>( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest<T extends keyof TMessageMap['outbound']['requests'] & string>( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise<ExtractRequestResult<TMessageMap['outbound']['requests'][T]>> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification<T extends keyof TMessageMap['outbound']['notifications'] & string>( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise<void> { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References:
You are a code assistant
Definition of 'RequestId' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp
Definition: type RequestId = string; type NotificationHandler = (payload: unknown) => void; type RequestHandler = (requestId: RequestId, payload: unknown) => void; type ResponseHandler = (message: ResponseMessage) => void; export class WebviewInstanceMessageBus<T extends MessageMap = MessageMap> implements WebviewMessageBus<T>, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry<NotificationHandler>(); #requestEvents = new SimpleRegistry<RequestHandler>(); #pendingResponseEvents = new SimpleRegistry<ResponseHandler>(); #logger: Logger; constructor( webviewAddress: WebviewAddress, runtimeMessageBus: WebviewRuntimeMessageBus, logger: Logger, ) { this.#address = webviewAddress; this.#runtimeMessageBus = runtimeMessageBus; this.#logger = withPrefix( logger, `[WebviewInstanceMessageBus:${webviewAddress.webviewId}:${webviewAddress.webviewInstanceId}]`, ); this.#logger.debug('initializing'); const eventFilter = buildWebviewAddressFilter(webviewAddress); this.#eventSubscriptions.add( this.#runtimeMessageBus.subscribe( 'webview:notification', async (message) => { try { await this.#notificationEvents.handle(message.type, message.payload); } catch (error) { this.#logger.debug( `Failed to handle webview instance notification: ${message.type}`, error instanceof Error ? error : undefined, ); } }, eventFilter, ), this.#runtimeMessageBus.subscribe( 'webview:request', async (message) => { try { await this.#requestEvents.handle(message.type, message.requestId, message.payload); } catch (error) { this.#logger.error(error as Error); } }, eventFilter, ), this.#runtimeMessageBus.subscribe( 'webview:response', async (message) => { try { await this.#pendingResponseEvents.handle(message.requestId, message); } catch (error) { this.#logger.error(error as Error); } }, eventFilter, ), ); this.#logger.debug('initialized'); } sendNotification(type: Method, payload?: unknown): void { this.#logger.debug(`Sending notification: ${type}`); this.#runtimeMessageBus.publish('plugin:notification', { ...this.#address, type, payload, }); } onNotification(type: Method, handler: Handler): Disposable { return this.#notificationEvents.register(type, handler); } async sendRequest(type: Method, payload?: unknown): Promise<never> { const requestId = generateRequestId(); this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestHandle = this.#pendingResponseEvents.register( requestId, (message: ResponseMessage) => { if (message.success) { resolve(message.payload as PromiseLike<never>); } else { reject(new Error(message.reason)); } clearTimeout(timeout); pendingRequestHandle.dispose(); }, ); this.#runtimeMessageBus.publish('plugin:request', { ...this.#address, requestId, type, payload, }); timeout = setTimeout(() => { pendingRequestHandle.dispose(); this.#logger.debug(`Request with ID: ${requestId} timed out`); reject(new Error('Request timed out')); }, 10000); }); } onRequest(type: Method, handler: Handler): Disposable { return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => { try { const result = handler(payload); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: true, payload: result, }); } catch (error) { this.#logger.error(`Error handling request of type ${type}:`, error as Error); this.#runtimeMessageBus.publish('plugin:response', { ...this.#address, requestId, type, success: false, reason: (error as Error).message, }); } }); } dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:140 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:12
You are a code assistant
Definition of 'ChatMessages' in file packages/webview-chat/src/plugin/index.ts in project gitlab-lsp
Definition: type ChatMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { newUserPrompt: { prompt: string; }; }; }; pluginToWebview: { notifications: { newUserPrompt: { prompt: string; }; }; }; }>; 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 src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp
Definition: constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References:
You are a code assistant
Definition of 'updateAgentOptions' in file src/common/fetch.ts in project gitlab-lsp
Definition: updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp
Definition: class Greet3 end def generate_greetings end def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:34
You are a code assistant
Definition of 'Greet4' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: class Greet4: def __init__(self, name): def greet(self): class Greet3: References:
You are a code assistant
Definition of 'constructor' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp
Definition: constructor( lsFetch: LsFetch, configService: ConfigService, featureFlagService: FeatureFlagService, api: GitLabApiClient, ) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; const trackingUrl = DEFAULT_TRACKING_ENDPOINT; this.#lsFetch = lsFetch; this.#configService = configService; this.#featureFlagService = featureFlagService; this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); this.#options.trackingUrl = trackingUrl; this.#ajv.addMetaSchema(SnowplowMetaSchema); } isEnabled(): boolean { return Boolean(this.#options.enabled); } async #reconfigure(config: IConfig) { const { baseUrl } = config.client; const trackingUrl = config.client.telemetry?.trackingUrl; 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(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL) ? GitlabRealm.saas : GitlabRealm.selfManaged; } if (trackingUrl && this.#options.trackingUrl !== trackingUrl) { await this.#snowplow.stop(); this.#snowplow.destroy(); this.#snowplow = Snowplow.getInstance(this.#lsFetch, { ...DEFAULT_SNOWPLOW_OPTIONS, endpoint: trackingUrl, enabled: this.isEnabled.bind(this), }); } if (actions) { this.#options.actions = actions; } this.#setClientContext({ extension: config.client.telemetry?.extension, ide: config.client.telemetry?.ide, }); } #setClientContext(context: IClientContext) { this.#clientContext.data = { ide_name: context?.ide?.name ?? null, ide_vendor: context?.ide?.vendor ?? null, ide_version: context?.ide?.version ?? null, extension_name: context?.extension?.name ?? null, extension_version: context?.extension?.version ?? null, language_server_version: lsVersion ?? null, }; } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ) { const { documentContext, source = SuggestionSource.network, language, isStreaming, triggerKind, optionsCount, additionalContexts, isDirectConnection, } = context; const { gitlab_instance_id, gitlab_global_user_id, gitlab_host_name, gitlab_saas_duo_pro_namespace_ids, } = this.#configService.get('client.snowplowTrackerOptions') ?? {}; if (source === SuggestionSource.cache) { log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`); } else { log.debug(`Snowplow Telemetry: Received request to create a new suggestion`); } // 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); const advancedContextData = this.#getAdvancedContextData({ additionalContexts, documentContext, }); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0', data: { suffix_length: documentContext?.suffix.length ?? 0, prefix_length: documentContext?.prefix.length ?? 0, gitlab_realm: this.#gitlabRealm, model_engine: null, model_name: null, language: language ?? null, api_status_code: null, debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS, suggestion_source: source, gitlab_global_user_id: gitlab_global_user_id ?? null, gitlab_host_name: gitlab_host_name ?? null, gitlab_instance_id: gitlab_instance_id ?? null, gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null, gitlab_instance_version: this.#api.instanceVersion ?? null, is_streaming: isStreaming ?? false, is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind), options_count: optionsCount ?? null, has_advanced_context: advancedContextData.hasAdvancedContext, is_direct_connection: isDirectConnection ?? null, total_context_size_bytes: advancedContextData.totalContextSizeBytes, content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes, content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes, context_items: advancedContextData.contextItems, }, }); this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`); } // FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute // the solution might be some generic update method used by both public updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ) { const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate; if (context) { if (model) { context.data.language = model.lang ?? null; context.data.model_engine = model.engine ?? null; context.data.model_name = model.name ?? null; context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null; context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null; context.data.context_tokens_sent = model.tokens_consumption_metadata?.context_tokens_sent ?? null; context.data.context_tokens_used = model.tokens_consumption_metadata?.context_tokens_used ?? null; } if (status) { context.data.api_status_code = status; } if (optionsCount) { context.data.options_count = optionsCount; } if (isDirectConnection !== undefined) { context.data.is_direct_connection = isDirectConnection; } if (acceptedOption) { context.data.accepted_option = acceptedOption; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { if (!this.isEnabled()) { return; } const event: StructuredEvent = { category: CODE_SUGGESTIONS_CATEGORY, action: eventType, label: uniqueTrackingId, }; try { const contexts: SelfDescribingJson[] = [this.#clientContext]; const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId); if (codeSuggestionContext) { contexts.push(codeSuggestionContext); } const suggestionContextValid = this.#ajv.validate( CodeSuggestionContextSchema, codeSuggestionContext?.data, ); if (!suggestionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } const ideExtensionContextValid = this.#ajv.validate( IdeExtensionContextSchema, this.#clientContext?.data, ); if (!ideExtensionContextValid) { log.warn(EVENT_VALIDATION_ERROR_MSG); log.debug(JSON.stringify(this.#ajv.errors, null, 2)); return; } await this.#snowplow.trackStructEvent(event, contexts); } catch (error) { log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error); } } public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const isStreaming = Boolean( this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming, ); const allowedTransitions = isStreaming ? streamingSuggestionStateGraph.get(state) : nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `Snowplow 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( `Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Snowplow Telemetry: Could not track telemetry', e), ); log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } rejectOpenedSuggestions() { log.debug(`Snowplow Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } #hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null { const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextFeatureFlagsEnabled) { return Boolean(advancedContexts?.length); } return null; } #getAdvancedContextData({ additionalContexts, documentContext, }: { additionalContexts?: AdditionalContext[]; documentContext?: IDocContext; }) { const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts); const contentAboveCursorSizeBytes = documentContext?.prefix ? getByteSize(documentContext.prefix) : 0; const contentBelowCursorSizeBytes = documentContext?.suffix ? getByteSize(documentContext.suffix) : 0; const contextItems: ContextItem[] | null = additionalContexts?.map((item) => ({ file_extension: item.name.split('.').pop() || '', type: item.type, resolution_strategy: item.resolution_strategy, byte_size: item?.content ? getByteSize(item.content) : 0, })) ?? null; const totalContextSizeBytes = contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0; return { totalContextSizeBytes, contentAboveCursorSizeBytes, contentBelowCursorSizeBytes, contextItems, hasAdvancedContext, }; } static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null { let isInvoked = null; if (triggerKind === InlineCompletionTriggerKind.Invoked) { isInvoked = true; } else if (triggerKind === InlineCompletionTriggerKind.Automatic) { isInvoked = false; } return isInvoked; } } References:
You are a code assistant
Definition of 'getCommentResolver' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References: - src/common/tree_sitter/intent_resolver.ts:36 - src/common/tree_sitter/comments/comment_resolver.test.ts:335 - src/common/tree_sitter/comments/comment_resolver.test.ts:336
You are a code assistant
Definition of 'RequestMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp
Definition: export type RequestMessage = NotificationMessage & { requestId: string; }; export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; export type FailedResponse = WebviewAddress & { requestId: string; success: false; reason: string; type: string; }; export type ResponseMessage = SuccessfulResponse | FailedResponse; 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: - packages/lib_webview/src/events/webview_runtime_message_bus.ts:36 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:33
You are a code assistant
Definition of 'AiContextItemSubType' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp
Definition: export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:20
You are a code assistant
Definition of 'updateAgentOptions' in file src/common/fetch.ts in project gitlab-lsp
Definition: updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>; } export const LsFetch = createInterfaceId<LsFetch>('LsFetch'); export class FetchBase implements LsFetch { updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References:
You are a code assistant
Definition of 'Record' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp
Definition: type Record = { id: string; }; export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } 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: - packages/webview_duo_chat/src/contract.ts:24 - packages/webview_duo_chat/src/contract.ts:23
You are a code assistant
Definition of 'SocketIOWebViewTransport' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp
Definition: export class SocketIOWebViewTransport implements Transport { #server: Server; #logger?: Logger; #messageEmitter = createWebviewTransportEventEmitter(); #connections: Map<WebviewSocketConnectionId, Socket> = new Map(); constructor(server: Server, logger?: Logger) { this.#server = server; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#initialize(); } #initialize(): void { this.#logger?.debug('Initializing webview transport'); const namespace = this.#server.of(NAMESPACE_REGEX_PATTERN); namespace.on('connection', (socket) => { const match = socket.nsp.name.match(NAMESPACE_REGEX_PATTERN); if (!match) { this.#logger?.error('Failed to parse namespace for socket connection'); return; } const webviewId = match[1] as WebviewId; const webviewInstanceId = randomUUID() as WebviewInstanceId; const webviewInstanceInfo: WebviewInstanceInfo = { webviewId, webviewInstanceId, }; const connectionId = buildConnectionId(webviewInstanceInfo); this.#connections.set(connectionId, socket); this.#messageEmitter.emit('webview_instance_created', webviewInstanceInfo); socket.on(SOCKET_NOTIFICATION_CHANNEL, (message: unknown) => { if (!isSocketNotificationMessage(message)) { this.#logger?.debug(`[${connectionId}] received notification with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received notification`); this.#messageEmitter.emit('webview_instance_notification_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, }); }); socket.on(SOCKET_REQUEST_CHANNEL, (message: unknown) => { if (!isSocketRequestMessage(message)) { this.#logger?.debug(`[${connectionId}] received request with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received request`); this.#messageEmitter.emit('webview_instance_request_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, }); }); socket.on(SOCKET_RESPONSE_CHANNEL, (message: unknown) => { if (!isSocketResponseMessage(message)) { this.#logger?.debug(`[${connectionId}] received response with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received response`); this.#messageEmitter.emit('webview_instance_response_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, success: message.success, reason: message.reason ?? '', }); }); socket.on('error', (error) => { this.#logger?.debug(`[${connectionId}] error`, error); }); socket.on('disconnect', (reason) => { this.#logger?.debug(`[${connectionId}] disconnected with reason: ${reason}`); this.#connections.delete(connectionId); this.#messageEmitter.emit('webview_instance_destroyed', webviewInstanceInfo); }); }); this.#logger?.debug('transport initialized'); } async publish<K extends keyof MessagesToClient>( type: K, message: MessagesToClient[K], ): Promise<void> { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } 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]), }; } dispose() { this.#messageEmitter.removeAllListeners(); for (const connection of this.#connections.values()) { connection.disconnect(); } this.#connections.clear(); } } References: - src/node/setup_http.ts:21
You are a code assistant
Definition of 'AiCompletionResponseChannelEvents' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp
Definition: interface AiCompletionResponseChannelEvents extends ChannelEvents<AiCompletionResponseResponseType> { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:
You are a code assistant
Definition of 'GITLAB_COM_URL' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp
Definition: export const GITLAB_COM_URL = 'https://gitlab.com'; export const CONFIG_NAMESPACE = 'gitlab'; export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_VERSION = '16.1.0'; export const REQUEST_TIMEOUT_MILLISECONDS = 25000; // Webview IDs export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow'; export const DUO_CHAT_WEBVIEW_ID = 'chat'; References:
You are a code assistant
Definition of 'TestStreamProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp
Definition: class TestStreamProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return { ...input, completion: `${input.completion} processed` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise<SuggestionOption[]> { return input; } } pipeline.addProcessor(new TestStreamProcessor()); 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 processed', done: false }); }); test('should process completion input correctly', async () => { 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:42
You are a code assistant
Definition of 'readFile' in file src/node/services/fs/file.ts in project gitlab-lsp
Definition: async readFile({ fileUri }: ReadFile): Promise<string> { return readFile(fsPathFromUri(fileUri), 'utf8'); } } References: - src/node/duo_workflow/desktop_workflow_runner.ts:184 - src/node/duo_workflow/desktop_workflow_runner.ts:137 - src/tests/int/fetch.test.ts:40 - src/tests/unit/tree_sitter/test_utils.ts:38 - src/tests/int/fetch.test.ts:15 - src/node/services/fs/file.ts:9
You are a code assistant
Definition of 'getInstance' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp
Definition: public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise<void> { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to "gl" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with "js-*"" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise<void> { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:
You are a code assistant
Definition of 'setCodeSuggestionsContext' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References:
You are a code assistant
Definition of 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'addItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp
Definition: addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise<AiContextItemWithContent[]> { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:
You are a code assistant
Definition of 'DirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp
Definition: export interface DirectoryWalker { 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: - src/common/services/fs/virtual_file_service.ts:46 - src/common/services/fs/virtual_file_service.ts:42 - src/common/services/duo_access/project_access_cache.ts:92
You are a code assistant
Definition of 'AdvanceContextFilter' in file src/common/advanced_context/advanced_context_filters.ts in project gitlab-lsp
Definition: type AdvanceContextFilter = (args: AdvancedContextFilterArgs) => Promise<ContextResolution[]>; /** * Filters context resolutions that have empty content. */ const emptyContentFilter = async ({ contextResolutions }: AdvancedContextFilterArgs) => { return contextResolutions.filter(({ content }) => content.replace(/\s/g, '') !== ''); }; /** * Filters context resolutions that * contain a Duo project that have Duo features enabled. * See `DuoProjectAccessChecker` for more details. */ const duoProjectAccessFilter: AdvanceContextFilter = async ({ contextResolutions, dependencies: { duoProjectAccessChecker }, documentContext, }: AdvancedContextFilterArgs) => { if (!documentContext?.workspaceFolder) { return contextResolutions; } return contextResolutions.reduce((acc, resolution) => { const { uri: resolutionUri } = resolution; const projectStatus = duoProjectAccessChecker.checkProjectStatus( resolutionUri, documentContext.workspaceFolder as WorkspaceFolder, ); if (projectStatus === DuoProjectStatus.DuoDisabled) { log.warn(`Advanced Context Filter: Duo features are not enabled for ${resolutionUri}`); return acc; } return [...acc, resolution]; }, [] as ContextResolution[]); }; /** * Filters context resolutions that meet the byte size limit. * The byte size limit takes into the size of the total * context resolutions content + size of document content. */ const byteSizeLimitFilter: AdvanceContextFilter = async ({ contextResolutions, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs) => { const documentSize = getByteSize(`${documentContext.prefix}${documentContext.suffix}`); let currentTotalSize = documentSize; const filteredResolutions: ContextResolution[] = []; for (const resolution of contextResolutions) { currentTotalSize += getByteSize(resolution.content); if (currentTotalSize > byteSizeLimit) { // trim the current resolution content to fit the byte size limit const trimmedContent = Buffer.from(resolution.content) .slice(0, byteSizeLimit - currentTotalSize) .toString(); if (trimmedContent.length) { log.info( `Advanced Context Filter: ${resolution.uri} content trimmed to fit byte size limit: ${trimmedContent.length} bytes.`, ); filteredResolutions.push({ ...resolution, content: trimmedContent }); } log.debug( `Advanced Context Filter: Byte size limit exceeded for ${resolution.uri}. Skipping resolution.`, ); break; } filteredResolutions.push(resolution); } return filteredResolutions; }; /** * Advanced context filters that are applied to context resolutions. * @see filterContextResolutions */ const advancedContextFilters: AdvanceContextFilter[] = [ emptyContentFilter, duoProjectAccessFilter, byteSizeLimitFilter, ]; /** * Filters context resolutions based on business logic. * The filters are order dependent. * @see advancedContextFilters */ export const filterContextResolutions = async ({ contextResolutions, dependencies, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs): Promise<ContextResolution[]> => { return advancedContextFilters.reduce(async (prevPromise, filter) => { const resolutions = await prevPromise; return filter({ contextResolutions: resolutions, dependencies, documentContext, byteSizeLimit, }); }, Promise.resolve(contextResolutions)); }; References: - src/common/advanced_context/advanced_context_filters.ts:32 - src/common/advanced_context/advanced_context_filters.ts:60
You are a code assistant
Definition of 'constructor' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp
Definition: constructor(middlewares: SuggestionClientMiddleware[]) { this.#middlewares = [...middlewares]; this.#pipeline = this.#buildPipeline(); } use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce<SuggestionClientFn>( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> { return this.#pipeline(context); } } References:
You are a code assistant
Definition of 'LONG_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp
Definition: export const LONG_COMPLETION_CONTEXT: IDocContext = { prefix: 'abc 123', suffix: 'def 456', fileRelativePath: 'test.js', position: { line: 0, character: 7, }, uri: 'file:///example.ts', languageId: 'typescript', }; const textDocument: TextDocumentIdentifier = { uri: '/' }; const position: Position = { line: 0, character: 0 }; export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:
You are a code assistant
Definition of 'engaged' in file src/common/feature_state/feature_state_manager.test.ts in project gitlab-lsp
Definition: get engaged() { return languageCheckEngaged; }, id: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', onChanged: mockOn, }); mockOn.mockImplementation((_callback) => { notifyClient = _callback; }); const duoProjectAccessCheck = createFakePartial<ProjectDuoAccessCheck>({ get engaged() { return duoProjectAccessCheckEngaged; }, id: DUO_DISABLED_FOR_PROJECT, details: 'DUO is disabled for this project', onChanged: mockOn, }); // the CodeSuggestionStateManager is a top-level service that orchestrates the feature checks and sends out notifications, it doesn't have public API const stateManager = new DefaultFeatureStateManager( supportedLanguageCheck, duoProjectAccessCheck, ); stateManager.init(mockSendNotification); mockSendNotification.mockReset(); }); describe('on check engage', () => { it('should notify the client', async () => { const mockChecksEngagedState = createFakePartial<FeatureState[]>([ { featureId: CODE_SUGGESTIONS, engagedChecks: [ { checkId: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', }, ], }, { featureId: CHAT, engagedChecks: [], }, ]); notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith( expect.arrayContaining(mockChecksEngagedState), ); }); }); describe('on check disengage', () => { const mockNoCheckEngagedState = createFakePartial<FeatureState[]>([ { featureId: CODE_SUGGESTIONS, engagedChecks: [], }, { featureId: CHAT, engagedChecks: [], }, ]); it('should notify the client', () => { languageCheckEngaged = false; notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith(mockNoCheckEngagedState); }); }); }); References:
You are a code assistant
Definition of 'MockWebviewLocationService' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp
Definition: class MockWebviewLocationService extends WebviewLocationService { #uriMap = new Map<WebviewId, string[]>(); 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: - src/common/webview/webview_metadata_provider.test.ts:23 - src/common/webview/webview_metadata_provider.test.ts:18
You are a code assistant
Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp
Definition: class Greet { constructor(name) {} greet() {} } class Greet2 { name: string; 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/go.go:13 - src/tests/fixtures/intent/empty_function/go.go:23 - src/tests/fixtures/intent/empty_function/ruby.rb:16 - src/tests/fixtures/intent/empty_function/go.go:15 - src/tests/fixtures/intent/empty_function/go.go:20 - src/tests/fixtures/intent/go_comments.go:24
You are a code assistant
Definition of 'DiagnosticsPublisherFn' in file src/common/diagnostics_publisher.ts in project gitlab-lsp
Definition: export type DiagnosticsPublisherFn = (data: PublishDiagnosticsParams) => Promise<void>; export interface DiagnosticsPublisher { init(publish: DiagnosticsPublisherFn): void; } References: - src/common/security_diagnostics_publisher.ts:62 - src/common/diagnostics_publisher.ts:6
You are a code assistant
Definition of 'constructor' in file src/browser/tree_sitter/index.ts in project gitlab-lsp
Definition: constructor(configService: ConfigService) { super({ languages: [] }); this.#configService = configService; } getLanguages() { return this.languages; } getLoadState() { return this.loadState; } async init(): Promise<void> { const baseAssetsUrl = this.#configService.get('client.baseAssetsUrl'); this.languages = this.buildTreeSitterInfoByExtMap([ { name: 'bash', extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-c', }, { name: 'c', extensions: ['.c'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-c', }, { name: 'cpp', extensions: ['.cpp'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-cpp.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-cpp', }, { name: 'c_sharp', extensions: ['.cs'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-c_sharp.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-c-sharp', }, { name: 'css', extensions: ['.css'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-css.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-css', }, { name: 'go', extensions: ['.go'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-go.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-go', }, { name: 'html', extensions: ['.html'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-html.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-html', }, { name: 'java', extensions: ['.java'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-java.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-java', }, { name: 'javascript', extensions: ['.js'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-javascript.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-javascript', }, { name: 'powershell', extensions: ['.ps1'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-powershell.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-powershell', }, { name: 'python', extensions: ['.py'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-python.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-python', }, { name: 'ruby', extensions: ['.rb'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-ruby.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-ruby', }, // TODO: Parse throws an error - investigate separately // { // name: 'sql', // extensions: ['.sql'], // wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-sql.wasm', baseAssetsUrl), // nodeModulesPath: 'tree-sitter-sql', // }, { name: 'scala', extensions: ['.scala'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-scala.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-scala', }, { name: 'typescript', extensions: ['.ts'], wasmPath: resolveGrammarAbsoluteUrl( 'vendor/grammars/tree-sitter-typescript.wasm', baseAssetsUrl, ), nodeModulesPath: 'tree-sitter-typescript/typescript', }, // TODO: Parse throws an error - investigate separately // { // name: 'hcl', // terraform, terragrunt // extensions: ['.tf', '.hcl'], // wasmPath: resolveGrammarAbsoluteUrl( // 'vendor/grammars/tree-sitter-hcl.wasm', // baseAssetsUrl, // ), // nodeModulesPath: 'tree-sitter-hcl', // }, { name: 'json', extensions: ['.json'], wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-json.wasm', baseAssetsUrl), nodeModulesPath: 'tree-sitter-json', }, ]); try { await Parser.init({ locateFile(scriptName: string) { return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl); }, }); log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:
You are a code assistant
Definition of 'isExtensionMessage' in file src/common/webview/extension/utils/extension_message.ts in project gitlab-lsp
Definition: export const isExtensionMessage = (message: unknown): message is ExtensionMessage => { return ( typeof message === 'object' && message !== null && 'webviewId' in message && 'type' in message ); }; References: - src/common/webview/extension/handlers/handle_request_message.ts:8 - src/common/webview/extension/handlers/handle_notification_message.ts:8
You are a code assistant
Definition of 'constructor' in file src/tests/int/lsp_client.ts in project gitlab-lsp
Definition: constructor(gitlabToken: string) { this.#gitlabToken = gitlabToken; const command = process.env.LSP_COMMAND ?? 'node'; const args = process.env.LSP_ARGS?.split(' ') ?? ['./out/node/main-bundle.js', '--stdio']; console.log(`Running LSP using command \`${command} ${args.join(' ')}\` `); const file = command === 'node' ? args[0] : command; expect(file).not.toBe(undefined); expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: true }); this.#childProcess = spawn(command, args); this.#childProcess.stderr.on('data', (chunk: Buffer | string) => { const chunkString = chunk.toString('utf8'); this.childProcessConsole = this.childProcessConsole.concat(chunkString.split('\n')); process.stderr.write(chunk); }); // Use stdin and stdout for communication: this.#connection = createMessageConnection( new StreamMessageReader(this.#childProcess.stdout), new StreamMessageWriter(this.#childProcess.stdin), ); this.#connection.listen(); this.#connection.onError(function (err) { console.error(err); expect(err).not.toBeTruthy(); }); } /** * Make sure to call this method to shutdown the LS rpc connection */ public dispose() { this.#connection.end(); } /** * Send the LSP 'initialize' message. * * @param initializeParams Provide custom values that override defaults. Merged with defaults. * @returns InitializeResponse object */ public async sendInitialize( initializeParams?: CustomInitializeParams, ): Promise<InitializeResult> { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType<InitializeParams, InitializeResult, InitializeError>( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise<void> { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType<InitializedParams>('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise<void> { const defaults = createFakePartial<ChangeConfigOptions>({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType<DidChangeConfigurationParams>( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise<void> { const params = { textDocument: { uri, }, }; const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose'); await this.#connection.sendNotification(request, params); } /** * Send LSP 'textDocument/didChange' using Full sync method notification * * @param uri File URL. Should include the workspace path in the url * @param version Change version (incrementing from 0) * @param text Full contents of the file */ public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise<void> { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise<CompletionItem[] | CompletionList | null> { const params: CompletionParams = { textDocument: { uri, }, position: { line, character, }, context: { triggerKind: 1, // invoked }, }; const request = new RequestType1< CompletionParams, CompletionItem[] | CompletionList | null, void >('textDocument/completion'); const result = await this.#connection.sendRequest(request, params); return result; } public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise<WebviewMetadata[]> { const result = await this.#connection.sendRequest<WebviewMetadata[]>( '$/gitlab/webview-metadata', ); return result; } } References:
You are a code assistant
Definition of 'RequestPublisher' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: 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 'warn' in file packages/lib_logging/src/types.ts in project gitlab-lsp
Definition: warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } References:
You are a code assistant
Definition of 'buildWithContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp
Definition: static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial<GitLabChatRecordAttributes>) { const convertedAttributes = attributes as Partial<GitLabChatRecord>; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References:
You are a code assistant
Definition of 'getTotalCommentLines' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp
Definition: getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set<number>(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:
You are a code assistant
Definition of '__init__' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp
Definition: def __init__(self, name): pass def greet(self): pass class Greet2: def __init__(self, name): self.name = name def greet(self): print(f"Hello {self.name}") class Greet3: pass def greet3(name): ... class Greet4: def __init__(self, name): ... def greet(self): ... class Greet3: ... def greet3(name): class Greet4: def __init__(self, name): def greet(self): class Greet3: References:
You are a code assistant
Definition of 'WorkspaceFolderUri' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: type WorkspaceFolderUri = string; const duoFeaturesEnabledQuery = gql` query GetProject($projectPath: ID!) { project(fullPath: $projectPath) { duoFeaturesEnabled } } `; interface GitConfig { [section: string]: { [key: string]: string }; } type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string }; export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { 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: - src/common/git/repository_service.ts:280 - src/common/git/repository_service.ts:245 - src/common/git/repository_service.ts:241
You are a code assistant
Definition of 'getForSaaSAccount' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp
Definition: async getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined> { return new ChatPlatformForAccount(this.#client); } } References:
You are a code assistant
Definition of 'ITelemetryNotificationParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp
Definition: export interface ITelemetryNotificationParams { category: 'code_suggestions'; action: TRACKING_EVENTS; context: { trackingId: string; optionId?: number; }; } export interface IStartWorkflowParams { goal: string; image: string; } export const waitMs = (msToWait: number) => new Promise((resolve) => { setTimeout(resolve, msToWait); }); /* CompletionRequest represents LS client's request for either completion or inlineCompletion */ export interface CompletionRequest { textDocument: TextDocumentIdentifier; position: Position; token: CancellationToken; inlineCompletionContext?: InlineCompletionContext; } export class DefaultSuggestionService { readonly #suggestionClientPipeline: SuggestionClientPipeline; #configService: ConfigService; #api: GitLabApiClient; #tracker: TelemetryTracker; #connection: Connection; #documentTransformerService: DocumentTransformerService; #circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests'); #subscriptions: Disposable[] = []; #suggestionsCache: SuggestionsCache; #treeSitterParser: TreeSitterParser; #duoProjectAccessChecker: DuoProjectAccessChecker; #featureFlagService: FeatureFlagService; #postProcessorPipeline = new PostProcessorPipeline(); constructor({ telemetryTracker, configService, api, connection, documentTransformerService, featureFlagService, treeSitterParser, duoProjectAccessChecker, }: SuggestionServiceOptions) { this.#configService = configService; this.#api = api; this.#tracker = telemetryTracker; this.#connection = connection; this.#documentTransformerService = documentTransformerService; this.#suggestionsCache = new SuggestionsCache(this.#configService); this.#treeSitterParser = treeSitterParser; this.#featureFlagService = featureFlagService; const suggestionClient = new FallbackClient( new DirectConnectionClient(this.#api, this.#configService), new DefaultSuggestionClient(this.#api), ); this.#suggestionClientPipeline = new SuggestionClientPipeline([ clientToMiddleware(suggestionClient), createTreeSitterMiddleware({ treeSitterParser, getIntentFn: getIntent, }), ]); this.#subscribeToCircuitBreakerEvents(); this.#duoProjectAccessChecker = duoProjectAccessChecker; } completionHandler = async ( { textDocument, position }: CompletionParams, token: CancellationToken, ): Promise<CompletionItem[]> => { log.debug('Completion requested'); const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token }); if (suggestionOptions.find(isStream)) { log.warn( `Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`, ); } return completionOptionMapper(suggestionOptions.filter(isTextSuggestion)); }; #getSuggestionOptions = async ( request: CompletionRequest, ): Promise<SuggestionOptionOrStream[]> => { const { textDocument, position, token, inlineCompletionContext: context } = request; const suggestionContext = this.#documentTransformerService.getContext( textDocument.uri, position, this.#configService.get('client.workspaceFolders') ?? [], context, ); if (!suggestionContext) { return []; } const cachedSuggestions = this.#useAndTrackCachedSuggestions( textDocument, position, suggestionContext, context?.triggerKind, ); if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) { const options = await this.#handleNonStreamingCompletion(request, suggestionContext); options.unshift(...(cachedSuggestions ?? [])); (cachedSuggestions ?? []).forEach((cs) => this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, { optionsCount: options.length, }), ); return options; } if (cachedSuggestions) { return cachedSuggestions; } // debounce await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS); if (token.isCancellationRequested) { log.debug('Debounce triggered for completion'); return []; } if ( context && shouldRejectCompletionWithSelectedCompletionTextMismatch( context, this.#documentTransformerService.get(textDocument.uri), ) ) { return []; } const additionalContexts = await this.#getAdditionalContexts(suggestionContext); // right now we only support streaming for inlineCompletion // if the context is present, we know we are handling inline completion if ( context && this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations) ) { const intentResolution = await this.#getIntent(suggestionContext); if (intentResolution?.intent === 'generation') { return this.#handleStreamingInlineCompletion( suggestionContext, intentResolution.commentForCursor?.content, intentResolution.generationType, additionalContexts, ); } } return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts); }; inlineCompletionHandler = async ( params: InlineCompletionParams, token: CancellationToken, ): Promise<InlineCompletionList> => { log.debug('Inline completion requested'); const options = await this.#getSuggestionOptions({ textDocument: params.textDocument, position: params.position, token, inlineCompletionContext: params.context, }); return inlineCompletionOptionMapper(params, options); }; async #handleStreamingInlineCompletion( context: IDocContext, userInstruction?: string, generationType?: GenerationType, additionalContexts?: AdditionalContext[], ): Promise<StartStreamOption[]> { if (this.#circuitBreaker.isOpen()) { log.warn('Stream was not started as the circuit breaker is open.'); return []; } const streamId = uniqueId('code-suggestion-stream-'); const uniqueTrackingId = generateUniqueTrackingId(); setTimeout(() => { log.debug(`Starting to stream (id: ${streamId})`); const streamingHandler = new DefaultStreamingHandler({ api: this.#api, circuitBreaker: this.#circuitBreaker, connection: this.#connection, documentContext: context, parser: this.#treeSitterParser, postProcessorPipeline: this.#postProcessorPipeline, streamId, tracker: this.#tracker, uniqueTrackingId, userInstruction, generationType, additionalContexts, }); streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e)); }, 0); return [{ streamId, uniqueTrackingId }]; } async #handleNonStreamingCompletion( request: CompletionRequest, documentContext: IDocContext, additionalContexts?: AdditionalContext[], ): Promise<SuggestionOption[]> { const uniqueTrackingId: string = generateUniqueTrackingId(); try { return await this.#getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }); } catch (e) { if (isFetchError(e)) { this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status }); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); this.#circuitBreaker.error(); log.error('Failed to get code suggestions!', e); return []; } } /** * FIXME: unify how we get code completion and generation * so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`) * */ async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> { try { const treeAndLanguage = await this.#treeSitterParser.parseFile(context); if (!treeAndLanguage) { return undefined; } return await getIntent({ treeAndLanguage, position: context.position, prefix: context.prefix, suffix: context.suffix, }); } catch (error) { log.error('Failed to parse with tree sitter', error); return undefined; } } #trackShowIfNeeded(uniqueTrackingId: string) { if ( !canClientTrackEvent( this.#configService.get('client.telemetry.actions'), TRACKING_EVENTS.SHOWN, ) ) { /* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server. Otherwise the server will assume that returned suggestions are shown and tracks the event */ this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); } } async #getSuggestions({ request, uniqueTrackingId, documentContext, additionalContexts, }: { request: CompletionRequest; uniqueTrackingId: string; documentContext: IDocContext; additionalContexts?: AdditionalContext[]; }): Promise<SuggestionOption[]> { const { textDocument, position, token } = request; const triggerKind = request.inlineCompletionContext?.triggerKind; log.info('Suggestion requested.'); if (this.#circuitBreaker.isOpen()) { log.warn('Code suggestions were not requested as the circuit breaker is open.'); return []; } if (!this.#configService.get('client.token')) { return []; } // Do not send a suggestion if content is less than 10 characters const contentLength = (documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0); if (contentLength < 10) { return []; } if (!isAtOrNearEndOfLine(documentContext.suffix)) { return []; } // Creates the suggestion and tracks suggestion_requested this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, triggerKind, additionalContexts, }); /** how many suggestion options should we request from the API */ const optionsCount: OptionsCount = triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1; const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({ document: documentContext, projectPath: this.#configService.get('client.projectPath'), optionsCount, additionalContexts, }); this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { model: suggestionsResponse?.model, status: suggestionsResponse?.status, optionsCount: suggestionsResponse?.choices?.length, isDirectConnection: suggestionsResponse?.isDirectConnection, }); if (suggestionsResponse?.error) { throw new Error(suggestionsResponse.error); } this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#circuitBreaker.success(); const areSuggestionsNotProvided = !suggestionsResponse?.choices?.length || suggestionsResponse?.choices.every(({ text }) => !text?.length); const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({ ...choice, index, uniqueTrackingId, lang: suggestionsResponse?.model?.lang, })); const processedChoices = await this.#postProcessorPipeline.run({ documentContext, input: suggestionOptions, type: 'completion', }); this.#suggestionsCache.addToSuggestionCache({ request: { document: textDocument, position, context: documentContext, additionalContexts, }, suggestions: processedChoices, }); if (token.isCancellationRequested) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); return []; } if (areSuggestionsNotProvided) { this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); return []; } this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions }); this.#trackShowIfNeeded(uniqueTrackingId); return processedChoices; } dispose() { this.#subscriptions.forEach((subscription) => subscription?.dispose()); } #subscribeToCircuitBreakerEvents() { this.#subscriptions.push( this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)), ); this.#subscriptions.push( this.#circuitBreaker.onClose(() => this.#connection.sendNotification(API_RECOVERY_NOTIFICATION), ), ); } #useAndTrackCachedSuggestions( textDocument: TextDocumentIdentifier, position: Position, documentContext: IDocContext, triggerKind?: InlineCompletionTriggerKind, ): SuggestionOption[] | undefined { const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({ document: textDocument, position, context: documentContext, }); if (suggestionsCache?.options?.length) { const { uniqueTrackingId, lang } = suggestionsCache.options[0]; const { additionalContexts } = suggestionsCache; this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, source: SuggestionSource.cache, triggerKind, suggestionOptions: suggestionsCache?.options, language: lang, additionalContexts, }); this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED); this.#trackShowIfNeeded(uniqueTrackingId); return suggestionsCache.options.map((option, index) => ({ ...option, index })); } return undefined; } async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> { let additionalContexts: AdditionalContext[] = []; const advancedContextEnabled = shouldUseAdvancedContext( this.#featureFlagService, this.#configService, ); if (advancedContextEnabled) { const advancedContext = await getAdvancedContext({ documentContext, dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker }, }); additionalContexts = advancedContextToRequestBody(advancedContext); } return additionalContexts; } } References: - src/common/message_handler.ts:131
You are a code assistant
Definition of 'readFile' in file src/common/services/fs/file.ts in project gitlab-lsp
Definition: readFile(_args: ReadFile): Promise<string> { return Promise.resolve(''); } } References: - src/tests/unit/tree_sitter/test_utils.ts:38 - src/tests/int/fetch.test.ts:15 - src/node/services/fs/file.ts:9 - src/node/duo_workflow/desktop_workflow_runner.ts:184 - src/node/duo_workflow/desktop_workflow_runner.ts:137 - src/tests/int/fetch.test.ts:40
You are a code assistant
Definition of 'use' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp
Definition: use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce<SuggestionClientFn>( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined> { return this.#pipeline(context); } } References:
You are a code assistant
Definition of 'goIntoStreamingMode' in file src/common/suggestion/suggestion_service.test.ts in project gitlab-lsp
Definition: function goIntoStreamingMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(true); mockParseFile.mockResolvedValue('generation'); } function goIntoCompletionMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(false); mockParseFile.mockResolvedValue('completion'); } it('starts breaking after 4 errors', async () => { jest.mocked(DefaultStreamingHandler).mockClear(); jest.mocked(DefaultStreamingHandler).mockReturnValue( createFakePartial<DefaultStreamingHandler>({ startStream: jest.fn().mockResolvedValue([]), }), ); goIntoStreamingMode(); const successResult = await getCompletions(); expect(successResult.items.length).toEqual(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); jest.mocked(DefaultStreamingHandler).mockClear(); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue('test problem'); await turnOnCircuitBreaker(); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toEqual([]); expect(DefaultStreamingHandler).not.toHaveBeenCalled(); }); it(`starts the stream after circuit breaker's break time elapses`, async () => { jest.useFakeTimers().setSystemTime(new Date(Date.now())); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue(new Error('test problem')); await turnOnCircuitBreaker(); jest.advanceTimersByTime(CIRCUIT_BREAK_INTERVAL_MS + 1); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toHaveLength(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); }); }); }); describe('selection completion info', () => { beforeEach(() => { mockGetCodeSuggestions.mockReset(); mockGetCodeSuggestions.mockResolvedValue({ choices: [{ text: 'log("Hello world")' }], model: { lang: 'js', }, }); }); describe('when undefined', () => { it('does not update choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: undefined, }), }, token, ); expect(items[0].insertText).toBe('log("Hello world")'); }); }); describe('with range and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: { text: 'console.', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 2 } }, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log("Hello world")'); }); }); describe('with range (Array) and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial<InlineCompletionContext>({ selectedCompletionInfo: { text: 'console.', // NOTE: This forcefully simulates the behavior we see where range is an Array at runtime. range: [ { line: 1, character: 0 }, { line: 1, character: 2 }, ] as unknown as Range, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log("Hello world")'); }); }); }); describe('Additional Context', () => { beforeEach(async () => { jest.mocked(shouldUseAdvancedContext).mockReturnValueOnce(true); getAdvancedContextSpy.mockResolvedValue(sampleAdvancedContext); contextBodySpy.mockReturnValue(sampleAdditionalContexts); await requestInlineCompletionNoDebounce(inlineCompletionParams, token); }); it('getCodeSuggestions should have additional context passed if feature is enabled', async () => { expect(getAdvancedContextSpy).toHaveBeenCalled(); expect(contextBodySpy).toHaveBeenCalledWith(sampleAdvancedContext); expect(api.getCodeSuggestions).toHaveBeenCalledWith( expect.objectContaining({ context: sampleAdditionalContexts }), ); }); it('should be tracked with telemetry', () => { expect(tracker.setCodeSuggestionsContext).toHaveBeenCalledWith( TRACKING_ID, expect.objectContaining({ additionalContexts: sampleAdditionalContexts }), ); }); }); }); }); }); References: - src/common/suggestion/suggestion_service.test.ts:987 - src/common/suggestion/suggestion_service.test.ts:1013 - src/common/suggestion/suggestion_service.test.ts:998
You are a code assistant
Definition of 'getSelectedText' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp
Definition: export const getSelectedText = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection } = editor; // const selectionRange = new vscode.Range( // selection.start.line, // selection.start.character, // selection.end.line, // selection.end.character, // ); // return editor.document.getText(selectionRange); }; export const getActiveFileName = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return vscode.workspace.asRelativePath(editor.document.uri); }; export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:16
You are a code assistant
Definition of 'error' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp
Definition: error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } success() { this.#errorCount = 0; this.#close(); } onOpen(listener: () => void): Disposable { this.#eventEmitter.on('open', listener); return { dispose: () => this.#eventEmitter.removeListener('open', listener) }; } onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94
You are a code assistant
Definition of 'triggerDocumentEvent' in file src/common/feature_state/project_duo_acces_check.test.ts in project gitlab-lsp
Definition: function triggerDocumentEvent(documentUri: string) { const document = createFakePartial<TextDocument>({ uri: documentUri }); const event = createFakePartial<TextDocumentChangeEvent<TextDocument>>({ document }); documentEventListener(event, TextDocumentChangeListenerType.onDidSetActive); } beforeEach(async () => { onDocumentChange.mockImplementation((_listener) => { documentEventListener = _listener; }); onDuoProjectCacheUpdate.mockImplementation((_listener) => { duoProjectCacheUpdateListener = _listener; }); check = new DefaultProjectDuoAccessCheck( documentService, configService, duoProjectAccessChecker, duoProjectAccessCache, ); disposables.push(check.onChanged(policyEngagedChangeListener)); }); afterEach(() => { while (disposables.length > 0) { disposables.pop()!.dispose(); } }); describe('is updated on config change"', () => { it('should NOT be engaged when no client setting provided and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', null); expect(check.engaged).toBe(false); }); it('should be engaged when disabled in setting and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', false); expect(check.engaged).toBe(true); }); it('should NOT be engaged when enabled in setting and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', true); expect(check.engaged).toBe(false); }); }); describe('is updated on document set active in editor event', () => { beforeEach(() => { configService.set('client.workspaceFolders', [workspaceFolder]); }); it('should NOT be engaged when duo enabled for project file', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoEnabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); }); it('should be engaged when duo disabled for project file', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoDisabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(true); }); it('should use default setting when no GitLab project detected', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.NonGitlabProject); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); }); }); describe('is updated on duo cache update', () => { beforeEach(() => { configService.set('client.workspaceFolders', [workspaceFolder]); configService.set('client.duo.enabledWithoutGitlabProject', false); }); it('should be engaged and rely on setting value when file does not belong to Duo project', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoEnabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.NonGitlabProject); duoProjectCacheUpdateListener(); expect(check.engaged).toBe(true); }); }); describe('change event', () => { it('emits after check is updated', () => { policyEngagedChangeListener.mockClear(); configService.set('client.duo.enabledWithoutGitlabProject', false); expect(policyEngagedChangeListener).toHaveBeenCalledTimes(1); }); }); }); References: - src/common/feature_state/project_duo_acces_check.test.ts:117 - src/common/feature_state/supported_language_check.test.ts:109 - src/common/feature_state/project_duo_acces_check.test.ts:134 - src/common/feature_state/supported_language_check.test.ts:81 - src/common/feature_state/project_duo_acces_check.test.ts:96 - src/common/feature_state/project_duo_acces_check.test.ts:106 - src/common/feature_state/supported_language_check.test.ts:115 - src/common/feature_state/supported_language_check.test.ts:72 - src/common/feature_state/supported_language_check.test.ts:88 - src/common/feature_state/supported_language_check.test.ts:63
You are a code assistant
Definition of 'generate_greetings' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp
Definition: def generate_greetings end def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:37
You are a code assistant
Definition of 'merge' in file src/common/config_service.ts in project gitlab-lsp
Definition: merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:
You are a code assistant
Definition of 'ProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp
Definition: export interface ProjectDuoAccessCheck extends StateCheck {} export const ProjectDuoAccessCheck = createInterfaceId<ProjectDuoAccessCheck>('ProjectDuoAccessCheck'); @Injectable(ProjectDuoAccessCheck, [ DocumentService, ConfigService, DuoProjectAccessChecker, DuoProjectAccessCache, ]) export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; 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: - src/common/feature_state/feature_state_manager.ts:29 - src/common/feature_state/project_duo_acces_check.test.ts:15
You are a code assistant
Definition of 'constructor' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp
Definition: constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn<FeatureStateNotificationParams>): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( "The state manager hasn't been initialized. It can't send notifications. Call the init method first.", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References:
You are a code assistant
Definition of 'onRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp
Definition: 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 'Greet2' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp
Definition: class Greet2 { name: string; 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:24
You are a code assistant
Definition of 'PostProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp
Definition: export abstract class PostProcessor { processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise<StreamingCompletionResponse> { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise<SuggestionOption[]> { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run<T extends ProcessorType>({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise<ProcessorInputMap[T]> { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise<ProcessorInputMap[T]>; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise<ProcessorInputMap[T]>; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise<ProcessorInputMap[T]>, ); } } References: - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:41
You are a code assistant
Definition of 'StartStreamParams' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp
Definition: 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.ts:53 - src/common/suggestion/streaming_handler.ts:51 - src/common/suggestion/streaming_handler.ts:75
You are a code assistant
Definition of 'FetchAgentOptions' in file src/common/fetch.ts in project gitlab-lsp
Definition: export interface FetchAgentOptions { ignoreCertificateErrors: boolean; ca?: string; cert?: string; certKey?: string; } export type FetchHeaders = { [key: string]: string; }; export interface LsFetch { initialize(): Promise<void>; destroy(): Promise<void>; fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>; } export const LsFetch = createInterfaceId<LsFetch>('LsFetch'); export class FetchBase implements LsFetch { updateRequestInit(method: string, init?: RequestInit): RequestInit { if (typeof init === 'undefined') { // eslint-disable-next-line no-param-reassign init = { method }; } else { // eslint-disable-next-line no-param-reassign init.method = method; } return init; } async initialize(): Promise<void> {} async destroy(): Promise<void> {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return fetch(input, init); } async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator<string, void, void> { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { // eslint-disable-next-line no-underscore-dangle, no-restricted-globals const _global = typeof global === 'undefined' ? self : global; return _global.fetch(input, init); } // eslint-disable-next-line @typescript-eslint/no-unused-vars updateAgentOptions(_opts: FetchAgentOptions): void {} } References: - src/common/fetch.ts:87 - src/node/fetch.ts:120 - src/common/fetch.ts:24
You are a code assistant
Definition of 'isTextDocument' in file src/common/document_service.ts in project gitlab-lsp
Definition: function isTextDocument(param: TextDocument | DocumentUri): param is TextDocument { return (param as TextDocument).uri !== undefined; } 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/document_service.ts:53
You are a code assistant
Definition of 'onDuoProjectCacheUpdate' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp
Definition: 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 'resolveUris' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp
Definition: 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 'SAAS_INSTANCE_URL' in file src/common/tracking/constants.ts in project gitlab-lsp
Definition: export const SAAS_INSTANCE_URL = 'https://gitlab.com'; export const TELEMETRY_NOTIFICATION = '$/gitlab/telemetry'; export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions'; export const GC_TIME = 60000; export const INSTANCE_TRACKING_EVENTS_MAP = { [TRACKING_EVENTS.REQUESTED]: null, [TRACKING_EVENTS.LOADED]: null, [TRACKING_EVENTS.NOT_PROVIDED]: null, [TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide', [TRACKING_EVENTS.ERRORED]: null, [TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide', [TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide', [TRACKING_EVENTS.CANCELLED]: null, [TRACKING_EVENTS.STREAM_STARTED]: null, [TRACKING_EVENTS.STREAM_COMPLETED]: null, }; // FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net'; export const TELEMETRY_DISABLED_WARNING_MSG = 'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.'; export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.'; References:
You are a code assistant
Definition of 'getRepositoryFileForUri' in file src/common/git/repository_service.ts in project gitlab-lsp
Definition: getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:
You are a code assistant
Definition of 'sanitizeRange' in file src/common/utils/sanitize_range.ts in project gitlab-lsp
Definition: export function sanitizeRange(range: Range): Range { if (Array.isArray(range)) { return { start: range[0], end: range[1] }; } return range; } References: - src/common/suggestion/suggestion_filter.ts:35 - src/common/utils/sanitize_range.test.ts:9 - src/common/document_transformer_service.ts:118 - src/common/utils/suggestion_mappers.ts:61
You are a code assistant
Definition of 'get' in file src/common/fetch.ts in project gitlab-lsp
Definition: 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: - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20 - src/common/utils/headers_to_snowplow_options.ts:22
You are a code assistant
Definition of 'hasbinFirst' in file src/tests/int/hasbin.ts in project gitlab-lsp
Definition: 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 'submitFeedback' in file packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts in project gitlab-lsp
Definition: export const submitFeedback = async (_: SubmitFeedbackParams) => { // const hasFeedback = Boolean(extendedTextFeedback?.length) || Boolean(feedbackChoices?.length); // if (!hasFeedback) { // return; // } // const standardContext = buildStandardContext(extendedTextFeedback, gitlabEnvironment); // const ideExtensionVersion = buildIdeExtensionContext(); // await Snowplow.getInstance().trackStructEvent( // { // category: 'ask_gitlab_chat', // action: 'click_button', // label: 'response_feedback', // property: feedbackChoices?.join(','), // }, // [standardContext, ideExtensionVersion], // ); }; References:
You are a code assistant
Definition of 'IDuoConfig' in file src/common/config_service.ts in project gitlab-lsp
Definition: export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record<string, boolean>; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter<IConfig>; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter<IConfig>; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial<IConfig>): void; } export const ConfigService = createInterfaceId<ConfigService>('ConfigService'); @Injectable(ConfigService, []) export class DefaultConfigService implements ConfigService { #config: IConfig; #eventEmitter = new EventEmitter(); constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter<IConfig> = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter<IConfig> = (key: string, value: unknown) => { set(this.#config, key, value); this.#triggerChange(); }; onConfigChange(listener: (config: IConfig) => void): Disposable { this.#eventEmitter.on('configChange', listener); return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) }; } #triggerChange() { this.#eventEmitter.emit('configChange', this.#config); } merge(newConfig: Partial<IConfig>) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:75
You are a code assistant
Definition of 'DuoWorkflowEventConnectionType' in file packages/webview_duo_workflow/src/types.ts in project gitlab-lsp
Definition: export type DuoWorkflowEventConnectionType = { duoWorkflowEvents: DuoWorkflowEvents; }; References: - src/common/graphql/workflow/service.ts:76
You are a code assistant
Definition of 'IDirectConnectionDetails' in file src/common/api.ts in project gitlab-lsp
Definition: 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/suggestion_client/direct_connection_client.ts:24
You are a code assistant
Definition of 'UNSUPPORTED_LANGUAGE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: 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 'SuggestionSource' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } export interface IClientContext { ide?: IIDEInfo; extension?: IClientInfo; } export interface ITelemetryOptions { enabled?: boolean; baseUrl?: string; trackingUrl?: string; actions?: Array<{ action: TRACKING_EVENTS }>; ide?: IIDEInfo; extension?: IClientInfo; } export interface ICodeSuggestionModel { lang: string; engine: string; name: string; tokens_consumption_metadata?: { input_tokens?: number; output_tokens?: number; context_tokens_sent?: number; context_tokens_used?: number; }; } export interface TelemetryTracker { isEnabled(): boolean; setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial<ICodeSuggestionContextUpdate>, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial<ICodeSuggestionContextUpdate>, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References: - src/common/tracking/snowplow_tracker.ts:61 - src/common/tracking/tracking_types.ts:9
You are a code assistant
Definition of 'Injectable' in file packages/lib_di/src/index.ts in project gitlab-lsp
Definition: export function Injectable<I, TDependencies extends InterfaceId<unknown>[]>( id: InterfaceId<I>, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function <T extends { new (...args: UnwrapInterfaceIds<TDependencies>): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set<string>(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map<string, ClassWithDependencies>): ClassWithDependencies[] => { const visited = new Set<string>(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance<T extends object> = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = <T extends object>( id: InterfaceId<T>, instance: T, ): BrandedInstance<T> => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map<string, unknown>(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been "branded" by the `brandInstance` method */ addInstances(...instances: BrandedInstance<object>[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map<string, ClassWithDependencies>(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get<T>(id: InterfaceId<T>): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.test.ts:98 - src/common/config_service.ts:110 - src/common/ai_context_management_2/policies/duo_project_policy.ts:11 - src/common/services/duo_access/project_access_cache.ts:85 - packages/lib_di/src/index.test.ts:25 - packages/lib_di/src/index.test.ts:36 - src/common/api.ts:119 - src/common/ai_context_management_2/ai_context_aggregator.ts:22 - src/common/services/fs/dir.ts:40 - src/common/suggestion/supported_languages_service.ts:28 - src/common/secret_redaction/index.ts:13 - src/common/core/handlers/did_change_workspace_folders_handler.ts:12 - src/common/feature_state/feature_state_manager.ts:19 - packages/lib_di/src/index.test.ts:20 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:14 - src/common/feature_state/supported_language_check.ts:16 - packages/lib_di/src/index.test.ts:142 - src/common/security_diagnostics_publisher.ts:31 - src/node/services/fs/dir.ts:22 - src/node/duo_workflow/desktop_workflow_runner.ts:41 - src/common/advanced_context/advanced_context_service.ts:18 - packages/lib_di/src/index.test.ts:161 - src/common/core/handlers/initialize_handler.ts:17 - src/common/services/duo_access/project_access_checker.ts:18 - src/common/ai_context_management_2/ai_policy_management.ts:20 - src/node/services/fs/file.ts:6 - src/common/core/handlers/token_check_notifier.ts:10 - src/common/workspace/workspace_service.ts:18 - src/common/document_transformer_service.ts:75 - src/common/services/fs/virtual_file_service.ts:40 - src/common/feature_state/project_duo_acces_check.ts:19 - src/common/git/repository_service.ts:26 - src/common/feature_flags.ts:41 - src/common/ai_context_management_2/ai_context_manager.ts:11 - src/common/services/fs/file.ts:13 - src/node/fetch.ts:36 - src/common/connection_service.ts:41 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:19 - src/common/graphql/workflow/service.ts:12
You are a code assistant
Definition of 'CODE_SUGGESTIONS' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp
Definition: export const CODE_SUGGESTIONS = 'code_suggestions' as const; export const CHAT = 'chat' as const; // export const WORKFLOW = 'workflow' as const; export type Feature = typeof CODE_SUGGESTIONS | typeof CHAT; // | typeof WORKFLOW; 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 'constructor' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp
Definition: constructor( name: string, maxErrorsBeforeBreaking: number = MAX_ERRORS_BEFORE_CIRCUIT_BREAK, breakTimeMs: number = CIRCUIT_BREAK_INTERVAL_MS, ) { this.#name = name; this.#maxErrorsBeforeBreaking = maxErrorsBeforeBreaking; this.#breakTimeMs = breakTimeMs; } error() { this.#errorCount += 1; if (this.#errorCount >= this.#maxErrorsBeforeBreaking) { this.#open(); } } #open() { this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#breakTimeMs / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#breakTimeMs); this.#eventEmitter.emit('open'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } 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) }; } } References:
You are a code assistant
Definition of 'constructor' in file src/common/workspace/workspace_service.ts in project gitlab-lsp
Definition: constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:
You are a code assistant
Definition of 'constructor' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp
Definition: constructor(address: AddressInfo) { this.#addressInfo = address; } getUri(webviewId: WebviewId): string { return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`; } } References:
You are a code assistant
Definition of 'WEB_IDE_AUTH_SCOPE' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp
Definition: export const WEB_IDE_AUTH_SCOPE = 'api'; // region: Mediator commands ------------------------------------------- export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`; // Return type from `COMMAND_FETCH_BUFFER_FROM_API` export interface VSCodeBuffer { readonly buffer: Uint8Array; } // region: Shared configuration ---------------------------------------- export interface InteropConfig { projectPath: string; gitlabUrl: string; } // region: API types --------------------------------------------------- /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ export interface PostRequest<_TReturnType> { type: 'rest'; method: 'POST'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; body?: unknown; headers?: Record<string, string>; } /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the _TReturnType */ interface GetRequestBase<_TReturnType> { method: 'GET'; /** * The request path without `/api/v4` * If you want to make request to `https://gitlab.example/api/v4/projects` * set the path to `/projects` */ path: string; searchParams?: Record<string, string>; headers?: Record<string, string>; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase<Uint8Array> { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record<string, unknown>; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchFromApi = <_TReturnType>( request: ApiRequest<_TReturnType>, ) => Promise<_TReturnType>; // The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API // Will throw ResponseError if HTTP response status isn't 200 export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>; /* API exposed by the Web IDE extension * See https://code.visualstudio.com/api/references/vscode-api#extensions */ export interface WebIDEExtension { isTelemetryEnabled: () => boolean; projectPath: string; gitlabUrl: string; } export interface ResponseError extends Error { status: number; body?: unknown; } References:
You are a code assistant
Definition of 'preparePayload' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp
Definition: function preparePayload(payload: Payload): Record<string, string> { const stringifiedPayload: Record<string, string> = {}; Object.keys(payload).forEach((key) => { stringifiedPayload[key] = String(payload[key]); }); stringifiedPayload.stm = new Date().getTime().toString(); return stringifiedPayload; } export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise<void> { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to "gl" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with "js-*"" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise<void> { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:107
You are a code assistant
Definition of 'IntentResolution' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp
Definition: export type IntentResolution = { intent: Intent; commentForCursor?: Comment; generationType?: GenerationType; }; /** * Determines the user intent based on cursor position and context within the file. * Intent is determined based on several ordered rules: * - Returns 'completion' if the cursor is located on or after an empty comment. * - Returns 'generation' if the cursor is located after a non-empty comment. * - Returns 'generation' if the cursor is not located after a comment and the file is less than 5 lines. * - Returns undefined if neither a comment nor small file is detected. */ export async function getIntent({ treeAndLanguage, position, prefix, suffix, }: { treeAndLanguage: TreeAndLanguage; position: Position; prefix: string; suffix: string; }): Promise<IntentResolution> { const commentResolver = getCommentResolver(); const emptyFunctionResolver = getEmptyFunctionResolver(); const cursorPosition = { row: position.line, column: position.character }; const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage; const commentResolution = commentResolver.getCommentForCursor({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (commentResolution) { const { commentAtCursor, commentAboveCursor } = commentResolution; if (commentAtCursor) { log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion'); return { intent: 'completion' }; } const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor); if (isCommentEmpty) { log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion'); return { intent: 'completion' }; } log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation'); return { intent: 'generation', generationType: 'comment', commentForCursor: commentAboveCursor, }; } const textContent = `${prefix}${suffix}`; const totalCommentLines = commentResolver.getTotalCommentLines({ languageName: languageInfo.name, treeSitterLanguage, tree, }); if (isSmallFile(textContent, totalCommentLines)) { log.debug('IntentResolver: Small file detected, sending intent: generation'); return { intent: 'generation', generationType: 'small_file' }; } const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (isCursorInEmptyFunction) { log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation'); return { intent: 'generation', generationType: 'empty_function' }; } log.debug( 'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.', ); return { intent: undefined }; } References:
You are a code assistant
Definition of 'AiContextFileRetriever' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp
Definition: export const AiContextFileRetriever = createInterfaceId<AiContextFileRetriever>('AiContextFileRetriever'); @Injectable(AiContextFileRetriever, [FileResolver, SecretRedactor]) export class DefaultAiContextFileRetriever implements AiContextRetriever { constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} async retrieve(aiContextItem: AiContextItem): Promise<string | null> { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References: - src/common/ai_context_management_2/ai_context_manager.ts:15 - src/common/ai_context_management_2/ai_context_manager.ts:13
You are a code assistant
Definition of 'onFileSystemEvent' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp
Definition: onFileSystemEvent(listener: FileSystemEventListener) { this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener), }; } } References:
You are a code assistant
Definition of 'AiCompletionResponseResponseType' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp
Definition: type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents<AiCompletionResponseResponseType> { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:92
You are a code assistant
Definition of 'fetchBase' in file src/common/fetch.ts in project gitlab-lsp
Definition: 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 'init' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp
Definition: init(notify: NotifyFn<FeatureStateNotificationParams>): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( "The state manager hasn't been initialized. It can't send notifications. Call the init method first.", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References:
You are a code assistant
Definition of 'isInstanceFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp
Definition: isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean { return this.#featureFlags.get(name) ?? false; } /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean { const value = this.#configService.get('client.featureFlags')?.[name]; return value ?? false; } } References:
You are a code assistant
Definition of 'rejectOpenedSuggestions' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References:
You are a code assistant
Definition of 'rejectOpenedSuggestions' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp
Definition: 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 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:
You are a code assistant
Definition of 'isWebviewInstanceCreatedEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp
Definition: 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:
You are a code assistant
Definition of 'FileExtension' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp
Definition: type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:
You are a code assistant
Definition of 'NullLogger' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp
Definition: export class NullLogger implements Logger { debug(e: Error): void; debug(message: string, e?: Error | undefined): void; debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:21 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:15 - packages/webview_duo_chat/src/plugin/port/log.ts:3
You are a code assistant
Definition of 'TelemetryTracker' in file src/common/tracking/tracking_types.ts in project gitlab-lsp
Definition: export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker'); References: - src/common/connection.ts:20 - src/common/message_handler.ts:34 - src/common/suggestion/suggestion_service.ts:77 - src/common/message_handler.ts:73 - src/common/suggestion/suggestion_service.ts:121 - src/common/suggestion/streaming_handler.ts:43
You are a code assistant
Definition of 'main' in file src/node/main.ts in project gitlab-lsp
Definition: async function main() { const useSourceMaps = process.argv.includes('--use-source-maps'); const printVersion = process.argv.includes('--version') || process.argv.includes('-v'); const version = getLanguageServerVersion(); if (printVersion) { // eslint-disable-next-line no-console console.error(`GitLab Language Server v${version}`); return; } if (useSourceMaps) installSourceMapSupport(); const container = new Container(); container.instantiate(DefaultConfigService, DefaultSupportedLanguagesService); const configService = container.get(ConfigService); const connection = createConnection(ProposedFeatures.all); container.addInstances(brandInstance(LsConnection, connection)); const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument); container.addInstances(brandInstance(LsTextDocuments, documents)); log.setup(configService); // Send all console messages to stderr. Stdin/stdout may be in use // as the LSP communications channel. // // This has to happen after the `createConnection` because the `vscode-languageserver` server version 9 and higher // patches the console as well // https://github.com/microsoft/vscode-languageserver-node/blob/84285312d8d9f22ee0042e709db114e5415dbdde/server/src/node/main.ts#L270 // // FIXME: we should really use the remote logging with `window/logMessage` messages // That's what the authors of the languageserver-node want us to use // https://github.com/microsoft/vscode-languageserver-node/blob/4e057d5d6109eb3fcb075d0f99456f05910fda44/server/src/common/server.ts#L133 global.console = new Console({ stdout: process.stderr, stderr: process.stderr }); const lsFetch = new Fetch(); await lsFetch.initialize(); container.addInstances(brandInstance(LsFetch, lsFetch)); const documentService = new DefaultDocumentService(documents); container.addInstances(brandInstance(DocumentService, documentService)); container.instantiate( GitLabAPI, DefaultDocumentTransformerService, DefaultFeatureFlagService, DefaultTokenCheckNotifier, DefaultSecretRedactor, DefaultSecurityDiagnosticsPublisher, DefaultConnectionService, DefaultInitializeHandler, DefaultDidChangeWorkspaceFoldersHandler, DefaultCodeSuggestionsSupportedLanguageCheck, DefaultProjectDuoAccessCheck, DefaultAdvancedContextService, // Workspace Dependencies DesktopFileResolver, DesktopDirectoryWalker, DefaultDuoProjectAccessChecker, DefaultDuoProjectAccessCache, DefaultVirtualFileSystemService, DefaultRepositoryService, DefaultWorkspaceService, DefaultFeatureStateManager, // Ai Context Dependencies DefaultAiContextAggregator, DefaultAiFileContextProvider, DefaultAiContextFileRetriever, DefaultAiPolicyManager, DefaultDuoProjectPolicy, DefaultAiContextManager, ); const snowplowTracker = new SnowplowTracker( container.get(LsFetch), container.get(ConfigService), container.get(FeatureFlagService), container.get(GitLabApiClient), ); const instanceTracker = new InstanceTracker( container.get(GitLabApiClient), container.get(ConfigService), ); const telemetryTracker = new MultiTracker([snowplowTracker, instanceTracker]); container.addInstances(brandInstance(TelemetryTracker, telemetryTracker)); const treeSitterParser = new DesktopTreeSitterParser(); const workflowAPI = new DesktopWorkflowRunner( configService, lsFetch, container.get(GitLabApiClient), ); const workflowGraphqlAPI = new WorkflowGraphQLService(container.get(GitLabApiClient), log); const webviewLocationService = new WebviewLocationService(); const webviewTransports = new Set<Transport>(); const webviewMetadataProvider = new WebviewMetadataProvider( webviewLocationService, webviewPlugins, ); log.info(`GitLab Language Server is starting (v${version})`); webviewTransports.add( new JsonRpcConnectionTransport({ connection, logger: log, }), ); const extensionMessageBusProvider = new ExtensionConnectionMessageBusProvider({ connection, logger: log, }); setup( telemetryTracker, connection, container.get(DocumentTransformerService), container.get(GitLabApiClient), container.get(FeatureFlagService), configService, { treeSitterParser, }, webviewMetadataProvider, workflowAPI, container.get(DuoProjectAccessChecker), container.get(DuoProjectAccessCache), container.get(VirtualFileSystemService), ); // Make the text document manager listen on the connection for open, change and close text document events documents.listen(connection); // Listen on the connection connection.listen(); webviewPlugins.add(workflowPluginFactory(workflowGraphqlAPI, workflowAPI, connection)); webviewPlugins.add( duoChatPluginFactory({ gitlabApiClient: container.get(GitLabApiClient), }), ); await setupHttp(Array.from(webviewPlugins), webviewLocationService, webviewTransports, log); setupWebviewRuntime({ extensionMessageBusProvider, plugins: Array.from(webviewPlugins), transports: Array.from(webviewTransports), logger: log, }); log.info('GitLab Language Server has started'); } main().catch((e) => log.error(`failed to start the language server`, e)); References: - src/browser/main.ts:147 - src/node/main.ts:238
You are a code assistant
Definition of 'success' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp
Definition: success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:
You are a code assistant
Definition of 'VirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp
Definition: export const VirtualFileSystemService = createInterfaceId<VirtualFileSystemService>( 'VirtualFileSystemService', ); @Injectable(VirtualFileSystemService, [DirectoryWalker]) export class DefaultVirtualFileSystemService { #directoryWalker: DirectoryWalker; #emitter = new EventEmitter(); constructor(directoryWalker: DirectoryWalker) { this.#directoryWalker = directoryWalker; } #handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => { const fileUri = fsPathToUri(filePath); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, { event, fileUri, workspaceFolder, }); }; async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> { await Promise.all( workspaceFolders.map(async (workspaceFolder) => { const files = await this.#directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, }); this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, { files, workspaceFolder, }); this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange); }), ); } #emitFileSystemEvent<T extends VirtualFileSystemEvents>( eventType: T, data: FileSystemEventMap[T], ) { this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data); } onFileSystemEvent(listener: FileSystemEventListener) { this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener), }; } } References: - src/common/message_handler.ts:39 - src/common/connection.ts:35 - src/common/message_handler.ts:87
You are a code assistant
Definition of 'renderGFM' in file packages/webview_duo_chat/src/app/render_gfm.ts in project gitlab-lsp
Definition: export function renderGFM(element: HTMLElement) { if (!element) { return; } const highlightEls = Array.from( element.querySelectorAll('.js-syntax-highlight'), ) as HTMLElement[]; syntaxHighlight(highlightEls); } References:
You are a code assistant
Definition of 'IgnoreManager' in file src/common/git/ignore_manager.ts in project gitlab-lsp
Definition: export class IgnoreManager { #ignoreTrie: IgnoreTrie; repoUri: string; constructor(repoUri: string) { this.repoUri = repoUri; this.#ignoreTrie = new IgnoreTrie(); } async loadIgnoreFiles(files: string[]): Promise<void> { await this.#loadRootGitignore(); const gitignoreFiles = files.filter( (file) => path.basename(file) === '.gitignore' && file !== '.gitignore', ); await Promise.all(gitignoreFiles.map((file) => this.#loadGitignore(file))); } async #loadRootGitignore(): Promise<void> { const rootGitignorePath = path.join(this.repoUri, '.gitignore'); try { const content = await fs.readFile(rootGitignorePath, 'utf-8'); this.#addPatternsToTrie([], content); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { console.warn(`Failed to read root .gitignore file: ${rootGitignorePath}`, error); } } } async #loadGitignore(filePath: string): Promise<void> { try { const content = await fs.readFile(filePath, 'utf-8'); const relativePath = path.relative(this.repoUri, path.dirname(filePath)); const pathParts = relativePath.split(path.sep); this.#addPatternsToTrie(pathParts, content); } catch (error) { console.warn(`Failed to read .gitignore file: ${filePath}`, error); } } #addPatternsToTrie(pathParts: string[], content: string): void { const patterns = content .split('\n') .map((rule) => rule.trim()) .filter((rule) => rule && !rule.startsWith('#')); for (const pattern of patterns) { this.#ignoreTrie.addPattern(pathParts, pattern); } } isIgnored(filePath: string): boolean { const relativePath = path.relative(this.repoUri, filePath); const pathParts = relativePath.split(path.sep); return this.#ignoreTrie.isIgnored(pathParts); } dispose(): void { this.#ignoreTrie.dispose(); } } References: - src/common/git/repository_service.ts:268 - src/common/git/repository.ts:25 - src/common/git/repository.ts:36
You are a code assistant
Definition of 'TREE_SITTER_LANGUAGES' in file src/node/tree_sitter/languages.ts in project gitlab-lsp
Definition: export const TREE_SITTER_LANGUAGES = [ { name: 'c', extensions: ['.c'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-c.wasm'), nodeModulesPath: 'tree-sitter-c', }, { name: 'cpp', extensions: ['.cpp'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-cpp.wasm'), nodeModulesPath: 'tree-sitter-cpp', }, { name: 'c_sharp', extensions: ['.cs'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-c_sharp.wasm'), nodeModulesPath: 'tree-sitter-c-sharp', }, { name: 'css', extensions: ['.css'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-css.wasm'), nodeModulesPath: 'tree-sitter-css', }, { name: 'go', extensions: ['.go'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-go.wasm'), nodeModulesPath: 'tree-sitter-go', }, { name: 'java', extensions: ['.java'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-java.wasm'), nodeModulesPath: 'tree-sitter-java', }, { name: 'javascript', extensions: ['.js'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-javascript.wasm'), nodeModulesPath: 'tree-sitter-javascript', }, { name: 'python', extensions: ['.py'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-python.wasm'), nodeModulesPath: 'tree-sitter-python', }, { name: 'ruby', extensions: ['.rb'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-ruby.wasm'), nodeModulesPath: 'tree-sitter-ruby', }, { name: 'scala', extensions: ['.scala'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-scala.wasm'), nodeModulesPath: 'tree-sitter-scala', }, { name: 'typescript', extensions: ['.ts'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-typescript.wasm'), nodeModulesPath: 'tree-sitter-typescript/typescript', }, { name: 'tsx', extensions: ['.tsx', '.jsx'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-tsx.wasm'), nodeModulesPath: 'tree-sitter-typescript/tsx', }, // FIXME: parsing the file throws an error, address separately, same as sql // { // name: 'hcl', // terraform, terragrunt // extensions: ['.tf', '.hcl'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-hcl.wasm'), // nodeModulesPath: 'tree-sitter-hcl', // }, { name: 'kotlin', extensions: ['.kt'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-kotlin.wasm'), nodeModulesPath: 'tree-sitter-kotlin', }, { name: 'powershell', extensions: ['.ps1'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-powershell.wasm'), nodeModulesPath: 'tree-sitter-powershell', }, { name: 'rust', extensions: ['.rs'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-rust.wasm'), nodeModulesPath: 'tree-sitter-rust', }, // { FIXME: add back support for Vue // name: 'vue', // extensions: ['.vue'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-vue.wasm'), // }, { name: 'yaml', extensions: ['.yaml'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-yaml.wasm'), nodeModulesPath: '@tree-sitter-grammars/tree-sitter-yaml', }, { name: 'html', extensions: ['.html'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-html.wasm'), nodeModulesPath: 'tree-sitter-html', }, // FIXME: parsing the file throws an error, address separately, same as hcl // { // name: 'sql', // extensions: ['.sql'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-sql.wasm'), // nodeModulesPath: '@derekstride/tree-sitter-sql', // }, { name: 'bash', extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-bash.wasm'), nodeModulesPath: 'tree-sitter-bash', }, { name: 'json', extensions: ['.json'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-json.wasm'), nodeModulesPath: 'tree-sitter-json', }, ] satisfies TreeSitterLanguageInfo[]; References:
You are a code assistant
Definition of 'on' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp
Definition: 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 'createWebviewPlugin' in file src/node/webview/webview_fastify_middleware.ts in project gitlab-lsp
Definition: export const createWebviewPlugin = (options: Options): FastifyPluginRegistration => ({ plugin: (fastify, { webviewIds }) => setupWebviewRoutes(fastify, { webviewIds, getWebviewResourcePath: buildWebviewPath, }), options, }); const buildWebviewPath = (webviewId: WebviewId) => path.join(WEBVIEW_BASE_PATH, webviewId); References: - src/node/setup_http.ts:28
You are a code assistant
Definition of 'RpcMethods' in file src/common/webview/extension/types.ts in project gitlab-lsp
Definition: export type RpcMethods = { notification: string; request: string; }; export type Handlers = { notification: ExtensionMessageHandlerRegistry; request: ExtensionMessageHandlerRegistry; }; References: - src/common/webview/extension/extension_connection_message_bus.ts:21 - src/common/webview/extension/extension_connection_message_bus_provider.ts:28 - src/common/webview/extension/extension_connection_message_bus.ts:10