@volar/language-service 1.6.8 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,12 @@
1
- import { LanguageServiceHost } from '@volar/language-core';
2
- import { Config, ServiceContext, ServiceEnvironment } from './types';
3
- import type * as ts from 'typescript/lib/tsserverlibrary';
1
+ import { TypeScriptLanguageHost } from '@volar/language-core';
2
+ import { Config, ServiceContext, ServiceEnvironment, SharedModules } from './types';
4
3
  import type * as vscode from 'vscode-languageserver-protocol';
5
4
  export type LanguageService = ReturnType<typeof createLanguageServiceBase>;
6
- export declare function createLanguageService(modules: {
7
- typescript?: typeof import('typescript/lib/tsserverlibrary');
8
- }, env: ServiceEnvironment, config: Config, host: LanguageServiceHost, documentRegistry?: ts.DocumentRegistry): {
9
- triggerCharacters: string[];
10
- autoFormatTriggerCharacters: string[];
11
- signatureHelpTriggerCharacters: string[];
12
- signatureHelpRetriggerCharacters: string[];
5
+ export declare function createLanguageService(modules: SharedModules, env: ServiceEnvironment, config: Config, languageHost: TypeScriptLanguageHost): {
6
+ getTriggerCharacters: () => string[];
7
+ getAutoFormatTriggerCharacters: () => string[];
8
+ getSignatureHelpTriggerCharacters: () => string[];
9
+ getSignatureHelpRetriggerCharacters: () => string[];
13
10
  format: (uri: string, options: vscode.FormattingOptions, range: vscode.Range | undefined, onTypeParams: {
14
11
  ch: string;
15
12
  position: vscode.Position;
@@ -55,14 +52,14 @@ export declare function createLanguageService(modules: {
55
52
  getIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyIncomingCall[]>;
56
53
  getOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyOutgoingCall[]>;
57
54
  };
58
- dispose: () => void | undefined;
59
- context: ServiceContext;
55
+ dispose: () => void;
56
+ context: ServiceContext<any>;
60
57
  };
61
58
  declare function createLanguageServiceBase(context: ServiceContext): {
62
- triggerCharacters: string[];
63
- autoFormatTriggerCharacters: string[];
64
- signatureHelpTriggerCharacters: string[];
65
- signatureHelpRetriggerCharacters: string[];
59
+ getTriggerCharacters: () => string[];
60
+ getAutoFormatTriggerCharacters: () => string[];
61
+ getSignatureHelpTriggerCharacters: () => string[];
62
+ getSignatureHelpRetriggerCharacters: () => string[];
66
63
  format: (uri: string, options: vscode.FormattingOptions, range: vscode.Range | undefined, onTypeParams: {
67
64
  ch: string;
68
65
  position: vscode.Position;
@@ -108,7 +105,7 @@ declare function createLanguageServiceBase(context: ServiceContext): {
108
105
  getIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyIncomingCall[]>;
109
106
  getOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyOutgoingCall[]>;
110
107
  };
111
- dispose: () => void | undefined;
112
- context: ServiceContext;
108
+ dispose: () => void;
109
+ context: ServiceContext<any>;
113
110
  };
114
111
  export {};
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createLanguageService = void 0;
4
4
  const language_core_1 = require("@volar/language-core");
5
- const tsFaster = require("typescript-auto-import-cache");
6
5
  const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
7
6
  const documents_1 = require("./documents");
8
7
  const autoInsert = require("./languageFeatures/autoInsert");
@@ -37,55 +36,30 @@ const format = require("./documentFeatures/format");
37
36
  const linkedEditingRanges = require("./documentFeatures/linkedEditingRanges");
38
37
  const selectionRanges = require("./documentFeatures/selectionRanges");
39
38
  const common_1 = require("./utils/common");
40
- function createLanguageService(modules, env, config, host, documentRegistry) {
41
- const languageContext = (0, language_core_1.createLanguageContext)(modules, host, Object.values(config.languages ?? {}).filter(common_1.notEmpty));
42
- const context = createLanguageServicePluginContext(modules, env, config, host, languageContext, documentRegistry);
39
+ function createLanguageService(modules, env, config, languageHost) {
40
+ const languageContext = (0, language_core_1.createLanguageContext)(languageHost, Object.values(config.languages ?? {}).filter(common_1.notEmpty));
41
+ const context = createLanguageServicePluginContext(modules, env, config, languageHost, languageContext);
43
42
  return createLanguageServiceBase(context);
44
43
  }
45
44
  exports.createLanguageService = createLanguageService;
46
- function createLanguageServicePluginContext(modules, env, config, host, languageContext, documentRegistry) {
47
- const ts = modules.typescript;
48
- let tsLs;
49
- if (ts) {
50
- const created = tsFaster.createLanguageService(ts, languageContext.typescript.languageServiceHost, proxiedHost => ts.createLanguageService(proxiedHost, documentRegistry), languageContext.typescript.languageServiceHost.getCurrentDirectory());
51
- tsLs = created.languageService;
52
- if (created.setPreferences && env.getConfiguration) {
53
- updatePreferences();
54
- env.onDidChangeConfiguration?.(updatePreferences);
55
- async function updatePreferences() {
56
- const preferences = await env.getConfiguration?.('typescript.preferences');
57
- if (preferences) {
58
- created.setPreferences?.(preferences);
59
- }
60
- }
61
- }
62
- if (created.projectUpdated) {
63
- let scriptFileNames = new Set(host.getScriptFileNames());
64
- env.onDidChangeWatchedFiles?.((params) => {
65
- if (params.changes.some(change => change.type !== 2)) {
66
- scriptFileNames = new Set(host.getScriptFileNames());
67
- }
68
- for (const change of params.changes) {
69
- if (scriptFileNames.has(env.uriToFileName(change.uri))) {
70
- created.projectUpdated?.(env.uriToFileName(env.rootUri.fsPath));
71
- }
72
- }
73
- });
74
- }
75
- }
45
+ function createLanguageServicePluginContext(modules, env, config, host, languageContext) {
76
46
  const textDocumentMapper = (0, documents_1.createDocumentsAndSourceMaps)(env, host, languageContext.virtualFiles);
77
47
  const documents = new WeakMap();
78
48
  const documentVersions = new Map();
79
49
  const context = {
50
+ ...languageContext,
80
51
  env,
81
- config,
82
- host,
83
- core: languageContext,
52
+ inject: (key, ...args) => {
53
+ for (const service of Object.values(context.services)) {
54
+ const provide = service.provide?.[key];
55
+ if (provide) {
56
+ return provide(...args);
57
+ }
58
+ }
59
+ throw `No service provide ${key}`;
60
+ },
61
+ rules: config.rules ?? {},
84
62
  services: {},
85
- typescript: tsLs ? {
86
- languageServiceHost: languageContext.typescript.languageServiceHost,
87
- languageService: tsLs,
88
- } : undefined,
89
63
  documents: textDocumentMapper,
90
64
  commands: {
91
65
  rename: {
@@ -188,6 +162,9 @@ function createLanguageServicePluginContext(modules, env, config, host, language
188
162
  }
189
163
  }
190
164
  function getTextDocument(uri) {
165
+ for (const [_, map] of context.documents.getMapsByVirtualFileUri(uri)) {
166
+ return map.virtualFileDocument;
167
+ }
191
168
  const fileName = env.uriToFileName(uri);
192
169
  const scriptSnapshot = host.getScriptSnapshot(fileName);
193
170
  if (scriptSnapshot) {
@@ -195,7 +172,7 @@ function createLanguageServicePluginContext(modules, env, config, host, language
195
172
  if (!document) {
196
173
  const newVersion = (documentVersions.get(uri.toLowerCase()) ?? 0) + 1;
197
174
  documentVersions.set(uri.toLowerCase(), newVersion);
198
- document = vscode_languageserver_textdocument_1.TextDocument.create(uri, host.getScriptLanguageId?.(fileName) ?? (0, common_1.resolveCommonLanguageId)(uri), newVersion, scriptSnapshot.getText(0, scriptSnapshot.getLength()));
175
+ document = vscode_languageserver_textdocument_1.TextDocument.create(uri, host.getLanguageId?.(fileName) ?? (0, common_1.resolveCommonLanguageId)(uri), newVersion, scriptSnapshot.getText(0, scriptSnapshot.getLength()));
199
176
  documents.set(scriptSnapshot, document);
200
177
  }
201
178
  return document;
@@ -204,10 +181,10 @@ function createLanguageServicePluginContext(modules, env, config, host, language
204
181
  }
205
182
  function createLanguageServiceBase(context) {
206
183
  return {
207
- triggerCharacters: Object.values(context.services).map(service => service?.triggerCharacters ?? []).flat(),
208
- autoFormatTriggerCharacters: Object.values(context.services).map(service => service?.autoFormatTriggerCharacters ?? []).flat(),
209
- signatureHelpTriggerCharacters: Object.values(context.services).map(service => service?.signatureHelpTriggerCharacters ?? []).flat(),
210
- signatureHelpRetriggerCharacters: Object.values(context.services).map(service => service?.signatureHelpRetriggerCharacters ?? []).flat(),
184
+ getTriggerCharacters: () => Object.values(context.services).map(service => service?.triggerCharacters ?? []).flat(),
185
+ getAutoFormatTriggerCharacters: () => Object.values(context.services).map(service => service?.autoFormatTriggerCharacters ?? []).flat(),
186
+ getSignatureHelpTriggerCharacters: () => Object.values(context.services).map(service => service?.signatureHelpTriggerCharacters ?? []).flat(),
187
+ getSignatureHelpRetriggerCharacters: () => Object.values(context.services).map(service => service?.signatureHelpRetriggerCharacters ?? []).flat(),
211
188
  format: format.register(context),
212
189
  getFoldingRanges: foldingRanges.register(context),
213
190
  getSelectionRanges: selectionRanges.register(context),
@@ -241,7 +218,7 @@ function createLanguageServiceBase(context) {
241
218
  getInlayHints: inlayHints.register(context),
242
219
  doInlayHintResolve: inlayHintResolve.register(context),
243
220
  callHierarchy: callHierarchy.register(context),
244
- dispose: () => context.typescript?.languageService.dispose(),
221
+ dispose: () => Object.values(context.services).forEach(service => service.dispose?.()),
245
222
  context,
246
223
  };
247
224
  }
@@ -1,10 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.register = void 0;
4
+ const language_core_1 = require("@volar/language-core");
4
5
  const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
5
6
  const common_1 = require("../utils/common");
6
7
  const cancellation_1 = require("../utils/cancellation");
8
+ const documents_1 = require("../documents");
7
9
  function register(context) {
10
+ let fakeVersion = 0;
8
11
  return async (uri, options, range, onTypeParams, token = cancellation_1.NoneCancellationToken) => {
9
12
  let document = context.getTextDocument(uri);
10
13
  if (!document)
@@ -20,49 +23,48 @@ function register(context) {
20
23
  : (await tryFormat(document, range, undefined))?.edits;
21
24
  }
22
25
  const initialIndentLanguageId = await context.env.getConfiguration?.('volar.format.initialIndent') ?? { html: true };
23
- const originalSnapshot = source.snapshot;
24
- const rootVirtualFile = source.root;
26
+ let tempSourceSnapshot = source.snapshot;
27
+ const tempVirtualFile = source.language.createVirtualFile(source.fileName, source.snapshot, source.languageId);
25
28
  const originalDocument = document;
26
29
  let level = 0;
27
- let edited = false;
28
30
  while (true) {
29
- const embeddedFiles = getEmbeddedFilesByLevel(rootVirtualFile, level++);
31
+ const embeddedFiles = getEmbeddedFilesByLevel(tempVirtualFile, level++);
30
32
  if (embeddedFiles.length === 0)
31
33
  break;
34
+ // if (level===2) continue;
32
35
  let edits = [];
33
- const toPatchIndentUris = [];
34
- for (const embedded of embeddedFiles) {
35
- if (!embedded.capabilities.documentFormatting)
36
+ const toPatchIndent = [];
37
+ for (const file of embeddedFiles) {
38
+ if (!file.capabilities.documentFormatting)
36
39
  continue;
37
- const isCodeBlock = embedded.mappings.length === 1 && embedded.mappings[0].generatedRange[0] === 0 && embedded.mappings[0].generatedRange[1] === embedded.snapshot.getLength();
40
+ const isCodeBlock = file.mappings.length === 1 && file.mappings[0].generatedRange[0] === 0 && file.mappings[0].generatedRange[1] === file.snapshot.getLength();
38
41
  if (onTypeParams && !isCodeBlock)
39
42
  continue;
40
- const maps = [...context.documents.getMapsByVirtualFileName(embedded.fileName)];
41
- const map = maps.find(map => map[1].sourceFileDocument.uri === document.uri)?.[1];
42
- if (!map)
43
+ const docMap = createDocMap(file, source.fileName, tempSourceSnapshot);
44
+ if (!docMap)
43
45
  continue;
44
46
  let embeddedCodeResult;
45
47
  if (onTypeParams) {
46
- const embeddedPosition = map.toGeneratedPosition(onTypeParams.position);
48
+ const embeddedPosition = docMap.toGeneratedPosition(onTypeParams.position);
47
49
  if (embeddedPosition) {
48
- embeddedCodeResult = await tryFormat(map.virtualFileDocument, embeddedPosition, onTypeParams.ch);
50
+ embeddedCodeResult = await tryFormat(docMap.virtualFileDocument, embeddedPosition, onTypeParams.ch);
49
51
  }
50
52
  }
51
53
  else {
52
- embeddedCodeResult = await tryFormat(map.virtualFileDocument, {
53
- start: map.virtualFileDocument.positionAt(0),
54
- end: map.virtualFileDocument.positionAt(map.virtualFileDocument.getText().length),
54
+ embeddedCodeResult = await tryFormat(docMap.virtualFileDocument, {
55
+ start: docMap.virtualFileDocument.positionAt(0),
56
+ end: docMap.virtualFileDocument.positionAt(docMap.virtualFileDocument.getText().length),
55
57
  });
56
58
  }
57
59
  if (!embeddedCodeResult)
58
60
  continue;
59
- toPatchIndentUris.push({
60
- uri: map.virtualFileDocument.uri,
61
+ toPatchIndent.push({
62
+ virtualFileName: file.fileName,
61
63
  isCodeBlock,
62
64
  service: embeddedCodeResult.service,
63
65
  });
64
66
  for (const textEdit of embeddedCodeResult.edits) {
65
- const range = map.toSourceRange(textEdit.range);
67
+ const range = docMap.toSourceRange(textEdit.range);
66
68
  if (range) {
67
69
  edits.push({
68
70
  newText: textEdit.newText,
@@ -75,8 +77,8 @@ function register(context) {
75
77
  if (edits.length > 0) {
76
78
  const newText = vscode_languageserver_textdocument_1.TextDocument.applyEdits(document, edits);
77
79
  document = vscode_languageserver_textdocument_1.TextDocument.create(document.uri, document.languageId, document.version + 1, newText);
78
- context.core.virtualFiles.updateSource(context.env.uriToFileName(document.uri), (0, common_1.stringToSnapshot)(document.getText()), document.languageId);
79
- edited = true;
80
+ tempSourceSnapshot = (0, common_1.stringToSnapshot)(newText);
81
+ source.language.updateVirtualFile(tempVirtualFile, tempSourceSnapshot);
80
82
  }
81
83
  if (level > 1) {
82
84
  const baseIndent = options.insertSpaces ? ' '.repeat(options.tabSize) : '\t';
@@ -88,53 +90,56 @@ function register(context) {
88
90
  }
89
91
  }
90
92
  }
91
- for (const toPatchIndentUri of toPatchIndentUris) {
92
- for (const [_, map] of context.documents.getMapsByVirtualFileUri(toPatchIndentUri.uri)) {
93
- const indentSensitiveLines = new Set();
94
- for (const service of toPatchIndentUri.service.provideFormattingIndentSensitiveLines ? [toPatchIndentUri.service] : Object.values(context.services)) {
95
- if (token.isCancellationRequested)
96
- break;
97
- if (service.provideFormattingIndentSensitiveLines) {
98
- const lines = await service.provideFormattingIndentSensitiveLines(map.virtualFileDocument, token);
99
- if (lines) {
100
- for (const line of lines) {
101
- const sourceLine = map.toSourcePosition({ line: line, character: 0 })?.line;
102
- if (sourceLine !== undefined) {
103
- indentSensitiveLines.add(sourceLine);
104
- }
93
+ for (const item of toPatchIndent) {
94
+ let virtualFile;
95
+ (0, language_core_1.forEachEmbeddedFile)(tempVirtualFile, file => {
96
+ if (file.fileName === item.virtualFileName) {
97
+ virtualFile = file;
98
+ }
99
+ });
100
+ const docMap = createDocMap(virtualFile, source.fileName, tempSourceSnapshot);
101
+ if (!docMap)
102
+ continue;
103
+ const indentSensitiveLines = new Set();
104
+ for (const service of item.service.provideFormattingIndentSensitiveLines ? [item.service] : Object.values(context.services)) {
105
+ if (token.isCancellationRequested)
106
+ break;
107
+ if (service.provideFormattingIndentSensitiveLines) {
108
+ const lines = await service.provideFormattingIndentSensitiveLines(docMap.virtualFileDocument, token);
109
+ if (lines) {
110
+ for (const line of lines) {
111
+ const sourceLine = docMap.toSourcePosition({ line: line, character: 0 })?.line;
112
+ if (sourceLine !== undefined) {
113
+ indentSensitiveLines.add(sourceLine);
105
114
  }
106
115
  }
107
116
  }
108
117
  }
109
- let indentEdits = patchIndents(document, toPatchIndentUri.isCodeBlock, map.map, initialIndentLanguageId[map.virtualFileDocument.languageId] ? baseIndent : '');
110
- indentEdits = indentEdits.filter(edit => {
111
- for (let line = edit.range.start.line; line <= edit.range.end.line; line++) {
112
- if (indentSensitiveLines.has(line) && !edit.newText.includes('\n')) {
113
- return false;
114
- }
115
- if (onTypeParams && !editLines.has(line)) {
116
- return false;
117
- }
118
- if (!(0, common_1.isInsideRange)(range, edit.range)) {
119
- return false;
120
- }
118
+ }
119
+ let indentEdits = patchIndents(document, item.isCodeBlock, docMap.map, initialIndentLanguageId[docMap.virtualFileDocument.languageId] ? baseIndent : '');
120
+ indentEdits = indentEdits.filter(edit => {
121
+ for (let line = edit.range.start.line; line <= edit.range.end.line; line++) {
122
+ if (indentSensitiveLines.has(line) && !edit.newText.includes('\n')) {
123
+ return false;
124
+ }
125
+ if (onTypeParams && !editLines.has(line)) {
126
+ return false;
127
+ }
128
+ if (!(0, common_1.isInsideRange)(range, edit.range)) {
129
+ return false;
121
130
  }
122
- return true;
123
- });
124
- if (indentEdits.length > 0) {
125
- const newText = vscode_languageserver_textdocument_1.TextDocument.applyEdits(document, indentEdits);
126
- document = vscode_languageserver_textdocument_1.TextDocument.create(document.uri, document.languageId, document.version + 1, newText);
127
- context.core.virtualFiles.updateSource(context.env.uriToFileName(document.uri), (0, common_1.stringToSnapshot)(document.getText()), document.languageId);
128
- edited = true;
129
131
  }
132
+ return true;
133
+ });
134
+ if (indentEdits.length > 0) {
135
+ const newText = vscode_languageserver_textdocument_1.TextDocument.applyEdits(document, indentEdits);
136
+ document = vscode_languageserver_textdocument_1.TextDocument.create(document.uri, document.languageId, document.version + 1, newText);
137
+ tempSourceSnapshot = (0, common_1.stringToSnapshot)(newText);
138
+ source.language.updateVirtualFile(tempVirtualFile, tempSourceSnapshot);
130
139
  }
131
140
  }
132
141
  }
133
142
  }
134
- if (edited) {
135
- // recover
136
- context.core.virtualFiles.updateSource(context.env.uriToFileName(document.uri), originalSnapshot, document.languageId);
137
- }
138
143
  if (document.getText() === originalDocument.getText())
139
144
  return;
140
145
  const editRange = {
@@ -186,6 +191,18 @@ function register(context) {
186
191
  }
187
192
  }
188
193
  };
194
+ function createDocMap(file, _sourceFileName, _sourceSnapshot) {
195
+ const maps = (0, language_core_1.updateVirtualFileMaps)(file, (sourceFileName) => {
196
+ if (!sourceFileName) {
197
+ return [_sourceFileName, _sourceSnapshot];
198
+ }
199
+ });
200
+ if (maps.has(_sourceFileName) && maps.get(_sourceFileName)[0] === _sourceSnapshot) {
201
+ const [_, map] = maps.get(_sourceFileName);
202
+ const version = fakeVersion++;
203
+ return new documents_1.SourceMapWithDocuments(vscode_languageserver_textdocument_1.TextDocument.create(context.env.fileNameToUri(_sourceFileName), context.host.getLanguageId?.(_sourceFileName) ?? (0, common_1.resolveCommonLanguageId)(context.env.fileNameToUri(_sourceFileName)), version, _sourceSnapshot.getText(0, _sourceSnapshot.getLength())), vscode_languageserver_textdocument_1.TextDocument.create(context.env.fileNameToUri(file.fileName), context.host.getLanguageId?.(file.fileName) ?? (0, common_1.resolveCommonLanguageId)(context.env.fileNameToUri(file.fileName)), version, file.snapshot.getText(0, file.snapshot.getLength())), map);
204
+ }
205
+ }
189
206
  }
190
207
  exports.register = register;
191
208
  function patchIndents(document, isCodeBlock, map, initialIndent) {
@@ -1,4 +1,4 @@
1
- import { VirtualFiles, VirtualFile, FileRangeCapabilities, MirrorBehaviorCapabilities, MirrorMap, LanguageServiceHost } from '@volar/language-core';
1
+ import { VirtualFiles, VirtualFile, FileRangeCapabilities, MirrorBehaviorCapabilities, MirrorMap, TypeScriptLanguageHost } from '@volar/language-core';
2
2
  import { Mapping, SourceMap } from '@volar/source-map';
3
3
  import type * as vscode from 'vscode-languageserver-protocol';
4
4
  import { TextDocument } from 'vscode-languageserver-textdocument';
@@ -30,7 +30,7 @@ export declare class MirrorMapWithDocument extends SourceMapWithDocuments<[Mirro
30
30
  constructor(document: TextDocument, map: MirrorMap);
31
31
  findMirrorPositions(start: vscode.Position): Generator<readonly [import("vscode-languageserver-textdocument").Position, MirrorBehaviorCapabilities], void, unknown>;
32
32
  }
33
- export declare function createDocumentsAndSourceMaps(env: ServiceEnvironment, host: LanguageServiceHost, mapper: VirtualFiles): {
33
+ export declare function createDocumentsAndSourceMaps(env: ServiceEnvironment, host: TypeScriptLanguageHost, mapper: VirtualFiles): {
34
34
  getSourceByUri(sourceFileUri: string): import("@volar/language-core").Source | undefined;
35
35
  isVirtualFileUri(virtualFileUri: string): boolean;
36
36
  getVirtualFileByUri(virtualFileUri: string): readonly [VirtualFile, import("@volar/language-core").Source] | readonly [undefined, undefined];
package/out/documents.js CHANGED
@@ -132,9 +132,9 @@ class MirrorMapWithDocument extends SourceMapWithDocuments {
132
132
  exports.MirrorMapWithDocument = MirrorMapWithDocument;
133
133
  function createDocumentsAndSourceMaps(env, host, mapper) {
134
134
  let version = 0;
135
- const _maps = new WeakMap();
136
- const _mirrorMaps = new WeakMap();
137
- const _documents = new WeakMap();
135
+ const map2DocMap = new WeakMap();
136
+ const mirrorMap2DocMirrorMap = new WeakMap();
137
+ const snapshot2Doc = new WeakMap();
138
138
  return {
139
139
  getSourceByUri(sourceFileUri) {
140
140
  return mapper.getSource(env.uriToFileName(sourceFileUri));
@@ -151,10 +151,10 @@ function createDocumentsAndSourceMaps(env, host, mapper) {
151
151
  if (virtualFile) {
152
152
  const map = mapper.getMirrorMap(virtualFile);
153
153
  if (map) {
154
- if (!_mirrorMaps.has(map)) {
155
- _mirrorMaps.set(map, [virtualFile, new MirrorMapWithDocument(getDocumentByFileName(virtualFile.snapshot, fileName), map)]);
154
+ if (!mirrorMap2DocMirrorMap.has(map)) {
155
+ mirrorMap2DocMirrorMap.set(map, [virtualFile, new MirrorMapWithDocument(getDocumentByFileName(virtualFile.snapshot, fileName), map)]);
156
156
  }
157
- return _mirrorMaps.get(map);
157
+ return mirrorMap2DocMirrorMap.get(map);
158
158
  }
159
159
  }
160
160
  },
@@ -166,16 +166,16 @@ function createDocumentsAndSourceMaps(env, host, mapper) {
166
166
  if (source) {
167
167
  const result = [];
168
168
  (0, language_core_1.forEachEmbeddedFile)(source.root, (embedded) => {
169
- for (const [sourceFileName, map] of mapper.getMaps(embedded)) {
170
- if (sourceFileName === fileName) {
171
- if (!_maps.has(map)) {
172
- _maps.set(map, [
169
+ for (const [sourceFileName, [sourceSnapshot, map]] of mapper.getMaps(embedded)) {
170
+ if (sourceSnapshot === source.snapshot) {
171
+ if (!map2DocMap.has(map)) {
172
+ map2DocMap.set(map, [
173
173
  embedded,
174
- new SourceMapWithDocuments(getDocumentByFileName(source.snapshot, sourceFileName), getDocumentByFileName(embedded.snapshot, fileName), map)
174
+ new SourceMapWithDocuments(getDocumentByFileName(sourceSnapshot, sourceFileName), getDocumentByFileName(embedded.snapshot, fileName), map)
175
175
  ]);
176
176
  }
177
- if (_maps.has(map)) {
178
- result.push(_maps.get(map));
177
+ if (map2DocMap.has(map)) {
178
+ result.push(map2DocMap.get(map));
179
179
  }
180
180
  }
181
181
  }
@@ -192,15 +192,12 @@ function createDocumentsAndSourceMaps(env, host, mapper) {
192
192
  *getMapsByVirtualFileName(virtualFileName) {
193
193
  const [virtualFile] = mapper.getVirtualFile(virtualFileName);
194
194
  if (virtualFile) {
195
- for (const [sourceFileName, map] of mapper.getMaps(virtualFile)) {
196
- if (!_maps.has(map)) {
197
- const sourceSnapshot = mapper.getSource(sourceFileName)?.snapshot;
198
- if (sourceSnapshot) {
199
- _maps.set(map, [virtualFile, new SourceMapWithDocuments(getDocumentByFileName(sourceSnapshot, sourceFileName), getDocumentByFileName(virtualFile.snapshot, virtualFileName), map)]);
200
- }
195
+ for (const [sourceFileName, [sourceSnapshot, map]] of mapper.getMaps(virtualFile)) {
196
+ if (!map2DocMap.has(map)) {
197
+ map2DocMap.set(map, [virtualFile, new SourceMapWithDocuments(getDocumentByFileName(sourceSnapshot, sourceFileName), getDocumentByFileName(virtualFile.snapshot, virtualFileName), map)]);
201
198
  }
202
- if (_maps.has(map)) {
203
- yield _maps.get(map);
199
+ if (map2DocMap.has(map)) {
200
+ yield map2DocMap.get(map);
204
201
  }
205
202
  }
206
203
  }
@@ -211,13 +208,13 @@ function createDocumentsAndSourceMaps(env, host, mapper) {
211
208
  getDocumentByFileName,
212
209
  };
213
210
  function getDocumentByFileName(snapshot, fileName) {
214
- if (!_documents.has(snapshot)) {
215
- _documents.set(snapshot, new Map());
211
+ if (!snapshot2Doc.has(snapshot)) {
212
+ snapshot2Doc.set(snapshot, new Map());
216
213
  }
217
- const map = _documents.get(snapshot);
214
+ const map = snapshot2Doc.get(snapshot);
218
215
  if (!map.has(fileName)) {
219
216
  const uri = env.fileNameToUri(fileName);
220
- map.set(fileName, vscode_languageserver_textdocument_1.TextDocument.create(uri, host.getScriptLanguageId?.(fileName) ?? (0, common_1.resolveCommonLanguageId)(uri), version++, snapshot.getText(0, snapshot.getLength())));
217
+ map.set(fileName, vscode_languageserver_textdocument_1.TextDocument.create(uri, host.getLanguageId?.(fileName) ?? (0, common_1.resolveCommonLanguageId)(uri), version++, snapshot.getText(0, snapshot.getLength())));
221
218
  }
222
219
  return map.get(fileName);
223
220
  }
@@ -172,9 +172,9 @@ function register(context) {
172
172
  }
173
173
  const pluginCache = cacheMap.get(ruleId) ?? cacheMap.set(ruleId, new Map()).get(ruleId);
174
174
  const cache = pluginCache.get(lintDocument.uri);
175
- const tsProjectVersion = (ruleType === types_1.RuleType.Semantic) ? context.core.typescript.languageServiceHost.getProjectVersion?.() : undefined;
175
+ const projectVersion = (ruleType === types_1.RuleType.Semantic) ? context.host.getProjectVersion?.() : undefined;
176
176
  if (ruleType === types_1.RuleType.Semantic) {
177
- if (cache && cache.documentVersion === lintDocument.version && cache.tsProjectVersion === tsProjectVersion) {
177
+ if (cache && cache.documentVersion === lintDocument.version && cache.projectVersion === projectVersion) {
178
178
  return cache.errors;
179
179
  }
180
180
  }
@@ -220,7 +220,7 @@ function register(context) {
220
220
  pluginCache.set(lintDocument.uri, {
221
221
  documentVersion: lintDocument.version,
222
222
  errors,
223
- tsProjectVersion,
223
+ projectVersion,
224
224
  });
225
225
  return errors;
226
226
  }, ruleType === types_1.RuleType.Format ? transformFormatErrorRange : transformErrorRange, arr => arr.flat());
@@ -247,9 +247,9 @@ function register(context) {
247
247
  const serviceId = Object.keys(context.services).find(key => context.services[key] === service);
248
248
  const serviceCache = cacheMap.get(serviceId) ?? cacheMap.set(serviceId, new Map()).get(serviceId);
249
249
  const cache = serviceCache.get(document.uri);
250
- const tsProjectVersion = api === 'provideSemanticDiagnostics' ? context.core.typescript.languageServiceHost.getProjectVersion?.() : undefined;
250
+ const projectVersion = api === 'provideSemanticDiagnostics' ? context.host.getProjectVersion?.() : undefined;
251
251
  if (api === 'provideSemanticDiagnostics') {
252
- if (cache && cache.documentVersion === document.version && cache.tsProjectVersion === tsProjectVersion) {
252
+ if (cache && cache.documentVersion === document.version && cache.projectVersion === projectVersion) {
253
253
  return cache.errors;
254
254
  }
255
255
  }
@@ -277,7 +277,7 @@ function register(context) {
277
277
  serviceCache.set(document.uri, {
278
278
  documentVersion: document.version,
279
279
  errors,
280
- tsProjectVersion,
280
+ projectVersion,
281
281
  });
282
282
  return errors;
283
283
  }, transformErrorRange, arr => dedupe.withDiagnostics(arr.flat()));
@@ -291,7 +291,7 @@ function register(context) {
291
291
  return transformErrorRangeBase(errors, map, () => true);
292
292
  }
293
293
  function transformErrorRange(errors, map) {
294
- return transformErrorRangeBase(errors, map, data => !!data.diagnostic);
294
+ return transformErrorRangeBase(errors, map, data => typeof data.diagnostic === 'object' ? data.diagnostic.shouldReport() : !!data.diagnostic);
295
295
  }
296
296
  function transformErrorRangeBase(errors, map, filter) {
297
297
  const result = [];
package/out/types.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- import { LanguageContext, Language, LanguageServiceHost } from '@volar/language-core';
2
- import type * as ts from 'typescript/lib/tsserverlibrary';
3
- import type { DocumentContext, FileSystemProvider } from 'vscode-html-languageservice';
4
- import type { SchemaRequestService } from 'vscode-json-languageservice';
1
+ import { Language, LanguageContext } from '@volar/language-core';
5
2
  import type * as vscode from 'vscode-languageserver-protocol';
6
3
  import type { TextDocument } from 'vscode-languageserver-textdocument';
7
4
  import { URI } from 'vscode-uri';
@@ -14,43 +11,50 @@ export interface ServiceEnvironment {
14
11
  locale?: string;
15
12
  rootUri: URI;
16
13
  clientCapabilities?: vscode.ClientCapabilities;
14
+ getConfiguration?<T>(section: string, scopeUri?: string): Promise<T | undefined>;
15
+ onDidChangeConfiguration?(cb: () => void): vscode.Disposable;
16
+ onDidChangeWatchedFiles?(cb: (params: vscode.DidChangeWatchedFilesParams) => void): vscode.Disposable;
17
17
  uriToFileName(uri: string): string;
18
18
  fileNameToUri(fileName: string): string;
19
- getConfiguration?<T>(section: string, scopeUri?: string): Promise<T | undefined>;
20
- onDidChangeConfiguration?(cb: () => void): void;
21
- onDidChangeWatchedFiles?(cb: (params: vscode.DidChangeWatchedFilesParams) => void): () => void;
22
- documentContext?: DocumentContext;
23
- fileSystemProvider?: FileSystemProvider;
24
- schemaRequestService?: SchemaRequestService;
19
+ fs?: FileSystem;
20
+ }
21
+ export interface FileSystem {
22
+ stat(uri: string): Result<FileStat | undefined>;
23
+ readDirectory(uri: string): Result<[string, FileType][]>;
24
+ readFile(uri: string, encoding?: string): Result<string | undefined>;
25
+ }
26
+ export interface FileStat {
27
+ type: FileType;
28
+ ctime: number;
29
+ mtime: number;
30
+ size: number;
31
+ }
32
+ export declare enum FileType {
33
+ Unknown = 0,
34
+ File = 1,
35
+ Directory = 2,
36
+ SymbolicLink = 64
25
37
  }
26
38
  interface Command<T> {
27
39
  create: T;
28
40
  is(value: vscode.Command): boolean;
29
41
  }
30
- export interface ServiceContext {
42
+ export interface ServiceContext<Provide = any> extends LanguageContext {
31
43
  env: ServiceEnvironment;
32
- config: Config;
33
- host: LanguageServiceHost;
34
- typescript: {
35
- languageServiceHost: ts.LanguageServiceHost;
36
- languageService: ts.LanguageService;
37
- } | undefined;
44
+ inject<K extends keyof Provide>(key: K, ...args: Provide[K] extends (...args: any) => any ? Parameters<Provide[K]> : never): ReturnType<Provide[K] extends (...args: any) => any ? Provide[K] : never>;
45
+ getTextDocument(uri: string): TextDocument | undefined;
38
46
  commands: {
39
47
  showReferences: Command<(uri: string, position: vscode.Position, locations: vscode.Location[]) => vscode.Command | undefined>;
40
48
  rename: Command<(uri: string, position: vscode.Position) => vscode.Command | undefined>;
41
49
  setSelection: Command<(position: vscode.Position) => vscode.Command | undefined>;
42
50
  };
43
- /** @private */
44
- core: LanguageContext;
45
- /** @private */
46
51
  documents: DocumentsAndSourceMaps;
47
- /** @private */
52
+ rules: {
53
+ [id: string]: Rule;
54
+ };
48
55
  services: {
49
56
  [id: string]: ReturnType<Service>;
50
57
  };
51
- /** @private */
52
- getTextDocument(uri: string): TextDocument | undefined;
53
- /** @private */
54
58
  ruleFixes?: {
55
59
  [uri: string]: {
56
60
  [ruleId: string]: {
@@ -67,7 +71,7 @@ type ServiceProvide<P> = P extends undefined ? {
67
71
  } : {
68
72
  provide: P;
69
73
  };
70
- export type Service<P extends any = any> = {
74
+ export type Service<P = any> = {
71
75
  (context: ServiceContext | undefined, modules: SharedModules | undefined): {
72
76
  isAdditionalCompletion?: boolean;
73
77
  triggerCharacters?: string[];
@@ -121,6 +125,7 @@ export type Service<P extends any = any> = {
121
125
  resolveInlayHint?(inlayHint: vscode.InlayHint, token: vscode.CancellationToken): Result<vscode.InlayHint>;
122
126
  resolveReferencesCodeLensLocations?(document: TextDocument, range: vscode.Range, references: vscode.Location[], token: vscode.CancellationToken): Result<vscode.Location[]>;
123
127
  resolveEmbeddedRange?(range: vscode.Range): vscode.Range | undefined;
128
+ dispose?(): void;
124
129
  } & ServiceProvide<P>;
125
130
  };
126
131
  export interface AutoInsertionContext {
@@ -142,8 +147,8 @@ export interface Rule<Provide = any> {
142
147
  }
143
148
  export interface RuleContext<Provide = any> {
144
149
  env: ServiceEnvironment;
145
- report(error: vscode.Diagnostic, ...fixes: RuleFix[]): void;
146
150
  inject<K extends keyof Provide>(key: K, ...args: Provide[K] extends (...args: any) => any ? Parameters<Provide[K]> : never): ReturnType<Provide[K] extends (...args: any) => any ? Provide[K] : never>;
151
+ report(error: vscode.Diagnostic, ...fixes: RuleFix[]): void;
147
152
  }
148
153
  export interface RuleFix {
149
154
  /**
package/out/types.js CHANGED
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RuleType = void 0;
3
+ exports.RuleType = exports.FileType = void 0;
4
+ var FileType;
5
+ (function (FileType) {
6
+ FileType[FileType["Unknown"] = 0] = "Unknown";
7
+ FileType[FileType["File"] = 1] = "File";
8
+ FileType[FileType["Directory"] = 2] = "Directory";
9
+ FileType[FileType["SymbolicLink"] = 64] = "SymbolicLink";
10
+ })(FileType || (exports.FileType = FileType = {}));
4
11
  var RuleType;
5
12
  (function (RuleType) {
6
13
  RuleType[RuleType["Format"] = 0] = "Format";
7
14
  RuleType[RuleType["Syntax"] = 1] = "Syntax";
8
15
  RuleType[RuleType["Semantic"] = 2] = "Semantic";
9
- })(RuleType = exports.RuleType || (exports.RuleType = {}));
16
+ })(RuleType || (exports.RuleType = RuleType = {}));
10
17
  ;
11
18
  //# sourceMappingURL=types.js.map
@@ -68,15 +68,7 @@ async function ruleWorker(context, ruleType, uri, isValidSourceMap, worker, tran
68
68
  const virtualFile = context.documents.getSourceByUri(uri)?.root;
69
69
  const ruleCtx = {
70
70
  env: context.env,
71
- inject: (key, ...args) => {
72
- for (const service of Object.values(context.services)) {
73
- const provide = service.provide?.[key];
74
- if (provide) {
75
- return provide(...args);
76
- }
77
- }
78
- throw `No service provide ${key}`;
79
- },
71
+ inject: context.inject,
80
72
  report: () => { },
81
73
  };
82
74
  let results = [];
@@ -85,8 +77,8 @@ async function ruleWorker(context, ruleType, uri, isValidSourceMap, worker, tran
85
77
  if (!isValidSourceMap(file)) {
86
78
  return true;
87
79
  }
88
- for (const ruleId in context.config.rules) {
89
- const rule = context.config.rules[ruleId];
80
+ for (const ruleId in context.rules) {
81
+ const rule = context.rules[ruleId];
90
82
  if ((rule.type ?? types_1.RuleType.Syntax) !== ruleType) {
91
83
  continue;
92
84
  }
@@ -108,8 +100,8 @@ async function ruleWorker(context, ruleType, uri, isValidSourceMap, worker, tran
108
100
  });
109
101
  }
110
102
  else if (document) {
111
- for (const ruleId in context.config.rules) {
112
- const rule = context.config.rules[ruleId];
103
+ for (const ruleId in context.rules) {
104
+ const rule = context.rules[ruleId];
113
105
  if ((rule.type ?? types_1.RuleType.Syntax) !== ruleType) {
114
106
  continue;
115
107
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volar/language-service",
3
- "version": "1.6.8",
3
+ "version": "1.7.0",
4
4
  "main": "out/index.js",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -13,16 +13,13 @@
13
13
  "directory": "packages/language-service"
14
14
  },
15
15
  "dependencies": {
16
- "@volar/language-core": "1.6.8",
17
- "@volar/source-map": "1.6.8",
18
- "typescript-auto-import-cache": "^0.2.1",
16
+ "@volar/language-core": "1.7.0",
17
+ "@volar/source-map": "1.7.0",
19
18
  "vscode-languageserver-textdocument": "^1.0.8",
20
19
  "vscode-uri": "^3.0.7"
21
20
  },
22
21
  "devDependencies": {
23
- "vscode-html-languageservice": "^5.0.4",
24
- "vscode-json-languageservice": "^5.2.0",
25
22
  "vscode-languageserver-protocol": "^3.17.3"
26
23
  },
27
- "gitHead": "3d269c7e69850ac5497469bede13f057db8a4980"
24
+ "gitHead": "38ec4f727b32dbf2cf3284ab02695e3a8effacc5"
28
25
  }