instruction
stringclasses 1
value | input
stringlengths 67
168
| output
stringlengths 46
67k
|
---|---|---|
You are a code assistant | Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References: |
You are a code assistant | Definition of 'DuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
export interface DuoProjectAccessChecker {
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus;
}
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/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
- src/common/advanced_context/advanced_context_factory.ts:24
- src/common/connection.ts:33 |
You are a code assistant | Definition of '_DeepPartialArray' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp | Definition:
interface _DeepPartialArray<T> extends Array<_DeepPartial<T>> {}
// ban-types lint rule disabled so we can use Function from the copied utility-types implementation
// eslint-disable-next-line @typescript-eslint/ban-types
type _DeepPartial<T> = T extends Function
? T
: T extends Array<infer U>
? _DeepPartialArray<U>
: T extends object
? // eslint-disable-next-line no-use-before-define
DeepPartial<T>
: T | undefined;
type DeepPartial<T> = { [P in keyof T]?: _DeepPartial<T[P]> };
export const createFakePartial = <T>(x: DeepPartial<T>): T => x as T;
References: |
You are a code assistant | Definition of 'createFakePartial' in file src/common/test_utils/create_fake_partial.ts in project gitlab-lsp | Definition:
export const createFakePartial = <T>(x: Partial<T>): T => x as T;
References:
- src/common/suggestion_client/default_suggestion_client.test.ts:7
- src/common/suggestion/suggestion_service.test.ts:86
- src/common/tree_sitter/parser.test.ts:127
- src/common/services/duo_access/project_access_checker.test.ts:145
- src/common/tree_sitter/comments/comment_resolver.test.ts:30
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:44
- src/common/suggestion_client/direct_connection_client.test.ts:32
- src/common/suggestion/streaming_handler.test.ts:50
- src/common/feature_state/project_duo_acces_check.test.ts:27
- src/common/document_transformer_service.test.ts:68
- src/node/duo_workflow/desktop_workflow_runner.test.ts:22
- src/common/suggestion/suggestion_service.test.ts:164
- src/common/suggestion/suggestion_service.test.ts:89
- src/common/suggestion/suggestion_service.test.ts:76
- src/common/suggestion_client/direct_connection_client.test.ts:152
- src/common/feature_state/project_duo_acces_check.test.ts:41
- src/common/suggestion_client/fallback_client.test.ts:9
- src/common/advanced_context/advanced_context_factory.test.ts:72
- src/common/fetch_error.test.ts:37
- src/common/suggestion_client/direct_connection_client.test.ts:52
- src/common/suggestion_client/direct_connection_client.test.ts:35
- src/common/feature_state/feature_state_manager.test.ts:34
- src/common/services/duo_access/project_access_checker.test.ts:40
- src/common/api.test.ts:438
- src/common/tree_sitter/comments/comment_resolver.test.ts:31
- src/common/suggestion/suggestion_filter.test.ts:56
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:32
- src/common/services/duo_access/project_access_cache.test.ts:20
- src/common/suggestion_client/fallback_client.test.ts:30
- src/common/feature_state/feature_state_manager.test.ts:55
- src/common/services/duo_access/project_access_checker.test.ts:44
- src/common/suggestion/suggestion_filter.test.ts:77
- src/common/tree_sitter/comments/comment_resolver.test.ts:208
- src/common/tree_sitter/comments/comment_resolver.test.ts:212
- src/common/message_handler.test.ts:215
- src/common/suggestion/suggestion_service.test.ts:84
- src/common/services/duo_access/project_access_checker.test.ts:126
- src/common/connection.test.ts:44
- src/common/advanced_context/advanced_context_service.test.ts:39
- src/common/tracking/instance_tracker.test.ts:32
- src/common/services/duo_access/project_access_checker.test.ts:153
- src/common/services/duo_access/project_access_checker.test.ts:74
- src/common/tree_sitter/parser.test.ts:83
- src/common/suggestion/streaming_handler.test.ts:70
- src/common/tree_sitter/intent_resolver.test.ts:47
- src/common/services/duo_access/project_access_checker.test.ts:157
- src/common/fetch_error.test.ts:7
- src/common/core/handlers/initialize_handler.test.ts:8
- src/common/message_handler.test.ts:204
- src/common/suggestion/suggestion_service.test.ts:108
- src/common/advanced_context/advanced_context_service.test.ts:47
- src/common/suggestion_client/direct_connection_client.test.ts:58
- src/common/suggestion/suggestion_service.test.ts:100
- src/common/tree_sitter/comments/comment_resolver.test.ts:162
- src/common/tree_sitter/comments/comment_resolver.test.ts:27
- src/common/tree_sitter/comments/comment_resolver.test.ts:206
- src/common/feature_flags.test.ts:21
- src/common/message_handler.test.ts:136
- src/common/advanced_context/helpers.test.ts:7
- src/common/message_handler.test.ts:42
- src/common/suggestion/suggestion_service.test.ts:1038
- src/common/suggestion/suggestion_service.test.ts:469
- src/common/tree_sitter/comments/comment_resolver.test.ts:127
- src/common/suggestion/suggestion_service.test.ts:582
- src/common/services/duo_access/project_access_checker.test.ts:66
- src/common/graphql/workflow/service.test.ts:38
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:57
- src/common/tree_sitter/comments/comment_resolver.test.ts:16
- src/common/services/duo_access/project_access_checker.test.ts:100
- src/common/tracking/multi_tracker.test.ts:8
- src/common/suggestion/suggestion_service.test.ts:492
- src/common/advanced_context/advanced_context_service.test.ts:28
- src/common/suggestion_client/suggestion_client_pipeline.test.ts:10
- src/common/connection.test.ts:57
- src/common/suggestion/suggestion_service.test.ts:1073
- src/common/suggestion/streaming_handler.test.ts:46
- src/common/tree_sitter/comments/comment_resolver.test.ts:193
- src/common/suggestion/suggestion_filter.test.ts:57
- src/common/suggestion/suggestion_service.test.ts:756
- src/common/tree_sitter/comments/comment_resolver.test.ts:195
- src/common/advanced_context/advanced_context_factory.test.ts:73
- src/common/tree_sitter/comments/comment_resolver.test.ts:133
- src/common/connection.test.ts:59
- src/node/duo_workflow/desktop_workflow_runner.test.ts:24
- src/common/services/duo_access/project_access_checker.test.ts:122
- src/common/security_diagnostics_publisher.test.ts:51
- src/common/fetch_error.test.ts:21
- src/common/core/handlers/token_check_notifier.test.ts:11
- src/common/message_handler.test.ts:61
- src/common/suggestion/suggestion_service.test.ts:476
- src/common/suggestion_client/create_v2_request.test.ts:8
- src/common/suggestion/suggestion_service.test.ts:199
- src/common/services/duo_access/project_access_cache.test.ts:16
- src/common/advanced_context/advanced_context_service.test.ts:42
- src/common/services/duo_access/project_access_checker.test.ts:24
- src/common/api.test.ts:422
- src/common/security_diagnostics_publisher.test.ts:48
- src/common/suggestion/streaming_handler.test.ts:56
- src/common/tracking/instance_tracker.test.ts:176
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:28
- src/common/suggestion_client/fallback_client.test.ts:12
- src/common/feature_state/project_duo_acces_check.test.ts:35
- src/common/services/duo_access/project_access_checker.test.ts:118
- src/common/suggestion_client/direct_connection_client.test.ts:150
- src/common/feature_state/supported_language_check.test.ts:39
- src/common/services/duo_access/project_access_checker.test.ts:96
- src/common/suggestion_client/direct_connection_client.test.ts:33
- src/node/fetch.test.ts:16
- src/common/suggestion/streaming_handler.test.ts:62
- src/common/suggestion_client/tree_sitter_middleware.test.ts:24
- src/common/api.test.ts:298
- src/common/suggestion/suggestion_service.test.ts:205
- src/common/feature_state/feature_state_manager.test.ts:78
- src/common/suggestion/suggestion_service.test.ts:94
- src/common/suggestion_client/direct_connection_client.test.ts:106
- src/common/suggestion/suggestion_service.test.ts:461
- src/common/suggestion_client/default_suggestion_client.test.ts:11
- src/common/suggestion_client/direct_connection_client.test.ts:103
- src/common/api.test.ts:318
- src/common/services/duo_access/project_access_checker.test.ts:163
- src/common/feature_state/supported_language_check.test.ts:27
- src/common/suggestion/suggestion_service.test.ts:436
- src/common/suggestion_client/create_v2_request.test.ts:10
- src/common/feature_state/project_duo_acces_check.test.ts:32
- src/common/suggestion/suggestion_filter.test.ts:80
- src/common/tree_sitter/comments/comment_resolver.test.ts:164
- src/common/message_handler.test.ts:53
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:74
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:198
- src/common/services/duo_access/project_access_checker.test.ts:48
- src/common/services/duo_access/project_access_checker.test.ts:15
- src/common/advanced_context/advanced_context_service.test.ts:34
- src/common/message_handler.test.ts:57
- src/common/connection.test.ts:48
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:14
- src/common/advanced_context/helpers.test.ts:10
- src/common/connection.test.ts:58
- src/tests/int/lsp_client.ts:38
- src/common/tree_sitter/intent_resolver.test.ts:40
- src/common/connection.test.ts:47
- src/common/graphql/workflow/service.test.ts:35
- src/common/suggestion/suggestion_service.test.ts:983
- src/common/suggestion/suggestion_service.test.ts:105
- src/common/graphql/workflow/service.test.ts:41
- packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:16
- src/common/services/duo_access/project_access_checker.test.ts:70
- src/common/connection.test.ts:31
- src/common/feature_state/project_duo_acces_check.test.ts:23
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:17
- src/common/core/handlers/initialize_handler.test.ts:17
- src/common/feature_state/project_duo_acces_check.test.ts:40
- src/common/tracking/snowplow_tracker.test.ts:82
- src/common/api.test.ts:349
- src/common/tree_sitter/comments/comment_resolver.test.ts:129
- src/common/feature_state/supported_language_check.test.ts:38
- src/common/tracking/snowplow_tracker.test.ts:78
- src/common/suggestion_client/direct_connection_client.test.ts:50
- src/common/tree_sitter/intent_resolver.test.ts:160
- src/common/suggestion/streaming_handler.test.ts:65
- src/tests/int/lsp_client.ts:164
- src/common/suggestion_client/fallback_client.test.ts:8
- src/common/log.test.ts:10
- src/common/services/duo_access/project_access_cache.test.ts:12
- src/common/suggestion_client/fallback_client.test.ts:15
- src/common/test_utils/create_fake_response.ts:18
- src/common/tree_sitter/parser.test.ts:86
- src/common/suggestion_client/fallback_client.test.ts:7
- src/common/suggestion_client/tree_sitter_middleware.test.ts:33
- src/common/feature_flags.test.ts:17
- src/common/services/duo_access/project_access_checker.test.ts:148
- src/common/suggestion/suggestion_service.test.ts:193
- src/common/suggestion/suggestion_service.test.ts:1054
- src/common/connection.test.ts:53
- src/common/suggestion/streaming_handler.test.ts:75
- src/common/suggestion/suggestion_service.test.ts:464
- src/common/advanced_context/advanced_context_service.test.ts:53
- src/common/feature_state/feature_state_manager.test.ts:21
- src/common/message_handler.test.ts:48
- src/common/document_service.test.ts:8
- src/common/services/duo_access/project_access_checker.test.ts:92
- src/common/tree_sitter/comments/comment_resolver.test.ts:199
- src/common/suggestion_client/tree_sitter_middleware.test.ts:86
- src/common/suggestion/suggestion_service.test.ts:190
- src/common/suggestion/suggestion_filter.test.ts:79
- src/common/feature_flags.test.ts:93
- src/common/advanced_context/advanced_context_service.test.ts:50
- src/common/message_handler.test.ts:64
- src/common/suggestion/suggestion_filter.test.ts:35
- src/common/suggestion/suggestion_service.test.ts:770
- src/common/api.test.ts:406
- src/common/tracking/instance_tracker.test.ts:179
- src/common/suggestion_client/default_suggestion_client.test.ts:24
- src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:31
- src/common/suggestion_client/tree_sitter_middleware.test.ts:62
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:199
- src/common/suggestion_client/fallback_client.test.ts:27
- src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:24 |
You are a code assistant | Definition of 'generateGreetings' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References: |
You are a code assistant | Definition of 'greet_generator' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp | Definition:
def greet_generator
yield 'Hello'
end
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:40 |
You are a code assistant | Definition of 'shouldUseAdvancedContext' in file src/common/advanced_context/helpers.ts in project gitlab-lsp | Definition:
export const shouldUseAdvancedContext = (
featureFlagService: FeatureFlagService,
configService: ConfigService,
) => {
const isEditorAdvancedContextEnabled = featureFlagService.isInstanceFlagEnabled(
InstanceFeatureFlags.EditorAdvancedContext,
);
const isGenericContextEnabled = featureFlagService.isInstanceFlagEnabled(
InstanceFeatureFlags.CodeSuggestionsContext,
);
let isEditorOpenTabsContextEnabled = configService.get('client.openTabsContext');
if (isEditorOpenTabsContextEnabled === undefined) {
isEditorOpenTabsContextEnabled = true;
}
/**
* TODO - when we introduce other context resolution strategies,
* have `isEditorOpenTabsContextEnabled` only disable the corresponding resolver (`lruResolver`)
* https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/298
* https://gitlab.com/groups/gitlab-org/editor-extensions/-/epics/59#note_1981542181
*/
return (
isEditorAdvancedContextEnabled && isGenericContextEnabled && isEditorOpenTabsContextEnabled
);
};
References:
- src/common/suggestion/suggestion_service.ts:544
- src/common/advanced_context/helpers.test.ts:49
- src/common/tracking/snowplow_tracker.ts:467 |
You are a code assistant | Definition of 'Snowplow' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp | Definition:
export class Snowplow {
/** Disable sending events when it's not possible. */
disabled: boolean = false;
#emitter: Emitter;
#lsFetch: LsFetch;
#options: SnowplowOptions;
#tracker: TrackerCore;
static #instance?: Snowplow;
// eslint-disable-next-line no-restricted-syntax
private constructor(lsFetch: LsFetch, options: SnowplowOptions) {
this.#lsFetch = lsFetch;
this.#options = options;
this.#emitter = new Emitter(
this.#options.timeInterval,
this.#options.maxItems,
this.#sendEvent.bind(this),
);
this.#emitter.start();
this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) });
}
public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow {
if (!this.#instance) {
if (!options) {
throw new Error('Snowplow should be instantiated');
}
const sp = new Snowplow(lsFetch, options);
Snowplow.#instance = sp;
}
// FIXME: this eslint violation was introduced before we set up linting
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return Snowplow.#instance!;
}
async #sendEvent(events: PayloadBuilder[]): Promise<void> {
if (!this.#options.enabled() || this.disabled) {
return;
}
try {
const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`;
const data = {
schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4',
data: events.map((event) => {
const eventId = uuidv4();
// All values prefilled below are part of snowplow tracker protocol
// https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters
// Values are set according to either common GitLab standard:
// tna - representing tracker namespace and being set across GitLab to "gl"
// tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with "js-*""
// aid - represents app Id is configured via options to gitlab_ide_extension
// eid - represents uuid for each emitted event
event.add('eid', eventId);
event.add('p', 'app');
event.add('tv', 'js-gitlab');
event.add('tna', 'gl');
event.add('aid', this.#options.appId);
return preparePayload(event.build());
}),
};
const config = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
};
const response = await this.#lsFetch.post(url, config);
if (response.status !== 200) {
log.warn(
`Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`,
);
}
} catch (error) {
let errorHandled = false;
if (typeof error === 'object' && 'errno' in (error as object)) {
const errObject = error as object;
// ENOTFOUND occurs when the snowplow hostname cannot be resolved.
if ('errno' in errObject && errObject.errno === 'ENOTFOUND') {
this.disabled = true;
errorHandled = true;
log.info('Disabling telemetry, unable to resolve endpoint address.');
} else {
log.warn(JSON.stringify(errObject));
}
}
if (!errorHandled) {
log.warn('Failed to send telemetry event, this warning can be safely ignored');
log.warn(JSON.stringify(error));
}
}
}
public async trackStructEvent(
event: StructuredEvent,
context?: SelfDescribingJson[] | null,
): Promise<void> {
this.#tracker.track(buildStructEvent(event), context);
}
async stop() {
await this.#emitter.stop();
}
public destroy() {
Snowplow.#instance = undefined;
}
}
References:
- src/common/tracking/snowplow/snowplow.ts:74
- src/common/tracking/snowplow/snowplow.ts:54
- src/common/tracking/snowplow/snowplow.ts:69
- src/common/tracking/snowplow_tracker.ts:127 |
You are a code assistant | Definition of 'HostConfig' in file packages/lib_webview_client/src/types.ts in project gitlab-lsp | Definition:
export interface HostConfig<WebviewMessageMap extends MessageMap = MessageMap> {
host: MessageBus<WebviewMessageMap>;
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp | Definition:
constructor(
documentService: DocumentService,
supportedLanguagesService: SupportedLanguagesService,
) {
this.#documentService = documentService;
this.#supportedLanguagesService = supportedLanguagesService;
this.#documentService.onDocumentChange((event, handlerType) => {
if (handlerType === TextDocumentChangeListenerType.onDidSetActive) {
this.#updateWithDocument(event.document);
}
});
this.#supportedLanguagesService.onLanguageChange(() => this.#update());
}
onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable {
this.#stateEmitter.on('change', listener);
return {
dispose: () => this.#stateEmitter.removeListener('change', listener),
};
}
#updateWithDocument(document: TextDocument) {
this.#currentDocument = document;
this.#update();
}
get engaged() {
return !this.#isLanguageEnabled;
}
get id() {
return this.#isLanguageSupported && !this.#isLanguageEnabled
? DISABLED_LANGUAGE
: UNSUPPORTED_LANGUAGE;
}
details = 'Code suggestions are not supported for this language';
#update() {
this.#checkLanguage();
this.#stateEmitter.emit('change', this);
}
#checkLanguage() {
if (!this.#currentDocument) {
this.#isLanguageEnabled = false;
this.#isLanguageSupported = false;
return;
}
const { languageId } = this.#currentDocument;
this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId);
this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId);
}
}
References: |
You are a code assistant | Definition of 'WebviewInstanceRequestEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
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:49
- packages/lib_webview_transport/src/types.ts:43 |
You are a code assistant | Definition of 'GitLabPlatformManagerForChat' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp | Definition:
export class GitLabPlatformManagerForChat {
readonly #platformManager: GitLabPlatformManager;
constructor(platformManager: GitLabPlatformManager) {
this.#platformManager = platformManager;
}
async getProjectGqlId(): Promise<string | undefined> {
const projectManager = await this.#platformManager.getForActiveProject(false);
return projectManager?.project.gqlId;
}
/**
* Obtains a GitLab Platform to send API requests to the GitLab API
* for the Duo Chat feature.
*
* - It returns a GitLabPlatformForAccount for the first linked account.
* - It returns undefined if there are no accounts linked
*/
async getGitLabPlatform(): Promise<GitLabPlatformForAccount | undefined> {
const platforms = await this.#platformManager.getForAllAccounts();
if (!platforms.length) {
return undefined;
}
let platform: GitLabPlatformForAccount | undefined;
// Using a for await loop in this context because we want to stop
// evaluating accounts as soon as we find one with code suggestions enabled
for await (const result of platforms.map(getChatSupport)) {
if (result.hasSupportForChat) {
platform = result.platform;
break;
}
}
return platform;
}
async getGitLabEnvironment(): Promise<GitLabEnvironment> {
const platform = await this.getGitLabPlatform();
const instanceUrl = platform?.account.instanceUrl;
switch (instanceUrl) {
case GITLAB_COM_URL:
return GitLabEnvironment.GITLAB_COM;
case GITLAB_DEVELOPMENT_URL:
return GitLabEnvironment.GITLAB_DEVELOPMENT;
case GITLAB_STAGING_URL:
return GitLabEnvironment.GITLAB_STAGING;
case GITLAB_ORG_URL:
return GitLabEnvironment.GITLAB_ORG;
default:
return GitLabEnvironment.GITLAB_SELF_MANAGED;
}
}
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:50
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:51
- packages/webview_duo_chat/src/plugin/index.ts:19
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:26
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:150
- packages/webview_duo_chat/src/plugin/chat_controller.ts:20
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:58
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:152 |
You are a code assistant | Definition of 'createFakeFetchFromApi' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts in project gitlab-lsp | Definition:
export const createFakeFetchFromApi =
(...handlers: FakeRequestHandler<unknown>[]): fetchFromApi =>
async <T>(request: ApiRequest<T>) => {
const handler = handlers.find((h) => isEqual(h.request, request));
if (!handler) {
throw new Error(`No fake handler to handle request: ${JSON.stringify(request)}`);
}
return handler.response as T;
};
References:
- packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:25 |
You are a code assistant | Definition of 'retrieveItems' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp | Definition:
async retrieveItems(): Promise<AiContextItemWithContent[]> {
const items = Array.from(this.#items.values());
log.info(`Retrieving ${items.length} items`);
const retrievedItems = await Promise.all(
items.map(async (item) => {
try {
switch (item.type) {
case 'file': {
const content = await this.#fileRetriever.retrieve(item);
return content ? { ...item, content } : null;
}
default:
throw new Error(`Unknown item type: ${item.type}`);
}
} catch (error) {
log.error(`Failed to retrieve item ${item.id}`, error);
return null;
}
}),
);
return retrievedItems.filter((item) => item !== null);
}
}
References: |
You are a code assistant | Definition of 'TestType' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp | Definition:
type TestType =
| 'on_empty_comment'
| 'after_empty_comment'
| 'on_non_empty_comment'
| 'after_non_empty_comment'
| 'in_block_comment'
| 'on_block_comment'
| 'after_block_comment'
| 'in_jsdoc_comment'
| 'on_jsdoc_comment'
| 'after_jsdoc_comment'
| 'in_doc_comment'
| 'on_doc_comment'
| 'after_doc_comment'
| 'no_comment_large_file'
| 'on_comment_in_empty_function'
| 'after_comment_in_empty_function';
type FileExtension = string;
/**
* Position refers to the position of the cursor in the test file.
*/
type IntentTestCase = [TestType, Position, Intent];
/**
* Note: We use the language server procotol Ids here because `IDocContext` expects
* these Ids (which is passed into `ParseFile`) and because they are unique.
* `ParseFile` derives the tree sitter gramamr from the file's extension.
* Some grammars apply to multiple extensions, eg. `typescript` applies
* to both `.ts` and `.tsx`.
*/
const testCases: Array<[LanguageServerLanguageId, FileExtension, IntentTestCase[]]> = [
/* [ FIXME: add back support for vue
'vue',
'.vue', // ../../fixtures/intent/vue_comments.vue
[
['on_empty_comment', { line: 2, character: 9 }, 'completion'],
['after_empty_comment', { line: 3, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 30, character: 0 }, undefined],
// TODO: comments in the Vue `script` are not captured
// ['on_comment_in_empty_function', { line: 34, character: 33 }, 'completion'],
// ['after_comment_in_empty_function', { line: 35, character: 0 }, 'generation'],
],
], */
[
'typescript',
'.ts', // ../../fixtures/intent/typescript_comments.ts
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'],
['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'],
['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'],
['no_comment_large_file', { line: 24, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'],
],
],
[
'typescriptreact',
'.tsx', // ../../fixtures/intent/typescriptreact_comments.tsx
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'],
['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'],
['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'],
['no_comment_large_file', { line: 24, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'],
],
],
[
'javascript',
'.js', // ../../fixtures/intent/javascript_comments.js
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'],
['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'],
['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'],
['no_comment_large_file', { line: 24, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'],
],
],
[
'javascriptreact',
'.jsx', // ../../fixtures/intent/javascriptreact_comments.jsx
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_jsdoc_comment', { line: 15, character: 25 }, 'completion'],
['on_jsdoc_comment', { line: 16, character: 3 }, 'completion'],
['after_jsdoc_comment', { line: 17, character: 0 }, 'generation'],
['no_comment_large_file', { line: 24, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 31, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 32, character: 0 }, 'generation'],
],
],
[
'ruby',
'.rb', // ../../fixtures/intent/ruby_comments.rb
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 9, character: 23 }, 'completion'],
['on_block_comment', { line: 10, character: 4 }, 'completion'],
['after_block_comment', { line: 11, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 21, character: 30 }, 'completion'],
['after_comment_in_empty_function', { line: 22, character: 22 }, 'generation'],
],
],
[
'go',
'.go', // ../../fixtures/intent/go_comments.go
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 20, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 24, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 25, character: 0 }, 'generation'],
],
],
[
'java',
'.java', // ../../fixtures/intent/java_comments.java
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_doc_comment', { line: 14, character: 29 }, 'completion'],
['on_doc_comment', { line: 15, character: 3 }, 'completion'],
['after_doc_comment', { line: 16, character: 0 }, 'generation'],
['no_comment_large_file', { line: 23, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'],
],
],
[
'kotlin',
'.kt', // ../../fixtures/intent/kotlin_comments.kt
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_doc_comment', { line: 14, character: 29 }, 'completion'],
['on_doc_comment', { line: 15, character: 3 }, 'completion'],
['after_doc_comment', { line: 16, character: 0 }, 'generation'],
['no_comment_large_file', { line: 23, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'],
],
],
[
'rust',
'.rs', // ../../fixtures/intent/rust_comments.rs
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['in_doc_comment', { line: 11, character: 25 }, 'completion'],
['on_doc_comment', { line: 12, character: 42 }, 'completion'],
['after_doc_comment', { line: 15, character: 0 }, 'generation'],
['no_comment_large_file', { line: 23, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 26, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 27, character: 0 }, 'generation'],
],
],
[
'yaml',
'.yaml', // ../../fixtures/intent/yaml_comments.yaml
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
],
],
[
'html',
'.html', // ../../fixtures/intent/html_comments.html
[
['on_empty_comment', { line: 14, character: 12 }, 'completion'],
['after_empty_comment', { line: 15, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 8, character: 91 }, 'completion'],
['after_non_empty_comment', { line: 9, character: 0 }, 'generation'],
['in_block_comment', { line: 18, character: 29 }, 'completion'],
['on_block_comment', { line: 19, character: 7 }, 'completion'],
['after_block_comment', { line: 20, character: 0 }, 'generation'],
['no_comment_large_file', { line: 12, character: 66 }, undefined],
],
],
[
'c',
'.c', // ../../fixtures/intent/c_comments.c
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'],
],
],
[
'cpp',
'.cpp', // ../../fixtures/intent/cpp_comments.cpp
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'],
],
],
[
'c_sharp',
'.cs', // ../../fixtures/intent/c_sharp_comments.cs
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 4, character: 30 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['in_block_comment', { line: 8, character: 23 }, 'completion'],
['on_block_comment', { line: 9, character: 2 }, 'completion'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'],
['after_comment_in_empty_function', { line: 21, character: 22 }, 'generation'],
],
],
[
'css',
'.css', // ../../fixtures/intent/css_comments.css
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 3, character: 31 }, 'completion'],
['after_non_empty_comment', { line: 4, character: 0 }, 'generation'],
['in_block_comment', { line: 7, character: 23 }, 'completion'],
['on_block_comment', { line: 8, character: 2 }, 'completion'],
['after_block_comment', { line: 9, character: 0 }, 'generation'],
['no_comment_large_file', { line: 17, character: 0 }, undefined],
],
],
[
'bash',
'.sh', // ../../fixtures/intent/bash_comments.css
[
['on_empty_comment', { line: 4, character: 1 }, 'completion'],
['after_empty_comment', { line: 5, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 2, character: 65 }, 'completion'],
['after_non_empty_comment', { line: 3, character: 0 }, 'generation'],
['no_comment_large_file', { line: 10, character: 0 }, undefined],
['on_comment_in_empty_function', { line: 19, character: 12 }, 'completion'],
['after_comment_in_empty_function', { line: 20, character: 0 }, 'generation'],
],
],
[
'json',
'.json', // ../../fixtures/intent/json_comments.css
[
['on_empty_comment', { line: 20, character: 3 }, 'completion'],
['after_empty_comment', { line: 21, character: 0 }, 'completion'],
['on_non_empty_comment', { line: 0, character: 38 }, 'completion'],
['after_non_empty_comment', { line: 1, character: 0 }, 'generation'],
['no_comment_large_file', { line: 10, character: 0 }, undefined],
],
],
[
'scala',
'.scala', // ../../fixtures/intent/scala_comments.scala
[
['on_empty_comment', { line: 1, character: 3 }, 'completion'],
['after_empty_comment', { line: 2, character: 3 }, 'completion'],
['after_non_empty_comment', { line: 5, character: 0 }, 'generation'],
['after_block_comment', { line: 10, character: 0 }, 'generation'],
['no_comment_large_file', { line: 12, character: 0 }, undefined],
['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'],
],
],
[
'powersell',
'.ps1', // ../../fixtures/intent/powershell_comments.ps1
[
['on_empty_comment', { line: 20, character: 3 }, 'completion'],
['after_empty_comment', { line: 21, character: 3 }, 'completion'],
['after_non_empty_comment', { line: 10, character: 0 }, 'generation'],
['after_block_comment', { line: 8, character: 0 }, 'generation'],
['no_comment_large_file', { line: 22, character: 0 }, undefined],
['after_comment_in_empty_function', { line: 26, character: 0 }, 'generation'],
],
],
];
describe.each(testCases)('%s', (language, fileExt, cases) => {
it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => {
const fixturePath = getFixturePath('intent', `${language}_comments${fileExt}`);
const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({
fixturePath,
position,
languageId: language,
});
const intent = await getIntent({ treeAndLanguage, position, prefix, suffix });
expect(intent.intent).toBe(expectedIntent);
if (expectedIntent === 'generation') {
expect(intent.generationType).toBe('comment');
}
});
});
});
describe('Empty Function Intent', () => {
type TestType =
| 'empty_function_declaration'
| 'non_empty_function_declaration'
| 'empty_function_expression'
| 'non_empty_function_expression'
| 'empty_arrow_function'
| 'non_empty_arrow_function'
| 'empty_method_definition'
| 'non_empty_method_definition'
| 'empty_class_constructor'
| 'non_empty_class_constructor'
| 'empty_class_declaration'
| 'non_empty_class_declaration'
| 'empty_anonymous_function'
| 'non_empty_anonymous_function'
| 'empty_implementation'
| 'non_empty_implementation'
| 'empty_closure_expression'
| 'non_empty_closure_expression'
| 'empty_generator'
| 'non_empty_generator'
| 'empty_macro'
| 'non_empty_macro';
type FileExtension = string;
/**
* Position refers to the position of the cursor in the test file.
*/
type IntentTestCase = [TestType, Position, Intent];
const emptyFunctionTestCases: Array<
[LanguageServerLanguageId, FileExtension, IntentTestCase[]]
> = [
[
'typescript',
'.ts', // ../../fixtures/intent/empty_function/typescript.ts
[
['empty_function_declaration', { line: 0, character: 22 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_function_expression', { line: 6, character: 32 }, 'generation'],
['non_empty_function_expression', { line: 10, character: 4 }, undefined],
['empty_arrow_function', { line: 12, character: 26 }, 'generation'],
['non_empty_arrow_function', { line: 15, character: 4 }, undefined],
['empty_class_constructor', { line: 19, character: 21 }, 'generation'],
['empty_method_definition', { line: 21, character: 11 }, 'generation'],
['non_empty_class_constructor', { line: 29, character: 7 }, undefined],
['non_empty_method_definition', { line: 33, character: 0 }, undefined],
['empty_class_declaration', { line: 36, character: 14 }, 'generation'],
['empty_generator', { line: 38, character: 31 }, 'generation'],
['non_empty_generator', { line: 41, character: 4 }, undefined],
],
],
[
'javascript',
'.js', // ../../fixtures/intent/empty_function/javascript.js
[
['empty_function_declaration', { line: 0, character: 22 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_function_expression', { line: 6, character: 32 }, 'generation'],
['non_empty_function_expression', { line: 10, character: 4 }, undefined],
['empty_arrow_function', { line: 12, character: 26 }, 'generation'],
['non_empty_arrow_function', { line: 15, character: 4 }, undefined],
['empty_class_constructor', { line: 19, character: 21 }, 'generation'],
['empty_method_definition', { line: 21, character: 11 }, 'generation'],
['non_empty_class_constructor', { line: 27, character: 7 }, undefined],
['non_empty_method_definition', { line: 31, character: 0 }, undefined],
['empty_class_declaration', { line: 34, character: 14 }, 'generation'],
['empty_generator', { line: 36, character: 31 }, 'generation'],
['non_empty_generator', { line: 39, character: 4 }, undefined],
],
],
[
'go',
'.go', // ../../fixtures/intent/empty_function/go.go
[
['empty_function_declaration', { line: 0, character: 25 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_anonymous_function', { line: 6, character: 32 }, 'generation'],
['non_empty_anonymous_function', { line: 10, character: 0 }, undefined],
['empty_method_definition', { line: 19, character: 25 }, 'generation'],
['non_empty_method_definition', { line: 23, character: 0 }, undefined],
],
],
[
'java',
'.java', // ../../fixtures/intent/empty_function/java.java
[
['empty_function_declaration', { line: 0, character: 26 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_anonymous_function', { line: 7, character: 0 }, 'generation'],
['non_empty_anonymous_function', { line: 10, character: 0 }, undefined],
['empty_class_declaration', { line: 15, character: 18 }, 'generation'],
['non_empty_class_declaration', { line: 19, character: 0 }, undefined],
['empty_class_constructor', { line: 18, character: 13 }, 'generation'],
['empty_method_definition', { line: 20, character: 18 }, 'generation'],
['non_empty_class_constructor', { line: 26, character: 18 }, undefined],
['non_empty_method_definition', { line: 30, character: 18 }, undefined],
],
],
[
'rust',
'.rs', // ../../fixtures/intent/empty_function/rust.vue
[
['empty_function_declaration', { line: 0, character: 23 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_implementation', { line: 8, character: 13 }, 'generation'],
['non_empty_implementation', { line: 11, character: 0 }, undefined],
['empty_class_constructor', { line: 13, character: 0 }, 'generation'],
['non_empty_class_constructor', { line: 23, character: 0 }, undefined],
['empty_method_definition', { line: 17, character: 0 }, 'generation'],
['non_empty_method_definition', { line: 26, character: 0 }, undefined],
['empty_closure_expression', { line: 32, character: 0 }, 'generation'],
['non_empty_closure_expression', { line: 36, character: 0 }, undefined],
['empty_macro', { line: 42, character: 11 }, 'generation'],
['non_empty_macro', { line: 45, character: 11 }, undefined],
['empty_macro', { line: 55, character: 0 }, 'generation'],
['non_empty_macro', { line: 62, character: 20 }, undefined],
],
],
[
'kotlin',
'.kt', // ../../fixtures/intent/empty_function/kotlin.kt
[
['empty_function_declaration', { line: 0, character: 25 }, 'generation'],
['non_empty_function_declaration', { line: 4, character: 0 }, undefined],
['empty_anonymous_function', { line: 6, character: 32 }, 'generation'],
['non_empty_anonymous_function', { line: 9, character: 4 }, undefined],
['empty_class_declaration', { line: 12, character: 14 }, 'generation'],
['non_empty_class_declaration', { line: 15, character: 14 }, undefined],
['empty_method_definition', { line: 24, character: 0 }, 'generation'],
['non_empty_method_definition', { line: 28, character: 0 }, undefined],
],
],
[
'typescriptreact',
'.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx
[
['empty_function_declaration', { line: 0, character: 22 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 4 }, undefined],
['empty_function_expression', { line: 6, character: 32 }, 'generation'],
['non_empty_function_expression', { line: 10, character: 4 }, undefined],
['empty_arrow_function', { line: 12, character: 26 }, 'generation'],
['non_empty_arrow_function', { line: 15, character: 4 }, undefined],
['empty_class_constructor', { line: 19, character: 21 }, 'generation'],
['empty_method_definition', { line: 21, character: 11 }, 'generation'],
['non_empty_class_constructor', { line: 29, character: 7 }, undefined],
['non_empty_method_definition', { line: 33, character: 0 }, undefined],
['empty_class_declaration', { line: 36, character: 14 }, 'generation'],
['non_empty_arrow_function', { line: 40, character: 0 }, undefined],
['empty_arrow_function', { line: 41, character: 23 }, 'generation'],
['non_empty_arrow_function', { line: 44, character: 23 }, undefined],
['empty_generator', { line: 54, character: 31 }, 'generation'],
['non_empty_generator', { line: 57, character: 4 }, undefined],
],
],
[
'c',
'.c', // ../../fixtures/intent/empty_function/c.c
[
['empty_function_declaration', { line: 0, character: 24 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 0 }, undefined],
],
],
[
'cpp',
'.cpp', // ../../fixtures/intent/empty_function/cpp.cpp
[
['empty_function_declaration', { line: 0, character: 37 }, 'generation'],
['non_empty_function_declaration', { line: 3, character: 0 }, undefined],
['empty_function_expression', { line: 6, character: 43 }, 'generation'],
['non_empty_function_expression', { line: 10, character: 4 }, undefined],
['empty_class_constructor', { line: 15, character: 37 }, 'generation'],
['empty_method_definition', { line: 17, character: 18 }, 'generation'],
['non_empty_class_constructor', { line: 27, character: 7 }, undefined],
['non_empty_method_definition', { line: 31, character: 0 }, undefined],
['empty_class_declaration', { line: 35, character: 14 }, 'generation'],
],
],
[
'c_sharp',
'.cs', // ../../fixtures/intent/empty_function/c_sharp.cs
[
['empty_function_expression', { line: 2, character: 48 }, 'generation'],
['empty_class_constructor', { line: 4, character: 31 }, 'generation'],
['empty_method_definition', { line: 6, character: 31 }, 'generation'],
['non_empty_class_constructor', { line: 15, character: 0 }, undefined],
['non_empty_method_definition', { line: 20, character: 0 }, undefined],
['empty_class_declaration', { line: 24, character: 22 }, 'generation'],
],
],
[
'bash',
'.sh', // ../../fixtures/intent/empty_function/bash.sh
[
['empty_function_declaration', { line: 3, character: 48 }, 'generation'],
['non_empty_function_declaration', { line: 6, character: 31 }, undefined],
],
],
[
'scala',
'.scala', // ../../fixtures/intent/empty_function/scala.scala
[
['empty_function_declaration', { line: 1, character: 4 }, 'generation'],
['non_empty_function_declaration', { line: 5, character: 4 }, undefined],
['empty_method_definition', { line: 28, character: 3 }, 'generation'],
['non_empty_method_definition', { line: 34, character: 3 }, undefined],
['empty_class_declaration', { line: 22, character: 4 }, 'generation'],
['non_empty_class_declaration', { line: 27, character: 0 }, undefined],
['empty_anonymous_function', { line: 13, character: 0 }, 'generation'],
['non_empty_anonymous_function', { line: 17, character: 0 }, undefined],
],
],
[
'ruby',
'.rb', // ../../fixtures/intent/empty_function/ruby.rb
[
['empty_method_definition', { line: 0, character: 23 }, 'generation'],
['empty_method_definition', { line: 0, character: 6 }, undefined],
['non_empty_method_definition', { line: 3, character: 0 }, undefined],
['empty_anonymous_function', { line: 7, character: 27 }, 'generation'],
['non_empty_anonymous_function', { line: 9, character: 37 }, undefined],
['empty_anonymous_function', { line: 11, character: 25 }, 'generation'],
['empty_class_constructor', { line: 16, character: 22 }, 'generation'],
['non_empty_class_declaration', { line: 18, character: 0 }, undefined],
['empty_method_definition', { line: 20, character: 1 }, 'generation'],
['empty_class_declaration', { line: 33, character: 12 }, 'generation'],
],
],
[
'python',
'.py', // ../../fixtures/intent/empty_function/python.py
[
['empty_function_declaration', { line: 1, character: 4 }, 'generation'],
['non_empty_function_declaration', { line: 5, character: 4 }, undefined],
['empty_class_constructor', { line: 10, character: 0 }, 'generation'],
['empty_method_definition', { line: 14, character: 0 }, 'generation'],
['non_empty_class_constructor', { line: 19, character: 0 }, undefined],
['non_empty_method_definition', { line: 23, character: 4 }, undefined],
['empty_class_declaration', { line: 27, character: 4 }, 'generation'],
['empty_function_declaration', { line: 31, character: 4 }, 'generation'],
['empty_class_constructor', { line: 36, character: 4 }, 'generation'],
['empty_method_definition', { line: 40, character: 4 }, 'generation'],
['empty_class_declaration', { line: 44, character: 4 }, 'generation'],
['empty_function_declaration', { line: 49, character: 4 }, 'generation'],
['empty_class_constructor', { line: 53, character: 4 }, 'generation'],
['empty_method_definition', { line: 56, character: 4 }, 'generation'],
['empty_class_declaration', { line: 59, character: 4 }, 'generation'],
],
],
];
describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => {
it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => {
const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`);
const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({
fixturePath,
position,
languageId: language,
});
const intent = await getIntent({ treeAndLanguage, position, prefix, suffix });
expect(intent.intent).toBe(expectedIntent);
if (expectedIntent === 'generation') {
expect(intent.generationType).toBe('empty_function');
}
});
});
});
});
References: |
You are a code assistant | Definition of 'CONFIG_NAMESPACE' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp | Definition:
export const CONFIG_NAMESPACE = 'gitlab';
export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING';
// NOTE: This needs to _always_ be a 3 digits
export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0';
export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING';
// NOTE: This needs to _always_ be a 3 digits
export const MINIMUM_VERSION = '16.1.0';
export const REQUEST_TIMEOUT_MILLISECONDS = 25000;
// Webview IDs
export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow';
export const DUO_CHAT_WEBVIEW_ID = 'chat';
References: |
You are a code assistant | Definition of 'getLanguages' in file src/browser/tree_sitter/index.ts in project gitlab-lsp | Definition:
getLanguages() {
return this.languages;
}
getLoadState() {
return this.loadState;
}
async init(): Promise<void> {
const baseAssetsUrl = this.#configService.get('client.baseAssetsUrl');
this.languages = this.buildTreeSitterInfoByExtMap([
{
name: 'bash',
extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'c',
extensions: ['.c'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'cpp',
extensions: ['.cpp'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-cpp.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-cpp',
},
{
name: 'c_sharp',
extensions: ['.cs'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-c_sharp.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-c-sharp',
},
{
name: 'css',
extensions: ['.css'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-css.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-css',
},
{
name: 'go',
extensions: ['.go'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-go.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-go',
},
{
name: 'html',
extensions: ['.html'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-html.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-html',
},
{
name: 'java',
extensions: ['.java'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-java.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-java',
},
{
name: 'javascript',
extensions: ['.js'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-javascript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-javascript',
},
{
name: 'powershell',
extensions: ['.ps1'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-powershell.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-powershell',
},
{
name: 'python',
extensions: ['.py'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-python.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-python',
},
{
name: 'ruby',
extensions: ['.rb'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-ruby.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-ruby',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'sql',
// extensions: ['.sql'],
// wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-sql.wasm', baseAssetsUrl),
// nodeModulesPath: 'tree-sitter-sql',
// },
{
name: 'scala',
extensions: ['.scala'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-scala.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-scala',
},
{
name: 'typescript',
extensions: ['.ts'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-typescript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-typescript/typescript',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'hcl', // terraform, terragrunt
// extensions: ['.tf', '.hcl'],
// wasmPath: resolveGrammarAbsoluteUrl(
// 'vendor/grammars/tree-sitter-hcl.wasm',
// baseAssetsUrl,
// ),
// nodeModulesPath: 'tree-sitter-hcl',
// },
{
name: 'json',
extensions: ['.json'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-json.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-json',
},
]);
try {
await Parser.init({
locateFile(scriptName: string) {
return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl);
},
});
log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.');
this.loadState = TreeSitterParserLoadState.READY;
} catch (err) {
log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
}
}
References: |
You are a code assistant | Definition of 'messageMatcher' in file scripts/commit-lint/lint.js in project gitlab-lsp | Definition:
const messageMatcher = (r) => r.test.bind(r);
async function isConventional(message) {
return lint(
message,
{ ...config.rules, ...customRules },
{
defaultIgnores: false,
ignores: [
messageMatcher(/^[Rr]evert .*/),
messageMatcher(/^(?:fixup|squash)!/),
messageMatcher(/^Merge branch/),
messageMatcher(/^\d+\.\d+\.\d+/),
],
},
);
}
async function lintMr() {
const commits = await getCommitsInMr();
// When MR is set to squash, but it's not yet being merged, we check the MR Title
if (
CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' &&
CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train'
) {
console.log(
'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).',
);
return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of);
}
console.log('INFO: Checking all commits that will be added by this MR.');
return Promise.all(commits.map(isConventional));
}
async function run() {
if (!CI) {
console.error('This script can only run in GitLab CI.');
process.exit(1);
}
if (!LAST_MR_COMMIT) {
console.error(
'LAST_MR_COMMIT environment variable is not present. Make sure this script is run from `lint.sh`',
);
process.exit(1);
}
const results = await lintMr();
console.error(format({ results }, { helpUrl: urlSemanticRelease }));
const numOfErrors = results.reduce((acc, result) => acc + result.errors.length, 0);
if (numOfErrors !== 0) {
process.exit(1);
}
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
References:
- scripts/commit-lint/lint.js:45
- scripts/commit-lint/lint.js:44
- scripts/commit-lint/lint.js:46
- scripts/commit-lint/lint.js:47 |
You are a code assistant | Definition of 'debug' in file packages/lib_logging/src/types.ts in project gitlab-lsp | Definition:
debug(message: string, e?: Error): void;
info(e: Error): void;
info(message: string, e?: Error): void;
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
References: |
You are a code assistant | Definition of 'BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp | Definition:
export const BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES = supportedLanguages.map(
(l) => l.languageId,
);
export interface SupportedLanguagesUpdateParam {
allow?: string[];
deny?: string[];
}
export interface SupportedLanguagesService {
isLanguageEnabled(languageId: string): boolean;
isLanguageSupported(languageId: string): boolean;
onLanguageChange(listener: () => void): Disposable;
}
export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>(
'SupportedLanguagesService',
);
@Injectable(SupportedLanguagesService, [ConfigService])
export class DefaultSupportedLanguagesService implements SupportedLanguagesService {
#enabledLanguages: Set<string>;
#supportedLanguages: Set<string>;
#configService: ConfigService;
#eventEmitter = new EventEmitter();
constructor(configService: ConfigService) {
this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#configService = configService;
this.#configService.onConfigChange(() => this.#update());
}
#getConfiguredLanguages() {
const languages: SupportedLanguagesUpdateParam = {};
const additionalLanguages = this.#configService.get(
'client.codeCompletion.additionalLanguages',
);
if (Array.isArray(additionalLanguages)) {
languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier);
} else {
log.warn(
'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.',
);
}
const disabledSupportedLanguages = this.#configService.get(
'client.codeCompletion.disabledSupportedLanguages',
);
if (Array.isArray(disabledSupportedLanguages)) {
languages.deny = disabledSupportedLanguages;
} else {
log.warn(
'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.',
);
}
return languages;
}
#update() {
const { allow = [], deny = [] } = this.#getConfiguredLanguages();
const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
for (const language of allow) {
newSet.add(language.trim());
}
for (const language of deny) {
newSet.delete(language);
}
if (newSet.size === 0) {
log.warn('All languages have been disabled for Code Suggestions.');
}
const previousEnabledLanguages = this.#enabledLanguages;
this.#enabledLanguages = newSet;
if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) {
this.#triggerChange();
}
}
isLanguageSupported(languageId: string) {
return this.#supportedLanguages.has(languageId);
}
isLanguageEnabled(languageId: string) {
return this.#enabledLanguages.has(languageId);
}
onLanguageChange(listener: () => void): Disposable {
this.#eventEmitter.on('languageChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('languageChange');
}
#normalizeLanguageIdentifier(language: string) {
return language.trim().toLowerCase().replace(/^\./, '');
}
}
References: |
You are a code assistant | Definition of 'debug' in file packages/lib_logging/src/types.ts in project gitlab-lsp | Definition:
debug(e: Error): void;
debug(message: string, e?: Error): void;
info(e: Error): void;
info(message: string, e?: Error): void;
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
References: |
You are a code assistant | Definition of 'WEBVIEW_ID' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp | Definition:
export const WEBVIEW_ID = 'duo-chat' as WebviewId;
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 'WebIDEExtension' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
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/connection_service.ts in project gitlab-lsp | Definition:
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 'ProcessorInputMap' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp | Definition:
type ProcessorInputMap = {
stream: StreamingCompletionResponse;
completion: SuggestionOption[];
};
/**
* PostProcessor is an interface for classes that can be used to modify completion responses
* before they are sent to the client.
* They are run in order according to the order they are added to the PostProcessorPipeline.
* Post-processors can be used to filter, sort, or modify completion and streaming suggestions.
* Be sure to handle both streaming and completion responses in your implementation (if applicable).
* */
export abstract class PostProcessor {
processStream(
_context: IDocContext,
input: StreamingCompletionResponse,
): Promise<StreamingCompletionResponse> {
return Promise.resolve(input);
}
processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise<SuggestionOption[]> {
return Promise.resolve(input);
}
}
/**
* Pipeline for running post-processors on completion and streaming (generation) responses.
* Post-processors are used to modify completion responses before they are sent to the client.
* They can be used to filter, sort, or modify completion suggestions.
*/
export class PostProcessorPipeline {
#processors: PostProcessor[] = [];
addProcessor(processor: PostProcessor): void {
this.#processors.push(processor);
}
async run<T extends ProcessorType>({
documentContext,
input,
type,
}: {
documentContext: IDocContext;
input: ProcessorInputMap[T];
type: T;
}): Promise<ProcessorInputMap[T]> {
if (!this.#processors.length) return input as ProcessorInputMap[T];
return this.#processors.reduce(
async (prevPromise, processor) => {
const result = await prevPromise;
// eslint-disable-next-line default-case
switch (type) {
case 'stream':
return processor.processStream(
documentContext,
result as StreamingCompletionResponse,
) as Promise<ProcessorInputMap[T]>;
case 'completion':
return processor.processCompletion(
documentContext,
result as SuggestionOption[],
) as Promise<ProcessorInputMap[T]>;
}
throw new Error('Unexpected type in pipeline processing');
},
Promise.resolve(input) as Promise<ProcessorInputMap[T]>,
);
}
}
References: |
You are a code assistant | Definition of 'createMockFastifyInstance' in file src/node/webview/test-utils/mock_fastify_instance.ts in project gitlab-lsp | Definition:
export const createMockFastifyInstance = (): MockFastifyInstance & FastifyInstance => {
const reply: Partial<MockFastifyInstance> = {};
reply.register = jest.fn().mockReturnThis();
reply.get = jest.fn().mockReturnThis();
return reply as MockFastifyInstance & FastifyInstance;
};
References:
- src/node/webview/routes/webview_routes.test.ts:17 |
You are a code assistant | Definition of 'Options' in file src/node/webview/webview_fastify_middleware.ts in project gitlab-lsp | Definition:
type Options = {
webviewIds: WebviewId[];
};
export const createWebviewPlugin = (options: Options): FastifyPluginRegistration => ({
plugin: (fastify, { webviewIds }) =>
setupWebviewRoutes(fastify, {
webviewIds,
getWebviewResourcePath: buildWebviewPath,
}),
options,
});
const buildWebviewPath = (webviewId: WebviewId) => path.join(WEBVIEW_BASE_PATH, webviewId);
References:
- src/node/webview/webview_fastify_middleware.ts:12 |
You are a code assistant | Definition of 'GqlProjectWithDuoEnabledInfo' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp | Definition:
export interface GqlProjectWithDuoEnabledInfo {
duoFeaturesEnabled: boolean;
}
export interface DuoProjectAccessCache {
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[];
updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}): Promise<void>;
onDuoProjectCacheUpdate(listener: () => void): Disposable;
}
export const DuoProjectAccessCache =
createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache');
@Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient])
export class DefaultDuoProjectAccessCache {
#duoProjects: Map<WorkspaceFolderUri, DuoProject[]>;
#eventEmitter = new EventEmitter();
constructor(
private readonly directoryWalker: DirectoryWalker,
private readonly fileResolver: FileResolver,
private readonly api: GitLabApiClient,
) {
this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>();
}
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] {
return this.#duoProjects.get(workspaceFolder.uri) ?? [];
}
async updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}) {
try {
this.#duoProjects.clear();
const duoProjects = await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
return {
workspaceFolder,
projects: await this.#duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}),
};
}),
);
for (const { workspaceFolder, projects } of duoProjects) {
this.#logProjectsInfo(projects, workspaceFolder);
this.#duoProjects.set(workspaceFolder.uri, projects);
}
this.#triggerChange();
} catch (err) {
log.error('DuoProjectAccessCache: failed to update project access cache', err);
}
}
#logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) {
if (!projects.length) {
log.warn(
`DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`,
);
return;
}
log.debug(
`DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`,
);
}
async #duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}: {
workspaceFolder: WorkspaceFolder;
baseUrl: string;
}): Promise<DuoProject[]> {
const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl);
const projects = await Promise.all(
remotes.map(async (remote) => {
const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath);
return {
projectPath: remote.projectPath,
uri: remote.fileUri,
enabled,
host: remote.host,
namespace: remote.namespace,
namespaceWithPath: remote.namespaceWithPath,
} satisfies DuoProject;
}),
);
return projects;
}
async #gitlabRemotesForWorkspaceFolder(
workspaceFolder: WorkspaceFolder,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const paths = await this.directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
filters: {
fileEndsWith: ['/.git/config'],
},
});
const remotes = await Promise.all(
paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)),
);
return remotes.flat();
}
async #gitlabRemotesForFileUri(
fileUri: string,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri);
return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => {
const remote = parseGitLabRemote(remoteUrl, baseUrl);
if (remote) {
acc.push({ ...remote, fileUri });
}
return acc;
}, []);
}
async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> {
try {
const fileString = await this.fileResolver.readFile({ fileUri });
const config = ini.parse(fileString);
return this.#getRemoteUrls(config);
} catch (error) {
log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error);
return [];
}
}
#getRemoteUrls(config: GitConfig): string[] {
return Object.keys(config).reduce<string[]>((acc, section) => {
if (section.startsWith('remote ')) {
acc.push(config[section].url);
}
return acc;
}, []);
}
async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> {
try {
const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({
type: 'graphql',
query: duoFeaturesEnabledQuery,
variables: {
projectPath,
},
} satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>);
return Boolean(response?.project?.duoFeaturesEnabled);
} catch (error) {
log.error(
`DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`,
error,
);
return true;
}
}
onDuoProjectCacheUpdate(
listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void,
): Disposable {
this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener);
return {
dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener),
};
}
#triggerChange() {
this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects);
}
}
References:
- src/common/services/duo_access/project_access_cache.test.ts:51
- src/common/services/duo_access/project_access_cache.ts:227
- src/common/services/duo_access/project_access_cache.test.ts:123
- src/common/services/duo_access/project_access_cache.ts:221
- src/common/services/duo_access/project_access_cache.test.ts:155
- src/common/services/duo_access/project_access_cache.test.ts:86 |
You are a code assistant | Definition of 'buildTreeSitterInfoByExtMap' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
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 'GitLabPlatform' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
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 'ChatRecordRole' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp | Definition:
type ChatRecordRole = 'user' | 'assistant' | 'system';
type ChatRecordState = 'pending' | 'ready';
type ChatRecordType =
| 'general'
| 'explainCode'
| 'generateTests'
| 'refactorCode'
| 'newConversation';
type GitLabChatRecordAttributes = {
chunkId?: number | null;
type?: ChatRecordType;
role: ChatRecordRole;
content?: string;
contentHtml?: string;
requestId?: string;
state?: ChatRecordState;
errors?: string[];
timestamp?: string;
extras?: {
sources: object[];
};
};
export class GitLabChatRecord {
chunkId?: number | null;
role: ChatRecordRole;
content?: string;
contentHtml?: string;
id: string;
requestId?: string;
state: ChatRecordState;
timestamp: number;
type: ChatRecordType;
errors: string[];
extras?: {
sources: object[];
};
context?: GitLabChatRecordContext;
constructor({
chunkId,
type,
role,
content,
contentHtml,
state,
requestId,
errors,
timestamp,
extras,
}: GitLabChatRecordAttributes) {
this.chunkId = chunkId;
this.role = role;
this.content = content;
this.contentHtml = contentHtml;
this.type = type ?? this.#detectType();
this.state = state ?? 'ready';
this.requestId = requestId;
this.errors = errors ?? [];
this.id = uuidv4();
this.timestamp = timestamp ? Date.parse(timestamp) : Date.now();
this.extras = extras;
}
static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord {
const record = new GitLabChatRecord(attributes);
record.context = buildCurrentContext();
return record;
}
update(attributes: Partial<GitLabChatRecordAttributes>) {
const convertedAttributes = attributes as Partial<GitLabChatRecord>;
if (attributes.timestamp) {
convertedAttributes.timestamp = Date.parse(attributes.timestamp);
}
Object.assign(this, convertedAttributes);
}
#detectType(): ChatRecordType {
if (this.content === SPECIAL_MESSAGES.RESET) {
return 'newConversation';
}
return 'general';
}
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:32
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:17 |
You are a code assistant | Definition of 'INSTANCE_TRACKING_EVENTS_MAP' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
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 'withPrefix' in file packages/lib_logging/src/utils/with_prefix.ts in project gitlab-lsp | Definition:
export function withPrefix(logger: Logger, prefix: string): Logger {
const addPrefix = (message: string) => `${prefix} ${message}`;
return LOG_METHODS.reduce((acc, method) => {
acc[method] = (message: string | Error, e?: Error): void => {
if (typeof message === 'string') {
logger[method](addPrefix(message), e);
} else {
logger[method](message);
}
};
return acc;
}, {} as Logger);
}
References:
- src/common/graphql/workflow/service.ts:20
- packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:81
- packages/lib_webview/src/setup/setup_webview_runtime.ts:18
- packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:39
- packages/lib_logging/src/utils/with_prefix.test.ts:28
- src/common/webview/extension/extension_connection_message_bus_provider.ts:47
- packages/lib_webview/src/setup/plugin/webview_controller.ts:43
- packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:40 |
You are a code assistant | Definition of 'DidChangeDocumentInActiveEditorParams' in file src/common/notifications.ts in project gitlab-lsp | Definition:
export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri;
export const DidChangeDocumentInActiveEditor =
new NotificationType<DidChangeDocumentInActiveEditorParams>(
'$/gitlab/didChangeDocumentInActiveEditor',
);
References:
- src/common/document_service.ts:20
- src/common/document_service.ts:52 |
You are a code assistant | Definition of 'put' in file src/common/fetch.ts in project gitlab-lsp | Definition:
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References: |
You are a code assistant | Definition of 'RepoFileUri' in file src/common/git/repository.ts in project gitlab-lsp | Definition:
type RepoFileUri = URI;
type RepositoryUri = URI;
export type RepositoryFile = {
uri: RepoFileUri;
repositoryUri: RepositoryUri;
isIgnored: boolean;
workspaceFolder: WorkspaceFolder;
};
export class Repository {
workspaceFolder: WorkspaceFolder;
uri: URI;
configFileUri: URI;
#files: Map<string, RepositoryFile>;
#ignoreManager: IgnoreManager;
constructor({
configFileUri,
workspaceFolder,
uri,
ignoreManager,
}: {
workspaceFolder: WorkspaceFolder;
uri: RepositoryUri;
configFileUri: URI;
ignoreManager: IgnoreManager;
}) {
this.workspaceFolder = workspaceFolder;
this.uri = uri;
this.configFileUri = configFileUri;
this.#files = new Map();
this.#ignoreManager = ignoreManager;
}
async addFilesAndLoadGitIgnore(files: URI[]): Promise<void> {
log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`);
await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath));
for (const file of files) {
if (!this.#ignoreManager.isIgnored(file.fsPath)) {
this.#files.set(file.toString(), {
uri: file,
isIgnored: false,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
} else {
this.#files.set(file.toString(), {
uri: file,
isIgnored: true,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
}
}
}
isFileIgnored(filePath: URI): boolean {
return this.#ignoreManager.isIgnored(filePath.fsPath);
}
setFile(fileUri: URI): void {
if (!this.isFileIgnored(fileUri)) {
this.#files.set(fileUri.toString(), {
uri: fileUri,
isIgnored: false,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
} else {
this.#files.set(fileUri.toString(), {
uri: fileUri,
isIgnored: true,
repositoryUri: this.uri,
workspaceFolder: this.workspaceFolder,
});
}
}
getFile(fileUri: string): RepositoryFile | undefined {
return this.#files.get(fileUri);
}
removeFile(fileUri: string): void {
this.#files.delete(fileUri);
}
getFiles(): Map<string, RepositoryFile> {
return this.#files;
}
dispose(): void {
this.#ignoreManager.dispose();
this.#files.clear();
}
}
References:
- src/common/git/repository.ts:10 |
You are a code assistant | Definition of 'addPattern' in file src/common/git/ignore_trie.ts in project gitlab-lsp | Definition:
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 'Intent' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp | Definition:
export type Intent = typeof GENERATION | typeof COMPLETION | undefined;
export interface SuggestionContext {
document: IDocContext;
intent?: Intent;
projectPath?: string;
optionsCount?: OptionsCount;
additionalContexts?: AdditionalContext[];
}
export interface SuggestionResponse {
choices?: SuggestionResponseChoice[];
model?: SuggestionModel;
status: number;
error?: string;
isDirectConnection?: boolean;
}
export interface SuggestionResponseChoice {
text: string;
}
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/tree_sitter/intent_resolver.ts:12
- src/common/suggestion_client/suggestion_client.ts:21 |
You are a code assistant | Definition of 'AdvancedContextFilterArgs' in file src/common/advanced_context/advanced_context_filters.ts in project gitlab-lsp | Definition:
type AdvancedContextFilterArgs = {
contextResolutions: ContextResolution[];
documentContext: IDocContext;
byteSizeLimit: number;
dependencies: {
duoProjectAccessChecker: DuoProjectAccessChecker;
};
};
type AdvanceContextFilter = (args: AdvancedContextFilterArgs) => Promise<ContextResolution[]>;
/**
* Filters context resolutions that have empty content.
*/
const emptyContentFilter = async ({ contextResolutions }: AdvancedContextFilterArgs) => {
return contextResolutions.filter(({ content }) => content.replace(/\s/g, '') !== '');
};
/**
* Filters context resolutions that
* contain a Duo project that have Duo features enabled.
* See `DuoProjectAccessChecker` for more details.
*/
const duoProjectAccessFilter: AdvanceContextFilter = async ({
contextResolutions,
dependencies: { duoProjectAccessChecker },
documentContext,
}: AdvancedContextFilterArgs) => {
if (!documentContext?.workspaceFolder) {
return contextResolutions;
}
return contextResolutions.reduce((acc, resolution) => {
const { uri: resolutionUri } = resolution;
const projectStatus = duoProjectAccessChecker.checkProjectStatus(
resolutionUri,
documentContext.workspaceFolder as WorkspaceFolder,
);
if (projectStatus === DuoProjectStatus.DuoDisabled) {
log.warn(`Advanced Context Filter: Duo features are not enabled for ${resolutionUri}`);
return acc;
}
return [...acc, resolution];
}, [] as ContextResolution[]);
};
/**
* Filters context resolutions that meet the byte size limit.
* The byte size limit takes into the size of the total
* context resolutions content + size of document content.
*/
const byteSizeLimitFilter: AdvanceContextFilter = async ({
contextResolutions,
documentContext,
byteSizeLimit,
}: AdvancedContextFilterArgs) => {
const documentSize = getByteSize(`${documentContext.prefix}${documentContext.suffix}`);
let currentTotalSize = documentSize;
const filteredResolutions: ContextResolution[] = [];
for (const resolution of contextResolutions) {
currentTotalSize += getByteSize(resolution.content);
if (currentTotalSize > byteSizeLimit) {
// trim the current resolution content to fit the byte size limit
const trimmedContent = Buffer.from(resolution.content)
.slice(0, byteSizeLimit - currentTotalSize)
.toString();
if (trimmedContent.length) {
log.info(
`Advanced Context Filter: ${resolution.uri} content trimmed to fit byte size limit: ${trimmedContent.length} bytes.`,
);
filteredResolutions.push({ ...resolution, content: trimmedContent });
}
log.debug(
`Advanced Context Filter: Byte size limit exceeded for ${resolution.uri}. Skipping resolution.`,
);
break;
}
filteredResolutions.push(resolution);
}
return filteredResolutions;
};
/**
* Advanced context filters that are applied to context resolutions.
* @see filterContextResolutions
*/
const advancedContextFilters: AdvanceContextFilter[] = [
emptyContentFilter,
duoProjectAccessFilter,
byteSizeLimitFilter,
];
/**
* Filters context resolutions based on business logic.
* The filters are order dependent.
* @see advancedContextFilters
*/
export const filterContextResolutions = async ({
contextResolutions,
dependencies,
documentContext,
byteSizeLimit,
}: AdvancedContextFilterArgs): Promise<ContextResolution[]> => {
return advancedContextFilters.reduce(async (prevPromise, filter) => {
const resolutions = await prevPromise;
return filter({
contextResolutions: resolutions,
dependencies,
documentContext,
byteSizeLimit,
});
}, Promise.resolve(contextResolutions));
};
References:
- src/common/advanced_context/advanced_context_filters.ts:18
- src/common/advanced_context/advanced_context_filters.ts:23
- src/common/advanced_context/advanced_context_filters.ts:64
- src/common/advanced_context/advanced_context_filters.ts:114
- src/common/advanced_context/advanced_context_filters.ts:36 |
You are a code assistant | Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
class Greet:
def __init__(self, name):
pass
def greet(self):
pass
class Greet2:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello {self.name}")
class Greet3:
pass
def greet3(name):
...
class Greet4:
def __init__(self, name):
...
def greet(self):
...
class Greet3:
...
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References:
- 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 'isTextSuggestion' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp | Definition:
export const isTextSuggestion = (o: SuggestionOptionOrStream): o is SuggestionOption =>
Boolean((o as SuggestionOption).text);
export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] =>
options.map((option, index) => ({
label: `GitLab Suggestion ${index + 1}: ${option.text}`,
kind: CompletionItemKind.Text,
insertText: option.text,
detail: option.text,
command: {
title: 'Accept suggestion',
command: SUGGESTION_ACCEPTED_COMMAND,
arguments: [option.uniqueTrackingId],
},
data: {
index,
trackingId: option.uniqueTrackingId,
},
}));
/* this value will be used for telemetry so to make it human-readable
we use the 1-based indexing instead of 0 */
const getOptionTrackingIndex = (option: SuggestionOption) => {
return typeof option.index === 'number' ? option.index + 1 : undefined;
};
export const inlineCompletionOptionMapper = (
params: InlineCompletionParams,
options: SuggestionOptionOrStream[],
): InlineCompletionList => ({
items: options.map((option) => {
if (isStream(option)) {
// the streaming item is empty and only indicates to the client that streaming started
return {
insertText: '',
command: {
title: 'Start streaming',
command: START_STREAMING_COMMAND,
arguments: [option.streamId, option.uniqueTrackingId],
},
};
}
const completionInfo = params.context.selectedCompletionInfo;
let rangeDiff = 0;
if (completionInfo) {
const range = sanitizeRange(completionInfo.range);
rangeDiff = range.end.character - range.start.character;
}
return {
insertText: completionInfo
? `${completionInfo.text.substring(rangeDiff)}${option.text}`
: option.text,
range: Range.create(params.position, params.position),
command: {
title: 'Accept suggestion',
command: SUGGESTION_ACCEPTED_COMMAND,
arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)],
},
};
}),
});
References: |
You are a code assistant | Definition of 'isInstanceFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp | Definition:
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean;
/**
* 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: |
You are a code assistant | Definition of 'addFilesAndLoadGitIgnore' in file src/common/git/repository.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'CreateFastifyServerProps' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp | Definition:
type CreateFastifyServerProps = {
port: number;
plugins: FastifyPluginRegistration[];
logger: ILog;
};
type CreateHttpServerResult = {
address: URL;
server: FastifyInstance;
shutdown: () => Promise<void>;
};
export const createFastifyHttpServer = async (
props: Partial<CreateFastifyServerProps>,
): Promise<CreateHttpServerResult> => {
const { port = 0, plugins = [] } = props;
const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:');
const server = fastify({
forceCloseConnections: true,
ignoreTrailingSlash: true,
logger: createFastifyLogger(logger),
});
try {
await registerPlugins(server, plugins, logger);
const address = await startFastifyServer(server, port, logger);
await server.ready();
logger?.info(`server listening on ${address}`);
return {
address,
server,
shutdown: async () => {
try {
await server.close();
logger?.info('server shutdown');
} catch (err) {
logger?.error('error during server shutdown', err as Error);
}
},
};
} catch (err) {
logger?.error('error during server setup', err as Error);
throw err;
}
};
const registerPlugins = async (
server: FastifyInstance,
plugins: FastifyPluginRegistration[],
logger?: ILog,
) => {
await Promise.all(
plugins.map(async ({ plugin, options }) => {
try {
await server.register(plugin, options);
} catch (err) {
logger?.error('Error during plugin registration', err as Error);
throw err;
}
}),
);
};
const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise<URL> =>
new Promise((resolve, reject) => {
try {
server.listen({ port, host: '127.0.0.1' }, (err, address) => {
if (err) {
logger?.error(err);
reject(err);
return;
}
resolve(new URL(address));
});
} catch (error) {
reject(error);
}
});
const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined =>
logger ? pino(createLoggerTransport(logger)) : undefined;
References: |
You are a code assistant | Definition of 'testSolvers' in file packages/webview-chat/src/app/index.ts in project gitlab-lsp | Definition:
function testSolvers(index: number) {
const results = solvers.map(({ name, solver }) => {
const start = performance.now();
const result = solver.solve(index);
const duration = performance.now() - start;
return { name, result, duration };
});
results.forEach(({ name, result, duration }) => {
// eslint-disable-next-line no-alert
alert(`${name}: Fibonacci of ${index} is ${result} (calculated in ${duration.toFixed(2)} ms)`);
});
}
document.body.appendChild(inputBox);
document.body.appendChild(button);
References:
- packages/webview-chat/src/app/index.ts:27 |
You are a code assistant | Definition of 'TestTuple' in file src/common/log.test.ts in project gitlab-lsp | Definition:
type TestTuple = [keyof ILog, LogLevel];
it('does not log debug logs by default', () => {
log.debug('message');
expect(logFunction).not.toBeCalled();
});
it.each<TestTuple>([
['info', LOG_LEVEL.INFO],
['warn', LOG_LEVEL.WARNING],
['error', LOG_LEVEL.ERROR],
])('it handles log level "%s"', (methodName, logLevel) => {
log[methodName]('message');
expect(getLoggedMessage()).toContain(`[${logLevel}]: message`);
expect(getLoggedMessage()).not.toMatch(/\s+Error\s+at.*log\.[jt]s/m);
});
it('indents multiline messages', () => {
log.error('error happened\nand the next line\nexplains why');
expect(getLoggedMessage()).toContain(
`[error]: error happened\n and the next line\n explains why`,
);
});
describe.each`
exception | error | expectation
${new Error('wrong')} | ${new Error('wrong')} | ${'returns the error object '}
${'error'} | ${new Error('error')} | ${'transforms string into Error'}
${0} | ${'0'} | ${'returns JSON.stringify of the exception otherwise'}
`('get Error from unknown exception', ({ exception, error, expectation }) => {
it(`${expectation}`, () => {
log.error('test message', exception);
expect(getLoggedMessage()).toContain(error.message || error);
});
});
});
describe('log Error', () => {
it('passes the argument to the handler', () => {
const message = 'A very bad error occurred';
const error = {
message,
stack: 'stack',
};
log.error(error as Error);
expect(getLoggedMessage()).toMatch(/\[error\]: A very bad error occurred\s+stack/m);
});
});
});
});
References: |
You are a code assistant | Definition of 'constructor' in file packages/lib_handler_registry/src/errors/unhandled_handler_error.ts in project gitlab-lsp | Definition:
constructor(handlerId: string, originalError: Error) {
super(`Unhandled error in handler '${handlerId}': ${originalError.message}`);
this.name = 'UnhandledHandlerError';
this.originalError = originalError;
this.stack = originalError.stack;
}
}
References: |
You are a code assistant | Definition of 'DesktopDirectoryWalker' in file src/node/services/fs/dir.ts in project gitlab-lsp | Definition:
export class DesktopDirectoryWalker implements DirectoryWalker {
#watchers: Map<string, chokidar.FSWatcher> = new Map();
#applyFilters(fileUri: DocumentUri, filters: DirectoryToSearch['filters']) {
if (!filters) {
return true;
}
if (filters.fileEndsWith) {
return filters.fileEndsWith.some((end) => fileUri.endsWith(end));
}
return true;
}
async findFilesForDirectory(args: DirectoryToSearch): Promise<URI[]> {
const { filters, directoryUri } = args;
const perf = performance.now();
const pathMap = new Map<string, URI>();
const promise = new FastDirectoryCrawler()
.withFullPaths()
.filter((path) => {
const fileUri = fsPathToUri(path);
// save each normalized filesystem path avoid re-parsing the path
pathMap.set(path, fileUri);
return this.#applyFilters(fileUri.path, filters);
})
.crawl(fsPathFromUri(directoryUri))
.withPromise();
const paths = await promise;
log.debug(
`DirectoryWalker: found ${paths.length} paths, took ${Math.round(performance.now() - perf)}ms`,
);
return paths.map((path) => pathMap.get(path) as URI);
}
setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void {
const fsPath = fsPathFromUri(workspaceFolder.uri);
const watcher = chokidar.watch(fsPath, {
persistent: true,
alwaysStat: false,
ignoreInitial: true,
});
watcher
.on('add', (path) => fileChangeHandler('add', workspaceFolder, path))
.on('change', (path) => fileChangeHandler('change', workspaceFolder, path))
.on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path));
this.#watchers.set(workspaceFolder.uri, watcher);
}
async dispose(): Promise<void> {
const promises = Array.from(this.#watchers.values()).map((watcher) => watcher.close());
await Promise.all(promises);
this.#watchers.clear();
}
}
References:
- src/node/services/fs/dir.test.ts:27
- src/node/services/fs/dir.test.ts:14 |
You are a code assistant | Definition of 'isConventional' in file scripts/commit-lint/lint.js in project gitlab-lsp | Definition:
async function isConventional(message) {
return lint(
message,
{ ...config.rules, ...customRules },
{
defaultIgnores: false,
ignores: [
messageMatcher(/^[Rr]evert .*/),
messageMatcher(/^(?:fixup|squash)!/),
messageMatcher(/^Merge branch/),
messageMatcher(/^\d+\.\d+\.\d+/),
],
},
);
}
async function lintMr() {
const commits = await getCommitsInMr();
// When MR is set to squash, but it's not yet being merged, we check the MR Title
if (
CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' &&
CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train'
) {
console.log(
'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).',
);
return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of);
}
console.log('INFO: Checking all commits that will be added by this MR.');
return Promise.all(commits.map(isConventional));
}
async function run() {
if (!CI) {
console.error('This script can only run in GitLab CI.');
process.exit(1);
}
if (!LAST_MR_COMMIT) {
console.error(
'LAST_MR_COMMIT environment variable is not present. Make sure this script is run from `lint.sh`',
);
process.exit(1);
}
const results = await lintMr();
console.error(format({ results }, { helpUrl: urlSemanticRelease }));
const numOfErrors = results.reduce((acc, result) => acc + result.errors.length, 0);
if (numOfErrors !== 0) {
process.exit(1);
}
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
References:
- scripts/commit-lint/lint.js:64 |
You are a code assistant | Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp | Definition:
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/go.go:13
- src/tests/fixtures/intent/empty_function/go.go:23
- src/tests/fixtures/intent/empty_function/ruby.rb:16
- src/tests/fixtures/intent/empty_function/go.go:15
- src/tests/fixtures/intent/empty_function/go.go:20
- src/tests/fixtures/intent/go_comments.go:24 |
You are a code assistant | Definition of 'onRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp | Definition:
onRequest<T extends KeysWithOptionalParams<TRequests>>(
type: T,
handler: () => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
onRequest<T extends keyof TRequests>(
type: T,
handler: (payload: TRequests[T]['params']) => Promise<ExtractRequestResult<TRequests[T]>>,
): Disposable;
}
/**
* Defines the structure for message definitions, including notifications and requests.
*/
export type MessageDefinitions<
TNotifications extends NotificationMap = NotificationMap,
TRequests extends RequestMap = RequestMap,
> = {
notifications: TNotifications;
requests: TRequests;
};
export type MessageMap<
TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
> = {
inbound: TInboundMessageDefinitions;
outbound: TOutboundMessageDefinitions;
};
export interface MessageBus<T extends MessageMap = MessageMap>
extends NotificationPublisher<T['outbound']['notifications']>,
NotificationListener<T['inbound']['notifications']>,
RequestPublisher<T['outbound']['requests']>,
RequestListener<T['inbound']['requests']> {}
References: |
You are a code assistant | Definition of 'subscribeToUpdates' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp | Definition:
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 'AImpl' in file packages/lib_di/src/index.test.ts in project gitlab-lsp | Definition:
class AImpl implements A {
a = () => 'a';
}
@Injectable(B, [A])
class BImpl implements B {
#a: A;
constructor(a: A) {
this.#a = a;
}
b = () => `B(${this.#a.a()})`;
}
@Injectable(C, [A, B])
class CImpl implements C {
#a: A;
#b: B;
constructor(a: A, b: B) {
this.#a = a;
this.#b = b;
}
c = () => `C(${this.#b.b()}, ${this.#a.a()})`;
}
let container: Container;
beforeEach(() => {
container = new Container();
});
describe('addInstances', () => {
const O = createInterfaceId<object>('object');
it('fails if the instance is not branded', () => {
expect(() => container.addInstances({ say: 'hello' } as BrandedInstance<object>)).toThrow(
/invoked without branded object/,
);
});
it('fails if the instance is already present', () => {
const a = brandInstance(O, { a: 'a' });
const b = brandInstance(O, { b: 'b' });
expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/);
});
it('adds instance', () => {
const instance = { a: 'a' };
const a = brandInstance(O, instance);
container.addInstances(a);
expect(container.get(O)).toBe(instance);
});
});
describe('instantiate', () => {
it('can instantiate three classes A,B,C', () => {
container.instantiate(AImpl, BImpl, CImpl);
const cInstance = container.get(C);
expect(cInstance.c()).toBe('C(B(a), a)');
});
it('instantiates dependencies in multiple instantiate calls', () => {
container.instantiate(AImpl);
// the order is important for this test
// we want to make sure that the stack in circular dependency discovery is being cleared
// to try why this order is necessary, remove the `inStack.delete()` from
// the `if (!cwd && instanceIds.includes(id))` condition in prod code
expect(() => container.instantiate(CImpl, BImpl)).not.toThrow();
});
it('detects duplicate ids', () => {
@Injectable(A, [])
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl, AImpl2)).toThrow(
/The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/,
);
});
it('detects duplicate id with pre-existing instance', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/);
});
it('detects missing dependencies', () => {
expect(() => container.instantiate(BImpl)).toThrow(
/Class BImpl \(interface B\) depends on interfaces \[A]/,
);
});
it('it uses existing instances as dependencies', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
container.instantiate(BImpl);
expect(container.get(B).b()).toBe('B(a)');
});
it("detects classes what aren't decorated with @Injectable", () => {
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl2)).toThrow(
/Classes \[AImpl2] are not decorated with @Injectable/,
);
});
it('detects circular dependencies', () => {
@Injectable(A, [C])
class ACircular implements A {
a = () => 'hello';
constructor(c: C) {
// eslint-disable-next-line no-unused-expressions
c;
}
}
expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow(
/Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./,
);
});
// this test ensures that we don't store any references to the classes and we instantiate them only once
it('does not instantiate classes from previous instantiate call', () => {
let globCount = 0;
@Injectable(A, [])
class Counter implements A {
counter = globCount;
constructor() {
globCount++;
}
a = () => this.counter.toString();
}
container.instantiate(Counter);
container.instantiate(BImpl);
expect(container.get(A).a()).toBe('0');
});
});
describe('get', () => {
it('returns an instance of the interfaceId', () => {
container.instantiate(AImpl);
expect(container.get(A)).toBeInstanceOf(AImpl);
});
it('throws an error for missing dependency', () => {
container.instantiate();
expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/);
});
});
});
References:
- packages/lib_di/src/index.test.ts:109
- packages/lib_di/src/index.test.ts:122 |
You are a code assistant | Definition of 'MessageBus' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp | Definition:
export interface MessageBus<T extends MessageMap = MessageMap>
extends NotificationPublisher<T['outbound']['notifications']>,
NotificationListener<T['inbound']['notifications']>,
RequestPublisher<T['outbound']['requests']>,
RequestListener<T['inbound']['requests']> {}
References:
- packages/webview_duo_workflow/src/plugin/index.ts:9
- packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:4
- src/common/graphql/workflow/service.ts:45
- src/common/graphql/workflow/service.test.ts:17 |
You are a code assistant | Definition of 'destroy' in file src/common/fetch.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'CommentResolver' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp | Definition:
export class CommentResolver {
protected queryByLanguage: Map<string, Query>;
constructor() {
this.queryByLanguage = new Map();
}
#getQueryByLanguage(
language: TreeSitterLanguageName,
treeSitterLanguage: Language,
): Query | undefined {
const query = this.queryByLanguage.get(language);
if (query) {
return query;
}
const queryString = commentQueries[language];
if (!queryString) {
log.warn(`No comment query found for language: ${language}`);
return undefined;
}
const newQuery = treeSitterLanguage.query(queryString);
this.queryByLanguage.set(language, newQuery);
return newQuery;
}
/**
* Returns the comment that is on or directly above the cursor, if it exists.
* To handle the case the comment may be several new lines above the cursor,
* we traverse the tree to check if any nodes are between the comment and the cursor.
*/
getCommentForCursor({
languageName,
tree,
cursorPosition,
treeSitterLanguage,
}: {
languageName: TreeSitterLanguageName;
tree: Tree;
treeSitterLanguage: Language;
cursorPosition: Point;
}): CommentResolution | undefined {
const query = this.#getQueryByLanguage(languageName, treeSitterLanguage);
if (!query) {
return undefined;
}
const comments = query.captures(tree.rootNode).map((capture) => {
return {
start: capture.node.startPosition,
end: capture.node.endPosition,
content: capture.node.text,
capture,
};
});
const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition);
if (commentAtCursor) {
// No need to further check for isPositionInNode etc. as cursor is directly on the comment
return { commentAtCursor };
}
const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition);
if (!commentAboveCursor) {
return undefined;
}
const commentParentNode = commentAboveCursor.capture.node.parent;
if (!commentParentNode) {
return undefined;
}
if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) {
return undefined;
}
const directChildren = commentParentNode.children;
for (const child of directChildren) {
const hasNodeBetweenCursorAndComment =
child.startPosition.row > commentAboveCursor.capture.node.endPosition.row &&
child.startPosition.row <= cursorPosition.row;
if (hasNodeBetweenCursorAndComment) {
return undefined;
}
}
return { commentAboveCursor };
}
static #isPositionInNode(position: Point, node: SyntaxNode): boolean {
return position.row >= node.startPosition.row && position.row <= node.endPosition.row;
}
static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined {
return CommentResolver.#getLastComment(
comments.filter((comment) => comment.end.row < cursorPosition.row),
);
}
static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined {
return CommentResolver.#getLastComment(
comments.filter(
(comment) =>
comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row,
),
);
}
static #getLastComment(comments: Comment[]): Comment | undefined {
return comments.sort((a, b) => b.end.row - a.end.row)[0];
}
/**
* Returns the total number of lines that are comments in a parsed syntax tree.
* Uses a Set because we only want to count each line once.
* @param {Object} params - Parameters for counting comment lines.
* @param {TreeSitterLanguageName} params.languageName - The name of the programming language.
* @param {Tree} params.tree - The syntax tree to analyze.
* @param {Language} params.treeSitterLanguage - The Tree-sitter language instance.
* @returns {number} - The total number of unique lines containing comments.
*/
getTotalCommentLines({
treeSitterLanguage,
languageName,
tree,
}: {
languageName: TreeSitterLanguageName;
treeSitterLanguage: Language;
tree: Tree;
}): number {
const query = this.#getQueryByLanguage(languageName, treeSitterLanguage);
const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor()
const commentLineSet = new Set<number>(); // A Set is used to only count each line once (the same comment can span multiple lines)
captures.forEach((capture) => {
const { startPosition, endPosition } = capture.node;
for (let { row } = startPosition; row <= endPosition.row; row++) {
commentLineSet.add(row);
}
});
return commentLineSet.size;
}
static isCommentEmpty(comment: Comment): boolean {
const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' ');
// Count the number of alphanumeric characters in the trimmed content
const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length;
return alphanumericCount <= 2;
}
}
let commentResolver: CommentResolver;
export function getCommentResolver(): CommentResolver {
if (!commentResolver) {
commentResolver = new CommentResolver();
}
return commentResolver;
}
References:
- src/common/tree_sitter/comments/comment_resolver.ts:172
- src/common/tree_sitter/comments/comment_resolver.ts:169
- src/common/tree_sitter/comments/comment_resolver.ts:170
- src/common/tree_sitter/comments/comment_resolver.test.ts:15
- src/common/tree_sitter/comments/comment_resolver.test.ts:9 |
You are a code assistant | Definition of 'updateSuggestionState' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp | Definition:
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
if (this.#circuitBreaker.isOpen()) {
return;
}
if (!this.isEnabled()) return;
if (this.#isStreamingSuggestion(uniqueTrackingId)) return;
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const allowedTransitions = nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Instance telemetry: Could not track telemetry', e),
);
log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
const event = INSTANCE_TRACKING_EVENTS_MAP[eventType];
if (!event) {
return;
}
try {
const { language, suggestion_size } =
this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {};
await this.#api.fetchFromApi({
type: 'rest',
method: 'POST',
path: '/usage_data/track_event',
body: {
event,
additional_properties: {
unique_tracking_id: uniqueTrackingId,
timestamp: new Date().toISOString(),
language,
suggestion_size,
},
},
supportedSinceInstanceVersion: {
resourceName: 'track instance telemetry',
version: '17.2.0',
},
});
this.#circuitBreaker.success();
} catch (error) {
if (error instanceof InvalidInstanceVersionError) {
if (this.#invalidInstanceMsgLogged) return;
this.#invalidInstanceMsgLogged = true;
}
log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error);
this.#circuitBreaker.error();
}
}
rejectOpenedSuggestions() {
log.debug(`Instance Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
static #suggestionSize(options: SuggestionOption[]): number {
const countLines = (text: string) => (text ? text.split('\n').length : 0);
return Math.max(...options.map(({ text }) => countLines(text)));
}
#isStreamingSuggestion(uniqueTrackingId: string): boolean {
return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming);
}
}
References: |
You are a code assistant | Definition of 'ChatAvailableResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp | Definition:
export type ChatAvailableResponseType = {
currentUser: {
duoChatAvailable: boolean;
};
};
export async function getChatSupport(
platform?: GitLabPlatformForAccount | undefined,
): Promise<ChatSupportResponseInterface> {
const request: GraphQLRequest<ChatAvailableResponseType> = {
type: 'graphql',
query: queryGetChatAvailability,
variables: {},
};
const noSupportResponse: ChatSupportResponseInterface = { hasSupportForChat: false };
if (!platform) {
return noSupportResponse;
}
try {
const {
currentUser: { duoChatAvailable },
} = await platform.fetchFromApi(request);
if (duoChatAvailable) {
return {
hasSupportForChat: duoChatAvailable,
platform,
};
}
return noSupportResponse;
} catch (e) {
log.error(e as Error);
return noSupportResponse;
}
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:11 |
You are a code assistant | Definition of 'findFilesForDirectory' in file src/node/services/fs/dir.ts in project gitlab-lsp | Definition:
async findFilesForDirectory(args: DirectoryToSearch): Promise<URI[]> {
const { filters, directoryUri } = args;
const perf = performance.now();
const pathMap = new Map<string, URI>();
const promise = new FastDirectoryCrawler()
.withFullPaths()
.filter((path) => {
const fileUri = fsPathToUri(path);
// save each normalized filesystem path avoid re-parsing the path
pathMap.set(path, fileUri);
return this.#applyFilters(fileUri.path, filters);
})
.crawl(fsPathFromUri(directoryUri))
.withPromise();
const paths = await promise;
log.debug(
`DirectoryWalker: found ${paths.length} paths, took ${Math.round(performance.now() - perf)}ms`,
);
return paths.map((path) => pathMap.get(path) as URI);
}
setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void {
const fsPath = fsPathFromUri(workspaceFolder.uri);
const watcher = chokidar.watch(fsPath, {
persistent: true,
alwaysStat: false,
ignoreInitial: true,
});
watcher
.on('add', (path) => fileChangeHandler('add', workspaceFolder, path))
.on('change', (path) => fileChangeHandler('change', workspaceFolder, path))
.on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path));
this.#watchers.set(workspaceFolder.uri, watcher);
}
async dispose(): Promise<void> {
const promises = Array.from(this.#watchers.values()).map((watcher) => watcher.close());
await Promise.all(promises);
this.#watchers.clear();
}
}
References: |
You are a code assistant | Definition of 'prettyJson' in file src/common/utils/json.ts in project gitlab-lsp | Definition:
export const prettyJson = (
obj: Record<string, unknown> | unknown[],
space: string | number = 2,
): string => JSON.stringify(obj, null, space);
References:
- src/common/log.ts:33 |
You are a code assistant | Definition of 'constructor' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp | Definition:
constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {}
isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string }> {
const { providerType } = aiProviderItem;
switch (providerType) {
case 'file': {
const { repositoryFile } = aiProviderItem;
if (!repositoryFile) {
return Promise.resolve({ allowed: true });
}
const duoProjectStatus = this.duoProjectAccessChecker.checkProjectStatus(
repositoryFile.uri.toString(),
repositoryFile.workspaceFolder,
);
const enabled =
duoProjectStatus === DuoProjectStatus.DuoEnabled ||
duoProjectStatus === DuoProjectStatus.NonGitlabProject;
if (!enabled) {
return Promise.resolve({ allowed: false, reason: 'Duo is not enabled for this project' });
}
return Promise.resolve({ allowed: true });
}
default: {
throw new Error(`Unknown provider type ${providerType}`);
}
}
}
}
References: |
You are a code assistant | Definition of 'GitConfig' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp | Definition:
interface GitConfig {
[section: string]: { [key: string]: string };
}
type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string };
export interface GqlProjectWithDuoEnabledInfo {
duoFeaturesEnabled: boolean;
}
export interface DuoProjectAccessCache {
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[];
updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}): Promise<void>;
onDuoProjectCacheUpdate(listener: () => void): Disposable;
}
export const DuoProjectAccessCache =
createInterfaceId<DuoProjectAccessCache>('DuoProjectAccessCache');
@Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient])
export class DefaultDuoProjectAccessCache {
#duoProjects: Map<WorkspaceFolderUri, DuoProject[]>;
#eventEmitter = new EventEmitter();
constructor(
private readonly directoryWalker: DirectoryWalker,
private readonly fileResolver: FileResolver,
private readonly api: GitLabApiClient,
) {
this.#duoProjects = new Map<WorkspaceFolderUri, DuoProject[]>();
}
getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] {
return this.#duoProjects.get(workspaceFolder.uri) ?? [];
}
async updateCache({
baseUrl,
workspaceFolders,
}: {
baseUrl: string;
workspaceFolders: WorkspaceFolder[];
}) {
try {
this.#duoProjects.clear();
const duoProjects = await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
return {
workspaceFolder,
projects: await this.#duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}),
};
}),
);
for (const { workspaceFolder, projects } of duoProjects) {
this.#logProjectsInfo(projects, workspaceFolder);
this.#duoProjects.set(workspaceFolder.uri, projects);
}
this.#triggerChange();
} catch (err) {
log.error('DuoProjectAccessCache: failed to update project access cache', err);
}
}
#logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) {
if (!projects.length) {
log.warn(
`DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`,
);
return;
}
log.debug(
`DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`,
);
}
async #duoProjectsForWorkspaceFolder({
workspaceFolder,
baseUrl,
}: {
workspaceFolder: WorkspaceFolder;
baseUrl: string;
}): Promise<DuoProject[]> {
const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl);
const projects = await Promise.all(
remotes.map(async (remote) => {
const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath);
return {
projectPath: remote.projectPath,
uri: remote.fileUri,
enabled,
host: remote.host,
namespace: remote.namespace,
namespaceWithPath: remote.namespaceWithPath,
} satisfies DuoProject;
}),
);
return projects;
}
async #gitlabRemotesForWorkspaceFolder(
workspaceFolder: WorkspaceFolder,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const paths = await this.directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
filters: {
fileEndsWith: ['/.git/config'],
},
});
const remotes = await Promise.all(
paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)),
);
return remotes.flat();
}
async #gitlabRemotesForFileUri(
fileUri: string,
baseUrl: string,
): Promise<GitlabRemoteAndFileUri[]> {
const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri);
return remoteUrls.reduce<GitlabRemoteAndFileUri[]>((acc, remoteUrl) => {
const remote = parseGitLabRemote(remoteUrl, baseUrl);
if (remote) {
acc.push({ ...remote, fileUri });
}
return acc;
}, []);
}
async #remoteUrlsFromGitConfig(fileUri: string): Promise<string[]> {
try {
const fileString = await this.fileResolver.readFile({ fileUri });
const config = ini.parse(fileString);
return this.#getRemoteUrls(config);
} catch (error) {
log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error);
return [];
}
}
#getRemoteUrls(config: GitConfig): string[] {
return Object.keys(config).reduce<string[]>((acc, section) => {
if (section.startsWith('remote ')) {
acc.push(config[section].url);
}
return acc;
}, []);
}
async #checkDuoFeaturesEnabled(projectPath: string): Promise<boolean> {
try {
const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({
type: 'graphql',
query: duoFeaturesEnabledQuery,
variables: {
projectPath,
},
} satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>);
return Boolean(response?.project?.duoFeaturesEnabled);
} catch (error) {
log.error(
`DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`,
error,
);
return true;
}
}
onDuoProjectCacheUpdate(
listener: (duoProjectsCache: Map<WorkspaceFolderUri, DuoProject[]>) => void,
): Disposable {
this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener);
return {
dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener),
};
}
#triggerChange() {
this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects);
}
}
References:
- src/common/services/duo_access/project_access_cache.ts:210 |
You are a code assistant | Definition of 'ApiRequest' in file src/common/api_types.ts in project gitlab-lsp | Definition:
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 'setCodeSuggestionsContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp | Definition:
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
const {
documentContext,
source = SuggestionSource.network,
language,
isStreaming,
triggerKind,
optionsCount,
additionalContexts,
isDirectConnection,
} = context;
const {
gitlab_instance_id,
gitlab_global_user_id,
gitlab_host_name,
gitlab_saas_duo_pro_namespace_ids,
} = this.#configService.get('client.snowplowTrackerOptions') ?? {};
if (source === SuggestionSource.cache) {
log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`);
} else {
log.debug(`Snowplow Telemetry: Received request to create a new suggestion`);
}
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
const advancedContextData = this.#getAdvancedContextData({
additionalContexts,
documentContext,
});
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0',
data: {
suffix_length: documentContext?.suffix.length ?? 0,
prefix_length: documentContext?.prefix.length ?? 0,
gitlab_realm: this.#gitlabRealm,
model_engine: null,
model_name: null,
language: language ?? null,
api_status_code: null,
debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS,
suggestion_source: source,
gitlab_global_user_id: gitlab_global_user_id ?? null,
gitlab_host_name: gitlab_host_name ?? null,
gitlab_instance_id: gitlab_instance_id ?? null,
gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null,
gitlab_instance_version: this.#api.instanceVersion ?? null,
is_streaming: isStreaming ?? false,
is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind),
options_count: optionsCount ?? null,
has_advanced_context: advancedContextData.hasAdvancedContext,
is_direct_connection: isDirectConnection ?? null,
total_context_size_bytes: advancedContextData.totalContextSizeBytes,
content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes,
content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes,
context_items: advancedContextData.contextItems,
},
});
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
// FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute
// the solution might be some generic update method used by both
public updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate;
if (context) {
if (model) {
context.data.language = model.lang ?? null;
context.data.model_engine = model.engine ?? null;
context.data.model_name = model.name ?? null;
context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null;
context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null;
context.data.context_tokens_sent =
model.tokens_consumption_metadata?.context_tokens_sent ?? null;
context.data.context_tokens_used =
model.tokens_consumption_metadata?.context_tokens_used ?? null;
}
if (status) {
context.data.api_status_code = status;
}
if (optionsCount) {
context.data.options_count = optionsCount;
}
if (isDirectConnection !== undefined) {
context.data.is_direct_connection = isDirectConnection;
}
if (acceptedOption) {
context.data.accepted_option = acceptedOption;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
if (!this.isEnabled()) {
return;
}
const event: StructuredEvent = {
category: CODE_SUGGESTIONS_CATEGORY,
action: eventType,
label: uniqueTrackingId,
};
try {
const contexts: SelfDescribingJson[] = [this.#clientContext];
const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
if (codeSuggestionContext) {
contexts.push(codeSuggestionContext);
}
const suggestionContextValid = this.#ajv.validate(
CodeSuggestionContextSchema,
codeSuggestionContext?.data,
);
if (!suggestionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
const ideExtensionContextValid = this.#ajv.validate(
IdeExtensionContextSchema,
this.#clientContext?.data,
);
if (!ideExtensionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
await this.#snowplow.trackStructEvent(event, contexts);
} catch (error) {
log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error);
}
}
public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const isStreaming = Boolean(
this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming,
);
const allowedTransitions = isStreaming
? streamingSuggestionStateGraph.get(state)
: nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
rejectOpenedSuggestions() {
log.debug(`Snowplow Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
#hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null {
const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextFeatureFlagsEnabled) {
return Boolean(advancedContexts?.length);
}
return null;
}
#getAdvancedContextData({
additionalContexts,
documentContext,
}: {
additionalContexts?: AdditionalContext[];
documentContext?: IDocContext;
}) {
const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts);
const contentAboveCursorSizeBytes = documentContext?.prefix
? getByteSize(documentContext.prefix)
: 0;
const contentBelowCursorSizeBytes = documentContext?.suffix
? getByteSize(documentContext.suffix)
: 0;
const contextItems: ContextItem[] | null =
additionalContexts?.map((item) => ({
file_extension: item.name.split('.').pop() || '',
type: item.type,
resolution_strategy: item.resolution_strategy,
byte_size: item?.content ? getByteSize(item.content) : 0,
})) ?? null;
const totalContextSizeBytes =
contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0;
return {
totalContextSizeBytes,
contentAboveCursorSizeBytes,
contentBelowCursorSizeBytes,
contextItems,
hasAdvancedContext,
};
}
static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null {
let isInvoked = null;
if (triggerKind === InlineCompletionTriggerKind.Invoked) {
isInvoked = true;
} else if (triggerKind === InlineCompletionTriggerKind.Automatic) {
isInvoked = false;
}
return isInvoked;
}
}
References: |
You are a code assistant | Definition of 'transform' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp | Definition:
transform(code, id) {
if (id.endsWith('@gitlab/svgs/dist/icons.svg')) {
svgSpriteContent = fs.readFileSync(id, 'utf-8');
return 'export default ""';
}
if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) {
const base64Data = imageToBase64(id);
return `export default "data:image/svg+xml;base64,${base64Data}"`;
}
return code;
},
};
export function createViteConfigForWebview(name): UserConfig {
const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`);
return {
plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src/app', import.meta.url)),
},
},
root: './src/app',
base: '',
build: {
target: 'es2022',
emptyOutDir: true,
outDir,
rollupOptions: {
input: [path.join('src', 'app', 'index.html')],
},
},
};
}
References: |
You are a code assistant | Definition of 'TELEMETRY_NOTIFICATION' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
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 'DEFAULT_TRACKING_ENDPOINT' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
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 'IConfig' in file src/common/config_service.ts in project gitlab-lsp | Definition:
export interface IConfig {
// TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig
client: IClientConfig;
}
/**
* ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled)
* TODO: Maybe in the future we would like to separate these two
*/
export interface ConfigService {
get: TypedGetter<IConfig>;
/**
* set sets the property of the config
* the new value completely overrides the old one
*/
set: TypedSetter<IConfig>;
onConfigChange(listener: (config: IConfig) => void): Disposable;
/**
* merge adds `newConfig` properties into existing config, if the
* property is present in both old and new config, `newConfig`
* properties take precedence unless not defined
*
* This method performs deep merge
*
* **Arrays are not merged; they are replaced with the new value.**
*
*/
merge(newConfig: Partial<IConfig>): void;
}
export const ConfigService = createInterfaceId<ConfigService>('ConfigService');
@Injectable(ConfigService, [])
export class DefaultConfigService implements ConfigService {
#config: IConfig;
#eventEmitter = new EventEmitter();
constructor() {
this.#config = {
client: {
baseUrl: GITLAB_API_BASE_URL,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: true,
},
logLevel: LOG_LEVEL.INFO,
ignoreCertificateErrors: false,
httpAgentOptions: {},
},
};
}
get: TypedGetter<IConfig> = (key?: string) => {
return key ? get(this.#config, key) : this.#config;
};
set: TypedSetter<IConfig> = (key: string, value: unknown) => {
set(this.#config, key, value);
this.#triggerChange();
};
onConfigChange(listener: (config: IConfig) => void): Disposable {
this.#eventEmitter.on('configChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('configChange', this.#config);
}
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References:
- src/common/config_service.ts:112
- src/node/duo_workflow/desktop_workflow_runner.ts:59
- src/common/tracking/instance_tracker.ts:57
- src/common/config_service.ts:94
- src/common/security_diagnostics_publisher.ts:46
- src/common/config_service.ts:142
- src/common/tracking/snowplow_tracker.ts:187 |
You are a code assistant | Definition of 'rejectOpenedSuggestions' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References: |
You are a code assistant | Definition of 'loadStateValue' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
get loadStateValue(): TreeSitterParserLoadState {
return this.loadState;
}
async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> {
const init = await this.#handleInit();
if (!init) {
return undefined;
}
const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath);
if (!languageInfo) {
return undefined;
}
const parser = await this.getParser(languageInfo);
if (!parser) {
log.debug(
'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.',
);
return undefined;
}
const tree = parser.parse(`${context.prefix}${context.suffix}`);
return {
tree,
language: parser.getLanguage(),
languageInfo,
};
}
async #handleInit(): Promise<boolean> {
try {
await this.init();
return true;
} catch (err) {
log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
return false;
}
getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined {
return this.getLanguageInfoForFile(filename)?.name;
}
async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> {
if (this.parsers.has(languageInfo.name)) {
return this.parsers.get(languageInfo.name) as Parser;
}
try {
const parser = new Parser();
const language = await Parser.Language.load(languageInfo.wasmPath);
parser.setLanguage(language);
this.parsers.set(languageInfo.name, parser);
log.debug(
`TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`,
);
return parser;
} catch (err) {
this.loadState = TreeSitterParserLoadState.ERRORED;
// NOTE: We validate the below is not present in generation.test.ts integration test.
// Make sure to update the test appropriately if changing the error.
log.warn(
'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.',
err,
);
return undefined;
}
}
getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined {
const ext = filename.split('.').pop();
return this.languages.get(`.${ext}`);
}
buildTreeSitterInfoByExtMap(
languages: TreeSitterLanguageInfo[],
): Map<string, TreeSitterLanguageInfo> {
return languages.reduce((map, language) => {
for (const extension of language.extensions) {
map.set(extension, language);
}
return map;
}, new Map<string, TreeSitterLanguageInfo>());
}
}
References: |
You are a code assistant | Definition of 'instanceVersion' in file src/common/api.ts in project gitlab-lsp | Definition:
get instanceVersion() {
return this.#instanceVersion;
}
}
References: |
You are a code assistant | Definition of 'constructor' in file packages/lib_handler_registry/src/errors/handler_not_found_error.ts in project gitlab-lsp | Definition:
constructor(key: string) {
const message = `Handler not found for key ${key}`;
super(message);
}
}
References: |
You are a code assistant | Definition of 'WEB_IDE_EXTENSION_ID' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export const WEB_IDE_EXTENSION_ID = 'gitlab.gitlab-web-ide';
export const WEB_IDE_AUTH_PROVIDER_ID = 'gitlab-web-ide';
export const WEB_IDE_AUTH_SCOPE = 'api';
// region: Mediator commands -------------------------------------------
export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`;
export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`;
export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`;
export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`;
// Return type from `COMMAND_FETCH_BUFFER_FROM_API`
export interface VSCodeBuffer {
readonly buffer: Uint8Array;
}
// region: Shared configuration ----------------------------------------
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'GitLabProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_project.ts in project gitlab-lsp | Definition:
export interface GitLabProject {
gqlId: string;
restId: number;
name: string;
description: string;
namespaceWithPath: string;
webUrl: string;
// TODO: This is used only in one spot, probably a good idea to remove it from this main class
groupRestId?: number;
}
References:
- packages/webview_duo_chat/src/plugin/chat_platform.ts:47
- packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:28 |
You are a code assistant | Definition of 'constructor' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp | Definition:
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: |
You are a code assistant | Definition of 'WithConstructor' in file packages/lib_di/src/index.ts in project gitlab-lsp | Definition:
type WithConstructor = { new (...args: any[]): any; name: string };
type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] };
type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void;
const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, '');
/** ensures that only one interface ID implementation is present */
const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => {
const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id));
if (clashingWithExistingInstance.length > 0) {
throw new Error(
`The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`,
);
}
const groupedById = groupBy(cwds, (cwd) => cwd.id);
if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) {
return;
}
const messages = Object.entries(groupedById).map(
([id, groupedCwds]) =>
`'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`,
);
throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`);
};
/** throws an error if any class depends on an interface that is not available */
const dependenciesArePresent: Validator = (cwds, instanceIds) => {
const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]);
const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d)));
if (cwsWithUnmetDeps.length === 0) {
return;
}
const messages = cwsWithUnmetDeps.map((cwd) => {
const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId);
return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`;
});
throw new Error(messages.join('\n'));
};
/** uses depth first search to find out if the classes have circular dependency */
const noCircularDependencies: Validator = (cwds, instanceIds) => {
const inStack = new Set<string>();
const hasCircularDependency = (id: string): boolean => {
if (inStack.has(id)) {
return true;
}
inStack.add(id);
const cwd = cwds.find((c) => c.id === id);
// we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies
if (!cwd && instanceIds.includes(id)) {
inStack.delete(id);
return false;
}
if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`);
for (const dependencyId of cwd.dependencies) {
if (hasCircularDependency(dependencyId)) {
return true;
}
}
inStack.delete(id);
return false;
};
for (const cwd of cwds) {
if (hasCircularDependency(cwd.id)) {
throw new Error(
`Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`,
);
}
}
};
/**
* Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array.
* https://en.wikipedia.org/wiki/Topological_sorting
*/
const sortDependencies = (classes: Map<string, ClassWithDependencies>): ClassWithDependencies[] => {
const visited = new Set<string>();
const sortedClasses: ClassWithDependencies[] = [];
const topologicalSort = (interfaceId: string) => {
if (visited.has(interfaceId)) {
return;
}
visited.add(interfaceId);
const cwd = classes.get(interfaceId);
if (!cwd) {
// the instance for this ID is already initiated
return;
}
for (const d of cwd.dependencies || []) {
topologicalSort(d);
}
sortedClasses.push(cwd);
};
for (const id of classes.keys()) {
topologicalSort(id);
}
return sortedClasses;
};
/**
* Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded
*/
export type BrandedInstance<T extends object> = T;
/**
* use brandInstance to be able to pass this instance to the container.addInstances method
*/
export const brandInstance = <T extends object>(
id: InterfaceId<T>,
instance: T,
): BrandedInstance<T> => {
injectableMetadata.set(instance, { id, dependencies: [] });
return instance;
};
/**
* Container is responsible for initializing a dependency tree.
*
* It receives a list of classes decorated with the `@Injectable` decorator
* and it constructs instances of these classes in an order that ensures class' dependencies
* are initialized before the class itself.
*
* check https://gitlab.com/viktomas/needle for full documentation of this mini-framework
*/
export class Container {
#instances = new Map<string, unknown>();
/**
* addInstances allows you to add pre-initialized objects to the container.
* This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection).
* addInstances accepts a list of any objects that have been "branded" by the `brandInstance` method
*/
addInstances(...instances: BrandedInstance<object>[]) {
for (const instance of instances) {
const metadata = injectableMetadata.get(instance);
if (!metadata) {
throw new Error(
'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`',
);
}
if (this.#instances.has(metadata.id)) {
throw new Error(
`you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`,
);
}
this.#instances.set(metadata.id, instance);
}
}
/**
* instantiate accepts list of classes, validates that they can be managed by the container
* and then initialized them in such order that dependencies of a class are initialized before the class
*/
instantiate(...classes: WithConstructor[]) {
// ensure all classes have been decorated with @Injectable
const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name);
if (undecorated.length) {
throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`);
}
const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => {
// we verified just above that all classes are present in the metadata map
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { id, dependencies } = injectableMetadata.get(cls)!;
return { cls, id, dependencies };
});
const validators: Validator[] = [
interfaceUsedOnlyOnce,
dependenciesArePresent,
noCircularDependencies,
];
validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys())));
const classesById = new Map<string, ClassWithDependencies>();
// Index classes by their interface id
classesWithDeps.forEach((cwd) => {
classesById.set(cwd.id, cwd);
});
// Create instances in topological order
for (const cwd of sortDependencies(classesById)) {
const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId));
// eslint-disable-next-line new-cap
const instance = new cwd.cls(...args);
this.#instances.set(cwd.id, instance);
}
}
get<T>(id: InterfaceId<T>): T {
const instance = this.#instances.get(id);
if (!instance) {
throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`);
}
return instance as T;
}
}
References:
- packages/lib_di/src/index.ts:70 |
You are a code assistant | Definition of 'transformIndexHtml' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp | Definition:
transformIndexHtml(html) {
return html.replace('{{ svg placeholder }}', svgSpriteContent);
},
};
export const InlineSvgPlugin = {
name: 'inline-svg',
transform(code, id) {
if (id.endsWith('@gitlab/svgs/dist/icons.svg')) {
svgSpriteContent = fs.readFileSync(id, 'utf-8');
return 'export default ""';
}
if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) {
const base64Data = imageToBase64(id);
return `export default "data:image/svg+xml;base64,${base64Data}"`;
}
return code;
},
};
export function createViteConfigForWebview(name): UserConfig {
const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`);
return {
plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src/app', import.meta.url)),
},
},
root: './src/app',
base: '',
build: {
target: 'es2022',
emptyOutDir: true,
outDir,
rollupOptions: {
input: [path.join('src', 'app', 'index.html')],
},
},
};
}
References: |
You are a code assistant | Definition of 'Intent' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp | Definition:
export type Intent = 'completion' | 'generation' | undefined;
export type IntentResolution = {
intent: Intent;
commentForCursor?: Comment;
generationType?: GenerationType;
};
/**
* Determines the user intent based on cursor position and context within the file.
* Intent is determined based on several ordered rules:
* - Returns 'completion' if the cursor is located on or after an empty comment.
* - Returns 'generation' if the cursor is located after a non-empty comment.
* - Returns 'generation' if the cursor is not located after a comment and the file is less than 5 lines.
* - Returns undefined if neither a comment nor small file is detected.
*/
export async function getIntent({
treeAndLanguage,
position,
prefix,
suffix,
}: {
treeAndLanguage: TreeAndLanguage;
position: Position;
prefix: string;
suffix: string;
}): Promise<IntentResolution> {
const commentResolver = getCommentResolver();
const emptyFunctionResolver = getEmptyFunctionResolver();
const cursorPosition = { row: position.line, column: position.character };
const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage;
const commentResolution = commentResolver.getCommentForCursor({
languageName: languageInfo.name,
tree,
cursorPosition,
treeSitterLanguage,
});
if (commentResolution) {
const { commentAtCursor, commentAboveCursor } = commentResolution;
if (commentAtCursor) {
log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion');
return { intent: 'completion' };
}
const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor);
if (isCommentEmpty) {
log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion');
return { intent: 'completion' };
}
log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation');
return {
intent: 'generation',
generationType: 'comment',
commentForCursor: commentAboveCursor,
};
}
const textContent = `${prefix}${suffix}`;
const totalCommentLines = commentResolver.getTotalCommentLines({
languageName: languageInfo.name,
treeSitterLanguage,
tree,
});
if (isSmallFile(textContent, totalCommentLines)) {
log.debug('IntentResolver: Small file detected, sending intent: generation');
return { intent: 'generation', generationType: 'small_file' };
}
const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({
languageName: languageInfo.name,
tree,
cursorPosition,
treeSitterLanguage,
});
if (isCursorInEmptyFunction) {
log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation');
return { intent: 'generation', generationType: 'empty_function' };
}
log.debug(
'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.',
);
return { intent: undefined };
}
References:
- src/common/tree_sitter/intent_resolver.ts:12
- src/common/suggestion_client/suggestion_client.ts:21 |
You are a code assistant | Definition of 'ISnowplowCodeSuggestionContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp | Definition:
export interface ISnowplowCodeSuggestionContext {
schema: string;
data: {
prefix_length?: number;
suffix_length?: number;
language?: string | null;
gitlab_realm?: GitlabRealm;
model_engine?: string | null;
model_name?: string | null;
api_status_code?: number | null;
debounce_interval?: number | null;
suggestion_source?: SuggestionSource;
gitlab_global_user_id?: string | null;
gitlab_instance_id?: string | null;
gitlab_host_name?: string | null;
gitlab_saas_duo_pro_namespace_ids: number[] | null;
gitlab_instance_version: string | null;
is_streaming?: boolean;
is_invoked?: boolean | null;
options_count?: number | null;
accepted_option?: number | null;
/**
* boolean indicating whether the feature is enabled
* and we sent context in the request
*/
has_advanced_context?: boolean | null;
/**
* boolean indicating whether request is direct to cloud connector
*/
is_direct_connection?: boolean | null;
total_context_size_bytes?: number;
content_above_cursor_size_bytes?: number;
content_below_cursor_size_bytes?: number;
/**
* set of final context items sent to AI Gateway
*/
context_items?: ContextItem[] | null;
/**
* total tokens used in request to model provider
*/
input_tokens?: number | null;
/**
* total output tokens recieved from model provider
*/
output_tokens?: number | null;
/**
* total tokens sent as context to AI Gateway
*/
context_tokens_sent?: number | null;
/**
* total context tokens used in request to model provider
*/
context_tokens_used?: number | null;
};
}
interface ISnowplowClientContext {
schema: string;
data: {
ide_name?: string | null;
ide_vendor?: string | null;
ide_version?: string | null;
extension_name?: string | null;
extension_version?: string | null;
language_server_version?: string | null;
};
}
const DEFAULT_SNOWPLOW_OPTIONS = {
appId: 'gitlab_ide_extension',
timeInterval: 5000,
maxItems: 10,
};
export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`;
export class SnowplowTracker implements TelemetryTracker {
#snowplow: Snowplow;
#ajv = new Ajv({ strict: false });
#configService: ConfigService;
#api: GitLabApiClient;
#options: ITelemetryOptions = {
enabled: true,
baseUrl: SAAS_INSTANCE_URL,
trackingUrl: DEFAULT_TRACKING_ENDPOINT,
// the list of events that the client can track themselves
actions: [],
};
#clientContext: ISnowplowClientContext = {
schema: 'iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0',
data: {},
};
#codeSuggestionStates = new Map<string, TRACKING_EVENTS>();
#lsFetch: LsFetch;
#featureFlagService: FeatureFlagService;
#gitlabRealm: GitlabRealm = GitlabRealm.saas;
#codeSuggestionsContextMap = new Map<string, ISnowplowCodeSuggestionContext>();
constructor(
lsFetch: LsFetch,
configService: ConfigService,
featureFlagService: FeatureFlagService,
api: GitLabApiClient,
) {
this.#configService = configService;
this.#configService.onConfigChange((config) => this.#reconfigure(config));
this.#api = api;
const trackingUrl = DEFAULT_TRACKING_ENDPOINT;
this.#lsFetch = lsFetch;
this.#configService = configService;
this.#featureFlagService = featureFlagService;
this.#snowplow = Snowplow.getInstance(this.#lsFetch, {
...DEFAULT_SNOWPLOW_OPTIONS,
endpoint: trackingUrl,
enabled: this.isEnabled.bind(this),
});
this.#options.trackingUrl = trackingUrl;
this.#ajv.addMetaSchema(SnowplowMetaSchema);
}
isEnabled(): boolean {
return Boolean(this.#options.enabled);
}
async #reconfigure(config: IConfig) {
const { baseUrl } = config.client;
const trackingUrl = config.client.telemetry?.trackingUrl;
const enabled = config.client.telemetry?.enabled;
const actions = config.client.telemetry?.actions;
if (typeof enabled !== 'undefined') {
this.#options.enabled = enabled;
if (enabled === false) {
log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`);
} else if (enabled === true) {
log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`);
}
}
if (baseUrl) {
this.#options.baseUrl = baseUrl;
this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL)
? GitlabRealm.saas
: GitlabRealm.selfManaged;
}
if (trackingUrl && this.#options.trackingUrl !== trackingUrl) {
await this.#snowplow.stop();
this.#snowplow.destroy();
this.#snowplow = Snowplow.getInstance(this.#lsFetch, {
...DEFAULT_SNOWPLOW_OPTIONS,
endpoint: trackingUrl,
enabled: this.isEnabled.bind(this),
});
}
if (actions) {
this.#options.actions = actions;
}
this.#setClientContext({
extension: config.client.telemetry?.extension,
ide: config.client.telemetry?.ide,
});
}
#setClientContext(context: IClientContext) {
this.#clientContext.data = {
ide_name: context?.ide?.name ?? null,
ide_vendor: context?.ide?.vendor ?? null,
ide_version: context?.ide?.version ?? null,
extension_name: context?.extension?.name ?? null,
extension_version: context?.extension?.version ?? null,
language_server_version: lsVersion ?? null,
};
}
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
const {
documentContext,
source = SuggestionSource.network,
language,
isStreaming,
triggerKind,
optionsCount,
additionalContexts,
isDirectConnection,
} = context;
const {
gitlab_instance_id,
gitlab_global_user_id,
gitlab_host_name,
gitlab_saas_duo_pro_namespace_ids,
} = this.#configService.get('client.snowplowTrackerOptions') ?? {};
if (source === SuggestionSource.cache) {
log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`);
} else {
log.debug(`Snowplow Telemetry: Received request to create a new suggestion`);
}
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
const advancedContextData = this.#getAdvancedContextData({
additionalContexts,
documentContext,
});
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0',
data: {
suffix_length: documentContext?.suffix.length ?? 0,
prefix_length: documentContext?.prefix.length ?? 0,
gitlab_realm: this.#gitlabRealm,
model_engine: null,
model_name: null,
language: language ?? null,
api_status_code: null,
debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS,
suggestion_source: source,
gitlab_global_user_id: gitlab_global_user_id ?? null,
gitlab_host_name: gitlab_host_name ?? null,
gitlab_instance_id: gitlab_instance_id ?? null,
gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null,
gitlab_instance_version: this.#api.instanceVersion ?? null,
is_streaming: isStreaming ?? false,
is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind),
options_count: optionsCount ?? null,
has_advanced_context: advancedContextData.hasAdvancedContext,
is_direct_connection: isDirectConnection ?? null,
total_context_size_bytes: advancedContextData.totalContextSizeBytes,
content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes,
content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes,
context_items: advancedContextData.contextItems,
},
});
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
// FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute
// the solution might be some generic update method used by both
public updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate;
if (context) {
if (model) {
context.data.language = model.lang ?? null;
context.data.model_engine = model.engine ?? null;
context.data.model_name = model.name ?? null;
context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null;
context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null;
context.data.context_tokens_sent =
model.tokens_consumption_metadata?.context_tokens_sent ?? null;
context.data.context_tokens_used =
model.tokens_consumption_metadata?.context_tokens_used ?? null;
}
if (status) {
context.data.api_status_code = status;
}
if (optionsCount) {
context.data.options_count = optionsCount;
}
if (isDirectConnection !== undefined) {
context.data.is_direct_connection = isDirectConnection;
}
if (acceptedOption) {
context.data.accepted_option = acceptedOption;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
if (!this.isEnabled()) {
return;
}
const event: StructuredEvent = {
category: CODE_SUGGESTIONS_CATEGORY,
action: eventType,
label: uniqueTrackingId,
};
try {
const contexts: SelfDescribingJson[] = [this.#clientContext];
const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
if (codeSuggestionContext) {
contexts.push(codeSuggestionContext);
}
const suggestionContextValid = this.#ajv.validate(
CodeSuggestionContextSchema,
codeSuggestionContext?.data,
);
if (!suggestionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
const ideExtensionContextValid = this.#ajv.validate(
IdeExtensionContextSchema,
this.#clientContext?.data,
);
if (!ideExtensionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
await this.#snowplow.trackStructEvent(event, contexts);
} catch (error) {
log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error);
}
}
public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const isStreaming = Boolean(
this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming,
);
const allowedTransitions = isStreaming
? streamingSuggestionStateGraph.get(state)
: nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
rejectOpenedSuggestions() {
log.debug(`Snowplow Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
#hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null {
const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextFeatureFlagsEnabled) {
return Boolean(advancedContexts?.length);
}
return null;
}
#getAdvancedContextData({
additionalContexts,
documentContext,
}: {
additionalContexts?: AdditionalContext[];
documentContext?: IDocContext;
}) {
const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts);
const contentAboveCursorSizeBytes = documentContext?.prefix
? getByteSize(documentContext.prefix)
: 0;
const contentBelowCursorSizeBytes = documentContext?.suffix
? getByteSize(documentContext.suffix)
: 0;
const contextItems: ContextItem[] | null =
additionalContexts?.map((item) => ({
file_extension: item.name.split('.').pop() || '',
type: item.type,
resolution_strategy: item.resolution_strategy,
byte_size: item?.content ? getByteSize(item.content) : 0,
})) ?? null;
const totalContextSizeBytes =
contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0;
return {
totalContextSizeBytes,
contentAboveCursorSizeBytes,
contentBelowCursorSizeBytes,
contextItems,
hasAdvancedContext,
};
}
static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null {
let isInvoked = null;
if (triggerKind === InlineCompletionTriggerKind.Invoked) {
isInvoked = true;
} else if (triggerKind === InlineCompletionTriggerKind.Automatic) {
isInvoked = false;
}
return isInvoked;
}
}
References: |
You are a code assistant | Definition of 'sendDidChangeDocumentInActiveEditor' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
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 'PostRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp | Definition:
interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'POST';
body?: unknown;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the TReturnType
*/
interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'GET';
searchParams?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
export interface GitLabApiClient {
fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>;
connectToCable(): Promise<Cable>;
}
References: |
You are a code assistant | Definition of 'WorkspaceFilesUpdate' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp | Definition:
export type WorkspaceFilesUpdate = {
files: URI[];
workspaceFolder: WorkspaceFolder;
};
export enum VirtualFileSystemEvents {
WorkspaceFileUpdate = 'workspaceFileUpdate',
WorkspaceFilesUpdate = 'workspaceFilesUpdate',
}
const FILE_SYSTEM_EVENT_NAME = 'fileSystemEvent';
export interface FileSystemEventMap {
[VirtualFileSystemEvents.WorkspaceFileUpdate]: WorkspaceFileUpdate;
[VirtualFileSystemEvents.WorkspaceFilesUpdate]: WorkspaceFilesUpdate;
}
export interface FileSystemEventListener {
<T extends VirtualFileSystemEvents>(eventType: T, data: FileSystemEventMap[T]): void;
}
export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype;
export const VirtualFileSystemService = createInterfaceId<VirtualFileSystemService>(
'VirtualFileSystemService',
);
@Injectable(VirtualFileSystemService, [DirectoryWalker])
export class DefaultVirtualFileSystemService {
#directoryWalker: DirectoryWalker;
#emitter = new EventEmitter();
constructor(directoryWalker: DirectoryWalker) {
this.#directoryWalker = directoryWalker;
}
#handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => {
const fileUri = fsPathToUri(filePath);
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, {
event,
fileUri,
workspaceFolder,
});
};
async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> {
await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
const files = await this.#directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
});
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, {
files,
workspaceFolder,
});
this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange);
}),
);
}
#emitFileSystemEvent<T extends VirtualFileSystemEvents>(
eventType: T,
data: FileSystemEventMap[T],
) {
this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data);
}
onFileSystemEvent(listener: FileSystemEventListener) {
this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener),
};
}
}
References:
- src/common/git/repository_service.ts:182
- src/common/workspace/workspace_service.ts:46
- src/common/services/fs/virtual_file_service.ts:27
- src/common/git/repository_service.ts:51 |
You are a code assistant | Definition of 'DefaultDuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
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/services/duo_access/project_access_checker.test.ts:18 |
You are a code assistant | Definition of 'Metadata' in file packages/lib_di/src/index.ts in project gitlab-lsp | Definition:
interface Metadata {
id: string;
dependencies: string[];
}
/**
* Here we store the id and dependencies for all classes decorated with @Injectable
*/
const injectableMetadata = new WeakMap<object, Metadata>();
/**
* Decorate your class with @Injectable(id, dependencies)
* param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one)
* param dependencies = List of InterfaceIds that will be injected into class' constructor
*/
export function Injectable<I, TDependencies extends InterfaceId<unknown>[]>(
id: InterfaceId<I>,
dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments
) {
// this is the trickiest part of the whole DI framework
// we say, this decorator takes
// - id (the interface that the injectable implements)
// - dependencies (list of interface ids that will be injected to constructor)
//
// With then we return function that ensures that the decorated class implements the id interface
// and its constructor has arguments of same type and order as the dependencies argument to the decorator
return function <T extends { new (...args: UnwrapInterfaceIds<TDependencies>): I }>(
constructor: T,
{ kind }: ClassDecoratorContext,
) {
if (kind === 'class') {
injectableMetadata.set(constructor, { id, dependencies: dependencies || [] });
return constructor;
}
throw new Error('Injectable decorator can only be used on a class.');
};
}
// new (...args: any[]): any is actually how TS defines type of a class
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type WithConstructor = { new (...args: any[]): any; name: string };
type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] };
type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void;
const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, '');
/** ensures that only one interface ID implementation is present */
const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => {
const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id));
if (clashingWithExistingInstance.length > 0) {
throw new Error(
`The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`,
);
}
const groupedById = groupBy(cwds, (cwd) => cwd.id);
if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) {
return;
}
const messages = Object.entries(groupedById).map(
([id, groupedCwds]) =>
`'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`,
);
throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`);
};
/** throws an error if any class depends on an interface that is not available */
const dependenciesArePresent: Validator = (cwds, instanceIds) => {
const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]);
const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d)));
if (cwsWithUnmetDeps.length === 0) {
return;
}
const messages = cwsWithUnmetDeps.map((cwd) => {
const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId);
return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`;
});
throw new Error(messages.join('\n'));
};
/** uses depth first search to find out if the classes have circular dependency */
const noCircularDependencies: Validator = (cwds, instanceIds) => {
const inStack = new Set<string>();
const hasCircularDependency = (id: string): boolean => {
if (inStack.has(id)) {
return true;
}
inStack.add(id);
const cwd = cwds.find((c) => c.id === id);
// we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies
if (!cwd && instanceIds.includes(id)) {
inStack.delete(id);
return false;
}
if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`);
for (const dependencyId of cwd.dependencies) {
if (hasCircularDependency(dependencyId)) {
return true;
}
}
inStack.delete(id);
return false;
};
for (const cwd of cwds) {
if (hasCircularDependency(cwd.id)) {
throw new Error(
`Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`,
);
}
}
};
/**
* Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array.
* https://en.wikipedia.org/wiki/Topological_sorting
*/
const sortDependencies = (classes: Map<string, ClassWithDependencies>): ClassWithDependencies[] => {
const visited = new Set<string>();
const sortedClasses: ClassWithDependencies[] = [];
const topologicalSort = (interfaceId: string) => {
if (visited.has(interfaceId)) {
return;
}
visited.add(interfaceId);
const cwd = classes.get(interfaceId);
if (!cwd) {
// the instance for this ID is already initiated
return;
}
for (const d of cwd.dependencies || []) {
topologicalSort(d);
}
sortedClasses.push(cwd);
};
for (const id of classes.keys()) {
topologicalSort(id);
}
return sortedClasses;
};
/**
* Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded
*/
export type BrandedInstance<T extends object> = T;
/**
* use brandInstance to be able to pass this instance to the container.addInstances method
*/
export const brandInstance = <T extends object>(
id: InterfaceId<T>,
instance: T,
): BrandedInstance<T> => {
injectableMetadata.set(instance, { id, dependencies: [] });
return instance;
};
/**
* Container is responsible for initializing a dependency tree.
*
* It receives a list of classes decorated with the `@Injectable` decorator
* and it constructs instances of these classes in an order that ensures class' dependencies
* are initialized before the class itself.
*
* check https://gitlab.com/viktomas/needle for full documentation of this mini-framework
*/
export class Container {
#instances = new Map<string, unknown>();
/**
* addInstances allows you to add pre-initialized objects to the container.
* This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection).
* addInstances accepts a list of any objects that have been "branded" by the `brandInstance` method
*/
addInstances(...instances: BrandedInstance<object>[]) {
for (const instance of instances) {
const metadata = injectableMetadata.get(instance);
if (!metadata) {
throw new Error(
'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`',
);
}
if (this.#instances.has(metadata.id)) {
throw new Error(
`you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`,
);
}
this.#instances.set(metadata.id, instance);
}
}
/**
* instantiate accepts list of classes, validates that they can be managed by the container
* and then initialized them in such order that dependencies of a class are initialized before the class
*/
instantiate(...classes: WithConstructor[]) {
// ensure all classes have been decorated with @Injectable
const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name);
if (undecorated.length) {
throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`);
}
const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => {
// we verified just above that all classes are present in the metadata map
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { id, dependencies } = injectableMetadata.get(cls)!;
return { cls, id, dependencies };
});
const validators: Validator[] = [
interfaceUsedOnlyOnce,
dependenciesArePresent,
noCircularDependencies,
];
validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys())));
const classesById = new Map<string, ClassWithDependencies>();
// Index classes by their interface id
classesWithDeps.forEach((cwd) => {
classesById.set(cwd.id, cwd);
});
// Create instances in topological order
for (const cwd of sortDependencies(classesById)) {
const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId));
// eslint-disable-next-line new-cap
const instance = new cwd.cls(...args);
this.#instances.set(cwd.id, instance);
}
}
get<T>(id: InterfaceId<T>): T {
const instance = this.#instances.get(id);
if (!instance) {
throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`);
}
return instance as T;
}
}
References: |
You are a code assistant | Definition of 'ExponentialBackoffCircuitBreaker' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp | Definition:
export class ExponentialBackoffCircuitBreaker implements CircuitBreaker {
#name: string;
#state: CircuitBreakerState = CircuitBreakerState.CLOSED;
readonly #initialBackoffMs: number;
readonly #maxBackoffMs: number;
readonly #backoffMultiplier: number;
#errorCount = 0;
#eventEmitter = new EventEmitter();
#timeoutId: NodeJS.Timeout | null = null;
constructor(
name: string,
{
initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS,
maxBackoffMs = DEFAULT_MAX_BACKOFF_MS,
backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER,
}: ExponentialBackoffCircuitBreakerOptions = {},
) {
this.#name = name;
this.#initialBackoffMs = initialBackoffMs;
this.#maxBackoffMs = maxBackoffMs;
this.#backoffMultiplier = backoffMultiplier;
}
error() {
this.#errorCount += 1;
this.#open();
}
megaError() {
this.#errorCount += 3;
this.#open();
}
#open() {
if (this.#state === CircuitBreakerState.OPEN) {
return;
}
this.#state = CircuitBreakerState.OPEN;
log.warn(
`Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`,
);
this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime());
this.#eventEmitter.emit('open');
}
#close() {
if (this.#state === CircuitBreakerState.CLOSED) {
return;
}
if (this.#timeoutId) {
clearTimeout(this.#timeoutId);
}
this.#state = CircuitBreakerState.CLOSED;
this.#eventEmitter.emit('close');
}
isOpen() {
return this.#state === CircuitBreakerState.OPEN;
}
success() {
this.#errorCount = 0;
this.#close();
}
onOpen(listener: () => void): Disposable {
this.#eventEmitter.on('open', listener);
return { dispose: () => this.#eventEmitter.removeListener('open', listener) };
}
onClose(listener: () => void): Disposable {
this.#eventEmitter.on('close', listener);
return { dispose: () => this.#eventEmitter.removeListener('close', listener) };
}
#getBackoffTime() {
return Math.min(
this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1),
this.#maxBackoffMs,
);
}
}
References:
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:50
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:63
- src/common/suggestion_client/direct_connection_client.ts:36
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:80
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:92
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:35
- src/common/suggestion_client/direct_connection_client.ts:45
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:26
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:7
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:18
- src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:12 |
You are a code assistant | Definition of 'Transport' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
export interface Transport extends TransportListener, TransportPublisher {}
References:
- packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:8
- packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:8
- packages/lib_webview/src/setup/transport/setup_transport.ts:9 |
You are a code assistant | Definition of 'PostProcessorPipeline' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp | Definition:
export class PostProcessorPipeline {
#processors: PostProcessor[] = [];
addProcessor(processor: PostProcessor): void {
this.#processors.push(processor);
}
async run<T extends ProcessorType>({
documentContext,
input,
type,
}: {
documentContext: IDocContext;
input: ProcessorInputMap[T];
type: T;
}): Promise<ProcessorInputMap[T]> {
if (!this.#processors.length) return input as ProcessorInputMap[T];
return this.#processors.reduce(
async (prevPromise, processor) => {
const result = await prevPromise;
// eslint-disable-next-line default-case
switch (type) {
case 'stream':
return processor.processStream(
documentContext,
result as StreamingCompletionResponse,
) as Promise<ProcessorInputMap[T]>;
case 'completion':
return processor.processCompletion(
documentContext,
result as SuggestionOption[],
) as Promise<ProcessorInputMap[T]>;
}
throw new Error('Unexpected type in pipeline processing');
},
Promise.resolve(input) as Promise<ProcessorInputMap[T]>,
);
}
}
References:
- src/common/suggestion/streaming_handler.ts:41
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:7
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:11
- src/common/suggestion/suggestion_service.ts:139 |
You are a code assistant | Definition of 'AdvancedContextResolver' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp | Definition:
export abstract class AdvancedContextResolver {
abstract buildContext({
documentContext,
}: {
documentContext: IDocContext;
}): AsyncGenerator<ContextResolution>;
}
References: |
You are a code assistant | Definition of 'MessageMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp | Definition:
export type MessageMap<
TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions,
> = {
inbound: TInboundMessageDefinitions;
outbound: TOutboundMessageDefinitions;
};
export interface MessageBus<T extends MessageMap = MessageMap>
extends NotificationPublisher<T['outbound']['notifications']>,
NotificationListener<T['inbound']['notifications']>,
RequestPublisher<T['outbound']['requests']>,
RequestListener<T['inbound']['requests']> {}
References: |
You are a code assistant | Definition of 'getFiles' in file src/common/git/repository.ts in project gitlab-lsp | Definition:
getFiles(): Map<string, RepositoryFile> {
return this.#files;
}
dispose(): void {
this.#ignoreManager.dispose();
this.#files.clear();
}
}
References: |
You are a code assistant | Definition of 'MINIMUM_CODE_SUGGESTIONS_VERSION' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp | Definition:
export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0';
export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING';
// NOTE: This needs to _always_ be a 3 digits
export const MINIMUM_VERSION = '16.1.0';
export const REQUEST_TIMEOUT_MILLISECONDS = 25000;
// Webview IDs
export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow';
export const DUO_CHAT_WEBVIEW_ID = 'chat';
References: |
You are a code assistant | Definition of 'SHORT_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp | Definition:
export const SHORT_COMPLETION_CONTEXT: IDocContext = {
prefix: 'abc',
suffix: 'def',
fileRelativePath: 'test.js',
position: {
line: 0,
character: 3,
},
uri: 'file:///example.ts',
languageId: 'typescript',
};
export const LONG_COMPLETION_CONTEXT: IDocContext = {
prefix: 'abc 123',
suffix: 'def 456',
fileRelativePath: 'test.js',
position: {
line: 0,
character: 7,
},
uri: 'file:///example.ts',
languageId: 'typescript',
};
const textDocument: TextDocumentIdentifier = { uri: '/' };
const position: Position = { line: 0, character: 0 };
export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position };
References: |
You are a code assistant | Definition of 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.ts in project gitlab-lsp | Definition:
getMessageBus<TMessages extends MessageMap>(): MessageBus<TMessages> | null {
return 'gitlab' in window && isHostConfig<TMessages>(window.gitlab) ? window.gitlab.host : null;
}
}
References: |
You are a code assistant | Definition of 'SubmitFeedbackParams' in file packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts in project gitlab-lsp | Definition:
export type SubmitFeedbackParams = {
extendedTextFeedback: string | null;
feedbackChoices: string[] | null;
gitlabEnvironment: GitLabEnvironment;
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const submitFeedback = async (_: SubmitFeedbackParams) => {
// const hasFeedback = Boolean(extendedTextFeedback?.length) || Boolean(feedbackChoices?.length);
// if (!hasFeedback) {
// return;
// }
// const standardContext = buildStandardContext(extendedTextFeedback, gitlabEnvironment);
// const ideExtensionVersion = buildIdeExtensionContext();
// await Snowplow.getInstance().trackStructEvent(
// {
// category: 'ask_gitlab_chat',
// action: 'click_button',
// label: 'response_feedback',
// property: feedbackChoices?.join(','),
// },
// [standardContext, ideExtensionVersion],
// );
};
References:
- packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts:46 |
You are a code assistant | Definition of 'onClose' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
onClose(listener: () => void): Disposable;
}
References: |
You are a code assistant | Definition of 'STREAMING_COMPLETION_RESPONSE_NOTIFICATION' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp | Definition:
export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse';
export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming';
export const StreamingCompletionResponse = new NotificationType<StreamingCompletionResponse>(
STREAMING_COMPLETION_RESPONSE_NOTIFICATION,
);
export const CancelStreaming = new NotificationType<StreamWithId>(
CANCEL_STREAMING_COMPLETION_NOTIFICATION,
);
export interface StartStreamParams {
api: GitLabApiClient;
circuitBreaker: CircuitBreaker;
connection: Connection;
documentContext: IDocContext;
parser: TreeSitterParser;
postProcessorPipeline: PostProcessorPipeline;
streamId: string;
tracker: TelemetryTracker;
uniqueTrackingId: string;
userInstruction?: string;
generationType?: GenerationType;
additionalContexts?: AdditionalContext[];
}
export class DefaultStreamingHandler {
#params: StartStreamParams;
constructor(params: StartStreamParams) {
this.#params = params;
}
async startStream() {
return startStreaming(this.#params);
}
}
const startStreaming = async ({
additionalContexts,
api,
circuitBreaker,
connection,
documentContext,
parser,
postProcessorPipeline,
streamId,
tracker,
uniqueTrackingId,
userInstruction,
generationType,
}: StartStreamParams) => {
const language = parser.getLanguageNameForFile(documentContext.fileRelativePath);
tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
additionalContexts,
source: SuggestionSource.network,
language,
isStreaming: true,
});
let streamShown = false;
let suggestionProvided = false;
let streamCancelledOrErrored = false;
const cancellationTokenSource = new CancellationTokenSource();
const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => {
if (stream.id === streamId) {
streamCancelledOrErrored = true;
cancellationTokenSource.cancel();
if (streamShown) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
} else {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
}
}
});
const cancellationToken = cancellationTokenSource.token;
const endStream = async () => {
await connection.sendNotification(StreamingCompletionResponse, {
id: streamId,
done: true,
});
if (!streamCancelledOrErrored) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED);
if (!suggestionProvided) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
}
}
};
circuitBreaker.success();
const request: CodeSuggestionRequest = {
prompt_version: 1,
project_path: '',
project_id: -1,
current_file: {
content_above_cursor: documentContext.prefix,
content_below_cursor: documentContext.suffix,
file_name: documentContext.fileRelativePath,
},
intent: 'generation',
stream: true,
...(additionalContexts?.length && {
context: additionalContexts,
}),
...(userInstruction && {
user_instruction: userInstruction,
}),
generation_type: generationType,
};
const trackStreamStarted = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED);
});
const trackStreamShown = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
streamShown = true;
});
try {
for await (const response of api.getStreamingCodeSuggestions(request)) {
if (cancellationToken.isCancellationRequested) {
break;
}
if (circuitBreaker.isOpen()) {
break;
}
trackStreamStarted();
const processedCompletion = await postProcessorPipeline.run({
documentContext,
input: { id: streamId, completion: response, done: false },
type: 'stream',
});
await connection.sendNotification(StreamingCompletionResponse, processedCompletion);
if (response.replace(/\s/g, '').length) {
trackStreamShown();
suggestionProvided = true;
}
}
} catch (err) {
circuitBreaker.error();
if (isFetchError(err)) {
tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status });
}
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
streamCancelledOrErrored = true;
log.error('Error streaming code suggestions.', err);
} finally {
await endStream();
disposeStopStreaming.dispose();
cancellationTokenSource.dispose();
}
};
References: |
You are a code assistant | Definition of 'StreamingCompletionResponse' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp | Definition:
export const StreamingCompletionResponse = new NotificationType<StreamingCompletionResponse>(
STREAMING_COMPLETION_RESPONSE_NOTIFICATION,
);
export const CancelStreaming = new NotificationType<StreamWithId>(
CANCEL_STREAMING_COMPLETION_NOTIFICATION,
);
export interface StartStreamParams {
api: GitLabApiClient;
circuitBreaker: CircuitBreaker;
connection: Connection;
documentContext: IDocContext;
parser: TreeSitterParser;
postProcessorPipeline: PostProcessorPipeline;
streamId: string;
tracker: TelemetryTracker;
uniqueTrackingId: string;
userInstruction?: string;
generationType?: GenerationType;
additionalContexts?: AdditionalContext[];
}
export class DefaultStreamingHandler {
#params: StartStreamParams;
constructor(params: StartStreamParams) {
this.#params = params;
}
async startStream() {
return startStreaming(this.#params);
}
}
const startStreaming = async ({
additionalContexts,
api,
circuitBreaker,
connection,
documentContext,
parser,
postProcessorPipeline,
streamId,
tracker,
uniqueTrackingId,
userInstruction,
generationType,
}: StartStreamParams) => {
const language = parser.getLanguageNameForFile(documentContext.fileRelativePath);
tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
additionalContexts,
source: SuggestionSource.network,
language,
isStreaming: true,
});
let streamShown = false;
let suggestionProvided = false;
let streamCancelledOrErrored = false;
const cancellationTokenSource = new CancellationTokenSource();
const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => {
if (stream.id === streamId) {
streamCancelledOrErrored = true;
cancellationTokenSource.cancel();
if (streamShown) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
} else {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
}
}
});
const cancellationToken = cancellationTokenSource.token;
const endStream = async () => {
await connection.sendNotification(StreamingCompletionResponse, {
id: streamId,
done: true,
});
if (!streamCancelledOrErrored) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED);
if (!suggestionProvided) {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
}
}
};
circuitBreaker.success();
const request: CodeSuggestionRequest = {
prompt_version: 1,
project_path: '',
project_id: -1,
current_file: {
content_above_cursor: documentContext.prefix,
content_below_cursor: documentContext.suffix,
file_name: documentContext.fileRelativePath,
},
intent: 'generation',
stream: true,
...(additionalContexts?.length && {
context: additionalContexts,
}),
...(userInstruction && {
user_instruction: userInstruction,
}),
generation_type: generationType,
};
const trackStreamStarted = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED);
});
const trackStreamShown = once(() => {
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
streamShown = true;
});
try {
for await (const response of api.getStreamingCodeSuggestions(request)) {
if (cancellationToken.isCancellationRequested) {
break;
}
if (circuitBreaker.isOpen()) {
break;
}
trackStreamStarted();
const processedCompletion = await postProcessorPipeline.run({
documentContext,
input: { id: streamId, completion: response, done: false },
type: 'stream',
});
await connection.sendNotification(StreamingCompletionResponse, processedCompletion);
if (response.replace(/\s/g, '').length) {
trackStreamShown();
suggestionProvided = true;
}
}
} catch (err) {
circuitBreaker.error();
if (isFetchError(err)) {
tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status });
}
tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
streamCancelledOrErrored = true;
log.error('Error streaming code suggestions.', err);
} finally {
await endStream();
disposeStopStreaming.dispose();
cancellationTokenSource.dispose();
}
};
References:
- src/common/suggestion_client/post_processors/post_processor_pipeline.ts:9
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:119
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:16
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:58
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:44
- src/common/suggestion_client/post_processors/post_processor_pipeline.ts:23
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:133
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:149
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:103
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:87
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:179
- src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:29 |
You are a code assistant | Definition of 'constructor' in file src/common/suggestion_client/default_suggestion_client.ts in project gitlab-lsp | Definition:
constructor(api: GitLabApiClient) {
this.#api = api;
}
async getSuggestions(
suggestionContext: SuggestionContext,
): Promise<SuggestionResponse | undefined> {
const response = await this.#api.getCodeSuggestions(createV2Request(suggestionContext));
return response && { ...response, isDirectConnection: false };
}
}
References: |
You are a code assistant | Definition of 'WebviewHttpAccessInfoProvider' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp | Definition:
export class WebviewHttpAccessInfoProvider implements WebviewUriProvider {
#addressInfo: AddressInfo;
constructor(address: AddressInfo) {
this.#addressInfo = address;
}
getUri(webviewId: WebviewId): string {
return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`;
}
}
References:
- src/node/setup_http.ts:20 |
You are a code assistant | Definition of 'constructor' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp | Definition:
constructor(fileRetriever: AiContextFileRetriever) {
this.#fileRetriever = fileRetriever;
}
#items: Map<string, AiContextItem> = new Map();
addItem(item: AiContextItem): boolean {
if (this.#items.has(item.id)) {
return false;
}
this.#items.set(item.id, item);
return true;
}
removeItem(id: string): boolean {
return this.#items.delete(id);
}
getItem(id: string): AiContextItem | undefined {
return this.#items.get(id);
}
currentItems(): AiContextItem[] {
return Array.from(this.#items.values());
}
async retrieveItems(): Promise<AiContextItemWithContent[]> {
const items = Array.from(this.#items.values());
log.info(`Retrieving ${items.length} items`);
const retrievedItems = await Promise.all(
items.map(async (item) => {
try {
switch (item.type) {
case 'file': {
const content = await this.#fileRetriever.retrieve(item);
return content ? { ...item, content } : null;
}
default:
throw new Error(`Unknown item type: ${item.type}`);
}
} catch (error) {
log.error(`Failed to retrieve item ${item.id}`, error);
return null;
}
}),
);
return retrievedItems.filter((item) => item !== null);
}
}
References: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.