instruction
stringclasses 1
value | input
stringlengths 67
168
| output
stringlengths 46
67k
|
---|---|---|
You are a code assistant | Definition of 'register' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp | Definition:
register(key: string, handler: THandler): Disposable {
this.#handlers.set(key, handler);
return {
dispose: () => {
this.#handlers.delete(key);
},
};
}
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 'WebviewPluginSetupParams' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp | Definition:
type WebviewPluginSetupParams<T extends PluginMessageMap> = {
webview: WebviewConnection<{
inbound: T['webviewToPlugin'];
outbound: T['pluginToWebview'];
}>;
extension: MessageBus<{
inbound: T['extensionToPlugin'];
outbound: T['pluginToExtension'];
}>;
};
/**
* The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances.
*
* @template TWebviewPluginMessageMap - Message types recognized by the plugin.
* @param webviewMessageBus - The message bus for communication with individual webview instances.
* @param extensionMessageBus - The message bus for communication with the webview host (extension).
* @returns An optional function to dispose of resources when the plugin is unloaded.
*/
type WebviewPluginSetupFunc<T extends PluginMessageMap> = (
context: WebviewPluginSetupParams<T>,
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
) => Disposable | void;
/**
* The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances.
*
* @template TWebviewPluginMessageMap - Message types recognized by the plugin.
*/
export type WebviewPlugin<
TWebviewPluginMessageMap extends PartialDeep<PluginMessageMap> = PluginMessageMap,
> = {
id: WebviewId;
title: string;
setup: WebviewPluginSetupFunc<CreatePluginMessageMap<TWebviewPluginMessageMap>>;
};
References: |
You are a code assistant | Definition of 'emptyFunctionQueries' in file src/common/tree_sitter/empty_function/empty_function_queries.ts in project gitlab-lsp | Definition:
export const emptyFunctionQueries = {
bash: bashEmptyFunctionQuery,
c: cEmptyFunctionQuery,
cpp: cppEmptyFunctionQuery,
c_sharp: csharpEmptyFunctionQuery,
css: '',
go: goEmptyFunctionQuery,
java: javaEmptyFunctionQuery,
powershell: powershellEmptyFunctionQuery,
python: pythonEmptyFunctionQuery,
scala: scalaEmptyFunctionQuery,
typescript: typescriptEmptyFunctionQuery,
tsx: tsxEmptyFunctionQuery,
javascript: javascriptEmptyFunctionQuery,
kotlin: kotlinEmptyFunctionQuery,
rust: rustEmptyFunctionQuery,
ruby: rubyEmptyFunctionQuery,
vue: vueEmptyFunctionQuery,
// the following languages do not have functions, so queries are empty
yaml: '',
html: '',
json: '',
} satisfies Record<TreeSitterLanguageName, string>;
References: |
You are a code assistant | Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:8 |
You are a code assistant | Definition of 'initialize' in file src/common/fetch.ts in project gitlab-lsp | Definition:
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:17
- src/tests/fixtures/intent/empty_function/ruby.rb:25 |
You are a code assistant | Definition of 'getLanguageNameForFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
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 'dispose' in file src/common/workspace/workspace_service.ts in project gitlab-lsp | Definition:
dispose() {
this.#disposable.dispose();
}
}
References: |
You are a code assistant | Definition of 'TelemetryTracker' in file src/common/tracking/tracking_types.ts in project gitlab-lsp | Definition:
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/connection.ts:20
- src/common/message_handler.ts:34
- src/common/suggestion/suggestion_service.ts:77
- src/common/message_handler.ts:73
- src/common/suggestion/suggestion_service.ts:121
- src/common/suggestion/streaming_handler.ts:43 |
You are a code assistant | Definition of 'Account' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp | Definition:
export type Account = TokenAccount | OAuthAccount;
export const serializeAccountSafe = (account: Account) =>
JSON.stringify(account, ['instanceUrl', 'id', 'username', 'scopes']);
export const makeAccountId = (instanceUrl: string, userId: string | number) =>
`${instanceUrl}|${userId}`;
export const extractUserId = (accountId: string) => accountId.split('|').pop();
References:
- packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:7
- packages/webview_duo_chat/src/plugin/chat_platform.ts:20
- packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:13
- packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts:23
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:29 |
You are a code assistant | Definition of 'constructor' in file src/common/git/ignore_manager.ts in project gitlab-lsp | Definition:
constructor(repoUri: string) {
this.repoUri = repoUri;
this.#ignoreTrie = new IgnoreTrie();
}
async loadIgnoreFiles(files: string[]): Promise<void> {
await this.#loadRootGitignore();
const gitignoreFiles = files.filter(
(file) => path.basename(file) === '.gitignore' && file !== '.gitignore',
);
await Promise.all(gitignoreFiles.map((file) => this.#loadGitignore(file)));
}
async #loadRootGitignore(): Promise<void> {
const rootGitignorePath = path.join(this.repoUri, '.gitignore');
try {
const content = await fs.readFile(rootGitignorePath, 'utf-8');
this.#addPatternsToTrie([], content);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn(`Failed to read root .gitignore file: ${rootGitignorePath}`, error);
}
}
}
async #loadGitignore(filePath: string): Promise<void> {
try {
const content = await fs.readFile(filePath, 'utf-8');
const relativePath = path.relative(this.repoUri, path.dirname(filePath));
const pathParts = relativePath.split(path.sep);
this.#addPatternsToTrie(pathParts, content);
} catch (error) {
console.warn(`Failed to read .gitignore file: ${filePath}`, error);
}
}
#addPatternsToTrie(pathParts: string[], content: string): void {
const patterns = content
.split('\n')
.map((rule) => rule.trim())
.filter((rule) => rule && !rule.startsWith('#'));
for (const pattern of patterns) {
this.#ignoreTrie.addPattern(pathParts, pattern);
}
}
isIgnored(filePath: string): boolean {
const relativePath = path.relative(this.repoUri, filePath);
const pathParts = relativePath.split(path.sep);
return this.#ignoreTrie.isIgnored(pathParts);
}
dispose(): void {
this.#ignoreTrie.dispose();
}
}
References: |
You are a code assistant | Definition of 'postBuildVSCodeCopyFiles' in file scripts/watcher/watch.ts in project gitlab-lsp | Definition:
async function postBuildVSCodeCopyFiles(vsCodePath: string) {
const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`;
try {
await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir);
console.log(successColor, 'Copied files to vscode extension');
} catch (error) {
console.error(errorColor, 'Whoops, something went wrong...');
console.error(error);
}
}
function postBuild() {
const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1];
if (editor === 'vscode') {
const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension';
return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)];
}
console.warn('No editor specified, skipping post-build steps');
return [new Promise<void>((resolve) => resolve())];
}
async function run() {
const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`);
const now = performance.now();
const buildSuccessful = await runBuild();
if (!buildSuccessful) return watchMsg();
await Promise.all(postBuild());
console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`);
watchMsg();
}
let timeout: NodeJS.Timeout | null = null;
const dir = './src';
const watcher = chokidar.watch(dir, {
ignored: /(^|[/\\])\../, // ignore dotfiles
persistent: true,
});
let isReady = false;
watcher
.on('add', async (filePath) => {
if (!isReady) return;
console.log(`File ${filePath} has been added`);
await run();
})
.on('change', async (filePath) => {
if (!isReady) return;
console.log(`File ${filePath} has been changed`);
if (timeout) clearTimeout(timeout);
// We debounce the run function on change events in the case of many files being changed at once
timeout = setTimeout(async () => {
await run();
}, 1000);
})
.on('ready', async () => {
await run();
isReady = true;
})
.on('unlink', (filePath) => console.log(`File ${filePath} has been removed`));
console.log(textColor, 'Starting watcher...');
References:
- scripts/watcher/watch.ts:55 |
You are a code assistant | Definition of 'ClientFeatureFlags' in file src/common/feature_flags.ts in project gitlab-lsp | Definition:
export enum ClientFeatureFlags {
// Should match names found in https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/main/src/common/feature_flags/constants.ts
StreamCodeGenerations = 'streamCodeGenerations',
DuoWorkflow = 'duoWorkflow',
RemoteSecurityScans = 'remoteSecurityScans',
}
export enum InstanceFeatureFlags {
EditorAdvancedContext = 'advanced_context_resolver',
CodeSuggestionsContext = 'code_suggestions_context',
}
export const INSTANCE_FEATURE_FLAG_QUERY = gql`
query featureFlagsEnabled($name: String!) {
featureFlagEnabled(name: $name)
}
`;
export const FeatureFlagService = createInterfaceId<FeatureFlagService>('FeatureFlagService');
export interface FeatureFlagService {
/**
* Checks if a feature flag is enabled on the GitLab instance.
* @see `IGitLabAPI` for how the instance is determined.
* @requires `updateInstanceFeatureFlags` to be called first.
*/
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean;
/**
* Checks if a feature flag is enabled on the client.
* @see `ConfigService` for client configuration.
*/
isClientFlagEnabled(name: ClientFeatureFlags): boolean;
}
@Injectable(FeatureFlagService, [GitLabApiClient, ConfigService])
export class DefaultFeatureFlagService {
#api: GitLabApiClient;
#configService: ConfigService;
#featureFlags: Map<string, boolean> = new Map();
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#api = api;
this.#featureFlags = new Map();
this.#configService = configService;
this.#api.onApiReconfigured(async ({ isInValidState }) => {
if (!isInValidState) return;
await this.#updateInstanceFeatureFlags();
});
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #fetchFeatureFlag(name: string): Promise<boolean> {
try {
const result = await this.#api.fetchFromApi<{ featureFlagEnabled: boolean }>({
type: 'graphql',
query: INSTANCE_FEATURE_FLAG_QUERY,
variables: { name },
});
log.debug(`FeatureFlagService: feature flag ${name} is ${result.featureFlagEnabled}`);
return result.featureFlagEnabled;
} catch (e) {
// FIXME: we need to properly handle graphql errors
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/250
if (e instanceof ClientError) {
const fieldDoesntExistError = e.message.match(/field '([^']+)' doesn't exist on type/i);
if (fieldDoesntExistError) {
// we expect graphql-request to throw an error when the query doesn't exist (eg. GitLab 16.9)
// so we debug to reduce noise
log.debug(`FeatureFlagService: query doesn't exist`, e.message);
} else {
log.error(`FeatureFlagService: error fetching feature flag ${name}`, e);
}
}
return false;
}
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #updateInstanceFeatureFlags(): Promise<void> {
log.debug('FeatureFlagService: populating feature flags');
for (const flag of Object.values(InstanceFeatureFlags)) {
// eslint-disable-next-line no-await-in-loop
this.#featureFlags.set(flag, await this.#fetchFeatureFlag(flag));
}
}
/**
* Checks if a feature flag is enabled on the GitLab instance.
* @see `GitLabApiClient` for how the instance is determined.
* @requires `updateInstanceFeatureFlags` to be called first.
*/
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean {
return this.#featureFlags.get(name) ?? false;
}
/**
* Checks if a feature flag is enabled on the client.
* @see `ConfigService` for client configuration.
*/
isClientFlagEnabled(name: ClientFeatureFlags): boolean {
const value = this.#configService.get('client.featureFlags')?.[name];
return value ?? false;
}
}
References:
- src/common/feature_flags.ts:115
- src/common/feature_flags.ts:38 |
You are a code assistant | Definition of 'fileExistsSync' in file src/tests/int/hasbin.ts in project gitlab-lsp | Definition:
export function fileExistsSync(filePath: string) {
try {
return statSync(filePath).isFile();
} catch (error) {
return false;
}
}
References: |
You are a code assistant | Definition of 'normalizeSshRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp | Definition:
function normalizeSshRemote(remote: string): string {
// Regex to match git SSH remotes with custom port.
// Example: [[email protected]:7999]:group/repo_name.git
// For more information see:
// https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/309
const sshRemoteWithCustomPort = remote.match(`^\\[([a-zA-Z0-9_-]+@.*?):\\d+\\](.*)$`);
if (sshRemoteWithCustomPort) {
return `ssh://${sshRemoteWithCustomPort[1]}/${sshRemoteWithCustomPort[2]}`;
}
// Regex to match git SSH remotes with URL scheme and a custom port
// Example: ssh://[email protected]:2222/fatihacet/gitlab-vscode-extension.git
// For more information see:
// https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/644
const sshRemoteWithSchemeAndCustomPort = remote.match(`^ssh://([a-zA-Z0-9_-]+@.*?):\\d+(.*)$`);
if (sshRemoteWithSchemeAndCustomPort) {
return `ssh://${sshRemoteWithSchemeAndCustomPort[1]}${sshRemoteWithSchemeAndCustomPort[2]}`;
}
// Regex to match git SSH remotes without URL scheme and no custom port
// Example: [email protected]:2222/fatihacet/gitlab-vscode-extension.git
// For more information see this comment:
// https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/611#note_1154175809
const sshRemoteWithPath = remote.match(`([a-zA-Z0-9_-]+@.*?):(.*)`);
if (sshRemoteWithPath) {
return `ssh://${sshRemoteWithPath[1]}/${sshRemoteWithPath[2]}`;
}
if (remote.match(`^[a-zA-Z0-9_-]+@`)) {
// Regex to match gitlab potential starting names for ssh remotes.
return `ssh://${remote}`;
}
return remote;
}
export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined {
const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {};
if (!host || !pathname) {
return undefined;
}
// The instance url might have a custom route, i.e. www.company.com/gitlab. This route is
// optional in the remote url. This regex extracts namespace and project from the remote
// url while ignoring any custom route, if present. For more information see:
// - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11
// - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103
const pathRegExp =
instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : '';
const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`);
if (!match) {
return undefined;
}
const [namespace, projectPath] = match.slice(1, 3);
const namespaceWithPath = `${namespace}/${projectPath}`;
return { host, namespace, projectPath, namespaceWithPath };
}
References:
- src/common/services/git/git_remote_parser.ts:73 |
You are a code assistant | Definition of 'TokenCheckNotificationParams' in file src/common/notifications.ts in project gitlab-lsp | Definition:
export interface TokenCheckNotificationParams {
message?: string;
}
export const TokenCheckNotificationType = new NotificationType<TokenCheckNotificationParams>(
TOKEN_CHECK_NOTIFICATION,
);
// TODO: once the following clients are updated:
//
// - JetBrains: https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/main/src/main/kotlin/com/gitlab/plugin/lsp/GitLabLanguageServer.kt#L16
//
// We should remove the `TextDocument` type from the parameter since it's deprecated
export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri;
export const DidChangeDocumentInActiveEditor =
new NotificationType<DidChangeDocumentInActiveEditorParams>(
'$/gitlab/didChangeDocumentInActiveEditor',
);
References: |
You are a code assistant | Definition of 'isNonEmptyLine' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
function isNonEmptyLine(s: string) {
return s.trim().length > 0;
}
type Required<T> = {
[P in keyof T]-?: T[P];
};
const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = {
enabled: true,
maxSize: 1024 * 1024,
ttl: 60 * 1000,
prefixLines: 1,
suffixLines: 1,
};
export class SuggestionsCache {
#cache: LRUCache<string, SuggestionCacheEntry>;
#configService: ConfigService;
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 'ExtensionMessageHandlerKey' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp | Definition:
export type ExtensionMessageHandlerKey = {
webviewId: WebviewId;
type: string;
};
export class ExtensionMessageHandlerRegistry extends HashedRegistry<ExtensionMessageHandlerKey> {
constructor() {
super((key) => `${key.webviewId}:${key.type}`);
}
}
References: |
You are a code assistant | Definition of 'warn' in file packages/lib_logging/src/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;
}
References: |
You are a code assistant | Definition of 'get' in file src/common/document_transformer_service.ts in project gitlab-lsp | Definition:
get(uri: string): TextDocument | undefined;
getContext(
uri: string,
position: Position,
workspaceFolders: WorkspaceFolder[],
completionContext?: InlineCompletionContext,
): IDocContext | undefined;
transform(context: IDocContext): IDocContext;
}
export const DocumentTransformerService = createInterfaceId<DocumentTransformerService>(
'DocumentTransformerService',
);
@Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor])
export class DefaultDocumentTransformerService implements DocumentTransformerService {
#transformers: IDocTransformer[] = [];
#documents: LsTextDocuments;
constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) {
this.#documents = documents;
this.#transformers.push(secretRedactor);
}
get(uri: string) {
return this.#documents.get(uri);
}
getContext(
uri: string,
position: Position,
workspaceFolders: WorkspaceFolder[],
completionContext?: InlineCompletionContext,
): IDocContext | undefined {
const doc = this.get(uri);
if (doc === undefined) {
return undefined;
}
return this.transform(getDocContext(doc, position, workspaceFolders, completionContext));
}
transform(context: IDocContext): IDocContext {
return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context);
}
}
export function getDocContext(
document: TextDocument,
position: Position,
workspaceFolders: WorkspaceFolder[],
completionContext?: InlineCompletionContext,
): IDocContext {
let prefix: string;
if (completionContext?.selectedCompletionInfo) {
const { selectedCompletionInfo } = completionContext;
const range = sanitizeRange(selectedCompletionInfo.range);
prefix = `${document.getText({
start: document.positionAt(0),
end: range.start,
})}${selectedCompletionInfo.text}`;
} else {
prefix = document.getText({ start: document.positionAt(0), end: position });
}
const suffix = document.getText({
start: position,
end: document.positionAt(document.getText().length),
});
const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders);
const fileRelativePath = getRelativePath(document.uri, workspaceFolder);
return {
prefix,
suffix,
fileRelativePath,
position,
uri: document.uri,
languageId: document.languageId,
workspaceFolder,
};
}
References:
- src/common/utils/headers_to_snowplow_options.ts:20
- src/common/utils/headers_to_snowplow_options.ts:22
- src/common/utils/headers_to_snowplow_options.ts:21
- src/common/config_service.ts:134
- src/common/utils/headers_to_snowplow_options.ts:12 |
You are a code assistant | Definition of 'ContextResolution' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp | Definition:
export type ContextResolution = {
/**
* The uri of the resolution
*/
uri: TextDocument['uri'];
/**
* The type of resolution, either a file or a snippet
* `file` - indicates the content is a whole file
* `snippet` - indicates the content is a snippet of a file
*/
type: 'file' | 'snippet';
/**
* The content of the resolution
*/
content: string;
/**
* relative path of the file
*/
fileRelativePath: string;
/**
* resolution strategy
*/
strategy: 'open_tabs';
/**
* workspace folder for the item
*/
workspaceFolder: WorkspaceFolder;
};
/**
* Resolves additional (or advanced) context for a given `IDocContext`.
* Each resolution strategy will have its own resolver, eg. Open Files (LRU),
* Symbols, EcmaScript Imports, etc
*/
export abstract class AdvancedContextResolver {
abstract buildContext({
documentContext,
}: {
documentContext: IDocContext;
}): AsyncGenerator<ContextResolution>;
}
References:
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:77
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:100 |
You are a code assistant | Definition of 'Notifier' in file src/common/notifier.ts in project gitlab-lsp | Definition:
export interface Notifier<T> {
init(notify: NotifyFn<T>): void;
}
References: |
You are a code assistant | Definition of 'init' in file src/browser/tree_sitter/index.ts in project gitlab-lsp | Definition:
async init(): Promise<void> {
const baseAssetsUrl = this.#configService.get('client.baseAssetsUrl');
this.languages = this.buildTreeSitterInfoByExtMap([
{
name: 'bash',
extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'c',
extensions: ['.c'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'cpp',
extensions: ['.cpp'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-cpp.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-cpp',
},
{
name: 'c_sharp',
extensions: ['.cs'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-c_sharp.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-c-sharp',
},
{
name: 'css',
extensions: ['.css'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-css.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-css',
},
{
name: 'go',
extensions: ['.go'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-go.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-go',
},
{
name: 'html',
extensions: ['.html'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-html.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-html',
},
{
name: 'java',
extensions: ['.java'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-java.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-java',
},
{
name: 'javascript',
extensions: ['.js'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-javascript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-javascript',
},
{
name: 'powershell',
extensions: ['.ps1'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-powershell.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-powershell',
},
{
name: 'python',
extensions: ['.py'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-python.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-python',
},
{
name: 'ruby',
extensions: ['.rb'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-ruby.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-ruby',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'sql',
// extensions: ['.sql'],
// wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-sql.wasm', baseAssetsUrl),
// nodeModulesPath: 'tree-sitter-sql',
// },
{
name: 'scala',
extensions: ['.scala'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-scala.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-scala',
},
{
name: 'typescript',
extensions: ['.ts'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-typescript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-typescript/typescript',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'hcl', // terraform, terragrunt
// extensions: ['.tf', '.hcl'],
// wasmPath: resolveGrammarAbsoluteUrl(
// 'vendor/grammars/tree-sitter-hcl.wasm',
// baseAssetsUrl,
// ),
// nodeModulesPath: 'tree-sitter-hcl',
// },
{
name: 'json',
extensions: ['.json'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-json.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-json',
},
]);
try {
await Parser.init({
locateFile(scriptName: string) {
return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl);
},
});
log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.');
this.loadState = TreeSitterParserLoadState.READY;
} catch (err) {
log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
}
}
References: |
You are a code assistant | Definition of 'LruCache' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp | Definition:
export class LruCache {
#cache: LRUCache<DocumentUri, IDocContext>;
static #instance: LruCache | undefined;
// eslint-disable-next-line no-restricted-syntax
private constructor(maxSize: number) {
this.#cache = new LRUCache<DocumentUri, IDocContext>({
maxSize,
sizeCalculation: (value) => this.#getDocumentSize(value),
});
}
public static getInstance(maxSize: number): LruCache {
if (!LruCache.#instance) {
log.debug('LruCache: initializing');
LruCache.#instance = new LruCache(maxSize);
}
return LruCache.#instance;
}
public static destroyInstance(): void {
LruCache.#instance = undefined;
}
get openFiles() {
return this.#cache;
}
#getDocumentSize(context: IDocContext): number {
const size = getByteSize(`${context.prefix}${context.suffix}`);
return Math.max(1, size);
}
/**
* Update the file in the cache.
* Uses lru-cache under the hood.
*/
updateFile(context: IDocContext) {
return this.#cache.set(context.uri, context);
}
/**
* @returns `true` if the file was deleted, `false` if the file was not found
*/
deleteFile(uri: DocumentUri): boolean {
return this.#cache.delete(uri);
}
/**
* Get the most recently accessed files in the workspace
* @param context - The current document context `IDocContext`
* @param includeCurrentFile - Include the current file in the list of most recent files, default is `true`
*/
mostRecentFiles({
context,
includeCurrentFile = true,
}: {
context?: IDocContext;
includeCurrentFile?: boolean;
}): IDocContext[] {
const files = Array.from(this.#cache.values());
if (includeCurrentFile) {
return files;
}
return files.filter(
(file) =>
context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri,
);
}
}
References:
- src/common/advanced_context/advanced_context_service.test.ts:16
- src/common/advanced_context/lru_cache.ts:29
- src/common/advanced_context/lru_cache.test.ts:40
- src/common/advanced_context/lru_cache.ts:26 |
You are a code assistant | Definition of 'ExtensionConnectionMessageBus' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp | Definition:
export class ExtensionConnectionMessageBus<TMessageMap extends MessageMap = MessageMap>
implements MessageBus<TMessageMap>
{
#webviewId: WebviewId;
#connection: Connection;
#rpcMethods: RpcMethods;
#handlers: Handlers;
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:
- src/common/webview/extension/extension_connection_message_bus_provider.ts:63
- src/common/webview/extension/extension_connection_message_bus.test.ts:17
- src/common/webview/extension/extension_connection_message_bus.test.ts:27 |
You are a code assistant | Definition of 'SocketResponseMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp | Definition:
export type SocketResponseMessage = {
requestId: string;
type: string;
payload: unknown;
success: boolean;
reason?: string | undefined;
};
export function isSocketNotificationMessage(
message: unknown,
): message is SocketNotificationMessage {
return (
typeof message === 'object' &&
message !== null &&
'type' in message &&
typeof message.type === 'string'
);
}
export function isSocketRequestMessage(message: unknown): message is SocketIoRequestMessage {
return (
typeof message === 'object' &&
message !== null &&
'requestId' in message &&
typeof message.requestId === 'string' &&
'type' in message &&
typeof message.type === 'string'
);
}
export function isSocketResponseMessage(message: unknown): message is SocketResponseMessage {
return (
typeof message === 'object' &&
message !== null &&
'requestId' in message &&
typeof message.requestId === 'string'
);
}
References: |
You are a code assistant | Definition of 'WEBVIEW_TITLE' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp | Definition:
export const WEBVIEW_TITLE = 'GitLab Duo Chat';
type Record = {
id: string;
};
export interface GitlabChatSlashCommand {
name: string;
description: string;
shouldSubmit?: boolean;
}
export interface WebViewInitialStateInterface {
slashCommands: GitlabChatSlashCommand[];
}
export type Messages = CreatePluginMessageMap<{
pluginToWebview: {
notifications: {
newRecord: Record;
updateRecord: Record;
setLoadingState: boolean;
cleanChat: undefined;
};
};
webviewToPlugin: {
notifications: {
onReady: undefined;
cleanChat: undefined;
newPrompt: {
record: {
content: string;
};
};
trackFeedback: {
data?: {
extendedTextFeedback: string | null;
feedbackChoices: Array<string> | null;
};
};
};
};
pluginToExtension: {
notifications: {
showErrorMessage: {
message: string;
};
};
};
}>;
References: |
You are a code assistant | Definition of 'GitLabPlatformForAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
export interface GitLabPlatformForAccount extends GitLabPlatformBase {
type: 'account';
project: undefined;
}
export interface GitLabPlatformForProject extends GitLabPlatformBase {
type: 'project';
project: GitLabProject;
}
export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount;
export interface GitLabPlatformManager {
/**
* Returns GitLabPlatform for the active project
*
* This is how we decide what is "active project":
* - if there is only one Git repository opened, we always return GitLab project associated with that repository
* - if there are multiple Git repositories opened, we return the one associated with the active editor
* - if there isn't active editor, we will return undefined if `userInitiated` is false, or we ask user to select one if user initiated is `true`
*
* @param userInitiated - Indicates whether the user initiated the action.
* @returns A Promise that resolves with the fetched GitLabProject or undefined if an active project does not exist.
*/
getForActiveProject(userInitiated: boolean): Promise<GitLabPlatformForProject | undefined>;
/**
* Returns a GitLabPlatform for the active account
*
* This is how we decide what is "active account":
* - If the user has signed in to a single GitLab account, it will return that account.
* - If the user has signed in to multiple GitLab accounts, a UI picker will request the user to choose the desired account.
*/
getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined>;
/**
* onAccountChange indicates that any of the GitLab accounts in the extension has changed.
* This can mean account was removed, added or the account token has been changed.
*/
// onAccountChange: vscode.Event<void>;
getForAllAccounts(): Promise<GitLabPlatformForAccount[]>;
/**
* Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined.
*/
getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>;
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:29
- packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts:16
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:34
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:38
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:70
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:134
- packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:21 |
You are a code assistant | Definition of 'WorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp | Definition:
type WorkspaceService = typeof DefaultWorkspaceService.prototype;
export const WorkspaceService = createInterfaceId<WorkspaceService>('WorkspaceService');
@Injectable(WorkspaceService, [VirtualFileSystemService])
export class DefaultWorkspaceService {
#virtualFileSystemService: DefaultVirtualFileSystemService;
#workspaceFilesMap = new Map<string, FileSet>();
#disposable: { dispose: () => void };
constructor(virtualFileSystemService: DefaultVirtualFileSystemService) {
this.#virtualFileSystemService = virtualFileSystemService;
this.#disposable = this.#setupEventListeners();
}
#setupEventListeners() {
return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => {
switch (eventType) {
case VirtualFileSystemEvents.WorkspaceFilesUpdate:
this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate);
break;
case VirtualFileSystemEvents.WorkspaceFileUpdate:
this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate);
break;
default:
break;
}
});
}
#handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) {
const files: FileSet = new Map();
for (const file of update.files) {
files.set(file.toString(), file);
}
this.#workspaceFilesMap.set(update.workspaceFolder.uri, files);
}
#handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) {
let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri);
if (!files) {
files = new Map();
this.#workspaceFilesMap.set(update.workspaceFolder.uri, files);
}
switch (update.event) {
case 'add':
case 'change':
files.set(update.fileUri.toString(), update.fileUri);
break;
case 'unlink':
files.delete(update.fileUri.toString());
break;
default:
break;
}
}
getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined {
return this.#workspaceFilesMap.get(workspaceFolder.uri);
}
dispose() {
this.#disposable.dispose();
}
}
References: |
You are a code assistant | Definition of 'HashFunc' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp | Definition:
export type HashFunc<K> = (key: K) => string;
export class HashedRegistry<TKey, THandler extends Handler = Handler>
implements HandlerRegistry<TKey, THandler>
{
#hashFunc: HashFunc<TKey>;
#basicRegistry: SimpleRegistry<THandler>;
constructor(hashFunc: HashFunc<TKey>) {
this.#hashFunc = hashFunc;
this.#basicRegistry = new SimpleRegistry<THandler>();
}
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 'fetchFromApi' in file src/common/api.ts in project gitlab-lsp | Definition:
async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> {
if (!this.#token) {
return Promise.reject(new Error('Token needs to be provided to authorise API request.'));
}
if (
request.supportedSinceInstanceVersion &&
!this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version)
) {
return Promise.reject(
new InvalidInstanceVersionError(
`Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`,
),
);
}
if (request.type === 'graphql') {
return this.#graphqlRequest(request.query, request.variables);
}
switch (request.method) {
case 'GET':
return this.#fetch(request.path, request.searchParams, 'resource', request.headers);
case 'POST':
return this.#postFetch(request.path, 'resource', request.body, request.headers);
default:
// the type assertion is necessary because TS doesn't expect any other types
throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`);
}
}
async connectToCable(): Promise<ActionCableCable> {
const headers = this.#getDefaultHeaders(this.#token);
const websocketOptions = {
headers: {
...headers,
Origin: this.#baseURL,
},
};
return connectToCable(this.#baseURL, websocketOptions);
}
async #graphqlRequest<T = unknown, V extends Variables = Variables>(
document: RequestDocument,
variables?: V,
): Promise<T> {
const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/');
const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab"
const graphqlFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = input instanceof URL ? input.toString() : input;
return this.#lsFetch.post(url, {
...init,
headers: { ...headers, ...init?.headers },
});
};
const headers = this.#getDefaultHeaders(this.#token);
const client = new GraphQLClient(endpoint, {
headers,
fetch: graphqlFetch,
});
return client.request(document, variables);
}
async #fetch<T>(
apiResourcePath: string,
query: Record<string, QueryValue> = {},
resourceName = 'resource',
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`;
const result = await this.#lsFetch.get(url, {
headers: { ...this.#getDefaultHeaders(this.#token), ...headers },
});
await handleFetchError(result, resourceName);
return result.json() as Promise<T>;
}
async #postFetch<T>(
apiResourcePath: string,
resourceName = 'resource',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}`;
const response = await this.#lsFetch.post(url, {
headers: {
'Content-Type': 'application/json',
...this.#getDefaultHeaders(this.#token),
...headers,
},
body: JSON.stringify(body),
});
await handleFetchError(response, resourceName);
return response.json() as Promise<T>;
}
#getDefaultHeaders(token?: string) {
return {
Authorization: `Bearer ${token}`,
'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`,
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
};
}
#instanceVersionHigherOrEqualThen(version: string): boolean {
if (!this.#instanceVersion) return false;
return semverCompare(this.#instanceVersion, version) >= 0;
}
async #getGitLabInstanceVersion(): Promise<string> {
if (!this.#token) {
return '';
}
const headers = this.#getDefaultHeaders(this.#token);
const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, {
headers,
});
const { version } = await response.json();
return version;
}
get instanceVersion() {
return this.#instanceVersion;
}
}
References:
- packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11
- packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10 |
You are a code assistant | Definition of 'SuggestionClient' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp | Definition:
export interface SuggestionClient {
getSuggestions(context: SuggestionContext): Promise<SuggestionResponse | undefined>;
}
export type SuggestionClientFn = SuggestionClient['getSuggestions'];
export type SuggestionClientMiddleware = (
context: SuggestionContext,
next: SuggestionClientFn,
) => ReturnType<SuggestionClientFn>;
References:
- src/common/suggestion_client/client_to_middleware.ts:4 |
You are a code assistant | Definition of 'CustomInitializeParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp | Definition:
export type CustomInitializeParams = InitializeParams & {
initializationOptions?: IClientContext;
};
export const WORKFLOW_MESSAGE_NOTIFICATION = '$/gitlab/workflowMessage';
export interface SuggestionServiceOptions {
telemetryTracker: TelemetryTracker;
configService: ConfigService;
api: GitLabApiClient;
connection: Connection;
documentTransformerService: DocumentTransformerService;
treeSitterParser: TreeSitterParser;
featureFlagService: FeatureFlagService;
duoProjectAccessChecker: DuoProjectAccessChecker;
}
export interface ITelemetryNotificationParams {
category: 'code_suggestions';
action: TRACKING_EVENTS;
context: {
trackingId: string;
optionId?: number;
};
}
export interface IStartWorkflowParams {
goal: string;
image: string;
}
export const waitMs = (msToWait: number) =>
new Promise((resolve) => {
setTimeout(resolve, msToWait);
});
/* CompletionRequest represents LS client's request for either completion or inlineCompletion */
export interface CompletionRequest {
textDocument: TextDocumentIdentifier;
position: Position;
token: CancellationToken;
inlineCompletionContext?: InlineCompletionContext;
}
export class DefaultSuggestionService {
readonly #suggestionClientPipeline: SuggestionClientPipeline;
#configService: ConfigService;
#api: GitLabApiClient;
#tracker: TelemetryTracker;
#connection: Connection;
#documentTransformerService: DocumentTransformerService;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#suggestionsCache: SuggestionsCache;
#treeSitterParser: TreeSitterParser;
#duoProjectAccessChecker: DuoProjectAccessChecker;
#featureFlagService: FeatureFlagService;
#postProcessorPipeline = new PostProcessorPipeline();
constructor({
telemetryTracker,
configService,
api,
connection,
documentTransformerService,
featureFlagService,
treeSitterParser,
duoProjectAccessChecker,
}: SuggestionServiceOptions) {
this.#configService = configService;
this.#api = api;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#documentTransformerService = documentTransformerService;
this.#suggestionsCache = new SuggestionsCache(this.#configService);
this.#treeSitterParser = treeSitterParser;
this.#featureFlagService = featureFlagService;
const suggestionClient = new FallbackClient(
new DirectConnectionClient(this.#api, this.#configService),
new DefaultSuggestionClient(this.#api),
);
this.#suggestionClientPipeline = new SuggestionClientPipeline([
clientToMiddleware(suggestionClient),
createTreeSitterMiddleware({
treeSitterParser,
getIntentFn: getIntent,
}),
]);
this.#subscribeToCircuitBreakerEvents();
this.#duoProjectAccessChecker = duoProjectAccessChecker;
}
completionHandler = async (
{ textDocument, position }: CompletionParams,
token: CancellationToken,
): Promise<CompletionItem[]> => {
log.debug('Completion requested');
const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token });
if (suggestionOptions.find(isStream)) {
log.warn(
`Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`,
);
}
return completionOptionMapper(suggestionOptions.filter(isTextSuggestion));
};
#getSuggestionOptions = async (
request: CompletionRequest,
): Promise<SuggestionOptionOrStream[]> => {
const { textDocument, position, token, inlineCompletionContext: context } = request;
const suggestionContext = this.#documentTransformerService.getContext(
textDocument.uri,
position,
this.#configService.get('client.workspaceFolders') ?? [],
context,
);
if (!suggestionContext) {
return [];
}
const cachedSuggestions = this.#useAndTrackCachedSuggestions(
textDocument,
position,
suggestionContext,
context?.triggerKind,
);
if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) {
const options = await this.#handleNonStreamingCompletion(request, suggestionContext);
options.unshift(...(cachedSuggestions ?? []));
(cachedSuggestions ?? []).forEach((cs) =>
this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, {
optionsCount: options.length,
}),
);
return options;
}
if (cachedSuggestions) {
return cachedSuggestions;
}
// debounce
await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS);
if (token.isCancellationRequested) {
log.debug('Debounce triggered for completion');
return [];
}
if (
context &&
shouldRejectCompletionWithSelectedCompletionTextMismatch(
context,
this.#documentTransformerService.get(textDocument.uri),
)
) {
return [];
}
const additionalContexts = await this.#getAdditionalContexts(suggestionContext);
// right now we only support streaming for inlineCompletion
// if the context is present, we know we are handling inline completion
if (
context &&
this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations)
) {
const intentResolution = await this.#getIntent(suggestionContext);
if (intentResolution?.intent === 'generation') {
return this.#handleStreamingInlineCompletion(
suggestionContext,
intentResolution.commentForCursor?.content,
intentResolution.generationType,
additionalContexts,
);
}
}
return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts);
};
inlineCompletionHandler = async (
params: InlineCompletionParams,
token: CancellationToken,
): Promise<InlineCompletionList> => {
log.debug('Inline completion requested');
const options = await this.#getSuggestionOptions({
textDocument: params.textDocument,
position: params.position,
token,
inlineCompletionContext: params.context,
});
return inlineCompletionOptionMapper(params, options);
};
async #handleStreamingInlineCompletion(
context: IDocContext,
userInstruction?: string,
generationType?: GenerationType,
additionalContexts?: AdditionalContext[],
): Promise<StartStreamOption[]> {
if (this.#circuitBreaker.isOpen()) {
log.warn('Stream was not started as the circuit breaker is open.');
return [];
}
const streamId = uniqueId('code-suggestion-stream-');
const uniqueTrackingId = generateUniqueTrackingId();
setTimeout(() => {
log.debug(`Starting to stream (id: ${streamId})`);
const streamingHandler = new DefaultStreamingHandler({
api: this.#api,
circuitBreaker: this.#circuitBreaker,
connection: this.#connection,
documentContext: context,
parser: this.#treeSitterParser,
postProcessorPipeline: this.#postProcessorPipeline,
streamId,
tracker: this.#tracker,
uniqueTrackingId,
userInstruction,
generationType,
additionalContexts,
});
streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e));
}, 0);
return [{ streamId, uniqueTrackingId }];
}
async #handleNonStreamingCompletion(
request: CompletionRequest,
documentContext: IDocContext,
additionalContexts?: AdditionalContext[],
): Promise<SuggestionOption[]> {
const uniqueTrackingId: string = generateUniqueTrackingId();
try {
return await this.#getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
});
} catch (e) {
if (isFetchError(e)) {
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status });
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
this.#circuitBreaker.error();
log.error('Failed to get code suggestions!', e);
return [];
}
}
/**
* FIXME: unify how we get code completion and generation
* so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`)
* */
async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> {
try {
const treeAndLanguage = await this.#treeSitterParser.parseFile(context);
if (!treeAndLanguage) {
return undefined;
}
return await getIntent({
treeAndLanguage,
position: context.position,
prefix: context.prefix,
suffix: context.suffix,
});
} catch (error) {
log.error('Failed to parse with tree sitter', error);
return undefined;
}
}
#trackShowIfNeeded(uniqueTrackingId: string) {
if (
!canClientTrackEvent(
this.#configService.get('client.telemetry.actions'),
TRACKING_EVENTS.SHOWN,
)
) {
/* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server.
Otherwise the server will assume that returned suggestions are shown and tracks the event */
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
}
}
async #getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
}: {
request: CompletionRequest;
uniqueTrackingId: string;
documentContext: IDocContext;
additionalContexts?: AdditionalContext[];
}): Promise<SuggestionOption[]> {
const { textDocument, position, token } = request;
const triggerKind = request.inlineCompletionContext?.triggerKind;
log.info('Suggestion requested.');
if (this.#circuitBreaker.isOpen()) {
log.warn('Code suggestions were not requested as the circuit breaker is open.');
return [];
}
if (!this.#configService.get('client.token')) {
return [];
}
// Do not send a suggestion if content is less than 10 characters
const contentLength =
(documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0);
if (contentLength < 10) {
return [];
}
if (!isAtOrNearEndOfLine(documentContext.suffix)) {
return [];
}
// Creates the suggestion and tracks suggestion_requested
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
triggerKind,
additionalContexts,
});
/** how many suggestion options should we request from the API */
const optionsCount: OptionsCount =
triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1;
const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({
document: documentContext,
projectPath: this.#configService.get('client.projectPath'),
optionsCount,
additionalContexts,
});
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, {
model: suggestionsResponse?.model,
status: suggestionsResponse?.status,
optionsCount: suggestionsResponse?.choices?.length,
isDirectConnection: suggestionsResponse?.isDirectConnection,
});
if (suggestionsResponse?.error) {
throw new Error(suggestionsResponse.error);
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#circuitBreaker.success();
const areSuggestionsNotProvided =
!suggestionsResponse?.choices?.length ||
suggestionsResponse?.choices.every(({ text }) => !text?.length);
const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({
...choice,
index,
uniqueTrackingId,
lang: suggestionsResponse?.model?.lang,
}));
const processedChoices = await this.#postProcessorPipeline.run({
documentContext,
input: suggestionOptions,
type: 'completion',
});
this.#suggestionsCache.addToSuggestionCache({
request: {
document: textDocument,
position,
context: documentContext,
additionalContexts,
},
suggestions: processedChoices,
});
if (token.isCancellationRequested) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
return [];
}
if (areSuggestionsNotProvided) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
return [];
}
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions });
this.#trackShowIfNeeded(uniqueTrackingId);
return processedChoices;
}
dispose() {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
}
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
#useAndTrackCachedSuggestions(
textDocument: TextDocumentIdentifier,
position: Position,
documentContext: IDocContext,
triggerKind?: InlineCompletionTriggerKind,
): SuggestionOption[] | undefined {
const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({
document: textDocument,
position,
context: documentContext,
});
if (suggestionsCache?.options?.length) {
const { uniqueTrackingId, lang } = suggestionsCache.options[0];
const { additionalContexts } = suggestionsCache;
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
source: SuggestionSource.cache,
triggerKind,
suggestionOptions: suggestionsCache?.options,
language: lang,
additionalContexts,
});
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#trackShowIfNeeded(uniqueTrackingId);
return suggestionsCache.options.map((option, index) => ({ ...option, index }));
}
return undefined;
}
async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> {
let additionalContexts: AdditionalContext[] = [];
const advancedContextEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextEnabled) {
const advancedContext = await getAdvancedContext({
documentContext,
dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker },
});
additionalContexts = advancedContextToRequestBody(advancedContext);
}
return additionalContexts;
}
}
References:
- src/common/core/handlers/initialize_handler.ts:26
- src/common/core/handlers/initialize_handler.test.ts:8
- src/tests/int/lsp_client.ts:138
- src/common/test_utils/mocks.ts:27 |
You are a code assistant | Definition of 'setup' in file src/common/connection.ts in project gitlab-lsp | Definition:
export function setup(
telemetryTracker: TelemetryTracker,
connection: Connection,
documentTransformerService: DocumentTransformerService,
apiClient: GitLabApiClient,
featureFlagService: FeatureFlagService,
configService: ConfigService,
{
treeSitterParser,
}: {
treeSitterParser: TreeSitterParser;
},
webviewMetadataProvider: WebviewMetadataProvider | undefined = undefined,
workflowAPI: WorkflowAPI | undefined = undefined,
duoProjectAccessChecker: DuoProjectAccessChecker,
duoProjectAccessCache: DuoProjectAccessCache,
virtualFileSystemService: VirtualFileSystemService,
) {
const suggestionService = new DefaultSuggestionService({
telemetryTracker,
connection,
configService,
api: apiClient,
featureFlagService,
treeSitterParser,
documentTransformerService,
duoProjectAccessChecker,
});
const messageHandler = new MessageHandler({
telemetryTracker,
connection,
configService,
featureFlagService,
duoProjectAccessCache,
virtualFileSystemService,
workflowAPI,
});
connection.onCompletion(suggestionService.completionHandler);
// TODO: does Visual Studio or Neovim need this? VS Code doesn't
connection.onCompletionResolve((item: CompletionItem) => item);
connection.onRequest(InlineCompletionRequest.type, suggestionService.inlineCompletionHandler);
connection.onDidChangeConfiguration(messageHandler.didChangeConfigurationHandler);
connection.onNotification(TELEMETRY_NOTIFICATION, messageHandler.telemetryNotificationHandler);
connection.onNotification(
START_WORKFLOW_NOTIFICATION,
messageHandler.startWorkflowNotificationHandler,
);
connection.onRequest(GET_WEBVIEW_METADATA_REQUEST, () => {
return webviewMetadataProvider?.getMetadata() ?? [];
});
connection.onShutdown(messageHandler.onShutdownHandler);
}
References:
- src/common/connection.test.ts:43
- src/browser/main.ts:122
- src/node/main.ts:197 |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/go_comments.go in project gitlab-lsp | Definition:
func (g Greet) greet() {
// function to greet the user
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:20
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21 |
You are a code assistant | Definition of 'greet4' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
const greet4 = function (name) {
console.log(name);
};
const greet5 = (name) => {};
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:10 |
You are a code assistant | Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp | Definition:
public updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate;
if (context) {
if (model) {
context.data.language = model.lang ?? null;
context.data.model_engine = model.engine ?? null;
context.data.model_name = model.name ?? null;
context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null;
context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null;
context.data.context_tokens_sent =
model.tokens_consumption_metadata?.context_tokens_sent ?? null;
context.data.context_tokens_used =
model.tokens_consumption_metadata?.context_tokens_used ?? null;
}
if (status) {
context.data.api_status_code = status;
}
if (optionsCount) {
context.data.options_count = optionsCount;
}
if (isDirectConnection !== undefined) {
context.data.is_direct_connection = isDirectConnection;
}
if (acceptedOption) {
context.data.accepted_option = acceptedOption;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
if (!this.isEnabled()) {
return;
}
const event: StructuredEvent = {
category: CODE_SUGGESTIONS_CATEGORY,
action: eventType,
label: uniqueTrackingId,
};
try {
const contexts: SelfDescribingJson[] = [this.#clientContext];
const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
if (codeSuggestionContext) {
contexts.push(codeSuggestionContext);
}
const suggestionContextValid = this.#ajv.validate(
CodeSuggestionContextSchema,
codeSuggestionContext?.data,
);
if (!suggestionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
const ideExtensionContextValid = this.#ajv.validate(
IdeExtensionContextSchema,
this.#clientContext?.data,
);
if (!ideExtensionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
await this.#snowplow.trackStructEvent(event, contexts);
} catch (error) {
log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error);
}
}
public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const isStreaming = Boolean(
this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming,
);
const allowedTransitions = isStreaming
? streamingSuggestionStateGraph.get(state)
: nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
rejectOpenedSuggestions() {
log.debug(`Snowplow Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
#hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null {
const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextFeatureFlagsEnabled) {
return Boolean(advancedContexts?.length);
}
return null;
}
#getAdvancedContextData({
additionalContexts,
documentContext,
}: {
additionalContexts?: AdditionalContext[];
documentContext?: IDocContext;
}) {
const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts);
const contentAboveCursorSizeBytes = documentContext?.prefix
? getByteSize(documentContext.prefix)
: 0;
const contentBelowCursorSizeBytes = documentContext?.suffix
? getByteSize(documentContext.suffix)
: 0;
const contextItems: ContextItem[] | null =
additionalContexts?.map((item) => ({
file_extension: item.name.split('.').pop() || '',
type: item.type,
resolution_strategy: item.resolution_strategy,
byte_size: item?.content ? getByteSize(item.content) : 0,
})) ?? null;
const totalContextSizeBytes =
contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0;
return {
totalContextSizeBytes,
contentAboveCursorSizeBytes,
contentBelowCursorSizeBytes,
contextItems,
hasAdvancedContext,
};
}
static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null {
let isInvoked = null;
if (triggerKind === InlineCompletionTriggerKind.Invoked) {
isInvoked = true;
} else if (triggerKind === InlineCompletionTriggerKind.Automatic) {
isInvoked = false;
}
return isInvoked;
}
}
References: |
You are a code assistant | Definition of 'has' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp | Definition:
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 'Greet3' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:34 |
You are a code assistant | Definition of 'AiCompletionResponseParams' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp | Definition:
type AiCompletionResponseParams = {
channel: 'GraphqlChannel';
query: string;
variables: string;
operationName: 'aiCompletionResponse';
};
const AI_MESSAGE_SUBSCRIPTION_QUERY = gql`
subscription aiCompletionResponse(
$userId: UserID
$clientSubscriptionId: String
$aiAction: AiAction
$htmlResponse: Boolean = true
) {
aiCompletionResponse(
userId: $userId
aiAction: $aiAction
clientSubscriptionId: $clientSubscriptionId
) {
id
requestId
content
contentHtml @include(if: $htmlResponse)
errors
role
timestamp
type
chunkId
extras {
sources
}
}
}
`;
export type AiCompletionResponseMessageType = {
requestId: string;
role: string;
content: string;
contentHtml?: string;
timestamp: string;
errors: string[];
extras?: {
sources: object[];
};
chunkId?: number;
type?: string;
};
type AiCompletionResponseResponseType = {
result: {
data: {
aiCompletionResponse: AiCompletionResponseMessageType;
};
};
more: boolean;
};
interface AiCompletionResponseChannelEvents
extends ChannelEvents<AiCompletionResponseResponseType> {
systemMessage: (msg: AiCompletionResponseMessageType) => void;
newChunk: (msg: AiCompletionResponseMessageType) => void;
fullMessage: (msg: AiCompletionResponseMessageType) => void;
}
export class AiCompletionResponseChannel extends Channel<
AiCompletionResponseParams,
AiCompletionResponseResponseType,
AiCompletionResponseChannelEvents
> {
static identifier = 'GraphqlChannel';
constructor(params: AiCompletionResponseInput) {
super({
channel: 'GraphqlChannel',
operationName: 'aiCompletionResponse',
query: AI_MESSAGE_SUBSCRIPTION_QUERY,
variables: JSON.stringify(params),
});
}
receive(message: AiCompletionResponseResponseType) {
if (!message.result.data.aiCompletionResponse) return;
const data = message.result.data.aiCompletionResponse;
if (data.role.toLowerCase() === 'system') {
this.emit('systemMessage', data);
} else if (data.chunkId) {
this.emit('newChunk', data);
} else {
this.emit('fullMessage', data);
}
}
}
References: |
You are a code assistant | Definition of 'broadcast' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'WebviewLocationService' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
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_metadata_provider.ts:13
- src/common/webview/webview_resource_location_service.test.ts:20
- src/node/main.ts:176
- src/common/webview/webview_resource_location_service.test.ts:13
- src/common/webview/webview_metadata_provider.ts:15 |
You are a code assistant | Definition of 'RepositoryFile' in file src/common/git/repository.ts in project gitlab-lsp | Definition:
export type RepositoryFile = {
uri: RepoFileUri;
repositoryUri: RepositoryUri;
isIgnored: boolean;
workspaceFolder: WorkspaceFolder;
};
export class Repository {
workspaceFolder: WorkspaceFolder;
uri: URI;
configFileUri: URI;
#files: Map<string, RepositoryFile>;
#ignoreManager: IgnoreManager;
constructor({
configFileUri,
workspaceFolder,
uri,
ignoreManager,
}: {
workspaceFolder: WorkspaceFolder;
uri: RepositoryUri;
configFileUri: URI;
ignoreManager: IgnoreManager;
}) {
this.workspaceFolder = workspaceFolder;
this.uri = uri;
this.configFileUri = configFileUri;
this.#files = new Map();
this.#ignoreManager = ignoreManager;
}
async addFilesAndLoadGitIgnore(files: URI[]): Promise<void> {
log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`);
await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath));
for (const file of files) {
if (!this.#ignoreManager.isIgnored(file.fsPath)) {
this.#files.set(file.toString(), {
uri: file,
isIgnored: false,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
} else {
this.#files.set(file.toString(), {
uri: file,
isIgnored: true,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
}
}
}
isFileIgnored(filePath: URI): boolean {
return this.#ignoreManager.isIgnored(filePath.fsPath);
}
setFile(fileUri: URI): void {
if (!this.isFileIgnored(fileUri)) {
this.#files.set(fileUri.toString(), {
uri: fileUri,
isIgnored: false,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
} else {
this.#files.set(fileUri.toString(), {
uri: fileUri,
isIgnored: true,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
}
}
getFile(fileUri: string): RepositoryFile | undefined {
return this.#files.get(fileUri);
}
removeFile(fileUri: string): void {
this.#files.delete(fileUri);
}
getFiles(): Map<string, RepositoryFile> {
return this.#files;
}
dispose(): void {
this.#ignoreManager.dispose();
this.#files.clear();
}
}
References:
- src/common/ai_context_management_2/providers/ai_file_context_provider.ts:111 |
You are a code assistant | Definition of 'IgnoreTrie' in file src/common/git/ignore_trie.ts in project gitlab-lsp | Definition:
export class IgnoreTrie {
#children: Map<string, IgnoreTrie>;
#ignoreInstance: Ignore | null;
constructor() {
this.#children = new Map();
this.#ignoreInstance = null;
}
addPattern(pathParts: string[], pattern: string): void {
if (pathParts.length === 0) {
if (!this.#ignoreInstance) {
this.#ignoreInstance = ignore();
}
this.#ignoreInstance.add(pattern);
} else {
const [current, ...rest] = pathParts;
if (!this.#children.has(current)) {
this.#children.set(current, new IgnoreTrie());
}
const child = this.#children.get(current);
if (!child) {
return;
}
child.addPattern(rest, pattern);
}
}
isIgnored(pathParts: string[]): boolean {
if (pathParts.length === 0) {
return false;
}
const [current, ...rest] = pathParts;
if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) {
return true;
}
const child = this.#children.get(current);
if (child) {
return child.isIgnored(rest);
}
return false;
}
dispose(): void {
this.#clear();
}
#clear(): void {
this.#children.forEach((child) => child.#clear());
this.#children.clear();
this.#ignoreInstance = null;
}
#removeChild(key: string): void {
const child = this.#children.get(key);
if (child) {
child.#clear();
this.#children.delete(key);
}
}
#prune(): void {
this.#children.forEach((child, key) => {
if (child.#isEmpty()) {
this.#removeChild(key);
} else {
child.#prune();
}
});
}
#isEmpty(): boolean {
return this.#children.size === 0 && !this.#ignoreInstance;
}
}
References:
- src/common/git/ignore_trie.ts:23
- src/common/git/ignore_manager.ts:6
- src/common/git/ignore_manager.ts:12 |
You are a code assistant | Definition of 'GraphQLRequest' in file src/common/api_types.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'PostRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'DuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp | Definition:
export interface DuoProjectAccessCache {
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[];
updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}): Promise<void>;
onDuoProjectCacheUpdate(listener: () => void): Disposable;
}
export const DuoProjectAccessCache =
createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache');
@Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient])
export class DefaultDuoProjectAccessCache {
#duoProjects: Map<WorkspaceFolderUri, DuoProject[]>;
#eventEmitter = new EventEmitter();
constructor(
private readonly directoryWalker: DirectoryWalker,
private readonly fileResolver: FileResolver,
private readonly api: GitLabApiClient,
) {
this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>();
}
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] {
return this.#duoProjects.get(workspaceFolder.uri) ?? [];
}
async updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}) {
try {
this.#duoProjects.clear();
const duoProjects = await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
return {
workspaceFolder,
projects: await this.#duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}),
};
}),
);
for (const { workspaceFolder, projects } of duoProjects) {
this.#logProjectsInfo(projects, workspaceFolder);
this.#duoProjects.set(workspaceFolder.uri, projects);
}
this.#triggerChange();
} catch (err) {
log.error('DuoProjectAccessCache: failed to update project access cache', err);
}
}
#logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) {
if (!projects.length) {
log.warn(
`DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`,
);
return;
}
log.debug(
`DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`,
);
}
async #duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}: {
workspaceFolder: WorkspaceFolder;
baseUrl: string;
}): Promise<DuoProject[]> {
const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl);
const projects = await Promise.all(
remotes.map(async (remote) => {
const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath);
return {
projectPath: remote.projectPath,
uri: remote.fileUri,
enabled,
host: remote.host,
namespace: remote.namespace,
namespaceWithPath: remote.namespaceWithPath,
} satisfies DuoProject;
}),
);
return projects;
}
async #gitlabRemotesForWorkspaceFolder(
workspaceFolder: WorkspaceFolder,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const paths = await this.directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
filters: {
fileEndsWith: ['/.git/config'],
},
});
const remotes = await Promise.all(
paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)),
);
return remotes.flat();
}
async #gitlabRemotesForFileUri(
fileUri: string,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri);
return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => {
const remote = parseGitLabRemote(remoteUrl, baseUrl);
if (remote) {
acc.push({ ...remote, fileUri });
}
return acc;
}, []);
}
async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> {
try {
const fileString = await this.fileResolver.readFile({ fileUri });
const config = ini.parse(fileString);
return this.#getRemoteUrls(config);
} catch (error) {
log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error);
return [];
}
}
#getRemoteUrls(config: GitConfig): string[] {
return Object.keys(config).reduce<string[]>((acc, section) => {
if (section.startsWith('remote ')) {
acc.push(config[section].url);
}
return acc;
}, []);
}
async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> {
try {
const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({
type: 'graphql',
query: duoFeaturesEnabledQuery,
variables: {
projectPath,
},
} satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>);
return Boolean(response?.project?.duoFeaturesEnabled);
} catch (error) {
log.error(
`DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`,
error,
);
return true;
}
}
onDuoProjectCacheUpdate(
listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void,
): Disposable {
this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener);
return {
dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener),
};
}
#triggerChange() {
this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects);
}
}
References:
- src/common/services/duo_access/project_access_checker.ts:20
- src/common/message_handler.ts:38
- src/common/connection.ts:34
- src/common/services/duo_access/project_access_checker.ts:22
- src/common/message_handler.ts:81
- src/common/services/duo_access/project_access_checker.test.ts:11
- src/common/feature_state/project_duo_acces_check.ts:44 |
You are a code assistant | Definition of 'getParser' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
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 'ConnectionService' in file src/common/connection_service.ts in project gitlab-lsp | Definition:
export const ConnectionService = createInterfaceId<ConnectionService>('ConnectionService');
const createNotifyFn =
<T>(c: LsConnection, method: NotificationType<T>) =>
(param: T) =>
c.sendNotification(method, param);
const createDiagnosticsPublisherFn = (c: LsConnection) => (param: PublishDiagnosticsParams) =>
c.sendDiagnostics(param);
@Injectable(ConnectionService, [
LsConnection,
TokenCheckNotifier,
InitializeHandler,
DidChangeWorkspaceFoldersHandler,
SecurityDiagnosticsPublisher,
DocumentService,
AiContextAggregator,
AiContextManager,
FeatureStateManager,
])
export class DefaultConnectionService implements ConnectionService {
#connection: LsConnection;
#aiContextAggregator: AiContextAggregator;
#aiContextManager: AiContextManager;
constructor(
connection: LsConnection,
tokenCheckNotifier: TokenCheckNotifier,
initializeHandler: InitializeHandler,
didChangeWorkspaceFoldersHandler: DidChangeWorkspaceFoldersHandler,
securityDiagnosticsPublisher: SecurityDiagnosticsPublisher,
documentService: DocumentService,
aiContextAggregator: AiContextAggregator,
aiContextManager: AiContextManager,
featureStateManager: FeatureStateManager,
) {
this.#connection = connection;
this.#aiContextAggregator = aiContextAggregator;
this.#aiContextManager = aiContextManager;
// request handlers
connection.onInitialize(initializeHandler.requestHandler);
// notifiers
this.#initializeNotifier(TokenCheckNotificationType, tokenCheckNotifier);
this.#initializeNotifier(FeatureStateChangeNotificationType, featureStateManager);
// notification handlers
connection.onNotification(DidChangeDocumentInActiveEditor, documentService.notificationHandler);
connection.onNotification(
DidChangeWorkspaceFoldersNotification.method,
didChangeWorkspaceFoldersHandler.notificationHandler,
);
// diagnostics publishers
this.#initializeDiagnosticsPublisher(securityDiagnosticsPublisher);
// custom handlers
this.#setupAiContextHandlers();
}
#initializeNotifier<T>(method: NotificationType<T>, notifier: Notifier<T>) {
notifier.init(createNotifyFn(this.#connection, method));
}
#initializeDiagnosticsPublisher(publisher: DiagnosticsPublisher) {
publisher.init(createDiagnosticsPublisherFn(this.#connection));
}
#setupAiContextHandlers() {
this.#connection.onRequest('$/gitlab/ai-context/query', async (query: AiContextQuery) => {
log.info(`recieved search query ${JSON.stringify(query)}`);
const results = await this.#aiContextAggregator.getContextForQuery(query);
log.info(`got back ${results.length}`);
return results;
});
this.#connection.onRequest('$/gitlab/ai-context/add', async (item: AiContextItem) => {
log.info(`recieved context item add request ${JSON.stringify(item)}`);
return this.#aiContextManager.addItem(item);
});
this.#connection.onRequest('$/gitlab/ai-context/remove', async (id: string) => {
log.info(`recieved context item add request ${JSON.stringify(id)}`);
return this.#aiContextManager.removeItem(id);
});
this.#connection.onRequest('$/gitlab/ai-context/current-items', async () => {
const currentItems = this.#aiContextManager.currentItems();
log.info(`returning ${currentItems.length} current items`);
return currentItems;
});
this.#connection.onRequest('$/gitlab/ai-context/retrieve', async () => {
const items = await this.#aiContextManager.retrieveItems();
log.info(`retrieved ${items.length} current items`);
return items;
});
}
}
References: |
You are a code assistant | Definition of 'COMMAND_FETCH_FROM_API' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`;
export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`;
export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`;
export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`;
// Return type from `COMMAND_FETCH_BUFFER_FROM_API`
export interface VSCodeBuffer {
readonly buffer: Uint8Array;
}
// region: Shared configuration ----------------------------------------
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/config_service.ts in project gitlab-lsp | Definition:
constructor() {
this.#config = {
client: {
baseUrl: GITLAB_API_BASE_URL,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: true,
},
logLevel: LOG_LEVEL.INFO,
ignoreCertificateErrors: false,
httpAgentOptions: {},
},
};
}
get: TypedGetter<IConfig> = (key?: string) => {
return key ? get(this.#config, key) : this.#config;
};
set: TypedSetter<IConfig> = (key: string, value: unknown) => {
set(this.#config, key, value);
this.#triggerChange();
};
onConfigChange(listener: (config: IConfig) => void): Disposable {
this.#eventEmitter.on('configChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('configChange', this.#config);
}
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References: |
You are a code assistant | Definition of 'LsRequestInit' in file src/node/fetch.ts in project gitlab-lsp | Definition:
export interface LsRequestInit extends RequestInit {
agent: ProxyAgent | https.Agent | http.Agent;
}
interface LsAgentOptions {
rejectUnauthorized: boolean;
ca?: Buffer;
cert?: Buffer;
key?: Buffer;
}
/**
* Wrap fetch to support proxy configurations
*/
@Injectable(LsFetch, [])
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/node/fetch.ts:202 |
You are a code assistant | Definition of 'InitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp | Definition:
export const InitializeHandler = createInterfaceId<InitializeHandler>('InitializeHandler');
@Injectable(InitializeHandler, [ConfigService])
export class DefaultInitializeHandler implements InitializeHandler {
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
}
requestHandler: RequestHandler<CustomInitializeParams, InitializeResult, InitializeError> = (
params: CustomInitializeParams,
): InitializeResult => {
const { clientInfo, initializationOptions, workspaceFolders } = params;
this.#configService.set('client.clientInfo', clientInfo);
this.#configService.set('client.workspaceFolders', workspaceFolders);
this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl);
this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo);
this.#configService.set('client.telemetry.extension', initializationOptions?.extension);
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
inlineCompletionProvider: true,
textDocumentSync: TextDocumentSyncKind.Full,
},
};
};
}
References:
- src/common/core/handlers/initialize_handler.test.ts:16
- src/common/connection_service.ts:62 |
You are a code assistant | Definition of 'getWorkflowEvents' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp | Definition:
getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]>;
}
export const workflowPluginFactory = (
graphqlApi: WorkflowGraphQLService,
workflowApi: WorkflowAPI,
connection: Connection,
): WebviewPlugin<DuoWorkflowMessages> => {
return {
id: WEBVIEW_ID,
title: WEBVIEW_TITLE,
setup: ({ webview }) => {
webview.onInstanceConnected((_webviewInstanceId, messageBus) => {
messageBus.onNotification('startWorkflow', async ({ goal, image }) => {
try {
const workflowId = await workflowApi.runWorkflow(goal, image);
messageBus.sendNotification('workflowStarted', workflowId);
await graphqlApi.pollWorkflowEvents(workflowId, messageBus);
} catch (e) {
const error = e as Error;
messageBus.sendNotification('workflowError', error.message);
}
});
messageBus.onNotification('openUrl', async ({ url }) => {
await connection.sendNotification('$/gitlab/openUrl', { url });
});
});
},
};
};
References: |
You are a code assistant | Definition of 'DefaultInitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp | Definition:
export class DefaultInitializeHandler implements InitializeHandler {
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
}
requestHandler: RequestHandler<CustomInitializeParams, InitializeResult, InitializeError> = (
params: CustomInitializeParams,
): InitializeResult => {
const { clientInfo, initializationOptions, workspaceFolders } = params;
this.#configService.set('client.clientInfo', clientInfo);
this.#configService.set('client.workspaceFolders', workspaceFolders);
this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl);
this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo);
this.#configService.set('client.telemetry.extension', initializationOptions?.extension);
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
inlineCompletionProvider: true,
textDocumentSync: TextDocumentSyncKind.Full,
},
};
};
}
References:
- src/common/core/handlers/initialize_handler.test.ts:22 |
You are a code assistant | Definition of 'constructor' in file src/common/message_handler.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'DefaultStreamingHandler' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp | Definition:
export class DefaultStreamingHandler {
#params: StartStreamParams;
constructor(params: StartStreamParams) {
this.#params = params;
}
async startStream() {
return startStreaming(this.#params);
}
}
const startStreaming = async ({
additionalContexts,
api,
circuitBreaker,
connection,
documentContext,
parser,
postProcessorPipeline,
streamId,
tracker,
uniqueTrackingId,
userInstruction,
generationType,
}: StartStreamParams) => {
const language = parser.getLanguageNameForFile(documentContext.fileRelativePath);
tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
additionalContexts,
source: SuggestionSource.network,
language,
isStreaming: true,
});
let streamShown = false;
let suggestionProvided = false;
let streamCancelledOrErrored = false;
const cancellationTokenSource = new CancellationTokenSource();
const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => {
if (stream.id === streamId) {
streamCancelledOrErrored = true;
cancellationTokenSource.cancel();
if (streamShown) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
} else {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
}
}
});
const cancellationToken = cancellationTokenSource.token;
const endStream = async () => {
await connection.sendNotification(StreamingCompletionResponse, {
id: streamId,
done: true,
});
if (!streamCancelledOrErrored) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED);
if (!suggestionProvided) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
}
}
};
circuitBreaker.success();
const request: CodeSuggestionRequest = {
prompt_version: 1,
project_path: '',
project_id: -1,
current_file: {
content_above_cursor: documentContext.prefix,
content_below_cursor: documentContext.suffix,
file_name: documentContext.fileRelativePath,
},
intent: 'generation',
stream: true,
...(additionalContexts?.length && {
context: additionalContexts,
}),
...(userInstruction && {
user_instruction: userInstruction,
}),
generation_type: generationType,
};
const trackStreamStarted = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED);
});
const trackStreamShown = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
streamShown = true;
});
try {
for await (const response of api.getStreamingCodeSuggestions(request)) {
if (cancellationToken.isCancellationRequested) {
break;
}
if (circuitBreaker.isOpen()) {
break;
}
trackStreamStarted();
const processedCompletion = await postProcessorPipeline.run({
documentContext,
input: { id: streamId, completion: response, done: false },
type: 'stream',
});
await connection.sendNotification(StreamingCompletionResponse, processedCompletion);
if (response.replace(/\s/g, '').length) {
trackStreamShown();
suggestionProvided = true;
}
}
} catch (err) {
circuitBreaker.error();
if (isFetchError(err)) {
tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status });
}
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
streamCancelledOrErrored = true;
log.error('Error streaming code suggestions.', err);
} finally {
await endStream();
disposeStopStreaming.dispose();
cancellationTokenSource.dispose();
}
};
References:
- src/common/suggestion/streaming_handler.test.ts:83
- src/common/suggestion/suggestion_service.ts:302 |
You are a code assistant | Definition of 'GitlabRemoteAndFileUri' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp | Definition:
type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string };
export interface GqlProjectWithDuoEnabledInfo {
duoFeaturesEnabled: boolean;
}
export interface DuoProjectAccessCache {
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[];
updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}): Promise<void>;
onDuoProjectCacheUpdate(listener: () => void): Disposable;
}
export const DuoProjectAccessCache =
createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache');
@Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient])
export class DefaultDuoProjectAccessCache {
#duoProjects: Map<WorkspaceFolderUri, DuoProject[]>;
#eventEmitter = new EventEmitter();
constructor(
private readonly directoryWalker: DirectoryWalker,
private readonly fileResolver: FileResolver,
private readonly api: GitLabApiClient,
) {
this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>();
}
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] {
return this.#duoProjects.get(workspaceFolder.uri) ?? [];
}
async updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}) {
try {
this.#duoProjects.clear();
const duoProjects = await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
return {
workspaceFolder,
projects: await this.#duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}),
};
}),
);
for (const { workspaceFolder, projects } of duoProjects) {
this.#logProjectsInfo(projects, workspaceFolder);
this.#duoProjects.set(workspaceFolder.uri, projects);
}
this.#triggerChange();
} catch (err) {
log.error('DuoProjectAccessCache: failed to update project access cache', err);
}
}
#logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) {
if (!projects.length) {
log.warn(
`DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`,
);
return;
}
log.debug(
`DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`,
);
}
async #duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}: {
workspaceFolder: WorkspaceFolder;
baseUrl: string;
}): Promise<DuoProject[]> {
const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl);
const projects = await Promise.all(
remotes.map(async (remote) => {
const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath);
return {
projectPath: remote.projectPath,
uri: remote.fileUri,
enabled,
host: remote.host,
namespace: remote.namespace,
namespaceWithPath: remote.namespaceWithPath,
} satisfies DuoProject;
}),
);
return projects;
}
async #gitlabRemotesForWorkspaceFolder(
workspaceFolder: WorkspaceFolder,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const paths = await this.directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
filters: {
fileEndsWith: ['/.git/config'],
},
});
const remotes = await Promise.all(
paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)),
);
return remotes.flat();
}
async #gitlabRemotesForFileUri(
fileUri: string,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri);
return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => {
const remote = parseGitLabRemote(remoteUrl, baseUrl);
if (remote) {
acc.push({ ...remote, fileUri });
}
return acc;
}, []);
}
async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> {
try {
const fileString = await this.fileResolver.readFile({ fileUri });
const config = ini.parse(fileString);
return this.#getRemoteUrls(config);
} catch (error) {
log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error);
return [];
}
}
#getRemoteUrls(config: GitConfig): string[] {
return Object.keys(config).reduce<string[]>((acc, section) => {
if (section.startsWith('remote ')) {
acc.push(config[section].url);
}
return acc;
}, []);
}
async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> {
try {
const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({
type: 'graphql',
query: duoFeaturesEnabledQuery,
variables: {
projectPath,
},
} satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>);
return Boolean(response?.project?.duoFeaturesEnabled);
} catch (error) {
log.error(
`DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`,
error,
);
return true;
}
}
onDuoProjectCacheUpdate(
listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void,
): Disposable {
this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener);
return {
dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener),
};
}
#triggerChange() {
this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects);
}
}
References: |
You are a code assistant | Definition of 'GitLabPlatformForProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
export interface GitLabPlatformForProject extends GitLabPlatformBase {
type: 'project';
project: GitLabProject;
}
export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount;
export interface GitLabPlatformManager {
/**
* Returns GitLabPlatform for the active project
*
* This is how we decide what is "active project":
* - if there is only one Git repository opened, we always return GitLab project associated with that repository
* - if there are multiple Git repositories opened, we return the one associated with the active editor
* - if there isn't active editor, we will return undefined if `userInitiated` is false, or we ask user to select one if user initiated is `true`
*
* @param userInitiated - Indicates whether the user initiated the action.
* @returns A Promise that resolves with the fetched GitLabProject or undefined if an active project does not exist.
*/
getForActiveProject(userInitiated: boolean): Promise<GitLabPlatformForProject | undefined>;
/**
* Returns a GitLabPlatform for the active account
*
* This is how we decide what is "active account":
* - If the user has signed in to a single GitLab account, it will return that account.
* - If the user has signed in to multiple GitLab accounts, a UI picker will request the user to choose the desired account.
*/
getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined>;
/**
* onAccountChange indicates that any of the GitLab accounts in the extension has changed.
* This can mean account was removed, added or the account token has been changed.
*/
// onAccountChange: vscode.Event<void>;
getForAllAccounts(): Promise<GitLabPlatformForAccount[]>;
/**
* Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined.
*/
getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>;
}
References: |
You are a code assistant | Definition of 'CustomInitializeParams' in file src/common/message_handler.ts in project gitlab-lsp | Definition:
export type CustomInitializeParams = InitializeParams & {
initializationOptions?: IClientContext;
};
export const WORKFLOW_MESSAGE_NOTIFICATION = '$/gitlab/workflowMessage';
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/test_utils/mocks.ts:27
- src/common/core/handlers/initialize_handler.ts:26
- src/common/core/handlers/initialize_handler.test.ts:8
- src/tests/int/lsp_client.ts:138 |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp | Definition:
func greet(name string) {
fmt.Println(name)
}
var greet = func(name string) { }
var greet = func(name string) {
fmt.Println(name)
}
type Greet struct{}
type Greet struct {
name string
}
// empty method declaration
func (g Greet) greet() { }
// non-empty method declaration
func (g Greet) greet() {
fmt.Printf("Hello %s\n", g.name)
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:20
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21 |
You are a code assistant | Definition of 'ISecurityScannerOptions' in file src/common/config_service.ts in project gitlab-lsp | Definition:
export interface ISecurityScannerOptions {
enabled?: boolean;
serviceUrl?: string;
}
export interface IWorkflowSettings {
dockerSocket?: string;
}
export interface IDuoConfig {
enabledWithoutGitlabProject?: boolean;
}
export interface IClientConfig {
/** GitLab API URL used for getting code suggestions */
baseUrl?: string;
/** Full project path. */
projectPath?: string;
/** PAT or OAuth token used to authenticate to GitLab API */
token?: string;
/** The base URL for language server assets in the client-side extension */
baseAssetsUrl?: string;
clientInfo?: IClientInfo;
// FIXME: this key should be codeSuggestions (we have code completion and code generation)
codeCompletion?: ICodeCompletionConfig;
openTabsContext?: boolean;
telemetry?: ITelemetryOptions;
/** Config used for caching code suggestions */
suggestionsCache?: ISuggestionsCacheOptions;
workspaceFolders?: WorkspaceFolder[] | null;
/** Collection of Feature Flag values which are sent from the client */
featureFlags?: Record<string, boolean>;
logLevel?: LogLevel;
ignoreCertificateErrors?: boolean;
httpAgentOptions?: IHttpAgentOptions;
snowplowTrackerOptions?: ISnowplowTrackerOptions;
// TODO: move to `duo`
duoWorkflowSettings?: IWorkflowSettings;
securityScannerOptions?: ISecurityScannerOptions;
duo?: IDuoConfig;
}
export interface IConfig {
// TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig
client: IClientConfig;
}
/**
* ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled)
* TODO: Maybe in the future we would like to separate these two
*/
export interface ConfigService {
get: TypedGetter<IConfig>;
/**
* set sets the property of the config
* the new value completely overrides the old one
*/
set: TypedSetter<IConfig>;
onConfigChange(listener: (config: IConfig) => void): Disposable;
/**
* merge adds `newConfig` properties into existing config, if the
* property is present in both old and new config, `newConfig`
* properties take precedence unless not defined
*
* This method performs deep merge
*
* **Arrays are not merged; they are replaced with the new value.**
*
*/
merge(newConfig: Partial<IConfig>): void;
}
export const ConfigService = createInterfaceId<ConfigService>('ConfigService');
@Injectable(ConfigService, [])
export class DefaultConfigService implements ConfigService {
#config: IConfig;
#eventEmitter = new EventEmitter();
constructor() {
this.#config = {
client: {
baseUrl: GITLAB_API_BASE_URL,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: true,
},
logLevel: LOG_LEVEL.INFO,
ignoreCertificateErrors: false,
httpAgentOptions: {},
},
};
}
get: TypedGetter<IConfig> = (key?: string) => {
return key ? get(this.#config, key) : this.#config;
};
set: TypedSetter<IConfig> = (key: string, value: unknown) => {
set(this.#config, key, value);
this.#triggerChange();
};
onConfigChange(listener: (config: IConfig) => void): Disposable {
this.#eventEmitter.on('configChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('configChange', this.#config);
}
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References:
- src/common/security_diagnostics_publisher.ts:35
- src/common/config_service.ts:74 |
You are a code assistant | Definition of 'GitlabChatSlashCommand' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts in project gitlab-lsp | Definition:
export interface GitlabChatSlashCommand {
name: string;
description: string;
shouldSubmit?: boolean;
}
const ResetCommand: GitlabChatSlashCommand = {
name: '/reset',
description: 'Reset conversation and ignore the previous messages.',
shouldSubmit: true,
};
const CleanCommand: GitlabChatSlashCommand = {
name: '/clear',
description: 'Delete all messages in this conversation.',
};
const TestsCommand: GitlabChatSlashCommand = {
name: '/tests',
description: 'Write tests for the selected snippet.',
};
const RefactorCommand: GitlabChatSlashCommand = {
name: '/refactor',
description: 'Refactor the selected snippet.',
};
const ExplainCommand: GitlabChatSlashCommand = {
name: '/explain',
description: 'Explain the selected snippet.',
};
export const defaultSlashCommands: GitlabChatSlashCommand[] = [
ResetCommand,
CleanCommand,
TestsCommand,
RefactorCommand,
ExplainCommand,
];
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:23
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:13
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:28
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:7
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:18 |
You are a code assistant | Definition of 'updateSuggestionState' in file src/common/tracking/tracking_types.ts in project gitlab-lsp | Definition:
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void;
}
export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker');
References: |
You are a code assistant | Definition of 'initialize' in file src/common/fetch.ts in project gitlab-lsp | Definition:
initialize(): Promise<void>;
destroy(): Promise<void>;
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
updateAgentOptions(options: FetchAgentOptions): void;
streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>;
}
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:25
- src/tests/fixtures/intent/empty_function/ruby.rb:17 |
You are a code assistant | Definition of 'isIgnored' in file src/common/git/ignore_manager.ts in project gitlab-lsp | Definition:
isIgnored(filePath: string): boolean {
const relativePath = path.relative(this.repoUri, filePath);
const pathParts = relativePath.split(path.sep);
return this.#ignoreTrie.isIgnored(pathParts);
}
dispose(): void {
this.#ignoreTrie.dispose();
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp | Definition:
constructor(configService: ConfigService) {
this.#configService = configService;
}
requestHandler: RequestHandler<CustomInitializeParams, InitializeResult, InitializeError> = (
params: CustomInitializeParams,
): InitializeResult => {
const { clientInfo, initializationOptions, workspaceFolders } = params;
this.#configService.set('client.clientInfo', clientInfo);
this.#configService.set('client.workspaceFolders', workspaceFolders);
this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl);
this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo);
this.#configService.set('client.telemetry.extension', initializationOptions?.extension);
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
inlineCompletionProvider: true,
textDocumentSync: TextDocumentSyncKind.Full,
},
};
};
}
References: |
You are a code assistant | Definition of 'dispose' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp | Definition:
dispose(): void {
this.#messageEmitter.removeAllListeners();
this.#disposables.forEach((disposable) => disposable.dispose());
this.#logger?.debug('JsonRpcConnectionTransport disposed');
}
}
References: |
You are a code assistant | Definition of 'createMockFastifyRequest' in file src/node/webview/test-utils/mock_fastify_request.ts in project gitlab-lsp | Definition:
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:
- src/node/webview/handlers/webview_handler.test.ts:21
- src/node/webview/handlers/webview_handler.test.ts:49
- src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:13
- src/node/webview/handlers/webview_handler.test.ts:34 |
You are a code assistant | Definition of 'FeatureFlagService' in file src/common/feature_flags.ts in project gitlab-lsp | Definition:
export const FeatureFlagService = createInterfaceId<FeatureFlagService>('FeatureFlagService');
export interface FeatureFlagService {
/**
* Checks if a feature flag is enabled on the GitLab instance.
* @see `IGitLabAPI` for how the instance is determined.
* @requires `updateInstanceFeatureFlags` to be called first.
*/
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean;
/**
* Checks if a feature flag is enabled on the client.
* @see `ConfigService` for client configuration.
*/
isClientFlagEnabled(name: ClientFeatureFlags): boolean;
}
@Injectable(FeatureFlagService, [GitLabApiClient, ConfigService])
export class DefaultFeatureFlagService {
#api: GitLabApiClient;
#configService: ConfigService;
#featureFlags: Map<string, boolean> = new Map();
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#api = api;
this.#featureFlags = new Map();
this.#configService = configService;
this.#api.onApiReconfigured(async ({ isInValidState }) => {
if (!isInValidState) return;
await this.#updateInstanceFeatureFlags();
});
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #fetchFeatureFlag(name: string): Promise<boolean> {
try {
const result = await this.#api.fetchFromApi<{ featureFlagEnabled: boolean }>({
type: 'graphql',
query: INSTANCE_FEATURE_FLAG_QUERY,
variables: { name },
});
log.debug(`FeatureFlagService: feature flag ${name} is ${result.featureFlagEnabled}`);
return result.featureFlagEnabled;
} catch (e) {
// FIXME: we need to properly handle graphql errors
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/250
if (e instanceof ClientError) {
const fieldDoesntExistError = e.message.match(/field '([^']+)' doesn't exist on type/i);
if (fieldDoesntExistError) {
// we expect graphql-request to throw an error when the query doesn't exist (eg. GitLab 16.9)
// so we debug to reduce noise
log.debug(`FeatureFlagService: query doesn't exist`, e.message);
} else {
log.error(`FeatureFlagService: error fetching feature flag ${name}`, e);
}
}
return false;
}
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #updateInstanceFeatureFlags(): Promise<void> {
log.debug('FeatureFlagService: populating feature flags');
for (const flag of Object.values(InstanceFeatureFlags)) {
// eslint-disable-next-line no-await-in-loop
this.#featureFlags.set(flag, await this.#fetchFeatureFlag(flag));
}
}
/**
* Checks if a feature flag is enabled on the GitLab instance.
* @see `GitLabApiClient` for how the instance is determined.
* @requires `updateInstanceFeatureFlags` to be called first.
*/
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean {
return this.#featureFlags.get(name) ?? false;
}
/**
* Checks if a feature flag is enabled on the client.
* @see `ConfigService` for client configuration.
*/
isClientFlagEnabled(name: ClientFeatureFlags): boolean {
const value = this.#configService.get('client.featureFlags')?.[name];
return value ?? false;
}
}
References:
- src/common/suggestion/suggestion_service.ts:83
- src/common/tracking/snowplow_tracker.ts:152
- src/common/connection.ts:24
- src/common/message_handler.ts:37
- src/common/security_diagnostics_publisher.ts:40
- src/common/suggestion/suggestion_service.ts:137
- src/common/advanced_context/helpers.ts:21
- src/common/security_diagnostics_publisher.ts:37
- src/common/message_handler.ts:83
- src/common/feature_flags.test.ts:13
- src/common/security_diagnostics_publisher.test.ts:19
- src/common/tracking/snowplow_tracker.ts:161
- src/common/tracking/snowplow_tracker.test.ts:76 |
You are a code assistant | Definition of 'AiMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
type AiMessage = SuccessMessage | ErrorMessage;
type ChatInputTemplate = {
query: string;
defaultVariables: {
platformOrigin?: string;
};
};
export class GitLabChatApi {
#cachedActionQuery?: ChatInputTemplate = undefined;
#manager: GitLabPlatformManagerForChat;
constructor(manager: GitLabPlatformManagerForChat) {
this.#manager = manager;
}
async processNewUserPrompt(
question: string,
subscriptionId?: string,
currentFileContext?: GitLabChatFileContext,
): Promise<AiActionResponseType> {
return this.#sendAiAction({
question,
currentFileContext,
clientSubscriptionId: subscriptionId,
});
}
async pullAiMessage(requestId: string, role: string): Promise<AiMessage> {
const response = await pullHandler(() => this.#getAiMessage(requestId, role));
if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']);
return successResponse(response);
}
async cleanChat(): Promise<AiActionResponseType> {
return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN });
}
async #currentPlatform() {
const platform = await this.#manager.getGitLabPlatform();
if (!platform) throw new Error('Platform is missing!');
return platform;
}
async #getAiMessage(requestId: string, role: string): Promise<AiMessageResponseType | undefined> {
const request: GraphQLRequest<AiMessagesResponseType> = {
type: 'graphql',
query: AI_MESSAGES_QUERY,
variables: { requestIds: [requestId], roles: [role.toUpperCase()] },
};
const platform = await this.#currentPlatform();
const history = await platform.fetchFromApi(request);
return history.aiMessages.nodes[0];
}
async subscribeToUpdates(
messageCallback: (message: AiCompletionResponseMessageType) => Promise<void>,
subscriptionId?: string,
) {
const platform = await this.#currentPlatform();
const channel = new AiCompletionResponseChannel({
htmlResponse: true,
userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`,
aiAction: 'CHAT',
clientSubscriptionId: subscriptionId,
});
const cable = await platform.connectToCable();
// we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397
// sometimes a chunk comes after the full message and it broke the chat
let fullMessageReceived = false;
channel.on('newChunk', async (msg) => {
if (fullMessageReceived) {
log.info(`CHAT-DEBUG: full message received, ignoring chunk`);
return;
}
await messageCallback(msg);
});
channel.on('fullMessage', async (message) => {
fullMessageReceived = true;
await messageCallback(message);
if (subscriptionId) {
cable.disconnect();
}
});
cable.subscribe(channel);
}
async #sendAiAction(variables: object): Promise<AiActionResponseType> {
const platform = await this.#currentPlatform();
const { query, defaultVariables } = await this.#actionQuery();
const projectGqlId = await this.#manager.getProjectGqlId();
const request: GraphQLRequest<AiActionResponseType> = {
type: 'graphql',
query,
variables: {
...variables,
...defaultVariables,
resourceId: projectGqlId ?? null,
},
};
return platform.fetchFromApi(request);
}
async #actionQuery(): Promise<ChatInputTemplate> {
if (!this.#cachedActionQuery) {
const platform = await this.#currentPlatform();
try {
const { version } = await platform.fetchFromApi(versionRequest);
this.#cachedActionQuery = ifVersionGte<ChatInputTemplate>(
version,
MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION,
() => CHAT_INPUT_TEMPLATE_17_3_AND_LATER,
() => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER,
);
} catch (e) {
log.debug(`GitLab version check for sending chat failed:`, e as Error);
this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER;
}
}
return this.#cachedActionQuery;
}
}
References: |
You are a code assistant | Definition of 'sendTextDocumentDidClose' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
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 'WebviewInstanceCreatedEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
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:
- packages/lib_webview_transport/src/types.ts:40 |
You are a code assistant | Definition of 'ReadFile' in file src/common/services/fs/file.ts in project gitlab-lsp | Definition:
export interface ReadFile {
fileUri: string;
}
export interface FileResolver {
readFile(_args: ReadFile): Promise<string>;
}
export const FileResolver = createInterfaceId<FileResolver>('FileResolver');
@Injectable(FileResolver, [])
export class EmptyFileResolver {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
readFile(_args: ReadFile): Promise<string> {
return Promise.resolve('');
}
}
References:
- src/common/services/fs/file.ts:16
- src/node/services/fs/file.ts:8
- src/common/services/fs/file.ts:8 |
You are a code assistant | Definition of 'SuggestionCacheEntry' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
export type SuggestionCacheEntry = {
character: number;
suggestions: SuggestionOption[];
additionalContexts?: AdditionalContext[];
currentLine: string;
timesRetrievedByPosition: TimesRetrievedByPosition;
};
export type SuggestionCacheContext = {
document: TextDocumentIdentifier;
context: IDocContext;
position: Position;
additionalContexts?: AdditionalContext[];
};
export type SuggestionCache = {
options: SuggestionOption[];
additionalContexts?: AdditionalContext[];
};
function isNonEmptyLine(s: string) {
return s.trim().length > 0;
}
type Required<T> = {
[P in keyof T]-?: T[P];
};
const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = {
enabled: true,
maxSize: 1024 * 1024,
ttl: 60 * 1000,
prefixLines: 1,
suffixLines: 1,
};
export class SuggestionsCache {
#cache: LRUCache<string, SuggestionCacheEntry>;
#configService: ConfigService;
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 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp | Definition:
warn(): void {
// NOOP
}
error(e: Error): void;
error(message: string, e?: Error | undefined): void;
error(): void {
// NOOP
}
}
References: |
You are a code assistant | Definition of 'info' in file src/common/log.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'constructor' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
constructor(projectAccessCache: DuoProjectAccessCache) {
this.#projectAccessCache = projectAccessCache;
}
/**
* Check if Duo features are enabled for a given DocumentUri.
*
* We match the DocumentUri to the project with the longest path.
* The enabled projects come from the `DuoProjectAccessCache`.
*
* @reference `DocumentUri` is the URI of the document to check. Comes from
* the `TextDocument` object.
*/
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus {
const projects = this.#projectAccessCache.getProjectsForWorkspaceFolder(workspaceFolder);
if (projects.length === 0) {
return DuoProjectStatus.NonGitlabProject;
}
const project = this.#findDeepestProjectByPath(uri, projects);
if (!project) {
return DuoProjectStatus.NonGitlabProject;
}
return project.enabled ? DuoProjectStatus.DuoEnabled : DuoProjectStatus.DuoDisabled;
}
#findDeepestProjectByPath(uri: string, projects: DuoProject[]): DuoProject | undefined {
let deepestProject: DuoProject | undefined;
for (const project of projects) {
if (uri.startsWith(project.uri.replace('.git/config', ''))) {
if (!deepestProject || project.uri.length > deepestProject.uri.length) {
deepestProject = project;
}
}
}
return deepestProject;
}
}
References: |
You are a code assistant | Definition of 'nonStreamingSuggestionStateGraph' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
export const nonStreamingSuggestionStateGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[TRACKING_EVENTS.REQUESTED, [TRACKING_EVENTS.LOADED, TRACKING_EVENTS.ERRORED]],
[
TRACKING_EVENTS.LOADED,
[TRACKING_EVENTS.SHOWN, TRACKING_EVENTS.CANCELLED, TRACKING_EVENTS.NOT_PROVIDED],
],
[TRACKING_EVENTS.SHOWN, [TRACKING_EVENTS.ACCEPTED, TRACKING_EVENTS.REJECTED]],
...endStatesGraph,
]);
export const streamingSuggestionStateGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[
TRACKING_EVENTS.REQUESTED,
[TRACKING_EVENTS.STREAM_STARTED, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.CANCELLED],
],
[
TRACKING_EVENTS.STREAM_STARTED,
[TRACKING_EVENTS.SHOWN, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.STREAM_COMPLETED],
],
[
TRACKING_EVENTS.SHOWN,
[
TRACKING_EVENTS.ERRORED,
TRACKING_EVENTS.STREAM_COMPLETED,
TRACKING_EVENTS.ACCEPTED,
TRACKING_EVENTS.REJECTED,
],
],
[
TRACKING_EVENTS.STREAM_COMPLETED,
[TRACKING_EVENTS.ACCEPTED, TRACKING_EVENTS.REJECTED, TRACKING_EVENTS.NOT_PROVIDED],
],
...endStatesGraph,
]);
export const endStates = [...endStatesGraph].map(([state]) => state);
export const SAAS_INSTANCE_URL = 'https://gitlab.com';
export const TELEMETRY_NOTIFICATION = '$/gitlab/telemetry';
export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions';
export const GC_TIME = 60000;
export const INSTANCE_TRACKING_EVENTS_MAP = {
[TRACKING_EVENTS.REQUESTED]: null,
[TRACKING_EVENTS.LOADED]: null,
[TRACKING_EVENTS.NOT_PROVIDED]: null,
[TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide',
[TRACKING_EVENTS.ERRORED]: null,
[TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide',
[TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide',
[TRACKING_EVENTS.CANCELLED]: null,
[TRACKING_EVENTS.STREAM_STARTED]: null,
[TRACKING_EVENTS.STREAM_COMPLETED]: null,
};
// FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker
export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net';
export const TELEMETRY_DISABLED_WARNING_MSG =
'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.';
export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.';
References: |
You are a code assistant | Definition of 'convertToJavaScriptRegex' in file src/common/secret_redaction/helpers.ts in project gitlab-lsp | Definition:
export const convertToJavaScriptRegex = (pcreRegex: string) => {
// Remove the (?i) flag (case-insensitive) if present
const regexWithoutCaseInsensitiveFlag = pcreRegex.replace(/\(\?i\)/g, '');
// Replace \x60 escape with a backtick
const jsRegex = regexWithoutCaseInsensitiveFlag.replace(/\\x60/g, '`');
return jsRegex;
};
References:
- src/common/secret_redaction/helpers.test.ts:26
- src/common/secret_redaction/helpers.test.ts:8
- src/common/secret_redaction/index.ts:22
- src/common/secret_redaction/helpers.test.ts:17 |
You are a code assistant | Definition of 'readFile' in file src/common/services/fs/file.ts in project gitlab-lsp | Definition:
readFile(_args: ReadFile): Promise<string>;
}
export const FileResolver = createInterfaceId<FileResolver>('FileResolver');
@Injectable(FileResolver, [])
export class EmptyFileResolver {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
readFile(_args: ReadFile): Promise<string> {
return Promise.resolve('');
}
}
References:
- src/tests/int/fetch.test.ts:40
- src/tests/unit/tree_sitter/test_utils.ts:38
- src/tests/int/fetch.test.ts:15
- src/node/services/fs/file.ts:9
- src/node/duo_workflow/desktop_workflow_runner.ts:184
- src/node/duo_workflow/desktop_workflow_runner.ts:137 |
You are a code assistant | Definition of 'SUGGESTION_ACCEPTED_COMMAND' in file src/common/constants.ts in project gitlab-lsp | Definition:
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 'splitTextFileForPosition' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp | Definition:
export const splitTextFileForPosition = (text: string, position: Position) => {
const lines = text.split('\n');
// Ensure the position is within bounds
const maxRow = lines.length - 1;
const row = Math.min(position.line, maxRow);
const maxColumn = lines[row]?.length || 0;
const column = Math.min(position.character, maxColumn);
// Get the part of the current line before the cursor and after the cursor
const prefixLine = lines[row].slice(0, column);
const suffixLine = lines[row].slice(column);
// Combine lines before the current row for the prefix
const prefixLines = lines.slice(0, row).concat(prefixLine);
const prefix = prefixLines.join('\n');
// Combine lines after the current row for the suffix
const suffixLines = [suffixLine].concat(lines.slice(row + 1));
const suffix = suffixLines.join('\n');
return { prefix, suffix };
};
References:
- src/tests/unit/tree_sitter/test_utils.ts:39 |
You are a code assistant | Definition of 'DuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
export const DuoProjectAccessChecker =
createInterfaceId<DuoProjectAccessChecker>('DuoProjectAccessChecker');
@Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache])
export class DefaultDuoProjectAccessChecker {
#projectAccessCache: DuoProjectAccessCache;
constructor(projectAccessCache: DuoProjectAccessCache) {
this.#projectAccessCache = projectAccessCache;
}
/**
* Check if Duo features are enabled for a given DocumentUri.
*
* We match the DocumentUri to the project with the longest path.
* The enabled projects come from the `DuoProjectAccessCache`.
*
* @reference `DocumentUri` is the URI of the document to check. Comes from
* the `TextDocument` object.
*/
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus {
const projects = this.#projectAccessCache.getProjectsForWorkspaceFolder(workspaceFolder);
if (projects.length === 0) {
return DuoProjectStatus.NonGitlabProject;
}
const project = this.#findDeepestProjectByPath(uri, projects);
if (!project) {
return DuoProjectStatus.NonGitlabProject;
}
return project.enabled ? DuoProjectStatus.DuoEnabled : DuoProjectStatus.DuoDisabled;
}
#findDeepestProjectByPath(uri: string, projects: DuoProject[]): DuoProject | undefined {
let deepestProject: DuoProject | undefined;
for (const project of projects) {
if (uri.startsWith(project.uri.replace('.git/config', ''))) {
if (!deepestProject || project.uri.length > deepestProject.uri.length) {
deepestProject = project;
}
}
}
return deepestProject;
}
}
References:
- src/common/advanced_context/advanced_context_factory.ts:24
- src/common/connection.ts:33
- src/common/feature_state/project_duo_acces_check.ts:32
- src/common/advanced_context/advanced_context_filters.test.ts:16
- src/common/advanced_context/advanced_context_filters.ts:14
- src/common/feature_state/project_duo_acces_check.ts:43
- src/common/suggestion/suggestion_service.ts:135
- src/common/ai_context_management_2/policies/duo_project_policy.ts:13
- src/common/suggestion/suggestion_service.ts:84
- src/common/services/duo_access/project_access_checker.test.ts:12 |
You are a code assistant | Definition of 'SimpleRegistry' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp | Definition:
export class SimpleRegistry<THandler extends Handler = Handler>
implements HandlerRegistry<string, THandler>
{
#handlers = new Map<string, THandler>();
get size() {
return this.#handlers.size;
}
register(key: string, handler: THandler): Disposable {
this.#handlers.set(key, handler);
return {
dispose: () => {
this.#handlers.delete(key);
},
};
}
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:
- packages/lib_handler_registry/src/registry/hashed_registry.ts:16
- packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:22
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:28
- packages/lib_handler_registry/src/registry/simple_registry.test.ts:5
- packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:20
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:24
- packages/lib_handler_registry/src/registry/simple_registry.test.ts:8
- packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:18
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:26 |
You are a code assistant | Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
const greet3 = function (name) {};
const greet4 = function (name) {
console.log(name);
};
const greet5 = (name) => {};
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:8 |
You are a code assistant | Definition of 'MOCK_FILE_1' in file src/tests/int/test_utils.ts in project gitlab-lsp | Definition:
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 'COMMAND_MEDIATOR_TOKEN' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`;
export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`;
// Return type from `COMMAND_FETCH_BUFFER_FROM_API`
export interface VSCodeBuffer {
readonly buffer: Uint8Array;
}
// region: Shared configuration ----------------------------------------
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'streamFetch' in file src/browser/fetch.ts in project gitlab-lsp | Definition:
async *streamFetch(
url: string,
body: string,
headers: FetchHeaders,
): AsyncGenerator<string, void, void> {
const response = await this.fetch(url, {
method: 'POST',
headers,
body,
});
await handleFetchError(response, 'Streaming Code Suggestions');
const reader = response?.body?.getReader();
if (!reader) {
return undefined;
}
let buffer = '';
let readResult = await reader.read();
while (!readResult.done) {
// TODO: We should consider streaming the raw bytes instead of the decoded string
const rawContent = new TextDecoder().decode(readResult.value);
buffer += rawContent;
// TODO if we cancel the stream, and nothing will consume it, we probably leave the HTTP connection open :-O
yield buffer;
// eslint-disable-next-line no-await-in-loop
readResult = await reader.read();
}
return undefined;
}
}
References: |
You are a code assistant | Definition of 'error' in file src/common/log_types.ts in project gitlab-lsp | Definition:
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:
- 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 'configureApi' in file src/common/api.ts in project gitlab-lsp | Definition:
async configureApi({
token,
baseUrl = GITLAB_API_BASE_URL,
}: {
token?: string;
baseUrl?: string;
}) {
if (this.#token === token && this.#baseURL === baseUrl) return;
this.#token = token;
this.#baseURL = baseUrl;
const { valid, reason, message } = await this.checkToken(this.#token);
let validationMessage;
if (!valid) {
this.#configService.set('client.token', undefined);
validationMessage = `Token is invalid. ${message}. Reason: ${reason}`;
log.warn(validationMessage);
} else {
log.info('Token is valid');
}
this.#instanceVersion = await this.#getGitLabInstanceVersion();
this.#fireApiReconfigured(valid, validationMessage);
}
#looksLikePatToken(token: string): boolean {
// OAuth tokens will be longer than 42 characters and PATs will be shorter.
return token.length < 42;
}
async #checkPatToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(
`${this.#baseURL}/api/v4/personal_access_tokens/self`,
{ headers },
);
await handleFetchError(response, 'Information about personal access token');
const { active, scopes } = (await response.json()) as PersonalAccessToken;
if (!active) {
return {
valid: false,
reason: 'not_active',
message: 'Token is not active.',
};
}
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async #checkOAuthToken(token: string): Promise<TokenCheckResponse> {
const headers = this.#getDefaultHeaders(token);
const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, {
headers,
});
await handleFetchError(response, 'Information about OAuth token');
const { scope: scopes } = (await response.json()) as OAuthToken;
if (!this.#hasValidScopes(scopes)) {
const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', ');
return {
valid: false,
reason: 'invalid_scopes',
message: `Token has scope(s) ${joinedScopes} (needs 'api').`,
};
}
return { valid: true };
}
async checkToken(token: string = ''): Promise<TokenCheckResponse> {
try {
if (this.#looksLikePatToken(token)) {
log.info('Checking token for PAT validity');
return await this.#checkPatToken(token);
}
log.info('Checking token for OAuth validity');
return await this.#checkOAuthToken(token);
} catch (err) {
log.error('Error performing token check', err);
return {
valid: false,
reason: 'unknown',
message: `Failed to check token: ${err}`,
};
}
}
#hasValidScopes(scopes: string[]): boolean {
return scopes.includes('api');
}
async getCodeSuggestions(
request: CodeSuggestionRequest,
): Promise<CodeSuggestionResponse | undefined> {
if (!this.#token) {
throw new Error('Token needs to be provided to request Code Suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
const response = await this.#lsFetch.post(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
{ headers, body: JSON.stringify(request) },
);
await handleFetchError(response, 'Code Suggestions');
const data = await response.json();
return { ...data, status: response.status };
}
async *getStreamingCodeSuggestions(
request: CodeSuggestionRequest,
): AsyncGenerator<string, void, void> {
if (!this.#token) {
throw new Error('Token needs to be provided to stream code suggestions');
}
const headers = {
...this.#getDefaultHeaders(this.#token),
'Content-Type': 'application/json',
};
yield* this.#lsFetch.streamFetch(
`${this.#baseURL}/api/v4/code_suggestions/completions`,
JSON.stringify(request),
headers,
);
}
async fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType> {
if (!this.#token) {
return Promise.reject(new Error('Token needs to be provided to authorise API request.'));
}
if (
request.supportedSinceInstanceVersion &&
!this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version)
) {
return Promise.reject(
new InvalidInstanceVersionError(
`Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`,
),
);
}
if (request.type === 'graphql') {
return this.#graphqlRequest(request.query, request.variables);
}
switch (request.method) {
case 'GET':
return this.#fetch(request.path, request.searchParams, 'resource', request.headers);
case 'POST':
return this.#postFetch(request.path, 'resource', request.body, request.headers);
default:
// the type assertion is necessary because TS doesn't expect any other types
throw new Error(`Unknown request type ${(request as ApiRequest<unknown>).type}`);
}
}
async connectToCable(): Promise<ActionCableCable> {
const headers = this.#getDefaultHeaders(this.#token);
const websocketOptions = {
headers: {
...headers,
Origin: this.#baseURL,
},
};
return connectToCable(this.#baseURL, websocketOptions);
}
async #graphqlRequest<T = unknown, V extends Variables = Variables>(
document: RequestDocument,
variables?: V,
): Promise<T> {
const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/');
const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. "https://example.com/gitlab"
const graphqlFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = input instanceof URL ? input.toString() : input;
return this.#lsFetch.post(url, {
...init,
headers: { ...headers, ...init?.headers },
});
};
const headers = this.#getDefaultHeaders(this.#token);
const client = new GraphQLClient(endpoint, {
headers,
fetch: graphqlFetch,
});
return client.request(document, variables);
}
async #fetch<T>(
apiResourcePath: string,
query: Record<string, QueryValue> = {},
resourceName = 'resource',
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`;
const result = await this.#lsFetch.get(url, {
headers: { ...this.#getDefaultHeaders(this.#token), ...headers },
});
await handleFetchError(result, resourceName);
return result.json() as Promise<T>;
}
async #postFetch<T>(
apiResourcePath: string,
resourceName = 'resource',
body?: unknown,
headers?: Record<string, string>,
): Promise<T> {
const url = `${this.#baseURL}/api/v4${apiResourcePath}`;
const response = await this.#lsFetch.post(url, {
headers: {
'Content-Type': 'application/json',
...this.#getDefaultHeaders(this.#token),
...headers,
},
body: JSON.stringify(body),
});
await handleFetchError(response, resourceName);
return response.json() as Promise<T>;
}
#getDefaultHeaders(token?: string) {
return {
Authorization: `Bearer ${token}`,
'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`,
'X-Gitlab-Language-Server-Version': getLanguageServerVersion(),
};
}
#instanceVersionHigherOrEqualThen(version: string): boolean {
if (!this.#instanceVersion) return false;
return semverCompare(this.#instanceVersion, version) >= 0;
}
async #getGitLabInstanceVersion(): Promise<string> {
if (!this.#token) {
return '';
}
const headers = this.#getDefaultHeaders(this.#token);
const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, {
headers,
});
const { version } = await response.json();
return version;
}
get instanceVersion() {
return this.#instanceVersion;
}
}
References:
- src/common/api.test.ts:78
- src/common/api.test.ts:134 |
You are a code assistant | Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/go_comments.go:24
- src/tests/fixtures/intent/empty_function/go.go:13
- src/tests/fixtures/intent/empty_function/go.go:23
- src/tests/fixtures/intent/empty_function/ruby.rb:16
- src/tests/fixtures/intent/empty_function/go.go:15
- src/tests/fixtures/intent/empty_function/go.go:20 |
You are a code assistant | Definition of 'FileChangeHandler' in file src/common/services/fs/dir.ts in project gitlab-lsp | Definition:
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:57
- src/common/services/fs/dir.ts:53
- src/common/services/fs/virtual_file_service.ts:50
- src/common/services/fs/dir.ts:35 |
You are a code assistant | Definition of 'constructor' in file src/common/git/ignore_trie.ts in project gitlab-lsp | Definition:
constructor() {
this.#children = new Map();
this.#ignoreInstance = null;
}
addPattern(pathParts: string[], pattern: string): void {
if (pathParts.length === 0) {
if (!this.#ignoreInstance) {
this.#ignoreInstance = ignore();
}
this.#ignoreInstance.add(pattern);
} else {
const [current, ...rest] = pathParts;
if (!this.#children.has(current)) {
this.#children.set(current, new IgnoreTrie());
}
const child = this.#children.get(current);
if (!child) {
return;
}
child.addPattern(rest, pattern);
}
}
isIgnored(pathParts: string[]): boolean {
if (pathParts.length === 0) {
return false;
}
const [current, ...rest] = pathParts;
if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) {
return true;
}
const child = this.#children.get(current);
if (child) {
return child.isIgnored(rest);
}
return false;
}
dispose(): void {
this.#clear();
}
#clear(): void {
this.#children.forEach((child) => child.#clear());
this.#children.clear();
this.#ignoreInstance = null;
}
#removeChild(key: string): void {
const child = this.#children.get(key);
if (child) {
child.#clear();
this.#children.delete(key);
}
}
#prune(): void {
this.#children.forEach((child, key) => {
if (child.#isEmpty()) {
this.#removeChild(key);
} else {
child.#prune();
}
});
}
#isEmpty(): boolean {
return this.#children.size === 0 && !this.#ignoreInstance;
}
}
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() {}
}
class Greet2 {
name: string;
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb: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 'setupWebviewRoutes' in file src/node/webview/routes/webview_routes.ts in project gitlab-lsp | Definition:
export const setupWebviewRoutes = async (
fastify: FastifyInstance,
{ webviewIds, getWebviewResourcePath }: SetupWebviewRoutesOptions,
): Promise<void> => {
await fastify.register(
async (instance) => {
instance.get('/', buildWebviewCollectionMetadataRequestHandler(webviewIds));
instance.get('/:webviewId', buildWebviewRequestHandler(webviewIds, getWebviewResourcePath));
// registering static resources across multiple webviews should not be done in parallel since we need to ensure that the fastify instance has been modified by the static files plugin
for (const webviewId of webviewIds) {
// eslint-disable-next-line no-await-in-loop
await registerStaticPluginSafely(instance, {
root: getWebviewResourcePath(webviewId),
prefix: `/${webviewId}/`,
});
}
},
{ prefix: '/webview' },
);
};
References:
- src/node/webview/routes/webview_routes.test.ts:40
- src/node/webview/routes/webview_routes.test.ts:22
- src/node/webview/webview_fastify_middleware.ts:14
- src/node/webview/routes/webview_routes.test.ts:55 |
You are a code assistant | Definition of 'LsFetch' in file src/common/fetch.ts in project gitlab-lsp | Definition:
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References:
- src/common/tracking/snowplow_tracker.test.ts:70
- src/common/tracking/snowplow/snowplow.ts:69
- src/common/tracking/snowplow_tracker.ts:150
- src/common/api.test.ts:34
- src/common/api.ts:127
- src/node/duo_workflow/desktop_workflow_runner.ts:53
- src/common/tracking/snowplow/snowplow.ts:57
- src/common/api.ts:135
- src/node/duo_workflow/desktop_workflow_runner.ts:47
- src/common/tracking/snowplow_tracker.ts:159
- src/node/duo_workflow/desktop_workflow_runner.test.ts:22
- src/common/tracking/snowplow/snowplow.ts:48 |
You are a code assistant | Definition of 'CANCEL_STREAMING_COMPLETION_NOTIFICATION' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp | Definition:
export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming';
export const StreamingCompletionResponse = new NotificationType<StreamingCompletionResponse>(
STREAMING_COMPLETION_RESPONSE_NOTIFICATION,
);
export const CancelStreaming = new NotificationType<StreamWithId>(
CANCEL_STREAMING_COMPLETION_NOTIFICATION,
);
export interface StartStreamParams {
api: GitLabApiClient;
circuitBreaker: CircuitBreaker;
connection: Connection;
documentContext: IDocContext;
parser: TreeSitterParser;
postProcessorPipeline: PostProcessorPipeline;
streamId: string;
tracker: TelemetryTracker;
uniqueTrackingId: string;
userInstruction?: string;
generationType?: GenerationType;
additionalContexts?: AdditionalContext[];
}
export class DefaultStreamingHandler {
#params: StartStreamParams;
constructor(params: StartStreamParams) {
this.#params = params;
}
async startStream() {
return startStreaming(this.#params);
}
}
const startStreaming = async ({
additionalContexts,
api,
circuitBreaker,
connection,
documentContext,
parser,
postProcessorPipeline,
streamId,
tracker,
uniqueTrackingId,
userInstruction,
generationType,
}: StartStreamParams) => {
const language = parser.getLanguageNameForFile(documentContext.fileRelativePath);
tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
additionalContexts,
source: SuggestionSource.network,
language,
isStreaming: true,
});
let streamShown = false;
let suggestionProvided = false;
let streamCancelledOrErrored = false;
const cancellationTokenSource = new CancellationTokenSource();
const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => {
if (stream.id === streamId) {
streamCancelledOrErrored = true;
cancellationTokenSource.cancel();
if (streamShown) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
} else {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
}
}
});
const cancellationToken = cancellationTokenSource.token;
const endStream = async () => {
await connection.sendNotification(StreamingCompletionResponse, {
id: streamId,
done: true,
});
if (!streamCancelledOrErrored) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED);
if (!suggestionProvided) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
}
}
};
circuitBreaker.success();
const request: CodeSuggestionRequest = {
prompt_version: 1,
project_path: '',
project_id: -1,
current_file: {
content_above_cursor: documentContext.prefix,
content_below_cursor: documentContext.suffix,
file_name: documentContext.fileRelativePath,
},
intent: 'generation',
stream: true,
...(additionalContexts?.length && {
context: additionalContexts,
}),
...(userInstruction && {
user_instruction: userInstruction,
}),
generation_type: generationType,
};
const trackStreamStarted = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED);
});
const trackStreamShown = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
streamShown = true;
});
try {
for await (const response of api.getStreamingCodeSuggestions(request)) {
if (cancellationToken.isCancellationRequested) {
break;
}
if (circuitBreaker.isOpen()) {
break;
}
trackStreamStarted();
const processedCompletion = await postProcessorPipeline.run({
documentContext,
input: { id: streamId, completion: response, done: false },
type: 'stream',
});
await connection.sendNotification(StreamingCompletionResponse, processedCompletion);
if (response.replace(/\s/g, '').length) {
trackStreamShown();
suggestionProvided = true;
}
}
} catch (err) {
circuitBreaker.error();
if (isFetchError(err)) {
tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status });
}
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
streamCancelledOrErrored = true;
log.error('Error streaming code suggestions.', err);
} finally {
await endStream();
disposeStopStreaming.dispose();
cancellationTokenSource.dispose();
}
};
References: |
You are a code assistant | Definition of 'fsPathFromUri' in file src/common/services/fs/utils.ts in project gitlab-lsp | Definition:
export const fsPathFromUri = (uri: DocumentUri): string => {
return URI.parse(uri).fsPath;
};
export const fsPathToUri = (fsPath: string): URI => {
return URI.file(fsPath);
};
export const parseURIString = (uri: string): URI => {
return URI.parse(uri);
};
References:
- src/node/services/fs/file.ts:9
- src/node/services/fs/dir.ts:48
- src/node/services/fs/dir.ts:58 |
You are a code assistant | Definition of 'QueryValue' in file src/common/utils/create_query_string.ts in project gitlab-lsp | Definition:
export type QueryValue = string | boolean | string[] | number | undefined | null;
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: |
You are a code assistant | Definition of 'resolveError' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp | Definition:
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:
- packages/lib_handler_registry/src/registry/simple_registry.ts:39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.