instruction
stringclasses 1
value | input
stringlengths 67
168
| output
stringlengths 46
67k
|
---|---|---|
You are a code assistant | Definition of 'GITLAB_COM_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp | Definition:
export const GITLAB_COM_URL: string = 'https://gitlab.com';
export const GITLAB_STAGING_URL: string = 'https://staging.gitlab.com';
export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org';
export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost';
export enum GitLabEnvironment {
GITLAB_COM = 'production',
GITLAB_STAGING = 'staging',
GITLAB_ORG = 'org',
GITLAB_DEVELOPMENT = 'development',
GITLAB_SELF_MANAGED = 'self-managed',
}
export class GitLabPlatformManagerForChat {
readonly #platformManager: GitLabPlatformManager;
constructor(platformManager: GitLabPlatformManager) {
this.#platformManager = platformManager;
}
async getProjectGqlId(): Promise<string | undefined> {
const projectManager = await this.#platformManager.getForActiveProject(false);
return projectManager?.project.gqlId;
}
/**
* Obtains a GitLab Platform to send API requests to the GitLab API
* for the Duo Chat feature.
*
* - It returns a GitLabPlatformForAccount for the first linked account.
* - It returns undefined if there are no accounts linked
*/
async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> {
const platforms = await this.#platformManager.getForAllAccounts();
if (!platforms.length) {
return undefined;
}
let platform: GitLabPlatformForAccount | undefined;
// Using a for await loop in this context because we want to stop
// evaluating accounts as soon as we find one with code suggestions enabled
for await (const result of platforms.map(getChatSupport)) {
if (result.hasSupportForChat) {
platform = result.platform;
break;
}
}
return platform;
}
async getGitLabEnvironment(): Promise<GitLabEnvironment> {
const platform = await this.getGitLabPlatform();
const instanceUrl = platform?.account.instanceUrl;
switch (instanceUrl) {
case GITLAB_COM_URL:
return GitLabEnvironment.GITLAB_COM;
case GITLAB_DEVELOPMENT_URL:
return GitLabEnvironment.GITLAB_DEVELOPMENT;
case GITLAB_STAGING_URL:
return GitLabEnvironment.GITLAB_STAGING;
case GITLAB_ORG_URL:
return GitLabEnvironment.GITLAB_ORG;
default:
return GitLabEnvironment.GITLAB_SELF_MANAGED;
}
}
}
References: |
You are a code assistant | Definition of 'subscribe' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp | Definition:
public subscribe<K extends keyof TMessageMap>(
messageType: K,
listener: Listener<TMessageMap[K]>,
filter?: FilterFunction<TMessageMap[K]>,
): Disposable {
const subscriptions = this.#subscriptions.get(messageType) ?? new Set<Subscription<unknown>>();
const subscription: Subscription<unknown> = {
listener: listener as Listener<unknown>,
filter: filter as FilterFunction<unknown> | undefined,
};
subscriptions.add(subscription);
this.#subscriptions.set(messageType, subscriptions);
return {
dispose: () => {
const targetSubscriptions = this.#subscriptions.get(messageType);
if (targetSubscriptions) {
targetSubscriptions.delete(subscription);
if (targetSubscriptions.size === 0) {
this.#subscriptions.delete(messageType);
}
}
},
};
}
public publish<K extends keyof TMessageMap>(messageType: K, data: TMessageMap[K]): void {
const targetSubscriptions = this.#subscriptions.get(messageType);
if (targetSubscriptions) {
Array.from(targetSubscriptions).forEach((subscription) => {
const { listener, filter } = subscription as Subscription<TMessageMap[K]>;
if (!filter || filter(data)) {
listener(data);
}
});
}
}
public hasListeners<K extends keyof TMessageMap>(messageType: K): boolean {
return this.#subscriptions.has(messageType);
}
public listenerCount<K extends keyof TMessageMap>(messageType: K): number {
return this.#subscriptions.get(messageType)?.size ?? 0;
}
public clear(): void {
this.#subscriptions.clear();
}
public dispose(): void {
this.clear();
}
}
References: |
You are a code assistant | Definition of 'handleFetchError' in file src/common/handle_fetch_error.ts in project gitlab-lsp | Definition:
export const handleFetchError = async (response: Response, resourceName: string) => {
if (!response.ok) {
const body = await response.text().catch(() => undefined);
throw new FetchError(response, resourceName, body);
}
};
References:
- src/common/api.ts:284
- src/common/api.ts:410
- src/common/api.ts:229
- src/common/handle_fetch_error.test.ts:15
- src/node/fetch.ts:172
- src/common/api.ts:388
- src/common/security_diagnostics_publisher.ts:103
- src/common/handle_fetch_error.test.ts:27
- src/common/suggestion_client/direct_connection_client.ts:117
- src/browser/fetch.ts:24
- src/common/api.ts:198
- src/common/handle_fetch_error.test.ts:37 |
You are a code assistant | Definition of 'ErrorMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
interface ErrorMessage {
type: 'error';
requestId: string;
role: 'system';
errors: string[];
}
const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({
requestId,
errors,
role: 'system',
type: 'error',
});
interface SuccessMessage {
type: 'message';
requestId: string;
role: string;
content: string;
contentHtml: string;
timestamp: string;
errors: string[];
extras?: {
sources: object[];
};
}
const successResponse = (response: AiMessageResponseType): SuccessMessage => ({
type: 'message',
...response,
});
type AiMessage = SuccessMessage | ErrorMessage;
type ChatInputTemplate = {
query: string;
defaultVariables: {
platformOrigin?: string;
};
};
export class GitLabChatApi {
#cachedActionQuery?: ChatInputTemplate = undefined;
#manager: GitLabPlatformManagerForChat;
constructor(manager: GitLabPlatformManagerForChat) {
this.#manager = manager;
}
async processNewUserPrompt(
question: string,
subscriptionId?: string,
currentFileContext?: GitLabChatFileContext,
): Promise<AiActionResponseType> {
return this.#sendAiAction({
question,
currentFileContext,
clientSubscriptionId: subscriptionId,
});
}
async pullAiMessage(requestId: string, role: string): Promise<AiMessage> {
const response = await pullHandler(() => this.#getAiMessage(requestId, role));
if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']);
return successResponse(response);
}
async cleanChat(): Promise<AiActionResponseType> {
return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN });
}
async #currentPlatform() {
const platform = await this.#manager.getGitLabPlatform();
if (!platform) throw new Error('Platform is missing!');
return platform;
}
async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> {
const request: GraphQLRequest<AiMessagesResponseType> = {
type: 'graphql',
query: AI_MESSAGES_QUERY,
variables: { requestIds: [requestId], roles: [role.toUpperCase()] },
};
const platform = await this.#currentPlatform();
const history = await platform.fetchFromApi(request);
return history.aiMessages.nodes[0];
}
async subscribeToUpdates(
messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>,
subscriptionId?: string,
) {
const platform = await this.#currentPlatform();
const channel = new AiCompletionResponseChannel({
htmlResponse: true,
userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`,
aiAction: 'CHAT',
clientSubscriptionId: subscriptionId,
});
const cable = await platform.connectToCable();
// we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397
// sometimes a chunk comes after the full message and it broke the chat
let fullMessageReceived = false;
channel.on('newChunk', async (msg) => {
if (fullMessageReceived) {
log.info(`CHAT-DEBUG: full message received, ignoring chunk`);
return;
}
await messageCallback(msg);
});
channel.on('fullMessage', async (message) => {
fullMessageReceived = true;
await messageCallback(message);
if (subscriptionId) {
cable.disconnect();
}
});
cable.subscribe(channel);
}
async #sendAiAction(variables: object): Promise<AiActionResponseType> {
const platform = await this.#currentPlatform();
const { query, defaultVariables } = await this.#actionQuery();
const projectGqlId = await this.#manager.getProjectGqlId();
const request: GraphQLRequest<AiActionResponseType> = {
type: 'graphql',
query,
variables: {
...variables,
...defaultVariables,
resourceId: projectGqlId ?? null,
},
};
return platform.fetchFromApi(request);
}
async #actionQuery(): Promise<ChatInputTemplate> {
if (!this.#cachedActionQuery) {
const platform = await this.#currentPlatform();
try {
const { version } = await platform.fetchFromApi(versionRequest);
this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>(
version,
MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION,
() => CHAT_INPUT_TEMPLATE_17_3_AND_LATER,
() => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER,
);
} catch (e) {
log.debug(`GitLab version check for sending chat failed:`, e as Error);
this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER;
}
}
return this.#cachedActionQuery;
}
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:113 |
You are a code assistant | Definition of 'DefaultAiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp | Definition:
export class DefaultAiContextManager {
#fileRetriever: AiContextFileRetriever;
constructor(fileRetriever: AiContextFileRetriever) {
this.#fileRetriever = fileRetriever;
}
#items: Map<string, AiContextItem> = new Map();
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 'createQueryString' in file src/common/utils/create_query_string.ts in project gitlab-lsp | Definition:
export const createQueryString = (query: Record<string, QueryValue>): string => {
const q = new URLSearchParams();
Object.entries(query).forEach(([name, value]) => {
if (notNullOrUndefined(value)) {
q.set(name, `${value}`);
}
});
return q.toString() && `?${q}`;
};
References:
- src/common/api.ts:382 |
You are a code assistant | Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp | Definition:
def greet2(name)
puts name
end
greet3 = Proc.new { |name| }
greet4 = Proc.new { |name| puts name }
greet5 = lambda { |name| }
greet6 = lambda { |name| puts name }
class Greet
def initialize(name)
end
def greet
end
end
class Greet2
def initialize(name)
@name = name
end
def greet
puts "Hello #{@name}"
end
end
class Greet3
end
def generate_greetings
end
def greet_generator
yield 'Hello'
end
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:4 |
You are a code assistant | Definition of 'constructor' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp | Definition:
constructor({ webviewId, connection, rpcMethods, handlers }: ExtensionConnectionMessageBusProps) {
this.#webviewId = webviewId;
this.#connection = connection;
this.#rpcMethods = rpcMethods;
this.#handlers = handlers;
}
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 'size' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp | Definition:
get size() {
return this.#basicRegistry.size;
}
register(key: TKey, handler: THandler): Disposable {
const hash = this.#hashFunc(key);
return this.#basicRegistry.register(hash, handler);
}
has(key: TKey): boolean {
const hash = this.#hashFunc(key);
return this.#basicRegistry.has(hash);
}
async handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> {
const hash = this.#hashFunc(key);
return this.#basicRegistry.handle(hash, ...args);
}
dispose() {
this.#basicRegistry.dispose();
}
}
References: |
You are a code assistant | Definition of 'setupFileWatcher' in file src/common/services/fs/dir.ts in project gitlab-lsp | Definition:
setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) {
throw new Error(`${workspaceFolder} ${changeHandler} not implemented`);
}
}
References: |
You are a code assistant | Definition of 'WebviewEventInfo' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
export type WebviewEventInfo = {
type: string;
payload?: unknown;
};
export type WebviewInstanceCreatedEventData = WebviewAddress;
export type WebviewInstanceDestroyedEventData = WebviewAddress;
export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo;
export type WebviewInstanceRequestEventData = WebviewAddress &
WebviewEventInfo &
WebviewRequestInfo;
export type SuccessfulResponse = {
success: true;
};
export type FailedResponse = {
success: false;
reason: string;
};
export type WebviewInstanceResponseEventData = WebviewAddress &
WebviewRequestInfo &
WebviewEventInfo &
(SuccessfulResponse | FailedResponse);
export type MessagesToServer = {
webview_instance_created: WebviewInstanceCreatedEventData;
webview_instance_destroyed: WebviewInstanceDestroyedEventData;
webview_instance_notification_received: WebviewInstanceNotificationEventData;
webview_instance_request_received: WebviewInstanceRequestEventData;
webview_instance_response_received: WebviewInstanceResponseEventData;
};
export type MessagesToClient = {
webview_instance_notification: WebviewInstanceNotificationEventData;
webview_instance_request: WebviewInstanceRequestEventData;
webview_instance_response: WebviewInstanceResponseEventData;
};
export interface TransportMessageHandler<T> {
(payload: T): void;
}
export interface TransportListener {
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable;
}
export interface TransportPublisher {
publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>;
}
export interface Transport extends TransportListener, TransportPublisher {}
References: |
You are a code assistant | Definition of 'run' in file scripts/watcher/watch.ts in project gitlab-lsp | Definition:
async function run() {
const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`);
const now = performance.now();
const buildSuccessful = await runBuild();
if (!buildSuccessful) return watchMsg();
await Promise.all(postBuild());
console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`);
watchMsg();
}
let timeout: NodeJS.Timeout | null = null;
const dir = './src';
const watcher = chokidar.watch(dir, {
ignored: /(^|[/\\])\../, // ignore dotfiles
persistent: true,
});
let isReady = false;
watcher
.on('add', async (filePath) => {
if (!isReady) return;
console.log(`File ${filePath} has been added`);
await run();
})
.on('change', async (filePath) => {
if (!isReady) return;
console.log(`File ${filePath} has been changed`);
if (timeout) clearTimeout(timeout);
// We debounce the run function on change events in the case of many files being changed at once
timeout = setTimeout(async () => {
await run();
}, 1000);
})
.on('ready', async () => {
await run();
isReady = true;
})
.on('unlink', (filePath) => console.log(`File ${filePath} has been removed`));
console.log(textColor, 'Starting watcher...');
References:
- scripts/watcher/watch.ts:95
- scripts/watcher/watch.ts:87
- scripts/watcher/watch.ts:99
- scripts/commit-lint/lint.js:93 |
You are a code assistant | Definition of 'notificationHandler' in file src/common/document_service.ts in project gitlab-lsp | Definition:
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:
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:60 |
You are a code assistant | Definition of 'constructor' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp | Definition:
constructor(
configService: ConfigService,
connection: LsConnection,
documentService: DocumentService,
documentTransformer: DocumentTransformerService,
supportedLanguagesService: SupportedLanguagesService,
) {
this.#configService = configService;
this.#documentTransformer = documentTransformer;
this.#supportedLanguagesService = supportedLanguagesService;
const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => {
await this.#updateAdvancedContext(document, handlerType);
});
connection.onShutdown(() => subscription.dispose());
}
/**
* Currently updates the LRU cache with the most recently accessed files in the workspace.
* We only update the advanced context for supported languages. We also ensure to run
* documents through the `DocumentTransformer` to ensure the secret redaction is applied.
*/
async #updateAdvancedContext(
document: TextDocument,
handlerType: TextDocumentChangeListenerType,
) {
const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT);
// eslint-disable-next-line default-case
switch (handlerType) {
case TextDocumentChangeListenerType.onDidClose: {
// We don't check if the language is supported for `onDidClose` because we want
// always attempt to delete the file from the cache.
const fileDeleted = lruCache.deleteFile(document.uri);
if (fileDeleted) {
log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`);
} else {
log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`);
}
break;
}
case TextDocumentChangeListenerType.onDidChangeContent:
case TextDocumentChangeListenerType.onDidSave:
case TextDocumentChangeListenerType.onDidOpen:
case TextDocumentChangeListenerType.onDidSetActive: {
const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled(
document.languageId,
);
if (!languageEnabled) {
return;
}
const context = this.#documentTransformer.getContext(
document.uri,
{ line: 0, character: 0 },
this.#configService.get().client.workspaceFolders ?? [],
undefined,
);
if (!context) {
log.debug(`Advanced Context: document context for ${document.uri} was not found`);
return;
}
lruCache.updateFile(context);
log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`);
break;
}
}
}
}
References: |
You are a code assistant | Definition of 'REQUEST_TIMEOUT_MILLISECONDS' in file src/common/constants.ts in project gitlab-lsp | Definition:
export const REQUEST_TIMEOUT_MILLISECONDS = 15000;
export const GITLAB_API_BASE_URL = 'https://gitlab.com';
export const SUGGESTION_ACCEPTED_COMMAND = 'gitlab.ls.codeSuggestionAccepted';
export const START_STREAMING_COMMAND = 'gitlab.ls.startStreaming';
export const WORKFLOW_EXECUTOR_VERSION = 'v0.0.5';
export const SUGGESTIONS_DEBOUNCE_INTERVAL_MS = 250;
export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`;
References: |
You are a code assistant | Definition of 'dispose' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
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 'loggerWithPrefix' in file src/node/http/utils/logger_with_prefix.ts in project gitlab-lsp | Definition:
export function loggerWithPrefix(logger: ILog, prefix: string): ILog {
const addPrefix = (message: string) => `${prefix} ${message}`;
return LOG_METHODS.reduce((acc, method) => {
acc[method] = (message: string | Error, e?: Error): void => {
if (typeof message === 'string') {
logger[method](addPrefix(message), e);
} else {
logger[method](message);
}
};
return acc;
}, {} as ILog);
}
References:
- src/node/http/utils/logger_with_prefix.test.ts:28
- src/node/http/create_fastify_http_server.ts:22 |
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) {}
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: |
You are a code assistant | Definition of 'DirectoryToSearch' in file src/common/services/fs/dir.ts in project gitlab-lsp | Definition:
export interface DirectoryToSearch {
/**
* The URI of the directory to search.
* Example: 'file:///path/to/directory'
*/
directoryUri: string;
/**
* The filters to apply to the search.
* They form a logical AND, meaning
* that a file must match all filters to be included in the results.
*/
filters?: {
/**
* The file name or extensions to filter by.
* MUST be Unix-style paths.
*/
fileEndsWith?: string[];
};
}
export type FileChangeHandler = (
event: 'add' | 'change' | 'unlink',
workspaceFolder: WorkspaceFolder,
filePath: string,
stats?: Stats,
) => void;
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/node/services/fs/dir.ts:36
- src/common/services/fs/dir.ts:48
- src/common/services/fs/dir.ts:34 |
You are a code assistant | Definition of 'sendDidChangeConfiguration' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
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 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp | Definition:
async processStream(
_context: IDocContext,
input: StreamingCompletionResponse,
): Promise<StreamingCompletionResponse> {
return { ...input, 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: |
You are a code assistant | Definition of 'updateCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp | Definition:
async updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}) {
try {
this.#duoProjects.clear();
const duoProjects = await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
return {
workspaceFolder,
projects: await this.#duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}),
};
}),
);
for (const { workspaceFolder, projects } of duoProjects) {
this.#logProjectsInfo(projects, workspaceFolder);
this.#duoProjects.set(workspaceFolder.uri, projects);
}
this.#triggerChange();
} catch (err) {
log.error('DuoProjectAccessCache: failed to update project access cache', err);
}
}
#logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) {
if (!projects.length) {
log.warn(
`DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`,
);
return;
}
log.debug(
`DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`,
);
}
async #duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}: {
workspaceFolder: WorkspaceFolder;
baseUrl: string;
}): Promise<DuoProject[]> {
const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl);
const projects = await Promise.all(
remotes.map(async (remote) => {
const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath);
return {
projectPath: remote.projectPath,
uri: remote.fileUri,
enabled,
host: remote.host,
namespace: remote.namespace,
namespaceWithPath: remote.namespaceWithPath,
} satisfies DuoProject;
}),
);
return projects;
}
async #gitlabRemotesForWorkspaceFolder(
workspaceFolder: WorkspaceFolder,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const paths = await this.directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
filters: {
fileEndsWith: ['/.git/config'],
},
});
const remotes = await Promise.all(
paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)),
);
return remotes.flat();
}
async #gitlabRemotesForFileUri(
fileUri: string,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri);
return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => {
const remote = parseGitLabRemote(remoteUrl, baseUrl);
if (remote) {
acc.push({ ...remote, fileUri });
}
return acc;
}, []);
}
async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> {
try {
const fileString = await this.fileResolver.readFile({ fileUri });
const config = ini.parse(fileString);
return this.#getRemoteUrls(config);
} catch (error) {
log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error);
return [];
}
}
#getRemoteUrls(config: GitConfig): string[] {
return Object.keys(config).reduce<string[]>((acc, section) => {
if (section.startsWith('remote ')) {
acc.push(config[section].url);
}
return acc;
}, []);
}
async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> {
try {
const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({
type: 'graphql',
query: duoFeaturesEnabledQuery,
variables: {
projectPath,
},
} satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>);
return Boolean(response?.project?.duoFeaturesEnabled);
} catch (error) {
log.error(
`DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`,
error,
);
return true;
}
}
onDuoProjectCacheUpdate(
listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void,
): Disposable {
this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener);
return {
dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener),
};
}
#triggerChange() {
this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects);
}
}
References: |
You are a code assistant | Definition of 'isLanguageEnabled' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp | Definition:
isLanguageEnabled(languageId: string): boolean;
isLanguageSupported(languageId: string): boolean;
onLanguageChange(listener: () => void): Disposable;
}
export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>(
'SupportedLanguagesService',
);
@Injectable(SupportedLanguagesService, [ConfigService])
export class DefaultSupportedLanguagesService implements SupportedLanguagesService {
#enabledLanguages: Set<string>;
#supportedLanguages: Set<string>;
#configService: ConfigService;
#eventEmitter = new EventEmitter();
constructor(configService: ConfigService) {
this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#configService = configService;
this.#configService.onConfigChange(() => this.#update());
}
#getConfiguredLanguages() {
const languages: SupportedLanguagesUpdateParam = {};
const additionalLanguages = this.#configService.get(
'client.codeCompletion.additionalLanguages',
);
if (Array.isArray(additionalLanguages)) {
languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier);
} else {
log.warn(
'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.',
);
}
const disabledSupportedLanguages = this.#configService.get(
'client.codeCompletion.disabledSupportedLanguages',
);
if (Array.isArray(disabledSupportedLanguages)) {
languages.deny = disabledSupportedLanguages;
} else {
log.warn(
'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.',
);
}
return languages;
}
#update() {
const { allow = [], deny = [] } = this.#getConfiguredLanguages();
const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
for (const language of allow) {
newSet.add(language.trim());
}
for (const language of deny) {
newSet.delete(language);
}
if (newSet.size === 0) {
log.warn('All languages have been disabled for Code Suggestions.');
}
const previousEnabledLanguages = this.#enabledLanguages;
this.#enabledLanguages = newSet;
if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) {
this.#triggerChange();
}
}
isLanguageSupported(languageId: string) {
return this.#supportedLanguages.has(languageId);
}
isLanguageEnabled(languageId: string) {
return this.#enabledLanguages.has(languageId);
}
onLanguageChange(listener: () => void): Disposable {
this.#eventEmitter.on('languageChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('languageChange');
}
#normalizeLanguageIdentifier(language: string) {
return language.trim().toLowerCase().replace(/^\./, '');
}
}
References: |
You are a code assistant | Definition of 'CodeSuggestionResponse' in file src/common/api.ts in project gitlab-lsp | Definition:
export interface CodeSuggestionResponse {
choices?: SuggestionOption[];
model?: ICodeSuggestionModel;
status: number;
error?: string;
isDirectConnection?: boolean;
}
// FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption
export interface StartStreamOption {
uniqueTrackingId: string;
/** the streamId represents the beginning of a stream * */
streamId: string;
}
export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption;
export interface PersonalAccessToken {
name: string;
scopes: string[];
active: boolean;
}
export interface OAuthToken {
scope: string[];
}
export interface TokenCheckResponse {
valid: boolean;
reason?: 'unknown' | 'not_active' | 'invalid_scopes';
message?: string;
}
export interface IDirectConnectionDetailsHeaders {
'X-Gitlab-Global-User-Id': string;
'X-Gitlab-Instance-Id': string;
'X-Gitlab-Host-Name': string;
'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string;
}
export interface IDirectConnectionModelDetails {
model_provider: string;
model_name: string;
}
export interface IDirectConnectionDetails {
base_url: string;
token: string;
expires_at: number;
headers: IDirectConnectionDetailsHeaders;
model_details: IDirectConnectionModelDetails;
}
const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured';
@Injectable(GitLabApiClient, [LsFetch, ConfigService])
export class GitLabAPI implements GitLabApiClient {
#token: string | undefined;
#baseURL: string;
#clientInfo?: IClientInfo;
#lsFetch: LsFetch;
#eventEmitter = new EventEmitter();
#configService: ConfigService;
#instanceVersion?: string;
constructor(lsFetch: LsFetch, configService: ConfigService) {
this.#baseURL = GITLAB_API_BASE_URL;
this.#lsFetch = lsFetch;
this.#configService = configService;
this.#configService.onConfigChange(async (config) => {
this.#clientInfo = configService.get('client.clientInfo');
this.#lsFetch.updateAgentOptions({
ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false,
...(this.#configService.get('client.httpAgentOptions') ?? {}),
});
await this.configureApi(config.client);
});
}
onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable {
this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener);
return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) };
}
#fireApiReconfigured(isInValidState: boolean, validationMessage?: string) {
const data: ApiReconfiguredData = { isInValidState, validationMessage };
this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data);
}
async configureApi({
token,
baseUrl = GITLAB_API_BASE_URL,
}: {
token?: string;
baseUrl?: string;
}) {
if (this.#token === token && this.#baseURL === baseUrl) return;
this.#token = token;
this.#baseURL = baseUrl;
const { valid, reason, message } = await this.checkToken(this.#token);
let validationMessage;
if (!valid) {
this.#configService.set('client.token', undefined);
validationMessage = `Token is invalid. ${message}. Reason: ${reason}`;
log.warn(validationMessage);
} else {
log.info('Token is valid');
}
this.#instanceVersion = await this.#getGitLabInstanceVersion();
this.#fireApiReconfigured(valid, validationMessage);
}
#looksLikePatToken(token: string): boolean {
// OAuth tokens will be longer than 42 characters and PATs will be shorter.
return token.length < 42;
}
async #checkPatToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(
`${this.#baseURL}/api/v4/personal_access_tokens/self`,
{ headers },
);
await handleFetchError(response, 'Information about personal access token');
const { active, scopes } = (await response.json()) as PersonalAccessToken;
if (!active) {
return {
valid: false,
reason: 'not_active',
message: 'Token is not active.',
};
}
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async #checkOAuthToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, {
headers,
});
await handleFetchError(response, 'Information about OAuth token');
const { scope: scopes } = (await response.json()) as OAuthToken;
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async checkToken(token: string = ''): Promise<TokenCheckResponse> {
try {
if (this.#looksLikePatToken(token)) {
log.info('Checking token for PAT validity');
return await this.#checkPatToken(token);
}
log.info('Checking token for OAuth validity');
return await this.#checkOAuthToken(token);
} catch (err) {
log.error('Error performing token check', err);
return {
valid: false,
reason: 'unknown',
message: `Failed to check token: ${err}`,
};
}
}
#hasValidScopes(scopes: string[]): boolean {
return scopes.includes('api');
}
async getCodeSuggestions(
request: CodeSuggestionRequest,
): Promise<CodeSuggestionResponse | undefined> {
if (!this.#token) {
throw new Error('Token needs to be provided to request Code Suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
const response = await this.#lsFetch.post(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
{ headers, body: JSON.stringify(request) },
);
await handleFetchError(response, 'Code Suggestions');
const data = await response.json();
return { ...data, status: response.status };
}
async *getStreamingCodeSuggestions(
request: CodeSuggestionRequest,
): AsyncGenerator<string, void, void> {
if (!this.#token) {
throw new Error('Token needs to be provided to stream code suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
yield* this.#lsFetch.streamFetch(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
JSON.stringify(request),
headers,
);
}
async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> {
if (!this.#token) {
return Promise.reject(new Error('Token needs to be provided to authorise API request.'));
}
if (
request.supportedSinceInstanceVersion &&
!this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version)
) {
return Promise.reject(
new InvalidInstanceVersionError(
`Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`,
),
);
}
if (request.type === 'graphql') {
return this.#graphqlRequest(request.query, request.variables);
}
switch (request.method) {
case 'GET':
return this.#fetch(request.path, request.searchParams, 'resource', request.headers);
case 'POST':
return this.#postFetch(request.path, 'resource', request.body, request.headers);
default:
// the type assertion is necessary because TS doesn't expect any other types
throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`);
}
}
async connectToCable(): Promise<ActionCableCable> {
const headers = this.#getDefaultHeaders(this.#token);
const websocketOptions = {
headers: {
...headers,
Origin: this.#baseURL,
},
};
return connectToCable(this.#baseURL, websocketOptions);
}
async #graphqlRequest<T = unknown, V extends Variables = Variables>(
document: RequestDocument,
variables?: V,
): Promise<T> {
const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/');
const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab"
const graphqlFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = input instanceof URL ? input.toString() : input;
return this.#lsFetch.post(url, {
...init,
headers: { ...headers, ...init?.headers },
});
};
const headers = this.#getDefaultHeaders(this.#token);
const client = new GraphQLClient(endpoint, {
headers,
fetch: graphqlFetch,
});
return client.request(document, variables);
}
async #fetch<T>(
apiResourcePath: string,
query: Record<string, QueryValue> = {},
resourceName = 'resource',
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`;
const result = await this.#lsFetch.get(url, {
headers: { ...this.#getDefaultHeaders(this.#token), ...headers },
});
await handleFetchError(result, resourceName);
return result.json() as Promise<T>;
}
async #postFetch<T>(
apiResourcePath: string,
resourceName = 'resource',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}`;
const response = await this.#lsFetch.post(url, {
headers: {
'Content-Type': 'application/json',
...this.#getDefaultHeaders(this.#token),
...headers,
},
body: JSON.stringify(body),
});
await handleFetchError(response, resourceName);
return response.json() as Promise<T>;
}
#getDefaultHeaders(token?: string) {
return {
Authorization: `Bearer ${token}`,
'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`,
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
};
}
#instanceVersionHigherOrEqualThen(version: string): boolean {
if (!this.#instanceVersion) return false;
return semverCompare(this.#instanceVersion, version) >= 0;
}
async #getGitLabInstanceVersion(): Promise<string> {
if (!this.#token) {
return '';
}
const headers = this.#getDefaultHeaders(this.#token);
const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, {
headers,
});
const { version } = await response.json();
return version;
}
get instanceVersion() {
return this.#instanceVersion;
}
}
References:
- src/common/test_utils/mocks.ts:19 |
You are a code assistant | Definition of 'DO_NOT_SHOW_VERSION_WARNING' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp | Definition:
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 'CircuitBreakerState' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
export enum CircuitBreakerState {
OPEN = 'Open',
CLOSED = 'Closed',
}
export interface CircuitBreaker {
error(): void;
success(): void;
isOpen(): boolean;
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References:
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:20
- src/common/circuit_breaker/fixed_time_circuit_breaker.ts:14 |
You are a code assistant | Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp | Definition:
fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>;
connectToCable(): Promise<Cable>;
}
References:
- packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11
- packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10 |
You are a code assistant | Definition of 'handleWebviewMessage' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp | Definition:
export const handleWebviewMessage = (
messageEmitter: WebviewTransportEventEmitter,
logger?: Logger,
) =>
withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => {
messageEmitter.emit('webview_instance_notification_received', message);
});
export type JsonRpcConnectionTransportProps = {
connection: Connection;
logger: Logger;
notificationRpcMethod?: string;
webviewCreatedRpcMethod?: string;
webviewDestroyedRpcMethod?: string;
};
export class JsonRpcConnectionTransport implements Transport {
#messageEmitter = createWebviewTransportEventEmitter();
#connection: Connection;
#notificationChannel: string;
#webviewCreatedChannel: string;
#webviewDestroyedChannel: string;
#logger?: Logger;
#disposables: Disposable[] = [];
constructor({
connection,
logger,
notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD,
webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD,
webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD,
}: JsonRpcConnectionTransportProps) {
this.#connection = connection;
this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined;
this.#notificationChannel = notificationChannel;
this.#webviewCreatedChannel = webviewCreatedChannel;
this.#webviewDestroyedChannel = webviewDestroyedChannel;
this.#subscribeToConnection();
}
#subscribeToConnection() {
const channelToNotificationHandlerMap = {
[this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger),
[this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger),
[this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger),
};
Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => {
const disposable = this.#connection.onNotification(channel, handler);
this.#disposables.push(disposable);
});
}
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable {
this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]);
return {
dispose: () =>
this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]),
};
}
publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void> {
if (type === 'webview_instance_notification') {
return this.#connection.sendNotification(this.#notificationChannel, payload);
}
throw new Error(`Unknown message type: ${type}`);
}
dispose(): void {
this.#messageEmitter.removeAllListeners();
this.#disposables.forEach((disposable) => disposable.dispose());
this.#logger?.debug('JsonRpcConnectionTransport disposed');
}
}
References:
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:93 |
You are a code assistant | Definition of 'removeFile' in file src/common/git/repository.ts in project gitlab-lsp | Definition:
removeFile(fileUri: string): void {
this.#files.delete(fileUri);
}
getFiles(): Map<string, RepositoryFile> {
return this.#files;
}
dispose(): void {
this.#ignoreManager.dispose();
this.#files.clear();
}
}
References: |
You are a code assistant | Definition of 'DefaultSupportedLanguagesService' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp | Definition:
export class DefaultSupportedLanguagesService implements SupportedLanguagesService {
#enabledLanguages: Set<string>;
#supportedLanguages: Set<string>;
#configService: ConfigService;
#eventEmitter = new EventEmitter();
constructor(configService: ConfigService) {
this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#configService = configService;
this.#configService.onConfigChange(() => this.#update());
}
#getConfiguredLanguages() {
const languages: SupportedLanguagesUpdateParam = {};
const additionalLanguages = this.#configService.get(
'client.codeCompletion.additionalLanguages',
);
if (Array.isArray(additionalLanguages)) {
languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier);
} else {
log.warn(
'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.',
);
}
const disabledSupportedLanguages = this.#configService.get(
'client.codeCompletion.disabledSupportedLanguages',
);
if (Array.isArray(disabledSupportedLanguages)) {
languages.deny = disabledSupportedLanguages;
} else {
log.warn(
'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.',
);
}
return languages;
}
#update() {
const { allow = [], deny = [] } = this.#getConfiguredLanguages();
const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
for (const language of allow) {
newSet.add(language.trim());
}
for (const language of deny) {
newSet.delete(language);
}
if (newSet.size === 0) {
log.warn('All languages have been disabled for Code Suggestions.');
}
const previousEnabledLanguages = this.#enabledLanguages;
this.#enabledLanguages = newSet;
if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) {
this.#triggerChange();
}
}
isLanguageSupported(languageId: string) {
return this.#supportedLanguages.has(languageId);
}
isLanguageEnabled(languageId: string) {
return this.#enabledLanguages.has(languageId);
}
onLanguageChange(listener: () => void): Disposable {
this.#eventEmitter.on('languageChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('languageChange');
}
#normalizeLanguageIdentifier(language: string) {
return language.trim().toLowerCase().replace(/^\./, '');
}
}
References:
- src/common/feature_state/supported_language_check.test.ts:32
- src/common/suggestion/supported_languages_service.test.ts:9
- src/common/suggestion/supported_languages_service.test.ts:13 |
You are a code assistant | Definition of 'dispose' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp | Definition:
dispose(): void {
this.#compositeDisposable.dispose();
this.#instanceInfos.forEach((info) => info.messageBus.dispose());
this.#instanceInfos.clear();
}
#subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) {
const eventFilter = buildWebviewIdFilter(this.webviewId);
this.#compositeDisposable.add(
runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter),
runtimeMessageBus.subscribe(
'webview:disconnect',
this.#handleDisconnected.bind(this),
eventFilter,
),
);
}
#handleConnected(address: WebviewAddress) {
this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`);
if (this.#instanceInfos.has(address.webviewInstanceId)) {
// we are already connected with this webview instance
return;
}
const messageBus = this.#messageBusFactory(address);
const pluginCallbackDisposables = new CompositeDisposable();
this.#instanceInfos.set(address.webviewInstanceId, {
messageBus,
pluginCallbackDisposables,
});
this.#handlers.forEach((handler) => {
const disposable = handler(address.webviewInstanceId, messageBus);
if (isDisposable(disposable)) {
pluginCallbackDisposables.add(disposable);
}
});
}
#handleDisconnected(address: WebviewAddress) {
this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`);
const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId);
if (!instanceInfo) {
// we aren't tracking this instance
return;
}
instanceInfo.pluginCallbackDisposables.dispose();
instanceInfo.messageBus.dispose();
this.#instanceInfos.delete(address.webviewInstanceId);
}
}
References: |
You are a code assistant | Definition of 'RepositoryService' in file src/common/git/repository_service.ts in project gitlab-lsp | Definition:
export type RepositoryService = typeof DefaultRepositoryService.prototype;
export const RepositoryService = createInterfaceId<RepositoryService>('RepositoryService');
@Injectable(RepositoryService, [VirtualFileSystemService])
export class DefaultRepositoryService {
#virtualFileSystemService: DefaultVirtualFileSystemService;
constructor(virtualFileSystemService: DefaultVirtualFileSystemService) {
this.#virtualFileSystemService = virtualFileSystemService;
this.#setupEventListeners();
}
#setupEventListeners() {
return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => {
switch (eventType) {
case VirtualFileSystemEvents.WorkspaceFilesUpdate:
await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate);
break;
case VirtualFileSystemEvents.WorkspaceFileUpdate:
await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate);
break;
default:
break;
}
});
}
async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) {
log.info(`Workspace files update: ${update.files.length}`);
const perf1 = performance.now();
await this.handleWorkspaceFilesUpdate({
...update,
});
const perf2 = performance.now();
log.info(`Workspace files initialization took ${perf2 - perf1}ms`);
const perf3 = performance.now();
const files = this.getFilesForWorkspace(update.workspaceFolder.uri, {
excludeGitFolder: true,
excludeIgnored: true,
});
const perf4 = performance.now();
log.info(`Fetched workspace files in ${perf4 - perf3}ms`);
log.info(`Workspace git files: ${files.length}`);
// const treeFile = await readFile(
// '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt',
// 'utf-8',
// );
// const treeFiles = treeFile.split('\n').filter(Boolean);
// // get the set difference between the files in the tree and the non-ignored files
// // we need the difference between the two sets to know which files are not in the tree
// const diff = new Set(
// files.map((file) =>
// relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath),
// ),
// );
// for (const file of treeFiles) {
// diff.delete(file);
// }
// log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`);
}
async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) {
log.info(`Workspace file update: ${JSON.stringify(update)}`);
await this.handleWorkspaceFileUpdate({
...update,
});
const perf1 = performance.now();
const files = this.getFilesForWorkspace(update.workspaceFolder.uri, {
excludeGitFolder: true,
excludeIgnored: true,
});
const perf2 = performance.now();
log.info(`Fetched workspace files in ${perf2 - perf1}ms`);
log.info(`Workspace git files: ${files.length}`);
}
/**
* unique map of workspace folders that point to a map of repositories
* We store separate repository maps for each workspace because
* the events from the VFS service are at the workspace level.
* If we combined them, we may get race conditions
*/
#workspaces: Map<WorkspaceFolderUri, RepositoryMap> = new Map();
#workspaceRepositoryTries: Map<WorkspaceFolderUri, RepositoryTrie> = new Map();
#buildRepositoryTrie(repositories: Repository[]): RepositoryTrie {
const root = new RepositoryTrie();
for (const repo of repositories) {
let node = root;
const parts = repo.uri.path.split('/').filter(Boolean);
for (const part of parts) {
if (!node.children.has(part)) {
node.children.set(part, new RepositoryTrie());
}
node = node.children.get(part) as RepositoryTrie;
}
node.repository = repo.uri;
}
return root;
}
findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null {
const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri);
if (!trie) return null;
let node = trie;
let lastMatchingRepo: URI | null = null;
const parts = fileUri.path.split('/').filter(Boolean);
for (const part of parts) {
if (node.repository) {
lastMatchingRepo = node.repository;
}
if (!node.children.has(part)) break;
node = node.children.get(part) as RepositoryTrie;
}
return node.repository || lastMatchingRepo;
}
getRepositoryFileForUri(
fileUri: URI,
repositoryUri: URI,
workspaceFolder: WorkspaceFolder,
): RepositoryFile | null {
const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get(
repositoryUri.toString(),
);
if (!repository) {
return null;
}
return repository.getFile(fileUri.toString()) ?? null;
}
#updateRepositoriesForFolder(
workspaceFolder: WorkspaceFolder,
repositoryMap: RepositoryMap,
repositoryTrie: RepositoryTrie,
) {
this.#workspaces.set(workspaceFolder.uri, repositoryMap);
this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie);
}
async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) {
// clear existing repositories from workspace
this.#emptyRepositoriesForWorkspace(workspaceFolder.uri);
const repositories = this.#detectRepositories(files, workspaceFolder);
const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo]));
// Build and cache the repository trie for this workspace
const trie = this.#buildRepositoryTrie(repositories);
this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie);
await Promise.all(
repositories.map((repo) =>
repo.addFilesAndLoadGitIgnore(
files.filter((file) => {
const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder);
return matchingRepo && matchingRepo.toString() === repo.uri.toString();
}),
),
),
);
}
async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) {
const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder);
if (!repoUri) {
log.debug(`No matching repository found for file ${fileUri.toString()}`);
return;
}
const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri);
const repository = repositoryMap.get(repoUri.toString());
if (!repository) {
log.debug(`Repository not found for URI ${repoUri.toString()}`);
return;
}
if (repository.isFileIgnored(fileUri)) {
log.debug(`File ${fileUri.toString()} is ignored`);
return;
}
switch (event) {
case 'add':
repository.setFile(fileUri);
log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`);
break;
case 'change':
repository.setFile(fileUri);
log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`);
break;
case 'unlink':
repository.removeFile(fileUri.toString());
log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`);
break;
default:
log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`);
}
}
#getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap {
return this.#workspaces.get(workspaceFolderUri) || new Map();
}
#emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void {
log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`);
const repos = this.#workspaces.get(workspaceFolderUri);
if (!repos || repos.size === 0) return;
// clear up ignore manager trie from memory
repos.forEach((repo) => {
repo.dispose();
log.debug(`Repository ${repo.uri} has been disposed`);
});
repos.clear();
const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri);
if (trie) {
trie.dispose();
this.#workspaceRepositoryTries.delete(workspaceFolderUri);
}
this.#workspaces.delete(workspaceFolderUri);
log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`);
}
#detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] {
const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config'));
return gitConfigFiles.map((file) => {
const projectUri = fsPathToUri(file.path.replace('.git/config', ''));
const ignoreManager = new IgnoreManager(projectUri.fsPath);
log.info(`Detected repository at ${projectUri.path}`);
return new Repository({
ignoreManager,
uri: projectUri,
configFileUri: file,
workspaceFolder,
});
});
}
getFilesForWorkspace(
workspaceFolderUri: WorkspaceFolderUri,
options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {},
): RepositoryFile[] {
const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri);
const allFiles: RepositoryFile[] = [];
repositories.forEach((repository) => {
repository.getFiles().forEach((file) => {
// apply the filters
if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) {
return;
}
if (options.excludeIgnored && file.isIgnored) {
return;
}
allFiles.push(file);
});
});
return allFiles;
}
// Helper method to check if a file is in the .git folder
#isInGitFolder(fileUri: URI, repositoryUri: URI): boolean {
const relativePath = fileUri.path.slice(repositoryUri.path.length);
return relativePath.split('/').some((part) => part === '.git');
}
}
References: |
You are a code assistant | Definition of 'GraphQLRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
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 'ProcessorType' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp | Definition:
type ProcessorType = 'stream' | 'completion';
type ProcessorInputMap = {
stream: StreamingCompletionResponse;
completion: SuggestionOption[];
};
/**
* PostProcessor is an interface for classes that can be used to modify completion responses
* before they are sent to the client.
* They are run in order according to the order they are added to the PostProcessorPipeline.
* Post-processors can be used to filter, sort, or modify completion and streaming suggestions.
* Be sure to handle both streaming and completion responses in your implementation (if applicable).
* */
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: |
You are a code assistant | Definition of 'SetupWebviewRuntimeProps' in file packages/lib_webview/src/setup/setup_webview_runtime.ts in project gitlab-lsp | Definition:
export type SetupWebviewRuntimeProps = {
extensionMessageBusProvider: ExtensionMessageBusProvider;
transports: Transport[];
plugins: WebviewPlugin[];
logger: Logger;
};
export function setupWebviewRuntime(props: SetupWebviewRuntimeProps): Disposable {
const logger = withPrefix(props.logger, '[Webview]');
logger.debug('Setting up webview runtime');
try {
const runtimeMessageBus = new WebviewRuntimeMessageBus();
const transportDisposable = setupTransports(props.transports, runtimeMessageBus, logger);
const webviewPluginDisposable = setupWebviewPlugins({
runtimeMessageBus,
logger,
plugins: props.plugins,
extensionMessageBusProvider: props.extensionMessageBusProvider,
});
logger.info('Webview runtime setup completed successfully');
return {
dispose: () => {
logger.debug('Disposing webview runtime');
transportDisposable.dispose();
webviewPluginDisposable.dispose();
logger.info('Webview runtime disposed');
},
};
} catch (error) {
props.logger.error(
'Failed to setup webview runtime',
error instanceof Error ? error : undefined,
);
return {
dispose: () => {
logger.debug('Disposing empty webview runtime due to setup failure');
},
};
}
}
References:
- packages/lib_webview/src/setup/setup_webview_runtime.ts:17 |
You are a code assistant | Definition of 'defaultSlashCommands' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts in project gitlab-lsp | Definition:
export const defaultSlashCommands: GitlabChatSlashCommand[] = [
ResetCommand,
CleanCommand,
TestsCommand,
RefactorCommand,
ExplainCommand,
];
References: |
You are a code assistant | Definition of 'onConfigChange' in file src/common/config_service.ts in project gitlab-lsp | Definition:
onConfigChange(listener: (config: IConfig) => void): Disposable {
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 'transformHeadersToSnowplowOptions' in file src/common/utils/headers_to_snowplow_options.ts in project gitlab-lsp | Definition:
export const transformHeadersToSnowplowOptions = (
headers?: IDirectConnectionDetailsHeaders,
): ISnowplowTrackerOptions => {
let gitlabSaasDuoProNamespaceIds: number[] | undefined;
try {
gitlabSaasDuoProNamespaceIds = get(headers, 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids')
?.split(',')
.map((id) => parseInt(id, 10));
} catch (err) {
log.debug('Failed to transform "X-Gitlab-Saas-Duo-Pro-Namespace-Ids" to telemetry options.');
}
return {
gitlab_instance_id: get(headers, 'X-Gitlab-Instance-Id'),
gitlab_global_user_id: get(headers, 'X-Gitlab-Global-User-Id'),
gitlab_host_name: get(headers, 'X-Gitlab-Host-Name'),
gitlab_saas_duo_pro_namespace_ids: gitlabSaasDuoProNamespaceIds,
};
};
References:
- src/common/utils/headers_to_snowplow_options.test.ts:16
- src/common/suggestion_client/direct_connection_client.ts:94 |
You are a code assistant | Definition of 'AiContextRetriever' in file src/common/ai_context_management_2/retrievers/ai_context_retriever.ts in project gitlab-lsp | Definition:
export interface AiContextRetriever {
retrieve(item: AiContextItem): Promise<string | null>;
}
References: |
You are a code assistant | Definition of 'START_STREAMING_COMMAND' in file src/common/constants.ts in project gitlab-lsp | Definition:
export const START_STREAMING_COMMAND = 'gitlab.ls.startStreaming';
export const WORKFLOW_EXECUTOR_VERSION = 'v0.0.5';
export const SUGGESTIONS_DEBOUNCE_INTERVAL_MS = 250;
export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`;
References: |
You are a code assistant | Definition of 'AiContextProviderItem' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp | Definition:
export type AiContextProviderItem =
| {
providerType: 'file';
subType: 'open_tab' | 'local_file_search';
fileUri: URI;
workspaceFolder: WorkspaceFolder;
repositoryFile: RepositoryFile | null;
}
| {
providerType: 'other';
};
export interface AiContextProvider {
getProviderItems(
query: string,
workspaceFolder: WorkspaceFolder[],
): Promise<AiContextProviderItem[]>;
}
References:
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:111
- src/common/ai_context_management_2/ai_context_aggregator.ts:54
- src/common/ai_context_management_2/ai_policy_management.ts:28
- src/common/ai_context_management_2/policies/ai_context_policy.ts:4
- src/common/ai_context_management_2/policies/duo_project_policy.ts:15
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:100 |
You are a code assistant | Definition of 'Greet2' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp | Definition:
class Greet2
def initialize(name)
@name = name
end
def greet
puts "Hello #{@name}"
end
end
class Greet3
end
def generate_greetings
end
def greet_generator
yield 'Hello'
end
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:24 |
You are a code assistant | Definition of 'SnowplowOptions' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp | Definition:
export type SnowplowOptions = {
appId: string;
endpoint: string;
timeInterval: number;
maxItems: number;
enabled: EnabledCallback;
};
/**
* Adds the 'stm' parameter with the current time to the payload
* Stringify all payload values
* @param payload - The payload which will be mutated
*/
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:69
- src/common/tracking/snowplow/snowplow.ts:57
- src/common/tracking/snowplow/snowplow.ts:50 |
You are a code assistant | Definition of 'getForAllAccounts' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
getForAllAccounts(): Promise<GitLabPlatformForAccount[]>;
/**
* Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined.
*/
getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>;
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/document_service.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
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:
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1 |
You are a code assistant | Definition of 'info' in file packages/lib_logging/src/types.ts in project gitlab-lsp | Definition:
info(message: string, e?: Error): void;
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
References: |
You are a code assistant | Definition of 'CircuitBreaker' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
export interface CircuitBreaker {
error(): void;
success(): void;
isOpen(): boolean;
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References:
- src/common/suggestion/streaming_handler.test.ts:31
- src/common/suggestion/streaming_handler.ts:37 |
You are a code assistant | Definition of 'AImpl2' in file packages/lib_di/src/index.test.ts in project gitlab-lsp | Definition:
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl2)).toThrow(
/Classes \[AImpl2] are not decorated with @Injectable/,
);
});
it('detects circular dependencies', () => {
@Injectable(A, [C])
class ACircular implements A {
a = () => 'hello';
constructor(c: C) {
// eslint-disable-next-line no-unused-expressions
c;
}
}
expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow(
/Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./,
);
});
// this test ensures that we don't store any references to the classes and we instantiate them only once
it('does not instantiate classes from previous instantiate call', () => {
let globCount = 0;
@Injectable(A, [])
class Counter implements A {
counter = globCount;
constructor() {
globCount++;
}
a = () => this.counter.toString();
}
container.instantiate(Counter);
container.instantiate(BImpl);
expect(container.get(A).a()).toBe('0');
});
});
describe('get', () => {
it('returns an instance of the interfaceId', () => {
container.instantiate(AImpl);
expect(container.get(A)).toBeInstanceOf(AImpl);
});
it('throws an error for missing dependency', () => {
container.instantiate();
expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/);
});
});
});
References: |
You are a code assistant | Definition of 'isAllowed' in file src/common/ai_context_management_2/policies/ai_context_policy.ts in project gitlab-lsp | Definition:
isAllowed(aiProviderItem: AiContextProviderItem): Promise<{
allowed: boolean;
reason?: string;
}>;
}
References: |
You are a code assistant | Definition of 'SupportedLanguagesUpdateParam' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp | Definition:
export interface SupportedLanguagesUpdateParam {
allow?: string[];
deny?: string[];
}
export interface SupportedLanguagesService {
isLanguageEnabled(languageId: string): boolean;
isLanguageSupported(languageId: string): boolean;
onLanguageChange(listener: () => void): Disposable;
}
export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>(
'SupportedLanguagesService',
);
@Injectable(SupportedLanguagesService, [ConfigService])
export class DefaultSupportedLanguagesService implements SupportedLanguagesService {
#enabledLanguages: Set<string>;
#supportedLanguages: Set<string>;
#configService: ConfigService;
#eventEmitter = new EventEmitter();
constructor(configService: ConfigService) {
this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#configService = configService;
this.#configService.onConfigChange(() => this.#update());
}
#getConfiguredLanguages() {
const languages: SupportedLanguagesUpdateParam = {};
const additionalLanguages = this.#configService.get(
'client.codeCompletion.additionalLanguages',
);
if (Array.isArray(additionalLanguages)) {
languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier);
} else {
log.warn(
'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.',
);
}
const disabledSupportedLanguages = this.#configService.get(
'client.codeCompletion.disabledSupportedLanguages',
);
if (Array.isArray(disabledSupportedLanguages)) {
languages.deny = disabledSupportedLanguages;
} else {
log.warn(
'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.',
);
}
return languages;
}
#update() {
const { allow = [], deny = [] } = this.#getConfiguredLanguages();
const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
for (const language of allow) {
newSet.add(language.trim());
}
for (const language of deny) {
newSet.delete(language);
}
if (newSet.size === 0) {
log.warn('All languages have been disabled for Code Suggestions.');
}
const previousEnabledLanguages = this.#enabledLanguages;
this.#enabledLanguages = newSet;
if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) {
this.#triggerChange();
}
}
isLanguageSupported(languageId: string) {
return this.#supportedLanguages.has(languageId);
}
isLanguageEnabled(languageId: string) {
return this.#enabledLanguages.has(languageId);
}
onLanguageChange(listener: () => void): Disposable {
this.#eventEmitter.on('languageChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('languageChange');
}
#normalizeLanguageIdentifier(language: string) {
return language.trim().toLowerCase().replace(/^\./, '');
}
}
References:
- src/common/suggestion/supported_languages_service.ts:46 |
You are a code assistant | Definition of 'WebviewUriProviderRegistry' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
export interface WebviewUriProviderRegistry {
register(provider: WebviewUriProvider): void;
}
export class WebviewLocationService implements WebviewUriProviderRegistry {
#uriProviders = new Set<WebviewUriProvider>();
register(provider: WebviewUriProvider) {
this.#uriProviders.add(provider);
}
resolveUris(webviewId: WebviewId): Uri[] {
const uris: Uri[] = [];
for (const provider of this.#uriProviders) {
uris.push(provider.getUri(webviewId));
}
return uris;
}
}
References:
- src/node/setup_http.ts:11 |
You are a code assistant | Definition of 'ApiRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
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 'isEnabled' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
isEnabled(): boolean {
return Boolean(this.#enabledTrackers.length);
}
setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context));
}
updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) =>
t.updateCodeSuggestionsContext(uniqueTrackingId, contextUpdate),
);
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS) {
this.#enabledTrackers.forEach((t) => t.updateSuggestionState(uniqueTrackingId, newState));
}
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References: |
You are a code assistant | Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp | Definition:
constructor(a: A) {
this.#a = a;
}
b = () => `B(${this.#a.a()})`;
}
@Injectable(C, [A, B])
class CImpl implements C {
#a: A;
#b: B;
constructor(a: A, b: B) {
this.#a = a;
this.#b = b;
}
c = () => `C(${this.#b.b()}, ${this.#a.a()})`;
}
let container: Container;
beforeEach(() => {
container = new Container();
});
describe('addInstances', () => {
const O = createInterfaceId<object>('object');
it('fails if the instance is not branded', () => {
expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow(
/invoked without branded object/,
);
});
it('fails if the instance is already present', () => {
const a = brandInstance(O, { a: 'a' });
const b = brandInstance(O, { b: 'b' });
expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/);
});
it('adds instance', () => {
const instance = { a: 'a' };
const a = brandInstance(O, instance);
container.addInstances(a);
expect(container.get(O)).toBe(instance);
});
});
describe('instantiate', () => {
it('can instantiate three classes A,B,C', () => {
container.instantiate(AImpl, BImpl, CImpl);
const cInstance = container.get(C);
expect(cInstance.c()).toBe('C(B(a), a)');
});
it('instantiates dependencies in multiple instantiate calls', () => {
container.instantiate(AImpl);
// the order is important for this test
// we want to make sure that the stack in circular dependency discovery is being cleared
// to try why this order is necessary, remove the `inStack.delete()` from
// the `if (!cwd && instanceIds.includes(id))` condition in prod code
expect(() => container.instantiate(CImpl, BImpl)).not.toThrow();
});
it('detects duplicate ids', () => {
@Injectable(A, [])
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl, AImpl2)).toThrow(
/The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/,
);
});
it('detects duplicate id with pre-existing instance', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/);
});
it('detects missing dependencies', () => {
expect(() => container.instantiate(BImpl)).toThrow(
/Class BImpl \(interface B\) depends on interfaces \[A]/,
);
});
it('it uses existing instances as dependencies', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
container.instantiate(BImpl);
expect(container.get(B).b()).toBe('B(a)');
});
it("detects classes what aren't decorated with @Injectable", () => {
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl2)).toThrow(
/Classes \[AImpl2] are not decorated with @Injectable/,
);
});
it('detects circular dependencies', () => {
@Injectable(A, [C])
class ACircular implements A {
a = () => 'hello';
constructor(c: C) {
// eslint-disable-next-line no-unused-expressions
c;
}
}
expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow(
/Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./,
);
});
// this test ensures that we don't store any references to the classes and we instantiate them only once
it('does not instantiate classes from previous instantiate call', () => {
let globCount = 0;
@Injectable(A, [])
class Counter implements A {
counter = globCount;
constructor() {
globCount++;
}
a = () => this.counter.toString();
}
container.instantiate(Counter);
container.instantiate(BImpl);
expect(container.get(A).a()).toBe('0');
});
});
describe('get', () => {
it('returns an instance of the interfaceId', () => {
container.instantiate(AImpl);
expect(container.get(A)).toBeInstanceOf(AImpl);
});
it('throws an error for missing dependency', () => {
container.instantiate();
expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/);
});
});
});
References: |
You are a code assistant | Definition of 'CHAT' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp | Definition:
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 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp | Definition:
func (g Greet) greet() {
fmt.Printf("Hello %s\n", g.name)
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20 |
You are a code assistant | Definition of 'Fetch' in file src/node/fetch.ts in project gitlab-lsp | Definition:
export class Fetch extends FetchBase implements LsFetch {
#proxy?: ProxyAgent;
#userProxy?: string;
#initialized: boolean = false;
#httpsAgent: https.Agent;
#agentOptions: Readonly<LsAgentOptions>;
constructor(userProxy?: string) {
super();
this.#agentOptions = {
rejectUnauthorized: true,
};
this.#userProxy = userProxy;
this.#httpsAgent = this.#createHttpsAgent();
}
async initialize(): Promise<void> {
// Set http_proxy and https_proxy environment variables
// which will then get picked up by the ProxyAgent and
// used.
try {
const proxy = await getProxySettings();
if (proxy?.http) {
process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`;
log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`);
}
if (proxy?.https) {
process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`;
log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`);
}
if (!proxy?.http && !proxy?.https) {
log.debug(`fetch: Detected no proxy settings`);
}
} catch (err) {
log.warn('Unable to load proxy settings', err);
}
if (this.#userProxy) {
log.debug(`fetch: Detected user proxy ${this.#userProxy}`);
process.env.http_proxy = this.#userProxy;
process.env.https_proxy = this.#userProxy;
}
if (process.env.http_proxy || process.env.https_proxy) {
log.info(
`fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`,
);
this.#proxy = this.#createProxyAgent();
}
this.#initialized = true;
}
async destroy(): Promise<void> {
this.#proxy?.destroy();
}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
if (!this.#initialized) {
throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.');
}
try {
return await this.#fetchLogged(input, {
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS),
...init,
agent: this.#getAgent(input),
});
} catch (e) {
if (hasName(e) && e.name === 'AbortError') {
throw new TimeoutError(input);
}
throw e;
}
}
updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void {
let fileOptions = {};
try {
fileOptions = {
...(ca ? { ca: fs.readFileSync(ca) } : {}),
...(cert ? { cert: fs.readFileSync(cert) } : {}),
...(certKey ? { key: fs.readFileSync(certKey) } : {}),
};
} catch (err) {
log.error('Error reading https agent options from file', err);
}
const newOptions: LsAgentOptions = {
rejectUnauthorized: !ignoreCertificateErrors,
...fileOptions,
};
if (isEqual(newOptions, this.#agentOptions)) {
// new and old options are the same, nothing to do
return;
}
this.#agentOptions = newOptions;
this.#httpsAgent = this.#createHttpsAgent();
if (this.#proxy) {
this.#proxy = this.#createProxyAgent();
}
}
async *streamFetch(
url: string,
body: string,
headers: FetchHeaders,
): AsyncGenerator<string, void, void> {
let buffer = '';
const decoder = new TextDecoder();
async function* readStream(
stream: ReadableStream<Uint8Array>,
): AsyncGenerator<string, void, void> {
for await (const chunk of stream) {
buffer += decoder.decode(chunk);
yield buffer;
}
}
const response: Response = await this.fetch(url, {
method: 'POST',
headers,
body,
});
await handleFetchError(response, 'Code Suggestions Streaming');
if (response.body) {
// Note: Using (node:stream).ReadableStream as it supports async iterators
yield* readStream(response.body as ReadableStream);
}
}
#createHttpsAgent(): https.Agent {
const agentOptions = {
...this.#agentOptions,
keepAlive: true,
};
log.debug(
`fetch: https agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(agentOptions),
)}.`,
);
return new https.Agent(agentOptions);
}
#createProxyAgent(): ProxyAgent {
log.debug(
`fetch: proxy agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(this.#agentOptions),
)}.`,
);
return new ProxyAgent(this.#agentOptions);
}
async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> {
const start = Date.now();
const url = this.#extractURL(input);
if (init.agent === httpAgent) {
log.debug(`fetch: request for ${url} made with http agent.`);
} else {
const type = init.agent === this.#proxy ? 'proxy' : 'https';
log.debug(`fetch: request for ${url} made with ${type} agent.`);
}
try {
const resp = await fetch(input, init);
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`);
return resp;
} catch (e) {
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`);
log.error(`fetch: request to ${url} failed with:`, e);
throw e;
}
}
#getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent {
if (this.#proxy) {
return this.#proxy;
}
if (input.toString().startsWith('https://')) {
return this.#httpsAgent;
}
return httpAgent;
}
#extractURL(input: RequestInfo | URL): string {
if (input instanceof URL) {
return input.toString();
}
if (typeof input === 'string') {
return input;
}
return input.url;
}
#sanitizeAgentOptions(agentOptions: LsAgentOptions) {
const { ca, cert, key, ...options } = agentOptions;
return {
...options,
...(ca ? { ca: '<hidden>' } : {}),
...(cert ? { cert: '<hidden>' } : {}),
...(key ? { key: '<hidden>' } : {}),
};
}
}
References:
- src/tests/int/fetch.test.ts:154
- src/node/fetch.test.ts:38
- src/node/fetch.test.ts:57
- src/node/fetch.test.ts:90
- src/browser/fetch.test.ts:33
- src/node/fetch.test.ts:74
- src/tests/int/snowplow.test.ts:16
- src/browser/main.ts:67
- src/node/main.ts:113
- src/tests/int/fetch.test.ts:124
- src/node/fetch.test.ts:191
- src/node/fetch.test.ts:194
- src/tests/int/fetch.test.ts:82 |
You are a code assistant | Definition of 'WEBVIEW_ID' in file packages/webview-chat/src/constants.ts in project gitlab-lsp | Definition:
export const WEBVIEW_ID = 'chat' as WebviewId;
export const WEBVIEW_TITLE = 'GitLab: Duo Chat';
References: |
You are a code assistant | Definition of 'getForAllAccounts' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp | Definition:
async getForAllAccounts(): Promise<GitLabPlatformForAccount[]> {
return [new ChatPlatformForAccount(this.#client)];
}
async getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined> {
return new ChatPlatformForAccount(this.#client);
}
}
References: |
You are a code assistant | Definition of 'CreateFastifyRequestParams' in file src/node/webview/test-utils/mock_fastify_request.ts in project gitlab-lsp | Definition:
type CreateFastifyRequestParams = {
url: string;
params: Record<string, unknown>;
};
export function createMockFastifyRequest(
params?: Partial<CreateFastifyRequestParams>,
): FastifyRequest {
// eslint-disable-next-line no-param-reassign
params ??= {};
return {
url: params.url ?? '',
params: params.params ?? {},
} as FastifyRequest;
}
References: |
You are a code assistant | Definition of 'SupportedSinceInstanceVersion' in file src/common/api_types.ts in project gitlab-lsp | Definition:
interface SupportedSinceInstanceVersion {
version: string;
resourceName: string;
}
interface BaseRestRequest<_TReturnType> {
type: 'rest';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
headers?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'POST';
body?: unknown;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the TReturnType
*/
interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'GET';
searchParams?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
export type AdditionalContext = {
/**
* The type of the context element. Options: `file` or `snippet`.
*/
type: 'file' | 'snippet';
/**
* The name of the context element. A name of the file or a code snippet.
*/
name: string;
/**
* The content of the context element. The body of the file or a function.
*/
content: string;
/**
* Where the context was derived from
*/
resolution_strategy: ContextResolution['strategy'];
};
// FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption
// this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP
export interface SuggestionOption {
index?: number;
text: string;
uniqueTrackingId: string;
lang?: string;
}
export interface TelemetryRequest {
event: string;
additional_properties: {
unique_tracking_id: string;
language?: string;
suggestion_size?: number;
timestamp: string;
};
}
References:
- src/common/api_types.ts:31
- packages/webview_duo_chat/src/plugin/types.ts:41
- packages/webview_duo_chat/src/plugin/types.ts:49
- src/common/api_types.ts:23
- packages/webview_duo_chat/src/plugin/types.ts:65
- src/common/api_types.ts:47 |
You are a code assistant | Definition of 'WORKSPACE_FOLDER_URI' in file src/tests/int/test_utils.ts in project gitlab-lsp | Definition:
export const WORKSPACE_FOLDER_URI: URI = 'file://base/path';
export const MOCK_FILE_1 = {
uri: `${WORKSPACE_FOLDER_URI}/some-file.js`,
languageId: 'javascript',
version: 0,
text: '',
};
export const MOCK_FILE_2 = {
uri: `${WORKSPACE_FOLDER_URI}/some-other-file.js`,
languageId: 'javascript',
version: 0,
text: '',
};
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Matchers<LspClient> {
toEventuallyContainChildProcessConsoleOutput(
expectedMessage: string,
timeoutMs?: number,
intervalMs?: number,
): Promise<LspClient>;
}
}
}
expect.extend({
/**
* Custom matcher to check the language client child process console output for an expected string.
* This is useful when an operation does not directly run some logic, (e.g. internally emits events
* which something later does the thing you're testing), so you cannot just await and check the output.
*
* await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo');
*
* @param lsClient LspClient instance to check
* @param expectedMessage Message to check for
* @param timeoutMs How long to keep checking before test is considered failed
* @param intervalMs How frequently to check the log
*/
async toEventuallyContainChildProcessConsoleOutput(
lsClient: LspClient,
expectedMessage: string,
timeoutMs = 1000,
intervalMs = 25,
) {
const expectedResult = `Expected language service child process console output to contain "${expectedMessage}"`;
const checkOutput = () =>
lsClient.childProcessConsole.some((line) => line.includes(expectedMessage));
const sleep = () =>
new Promise((resolve) => {
setTimeout(resolve, intervalMs);
});
let remainingRetries = Math.ceil(timeoutMs / intervalMs);
while (remainingRetries > 0) {
if (checkOutput()) {
return {
message: () => expectedResult,
pass: true,
};
}
// eslint-disable-next-line no-await-in-loop
await sleep();
remainingRetries--;
}
return {
message: () => `"${expectedResult}", but it was not found within ${timeoutMs}ms`,
pass: false,
};
},
});
References: |
You are a code assistant | Definition of 'ExtractRequestResult' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp | Definition:
export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> =
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
T['result'] extends undefined ? void : T;
/**
* Interface for publishing requests.
* @interface
* @template {RequestMap} TRequests
*/
export interface RequestPublisher<TRequests extends RequestMap> {
sendRequest<T extends KeysWithOptionalParams<TRequests>>(
type: T,
): Promise<ExtractRequestResult<TRequests[T]>>;
sendRequest<T extends keyof TRequests>(
type: T,
payload: TRequests[T]['params'],
): Promise<ExtractRequestResult<TRequests[T]>>;
}
/**
* Interface for listening to requests.
* @interface
* @template {RequestMap} TRequests
*/
export interface RequestListener<TRequests extends RequestMap> {
onRequest<T extends KeysWithOptionalParams<TRequests>>(
type: T,
handler: () => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
onRequest<T extends keyof TRequests>(
type: T,
handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
}
/**
* Defines the structure for message definitions, including notifications and requests.
*/
export type MessageDefinitions<
TNotifications extends NotificationMap = NotificationMap,
TRequests extends RequestMap = RequestMap,
> = {
notifications: TNotifications;
requests: TRequests;
};
export type MessageMap<
TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
> = {
inbound: TInboundMessageDefinitions;
outbound: TOutboundMessageDefinitions;
};
export interface MessageBus<T extends MessageMap = MessageMap>
extends NotificationPublisher<T['outbound']['notifications']>,
NotificationListener<T['inbound']['notifications']>,
RequestPublisher<T['outbound']['requests']>,
RequestListener<T['inbound']['requests']> {}
References: |
You are a code assistant | Definition of 'BaseRestRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp | Definition:
interface BaseRestRequest<_TReturnType> {
type: 'rest';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
headers?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'POST';
body?: unknown;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the TReturnType
*/
interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'GET';
searchParams?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
export interface GitLabApiClient {
fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>;
connectToCable(): Promise<Cable>;
}
References: |
You are a code assistant | Definition of 'RepositoryUri' in file src/common/git/repository_service.ts in project gitlab-lsp | Definition:
type RepositoryUri = string;
type WorkspaceFolderUri = string;
type RepositoryMap = Map<RepositoryUri, Repository>;
export type RepositoryService = typeof DefaultRepositoryService.prototype;
export const RepositoryService = createInterfaceId<RepositoryService>('RepositoryService');
@Injectable(RepositoryService, [VirtualFileSystemService])
export class DefaultRepositoryService {
#virtualFileSystemService: DefaultVirtualFileSystemService;
constructor(virtualFileSystemService: DefaultVirtualFileSystemService) {
this.#virtualFileSystemService = virtualFileSystemService;
this.#setupEventListeners();
}
#setupEventListeners() {
return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => {
switch (eventType) {
case VirtualFileSystemEvents.WorkspaceFilesUpdate:
await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate);
break;
case VirtualFileSystemEvents.WorkspaceFileUpdate:
await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate);
break;
default:
break;
}
});
}
async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) {
log.info(`Workspace files update: ${update.files.length}`);
const perf1 = performance.now();
await this.handleWorkspaceFilesUpdate({
...update,
});
const perf2 = performance.now();
log.info(`Workspace files initialization took ${perf2 - perf1}ms`);
const perf3 = performance.now();
const files = this.getFilesForWorkspace(update.workspaceFolder.uri, {
excludeGitFolder: true,
excludeIgnored: true,
});
const perf4 = performance.now();
log.info(`Fetched workspace files in ${perf4 - perf3}ms`);
log.info(`Workspace git files: ${files.length}`);
// const treeFile = await readFile(
// '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt',
// 'utf-8',
// );
// const treeFiles = treeFile.split('\n').filter(Boolean);
// // get the set difference between the files in the tree and the non-ignored files
// // we need the difference between the two sets to know which files are not in the tree
// const diff = new Set(
// files.map((file) =>
// relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath),
// ),
// );
// for (const file of treeFiles) {
// diff.delete(file);
// }
// log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`);
}
async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) {
log.info(`Workspace file update: ${JSON.stringify(update)}`);
await this.handleWorkspaceFileUpdate({
...update,
});
const perf1 = performance.now();
const files = this.getFilesForWorkspace(update.workspaceFolder.uri, {
excludeGitFolder: true,
excludeIgnored: true,
});
const perf2 = performance.now();
log.info(`Fetched workspace files in ${perf2 - perf1}ms`);
log.info(`Workspace git files: ${files.length}`);
}
/**
* unique map of workspace folders that point to a map of repositories
* We store separate repository maps for each workspace because
* the events from the VFS service are at the workspace level.
* If we combined them, we may get race conditions
*/
#workspaces: Map<WorkspaceFolderUri, RepositoryMap> = new Map();
#workspaceRepositoryTries: Map<WorkspaceFolderUri, RepositoryTrie> = new Map();
#buildRepositoryTrie(repositories: Repository[]): RepositoryTrie {
const root = new RepositoryTrie();
for (const repo of repositories) {
let node = root;
const parts = repo.uri.path.split('/').filter(Boolean);
for (const part of parts) {
if (!node.children.has(part)) {
node.children.set(part, new RepositoryTrie());
}
node = node.children.get(part) as RepositoryTrie;
}
node.repository = repo.uri;
}
return root;
}
findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null {
const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri);
if (!trie) return null;
let node = trie;
let lastMatchingRepo: URI | null = null;
const parts = fileUri.path.split('/').filter(Boolean);
for (const part of parts) {
if (node.repository) {
lastMatchingRepo = node.repository;
}
if (!node.children.has(part)) break;
node = node.children.get(part) as RepositoryTrie;
}
return node.repository || lastMatchingRepo;
}
getRepositoryFileForUri(
fileUri: URI,
repositoryUri: URI,
workspaceFolder: WorkspaceFolder,
): RepositoryFile | null {
const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get(
repositoryUri.toString(),
);
if (!repository) {
return null;
}
return repository.getFile(fileUri.toString()) ?? null;
}
#updateRepositoriesForFolder(
workspaceFolder: WorkspaceFolder,
repositoryMap: RepositoryMap,
repositoryTrie: RepositoryTrie,
) {
this.#workspaces.set(workspaceFolder.uri, repositoryMap);
this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie);
}
async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) {
// clear existing repositories from workspace
this.#emptyRepositoriesForWorkspace(workspaceFolder.uri);
const repositories = this.#detectRepositories(files, workspaceFolder);
const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo]));
// Build and cache the repository trie for this workspace
const trie = this.#buildRepositoryTrie(repositories);
this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie);
await Promise.all(
repositories.map((repo) =>
repo.addFilesAndLoadGitIgnore(
files.filter((file) => {
const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder);
return matchingRepo && matchingRepo.toString() === repo.uri.toString();
}),
),
),
);
}
async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) {
const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder);
if (!repoUri) {
log.debug(`No matching repository found for file ${fileUri.toString()}`);
return;
}
const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri);
const repository = repositoryMap.get(repoUri.toString());
if (!repository) {
log.debug(`Repository not found for URI ${repoUri.toString()}`);
return;
}
if (repository.isFileIgnored(fileUri)) {
log.debug(`File ${fileUri.toString()} is ignored`);
return;
}
switch (event) {
case 'add':
repository.setFile(fileUri);
log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`);
break;
case 'change':
repository.setFile(fileUri);
log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`);
break;
case 'unlink':
repository.removeFile(fileUri.toString());
log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`);
break;
default:
log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`);
}
}
#getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap {
return this.#workspaces.get(workspaceFolderUri) || new Map();
}
#emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void {
log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`);
const repos = this.#workspaces.get(workspaceFolderUri);
if (!repos || repos.size === 0) return;
// clear up ignore manager trie from memory
repos.forEach((repo) => {
repo.dispose();
log.debug(`Repository ${repo.uri} has been disposed`);
});
repos.clear();
const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri);
if (trie) {
trie.dispose();
this.#workspaceRepositoryTries.delete(workspaceFolderUri);
}
this.#workspaces.delete(workspaceFolderUri);
log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`);
}
#detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] {
const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config'));
return gitConfigFiles.map((file) => {
const projectUri = fsPathToUri(file.path.replace('.git/config', ''));
const ignoreManager = new IgnoreManager(projectUri.fsPath);
log.info(`Detected repository at ${projectUri.path}`);
return new Repository({
ignoreManager,
uri: projectUri,
configFileUri: file,
workspaceFolder,
});
});
}
getFilesForWorkspace(
workspaceFolderUri: WorkspaceFolderUri,
options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {},
): RepositoryFile[] {
const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri);
const allFiles: RepositoryFile[] = [];
repositories.forEach((repository) => {
repository.getFiles().forEach((file) => {
// apply the filters
if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) {
return;
}
if (options.excludeIgnored && file.isIgnored) {
return;
}
allFiles.push(file);
});
});
return allFiles;
}
// Helper method to check if a file is in the .git folder
#isInGitFolder(fileUri: URI, repositoryUri: URI): boolean {
const relativePath = fileUri.path.slice(repositoryUri.path.length);
return relativePath.split('/').some((part) => part === '.git');
}
}
References:
- src/common/git/repository.ts:11
- src/common/git/repository.ts:34 |
You are a code assistant | Definition of 'WebviewInstanceInfo' in file packages/lib_webview_transport_socket_io/src/types.ts in project gitlab-lsp | Definition:
export type WebviewInstanceInfo = {
webviewId: WebviewId;
webviewInstanceId: WebviewInstanceId;
};
References:
- packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts:6
- packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:58 |
You are a code assistant | Definition of 'warn' in file src/common/log_types.ts in project gitlab-lsp | Definition:
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
export const LOG_LEVEL = {
DEBUG: 'debug',
INFO: 'info',
WARNING: 'warning',
ERROR: 'error',
} as const;
export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL];
References: |
You are a code assistant | Definition of 'parseFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> {
const init = await this.#handleInit();
if (!init) {
return undefined;
}
const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath);
if (!languageInfo) {
return undefined;
}
const parser = await this.getParser(languageInfo);
if (!parser) {
log.debug(
'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.',
);
return undefined;
}
const tree = parser.parse(`${context.prefix}${context.suffix}`);
return {
tree,
language: parser.getLanguage(),
languageInfo,
};
}
async #handleInit(): Promise<boolean> {
try {
await this.init();
return true;
} catch (err) {
log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
return false;
}
getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined {
return this.getLanguageInfoForFile(filename)?.name;
}
async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> {
if (this.parsers.has(languageInfo.name)) {
return this.parsers.get(languageInfo.name) as Parser;
}
try {
const parser = new Parser();
const language = await Parser.Language.load(languageInfo.wasmPath);
parser.setLanguage(language);
this.parsers.set(languageInfo.name, parser);
log.debug(
`TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`,
);
return parser;
} catch (err) {
this.loadState = TreeSitterParserLoadState.ERRORED;
// NOTE: We validate the below is not present in generation.test.ts integration test.
// Make sure to update the test appropriately if changing the error.
log.warn(
'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.',
err,
);
return undefined;
}
}
getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined {
const ext = filename.split('.').pop();
return this.languages.get(`.${ext}`);
}
buildTreeSitterInfoByExtMap(
languages: TreeSitterLanguageInfo[],
): Map<string, TreeSitterLanguageInfo> {
return languages.reduce((map, language) => {
for (const extension of language.extensions) {
map.set(extension, language);
}
return map;
}, new Map<string, TreeSitterLanguageInfo>());
}
}
References: |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp | Definition:
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20
- src/tests/fixtures/intent/empty_function/ruby.rb:29 |
You are a code assistant | Definition of 'handle' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp | Definition:
async handle(key: string, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> {
const handler = this.#handlers.get(key);
if (!handler) {
throw new HandlerNotFoundError(key);
}
try {
const handlerResult = await handler(...args);
return handlerResult as ReturnType<THandler>;
} catch (error) {
throw new UnhandledHandlerError(key, resolveError(error));
}
}
dispose() {
this.#handlers.clear();
}
}
function resolveError(e: unknown): Error {
if (e instanceof Error) {
return e;
}
if (typeof e === 'string') {
return new Error(e);
}
return new Error('Unknown error');
}
References: |
You are a code assistant | Definition of 'hasbinFirstSync' in file src/tests/int/hasbin.ts in project gitlab-lsp | Definition:
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 'onOpen' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References: |
You are a code assistant | Definition of 'has' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp | Definition:
has(key: string) {
return this.#handlers.has(key);
}
async handle(key: string, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> {
const handler = this.#handlers.get(key);
if (!handler) {
throw new HandlerNotFoundError(key);
}
try {
const handlerResult = await handler(...args);
return handlerResult as ReturnType<THandler>;
} catch (error) {
throw new UnhandledHandlerError(key, resolveError(error));
}
}
dispose() {
this.#handlers.clear();
}
}
function resolveError(e: unknown): Error {
if (e instanceof Error) {
return e;
}
if (typeof e === 'string') {
return new Error(e);
}
return new Error('Unknown error');
}
References: |
You are a code assistant | Definition of 'MessageHandlerOptions' in file src/common/message_handler.ts in project gitlab-lsp | Definition:
export interface MessageHandlerOptions {
telemetryTracker: TelemetryTracker;
configService: ConfigService;
connection: Connection;
featureFlagService: FeatureFlagService;
duoProjectAccessCache: DuoProjectAccessCache;
virtualFileSystemService: VirtualFileSystemService;
workflowAPI: WorkflowAPI | undefined;
}
export interface ITelemetryNotificationParams {
category: 'code_suggestions';
action: TRACKING_EVENTS;
context: {
trackingId: string;
optionId?: number;
};
}
export interface IStartWorkflowParams {
goal: string;
image: string;
}
export const waitMs = (msToWait: number) =>
new Promise((resolve) => {
setTimeout(resolve, msToWait);
});
/* CompletionRequest represents LS client's request for either completion or inlineCompletion */
export interface CompletionRequest {
textDocument: TextDocumentIdentifier;
position: Position;
token: CancellationToken;
inlineCompletionContext?: InlineCompletionContext;
}
export class MessageHandler {
#configService: ConfigService;
#tracker: TelemetryTracker;
#connection: Connection;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#duoProjectAccessCache: DuoProjectAccessCache;
#featureFlagService: FeatureFlagService;
#workflowAPI: WorkflowAPI | undefined;
#virtualFileSystemService: VirtualFileSystemService;
constructor({
telemetryTracker,
configService,
connection,
featureFlagService,
duoProjectAccessCache,
virtualFileSystemService,
workflowAPI = undefined,
}: MessageHandlerOptions) {
this.#configService = configService;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#featureFlagService = featureFlagService;
this.#workflowAPI = workflowAPI;
this.#subscribeToCircuitBreakerEvents();
this.#virtualFileSystemService = virtualFileSystemService;
this.#duoProjectAccessCache = duoProjectAccessCache;
}
didChangeConfigurationHandler = async (
{ settings }: ChangeConfigOptions = { settings: {} },
): Promise<void> => {
this.#configService.merge({
client: settings,
});
// update Duo project access cache
await this.#duoProjectAccessCache.updateCache({
baseUrl: this.#configService.get('client.baseUrl') ?? '',
workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [],
});
await this.#virtualFileSystemService.initialize(
this.#configService.get('client.workspaceFolders') ?? [],
);
};
telemetryNotificationHandler = async ({
category,
action,
context,
}: ITelemetryNotificationParams) => {
if (category === CODE_SUGGESTIONS_CATEGORY) {
const { trackingId, optionId } = context;
if (
trackingId &&
canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action)
) {
switch (action) {
case TRACKING_EVENTS.ACCEPTED:
if (optionId) {
this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId });
}
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED);
break;
case TRACKING_EVENTS.REJECTED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED);
break;
case TRACKING_EVENTS.CANCELLED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED);
break;
case TRACKING_EVENTS.SHOWN:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN);
break;
case TRACKING_EVENTS.NOT_PROVIDED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED);
break;
default:
break;
}
}
}
};
onShutdownHandler = () => {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
};
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
async #sendWorkflowErrorNotification(message: string) {
await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, {
message,
type: 'error',
});
}
startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => {
const duoWorkflow = this.#featureFlagService.isClientFlagEnabled(
ClientFeatureFlags.DuoWorkflow,
);
if (!duoWorkflow) {
await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`);
return;
}
if (!this.#workflowAPI) {
await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP');
return;
}
try {
await this.#workflowAPI?.runWorkflow(goal, image);
} catch (e) {
log.error('Error in running workflow', e);
await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`);
}
};
}
References:
- src/common/message_handler.ts:97 |
You are a code assistant | Definition of 'ExtensionMessageBusProvider' in file packages/lib_webview/src/types.ts in project gitlab-lsp | Definition:
export interface ExtensionMessageBusProvider {
getMessageBus<T extends MessageMap>(webviewId: WebviewId): MessageBus<T>;
}
References:
- packages/lib_webview/src/setup/setup_webview_runtime.ts:11
- packages/lib_webview/src/setup/plugin/setup_plugins.ts:11 |
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):
def greet(self):
class Greet3:
References: |
You are a code assistant | Definition of 'MessageHandler' in file src/common/message_handler.ts in project gitlab-lsp | Definition:
export class MessageHandler {
#configService: ConfigService;
#tracker: TelemetryTracker;
#connection: Connection;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#duoProjectAccessCache: DuoProjectAccessCache;
#featureFlagService: FeatureFlagService;
#workflowAPI: WorkflowAPI | undefined;
#virtualFileSystemService: VirtualFileSystemService;
constructor({
telemetryTracker,
configService,
connection,
featureFlagService,
duoProjectAccessCache,
virtualFileSystemService,
workflowAPI = undefined,
}: MessageHandlerOptions) {
this.#configService = configService;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#featureFlagService = featureFlagService;
this.#workflowAPI = workflowAPI;
this.#subscribeToCircuitBreakerEvents();
this.#virtualFileSystemService = virtualFileSystemService;
this.#duoProjectAccessCache = duoProjectAccessCache;
}
didChangeConfigurationHandler = async (
{ settings }: ChangeConfigOptions = { settings: {} },
): Promise<void> => {
this.#configService.merge({
client: settings,
});
// update Duo project access cache
await this.#duoProjectAccessCache.updateCache({
baseUrl: this.#configService.get('client.baseUrl') ?? '',
workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [],
});
await this.#virtualFileSystemService.initialize(
this.#configService.get('client.workspaceFolders') ?? [],
);
};
telemetryNotificationHandler = async ({
category,
action,
context,
}: ITelemetryNotificationParams) => {
if (category === CODE_SUGGESTIONS_CATEGORY) {
const { trackingId, optionId } = context;
if (
trackingId &&
canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action)
) {
switch (action) {
case TRACKING_EVENTS.ACCEPTED:
if (optionId) {
this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId });
}
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED);
break;
case TRACKING_EVENTS.REJECTED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED);
break;
case TRACKING_EVENTS.CANCELLED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED);
break;
case TRACKING_EVENTS.SHOWN:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN);
break;
case TRACKING_EVENTS.NOT_PROVIDED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED);
break;
default:
break;
}
}
}
};
onShutdownHandler = () => {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
};
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
async #sendWorkflowErrorNotification(message: string) {
await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, {
message,
type: 'error',
});
}
startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => {
const duoWorkflow = this.#featureFlagService.isClientFlagEnabled(
ClientFeatureFlags.DuoWorkflow,
);
if (!duoWorkflow) {
await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`);
return;
}
if (!this.#workflowAPI) {
await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP');
return;
}
try {
await this.#workflowAPI?.runWorkflow(goal, image);
} catch (e) {
log.error('Error in running workflow', e);
await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`);
}
};
}
References:
- src/common/connection.ts:48
- src/common/message_handler.test.ts:141
- src/common/message_handler.test.ts:213
- src/common/message_handler.test.ts:40
- src/common/message_handler.test.ts:105 |
You are a code assistant | Definition of 'Processor1' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp | Definition:
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:162
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:116 |
You are a code assistant | Definition of 'AiContextPolicyManager' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp | Definition:
export const AiContextPolicyManager =
createInterfaceId<AiContextPolicyManager>('AiContextAggregator');
export type AiContextQuery = {
query: string;
providerType: 'file';
textDocument?: TextDocument;
workspaceFolders: WorkspaceFolder[];
};
@Injectable(AiContextPolicyManager, [DuoProjectPolicy])
export class DefaultAiPolicyManager {
#policies: AiContextPolicy[] = [];
constructor(duoProjectPolicy: DuoProjectPolicy) {
this.#policies.push(duoProjectPolicy);
}
async runPolicies(aiContextProviderItem: AiContextProviderItem) {
const results = await Promise.all(
this.#policies.map(async (policy) => {
return policy.isAllowed(aiContextProviderItem);
}),
);
const disallowedResults = results.filter((result) => !result.allowed);
if (disallowedResults.length > 0) {
const reasons = disallowedResults.map((result) => result.reason).filter(Boolean);
return { allowed: false, reasons: reasons as string[] };
}
return { allowed: true };
}
}
References:
- src/common/ai_context_management_2/ai_context_aggregator.ts:30
- src/common/ai_context_management_2/ai_context_aggregator.ts:26 |
You are a code assistant | Definition of 'AiContextItem' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp | Definition:
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/retrievers/ai_context_retriever.ts:4
- src/common/ai_context_management_2/ai_context_manager.ts:21
- src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:21
- src/common/connection_service.ts:112 |
You are a code assistant | Definition of 'ResponseError' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'WebviewController' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp | Definition:
export class WebviewController<T extends MessageMap> implements WebviewConnection<T>, Disposable {
readonly webviewId: WebviewId;
#messageBusFactory: WebviewMessageBusFactory;
#handlers = new Set<WebviewMessageBusManagerHandler<T>>();
#instanceInfos = new Map<WebviewInstanceId, WebviewInstanceInfo>();
#compositeDisposable = new CompositeDisposable();
#logger: Logger;
constructor(
webviewId: WebviewId,
runtimeMessageBus: WebviewRuntimeMessageBus,
messageBusFactory: WebviewMessageBusFactory,
logger: Logger,
) {
this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`);
this.webviewId = webviewId;
this.#messageBusFactory = messageBusFactory;
this.#subscribeToEvents(runtimeMessageBus);
}
broadcast<TMethod extends keyof T['outbound']['notifications'] & string>(
type: TMethod,
payload: T['outbound']['notifications'][TMethod],
) {
for (const info of this.#instanceInfos.values()) {
info.messageBus.sendNotification(type.toString(), payload);
}
}
onInstanceConnected(handler: WebviewMessageBusManagerHandler<T>) {
this.#handlers.add(handler);
for (const [instanceId, info] of this.#instanceInfos) {
const disposable = handler(instanceId, info.messageBus);
if (isDisposable(disposable)) {
info.pluginCallbackDisposables.add(disposable);
}
}
}
dispose(): void {
this.#compositeDisposable.dispose();
this.#instanceInfos.forEach((info) => info.messageBus.dispose());
this.#instanceInfos.clear();
}
#subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) {
const eventFilter = buildWebviewIdFilter(this.webviewId);
this.#compositeDisposable.add(
runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter),
runtimeMessageBus.subscribe(
'webview:disconnect',
this.#handleDisconnected.bind(this),
eventFilter,
),
);
}
#handleConnected(address: WebviewAddress) {
this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`);
if (this.#instanceInfos.has(address.webviewInstanceId)) {
// we are already connected with this webview instance
return;
}
const messageBus = this.#messageBusFactory(address);
const pluginCallbackDisposables = new CompositeDisposable();
this.#instanceInfos.set(address.webviewInstanceId, {
messageBus,
pluginCallbackDisposables,
});
this.#handlers.forEach((handler) => {
const disposable = handler(address.webviewInstanceId, messageBus);
if (isDisposable(disposable)) {
pluginCallbackDisposables.add(disposable);
}
});
}
#handleDisconnected(address: WebviewAddress) {
this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`);
const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId);
if (!instanceInfo) {
// we aren't tracking this instance
return;
}
instanceInfo.pluginCallbackDisposables.dispose();
instanceInfo.messageBus.dispose();
this.#instanceInfos.delete(address.webviewInstanceId);
}
}
References:
- packages/lib_webview/src/setup/plugin/webview_controller.test.ts:32
- packages/lib_webview/src/setup/plugin/setup_plugins.ts:34 |
You are a code assistant | Definition of 'Uri' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
type Uri = string;
export interface WebviewUriProvider {
getUri(webviewId: WebviewId): Uri;
}
export interface WebviewUriProviderRegistry {
register(provider: WebviewUriProvider): void;
}
export class WebviewLocationService implements WebviewUriProviderRegistry {
#uriProviders = new Set<WebviewUriProvider>();
register(provider: WebviewUriProvider) {
this.#uriProviders.add(provider);
}
resolveUris(webviewId: WebviewId): Uri[] {
const uris: Uri[] = [];
for (const provider of this.#uriProviders) {
uris.push(provider.getUri(webviewId));
}
return uris;
}
}
References:
- src/common/webview/webview_resource_location_service.ts:6 |
You are a code assistant | Definition of 'main' in file src/browser/main.ts in project gitlab-lsp | Definition:
async function main() {
// eslint-disable-next-line no-restricted-globals
const worker: Worker = self as unknown as Worker;
const messageReader = new BrowserMessageReader(worker);
const messageWriter = new BrowserMessageWriter(worker);
const container = new Container();
container.instantiate(DefaultConfigService, DefaultSupportedLanguagesService);
const lsFetch = new Fetch();
container.addInstances(brandInstance(LsFetch, lsFetch));
const connection = createConnection(ProposedFeatures.all, messageReader, messageWriter);
container.addInstances(brandInstance(LsConnection, connection));
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
container.addInstances(brandInstance(LsTextDocuments, documents));
const configService = container.get(ConfigService);
const documentService = new DefaultDocumentService(documents);
container.addInstances(brandInstance(DocumentService, documentService));
container.instantiate(
GitLabAPI,
DefaultDocumentTransformerService,
DefaultFeatureFlagService,
DefaultTokenCheckNotifier,
DefaultSecretRedactor,
DefaultSecurityDiagnosticsPublisher,
DefaultConnectionService,
DefaultInitializeHandler,
DefaultCodeSuggestionsSupportedLanguageCheck,
DefaultProjectDuoAccessCheck,
DefaultFeatureStateManager,
DefaultAdvancedContextService,
DefaultDuoProjectAccessChecker,
DefaultDuoProjectAccessCache,
DefaultVirtualFileSystemService,
DefaultRepositoryService,
DefaultWorkspaceService,
DefaultDirectoryWalker,
EmptyFileResolver,
);
const snowplowTracker = new SnowplowTracker(
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 BrowserTreeSitterParser(configService);
log.setup(configService);
const version = getLanguageServerVersion();
log.info(`GitLab Language Server is starting (v${version})`);
await lsFetch.initialize();
setup(
telemetryTracker,
connection,
container.get(DocumentTransformerService),
container.get(GitLabApiClient),
container.get(FeatureFlagService),
configService,
{
treeSitterParser,
},
undefined,
undefined,
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();
log.info('GitLab Language Server has started');
}
main().catch((e) => log.error(e));
References:
- src/browser/main.ts:147
- src/node/main.ts:238 |
You are a code assistant | Definition of 'delete' in file src/common/fetch.ts in project gitlab-lsp | Definition:
delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
updateAgentOptions(options: FetchAgentOptions): void;
streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>;
}
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References: |
You are a code assistant | Definition of 'DefaultFeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp | Definition:
export class DefaultFeatureStateManager implements FeatureStateManager {
#checks: StateCheck[] = [];
#subscriptions: Disposable[] = [];
#notify?: NotifyFn<FeatureStateNotificationParams>;
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:
- src/common/feature_state/feature_state_manager.test.ts:44 |
You are a code assistant | Definition of 'run' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp | Definition:
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:
- scripts/watcher/watch.ts:99
- scripts/commit-lint/lint.js:93
- scripts/watcher/watch.ts:95
- scripts/watcher/watch.ts:87 |
You are a code assistant | Definition of 'DefaultTokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp | Definition:
export class DefaultTokenCheckNotifier implements TokenCheckNotifier {
#notify: NotifyFn<TokenCheckNotificationParams> | undefined;
constructor(api: GitLabApiClient) {
api.onApiReconfigured(async ({ isInValidState, validationMessage }) => {
if (!isInValidState) {
if (!this.#notify) {
throw new Error(
'The DefaultTokenCheckNotifier has not been initialized. Call init first.',
);
}
await this.#notify({
message: validationMessage,
});
}
});
}
init(callback: NotifyFn<TokenCheckNotificationParams>) {
this.#notify = callback;
}
}
References:
- src/common/core/handlers/token_check_notifier.test.ts:26 |
You are a code assistant | Definition of 'constructor' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
constructor(configService: ConfigService) {
this.#configService = configService;
const currentConfig = this.#getCurrentConfig();
this.#cache = new LRUCache<string, SuggestionCacheEntry>({
ttlAutopurge: true,
sizeCalculation: (value, key) =>
value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length,
...DEFAULT_CONFIG,
...currentConfig,
ttl: Number(currentConfig.ttl),
});
}
#getCurrentConfig(): Required<ISuggestionsCacheOptions> {
return {
...DEFAULT_CONFIG,
...(this.#configService.get('client.suggestionsCache') ?? {}),
};
}
#getSuggestionKey(ctx: SuggestionCacheContext) {
const prefixLines = ctx.context.prefix.split('\n');
const currentLine = prefixLines.pop() ?? '';
const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length;
const config = this.#getCurrentConfig();
const cachedPrefixLines = prefixLines
.filter(isNonEmptyLine)
.slice(-config.prefixLines)
.join('\n');
const cachedSuffixLines = ctx.context.suffix
.split('\n')
.filter(isNonEmptyLine)
.slice(0, config.suffixLines)
.join('\n');
return [
ctx.document.uri,
ctx.position.line,
cachedPrefixLines,
cachedSuffixLines,
indentation,
].join(':');
}
#increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) {
const item = this.#cache.get(suggestionKey);
if (item && item.timesRetrievedByPosition) {
item.timesRetrievedByPosition[character] =
(item.timesRetrievedByPosition[character] ?? 0) + 1;
}
}
addToSuggestionCache(config: {
request: SuggestionCacheContext;
suggestions: SuggestionOption[];
}) {
if (!this.#getCurrentConfig().enabled) {
return;
}
const currentLine = config.request.context.prefix.split('\n').at(-1) ?? '';
this.#cache.set(this.#getSuggestionKey(config.request), {
character: config.request.position.character,
suggestions: config.suggestions,
currentLine,
timesRetrievedByPosition: {},
additionalContexts: config.request.additionalContexts,
});
}
getCachedSuggestions(request: SuggestionCacheContext): SuggestionCache | undefined {
if (!this.#getCurrentConfig().enabled) {
return undefined;
}
const currentLine = request.context.prefix.split('\n').at(-1) ?? '';
const key = this.#getSuggestionKey(request);
const candidate = this.#cache.get(key);
if (!candidate) {
return undefined;
}
const { character } = request.position;
if (candidate.timesRetrievedByPosition[character] > 0) {
// If cache has already returned this suggestion from the same position before, discard it.
this.#cache.delete(key);
return undefined;
}
this.#increaseCacheEntryRetrievedCount(key, character);
const options = candidate.suggestions
.map((s) => {
const currentLength = currentLine.length;
const previousLength = candidate.currentLine.length;
const diff = currentLength - previousLength;
if (diff < 0) {
return null;
}
if (
currentLine.slice(0, previousLength) !== candidate.currentLine ||
s.text.slice(0, diff) !== currentLine.slice(previousLength)
) {
return null;
}
return {
...s,
text: s.text.slice(diff),
uniqueTrackingId: generateUniqueTrackingId(),
};
})
.filter((x): x is SuggestionOption => Boolean(x));
return {
options,
additionalContexts: candidate.additionalContexts,
};
}
}
References: |
You are a code assistant | Definition of 'СodeSuggestionContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp | Definition:
interface СodeSuggestionContext {
language?: string;
suggestion_size?: number;
timestamp: string;
is_streaming?: boolean;
}
export class InstanceTracker implements TelemetryTracker {
#api: GitLabApiClient;
#codeSuggestionsContextMap = new Map<string, СodeSuggestionContext>();
#circuitBreaker = new FixedTimeCircuitBreaker('Instance telemetry');
#configService: ConfigService;
#options: ITelemetryOptions = {
enabled: true,
actions: [],
};
#codeSuggestionStates = new Map<string, TRACKING_EVENTS>();
// API used for tracking events is available since GitLab v17.2.0.
// Given the track request is done for each CS request
// we need to make sure we do not log the unsupported instance message many times
#invalidInstanceMsgLogged = false;
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#configService = configService;
this.#configService.onConfigChange((config) => this.#reconfigure(config));
this.#api = api;
}
#reconfigure(config: IConfig) {
const { baseUrl } = config.client;
const enabled = config.client.telemetry?.enabled;
const actions = config.client.telemetry?.actions;
if (typeof enabled !== 'undefined') {
this.#options.enabled = enabled;
if (enabled === false) {
log.warn(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`);
} else if (enabled === true) {
log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`);
}
}
if (baseUrl) {
this.#options.baseUrl = baseUrl;
}
if (actions) {
this.#options.actions = actions;
}
}
isEnabled(): boolean {
return Boolean(this.#options.enabled);
}
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
if (this.#circuitBreaker.isOpen()) {
return;
}
const { language, isStreaming } = context;
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
is_streaming: isStreaming,
language,
timestamp: new Date().toISOString(),
});
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Instance telemetry: Could not track telemetry', e),
);
log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
async updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
if (this.#circuitBreaker.isOpen()) {
return;
}
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, suggestionOptions, isStreaming } = contextUpdate;
if (context) {
if (model) {
context.language = model.lang ?? null;
}
if (suggestionOptions?.length) {
context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions);
}
if (typeof isStreaming === 'boolean') {
context.is_streaming = isStreaming;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
if (this.#circuitBreaker.isOpen()) {
return;
}
if (!this.isEnabled()) return;
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const allowedTransitions = nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Instance telemetry: Could not track telemetry', e),
);
log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
const event = INSTANCE_TRACKING_EVENTS_MAP[eventType];
if (!event) {
return;
}
try {
const { language, suggestion_size } =
this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {};
await this.#api.fetchFromApi({
type: 'rest',
method: 'POST',
path: '/usage_data/track_event',
body: {
event,
additional_properties: {
unique_tracking_id: uniqueTrackingId,
timestamp: new Date().toISOString(),
language,
suggestion_size,
},
},
supportedSinceInstanceVersion: {
resourceName: 'track instance telemetry',
version: '17.2.0',
},
});
this.#circuitBreaker.success();
} catch (error) {
if (error instanceof InvalidInstanceVersionError) {
if (this.#invalidInstanceMsgLogged) return;
this.#invalidInstanceMsgLogged = true;
}
log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error);
this.#circuitBreaker.error();
}
}
rejectOpenedSuggestions() {
log.debug(`Instance Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
static #suggestionSize(options: SuggestionOption[]): number {
const countLines = (text: string) => (text ? text.split('\n').length : 0);
return Math.max(...options.map(({ text }) => countLines(text)));
}
#isStreamingSuggestion(uniqueTrackingId: string): boolean {
return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming);
}
}
References: |
You are a code assistant | Definition of 'error' in file packages/lib_logging/src/types.ts in project gitlab-lsp | Definition:
error(e: Error): void;
error(message: string, e?: Error): void;
}
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 'HandlesNotification' in file src/common/handler.ts in project gitlab-lsp | Definition:
export interface HandlesNotification<P> {
notificationHandler: NotificationHandler<P>;
}
References: |
You are a code assistant | Definition of 'getStreamingCodeSuggestions' in file src/common/api.ts in project gitlab-lsp | Definition:
async *getStreamingCodeSuggestions(
request: CodeSuggestionRequest,
): AsyncGenerator<string, void, void> {
if (!this.#token) {
throw new Error('Token needs to be provided to stream code suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
yield* this.#lsFetch.streamFetch(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
JSON.stringify(request),
headers,
);
}
async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> {
if (!this.#token) {
return Promise.reject(new Error('Token needs to be provided to authorise API request.'));
}
if (
request.supportedSinceInstanceVersion &&
!this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version)
) {
return Promise.reject(
new InvalidInstanceVersionError(
`Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`,
),
);
}
if (request.type === 'graphql') {
return this.#graphqlRequest(request.query, request.variables);
}
switch (request.method) {
case 'GET':
return this.#fetch(request.path, request.searchParams, 'resource', request.headers);
case 'POST':
return this.#postFetch(request.path, 'resource', request.body, request.headers);
default:
// the type assertion is necessary because TS doesn't expect any other types
throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`);
}
}
async connectToCable(): Promise<ActionCableCable> {
const headers = this.#getDefaultHeaders(this.#token);
const websocketOptions = {
headers: {
...headers,
Origin: this.#baseURL,
},
};
return connectToCable(this.#baseURL, websocketOptions);
}
async #graphqlRequest<T = unknown, V extends Variables = Variables>(
document: RequestDocument,
variables?: V,
): Promise<T> {
const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/');
const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab"
const graphqlFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = input instanceof URL ? input.toString() : input;
return this.#lsFetch.post(url, {
...init,
headers: { ...headers, ...init?.headers },
});
};
const headers = this.#getDefaultHeaders(this.#token);
const client = new GraphQLClient(endpoint, {
headers,
fetch: graphqlFetch,
});
return client.request(document, variables);
}
async #fetch<T>(
apiResourcePath: string,
query: Record<string, QueryValue> = {},
resourceName = 'resource',
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`;
const result = await this.#lsFetch.get(url, {
headers: { ...this.#getDefaultHeaders(this.#token), ...headers },
});
await handleFetchError(result, resourceName);
return result.json() as Promise<T>;
}
async #postFetch<T>(
apiResourcePath: string,
resourceName = 'resource',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}`;
const response = await this.#lsFetch.post(url, {
headers: {
'Content-Type': 'application/json',
...this.#getDefaultHeaders(this.#token),
...headers,
},
body: JSON.stringify(body),
});
await handleFetchError(response, resourceName);
return response.json() as Promise<T>;
}
#getDefaultHeaders(token?: string) {
return {
Authorization: `Bearer ${token}`,
'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`,
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
};
}
#instanceVersionHigherOrEqualThen(version: string): boolean {
if (!this.#instanceVersion) return false;
return semverCompare(this.#instanceVersion, version) >= 0;
}
async #getGitLabInstanceVersion(): Promise<string> {
if (!this.#token) {
return '';
}
const headers = this.#getDefaultHeaders(this.#token);
const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, {
headers,
});
const { version } = await response.json();
return version;
}
get instanceVersion() {
return this.#instanceVersion;
}
}
References: |
You are a code assistant | Definition of 'KeysWithOptionalParams' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp | Definition:
type KeysWithOptionalParams<R extends RequestMap> = {
[K in keyof R]: R[K]['params'] extends undefined ? never : K;
}[keyof R];
/**
* Extracts the response payload type from a request type.
* @template {MessagePayload} T
* @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse
*/
export type ExtractRequestResult<T extends RequestMap[keyof RequestMap]> =
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
T['result'] extends undefined ? void : T;
/**
* Interface for publishing requests.
* @interface
* @template {RequestMap} TRequests
*/
export interface RequestPublisher<TRequests extends RequestMap> {
sendRequest<T extends KeysWithOptionalParams<TRequests>>(
type: T,
): Promise<ExtractRequestResult<TRequests[T]>>;
sendRequest<T extends keyof TRequests>(
type: T,
payload: TRequests[T]['params'],
): Promise<ExtractRequestResult<TRequests[T]>>;
}
/**
* Interface for listening to requests.
* @interface
* @template {RequestMap} TRequests
*/
export interface RequestListener<TRequests extends RequestMap> {
onRequest<T extends KeysWithOptionalParams<TRequests>>(
type: T,
handler: () => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
onRequest<T extends keyof TRequests>(
type: T,
handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
}
/**
* Defines the structure for message definitions, including notifications and requests.
*/
export type MessageDefinitions<
TNotifications extends NotificationMap = NotificationMap,
TRequests extends RequestMap = RequestMap,
> = {
notifications: TNotifications;
requests: TRequests;
};
export type MessageMap<
TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
> = {
inbound: TInboundMessageDefinitions;
outbound: TOutboundMessageDefinitions;
};
export interface MessageBus<T extends MessageMap = MessageMap>
extends NotificationPublisher<T['outbound']['notifications']>,
NotificationListener<T['inbound']['notifications']>,
RequestPublisher<T['outbound']['requests']>,
RequestListener<T['inbound']['requests']> {}
References: |
You are a code assistant | Definition of 'withJsonRpcMessageValidation' in file packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.ts in project gitlab-lsp | Definition:
export function withJsonRpcMessageValidation<T>(
validator: MessageValidator<T>,
logger: Logger | undefined,
action: (message: T) => void,
): (message: unknown) => void {
return (message: unknown) => {
if (!validator(message)) {
logger?.error(`Invalid JSON-RPC message: ${JSON.stringify(message)}`);
return;
}
action(message);
};
}
References:
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:38
- packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:35
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:46
- packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:23
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:30
- packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:12 |
You are a code assistant | Definition of 'IIDEInfo' in file src/common/tracking/tracking_types.ts in project gitlab-lsp | Definition:
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/tracking_types.ts:46
- src/common/tracking/tracking_types.ts:55 |
You are a code assistant | Definition of 'TypedGetter' in file src/common/utils/type_utils.d.ts in project gitlab-lsp | Definition:
export interface TypedGetter<T> {
(): T;
<K1 extends keyof T>(key: `${K1 extends string ? K1 : never}`): T[K1];
/*
* from 2nd level down, we need to qualify the values with `NonNullable` utility.
* without doing that, we could possibly end up with a type `never`
* as long as any key in the string concatenation is `never`, the concatenated type becomes `never`
* and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T
*/
<K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`): NonNullable<T[K1]>[K2] | undefined;
<K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>, K3 extends keyof NonNullable<NonNullable<T[K1]>[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`): NonNullable<NonNullable<T[K1]>[K2]>[K3] | undefined;
}
/*
TypedSetter allows type-safe setting of nested properties of an object
*/
// there is no benefit in readability from formatting this type utility
// prettier-ignore
export interface TypedSetter<T> {
<K1 extends keyof T>(key: `${K1 extends string ? K1 : never}`, value: T[K1]): void;
/*
* from 2nd level down, we need to qualify the values with `NonNullable` utility.
* without doing that, we could possibly end up with a type `never`
* as long as any key in the string concatenation is `never`, the concatenated type becomes `never`
* and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T
*/
<K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`, value: T[K1][K2]): void;
<K1 extends keyof T, K2 extends keyof NonNullable<T[K1]>, K3 extends keyof NonNullable<NonNullable<T[K1]>[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`, value: T[K1][K2][K3]): void;
}
References: |
You are a code assistant | Definition of 'Validator' in file packages/lib_di/src/index.ts in project gitlab-lsp | Definition:
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.ts:112
- packages/lib_di/src/index.ts:77
- packages/lib_di/src/index.ts:98 |
You are a code assistant | Definition of 'Log' in file src/common/log.ts in project gitlab-lsp | Definition:
class Log implements ILog {
#configService: ConfigService | undefined;
setup(configService: ConfigService) {
this.#configService = configService;
}
/**
* @param messageOrError can be error (if we don't want to provide any additional info), or a string message
* @param trailingError is an optional error (if messageOrError was a message)
* but we also mention `unknown` type because JS doesn't guarantee that in `catch(e)`,
* the `e` is an `Error`, it can be anything.
* */
#log(
incomingLogLevel: LogLevel,
messageOrError: Error | string,
trailingError?: Error | unknown,
) {
const configuredLevel = this.#configService?.get('client.logLevel');
const shouldShowLog = getNumericMapping(configuredLevel) >= LOG_LEVEL_MAPPING[incomingLogLevel];
if (shouldShowLog) {
logWithLevel(incomingLogLevel, messageOrError, ensureError(trailingError));
}
}
debug(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError);
}
info(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.INFO, messageOrError, trailingError);
}
warn(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError);
}
error(messageOrError: Error | string, trailingError?: Error | unknown) {
this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError);
}
}
// TODO: rename the export and replace usages of `log` with `Log`.
export const log = new Log();
References:
- src/common/log.ts:105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.