Skip to content

feat(language-service): support tsconfig path alias resolution for document links #5562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/language-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ connection.onInitialize(params => {
getPropertiesAtLocation(...args) {
return sendTsServerRequest('_vue:getPropertiesAtLocation', args);
},
resolveModuleName(...args) {
return sendTsServerRequest('_vue:resolveModuleName', args);
},
getDocumentHighlights(fileName, position) {
return sendTsServerRequest(
'_vue:documentHighlights-full',
Expand Down
2 changes: 1 addition & 1 deletion packages/language-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ export function createVueLanguageServicePlugins(
}) as NonNullable<typeof tsPluginClient>;

return [
createCssPlugin(),
createJsonPlugin(),
createPugFormatPlugin(),
createVueAutoSpacePlugin(),
Expand All @@ -64,6 +63,7 @@ export function createVueLanguageServicePlugins(
createVueInlayHintsPlugin(ts),

// type aware plugins
createCssPlugin(tsPluginClient),
createTypescriptSemanticTokensPlugin(tsPluginClient),
createVueAutoDotValuePlugin(ts, tsPluginClient),
createVueComponentSemanticTokensPlugin(tsPluginClient),
Expand Down
31 changes: 23 additions & 8 deletions packages/language-service/lib/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,31 @@ import type { LanguageServicePlugin, TextDocument, VirtualCode } from '@volar/la
import { isRenameEnabled } from '@vue/language-core';
import { create as baseCreate, type Provide } from 'volar-service-css';
import type * as css from 'vscode-css-languageservice';
import { getEmbeddedInfo } from '../utils';
import { createTsAliasDocumentLinksProviders, getEmbeddedInfo } from '../utils';

export function create(): LanguageServicePlugin {
const base = baseCreate({ scssDocumentSelector: ['scss', 'postcss'] });
export function create(
{ resolveModuleName }: import('@vue/typescript-plugin/lib/requests').Requests,
): LanguageServicePlugin {
const baseService = baseCreate({ scssDocumentSelector: ['scss', 'postcss'] });
return {
...base,
...baseService,
capabilities: {
...baseService.capabilities,
documentLinkProvider: {
resolveProvider: true,
},
},
create(context) {
const baseInstance = base.create(context);
const baseServiceInstance = baseService.create(context);
const {
'css/languageService': getCssLs,
'css/stylesheet': getStylesheet,
} = baseInstance.provide as Provide;
} = baseServiceInstance.provide as Provide;

return {
...baseInstance,
...baseServiceInstance,
async provideDiagnostics(document, token) {
let diagnostics = await baseInstance.provideDiagnostics?.(document, token) ?? [];
let diagnostics = await baseServiceInstance.provideDiagnostics?.(document, token) ?? [];
if (document.languageId === 'postcss') {
diagnostics = diagnostics.filter(diag =>
diag.code !== 'css-semicolonexpected'
Expand Down Expand Up @@ -48,6 +56,13 @@ export function create(): LanguageServicePlugin {
return cssLs.prepareRename(document, position, stylesheet);
});
},

...createTsAliasDocumentLinksProviders(
context,
baseServiceInstance,
id => id.startsWith('style_'),
resolveModuleName,
),
};

function isWithinNavigationVirtualCode(
Expand Down
15 changes: 13 additions & 2 deletions packages/language-service/lib/plugins/vue-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import * as html from 'vscode-html-languageservice';
import { URI, Utils } from 'vscode-uri';
import { loadModelModifiersData, loadTemplateData } from '../data';
import { AttrNameCasing, checkCasing, TagNameCasing } from '../nameCasing';
import { getEmbeddedInfo } from '../utils';
import { createTsAliasDocumentLinksProviders, getEmbeddedInfo } from '../utils';

const specialTags = new Set([
'slot',
Expand All @@ -39,11 +39,12 @@ export function create(
languageId: 'html' | 'jade',
{
getComponentNames,
getElementAttrs,
getComponentProps,
getComponentEvents,
getComponentDirectives,
getComponentSlots,
getElementAttrs,
resolveModuleName,
}: import('@vue/typescript-plugin/lib/requests').Requests,
): LanguageServicePlugin {
let customData: html.IHTMLDataProvider[] = [];
Expand Down Expand Up @@ -93,6 +94,9 @@ export function create(
],
},
hoverProvider: true,
documentLinkProvider: {
resolveProvider: true,
},
},
create(context) {
const baseServiceInstance = baseService.create(context);
Expand Down Expand Up @@ -323,6 +327,13 @@ export function create(

return baseServiceInstance.provideHover?.(document, position, token);
},

...createTsAliasDocumentLinksProviders(
context,
baseServiceInstance,
'template',
resolveModuleName,
),
};

async function runWithVueData<T>(sourceDocumentUri: URI, root: VueVirtualCode, fn: () => T) {
Expand Down
60 changes: 59 additions & 1 deletion packages/language-service/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { type LanguageServiceContext, type SourceScript, type TextDocument } from '@volar/language-service';
import {
type LanguageServiceContext,
type LanguageServicePluginInstance,
type SourceScript,
type TextDocument,
} from '@volar/language-service';
import { VueVirtualCode } from '@vue/language-core';
import { URI } from 'vscode-uri';

Expand Down Expand Up @@ -50,3 +55,56 @@ export function getEmbeddedInfo(
root,
};
}

export function createTsAliasDocumentLinksProviders(
context: LanguageServiceContext,
service: LanguageServicePluginInstance,
filter: string | ((id: string) => boolean),
resolveModuleName: import('@vue/typescript-plugin/lib/requests').Requests['resolveModuleName'],
): Pick<
LanguageServicePluginInstance,
'provideDocumentLinks' | 'resolveDocumentLink'
> {
return {
async provideDocumentLinks(document, token) {
const info = getEmbeddedInfo(context, document, filter);
if (!info) {
return;
}
const { root } = info;

const documentLinks = await service.provideDocumentLinks?.(document, token);

for (const link of documentLinks ?? []) {
if (!link.target) {
continue;
}
let text = document.getText(link.range);
if (text.startsWith('./') || text.startsWith('../')) {
continue;
}
if (text.startsWith(`'`) || text.startsWith(`"`)) {
text = text.slice(1, -1);
}
link.data = {
fileName: root.fileName,
text: text,
originalTarget: link.target,
};
delete link.target;
}

return documentLinks;
},

async resolveDocumentLink(link) {
const { fileName, text, originalTarget } = link.data;
const { name } = await resolveModuleName(fileName, text) ?? {};

return {
...link,
target: name ?? originalTarget,
};
},
};
}
6 changes: 6 additions & 0 deletions packages/typescript-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { getElementAttrs } from './lib/requests/getElementAttrs';
import { getElementNames } from './lib/requests/getElementNames';
import { getImportPathForFile } from './lib/requests/getImportPathForFile';
import { getPropertiesAtLocation } from './lib/requests/getPropertiesAtLocation';
import { resolveModuleName } from './lib/requests/resolveModuleName';
import type { RequestContext } from './lib/requests/types';

const windowsPathReg = /\\/g;
Expand Down Expand Up @@ -147,6 +148,11 @@ export = createLanguageServicePlugin(
response: getElementNames.apply(getRequestContext(args[0]), args),
};
});
session.addProtocolHandler('_vue:resolveModuleName', ({ arguments: args }) => {
return {
response: resolveModuleName.apply(getRequestContext(args[0]), args),
};
});

projectService.logger.info('Vue specific commands are successfully added.');
}
Expand Down
1 change: 1 addition & 0 deletions packages/typescript-plugin/lib/requests/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface Requests {
getComponentSlots: Request<typeof import('./getComponentSlots.js')['getComponentSlots']>;
getElementAttrs: Request<typeof import('./getElementAttrs.js')['getElementAttrs']>;
getElementNames: Request<typeof import('./getElementNames.js')['getElementNames']>;
resolveModuleName: Request<typeof import('./resolveModuleName.js')['resolveModuleName']>;
getDocumentHighlights: Request<(fileName: string, position: number) => ts.DocumentHighlights[]>;
getEncodedSemanticClassifications: Request<(fileName: string, span: ts.TextSpan) => ts.Classifications>;
getQuickInfoAtPosition: Request<(fileName: string, position: ts.LineAndCharacter) => string>;
Expand Down
39 changes: 39 additions & 0 deletions packages/typescript-plugin/lib/requests/resolveModuleName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type * as ts from 'typescript';
import type { RequestContext } from './types';

export function resolveModuleName(
this: RequestContext,
fileName: string,
moduleName: string,
): { name?: string } {
const { typescript: ts, languageServiceHost } = this;
const compilerOptions = languageServiceHost.getCompilationSettings();

const ext = moduleName.split('.').pop();
const result = ts.resolveModuleName(
moduleName,
fileName,
{
...compilerOptions,
allowArbitraryExtensions: true,
},
{
fileExists(fileName) {
fileName = transformFileName(fileName, ext);
return languageServiceHost.fileExists(fileName);
},
} as ts.ModuleResolutionHost,
);

const resolveFileName = result.resolvedModule?.resolvedFileName;
return {
name: resolveFileName ? transformFileName(resolveFileName, ext) : undefined,
};
}

function transformFileName(fileName: string, ext: string | undefined) {
if (ext && fileName.endsWith(`.d.${ext}.ts`)) {
return fileName.slice(0, -`.d.${ext}.ts`.length) + `.${ext}`;
}
return fileName;
}
Loading