@bascik/language-server 0.1.0-rc.4 → 0.1.0-rc.6

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.
Files changed (119) hide show
  1. package/README.md +72 -30
  2. package/dist/analyzer.d.ts +70 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/analyzer.js +657 -77
  5. package/dist/analyzer.js.map +1 -1
  6. package/dist/api-rules.d.ts +7 -0
  7. package/dist/api-rules.d.ts.map +1 -1
  8. package/dist/api-rules.js +235 -16
  9. package/dist/api-rules.js.map +1 -1
  10. package/dist/bin.js +4 -1
  11. package/dist/bin.js.map +1 -1
  12. package/dist/check.d.ts +14 -1
  13. package/dist/check.d.ts.map +1 -1
  14. package/dist/check.js +116 -10
  15. package/dist/check.js.map +1 -1
  16. package/dist/cli.d.ts.map +1 -1
  17. package/dist/cli.js +27 -8
  18. package/dist/cli.js.map +1 -1
  19. package/dist/compatibility-rules.json +21 -3
  20. package/dist/component-metadata.d.ts.map +1 -1
  21. package/dist/component-metadata.js +3 -1
  22. package/dist/component-metadata.js.map +1 -1
  23. package/dist/component-usages.d.ts +47 -0
  24. package/dist/component-usages.d.ts.map +1 -0
  25. package/dist/component-usages.js +495 -0
  26. package/dist/component-usages.js.map +1 -0
  27. package/dist/config-reader.d.ts +41 -0
  28. package/dist/config-reader.d.ts.map +1 -0
  29. package/dist/config-reader.js +461 -0
  30. package/dist/config-reader.js.map +1 -0
  31. package/dist/config.d.ts +10 -0
  32. package/dist/config.d.ts.map +1 -1
  33. package/dist/config.js +25 -30
  34. package/dist/config.js.map +1 -1
  35. package/dist/directive-rules.d.ts +3 -3
  36. package/dist/directive-rules.d.ts.map +1 -1
  37. package/dist/directive-rules.js +6 -6
  38. package/dist/directive-rules.js.map +1 -1
  39. package/dist/hand-written-escaper.d.ts +35 -0
  40. package/dist/hand-written-escaper.d.ts.map +1 -0
  41. package/dist/hand-written-escaper.js +739 -0
  42. package/dist/hand-written-escaper.js.map +1 -0
  43. package/dist/module-specifiers.d.ts +25 -0
  44. package/dist/module-specifiers.d.ts.map +1 -1
  45. package/dist/module-specifiers.js +234 -165
  46. package/dist/module-specifiers.js.map +1 -1
  47. package/dist/name-groups.d.ts +36 -0
  48. package/dist/name-groups.d.ts.map +1 -0
  49. package/dist/name-groups.js +198 -0
  50. package/dist/name-groups.js.map +1 -0
  51. package/dist/plain-holes.d.ts +116 -0
  52. package/dist/plain-holes.d.ts.map +1 -0
  53. package/dist/plain-holes.js +1970 -0
  54. package/dist/plain-holes.js.map +1 -0
  55. package/dist/project.d.ts +58 -1
  56. package/dist/project.d.ts.map +1 -1
  57. package/dist/project.js +146 -8
  58. package/dist/project.js.map +1 -1
  59. package/dist/references.d.ts +47 -0
  60. package/dist/references.d.ts.map +1 -0
  61. package/dist/references.js +241 -0
  62. package/dist/references.js.map +1 -0
  63. package/dist/script-modules.d.ts +60 -0
  64. package/dist/script-modules.d.ts.map +1 -0
  65. package/dist/script-modules.js +382 -0
  66. package/dist/script-modules.js.map +1 -0
  67. package/dist/server-script-rules.d.ts +94 -1
  68. package/dist/server-script-rules.d.ts.map +1 -1
  69. package/dist/server-script-rules.js +2572 -230
  70. package/dist/server-script-rules.js.map +1 -1
  71. package/dist/server-script-templates.d.ts +250 -0
  72. package/dist/server-script-templates.d.ts.map +1 -0
  73. package/dist/server-script-templates.js +1685 -0
  74. package/dist/server-script-templates.js.map +1 -0
  75. package/dist/server.d.ts +191 -3
  76. package/dist/server.d.ts.map +1 -1
  77. package/dist/server.js +822 -50
  78. package/dist/server.js.map +1 -1
  79. package/dist/start.d.ts +10 -1
  80. package/dist/start.d.ts.map +1 -1
  81. package/dist/start.js +14 -2
  82. package/dist/start.js.map +1 -1
  83. package/dist/string-typed-flow.d.ts +26 -0
  84. package/dist/string-typed-flow.d.ts.map +1 -0
  85. package/dist/string-typed-flow.js +496 -0
  86. package/dist/string-typed-flow.js.map +1 -0
  87. package/dist/typescript-blocks.d.ts +205 -0
  88. package/dist/typescript-blocks.d.ts.map +1 -0
  89. package/dist/typescript-blocks.js +464 -0
  90. package/dist/typescript-blocks.js.map +1 -0
  91. package/dist/typescript-editor-mode.d.ts +28 -0
  92. package/dist/typescript-editor-mode.d.ts.map +1 -0
  93. package/dist/typescript-editor-mode.js +161 -0
  94. package/dist/typescript-editor-mode.js.map +1 -0
  95. package/dist/typescript-engine.d.ts +115 -0
  96. package/dist/typescript-engine.d.ts.map +1 -0
  97. package/dist/typescript-engine.js +286 -0
  98. package/dist/typescript-engine.js.map +1 -0
  99. package/dist/typescript-features.d.ts +136 -0
  100. package/dist/typescript-features.d.ts.map +1 -0
  101. package/dist/typescript-features.js +374 -0
  102. package/dist/typescript-features.js.map +1 -0
  103. package/dist/typescript-loader.d.ts +55 -0
  104. package/dist/typescript-loader.d.ts.map +1 -0
  105. package/dist/typescript-loader.js +202 -0
  106. package/dist/typescript-loader.js.map +1 -0
  107. package/dist/typescript-lsp.d.ts +8 -0
  108. package/dist/typescript-lsp.d.ts.map +1 -0
  109. package/dist/typescript-lsp.js +115 -0
  110. package/dist/typescript-lsp.js.map +1 -0
  111. package/dist/typescript-service.d.ts +350 -0
  112. package/dist/typescript-service.d.ts.map +1 -0
  113. package/dist/typescript-service.js +1465 -0
  114. package/dist/typescript-service.js.map +1 -0
  115. package/dist/typescript-worker.d.ts +11 -0
  116. package/dist/typescript-worker.d.ts.map +1 -0
  117. package/dist/typescript-worker.js +107 -0
  118. package/dist/typescript-worker.js.map +1 -0
  119. package/package.json +20 -7
package/dist/server.js CHANGED
@@ -3,14 +3,114 @@ import * as path from "node:path";
3
3
  import * as fs from "node:fs";
4
4
  import * as fsPromises from "node:fs/promises";
5
5
  import { pathToFileURL } from "node:url";
6
- import { DidChangeWatchedFilesNotification, FileChangeType, TextDocuments, TextDocumentSyncKind, } from "vscode-languageserver";
6
+ import { DiagnosticSeverity, DidChangeWatchedFilesNotification, FileChangeType, TextDocuments, TextDocumentSyncKind, } from "vscode-languageserver";
7
7
  import { TextDocument } from "vscode-languageserver-textdocument";
8
- import { buildSnapshot, CONFIG_FILE_CANDIDATES, isConfigFile, isExcludedProjectPath, isInsideComponentRoots, isPathInside, } from "./project.js";
9
- import { createDiagnostics, createCompletions, createHover, createDefinition, createCodeActions, } from "./analyzer.js";
10
- /** Files whose changes can alter a diagnostic: project config, and the HTML that defines or uses components. */
11
- const WATCHED_FILE_PATTERNS = ["**/bascik.config.{ts,js,mjs}", "**/*.html"];
8
+ import { buildSnapshot, CONFIG_FILE_CANDIDATES, isConfigFile, isExcludedProjectPath, hasIsolatedClientBlocks, isInsideComponentRoots, isPathInside, isUsageSourcePath, } from "./project.js";
9
+ import { createDiagnosticsSafely, createCompletions, createHover, createDefinition, createCodeActions, } from "./analyzer.js";
10
+ import { createReferences } from "./references.js";
11
+ import { EXTENSION_CONFIG_FILES } from "./config-reader.js";
12
+ import { invalidateScriptModules, normalizeModulePath, scriptModulesOf, snapshotRoots, } from "./script-modules.js";
13
+ import { hasTypeScriptBlocks, pageComponentsForTypeScript, relocateBlockRanges, typeScriptBlockAt, } from "./typescript-blocks.js";
14
+ import { toLspCompletionItem, toLspHover, toLspLocation, toLspSignatureHelp, } from "./typescript-lsp.js";
15
+ import { TYPESCRIPT_DIAGNOSTIC_SOURCE, } from "./typescript-service.js";
16
+ /** Languages whose files can run in Node and so get the markup rules. */
17
+ const SCRIPT_LANGUAGES = new Set([
18
+ "javascript",
19
+ "typescript",
20
+ ]);
21
+ const HTML_AND_SCRIPT_LANGUAGES = new Set([
22
+ "html",
23
+ ...SCRIPT_LANGUAGES,
24
+ ]);
25
+ /**
26
+ * Files whose changes can alter a diagnostic: project config, the HTML that
27
+ * defines or uses components, and script modules, whose imports decide
28
+ * which files run in Node (script-modules.ts).
29
+ */
30
+ const WATCHED_FILE_PATTERNS = [
31
+ "**/bascik.config.{ts,js,mjs}",
32
+ "**/*.html",
33
+ "**/*.{ts,mts,js,mjs}",
34
+ ];
35
+ /** A script module's extension, as WATCHED_FILE_PATTERNS watches it. */
36
+ const SCRIPT_MODULE_FILE = /\.(?:ts|mts|js|mjs)$/i;
37
+ /**
38
+ * With TypeScript checks on, also the files a `type="text/typescript"` block can import that
39
+ * WATCHED_FILE_PATTERNS does not watch already, and the files that decide how it is checked.
40
+ */
41
+ const TYPESCRIPT_WATCHED_FILE_PATTERNS = [
42
+ "**/*.{cts,cjs}",
43
+ "**/{tsconfig,package}.json",
44
+ ];
45
+ /** Files an edit to which can change a TypeScript block's errors. */
46
+ const TYPESCRIPT_INPUT_FILE = /\.(?:[mc]?ts|[mc]?js)$|(?:^|[\\/])(?:tsconfig|package)\.json$/i;
47
+ /**
48
+ * Completion trigger characters only TypeScript blocks use (a member after `.`, an import path after `/`). Bascik's
49
+ * own completions are for markup, so a request these trigger asks TypeScript alone.
50
+ */
51
+ const TYPESCRIPT_TRIGGER_CHARACTERS = [".", "/"];
52
+ /** Quiet period after an edit before TypeScript checks the open pages again. Bascik's diagnostics do not wait. */
53
+ const TYPESCRIPT_DELAY_MS = 150;
54
+ /**
55
+ * How long no open page may have TypeScript blocks before the TypeScript engine is released. Its programs hold
56
+ * the DOM library and Node's types (a few hundred megabytes); a page closed and opened again soon should not pay
57
+ * for building them twice.
58
+ */
59
+ export const TYPESCRIPT_RELEASE_DELAY_MS = 30_000;
60
+ /** The client's options with every field checked, since any client can send anything. */
61
+ export function readInitializationOptions(value) {
62
+ const options = typeof value === "object" && value !== null
63
+ ? value
64
+ : {};
65
+ const typescript = typeof options.typescript === "object" && options.typescript !== null
66
+ ? options.typescript
67
+ : {};
68
+ const pathOption = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
69
+ return {
70
+ typescriptEnabled: typescript.enabled !== false,
71
+ typescriptPath: pathOption(typescript.path),
72
+ typescriptEditorPath: pathOption(typescript.editorPath),
73
+ typescriptReleaseDelayMs: typeof typescript.releaseDelayMs === "number" &&
74
+ Number.isFinite(typescript.releaseDelayMs) &&
75
+ typescript.releaseDelayMs >= 0
76
+ ? typescript.releaseDelayMs
77
+ : undefined,
78
+ editorHasEmbeddedTypeScript: options.editorHasEmbeddedTypeScript === true,
79
+ };
80
+ }
81
+ /**
82
+ * The packages whose presence in a package.json makes a folder without a config a Bascik project: Bascik itself
83
+ * (a zero-config site), or the language server on its own (a linter-only component library).
84
+ */
85
+ const BASCIK_PACKAGES = ["@bascik/bascik", "@bascik/language-server"];
86
+ const DEPENDENCY_FIELDS = [
87
+ "dependencies",
88
+ "devDependencies",
89
+ "peerDependencies",
90
+ "optionalDependencies",
91
+ ];
12
92
  /** Quiet period before open documents are checked again after a change elsewhere in the project. */
13
93
  const REVALIDATION_DELAY_MS = 50;
94
+ /**
95
+ * The real path of `fsPath`, resolving symlinks in the part of it that exists, so a deleted file still
96
+ * resolves through its folder.
97
+ */
98
+ function realPathOfExisting(fsPath) {
99
+ let existing = path.resolve(fsPath);
100
+ const rest = [];
101
+ for (;;) {
102
+ try {
103
+ return path.join(fs.realpathSync.native(existing), ...rest.reverse());
104
+ }
105
+ catch {
106
+ const parent = path.dirname(existing);
107
+ if (parent === existing)
108
+ return path.resolve(fsPath);
109
+ rest.push(path.basename(existing));
110
+ existing = parent;
111
+ }
112
+ }
113
+ }
14
114
  export function uriToFsPath(uri) {
15
115
  if (uri.startsWith("file://")) {
16
116
  try {
@@ -24,6 +124,7 @@ export function uriToFsPath(uri) {
24
124
  }
25
125
  export class BascikLanguageServer {
26
126
  connection;
127
+ options;
27
128
  documents = new TextDocuments(TextDocument);
28
129
  workspaceFolders = [];
29
130
  projectSnapshots = new Map();
@@ -33,8 +134,47 @@ export class BascikLanguageServer {
33
134
  clientWatchesFolders = false;
34
135
  clientSendsFolderChanges = false;
35
136
  watcherRegistration;
36
- constructor(connection) {
137
+ /**
138
+ * Open buffers whose file the editor reported deleted, by URI, with the buffer's version at that moment.
139
+ * VS Code keeps a model for every file it previewed (Peek, the References panel) after the file is deleted,
140
+ * so such a buffer stops counting as a usage source until it is edited (its version moves on), closed, or
141
+ * the file comes back.
142
+ */
143
+ deletedBuffers = new Map();
144
+ /** What each project root's package.json said about @bascik/bascik, keyed by its path, until the file changes. */
145
+ packageJsonChecks = new Map();
146
+ /** Project roots already named in the output panel as not Bascik projects, so the note is written once. */
147
+ reportedNonBascikRoots = new Set();
148
+ /** The TypeScript engine, when the client left TypeScript checks on and the host can start one. */
149
+ typeScript;
150
+ /** Whether the editor answers language features about a page's own names inside TypeScript blocks itself. */
151
+ editorHasEmbeddedTypeScript = false;
152
+ /** The last diagnostics of each kind per open document; a publish sends both, since it replaces the list. */
153
+ bascikDiagnostics = new Map();
154
+ /**
155
+ * TypeScript's last result per open document, in offsets of the text it was checked against. A publish for a
156
+ * newer text moves the ranges with their blocks (see `currentTypeScriptDiagnostics`).
157
+ */
158
+ typeScriptResults = new Map();
159
+ /** The diagnostics last sent per document, so a TypeScript result that changes nothing is not sent again. */
160
+ lastSentDiagnostics = new Map();
161
+ /**
162
+ * The TypeScript checks owed per project: the pages edited since the last check, or every open page after a
163
+ * change that can affect them all (an imported file, a tsconfig, the Bascik config).
164
+ */
165
+ typeScriptPending = new Map();
166
+ /** Bumped per project on every TypeScript input change, so a check of several pages stops once it is stale. */
167
+ typeScriptGenerations = new Map();
168
+ /** Releases the TypeScript engine once no open page has TypeScript blocks (see `scheduleTypeScriptRelease`). */
169
+ typeScriptReleaseTimer;
170
+ typeScriptReleaseDelayMs = TYPESCRIPT_RELEASE_DELAY_MS;
171
+ /** Project roots whose missing TypeScript has been noted in the output panel. */
172
+ reportedTypeScriptRoots = new Set();
173
+ /** Whether the client's unusable TypeScript path has been shown, which happens once: it is one setting. */
174
+ reportedClientPathProblem = false;
175
+ constructor(connection, options = {}) {
37
176
  this.connection = connection;
177
+ this.options = options;
38
178
  this.documents.listen(this.connection);
39
179
  this.setupHandlers();
40
180
  }
@@ -57,6 +197,19 @@ export class BascikLanguageServer {
57
197
  ?.relativePatternSupport === true;
58
198
  this.clientSendsFolderChanges =
59
199
  params.capabilities.workspace?.workspaceFolders === true;
200
+ const clientOptions = readInitializationOptions(params.initializationOptions);
201
+ this.editorHasEmbeddedTypeScript =
202
+ clientOptions.editorHasEmbeddedTypeScript;
203
+ this.typeScriptReleaseDelayMs =
204
+ clientOptions.typescriptReleaseDelayMs ??
205
+ this.options.typeScriptReleaseDelayMs ??
206
+ TYPESCRIPT_RELEASE_DELAY_MS;
207
+ if (clientOptions.typescriptEnabled) {
208
+ this.typeScript = this.options.createTypeScriptEngine?.({
209
+ clientPath: clientOptions.typescriptPath,
210
+ editorPath: clientOptions.typescriptEditorPath,
211
+ });
212
+ }
60
213
  return {
61
214
  capabilities: {
62
215
  workspace: {
@@ -64,11 +217,23 @@ export class BascikLanguageServer {
64
217
  },
65
218
  textDocumentSync: TextDocumentSyncKind.Incremental,
66
219
  completionProvider: {
67
- triggerCharacters: ["<", " ", '"', "'", "-"],
220
+ triggerCharacters: [
221
+ "<",
222
+ " ",
223
+ '"',
224
+ "'",
225
+ "-",
226
+ ...TYPESCRIPT_TRIGGER_CHARACTERS,
227
+ ],
68
228
  resolveProvider: false,
69
229
  },
230
+ signatureHelpProvider: {
231
+ triggerCharacters: ["(", ","],
232
+ retriggerCharacters: [")"],
233
+ },
70
234
  hoverProvider: true,
71
235
  definitionProvider: true,
236
+ referencesProvider: true,
72
237
  codeActionProvider: true,
73
238
  },
74
239
  };
@@ -87,30 +252,44 @@ export class BascikLanguageServer {
87
252
  });
88
253
  this.documents.onDidChangeContent((change) => {
89
254
  void this.validateDocument(change.document);
90
- // Open HTML buffers feed prop usage into other documents' diagnostics.
91
- if (change.document.languageId === "html") {
92
- this.scheduleRevalidation(change.document, true);
93
- }
255
+ this.revalidateDependents(change.document);
256
+ this.typeScriptInputChanged(change.document, false);
94
257
  });
95
258
  this.documents.onDidClose((event) => {
259
+ this.deletedBuffers.delete(event.document.uri);
260
+ this.bascikDiagnostics.delete(event.document.uri);
261
+ this.typeScriptResults.delete(event.document.uri);
262
+ this.lastSentDiagnostics.delete(event.document.uri);
96
263
  this.connection.sendDiagnostics({
97
264
  uri: event.document.uri,
98
265
  diagnostics: [],
99
266
  });
100
- // Closing an open HTML buffer changes which usages supply component props.
101
- if (event.document.languageId === "html") {
102
- this.scheduleRevalidation(event.document, true);
103
- }
267
+ this.typeScriptInputChanged(event.document, true);
268
+ // Closing a buffer puts the file on disk back in its place.
269
+ this.revalidateDependents(event.document);
104
270
  });
271
+ // Bascik's own answers first; inside a TypeScript block, TypeScript's (see `typeScriptFeature`).
105
272
  this.connection.onCompletion(async (params) => {
106
273
  const document = this.documents.get(params.textDocument.uri);
107
274
  if (!document)
108
275
  return undefined;
109
276
  const fsPath = uriToFsPath(document.uri);
110
- const snapshot = await this.getSnapshotForFile(fsPath);
111
- if (!snapshot)
112
- return undefined;
113
- return createCompletions(document, params.position, snapshot);
277
+ const trigger = params.context?.triggerCharacter;
278
+ const typeScriptOnly = trigger !== undefined &&
279
+ TYPESCRIPT_TRIGGER_CHARACTERS.includes(trigger);
280
+ const snapshot = typeScriptOnly
281
+ ? undefined
282
+ : await this.getSnapshotForFile(fsPath);
283
+ const bascik = snapshot
284
+ ? createCompletions(document, params.position, snapshot)
285
+ : undefined;
286
+ const typeScript = await this.typeScriptFeature(document, params.position, "completion", trigger);
287
+ if (!typeScript?.length)
288
+ return bascik;
289
+ return [
290
+ ...(bascik ?? []),
291
+ ...typeScript.map((entry) => toLspCompletionItem(document, entry)),
292
+ ];
114
293
  });
115
294
  this.connection.onHover(async (params) => {
116
295
  const document = this.documents.get(params.textDocument.uri);
@@ -118,9 +297,13 @@ export class BascikLanguageServer {
118
297
  return undefined;
119
298
  const fsPath = uriToFsPath(document.uri);
120
299
  const snapshot = await this.getSnapshotForFile(fsPath);
121
- if (!snapshot)
122
- return undefined;
123
- return createHover(document, params.position, snapshot);
300
+ const bascik = snapshot
301
+ ? createHover(document, params.position, snapshot)
302
+ : undefined;
303
+ if (bascik)
304
+ return bascik;
305
+ const typeScript = await this.typeScriptFeature(document, params.position, "hover");
306
+ return typeScript ? toLspHover(document, typeScript) : undefined;
124
307
  });
125
308
  this.connection.onDefinition(async (params) => {
126
309
  const document = this.documents.get(params.textDocument.uri);
@@ -128,9 +311,52 @@ export class BascikLanguageServer {
128
311
  return undefined;
129
312
  const fsPath = uriToFsPath(document.uri);
130
313
  const snapshot = await this.getSnapshotForFile(fsPath);
131
- if (!snapshot)
314
+ const bascik = snapshot
315
+ ? createDefinition(document, params.position, snapshot, fsPath)
316
+ : undefined;
317
+ // Bascik's own (an import path in a directive script, a component) is the one answer: never both.
318
+ if (bascik?.length)
319
+ return bascik;
320
+ const typeScript = await this.typeScriptFeature(document, params.position, "definition");
321
+ return typeScript?.length ? typeScript.map(toLspLocation) : bascik;
322
+ });
323
+ this.connection.onSignatureHelp(async (params) => {
324
+ const document = this.documents.get(params.textDocument.uri);
325
+ if (!document)
132
326
  return undefined;
133
- return createDefinition(document, params.position, snapshot, fsPath);
327
+ const typeScript = await this.typeScriptFeature(document, params.position, "signatureHelp");
328
+ return typeScript ? toLspSignatureHelp(typeScript) : undefined;
329
+ });
330
+ // Find All References for a component. Every failure is an empty list, never an error.
331
+ this.connection.onReferences(async (params) => {
332
+ const uri = params.textDocument.uri;
333
+ if (!uri.startsWith("file:"))
334
+ return [];
335
+ const fsPath = uriToFsPath(uri);
336
+ // A request can name a file that is not open, such as one listed in the References panel.
337
+ let document = this.documents.get(uri);
338
+ if (!document && fsPath.toLowerCase().endsWith(".html")) {
339
+ try {
340
+ const text = await fsPromises.readFile(fsPath, "utf8");
341
+ document = TextDocument.create(uri, "html", 0, text);
342
+ }
343
+ catch {
344
+ return [];
345
+ }
346
+ }
347
+ if (!document)
348
+ return [];
349
+ const snapshot = await this.getSnapshotForFile(fsPath);
350
+ if (!snapshot)
351
+ return [];
352
+ return createReferences({
353
+ document,
354
+ fsPath,
355
+ position: params.position,
356
+ includeDeclaration: params.context?.includeDeclaration === true,
357
+ snapshot,
358
+ sources: this.referenceSources(snapshot),
359
+ });
134
360
  });
135
361
  this.connection.onCodeAction(async (params) => {
136
362
  const document = this.documents.get(params.textDocument.uri);
@@ -147,6 +373,47 @@ export class BascikLanguageServer {
147
373
  })));
148
374
  });
149
375
  }
376
+ /**
377
+ * A buffer the editor keeps open for a file deleted on disk (VS Code keeps the model of a file it showed
378
+ * in Peek or References), unedited since. It is not a source of usages for references or diagnostics.
379
+ */
380
+ isOrphanedBuffer(document) {
381
+ return this.deletedBuffers.get(document.uri) === document.version;
382
+ }
383
+ /** Open documents that still stand for a file or unsaved work, so their usages count. */
384
+ liveOpenDocuments() {
385
+ return this.documents
386
+ .all()
387
+ .filter((document) => !this.isOrphanedBuffer(document));
388
+ }
389
+ /**
390
+ * The text of every HTML file in a project that can use a component: pages and other HTML under `src` and
391
+ * the pages folder, and every component file, with open buffers' unsaved text in place of what is on disk.
392
+ * A buffer left open for a deleted file is not a source.
393
+ */
394
+ referenceSources(snapshot) {
395
+ const sources = new Map(snapshot.componentSourceByFile);
396
+ for (const [file, text] of snapshot.htmlUsageByFile)
397
+ sources.set(file, text);
398
+ for (const document of this.documents.all()) {
399
+ if (document.languageId !== "html" || !document.uri.startsWith("file:"))
400
+ continue;
401
+ const fsPath = uriToFsPath(document.uri);
402
+ if (!fsPath.toLowerCase().endsWith(".html"))
403
+ continue;
404
+ if (this.isOrphanedBuffer(document))
405
+ continue;
406
+ if (this.findProjectRoot(fsPath) !== snapshot.projectRoot)
407
+ continue;
408
+ if (isExcludedProjectPath(fsPath, snapshot.projectRoot))
409
+ continue;
410
+ if (!isUsageSourcePath(fsPath, snapshot) &&
411
+ !isInsideComponentRoots(fsPath.replace(/\\/g, "/"), snapshot.componentRoots))
412
+ continue;
413
+ sources.set(fsPath, document.getText());
414
+ }
415
+ return sources;
416
+ }
150
417
  /**
151
418
  * Follows the editor adding or removing workspace folders. A removed folder's projects are forgotten and its
152
419
  * open documents stop having diagnostics; a re-added folder starts again from disk.
@@ -166,7 +433,7 @@ export class BascikLanguageServer {
166
433
  }
167
434
  }
168
435
  void this.registerFileWatchers();
169
- this.scheduleRevalidation(undefined, false);
436
+ this.scheduleRevalidation(undefined, undefined);
170
437
  }
171
438
  /**
172
439
  * Asks the editor to report changes to config and HTML files, replacing any earlier request. Each workspace
@@ -179,14 +446,25 @@ export class BascikLanguageServer {
179
446
  return;
180
447
  this.watcherRegistration?.dispose();
181
448
  this.watcherRegistration = undefined;
449
+ const patterns = this.typeScript
450
+ ? [...WATCHED_FILE_PATTERNS, ...TYPESCRIPT_WATCHED_FILE_PATTERNS]
451
+ : WATCHED_FILE_PATTERNS;
182
452
  const watchers = this.clientWatchesFolders
183
- ? this.workspaceFolders.flatMap((folder) => WATCHED_FILE_PATTERNS.map((pattern) => ({
453
+ ? this.workspaceFolders.flatMap((folder) => patterns.map((pattern) => ({
184
454
  globPattern: { baseUri: pathToFileURL(folder).toString(), pattern },
185
455
  })))
186
- : WATCHED_FILE_PATTERNS.map((globPattern) => ({ globPattern }));
456
+ : patterns.map((globPattern) => ({ globPattern }));
187
457
  if (watchers.length === 0)
188
458
  return;
189
- this.watcherRegistration = await this.connection.client.register(DidChangeWatchedFilesNotification.type, { watchers });
459
+ // Called with `void`, so a rejection here (an editor refusing the registration, or a connection
460
+ // closing mid-request) would be unhandled and end the process. Without watchers the server still
461
+ // works; it only misses changes made outside open documents.
462
+ try {
463
+ this.watcherRegistration = await this.connection.client.register(DidChangeWatchedFilesNotification.type, { watchers });
464
+ }
465
+ catch (error) {
466
+ this.connection.console.error(`Bascik could not ask the editor to watch config and HTML files, so changes made outside open documents are not picked up until a reload: ${error instanceof Error ? error.message : String(error)}`);
467
+ }
190
468
  }
191
469
  /** Forgets every project snapshot, so the next request rebuilds them from disk. */
192
470
  invalidateSnapshots() {
@@ -204,17 +482,42 @@ export class BascikLanguageServer {
204
482
  */
205
483
  async handleWatchedFileChanges(changes) {
206
484
  let everything = false;
485
+ let scriptChanged = false;
207
486
  const affectedRoots = new Set();
208
- for (const { fsPath, type } of changes) {
487
+ for (const change of changes) {
488
+ const { type } = change;
489
+ const fsPath = this.toWorkspaceSpelling(change.fsPath);
490
+ this.trackDeletedBuffers(fsPath, type);
209
491
  const workspaceRoot = this.workspaceFolders.find((root) => isPathInside(fsPath, root));
210
492
  if (workspaceRoot && isExcludedProjectPath(fsPath, workspaceRoot))
211
493
  continue;
212
494
  if (isConfigFile(fsPath)) {
213
495
  // A config file appearing or disappearing also changes which project the files below it belong to.
214
- this.invalidateProject(path.dirname(path.resolve(fsPath)));
496
+ const configRoot = path.dirname(path.resolve(fsPath));
497
+ this.invalidateProject(configRoot);
498
+ if (this.typeScript) {
499
+ // Its import root and script scoping decide what TypeScript reports.
500
+ this.typeScript.forgetProject(configRoot);
501
+ this.scheduleTypeScriptCheck(configRoot, undefined);
502
+ }
215
503
  everything = true;
216
504
  continue;
217
505
  }
506
+ if (this.typeScript && TYPESCRIPT_INPUT_FILE.test(fsPath)) {
507
+ // An open buffer is the newer text; the engine already has it.
508
+ if (!this.documents.get(pathToFileURL(fsPath).toString()))
509
+ this.typeScript.fileChanged(fsPath);
510
+ const projectRoot = this.findProjectRoot(fsPath);
511
+ if (projectRoot)
512
+ this.scheduleTypeScriptCheck(projectRoot, undefined);
513
+ }
514
+ if (SCRIPT_MODULE_FILE.test(fsPath)) {
515
+ // A closed module's imports changed, or it appeared or went away:
516
+ // which files run in Node may differ. Open modules are checked again.
517
+ invalidateScriptModules();
518
+ scriptChanged = true;
519
+ continue;
520
+ }
218
521
  if (!fsPath.toLowerCase().endsWith(".html"))
219
522
  continue;
220
523
  const projectRoot = this.findProjectRoot(fsPath);
@@ -232,7 +535,7 @@ export class BascikLanguageServer {
232
535
  this.invalidateProject(projectRoot);
233
536
  continue;
234
537
  }
235
- if (!isPathInside(fsPath, path.join(projectRoot, "src")))
538
+ if (!isUsageSourcePath(fsPath, snapshot))
236
539
  continue;
237
540
  let html;
238
541
  if (type !== FileChangeType.Deleted) {
@@ -252,12 +555,51 @@ export class BascikLanguageServer {
252
555
  snapshot.htmlUsageByFile.set(fsPath, html);
253
556
  }
254
557
  if (everything) {
255
- this.scheduleRevalidation(undefined, false);
558
+ this.scheduleRevalidation(undefined, undefined);
256
559
  }
257
560
  else {
258
561
  for (const projectRoot of affectedRoots) {
259
- this.scheduleRevalidation(projectRoot, false);
562
+ this.scheduleRevalidation(projectRoot, undefined);
260
563
  }
564
+ // A module may belong to a project other than the one above it on
565
+ // disk (a shared importRoot), so every open module is checked again.
566
+ if (scriptChanged)
567
+ this.scheduleRevalidation(undefined, SCRIPT_LANGUAGES);
568
+ }
569
+ }
570
+ /**
571
+ * A watcher can report a path through a symlink's target (`/private/tmp/site/...` for a `/tmp/site`
572
+ * workspace, or a symlinked home folder) while the workspace folder, the snapshot and open documents use
573
+ * the folder's own spelling. Returns the path in that spelling when it lies in a workspace folder only
574
+ * once symlinks are resolved; otherwise as given.
575
+ */
576
+ toWorkspaceSpelling(fsPath) {
577
+ if (this.workspaceFolders.some((root) => isPathInside(fsPath, root)))
578
+ return fsPath;
579
+ const real = realPathOfExisting(fsPath);
580
+ for (const root of this.workspaceFolders) {
581
+ const realRoot = realPathOfExisting(root);
582
+ if (isPathInside(real, realRoot))
583
+ return path.join(path.resolve(root), path.relative(realRoot, real));
584
+ }
585
+ return fsPath;
586
+ }
587
+ /** Notes open buffers left behind by a deleted file or folder, and forgets them when the file is back. */
588
+ trackDeletedBuffers(fsPath, type) {
589
+ if (type !== FileChangeType.Deleted && this.deletedBuffers.size === 0)
590
+ return;
591
+ const target = realPathOfExisting(fsPath);
592
+ for (const document of this.documents.all()) {
593
+ if (!document.uri.startsWith("file:"))
594
+ continue;
595
+ const documentPath = uriToFsPath(document.uri);
596
+ if (!isPathInside(documentPath, fsPath) &&
597
+ !isPathInside(realPathOfExisting(documentPath), target))
598
+ continue;
599
+ if (type === FileChangeType.Deleted)
600
+ this.deletedBuffers.set(document.uri, document.version);
601
+ else
602
+ this.deletedBuffers.delete(document.uri);
261
603
  }
262
604
  }
263
605
  async getSnapshotForFile(fsPath) {
@@ -300,6 +642,63 @@ export class BascikLanguageServer {
300
642
  // Fall back to workspace folder
301
643
  return roots.find((r) => isPathInside(fsPath, r));
302
644
  }
645
+ /**
646
+ * Does Bascik check this project? A folder with a `bascik.config.*` does. A workspace folder without one (the
647
+ * fallback in `findProjectRoot`) is a Bascik project only when its root has a language server config
648
+ * (`bascik.ext.json` and the rest of {@link EXTENSION_CONFIG_FILES}, which a global install of the linter
649
+ * relies on) or its package.json lists one of {@link BASCIK_PACKAGES}. Otherwise it is some other project, and
650
+ * the output panel says so once. Navigation, hover and completion still work there; only diagnostics are
651
+ * withheld.
652
+ */
653
+ isBascikProject(projectRoot) {
654
+ if ([...CONFIG_FILE_CANDIDATES, ...EXTENSION_CONFIG_FILES].some((candidate) => fs.existsSync(path.join(projectRoot, candidate)))) {
655
+ this.reportedNonBascikRoots.delete(projectRoot);
656
+ return true;
657
+ }
658
+ const isBascik = this.packageJsonDependsOnBascik(projectRoot);
659
+ if (isBascik) {
660
+ this.reportedNonBascikRoots.delete(projectRoot);
661
+ }
662
+ else if (!this.reportedNonBascikRoots.has(projectRoot)) {
663
+ this.reportedNonBascikRoots.add(projectRoot);
664
+ this.connection.console.info(`${projectRoot} is not a Bascik project: it has no ${CONFIG_FILE_CANDIDATES.join(", ")} or ${EXTENSION_CONFIG_FILES.join(", ")}, and its package.json does not list ${BASCIK_PACKAGES.join(" or ")}, so it gets no Bascik diagnostics. Add any one of them to check it.`);
665
+ }
666
+ return isBascik;
667
+ }
668
+ /** Reads `<projectRoot>/package.json` again only when its size or modification time changed. */
669
+ packageJsonDependsOnBascik(projectRoot) {
670
+ const file = path.join(projectRoot, "package.json");
671
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
672
+ if (!stat) {
673
+ this.packageJsonChecks.delete(file);
674
+ return false;
675
+ }
676
+ const cached = this.packageJsonChecks.get(file);
677
+ if (cached?.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
678
+ return cached.dependsOnBascik;
679
+ }
680
+ let dependsOnBascik = false;
681
+ try {
682
+ const manifest = JSON.parse(fs.readFileSync(file, "utf8"));
683
+ dependsOnBascik = DEPENDENCY_FIELDS.some((field) => {
684
+ const dependencies = typeof manifest === "object" && manifest !== null
685
+ ? manifest[field]
686
+ : undefined;
687
+ return (typeof dependencies === "object" &&
688
+ dependencies !== null &&
689
+ BASCIK_PACKAGES.some((name) => Object.hasOwn(dependencies, name)));
690
+ });
691
+ }
692
+ catch (error) {
693
+ this.connection.console.info(`${file} could not be read (${error instanceof Error ? error.message : String(error)}), so it does not make ${projectRoot} a Bascik project.`);
694
+ }
695
+ this.packageJsonChecks.set(file, {
696
+ mtimeMs: stat.mtimeMs,
697
+ size: stat.size,
698
+ dependsOnBascik,
699
+ });
700
+ return dependsOnBascik;
701
+ }
303
702
  async validateDocument(document) {
304
703
  // Only files on disk have a project. Other schemes (git, output, untitled) must not get diagnostics.
305
704
  if (!document.uri.startsWith("file:"))
@@ -308,34 +707,382 @@ export class BascikLanguageServer {
308
707
  const fsPath = uriToFsPath(document.uri);
309
708
  // A file outside every workspace folder belongs to no project, so there is nothing to check it against.
310
709
  if (!this.workspaceFolders.some((root) => isPathInside(fsPath, root))) {
311
- this.connection.sendDiagnostics({
312
- uri: document.uri,
313
- version,
314
- diagnostics: [],
315
- });
710
+ this.typeScriptResults.delete(document.uri);
711
+ this.publish(document.uri, version, []);
712
+ return;
713
+ }
714
+ // A React or Vue app has its own src/components and src/api; Bascik's rules do not apply there.
715
+ const projectRoot = this.findProjectRoot(fsPath);
716
+ if (projectRoot && !this.isBascikProject(projectRoot)) {
717
+ this.typeScriptResults.delete(document.uri);
718
+ this.publish(document.uri, version, []);
316
719
  return;
317
720
  }
318
721
  const snapshot = await this.getSnapshotForFile(fsPath);
319
722
  // The document was edited or closed while the project was read; a newer check follows or the file is gone.
320
723
  if (this.documents.get(document.uri)?.version !== version)
321
724
  return;
322
- const openDocs = this.documents.all().map((d) => ({
725
+ const openDocs = this.liveOpenDocuments().map((d) => ({
323
726
  fsPath: uriToFsPath(d.uri),
324
727
  text: d.getText(),
325
728
  }));
326
- const diagnostics = createDiagnostics(document, fsPath, snapshot, openDocs);
327
- this.connection.sendDiagnostics({
328
- uri: document.uri,
329
- version,
330
- diagnostics,
729
+ const diagnostics = createDiagnosticsSafely(document, fsPath, this.scriptOwnerSnapshot(document, fsPath, snapshot, openDocs), openDocs);
730
+ this.publish(document.uri, version, diagnostics);
731
+ }
732
+ /**
733
+ * Sends a document's Bascik diagnostics with its latest TypeScript diagnostics. A publish replaces the
734
+ * document's whole list, so each kind is sent with the other's last result. TypeScript's may be from an older
735
+ * text until its next check: they are moved with their blocks, and dropped from a block whose text changed.
736
+ */
737
+ publish(uri, version, bascik) {
738
+ this.bascikDiagnostics.set(uri, bascik);
739
+ this.send(uri, version, [
740
+ ...bascik,
741
+ ...this.currentTypeScriptDiagnostics(uri),
742
+ ]);
743
+ }
744
+ send(uri, version, diagnostics) {
745
+ this.lastSentDiagnostics.set(uri, JSON.stringify(diagnostics));
746
+ this.connection.sendDiagnostics({ uri, version, diagnostics });
747
+ }
748
+ /**
749
+ * The document's last TypeScript diagnostics, located in its current text. Ranges checked against an older
750
+ * text move with their block when only the text around it changed, and are left out when the block itself
751
+ * changed, until TypeScript checks it again: an editor would otherwise show them on the wrong code.
752
+ */
753
+ currentTypeScriptDiagnostics(uri) {
754
+ const result = this.typeScriptResults.get(uri);
755
+ const document = this.documents.get(uri);
756
+ if (!result || !document)
757
+ return [];
758
+ const text = document.getText();
759
+ if (result.text !== text) {
760
+ result.diagnostics = relocateBlockRanges(result.text, text, result.diagnostics);
761
+ result.text = text;
762
+ }
763
+ return result.diagnostics.map((diagnostic) => toLspDiagnostic(document, diagnostic));
764
+ }
765
+ /**
766
+ * An edit to an open document that TypeScript blocks depend on: a page's own text, or a file a block may import
767
+ * (whose unsaved text the engine reads instead of the file on disk).
768
+ */
769
+ typeScriptInputChanged(document, closed) {
770
+ if (!this.typeScript || !document.uri.startsWith("file:"))
771
+ return;
772
+ const fsPath = uriToFsPath(document.uri);
773
+ const projectRoot = this.findProjectRoot(fsPath);
774
+ if (document.languageId === "html") {
775
+ if (closed && projectRoot)
776
+ this.typeScript.closePage(projectRoot, fsPath);
777
+ if (closed)
778
+ this.scheduleTypeScriptRelease();
779
+ if (!closed && projectRoot) {
780
+ // A page edit only changes that page's blocks, unless it is a component: its scripts run on the pages
781
+ // that use it, so what it adds to the globals (and, with `scoping.scriptBlocks` off, its names) are theirs.
782
+ const snapshot = this.projectSnapshots.get(projectRoot);
783
+ const isComponent = snapshot !== undefined &&
784
+ isInsideComponentRoots(fsPath, snapshot.componentRoots);
785
+ this.scheduleTypeScriptCheck(projectRoot, isComponent ? undefined : document.uri);
786
+ }
787
+ return;
788
+ }
789
+ if (!TYPESCRIPT_INPUT_FILE.test(fsPath))
790
+ return;
791
+ this.typeScript.setOpenFile(fsPath, closed ? undefined : document.getText());
792
+ if (projectRoot)
793
+ this.scheduleTypeScriptCheck(projectRoot, undefined);
794
+ }
795
+ /**
796
+ * Checks a page with TypeScript after a quiet period, or (with no page) every open page of the project, when a
797
+ * file they may all import changed. A page's blocks import nothing from other pages, so a page edit checks that
798
+ * page only. Earlier requests for the project go stale at once, so a running check stops instead of finishing
799
+ * work nobody reads; the pages it had yet to check stay owed.
800
+ */
801
+ scheduleTypeScriptCheck(projectRoot, pageUri) {
802
+ const engine = this.typeScript;
803
+ if (!engine)
804
+ return;
805
+ engine.cancel(projectRoot);
806
+ this.typeScriptGenerations.set(projectRoot, (this.typeScriptGenerations.get(projectRoot) ?? 0) + 1);
807
+ this.oweTypeScriptCheck(projectRoot, pageUri === undefined ? "all" : [pageUri], true);
808
+ }
809
+ /** Records pages (or every page) the project's next TypeScript check must cover, and starts its timer. */
810
+ oweTypeScriptCheck(projectRoot, pages, restartTimer) {
811
+ const engine = this.typeScript;
812
+ if (!engine)
813
+ return;
814
+ let pending = this.typeScriptPending.get(projectRoot);
815
+ if (!pending) {
816
+ pending = { all: false, pages: new Set() };
817
+ this.typeScriptPending.set(projectRoot, pending);
818
+ }
819
+ if (pages === "all")
820
+ pending.all = true;
821
+ else
822
+ for (const page of pages)
823
+ pending.pages.add(page);
824
+ if (pending.timer && !restartTimer)
825
+ return;
826
+ if (pending.timer)
827
+ clearTimeout(pending.timer);
828
+ const owed = pending;
829
+ owed.timer = setTimeout(() => {
830
+ if (this.typeScriptPending.get(projectRoot) === owed)
831
+ this.typeScriptPending.delete(projectRoot);
832
+ void this.checkTypeScriptProject(engine, projectRoot, owed);
833
+ }, TYPESCRIPT_DELAY_MS);
834
+ }
835
+ async checkTypeScriptProject(engine, projectRoot, owed) {
836
+ const open = this.documents
837
+ .all()
838
+ .filter((document) => document.languageId === "html" &&
839
+ document.uri.startsWith("file:") &&
840
+ this.findProjectRoot(uriToFsPath(document.uri)) === projectRoot);
841
+ // The edited pages first, then (after a change every page may see) the rest.
842
+ const pages = [
843
+ ...open.filter((document) => owed.pages.has(document.uri)),
844
+ ...(owed.all
845
+ ? open.filter((document) => !owed.pages.has(document.uri))
846
+ : []),
847
+ ];
848
+ const generation = this.typeScriptGenerations.get(projectRoot);
849
+ const checks = [];
850
+ for (const document of pages)
851
+ checks.push(await this.typeScriptPageCheck(projectRoot, document));
852
+ // Every page the engine will check, given together, so TypeScript builds its programs once rather than once
853
+ // per page (opening many pages at once otherwise rebuilt them for each).
854
+ const requests = checks.flatMap((check) => check.request === undefined ? [] : [check.request]);
855
+ if (requests.length > 1 &&
856
+ this.typeScriptGenerations.get(projectRoot) === generation)
857
+ engine.preparePages({
858
+ projectRoot,
859
+ importRoot: requests[0].importRoot,
860
+ pages: requests.map((request) => ({
861
+ htmlPath: request.htmlPath,
862
+ text: request.text,
863
+ isolatedClientBlocks: request.isolatedClientBlocks,
864
+ pageScopeHtml: request.pageScopeHtml,
865
+ usedComponents: request.usedComponents,
866
+ })),
867
+ });
868
+ for (let index = 0; index < checks.length; index++) {
869
+ // A newer change scheduled a check; the pages this one had yet to check go to it.
870
+ const stale = this.typeScriptGenerations.get(projectRoot) !== generation ||
871
+ !(await this.checkTypeScriptPage(engine, projectRoot, checks[index]));
872
+ if (stale) {
873
+ this.oweTypeScriptCheck(projectRoot, checks.slice(index).map((check) => check.document.uri), false);
874
+ return;
875
+ }
876
+ }
877
+ }
878
+ /** What checking a page with TypeScript takes: the engine's request, or none for a page it has nothing to say on. */
879
+ async typeScriptPageCheck(projectRoot, document) {
880
+ const { version } = document;
881
+ const text = document.getText();
882
+ const check = { document, version, text };
883
+ // A page without a TypeScript block costs nothing: TypeScript is not even loaded for it.
884
+ if (!hasTypeScriptBlocks(text))
885
+ return check;
886
+ const fsPath = uriToFsPath(document.uri);
887
+ if (!this.workspaceFolders.some((root) => isPathInside(fsPath, root)))
888
+ return check;
889
+ if (!this.isBascikProject(projectRoot))
890
+ return check;
891
+ const snapshot = await this.getSnapshotForFile(fsPath);
892
+ check.request = {
893
+ projectRoot,
894
+ importRoot: snapshot?.importRoot ?? path.join(projectRoot, "src"),
895
+ htmlPath: fsPath,
896
+ text,
897
+ isolatedClientBlocks: snapshot !== undefined && hasIsolatedClientBlocks(fsPath, snapshot),
898
+ ...(snapshot === undefined
899
+ ? {}
900
+ : pageComponentsForTypeScript(fsPath, text, snapshot, (componentPath) => this.documents
901
+ .get(pathToFileURL(componentPath).toString())
902
+ ?.getText())),
903
+ };
904
+ return check;
905
+ }
906
+ /**
907
+ * Checks one page with TypeScript and publishes the result. False when the check went stale (cancelled by a
908
+ * newer change, or the page was edited meanwhile), so the caller owes it again.
909
+ */
910
+ async checkTypeScriptPage(engine, projectRoot, check) {
911
+ const { document, version, text, request } = check;
912
+ const { uri } = document;
913
+ const previous = this.typeScriptResults.get(uri)?.diagnostics;
914
+ if (!request) {
915
+ const hasBlocks = hasTypeScriptBlocks(text);
916
+ if (!hasBlocks && previous?.length)
917
+ this.publishTypeScript(document, text, []);
918
+ if (!hasBlocks)
919
+ this.scheduleTypeScriptRelease();
920
+ return true;
921
+ }
922
+ // Edited meanwhile: it is checked again.
923
+ if (this.documents.get(uri)?.version !== version)
924
+ return false;
925
+ this.cancelTypeScriptRelease();
926
+ const result = await engine.diagnostics(request);
927
+ const fsPath = request.htmlPath;
928
+ // Closed meanwhile: there is nothing to show.
929
+ const current = this.documents.get(uri);
930
+ if (!current)
931
+ return true;
932
+ // Edited meanwhile, or cancelled by a newer change: it is checked again.
933
+ if (current.version !== version || result.status === "cancelled")
934
+ return false;
935
+ if (result.status === "failed") {
936
+ this.connection.console.error(`Bascik could not check the TypeScript in ${fsPath}: ${result.message}`);
937
+ return true;
938
+ }
939
+ if (result.clientPathProblem && !this.reportedClientPathProblem) {
940
+ // A path the user set that is mistyped or broken: said where they will see it, not only in a log.
941
+ this.reportedClientPathProblem = true;
942
+ const instead = result.status === "ok"
943
+ ? "TypeScript blocks are checked with another TypeScript instead."
944
+ : "TypeScript checks are off.";
945
+ const message = `Bascik cannot use its TypeScript path setting: ${result.clientPathProblem}. ${instead}`;
946
+ this.connection.console.warn(message);
947
+ // Typed void, but sent as a request: a client that refuses it must not leave a rejected promise behind.
948
+ const shown = this.connection.window.showWarningMessage(message);
949
+ if (shown instanceof Promise)
950
+ shown.catch(() => undefined);
951
+ }
952
+ if (result.status === "unavailable") {
953
+ // Off without TypeScript, quietly: one line in the output panel per project, nothing in the editor.
954
+ if (!this.reportedTypeScriptRoots.has(projectRoot)) {
955
+ this.reportedTypeScriptRoots.add(projectRoot);
956
+ this.connection.console.info(`${projectRoot}: ${result.message}`);
957
+ }
958
+ if (previous?.length)
959
+ this.publishTypeScript(document, text, []);
960
+ return true;
961
+ }
962
+ this.reportedTypeScriptRoots.delete(projectRoot);
963
+ this.publishTypeScript(document, text, result.diagnostics);
964
+ return true;
965
+ }
966
+ /**
967
+ * A language feature from TypeScript at a position inside one of a page's `type="text/typescript"` blocks, or
968
+ * `undefined` (TypeScript off, outside a block, nothing to say, or the page edited meanwhile). With an editor
969
+ * that answers about the page's own names itself, only what it cannot answer is asked for.
970
+ */
971
+ async typeScriptFeature(document, position, kind, triggerCharacter) {
972
+ const engine = this.typeScript;
973
+ if (!engine || document.languageId !== "html")
974
+ return undefined;
975
+ if (!document.uri.startsWith("file:"))
976
+ return undefined;
977
+ const text = document.getText();
978
+ const offset = document.offsetAt(position);
979
+ if (!typeScriptBlockAt(text, offset))
980
+ return undefined;
981
+ const projectRoot = this.findProjectRoot(uriToFsPath(document.uri));
982
+ if (!projectRoot)
983
+ return undefined;
984
+ const { version } = document;
985
+ const { request } = await this.typeScriptPageCheck(projectRoot, document);
986
+ if (!request || this.documents.get(document.uri)?.version !== version)
987
+ return undefined;
988
+ const result = await engine.feature({
989
+ ...request,
990
+ query: {
991
+ kind,
992
+ offset,
993
+ crossFileOnly: this.editorHasEmbeddedTypeScript,
994
+ triggerCharacter,
995
+ },
331
996
  });
997
+ // Edited meanwhile: the answer is for a text the editor no longer shows.
998
+ if (this.documents.get(document.uri)?.version !== version)
999
+ return undefined;
1000
+ if (result.status === "failed")
1001
+ this.connection.console.error(`Bascik could not answer a TypeScript ${kind} request in ${request.htmlPath}: ${result.message}`);
1002
+ return result.status === "ok" ? result.answer : undefined;
1003
+ }
1004
+ /**
1005
+ * Releases the TypeScript engine after `typeScriptReleaseDelayMs` if, by then, no open page has TypeScript
1006
+ * blocks: it holds a few hundred megabytes, which nothing needs then. The next page with blocks starts it again.
1007
+ */
1008
+ scheduleTypeScriptRelease() {
1009
+ if (!this.typeScript || this.typeScriptReleaseTimer)
1010
+ return;
1011
+ this.typeScriptReleaseTimer = setTimeout(() => {
1012
+ this.typeScriptReleaseTimer = undefined;
1013
+ const engine = this.typeScript;
1014
+ if (!engine)
1015
+ return;
1016
+ const needed = this.documents
1017
+ .all()
1018
+ .some((document) => document.languageId === "html" &&
1019
+ document.uri.startsWith("file:") &&
1020
+ hasTypeScriptBlocks(document.getText()));
1021
+ if (needed)
1022
+ return;
1023
+ void engine
1024
+ .release()
1025
+ .then(() => this.connection.console.info("TypeScript checks gave their memory back: no open page has TypeScript blocks. They start again with the next one."));
1026
+ }, this.typeScriptReleaseDelayMs);
1027
+ this.typeScriptReleaseTimer.unref?.();
1028
+ }
1029
+ cancelTypeScriptRelease() {
1030
+ clearTimeout(this.typeScriptReleaseTimer);
1031
+ this.typeScriptReleaseTimer = undefined;
1032
+ }
1033
+ /** Records a page's TypeScript result for `text` and sends it with Bascik's, unless that changes nothing. */
1034
+ publishTypeScript(document, text, diagnostics) {
1035
+ const { uri } = document;
1036
+ this.typeScriptResults.set(uri, { text, diagnostics });
1037
+ // Bascik's own check has not published yet (it waits on the project snapshot); it sends these with its own.
1038
+ const bascik = this.bascikDiagnostics.get(uri);
1039
+ if (!bascik)
1040
+ return;
1041
+ const all = [...bascik, ...this.currentTypeScriptDiagnostics(uri)];
1042
+ if (this.lastSentDiagnostics.get(uri) === JSON.stringify(all))
1043
+ return;
1044
+ this.send(uri, document.version, all);
1045
+ }
1046
+ /**
1047
+ * The snapshot to check a document with. A .ts or .js file that its own
1048
+ * project does not run in Node, but another built project does (a helper
1049
+ * under a `scripts.importRoot` or component root outside that project,
1050
+ * such as a monorepo's shared folder), is checked with that project.
1051
+ */
1052
+ scriptOwnerSnapshot(document, fsPath, snapshot, openDocs) {
1053
+ if (!SCRIPT_LANGUAGES.has(document.languageId))
1054
+ return snapshot;
1055
+ const key = normalizeModulePath(fsPath);
1056
+ if (snapshot && scriptModulesOf(snapshot, openDocs).has(key))
1057
+ return snapshot;
1058
+ for (const other of this.projectSnapshots.values()) {
1059
+ if (other === snapshot)
1060
+ continue;
1061
+ if (!snapshotRoots(other).some((root) => isPathInside(fsPath, root)))
1062
+ continue;
1063
+ if (scriptModulesOf(other, openDocs).has(key))
1064
+ return other;
1065
+ }
1066
+ return snapshot;
1067
+ }
1068
+ /**
1069
+ * Checks the open documents that a changed or closed buffer feeds. An HTML
1070
+ * buffer supplies prop usage to other HTML documents, and its directive
1071
+ * scripts decide which .ts and .js files run in Node (script-modules.ts);
1072
+ * a .ts or .js buffer's imports decide that too.
1073
+ */
1074
+ revalidateDependents(document) {
1075
+ if (document.languageId === "html")
1076
+ this.scheduleRevalidation(document, HTML_AND_SCRIPT_LANGUAGES);
1077
+ else if (SCRIPT_LANGUAGES.has(document.languageId))
1078
+ this.scheduleRevalidation(document, SCRIPT_LANGUAGES);
332
1079
  }
333
1080
  /**
334
1081
  * Checks open documents again shortly, so a burst of changes costs one pass. With a document or a project
335
- * root, only that project is checked; without one, every open document is. `htmlOnly` limits the pass to
336
- * HTML documents.
1082
+ * root, only that project is checked; without one, every open document is. `languages` limits the pass to
1083
+ * documents in those languages; undefined checks every language.
337
1084
  */
338
- scheduleRevalidation(scope, htmlOnly) {
1085
+ scheduleRevalidation(scope, languages) {
339
1086
  const projectRoot = typeof scope === "string"
340
1087
  ? scope
341
1088
  : scope
@@ -345,11 +1092,15 @@ export class BascikLanguageServer {
345
1092
  const previous = this.revalidationTimers.get(key);
346
1093
  if (previous)
347
1094
  clearTimeout(previous.timer);
348
- const onlyHtml = previous ? previous.htmlOnly && htmlOnly : htmlOnly;
1095
+ const merged = previous === undefined
1096
+ ? languages
1097
+ : previous.languages === undefined || languages === undefined
1098
+ ? undefined
1099
+ : new Set([...previous.languages, ...languages]);
349
1100
  const timer = setTimeout(() => {
350
1101
  this.revalidationTimers.delete(key);
351
1102
  for (const document of this.documents.all()) {
352
- if (onlyHtml && document.languageId !== "html")
1103
+ if (merged && !merged.has(document.languageId))
353
1104
  continue;
354
1105
  if (projectRoot &&
355
1106
  this.findProjectRoot(uriToFsPath(document.uri)) !== projectRoot) {
@@ -358,7 +1109,7 @@ export class BascikLanguageServer {
358
1109
  void this.validateDocument(document);
359
1110
  }
360
1111
  }, REVALIDATION_DELAY_MS);
361
- this.revalidationTimers.set(key, { timer, htmlOnly: onlyHtml });
1112
+ this.revalidationTimers.set(key, { timer, languages: merged });
362
1113
  }
363
1114
  listen() {
364
1115
  this.connection.listen();
@@ -368,8 +1119,29 @@ export class BascikLanguageServer {
368
1119
  for (const { timer } of this.revalidationTimers.values())
369
1120
  clearTimeout(timer);
370
1121
  this.revalidationTimers.clear();
1122
+ for (const { timer } of this.typeScriptPending.values())
1123
+ clearTimeout(timer);
1124
+ this.typeScriptPending.clear();
1125
+ this.cancelTypeScriptRelease();
1126
+ void this.typeScript?.dispose();
1127
+ this.typeScript = undefined;
371
1128
  this.watcherRegistration?.dispose();
372
1129
  this.watcherRegistration = undefined;
373
1130
  }
374
1131
  }
1132
+ /** A TypeScript diagnostic as the editor shows it: its range in the HTML, TypeScript's code, and Bascik's source tag. */
1133
+ function toLspDiagnostic(document, diagnostic) {
1134
+ return {
1135
+ range: {
1136
+ start: document.positionAt(diagnostic.start),
1137
+ end: document.positionAt(diagnostic.end),
1138
+ },
1139
+ message: diagnostic.message,
1140
+ severity: diagnostic.category === "error"
1141
+ ? DiagnosticSeverity.Error
1142
+ : DiagnosticSeverity.Warning,
1143
+ source: TYPESCRIPT_DIAGNOSTIC_SOURCE,
1144
+ code: diagnostic.code,
1145
+ };
1146
+ }
375
1147
  //# sourceMappingURL=server.js.map