@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/analyzer.js CHANGED
@@ -7,10 +7,14 @@ import { findCompatibilityMatches } from "./rules.js";
7
7
  import { analyzeApiRouteSource } from "./api-rules.js";
8
8
  import { findComponentStructureProblems, isKnownBascikAttribute, isKnownBuildValue, unknownBascikAttributeMessage, unknownDirectiveValueMessage, } from "./directive-rules.js";
9
9
  import { findModuleSpecifiers } from "./module-specifiers.js";
10
- import { analyzeServerScriptSource } from "./server-script-rules.js";
10
+ import { analyzeServerScriptSource, } from "./server-script-rules.js";
11
+ import { HAND_WRITTEN_ESCAPER_RULE } from "./hand-written-escaper.js";
12
+ import { normalizeModulePath, scriptModulesOf, } from "./script-modules.js";
13
+ import { parseImportSpecifier } from "./server-script-templates.js";
11
14
  import { analyzeComponentSource, } from "./component-metadata.js";
12
15
  import { parseIgnoreDirectives, isDiagnosticIgnored, } from "./ignore-comments.js";
13
16
  import { loadExtensionConfig } from "./config.js";
17
+ import { countInstancesOnPages, findNameGroups, sharedNameGroupMessage, } from "./name-groups.js";
14
18
  export const BUILT_IN_HTML_ELEMENTS = new Set([
15
19
  "a",
16
20
  "abbr",
@@ -128,7 +132,12 @@ export const SCRIPT_DIRECTIVES = [
128
132
  {
129
133
  name: "data-bascik-build",
130
134
  detail: "Bascik build-time script",
131
- documentation: "Executes in Node.js at build time. The default exported handler function returns HTML markup that replaces this script tag in the generated HTML.",
135
+ documentation: "Executes in Node.js at build time. In a component, it runs for each use with that page's context. The default exported handler function returns HTML markup that replaces this script tag in the generated HTML.",
136
+ },
137
+ {
138
+ name: "data-bascik-build-once",
139
+ detail: "Bascik build-time script, run once",
140
+ documentation: "Executes once, without page or route context, and reuses its markup wherever the file is used. In a component, it runs when the component is registered and every use shares the output; in a dynamic route template, every generated page shares it.",
132
141
  },
133
142
  {
134
143
  name: "data-bascik-routes",
@@ -138,12 +147,12 @@ export const SCRIPT_DIRECTIVES = [
138
147
  {
139
148
  name: "data-bascik-server",
140
149
  detail: "Bascik server-side request script",
141
- documentation: "Executes in Node.js per request on production and dev servers. The default exported handler function replaces this script tag.",
150
+ documentation: "Executes in Node.js per request on production and dev servers. The markup the default exported handler function returns replaces this script tag: a string, an html`...` value, or an array of them, joined with no separator.",
142
151
  },
143
152
  {
144
153
  name: "data-bascik-stream",
145
154
  detail: "Bascik server-side streaming script",
146
- documentation: "Executes in Node.js per request on production servers. Streams chunked HTML responses to the client as data becomes available.",
155
+ documentation: "Executes in Node.js per request on production and dev servers. Streams chunked HTML responses to the client as data becomes available. The handler returns markup as a server script does: a string, an html`...` value, or an array of them, joined with no separator.",
147
156
  },
148
157
  ];
149
158
  export const SCRIPT_BLOCK_RE = /(<script(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/script(?:[\t\n\f\r /][^>]*)?>/gi;
@@ -153,24 +162,45 @@ export function maskHtmlRawTextContents(html) {
153
162
  export function escapeRegExp(value) {
154
163
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
155
164
  }
165
+ /** Lookahead for the end of a tag name, as in the compiler: HTML whitespace, `/` or `>`. */
166
+ const TAG_NAME_END = "(?=[\\t\\n\\f\\r />])";
156
167
  export function findMatchingClose(html, tagName, contentStart) {
157
168
  const tn = tagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
- const openRe = new RegExp(`<${tn}[\\s>]`, "gi");
159
- const closeRe = new RegExp(`<\\/${tn}>`, "gi");
169
+ // Tag names end at HTML whitespace, `/` or `>`, and an end tag may carry whitespace or junk before
170
+ // its `>`, the shapes the compiler accepts (component-tags.ts, component-slots.ts).
171
+ // The end tag runs to the first `>` after its name, so it is found as the name, then indexOf(">"): a
172
+ // regex `[^>]*>` rescanned the rest of the document from each `</name` with no `>` (quadratic).
173
+ const openRe = new RegExp(`<${tn}${TAG_NAME_END}`, "gi");
174
+ const closeNameRe = new RegExp(`<\\/${tn}${TAG_NAME_END}`, "gi");
175
+ const closeFrom = (from) => {
176
+ closeNameRe.lastIndex = from;
177
+ const name = closeNameRe.exec(html);
178
+ if (!name)
179
+ return null;
180
+ // No `>` after this end tag means none after any later one either.
181
+ const gt = html.indexOf(">", name.index + name[0].length);
182
+ return gt === -1 ? null : { index: name.index, end: gt + 1 };
183
+ };
184
+ // The next open and end tag at or after `pos`, kept while `pos` has not passed them, so nested or
185
+ // self-closing tags do not search again for the same end tag each time.
186
+ let openMatch;
187
+ let closeMatch;
160
188
  let depth = 1;
161
189
  let pos = contentStart;
162
190
  while (pos < html.length) {
163
- openRe.lastIndex = pos;
164
- closeRe.lastIndex = pos;
165
- const openMatch = openRe.exec(html);
166
- const closeMatch = closeRe.exec(html);
191
+ if (closeMatch === undefined || (closeMatch && closeMatch.index < pos))
192
+ closeMatch = closeFrom(pos);
167
193
  if (!closeMatch)
168
194
  return -1;
195
+ if (openMatch === undefined || (openMatch && openMatch.index < pos)) {
196
+ openRe.lastIndex = pos;
197
+ openMatch = openRe.exec(html);
198
+ }
169
199
  if (!openMatch || closeMatch.index < openMatch.index) {
170
200
  depth--;
171
201
  if (depth === 0)
172
202
  return closeMatch.index;
173
- pos = closeMatch.index + closeMatch[0].length;
203
+ pos = closeMatch.end;
174
204
  }
175
205
  else {
176
206
  let inDoubleQuote = false;
@@ -219,7 +249,7 @@ const isTagNameChar = (code) => isTagNameStart(code) ||
219
249
  * so its result depends only on where the scan stands; `tagEndFrom` remembers
220
250
  * it per position and no position is scanned twice.
221
251
  */
222
- function* scanTags(source) {
252
+ function* scanTags(source, from = 0) {
223
253
  const length = source.length;
224
254
  // 0 = not scanned yet, -1 = no closing `>`, otherwise the index after `>`.
225
255
  const tagEndFrom = new Int32Array(length + 1);
@@ -253,7 +283,7 @@ function* scanTags(source) {
253
283
  tagEndFrom[index] = end;
254
284
  return end;
255
285
  };
256
- let cursor = 0;
286
+ let cursor = from;
257
287
  while (cursor < length) {
258
288
  const open = source.indexOf("<", cursor);
259
289
  if (open < 0)
@@ -276,33 +306,77 @@ function* scanTags(source) {
276
306
  name: source.slice(nameStart, nameEnd),
277
307
  closing,
278
308
  text: source.slice(open, end),
309
+ start: open,
310
+ end,
279
311
  };
280
312
  cursor = end;
281
313
  }
282
314
  }
283
315
  export function findNearestParentComponent(source, componentMap) {
284
- const stack = [];
285
- for (const tag of scanTags(source)) {
316
+ return findNearestParentComponents(source, [source.length], componentMap)[0];
317
+ }
318
+ /**
319
+ * For each offset (ascending), the component that `findNearestParentComponent(source.slice(0, offset))`
320
+ * finds, from one scan of `source`. Rescanning the prefix for every offset was quadratic in the number of
321
+ * offsets (one per `data-bascik-slot` tag).
322
+ *
323
+ * The open-element stack carries, per entry, the nearest component at or below it, so each answer is
324
+ * read in constant time. A tag that starts before an offset but ends after it is not a tag in that prefix
325
+ * (its `>` is cut off), so for that offset the prefix scan is continued from just after its `<`, exactly
326
+ * as the prefix scan would, on a copy of the stack.
327
+ */
328
+ export function findNearestParentComponents(source, offsets, componentMap) {
329
+ const apply = (stack, nearest, tag) => {
286
330
  const name = tag.name.toLowerCase();
287
331
  if (tag.closing) {
288
332
  const matchingIndex = stack.lastIndexOf(name);
289
- if (matchingIndex >= 0)
290
- stack.splice(matchingIndex);
333
+ if (matchingIndex >= 0) {
334
+ stack.length = matchingIndex;
335
+ nearest.length = matchingIndex;
336
+ }
291
337
  }
292
338
  else if (!/\/\s*>$/.test(tag.text)) {
293
339
  stack.push(name);
340
+ nearest.push(componentMap.has(name) ? name : nearest.at(-1));
341
+ }
342
+ };
343
+ const stack = [];
344
+ const nearest = [];
345
+ const tags = scanTags(source);
346
+ let pending = tags.next();
347
+ const results = [];
348
+ for (const offset of offsets) {
349
+ while (!pending.done && pending.value.end <= offset) {
350
+ apply(stack, nearest, pending.value);
351
+ pending = tags.next();
352
+ }
353
+ if (!pending.done && pending.value.start < offset) {
354
+ // The offset sits inside what the full scan reads as one tag (an unclosed quote can make it long),
355
+ // so the tags before it are read from the source cut at the offset. Each such offset rescans from
356
+ // that tag's start: quadratic only when many slot tags hide inside one long run-on tag, which
357
+ // markup does not do, so the cost is accepted rather than memoized.
358
+ const prefixStack = stack.slice();
359
+ const prefixNearest = nearest.slice();
360
+ for (const tag of scanTags(source.slice(0, offset), pending.value.start + 1))
361
+ apply(prefixStack, prefixNearest, tag);
362
+ results.push(prefixNearest.at(-1));
363
+ }
364
+ else {
365
+ results.push(nearest.at(-1));
294
366
  }
295
367
  }
296
- return stack.reverse().find((name) => componentMap.has(name));
368
+ return results;
297
369
  }
298
370
  export function parseScriptOpenTagAttributes(openTag) {
299
371
  const attrs = new Map();
300
372
  const insideTag = openTag.replace(/^<script\b/i, "").replace(/>$/, "");
301
- const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
373
+ // An unquoted value runs to whitespace (quotes, `=` and backticks
374
+ // included), and the first occurrence of a name wins, as in the tokenizer.
375
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
302
376
  let match;
303
377
  while ((match = attrRe.exec(insideTag)) !== null) {
304
378
  const name = match[1]?.toLowerCase();
305
- if (!name)
379
+ if (!name || attrs.has(name))
306
380
  continue;
307
381
  const value = match[2] ?? match[3] ?? match[4];
308
382
  attrs.set(name, value === undefined ? true : value);
@@ -314,11 +388,14 @@ export function parseScriptOpenTagAttributes(openTag) {
314
388
  * maps to `""`, as the DOM reports it. The first occurrence of a name wins, as
315
389
  * in the HTML tokenizer, and text inside a quoted value is never read as an
316
390
  * attribute. An unquoted value keeps its slashes; a trailing `/>` ends it.
391
+ *
392
+ * @internal Exported for the attribute tokenizer agreement test
393
+ * (skills-tests/tests/attribute-tokenizer-agreement.test.ts).
317
394
  */
318
- function readOpenTagAttributes(openTag) {
395
+ export function readOpenTagAttributes(openTag) {
319
396
  const attrs = new Map();
320
397
  const insideTag = openTag.replace(/^<[^\s/>]+/, "").replace(/\/?>$/, "");
321
- const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
398
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'][^\s]*)))?/gi;
322
399
  let match;
323
400
  while ((match = attrRe.exec(insideTag)) !== null) {
324
401
  const name = match[1].toLowerCase();
@@ -348,11 +425,22 @@ export function leadingSlashSpecifierMessage(specifier) {
348
425
  `Use '@/${rest}' to resolve against scripts.importRoot, ` +
349
426
  `or './${rest}' to resolve relative to this file.`);
350
427
  }
428
+ /**
429
+ * The script directives that run in Node and resolve `./`, `../` and `@/` specifiers against the
430
+ * file and `scripts.importRoot`. Leading-slash diagnostics and Go to Definition share this list.
431
+ */
432
+ const MODULE_RESOLVING_DIRECTIVES = [
433
+ "data-bascik-build",
434
+ "data-bascik-build-once",
435
+ "data-bascik-server",
436
+ "data-bascik-routes",
437
+ "data-bascik-stream",
438
+ ];
439
+ function hasModuleResolvingDirective(attrs) {
440
+ return MODULE_RESOLVING_DIRECTIVES.some((name) => attrs.has(name));
441
+ }
351
442
  export function collectLeadingSlashDiagnostics(document, openTag, scriptBody, blockStart, attrs) {
352
- if (!attrs.has("data-bascik-build") &&
353
- !attrs.has("data-bascik-server") &&
354
- !attrs.has("data-bascik-routes") &&
355
- !attrs.has("data-bascik-stream")) {
443
+ if (!hasModuleResolvingDirective(attrs)) {
356
444
  return [];
357
445
  }
358
446
  const out = [];
@@ -433,7 +521,60 @@ export function completionReplacementRange(document, position) {
433
521
  end: position,
434
522
  };
435
523
  }
436
- export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = []) {
524
+ /**
525
+ * The `component-name-underscore` message for a component file, or null. The
526
+ * tag is the lowercased file name up to its first dot, as the build derives it
527
+ * (`deriveComponentName` in @bascik/bascik), so `site-nav.my_v2.html` defines
528
+ * `<site-nav>` and gets no warning. An `#id` rule compiles to the class
529
+ * `b_id_<component>_<id>`, so `<a_b>` with `#c` and `<a>` with `#b_c` spell
530
+ * one class, which the build rejects; the example uses the file's own name.
531
+ */
532
+ export const componentNameUnderscoreMessage = (fileName) => {
533
+ const tag = fileName.split(".")[0].toLowerCase();
534
+ const at = tag.indexOf("_");
535
+ if (at === -1)
536
+ return null;
537
+ const head = tag.slice(0, at);
538
+ const rest = tag.slice(at + 1);
539
+ // The example needs a real pair: a component name and an id that starts
540
+ // with a letter, as an #id selector the build converts does.
541
+ return underscoreMessage(tag, head && /^[a-z]/.test(rest) ? { head, rest } : null);
542
+ };
543
+ const underscoreMessage = (tag, split) => {
544
+ const example = split
545
+ ? `: #btn in <${tag}> and #${split.rest}_btn in <${split.head}> both compile to the class b_id_${tag}_btn, which stops the build`
546
+ : "";
547
+ return `Component "${tag}" has an underscore in its name. The name is legal, but underscores can make two components' generated id classes spell the same name${example}. Use hyphens (e.g. "${tag.replace(/_/g, "-")}").`;
548
+ };
549
+ /**
550
+ * createDiagnostics, or one analysis-failed warning when it throws, so one
551
+ * file cannot stop `bascik --check` or end the language server. The
552
+ * template scanners keep their nesting on an explicit stack, so deep
553
+ * nesting does not throw; this is the net for whatever else does.
554
+ */
555
+ export function createDiagnosticsSafely(...args) {
556
+ try {
557
+ return createDiagnostics(...args);
558
+ }
559
+ catch (error) {
560
+ const reason = error instanceof Error ? error.message : String(error);
561
+ return [
562
+ {
563
+ range: {
564
+ start: { line: 0, character: 0 },
565
+ end: { line: 0, character: 0 },
566
+ },
567
+ message: `Bascik could not analyze this file (${reason}), so it shows no other Bascik diagnostics for it. Please report it with the file, or the smallest part of it that still shows this warning.`,
568
+ severity: DiagnosticSeverity.Warning,
569
+ source: "bascik",
570
+ code: "analysis-failed",
571
+ },
572
+ ];
573
+ }
574
+ }
575
+ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = [],
576
+ /** The files that run in Node (see script-modules.ts); found from the snapshot when left out. */
577
+ scriptModules) {
437
578
  const { languageId } = document;
438
579
  if (languageId !== "css" &&
439
580
  languageId !== "javascript" &&
@@ -447,6 +588,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
447
588
  }
448
589
  const text = document.getText();
449
590
  const diagnostics = [];
591
+ const earlyExtConfig = snapshot
592
+ ? loadExtensionConfig(snapshot.projectRoot)
593
+ : {};
450
594
  const isComponentDocument = snapshot !== undefined &&
451
595
  isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots);
452
596
  // The API folder is `directory.api`, so it is read from the project when there is one. Without a project
@@ -479,10 +623,18 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
479
623
  severity = DiagnosticSeverity.Information;
480
624
  }
481
625
  diagnostics.push({
482
- range: {
483
- start: { line: 0, character: 0 },
484
- end: { line: 0, character: Math.min(text.length, 10) },
485
- },
626
+ range: diag.range
627
+ ? {
628
+ start: {
629
+ line: diag.range.startLine,
630
+ character: diag.range.startChar,
631
+ },
632
+ end: { line: diag.range.endLine, character: diag.range.endChar },
633
+ }
634
+ : {
635
+ start: { line: 0, character: 0 },
636
+ end: { line: 0, character: Math.min(text.length, 10) },
637
+ },
486
638
  message: diag.message,
487
639
  severity,
488
640
  source: "bascik",
@@ -490,9 +642,77 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
490
642
  });
491
643
  }
492
644
  }
493
- if (languageId === "html" && fsPath.startsWith("/")) {
494
- if (snapshot &&
495
- isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots)) {
645
+ /** Located diagnostics for a script body at `bodyStart`, with the data its quick fixes need. */
646
+ const pushScriptDiagnostics = (found, bodyStart, bodyLength) => {
647
+ const bodyEnd = bodyStart + bodyLength;
648
+ for (const sd of found) {
649
+ let severity = DiagnosticSeverity.Error;
650
+ if (sd.severity === "warning")
651
+ severity = DiagnosticSeverity.Warning;
652
+ else if (sd.severity === "info")
653
+ severity = DiagnosticSeverity.Information;
654
+ let data;
655
+ if (sd.template)
656
+ data = {
657
+ templateStart: bodyStart + sd.template.start,
658
+ fixable: sd.template.fixable,
659
+ bodyStart,
660
+ bodyEnd,
661
+ };
662
+ else if (sd.code === HAND_WRITTEN_ESCAPER_RULE)
663
+ data = {
664
+ bodyStart,
665
+ bodyEnd,
666
+ ...(sd.escaper
667
+ ? {
668
+ delegate: {
669
+ ...sd.escaper,
670
+ start: bodyStart + sd.escaper.start,
671
+ end: bodyStart + sd.escaper.end,
672
+ },
673
+ }
674
+ : {}),
675
+ };
676
+ diagnostics.push({
677
+ range: {
678
+ start: document.positionAt(bodyStart + sd.start),
679
+ end: document.positionAt(bodyStart + sd.end),
680
+ },
681
+ message: sd.message,
682
+ severity,
683
+ source: "bascik",
684
+ code: sd.code,
685
+ ...(data ? { data } : {}),
686
+ });
687
+ }
688
+ };
689
+ // A .ts or .js file that runs in Node (a directive script's src= file, a
690
+ // module a script imports, an API route) gets the markup and escaper rules
691
+ // that inline directive scripts get. See script-modules.ts.
692
+ const isScriptLanguage = languageId === "typescript" || languageId === "javascript";
693
+ const modules = isScriptLanguage && snapshot !== undefined
694
+ ? (scriptModules ?? scriptModulesOf(snapshot, openDocumentTexts))
695
+ : undefined;
696
+ const modulePath = normalizeModulePath(fsPath);
697
+ const isScriptModuleDocument = isScriptLanguage &&
698
+ (isApiRouteDocument || modules?.has(modulePath) === true);
699
+ // API routes, and what server scripts, stream scripts and API routes
700
+ // import, run per request: every sink rule applies.
701
+ const isRequestTimeModule = isApiRouteDocument || modules?.requestTime.has(modulePath) === true;
702
+ // A module browser code imports too is also scoped for the browser.
703
+ const isBrowserModule = modules?.browser.has(modulePath) === true;
704
+ if (isScriptModuleDocument &&
705
+ earlyExtConfig.diagnostics?.serverScriptRules !== false)
706
+ pushScriptDiagnostics(analyzeServerScriptSource(text, {
707
+ hasSrcAttribute: false,
708
+ directive: "module",
709
+ requestTime: isRequestTimeModule,
710
+ escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
711
+ }), 0, text.length);
712
+ // isComponentDocument needs the file inside a resolved (absolute) component root, so an unsaved
713
+ // buffer never matches; no POSIX-only `startsWith("/")` gate, which skipped every Windows path.
714
+ if (languageId === "html") {
715
+ if (isComponentDocument) {
496
716
  const fileName = path.basename(normalizedDocumentPath);
497
717
  const nameWithoutExt = fileName.replace(/\.html$/i, "").toLowerCase();
498
718
  if (!nameWithoutExt.includes("-") &&
@@ -508,6 +728,19 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
508
728
  source: "bascik",
509
729
  });
510
730
  }
731
+ const underscore = componentNameUnderscoreMessage(fileName);
732
+ if (underscore) {
733
+ diagnostics.push({
734
+ range: {
735
+ start: { line: 0, character: 0 },
736
+ end: { line: 0, character: Math.min(text.length, 10) },
737
+ },
738
+ code: "component-name-underscore",
739
+ message: underscore,
740
+ severity: DiagnosticSeverity.Warning,
741
+ source: "bascik",
742
+ });
743
+ }
511
744
  }
512
745
  }
513
746
  // Scoping rules describe what Bascik cannot rewrite, so they apply to component files, the only code it scopes.
@@ -541,7 +774,9 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
541
774
  normalized === "text/javascript" ||
542
775
  normalized === "application/javascript" ||
543
776
  normalized === "text/ecmascript" ||
544
- normalized === "application/ecmascript");
777
+ normalized === "application/ecmascript" ||
778
+ // Bascik transpiles inline TypeScript and scopes it like JavaScript (components.ts isJs).
779
+ normalized === "text/typescript");
545
780
  };
546
781
  const scriptBlockRe = new RegExp(SCRIPT_BLOCK_RE.source, SCRIPT_BLOCK_RE.flags);
547
782
  const styleBlockRe = /(<style(?=[\t\n\f\r />])(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/style(?:[\t\n\f\r /][^>]*)?>/gi;
@@ -633,9 +868,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
633
868
  });
634
869
  }
635
870
  }
871
+ // Field names are renamed only when the project opts in to name scoping; by default they ship as written,
872
+ // so a form that posts elsewhere needs nothing.
636
873
  const formOpenTagRegex = /<form\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
637
874
  let formMatch;
638
875
  while (isComponentDocument &&
876
+ snapshot?.scopesName === true &&
639
877
  (formMatch = formOpenTagRegex.exec(text)) !== null) {
640
878
  const formAttributes = readOpenTagAttributes(formMatch[0]);
641
879
  const action = formAttributes.get("action");
@@ -662,6 +900,27 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
662
900
  source: "bascik",
663
901
  });
664
902
  }
903
+ if (snapshot && isComponentDocument && !snapshot.scopesName) {
904
+ const groups = findNameGroups(text);
905
+ const componentName = normalizeComponentName(fsPath);
906
+ const instances = groups.length > 0
907
+ ? countInstancesOnPages(componentName, snapshot, openDocumentTexts)
908
+ : undefined;
909
+ if (instances && instances.count > 1) {
910
+ for (const group of groups) {
911
+ diagnostics.push({
912
+ range: {
913
+ start: document.positionAt(group.attributeStart),
914
+ end: document.positionAt(group.attributeEnd),
915
+ },
916
+ code: "shared-name-group",
917
+ message: sharedNameGroupMessage(group, componentName, instances, snapshot.projectRoot),
918
+ severity: DiagnosticSeverity.Warning,
919
+ source: "bascik",
920
+ });
921
+ }
922
+ }
923
+ }
665
924
  if (snapshot && isComponentDocument) {
666
925
  const componentName = normalizeComponentName(fsPath);
667
926
  const directiveRegex = /data-bascik-attr-([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([\w-]+)"|'([\w-]+)'|([\w-]+))/gi;
@@ -670,7 +929,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
670
929
  const targetName = directiveMatch[1];
671
930
  const propName = directiveMatch[2] ?? directiveMatch[3] ?? directiveMatch[4];
672
931
  const suppliedInOpen = openDocumentTexts.some(({ text }) => htmlSuppliesComponentProp(text, componentName, propName));
673
- const suppliedInDisk = Array.from(snapshot.htmlUsageByFile.values()).some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
932
+ // Pages and HTML under src, plus every component file: a component root outside src (shared
933
+ // components in a monorepo) is not in htmlUsageByFile, as Find All References also allows for.
934
+ const suppliedInDisk = [
935
+ ...snapshot.htmlUsageByFile.values(),
936
+ ...(snapshot.componentSourceByFile?.values() ?? []),
937
+ ].some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
674
938
  if (suppliedInOpen || suppliedInDisk)
675
939
  continue;
676
940
  const start = document.positionAt(directiveMatch.index);
@@ -694,6 +958,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
694
958
  const attrs = parseScriptOpenTagAttributes(openTag);
695
959
  const directiveAttrs = [
696
960
  "data-bascik-build",
961
+ "data-bascik-build-once",
697
962
  "data-bascik-server",
698
963
  "data-bascik-routes",
699
964
  "data-bascik-stream",
@@ -704,7 +969,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
704
969
  const d1 = presentDirectives[i];
705
970
  const d2 = presentDirectives[j];
706
971
  let message;
707
- if ((d1 === "data-bascik-build" && d2 === "data-bascik-server") ||
972
+ if ((d1 === "data-bascik-build" && d2 === "data-bascik-build-once") ||
973
+ (d1 === "data-bascik-build-once" && d2 === "data-bascik-build")) {
974
+ message =
975
+ "data-bascik-build and data-bascik-build-once cannot both appear on the same <script> tag. Choose one build-script mode.";
976
+ }
977
+ else if ((d1 === "data-bascik-build" && d2 === "data-bascik-server") ||
708
978
  (d1 === "data-bascik-server" && d2 === "data-bascik-build")) {
709
979
  message =
710
980
  "data-bascik-build and data-bascik-server cannot both appear on the same <script> tag. Remove one - a script runs at build time or at request time, not both.";
@@ -740,7 +1010,21 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
740
1010
  start: document.positionAt(scriptMatch.index ?? 0),
741
1011
  end: document.positionAt((scriptMatch.index ?? 0) + openTag.length),
742
1012
  },
743
- message: unknownDirectiveValueMessage(buildValue.trim()),
1013
+ message: unknownDirectiveValueMessage(),
1014
+ severity: DiagnosticSeverity.Warning,
1015
+ source: "bascik",
1016
+ code: "unknown-directive-value",
1017
+ });
1018
+ }
1019
+ const buildOnceValue = attrs.get("data-bascik-build-once");
1020
+ if (typeof buildOnceValue === "string" &&
1021
+ !isKnownBuildValue(buildOnceValue)) {
1022
+ diagnostics.push({
1023
+ range: {
1024
+ start: document.positionAt(scriptMatch.index ?? 0),
1025
+ end: document.positionAt((scriptMatch.index ?? 0) + openTag.length),
1026
+ },
1027
+ message: unknownDirectiveValueMessage("data-bascik-build-once"),
744
1028
  severity: DiagnosticSeverity.Warning,
745
1029
  source: "bascik",
746
1030
  code: "unknown-directive-value",
@@ -749,38 +1033,27 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
749
1033
  const hasServerDirective = attrs.has("data-bascik-server") ||
750
1034
  attrs.has("data-bascik-stream") ||
751
1035
  attrs.has("data-bascik-build") ||
1036
+ attrs.has("data-bascik-build-once") ||
752
1037
  attrs.has("data-bascik-routes");
753
1038
  if (hasServerDirective) {
754
1039
  const directive = attrs.has("data-bascik-stream")
755
1040
  ? "stream"
756
1041
  : attrs.has("data-bascik-server")
757
1042
  ? "server"
758
- : attrs.has("data-bascik-build")
1043
+ : attrs.has("data-bascik-build") ||
1044
+ attrs.has("data-bascik-build-once")
759
1045
  ? "build"
760
1046
  : "routes";
761
1047
  const hasSrcAttribute = /\ssrc\s*=/i.test(openTag);
762
- const serverDiags = analyzeServerScriptSource(scriptBody, {
763
- hasSrcAttribute,
764
- directive,
765
- });
766
- for (const sd of serverDiags) {
767
- const start = document.positionAt(scriptBodyOffset + sd.start);
768
- const end = document.positionAt(scriptBodyOffset + sd.end);
769
- let severity = DiagnosticSeverity.Error;
770
- if (sd.severity === "warning") {
771
- severity = DiagnosticSeverity.Warning;
772
- }
773
- else if (sd.severity === "info") {
774
- severity = DiagnosticSeverity.Information;
775
- }
776
- diagnostics.push({
777
- range: { start, end },
778
- message: sd.message,
779
- severity,
780
- source: "bascik",
781
- code: sd.code,
1048
+ const serverDiags = earlyExtConfig.diagnostics?.serverScriptRules === false
1049
+ ? []
1050
+ : analyzeServerScriptSource(scriptBody, {
1051
+ hasSrcAttribute,
1052
+ directive,
1053
+ escapeFunctions: earlyExtConfig.diagnostics?.escapeFunctions ?? [],
1054
+ lineOffset: document.positionAt(scriptBodyOffset).line,
782
1055
  });
783
- }
1056
+ pushScriptDiagnostics(serverDiags, scriptBodyOffset, scriptBody.length);
784
1057
  }
785
1058
  diagnostics.push(...collectLeadingSlashDiagnostics(document, openTag, scriptBody, scriptMatch.index ?? 0, attrs));
786
1059
  // A directive script runs in Node, at build time or per request, and never in the browser Bascik scopes.
@@ -854,6 +1127,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
854
1127
  const matchStart = elementMatch.index;
855
1128
  const scriptDirectives = new Set([
856
1129
  "data-bascik-build",
1130
+ "data-bascik-build-once",
857
1131
  "data-bascik-server",
858
1132
  "data-bascik-routes",
859
1133
  "data-bascik-stream",
@@ -882,6 +1156,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
882
1156
  // 2. Diagnose data-bascik-slot outside of components, on the component itself, or targeting undeclared slots
883
1157
  const slotTagRe = /<([A-Za-z][\w-]*)(?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?\/?>/gi;
884
1158
  let slotMatch;
1159
+ const slotTags = [];
885
1160
  while ((slotMatch = slotTagRe.exec(maskedText)) !== null) {
886
1161
  const openTag = slotMatch[0];
887
1162
  const matchStart = slotMatch.index;
@@ -902,11 +1177,15 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
902
1177
  break;
903
1178
  }
904
1179
  }
905
- if (!slotAttr)
906
- continue;
907
- const tagOffset = slotMatch.index;
1180
+ if (slotAttr)
1181
+ slotTags.push({ matchStart, baseOffset, slotAttr });
1182
+ }
1183
+ // One scan finds every slot tag's parent; a prefix rescan per tag was quadratic.
1184
+ const slotParents = findNearestParentComponents(maskedText, slotTags.map(({ matchStart }) => matchStart), componentMap);
1185
+ for (const [slotIndex, slotTag] of slotTags.entries()) {
1186
+ const { matchStart, baseOffset, slotAttr } = slotTag;
908
1187
  const slotName = slotAttr.value;
909
- const parentName = findNearestParentComponent(maskedText.slice(0, tagOffset), componentMap);
1188
+ const parentName = slotParents[slotIndex];
910
1189
  const isInsideComponentDefinition = isComponentDocument;
911
1190
  if (!parentName && !isInsideComponentDefinition) {
912
1191
  const start = document.positionAt(matchStart + baseOffset + slotAttr.index);
@@ -940,7 +1219,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
940
1219
  if (componentNames.length > 0) {
941
1220
  componentNames.sort((a, b) => b.length - a.length);
942
1221
  const escapedNames = componentNames.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
943
- const componentTagRe = new RegExp(`<(${escapedNames.join("|")})\\b`, "gi");
1222
+ const componentTagRe = new RegExp(`<(${escapedNames.join("|")})${TAG_NAME_END}`, "gi");
944
1223
  let compMatch;
945
1224
  while ((compMatch = componentTagRe.exec(maskedText)) !== null) {
946
1225
  const tagStartIndex = compMatch.index;
@@ -985,7 +1264,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
985
1264
  }
986
1265
  if (compMeta.props.length > 0) {
987
1266
  const insideOpenTag = openTagText
988
- .replace(new RegExp(`^<${escapeRegExp(tagName)}\\b`, "i"), "")
1267
+ .replace(new RegExp(`^<${escapeRegExp(tagName)}${TAG_NAME_END}`, "i"), "")
989
1268
  .replace(/\/?>$/, "");
990
1269
  const baseAttrOffset = openTagText.indexOf(insideOpenTag);
991
1270
  const bareAttrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?/gi;
@@ -998,7 +1277,7 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
998
1277
  const declaredProp = compMeta.props.find((p) => p.name.toLowerCase() === lowerAttr);
999
1278
  if (!declaredProp)
1000
1279
  continue;
1001
- const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}\\b`, "i").test(openTagText);
1280
+ const alreadySupplied = new RegExp(`\\bdata-bascik-prop-${escapeRegExp(declaredProp.name)}(?![\\w-])`, "i").test(openTagText);
1002
1281
  if (alreadySupplied)
1003
1282
  continue;
1004
1283
  const attrOffset = tagStartIndex + baseAttrOffset + bareMatch.index;
@@ -1072,11 +1351,12 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1072
1351
  else if (languageId === "css") {
1073
1352
  addCompatibilityDiagnostics(text, "css", 0);
1074
1353
  }
1075
- else {
1354
+ else if (!isScriptModuleDocument || isBrowserModule) {
1355
+ // A module that only runs in Node is never scoped for the browser.
1076
1356
  addCompatibilityDiagnostics(text, "js", 0);
1077
1357
  }
1078
1358
  const ignoreRanges = parseIgnoreDirectives(text, languageId);
1079
- const extConfig = snapshot ? loadExtensionConfig(snapshot.projectRoot) : {};
1359
+ const extConfig = earlyExtConfig;
1080
1360
  const disabledRules = new Set(extConfig.diagnostics?.disabledRules?.map((r) => r.toLowerCase()) ?? []);
1081
1361
  if (extConfig.diagnostics?.enabled === false) {
1082
1362
  return [];
@@ -1095,7 +1375,19 @@ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts
1095
1375
  extConfig.diagnostics?.unclosedComponents === false) {
1096
1376
  return false;
1097
1377
  }
1098
- return !isDiagnosticIgnored(line, code, ignoreRanges);
1378
+ if (isDiagnosticIgnored(line, code, ignoreRanges))
1379
+ return false;
1380
+ // A hole on a later line of a multi-line template: an ignore comment
1381
+ // above the template's first line covers it too.
1382
+ const templateStart = diag.data
1383
+ ?.templateStart;
1384
+ if (typeof templateStart === "number") {
1385
+ const templateLine = document.positionAt(templateStart).line;
1386
+ if (templateLine !== line &&
1387
+ isDiagnosticIgnored(templateLine, code, ignoreRanges))
1388
+ return false;
1389
+ }
1390
+ return true;
1099
1391
  });
1100
1392
  }
1101
1393
  export function createCompletions(document, position, snapshot) {
@@ -1220,7 +1512,7 @@ export function createCompletions(document, position, snapshot) {
1220
1512
  {
1221
1513
  label: "bascik-stream",
1222
1514
  detail: "Bascik server-side streaming script block",
1223
- documentation: "Executes in Node.js per request on production servers. Streams chunked HTML responses to the client as data becomes available.",
1515
+ documentation: "Executes in Node.js per request on production and dev servers. Streams chunked HTML responses to the client as data becomes available.",
1224
1516
  insertText: `<script data-bascik-stream>\n export default async function (request, context, { signal }) {\n return \`$0\`;\n }\n</script>`,
1225
1517
  },
1226
1518
  ];
@@ -1351,9 +1643,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1351
1643
  if (offset < blockStart || offset > blockEnd)
1352
1644
  continue;
1353
1645
  const attrs = parseScriptOpenTagAttributes(openTag);
1354
- if (!attrs.has("data-bascik-build") &&
1355
- !attrs.has("data-bascik-server") &&
1356
- !attrs.has("data-bascik-routes")) {
1646
+ if (!hasModuleResolvingDirective(attrs)) {
1357
1647
  return undefined;
1358
1648
  }
1359
1649
  const baseDir = path.dirname(fsPath);
@@ -1378,7 +1668,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1378
1668
  start: document.positionAt(valueStart),
1379
1669
  end: document.positionAt(valueEnd),
1380
1670
  },
1381
- targetUri: `file://${resolved}`,
1671
+ targetUri: pathToFileURL(resolved).toString(),
1382
1672
  targetRange: {
1383
1673
  start: { line: 0, character: 0 },
1384
1674
  end: { line: 0, character: 0 },
@@ -1403,7 +1693,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1403
1693
  start: document.positionAt(openTagEnd + start),
1404
1694
  end: document.positionAt(openTagEnd + end),
1405
1695
  },
1406
- targetUri: `file://${resolved}`,
1696
+ targetUri: pathToFileURL(resolved).toString(),
1407
1697
  targetRange: {
1408
1698
  start: { line: 0, character: 0 },
1409
1699
  end: { line: 0, character: 0 },
@@ -1439,7 +1729,7 @@ export function createDefinition(document, position, snapshot, fsPath) {
1439
1729
  start: { line: position.line, character: start },
1440
1730
  end: { line: position.line, character: end },
1441
1731
  },
1442
- targetUri: `file://${componentPath}`,
1732
+ targetUri: pathToFileURL(componentPath).toString(),
1443
1733
  targetRange: {
1444
1734
  start: { line: 0, character: 0 },
1445
1735
  end: { line: 0, character: 0 },
@@ -1497,6 +1787,269 @@ export function buildAutoFixEdit(document, diag) {
1497
1787
  }
1498
1788
  return undefined;
1499
1789
  }
1790
+ const sameEdits = (action, wrap) => JSON.stringify(Object.values(action.edit?.changes ?? {})[0]) ===
1791
+ JSON.stringify(wrap.edits);
1792
+ /**
1793
+ * `body` with string contents, comments and template-literal text replaced
1794
+ * by spaces (offsets kept), and the code inside template holes kept.
1795
+ */
1796
+ function codeOnly(body) {
1797
+ const out = body.split("");
1798
+ const blank = (from, to) => {
1799
+ for (let k = from; k < to && k < out.length; k++)
1800
+ if (out[k] !== "\n")
1801
+ out[k] = " ";
1802
+ };
1803
+ // A stack of open template literals; each entry is the brace depth of
1804
+ // the hole code that the template sits in.
1805
+ const holes = [];
1806
+ let depth = 0;
1807
+ let i = 0;
1808
+ const template = (from) => {
1809
+ // Scan template text from `from` (just past ` or }) to the end or `${`.
1810
+ let k = from;
1811
+ while (k < body.length) {
1812
+ if (body[k] === "\\")
1813
+ k += 2;
1814
+ else if (body[k] === "`") {
1815
+ blank(from, k);
1816
+ i = k + 1;
1817
+ return;
1818
+ }
1819
+ else if (body[k] === "$" && body[k + 1] === "{") {
1820
+ blank(from, k);
1821
+ holes.push(depth);
1822
+ depth = 0;
1823
+ i = k + 2;
1824
+ return;
1825
+ }
1826
+ else
1827
+ k++;
1828
+ }
1829
+ blank(from, body.length);
1830
+ i = body.length;
1831
+ };
1832
+ while (i < body.length) {
1833
+ const c = body[i];
1834
+ if (c === "/" && body[i + 1] === "/") {
1835
+ const nl = body.indexOf("\n", i);
1836
+ const end = nl === -1 ? body.length : nl;
1837
+ blank(i, end);
1838
+ i = end;
1839
+ }
1840
+ else if (c === "/" && body[i + 1] === "*") {
1841
+ const close = body.indexOf("*/", i + 2);
1842
+ const end = close === -1 ? body.length : close + 2;
1843
+ blank(i, end);
1844
+ i = end;
1845
+ }
1846
+ else if (c === "'" || c === '"') {
1847
+ let k = i + 1;
1848
+ while (k < body.length && body[k] !== c && body[k] !== "\n")
1849
+ k += body[k] === "\\" ? 2 : 1;
1850
+ blank(i + 1, k);
1851
+ i = k + 1;
1852
+ }
1853
+ else if (c === "`")
1854
+ template(i + 1);
1855
+ else if (c === "{") {
1856
+ depth++;
1857
+ i++;
1858
+ }
1859
+ else if (c === "}") {
1860
+ if (depth === 0 && holes.length > 0) {
1861
+ depth = holes.pop();
1862
+ template(i + 1);
1863
+ }
1864
+ else {
1865
+ if (depth > 0)
1866
+ depth--;
1867
+ i++;
1868
+ }
1869
+ }
1870
+ else
1871
+ i++;
1872
+ }
1873
+ return out.join("");
1874
+ }
1875
+ /**
1876
+ * The quick fix for server-script-unescaped-markup: put `html` before the
1877
+ * template's backtick and import it from @bascik/bascik/html (after the
1878
+ * script's last import, or merged into an existing import from the module).
1879
+ * When the name html is already used in the script's code (a variable, a
1880
+ * parameter, another import), it imports `html as safeHtml` instead, so the
1881
+ * fix never tags with a binding that means something else; when safeHtml is
1882
+ * taken too, or a hole sits where html would throw, it is not offered.
1883
+ */
1884
+ export function buildWrapHtmlEdits(document, diag) {
1885
+ if (diag.code !== "server-script-unescaped-markup")
1886
+ return undefined;
1887
+ const data = diag.data;
1888
+ if (!data || !data.fixable)
1889
+ return undefined;
1890
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
1891
+ if (!plan)
1892
+ return undefined;
1893
+ const backtick = document.positionAt(data.templateStart);
1894
+ return {
1895
+ title: "Wrap template in html`...`",
1896
+ edits: [
1897
+ ...plan.edits,
1898
+ { range: { start: backtick, end: backtick }, newText: plan.local },
1899
+ ],
1900
+ };
1901
+ }
1902
+ /**
1903
+ * The local name to use for `exportName` from @bascik/bascik/html in the
1904
+ * script between `bodyStart` and `bodyEnd`, and the edits that import it:
1905
+ * after the script's last import, or merged into an existing import from
1906
+ * the module. When the name is already used in the script's code (a
1907
+ * variable, a parameter, another import), it imports `exportName as alias`
1908
+ * instead, so the edit never uses a binding that means something else;
1909
+ * when the alias is taken too, there is no plan. With `onlyAsTagOrCall`, an
1910
+ * existing import of the name counts only when the name is never shadowed.
1911
+ */
1912
+ function planHtmlImport(document, bodyStart, bodyEnd, exportName, alias, onlyAsTagOrCall) {
1913
+ const text = document.getText();
1914
+ const body = text.slice(bodyStart, bodyEnd);
1915
+ const at = (offset) => document.positionAt(bodyStart + offset);
1916
+ const edits = [];
1917
+ const existing = /\bimport\s*\{([^}]*)\}\s*from\s*["']@bascik\/bascik\/html["']/.exec(body);
1918
+ // Identifiers in code only: strings, comments and template text blanked,
1919
+ // and the import from the module left out, so `<html>` or "html" is no
1920
+ // clash but a parameter, a variable or another import named html is.
1921
+ const code = codeOnly(existing
1922
+ ? body.slice(0, existing.index) +
1923
+ " ".repeat(existing[0].length) +
1924
+ body.slice((existing.index ?? 0) + existing[0].length)
1925
+ : body);
1926
+ const word = (name) => `(?<![\\w$.])${escapeRegExp(name)}(?![\\w$])`;
1927
+ const uses = (name) => new RegExp(word(name)).test(code);
1928
+ // An imported name is safe to tag with when it is only ever a tag or a
1929
+ // callee: anywhere else (a parameter, a variable, a function declaration)
1930
+ // it may be shadowed.
1931
+ const onlyTagOrCall = (name) => !new RegExp(`(?<!\\bfunction\\s*)${word(name)}(?!\\s*[\`(])`).test(code) &&
1932
+ !new RegExp(`\\bfunction\\s*${word(name)}`).test(code);
1933
+ let local;
1934
+ let specifier;
1935
+ const entries = existing
1936
+ ? existing[1]
1937
+ .split(",")
1938
+ .map((e) => e.trim())
1939
+ .filter(Boolean)
1940
+ : [];
1941
+ // Names that are not identifiers (a half-typed `html as h(`) bind nothing.
1942
+ const bound = entries
1943
+ .map(parseImportSpecifier)
1944
+ .filter((parts) => parts?.[0] === exportName)
1945
+ .map((parts) => parts[1]);
1946
+ local = bound.find((name) => !onlyAsTagOrCall || onlyTagOrCall(name));
1947
+ if (local === undefined) {
1948
+ if (!bound.includes(exportName) && !uses(exportName)) {
1949
+ local = exportName;
1950
+ specifier = exportName;
1951
+ }
1952
+ else if (!bound.includes(alias) && !uses(alias)) {
1953
+ local = alias;
1954
+ specifier = `${exportName} as ${alias}`;
1955
+ }
1956
+ else
1957
+ return undefined;
1958
+ }
1959
+ if (specifier !== undefined && existing) {
1960
+ const open = (existing.index ?? 0) + existing[0].indexOf("{") + 1;
1961
+ const close = open + existing[1].length;
1962
+ edits.push({
1963
+ range: { start: at(open), end: at(close) },
1964
+ newText: ` ${[...entries, specifier].join(", ")} `,
1965
+ });
1966
+ }
1967
+ else if (specifier !== undefined) {
1968
+ const statement = `import { ${specifier} } from "@bascik/bascik/html";`;
1969
+ const imports = [
1970
+ ...body.matchAll(/^([ \t]*)import\b[^;]*?from\s*["'][^"']+["'][ \t]*;?[ \t]*$/gm),
1971
+ ];
1972
+ const last = imports[imports.length - 1];
1973
+ if (last) {
1974
+ const end = (last.index ?? 0) + last[0].length;
1975
+ edits.push({
1976
+ range: { start: at(end), end: at(end) },
1977
+ newText: `\n${last[1]}${statement}`,
1978
+ });
1979
+ }
1980
+ else {
1981
+ const first = /^([ \t]*)\S/m.exec(body);
1982
+ const lineStart = first?.index ?? 0;
1983
+ edits.push({
1984
+ range: { start: at(lineStart), end: at(lineStart) },
1985
+ newText: `${first?.[1] ?? ""}${statement}\n`,
1986
+ });
1987
+ }
1988
+ }
1989
+ return { local, edits };
1990
+ }
1991
+ /**
1992
+ * The code actions for hand-written-html-escaper. A one-return escaper with
1993
+ * one plain parameter gets "Make NAME() call esc()": its body becomes a call
1994
+ * to esc() from @bascik/bascik/html (imported, aliased when the name esc is
1995
+ * taken, as it is when the escaper itself is called esc). The callers keep
1996
+ * working: esc() escapes the same characters and quotes as well. Rewriting
1997
+ * the callers to html`...` is not automatic, since a template's value then
1998
+ * changes from a string to an html value. Every other escaper (a lookup
1999
+ * object, a longer body) gets "Import html from @bascik/bascik/html" when
2000
+ * the script does not import it yet, as a start on rewriting by hand.
2001
+ */
2002
+ export function buildEscaperActions(document, diag) {
2003
+ if (diag.code !== HAND_WRITTEN_ESCAPER_RULE)
2004
+ return [];
2005
+ const data = diag.data;
2006
+ if (!data)
2007
+ return [];
2008
+ const name = document.getText(diag.range);
2009
+ if (data.delegate) {
2010
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "esc", "escapeValue", true);
2011
+ if (plan) {
2012
+ const { start, end, param, block } = data.delegate;
2013
+ const startPos = document.positionAt(start);
2014
+ const lineStart = document.offsetAt({
2015
+ line: startPos.line,
2016
+ character: 0,
2017
+ });
2018
+ const indent = /^[ \t]*/.exec(document.getText().slice(lineStart, start))?.[0] ?? "";
2019
+ const call = `${plan.local}(${param})`;
2020
+ return [
2021
+ {
2022
+ title: name === "default"
2023
+ ? "Make the default export call esc() from @bascik/bascik/html"
2024
+ : `Make ${name}() call esc() from @bascik/bascik/html`,
2025
+ preferred: true,
2026
+ edits: [
2027
+ ...plan.edits,
2028
+ {
2029
+ range: { start: startPos, end: document.positionAt(end) },
2030
+ newText: block
2031
+ ? `{\n${indent} return ${call};\n${indent}}`
2032
+ : call,
2033
+ },
2034
+ ],
2035
+ },
2036
+ ];
2037
+ }
2038
+ }
2039
+ const body = document.getText().slice(data.bodyStart, data.bodyEnd);
2040
+ if (/\bimport\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s*["']@bascik\/bascik\/html["']/.test(body))
2041
+ return [];
2042
+ const plan = planHtmlImport(document, data.bodyStart, data.bodyEnd, "html", "safeHtml", true);
2043
+ if (!plan || plan.edits.length === 0)
2044
+ return [];
2045
+ return [
2046
+ {
2047
+ title: "Import html from @bascik/bascik/html to build markup safely",
2048
+ preferred: false,
2049
+ edits: plan.edits,
2050
+ },
2051
+ ];
2052
+ }
1500
2053
  export function createCodeActions(document, range, diagnostics, snapshot, fsPath) {
1501
2054
  const activeDiagnostics = diagnostics.length > 0
1502
2055
  ? diagnostics
@@ -1507,6 +2060,33 @@ export function createCodeActions(document, range, diagnostics, snapshot, fsPath
1507
2060
  for (const diag of activeDiagnostics) {
1508
2061
  if (!rangesOverlap(diag.range, range))
1509
2062
  continue;
2063
+ // Editor only: wrapping changes the value from a string to SafeHtml, so
2064
+ // `bascik --check --fix` (applyAutoFixes) never applies it.
2065
+ const escaperActions = buildEscaperActions(document, diag);
2066
+ if (escaperActions.length > 0) {
2067
+ for (const action of escaperActions)
2068
+ actions.push({
2069
+ title: action.title,
2070
+ kind: CodeActionKind.QuickFix,
2071
+ diagnostics: [diag],
2072
+ isPreferred: action.preferred,
2073
+ edit: { changes: { [document.uri]: action.edits } },
2074
+ });
2075
+ continue;
2076
+ }
2077
+ const wrap = buildWrapHtmlEdits(document, diag);
2078
+ if (wrap) {
2079
+ if (actions.some((a) => a.title === wrap.title && sameEdits(a, wrap)))
2080
+ continue;
2081
+ actions.push({
2082
+ title: wrap.title,
2083
+ kind: CodeActionKind.QuickFix,
2084
+ diagnostics: [diag],
2085
+ isPreferred: true,
2086
+ edit: { changes: { [document.uri]: wrap.edits } },
2087
+ });
2088
+ continue;
2089
+ }
1510
2090
  const fix = buildAutoFixEdit(document, diag);
1511
2091
  if (!fix)
1512
2092
  continue;