@orkestrel/guide 0.0.24 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import { arrayOf, isArray, isEmptyString, isError, isFiniteNumber, isFunction, isInstance, isNonEmptyArray, isNonEmptyString, isObject, isRecord, isString, literalOf, parseEnum, parseJSONAs, recordOf, unionOf } from "@orkestrel/contract";
1
+ import { isArray, isError, isFiniteNumber, isFunction, isInstance, isNonEmptyString, isObject, isRecord, isString, parseEnum, parseJSONAs } from "@orkestrel/contract";
2
2
  import { resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { globSync, writeFileSync } from "node:fs";
5
5
  import process from "node:process";
6
- import { coalesceText, createMarkdown, flattenText, isBlockquoteNode, isCodeBlockNode, isCodeSpanNode, isEmphasisNode, isHeadingNode, isImageNode, isLinkNode, isParagraphNode, isTableNode, renderMarkdown, walkNodes } from "@orkestrel/markdown";
7
- //#region src/server/constants.ts
6
+ import { Parity, parseManifest } from "../core/index.js";
7
+ // src/server/constants.ts
8
8
  /** Names the workspace-relative guide concept index. */
9
9
  var GUIDE_INDEX = "guides/README.md";
10
10
  /** Names the package manifest read for native pitch selection. */
@@ -13,8 +13,7 @@ var GUIDE_MANIFEST = "package.json";
13
13
  var GUIDE_README = "README.md";
14
14
  /** Holds the native command usage text written for unsupported arguments. */
15
15
  var GUIDE_USAGE = "usage: npm run test:guides [-- --to guide|--to source]";
16
- //#endregion
17
- //#region src/server/helpers.ts
16
+ // src/server/helpers.ts
18
17
  /**
19
18
  * Formats one finding with its guide prefix when needed.
20
19
  *
@@ -87,8 +86,7 @@ function selectGuidePitch(entries, name) {
87
86
  const spec = `guides/${name}.md`;
88
87
  return entries.some((entry) => entry.spec === spec) ? spec : void 0;
89
88
  }
90
- //#endregion
91
- //#region src/server/parsers.ts
89
+ // src/server/parsers.ts
92
90
  /**
93
91
  * Maps the supported `--to guide` and `--to source` arguments to an explicit rewrite destination.
94
92
  *
@@ -122,3591 +120,7 @@ function parsePackageName(manifest) {
122
120
  if (!isNonEmptyString(name)) return void 0;
123
121
  return name.slice(name.lastIndexOf("/") + 1);
124
122
  }
125
- //#endregion
126
- //#region src/core/constants.ts
127
- /**
128
- * Lists the declaration keywords a documented or exported symbol carries, in the order the
129
- * reflection grammar names them — the frozen population `ExportKeyword`, `isExportKeyword`, and
130
- * `surfaceSymbolShape` all derive from.
131
- *
132
- * @remarks
133
- * One frozen list feeds the type, the guard, and the shape, so a keyword cannot be admitted by one
134
- * and refused by another. Comment and template payload is excluded before reflection, and `enum`
135
- * is outside this population rather than forbidden by general package policy.
136
- */
137
- var EXPORT_KEYWORDS = Object.freeze([
138
- "type",
139
- "interface",
140
- "const",
141
- "function",
142
- "class"
143
- ]);
144
- /**
145
- * Lists the compared sites a {@link Drift} can describe.
146
- */
147
- var DRIFT_CATEGORIES = Object.freeze(["summary", "example"]);
148
- /**
149
- * Names the `## Surface` heading text a guide's documented exports section is keyed on.
150
- */
151
- var SURFACE = "Surface";
152
- /**
153
- * Names the `## Methods` heading text a guide's documented interface-methods section is keyed on.
154
- */
155
- var METHODS = "Methods";
156
- /**
157
- * Names the `## Tests` heading text a guide's documented test-link section is keyed on.
158
- */
159
- var TESTS = "Tests";
160
- /**
161
- * Names the header text of the column a `## Surface` table's declaration keyword is read from.
162
- */
163
- var KIND = "Kind";
164
- /**
165
- * Names the header text of the column a `## Surface` or `## Methods` table's compared
166
- * description paragraph is read from.
167
- */
168
- var SUMMARY = "Summary";
169
- /**
170
- * Names the `## By concept` heading text the manifest's run-map table is keyed on.
171
- */
172
- var MANIFEST = "By concept";
173
- /**
174
- * Lists the link `href` schemes a guides-parity link check skips as external — a link
175
- * with one of these prefixes (or a bare `#` anchor, handled separately in
176
- * `isExternalLink`) is never resolved against the filesystem.
177
- */
178
- var EXTERNAL_SCHEMES = Object.freeze([
179
- "http:",
180
- "https:",
181
- "mailto:",
182
- "tel:"
183
- ]);
184
- //#endregion
185
- //#region src/core/validators.ts
186
- /**
187
- * Checks whether `value` is one of the documented {@link ExportKeyword}
188
- * literals — the guard behind extracting a Surface table's `Kind` cell into a
189
- * typed symbol.
190
- *
191
- * @param value - The candidate value
192
- * @returns True if `value` is a valid {@link ExportKeyword}; false otherwise
193
- *
194
- * @example
195
- * ```ts
196
- * isExportKeyword('class') // true
197
- * isExportKeyword('enum') // false
198
- * ```
199
- */
200
- var isExportKeyword = literalOf(EXPORT_KEYWORDS);
201
- /** Checks whether `value` names a supported drift category. */
202
- var isDriftCategory = literalOf(DRIFT_CATEGORIES);
203
- recordOf({
204
- name: isString,
205
- keyword: isExportKeyword,
206
- summary: isString
207
- }, ["summary"]);
208
- /**
209
- * Checks whether `value` is a well-formed {@link MethodEntry} — a `name` string with an
210
- * optional `summary`.
211
- *
212
- * @param value - The value to test
213
- * @returns True if `value` is a well-formed {@link MethodEntry}; false otherwise
214
- *
215
- * @example
216
- * ```ts
217
- * isMethodEntry({ name: 'walk' }) // true
218
- * isMethodEntry({ name: 1 }) // false
219
- * ```
220
- */
221
- var isMethodEntry = recordOf({
222
- name: isString,
223
- summary: isString
224
- }, ["summary"]);
225
- recordOf({
226
- name: isString,
227
- title: isString,
228
- code: isString,
229
- language: isString
230
- }, ["title", "language"]);
231
- recordOf({
232
- key: isString,
233
- category: isDriftCategory,
234
- guide: isString,
235
- source: isString
236
- }, ["guide", "source"]);
237
- recordOf({
238
- interface: isString,
239
- methods: arrayOf(isMethodEntry)
240
- });
241
- recordOf({
242
- concept: isString,
243
- spec: isString,
244
- source: unionOf(isString, arrayOf(isString)),
245
- tests: isString
246
- });
247
- //#endregion
248
- //#region src/core/helpers.ts
249
- /**
250
- * Extracts aligned physical source-line records in one character traversal.
251
- * Real line and block comments and complete template tokens become spaces in
252
- * {@link SourceLine.code}, while ordinary code, quoted strings, and recognized
253
- * regex literals retain their columns. Genuine JSDoc opened from reflection
254
- * code is retained span by span at its exact physical column in
255
- * {@link SourceLine.jsdoc}; faux openers in comments and templates are
256
- * excluded. Membership remains each consumer's separate anchored grammar.
257
- *
258
- * @remarks
259
- * Regex recognition is a bounded lexical goal rather than TypeScript parser
260
- * grammar. Literal ECMAScript Unicode identifiers participate in slash-state
261
- * recognition, including private identifiers, without decoding escaped
262
- * identifier spellings. Slash after bare `}` is division, and a post-brace
263
- * regex statement requires an explicit `;`. General semicolonless
264
- * declaration/ASI classification is outside this finite projector, so callers
265
- * place an explicit `;` before a slash-leading statement after such a
266
- * declaration.
267
- *
268
- * @param source - The TypeScript source text to project
269
- * @returns One aligned terminator-free record per LF or CRLF physical line, including the final line
270
- *
271
- * @example Project source into physical code lines
272
- * ```ts
273
- * import { extractSourceLines } from '@orkestrel/guide'
274
- *
275
- * extractSourceLines('export const visible = true // note\n')
276
- * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }]
277
- * // … one record per remaining line
278
- * ```
279
- */
280
- function extractSourceLines(source) {
281
- const lines = [];
282
- let characters = [];
283
- let jsdocCharacters = [];
284
- const identifier = /#?[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*/uy;
285
- const templates = [];
286
- const parentheses = [];
287
- let start = 0;
288
- let mode = "code";
289
- let escaped = false;
290
- let regexClass = false;
291
- let operandExpected = true;
292
- let memberExpected = false;
293
- let pendingRole;
294
- let restricted;
295
- let separated = false;
296
- let blockTemplate = false;
297
- let lineTemplate = false;
298
- let jsdoc = false;
299
- let jsdocPresent = false;
300
- for (let offset = 0; offset < source.length; offset += 1) {
301
- const character = source[offset];
302
- if (character === void 0) continue;
303
- const next = source[offset + 1];
304
- const crlf = character === "\r" && next === "\n";
305
- if (character === "\n" || crlf) {
306
- const code = characters.join("");
307
- const present = jsdocPresent || jsdoc;
308
- lines.push({
309
- source: source.slice(start, offset),
310
- code,
311
- jsdoc: present ? jsdocCharacters.join("").padEnd(code.length, " ") : void 0
312
- });
313
- characters = [];
314
- jsdocCharacters = [];
315
- jsdocPresent = jsdoc;
316
- if (mode !== "template") separated = true;
317
- if (restricted !== void 0) {
318
- operandExpected = true;
319
- memberExpected = false;
320
- pendingRole = void 0;
321
- restricted = void 0;
322
- }
323
- if (crlf) offset += 1;
324
- start = offset + 1;
325
- if (mode === "line") mode = lineTemplate ? "templateCode" : "code";
326
- else if (mode === "regex") {
327
- mode = "code";
328
- operandExpected = true;
329
- regexClass = false;
330
- } else if (mode === "templateLine" || mode === "templateRegex") {
331
- mode = "templateCode";
332
- operandExpected = true;
333
- regexClass = false;
334
- } else if (mode === "single" || mode === "double") {
335
- if (!escaped) {
336
- mode = "code";
337
- operandExpected = true;
338
- }
339
- } else if (mode === "templateSingle" || mode === "templateDouble") {
340
- if (!escaped) {
341
- mode = "templateCode";
342
- operandExpected = true;
343
- }
344
- }
345
- escaped = false;
346
- continue;
347
- }
348
- if (mode === "line" || mode === "templateLine") {
349
- characters.push(" ");
350
- continue;
351
- }
352
- if (mode === "block" || mode === "templateBlock") {
353
- characters.push(" ");
354
- if (jsdoc) jsdocCharacters.push(character);
355
- if (character === "*" && next === "/") {
356
- characters.push(" ");
357
- if (jsdoc) {
358
- jsdocCharacters.push("/");
359
- jsdoc = false;
360
- }
361
- offset += 1;
362
- mode = blockTemplate ? "templateCode" : "code";
363
- }
364
- continue;
365
- }
366
- if (mode === "single" || mode === "double") {
367
- characters.push(character);
368
- if (escaped) {
369
- escaped = false;
370
- continue;
371
- }
372
- if (character === "\\") {
373
- escaped = true;
374
- continue;
375
- }
376
- if (mode === "single" && character === "'" || mode === "double" && character === "\"") {
377
- mode = "code";
378
- operandExpected = false;
379
- }
380
- continue;
381
- }
382
- if (mode === "regex") {
383
- characters.push(character);
384
- if (escaped) {
385
- escaped = false;
386
- continue;
387
- }
388
- if (character === "\\") {
389
- escaped = true;
390
- continue;
391
- }
392
- if (character === "[") regexClass = true;
393
- else if (character === "]") regexClass = false;
394
- else if (character === "/" && !regexClass) {
395
- mode = "code";
396
- operandExpected = false;
397
- }
398
- continue;
399
- }
400
- if (mode === "templateSingle" || mode === "templateDouble") {
401
- characters.push(" ");
402
- if (escaped) {
403
- escaped = false;
404
- continue;
405
- }
406
- if (character === "\\") {
407
- escaped = true;
408
- continue;
409
- }
410
- if (mode === "templateSingle" && character === "'" || mode === "templateDouble" && character === "\"") {
411
- mode = "templateCode";
412
- operandExpected = false;
413
- }
414
- continue;
415
- }
416
- if (mode === "templateRegex") {
417
- characters.push(" ");
418
- if (escaped) {
419
- escaped = false;
420
- continue;
421
- }
422
- if (character === "\\") {
423
- escaped = true;
424
- continue;
425
- }
426
- if (character === "[") regexClass = true;
427
- else if (character === "]") regexClass = false;
428
- else if (character === "/" && !regexClass) {
429
- mode = "templateCode";
430
- operandExpected = false;
431
- }
432
- continue;
433
- }
434
- if (mode === "template") {
435
- characters.push(" ");
436
- if (escaped) {
437
- escaped = false;
438
- continue;
439
- }
440
- if (character === "\\") {
441
- escaped = true;
442
- continue;
443
- }
444
- if (character === "$" && next === "{") {
445
- characters.push(" ");
446
- offset += 1;
447
- const index = templates.length - 1;
448
- if (index >= 0) templates[index] = 1;
449
- mode = "templateCode";
450
- operandExpected = true;
451
- memberExpected = false;
452
- pendingRole = void 0;
453
- continue;
454
- }
455
- if (character === "`") {
456
- templates.pop();
457
- mode = templates.length === 0 ? "code" : "templateCode";
458
- operandExpected = false;
459
- }
460
- continue;
461
- }
462
- const templateCode = mode === "templateCode";
463
- if (character === "/" && next === "/") {
464
- characters.push(" ", " ");
465
- offset += 1;
466
- lineTemplate = templateCode;
467
- mode = templateCode ? "templateLine" : "line";
468
- continue;
469
- }
470
- if (character === "/" && next === "*") {
471
- characters.push(" ", " ");
472
- if (!templateCode && source[offset + 2] === "*") {
473
- const column = offset - start;
474
- const width = jsdocCharacters.join("").length;
475
- jsdocCharacters.push(" ".repeat(column - width), "/", "*");
476
- jsdoc = true;
477
- jsdocPresent = true;
478
- }
479
- offset += 1;
480
- blockTemplate = templateCode;
481
- mode = templateCode ? "templateBlock" : "block";
482
- continue;
483
- }
484
- if (character === "'") {
485
- characters.push(templateCode ? " " : character);
486
- mode = templateCode ? "templateSingle" : "single";
487
- escaped = false;
488
- separated = false;
489
- restricted = void 0;
490
- continue;
491
- }
492
- if (character === "\"") {
493
- characters.push(templateCode ? " " : character);
494
- mode = templateCode ? "templateDouble" : "double";
495
- escaped = false;
496
- separated = false;
497
- restricted = void 0;
498
- continue;
499
- }
500
- if (character === "`") {
501
- characters.push(" ");
502
- templates.push(0);
503
- mode = "template";
504
- escaped = false;
505
- separated = false;
506
- restricted = void 0;
507
- continue;
508
- }
509
- const visible = templateCode ? " " : character;
510
- if (character === "/" && next === "=" && !operandExpected) {
511
- characters.push(visible, templateCode ? " " : "=");
512
- offset += 1;
513
- operandExpected = true;
514
- memberExpected = false;
515
- pendingRole = void 0;
516
- separated = false;
517
- restricted = void 0;
518
- continue;
519
- }
520
- if (character === "/") {
521
- characters.push(visible);
522
- if (operandExpected) {
523
- mode = templateCode ? "templateRegex" : "regex";
524
- escaped = false;
525
- regexClass = false;
526
- } else {
527
- operandExpected = true;
528
- memberExpected = false;
529
- pendingRole = void 0;
530
- }
531
- separated = false;
532
- restricted = void 0;
533
- continue;
534
- }
535
- identifier.lastIndex = offset;
536
- const identifierMatch = identifier.exec(source);
537
- if (identifierMatch !== null) {
538
- const token = identifierMatch[0];
539
- characters.push(templateCode ? " ".repeat(token.length) : token);
540
- if (token.startsWith("#")) {
541
- operandExpected = false;
542
- memberExpected = false;
543
- pendingRole = void 0;
544
- restricted = void 0;
545
- separated = false;
546
- offset += token.length - 1;
547
- continue;
548
- }
549
- const frame = parentheses[parentheses.length - 1];
550
- const label = restricted === "label";
551
- restricted = void 0;
552
- separated = false;
553
- if (memberExpected) {
554
- memberExpected = false;
555
- operandExpected = false;
556
- pendingRole = void 0;
557
- } else if (label) {
558
- operandExpected = false;
559
- pendingRole = void 0;
560
- restricted = "complete";
561
- } else if (/^(?:if|while|with)$/.test(token)) {
562
- pendingRole = "statement";
563
- operandExpected = true;
564
- } else if (token === "for") {
565
- pendingRole = "for";
566
- operandExpected = true;
567
- } else if (token === "export") {
568
- pendingRole = "export";
569
- operandExpected = true;
570
- } else if (token === "default" && pendingRole === "export") {
571
- pendingRole = void 0;
572
- operandExpected = true;
573
- } else if (/^(?:switch|catch)$/.test(token)) {
574
- pendingRole = "block";
575
- operandExpected = true;
576
- } else if (token === "await" && pendingRole === "for") operandExpected = true;
577
- else if (/^(?:return|throw|case|delete|void|typeof|new|await|yield|else|do|extends)$/.test(token)) {
578
- pendingRole = void 0;
579
- operandExpected = true;
580
- } else if (/^(?:in|instanceof)$/.test(token)) {
581
- pendingRole = void 0;
582
- operandExpected = true;
583
- } else if (/^(?:break|continue)$/.test(token)) {
584
- pendingRole = void 0;
585
- operandExpected = false;
586
- restricted = "label";
587
- } else if (token === "debugger") {
588
- pendingRole = void 0;
589
- operandExpected = false;
590
- restricted = "complete";
591
- } else if (token === "of" && frame?.role === "for" && frame.phase === "left" && !frame.binding && !operandExpected) {
592
- frame.phase = "right";
593
- operandExpected = true;
594
- pendingRole = void 0;
595
- } else if (/^(?:const|let|var)$/.test(token) && frame?.role === "for" && frame.phase === "left") {
596
- frame.binding = true;
597
- operandExpected = true;
598
- pendingRole = void 0;
599
- } else {
600
- if (frame?.binding === true) frame.binding = false;
601
- operandExpected = false;
602
- pendingRole = void 0;
603
- }
604
- offset += token.length - 1;
605
- continue;
606
- }
607
- if (/[0-9]/.test(character)) {
608
- let end = offset + 1;
609
- while (end < source.length) {
610
- const part = source[end];
611
- if (part === void 0 || !/[A-Za-z0-9_$.]/.test(part)) break;
612
- end += 1;
613
- }
614
- const token = source.slice(offset, end);
615
- characters.push(templateCode ? " ".repeat(token.length) : token);
616
- operandExpected = false;
617
- memberExpected = false;
618
- pendingRole = void 0;
619
- restricted = void 0;
620
- separated = false;
621
- offset = end - 1;
622
- continue;
623
- }
624
- if (character === "!" && next === "=" && source[offset + 2] === "=" || character === "=" && next === "=" && source[offset + 2] === "=") {
625
- characters.push(visible, templateCode ? " " : source.slice(offset + 1, offset + 3));
626
- offset += 2;
627
- operandExpected = true;
628
- memberExpected = false;
629
- pendingRole = void 0;
630
- restricted = void 0;
631
- separated = false;
632
- continue;
633
- }
634
- if ((character === "!" || character === "=") && next === "=") {
635
- characters.push(visible, templateCode ? " " : "=");
636
- offset += 1;
637
- operandExpected = true;
638
- memberExpected = false;
639
- pendingRole = void 0;
640
- restricted = void 0;
641
- separated = false;
642
- continue;
643
- }
644
- if (character === "+" && next === "+" || character === "-" && next === "-") {
645
- characters.push(visible, templateCode ? " " : next);
646
- offset += 1;
647
- if (separated) operandExpected = true;
648
- memberExpected = false;
649
- pendingRole = void 0;
650
- restricted = void 0;
651
- separated = false;
652
- continue;
653
- }
654
- if (character === "." && next === "." && source[offset + 2] === ".") {
655
- characters.push(visible, templateCode ? " " : "..");
656
- offset += 2;
657
- operandExpected = true;
658
- memberExpected = false;
659
- pendingRole = void 0;
660
- restricted = void 0;
661
- separated = false;
662
- continue;
663
- }
664
- if (character === "?" && next === ".") {
665
- characters.push(visible, templateCode ? " " : ".");
666
- offset += 1;
667
- operandExpected = false;
668
- memberExpected = true;
669
- pendingRole = void 0;
670
- restricted = void 0;
671
- separated = false;
672
- continue;
673
- }
674
- characters.push(visible);
675
- if (/\s/.test(character)) continue;
676
- separated = false;
677
- restricted = void 0;
678
- if (character === "(") {
679
- parentheses.push({
680
- role: pendingRole ?? "plain",
681
- phase: "left",
682
- binding: false
683
- });
684
- operandExpected = true;
685
- memberExpected = false;
686
- pendingRole = void 0;
687
- continue;
688
- }
689
- if (character === ")") {
690
- const frame = parentheses.pop();
691
- operandExpected = frame?.role === "statement" || frame?.role === "for";
692
- memberExpected = false;
693
- pendingRole = void 0;
694
- continue;
695
- }
696
- if (character === ";") {
697
- const frame = parentheses[parentheses.length - 1];
698
- if (frame?.role === "for" && frame.phase === "left") frame.phase = "classic";
699
- operandExpected = true;
700
- memberExpected = false;
701
- pendingRole = void 0;
702
- continue;
703
- }
704
- if (character === ".") {
705
- operandExpected = false;
706
- memberExpected = true;
707
- pendingRole = void 0;
708
- continue;
709
- }
710
- if (character === "]" || character === "}") {
711
- const frame = parentheses[parentheses.length - 1];
712
- if (frame?.role === "for" && frame.phase === "left" && frame.binding) frame.binding = false;
713
- }
714
- if (character === "]") operandExpected = false;
715
- else if (character === "}") {
716
- const index = templates.length - 1;
717
- const depth = templates[index];
718
- if (templateCode && index >= 0 && depth !== void 0) {
719
- templates[index] = depth - 1;
720
- if (depth === 1) mode = "template";
721
- }
722
- operandExpected = false;
723
- } else if (character === "{") {
724
- const index = templates.length - 1;
725
- const depth = templates[index];
726
- if (templateCode && index >= 0 && depth !== void 0) templates[index] = depth + 1;
727
- operandExpected = true;
728
- } else if (character !== "!") operandExpected = true;
729
- memberExpected = false;
730
- pendingRole = void 0;
731
- }
732
- const code = characters.join("");
733
- const present = jsdocPresent || jsdoc;
734
- lines.push({
735
- source: source.slice(start),
736
- code,
737
- jsdoc: present ? jsdocCharacters.join("").padEnd(code.length, " ") : void 0
738
- });
739
- return lines;
740
- }
741
- /**
742
- * Checks whether an opaque inventory key contains only canonical slash-separated
743
- * segments. Empty, `.` and `..` segments are rejected without rewriting the
744
- * key; ordinary dotfile segments remain valid.
745
- *
746
- * @param key - The opaque inventory key to inspect
747
- * @returns True if every segment is canonical; false otherwise
748
- *
749
- * @example
750
- * ```ts
751
- * hasCanonicalSegments('src/.hidden.ts') // true
752
- * hasCanonicalSegments('src/../alias.ts') // false
753
- * ```
754
- */
755
- function hasCanonicalSegments(key) {
756
- return key.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
757
- }
758
- /**
759
- * Normalizes a module scope to its canonical directory list. `'.'` represents
760
- * workspace root; empty, trailing, and dot-segment spellings reduce through
761
- * {@link resolvePath}, and duplicates are removed in first-seen order.
762
- *
763
- * @param module - The module scope to normalize
764
- * @returns The directory list `module` denotes
765
- *
766
- * @example
767
- * ```ts
768
- * normalizeDirectories('src/core') // ['src/core']
769
- * normalizeDirectories(['src/core', 'src/browser']) // ['src/core', 'src/browser']
770
- * ```
771
- */
772
- function normalizeDirectories(module) {
773
- const directories = [];
774
- const seen = /* @__PURE__ */ new Set();
775
- for (const value of isString(module) ? [module] : module) {
776
- const directory = resolvePath(".", value);
777
- if (seen.has(directory)) continue;
778
- seen.add(directory);
779
- directories.push(directory);
780
- }
781
- return directories;
782
- }
783
- /**
784
- * Computes the stable cache key for a {@link GuideModule}. Directories normalize before
785
- * joining, so equivalent module spellings share one key. The NUL separator
786
- * cannot occur in filesystem-backed canonical-segment inventory keys, so no
787
- * directory boundary can collide with directory text.
788
- *
789
- * @param module - The module scope to key
790
- * @returns The normalized directories joined by NUL
791
- *
792
- * @example
793
- * ```ts
794
- * computeModuleKey(['src/core', 'src/browser']) // 'src/core\0src/browser'
795
- * ```
796
- */
797
- function computeModuleKey(module) {
798
- return normalizeDirectories(module).join("\0");
799
- }
800
- /**
801
- * Selects the exact opaque file-inventory keys belonging under any canonical
802
- * {@link GuideModule} directory, sorted. `'.'` selects canonical root-relative
803
- * keys without accepting `/`, `./`, or `../` aliases. Every selected exact
804
- * `index.ts` and every `.test.ts` key is excluded independent of scope order.
805
- *
806
- * @param files - The workspace file inventory, root-relative path → file text
807
- * @param module - The module scope to filter to
808
- * @returns The scope's file keys, root-relative and sorted
809
- *
810
- * @example
811
- * ```ts
812
- * selectModuleKeys({ 'src/core/Guide.ts': '', 'src/core/index.ts': '' }, 'src/core') // ['src/core/Guide.ts']
813
- * ```
814
- */
815
- function selectModuleKeys(files, module) {
816
- const dirs = normalizeDirectories(module);
817
- const indexes = new Set(dirs.map((directory) => resolvePath(directory, "index.ts")));
818
- const keys = [];
819
- for (const key of Object.keys(files)) {
820
- if (!hasCanonicalSegments(key)) continue;
821
- if (!key.endsWith(".ts")) continue;
822
- if (key.endsWith(".test.ts")) continue;
823
- if (!dirs.some((directory) => directory === "." || key.startsWith(`${directory}/`)) || indexes.has(key)) continue;
824
- keys.push(key);
825
- }
826
- return keys.sort();
827
- }
828
- /**
829
- * Computes the bijection key for a surface symbol — `${keyword} ${name}` — so a symbol-set
830
- * comparison diffs (name, keyword) pairs rather than names alone.
831
- *
832
- * @param symbol - The symbol to key
833
- * @returns The `${keyword} ${name}` key
834
- *
835
- * @example
836
- * ```ts
837
- * computeSymbolKey({ name: 'Markdown', keyword: 'class' }) // 'class Markdown'
838
- * ```
839
- */
840
- function computeSymbolKey(symbol) {
841
- return `${symbol.keyword} ${symbol.name}`;
842
- }
843
- /**
844
- * Finds the names present in `names` but absent from `source` — the set-difference
845
- * behind a both-directions bijection assertion.
846
- *
847
- * @param names - The candidate names
848
- * @param source - The names to compare against
849
- * @returns The names in `names` that are not in `source`
850
- *
851
- * @example
852
- * ```ts
853
- * findMissing(['a', 'b'], ['a']) // ['b']
854
- * ```
855
- */
856
- function findMissing(names, source) {
857
- const existing = new Set(source);
858
- return names.filter((name) => !existing.has(name));
859
- }
860
- /**
861
- * Finds the fences whose language is absent from the caller's listed languages.
862
- * Untagged fences are always returned because they have no language to list.
863
- *
864
- * @param fences - The guide fences to check
865
- * @param languages - The listed language tags
866
- * @returns The unlisted fences in input order
867
- *
868
- * @example
869
- * ```ts
870
- * findUnlisted([{ language: 'typescript', code: 'walk()' }], ['ts'])
871
- * // [{ language: 'typescript', code: 'walk()' }]
872
- * ```
873
- */
874
- function findUnlisted(fences, languages) {
875
- const listed = new Set(languages);
876
- return fences.filter((fence) => fence.language === void 0 || !listed.has(fence.language));
877
- }
878
- /**
879
- * Finds the symbol-key set-difference between two symbol lists — `symbols` present but
880
- * absent from `source`, compared by {@link computeSymbolKey} so a symbol can drift in
881
- * neither name nor keyword.
882
- *
883
- * @param symbols - The candidate symbols
884
- * @param source - The symbols to compare against
885
- * @returns The symbol keys in `symbols` that are not in `source`
886
- *
887
- * @example
888
- * ```ts
889
- * findMissingSymbols([{ name: 'X', keyword: 'class' }], []) // ['class X']
890
- * ```
891
- */
892
- function findMissingSymbols(symbols, source) {
893
- return findMissing(symbols.map(computeSymbolKey), source.map(computeSymbolKey));
894
- }
895
- /**
896
- * Checks whether a source declares at least one behavioural member — a `class` or `interface`
897
- * in its surface that carries a call-signature member — so a guide owes a `## Methods` group only
898
- * where the source has one to document.
899
- *
900
- * @param source - The reflected source under parity
901
- * @returns True if a surface `class` or `interface` declares a member; false otherwise
902
- *
903
- * @example
904
- * ```ts
905
- * hasBehaviouralSurface(createSource({ files: { 'src/types.ts': 'export interface Widget { render(): void }' }, module: 'src' })) // true
906
- * hasBehaviouralSurface(createSource({ files: { 'src/constants.ts': 'export const NAMES = Object.freeze({})' }, module: 'src' })) // false
907
- * ```
908
- */
909
- function hasBehaviouralSurface(source) {
910
- return source.surface().some((symbol) => (symbol.keyword === "class" || symbol.keyword === "interface") && source.methods(symbol.name).length > 0);
911
- }
912
- /**
913
- * Finds the names in `names` that have no example — a fence containing the name at a
914
- * word boundary in `fences`, or a membership in `examples`, both count as
915
- * "has an example"; presence-only, fence and JSDoc content are never checked.
916
- *
917
- * @param names - The candidate symbol/member names to check
918
- * @param fences - The guide's ```ts Patterns fence bodies to search
919
- * @param examples - The names already known to carry an `@example` JSDoc block
920
- * @returns The names in `names` with no fence mention and no `@example`
921
- *
922
- * @example
923
- * ```ts
924
- * findUnexampled(['walk', 'fold'], ['walk()'], []) // ['fold']
925
- * findUnexampled(['walk'], [], ['walk']) // []
926
- * ```
927
- */
928
- function findUnexampled(names, fences, examples) {
929
- const exampled = new Set(examples);
930
- return names.filter((name) => {
931
- if (exampled.has(name)) return false;
932
- const boundary = new RegExp(`\\b${escapeRegExp(name)}\\b`);
933
- return !fences.some((fence) => boundary.test(fence));
934
- });
935
- }
936
- /**
937
- * Parses a fence's brace `import` statements into per-specifier imported identifier names —
938
- * `import type`, mixed multiline braces, and `x as y` aliases all count, each alias resolved to
939
- * the exported name `x` because that is the name the checked barrel surface must hold. Brace
940
- * bindings only: a default, namespace, side-effect, or mixed `import Default, { named }`
941
- * statement is not surfaced.
942
- *
943
- * @param fence - A ```ts Patterns fence's verbatim body text
944
- * @returns One entry per `import ... from 'specifier'` statement, in fence order
945
- *
946
- * @example
947
- * ```ts
948
- * extractFenceImports("import { a, b as c } from 'x'\n") // [{ specifier: 'x', names: ['a', 'b'] }]
949
- * ```
950
- */
951
- function extractFenceImports(fence) {
952
- const results = [];
953
- const pattern = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/gs;
954
- let match;
955
- while ((match = pattern.exec(fence)) !== null) {
956
- const body = match[1];
957
- const specifier = match[2];
958
- if (body === void 0 || specifier === void 0) continue;
959
- const names = body.split(",").map((part) => part.trim()).filter((part) => part.length > 0).map((part) => part.replace(/^type\s+/, "")).map((part) => {
960
- return part.match(/^(\w+)\s+as\s+\w+$/)?.[1] ?? part;
961
- }).filter((part) => /^\w+$/.test(part));
962
- results.push({
963
- specifier,
964
- names
965
- });
966
- }
967
- return results;
968
- }
969
- /**
970
- * Checks whether a guides-parity link check skips a link `href` — an external
971
- * scheme ({@link EXTERNAL_SCHEMES}) or a bare in-document `#` anchor.
972
- *
973
- * @param href - The link destination
974
- * @returns True if a link check leaves the href unresolved against the filesystem; false otherwise
975
- *
976
- * @example
977
- * ```ts
978
- * isExternalLink('https://example.com') // true
979
- * isExternalLink('../helpers.ts') // false
980
- * ```
981
- */
982
- function isExternalLink(href) {
983
- if (href.startsWith("#")) return true;
984
- return EXTERNAL_SCHEMES.some((scheme) => href.startsWith(scheme));
985
- }
986
- /**
987
- * Resolves a relative `target` from a root-relative `directory`, normalizing
988
- * forward-slash dot segments without filesystem or extension inference. A
989
- * parent pops only a retained real component; every excess leading parent is
990
- * preserved.
991
- *
992
- * @param directory - The root-relative directory to resolve from
993
- * @param target - The relative target to resolve
994
- * @returns The normalized path, or `'.'` when no segment remains, retaining every excess parent
995
- *
996
- * @example
997
- * ```ts
998
- * resolvePath('guides/src', '../../src/core/helpers.ts') // 'src/core/helpers.ts'
999
- * resolvePath('.', '../../outside.ts') // '../../outside.ts'
1000
- * ```
1001
- */
1002
- function resolvePath(directory, target) {
1003
- const combined = `${directory}/${target}`;
1004
- const segments = [];
1005
- for (const segment of combined.split("/")) {
1006
- if (segment === "" || segment === ".") continue;
1007
- if (segment === "..") {
1008
- const previous = segments[segments.length - 1];
1009
- if (previous !== void 0 && previous !== "..") segments.pop();
1010
- else segments.push(segment);
1011
- continue;
1012
- }
1013
- segments.push(segment);
1014
- }
1015
- return segments.length === 0 ? "." : segments.join("/");
1016
- }
1017
- /**
1018
- * Resolves a relative `target` from the directory containing a root-relative
1019
- * declaring `file`. A slashless file belongs to the workspace root; path
1020
- * reduction is delegated to {@link resolvePath}.
1021
- *
1022
- * @param file - The root-relative declaring file
1023
- * @param target - The relative link destination to resolve
1024
- * @returns The normalized path, retaining every excess leading parent
1025
- *
1026
- * @example
1027
- * ```ts
1028
- * resolveLink('guides/src/guide.md', '../../src/core/helpers.ts') // 'src/core/helpers.ts'
1029
- * resolveLink('index.ts', './root.ts') // 'root.ts'
1030
- * ```
1031
- */
1032
- function resolveLink(file, target) {
1033
- const index = file.lastIndexOf("/");
1034
- return resolvePath(index < 0 ? "." : file.slice(0, index), target);
1035
- }
1036
- /**
1037
- * Finds the first code-span value by descending an inline node list, following
1038
- * into `emphasis` / `link` / `image` children — the extraction rule behind a
1039
- * Surface or Methods table row's first-column identifier.
1040
- *
1041
- * @param nodes - The inline nodes to search
1042
- * @returns The first code span's literal text, or `undefined` when none is found
1043
- *
1044
- * @example
1045
- * ```ts
1046
- * findFirstCode([{ element: 'codeSpan', value: 'Markdown' }]) // 'Markdown'
1047
- * ```
1048
- */
1049
- function findFirstCode(nodes) {
1050
- for (const node of nodes) {
1051
- if (isCodeSpanNode(node)) return node.value;
1052
- if (isEmphasisNode(node) || isLinkNode(node) || isImageNode(node)) {
1053
- const value = findFirstCode(node.children);
1054
- if (value !== void 0) return value;
1055
- }
1056
- }
1057
- }
1058
- /**
1059
- * Extracts the link hrefs within one table cell's inline content, in walk order.
1060
- *
1061
- * @param cell - The cell's inline nodes
1062
- * @returns The cell's link hrefs, in walk order
1063
- *
1064
- * @example
1065
- * ```ts
1066
- * extractCellLinks([{ element: 'link', href: 'x.ts', children: [] }]) // ['x.ts']
1067
- * ```
1068
- */
1069
- function extractCellLinks(cell) {
1070
- const links = [];
1071
- for (const node of walkNodes({
1072
- element: "paragraph",
1073
- children: cell
1074
- })) if (isLinkNode(node)) links.push(node.href);
1075
- return links;
1076
- }
1077
- /**
1078
- * Returns the identifier prefix of a code-span text — everything before its first `<`,
1079
- * trimmed. Guide cells and headings may annotate a generic-parameterized name
1080
- * (`MarkdownHandler<TNode, T>`) for readability, but the bijection key is the
1081
- * bare identifier the source scanner captures, so both sides must normalize
1082
- * the same way.
1083
- *
1084
- * @param code - A code span's literal text
1085
- * @returns The identifier prefix, or an empty string when `code` is empty
1086
- *
1087
- * @example
1088
- * ```ts
1089
- * normalizeIdentifier('MarkdownHandler<TNode, T>') // 'MarkdownHandler'
1090
- * normalizeIdentifier('fold') // 'fold'
1091
- * ```
1092
- */
1093
- function normalizeIdentifier(code) {
1094
- const index = code.indexOf("<");
1095
- return (index < 0 ? code : code.slice(0, index)).trim();
1096
- }
1097
- /**
1098
- * Extracts compared inline content — the text of a table cell or candidate entity heading
1099
- * flattened with every code span kept as a code span, so `` `Widget` `` reads the same wherever
1100
- * the parity reader compares it. Emphasis drops to its text, a link drops to its text, an image
1101
- * drops to its alternative text, and the markdown parser has already unescaped `\|`.
1102
- *
1103
- * @param cell - The inline nodes to flatten
1104
- * @returns The compared text, code spans included
1105
- *
1106
- * @example
1107
- * ```ts
1108
- * extractCellText([{ element: 'codeSpan', value: 'Widget' }]) // '`Widget`'
1109
- * ```
1110
- */
1111
- function extractCellText(cell) {
1112
- let text = "";
1113
- for (const node of cell) if (isCodeSpanNode(node)) text += `\`${node.value}\``;
1114
- else if (isEmphasisNode(node) || isLinkNode(node) || isImageNode(node)) text += extractCellText(node.children);
1115
- else text += flattenText(node);
1116
- return text;
1117
- }
1118
- /**
1119
- * Builds one table cell's inline content from its compared text — the inverse of
1120
- * {@link extractCellText}. A single-backtick run whose text carries no inner backtick and
1121
- * neither a leading nor a trailing space becomes a code span; every other character, a backtick
1122
- * included, becomes literal text, which `renderMarkdown` escapes so the rendered cell parses back
1123
- * to the text this function was given.
1124
- *
1125
- * @remarks
1126
- * The compared form spells every code span with one backtick per side, because
1127
- * {@link extractCellText} emits `` `${value}` `` whatever delimiter the source used. A run this
1128
- * function refuses is therefore a run no parsed cell produced, and emitting it as text is what
1129
- * keeps the projection total: reading the rendered cell back through {@link extractCellText}
1130
- * returns the text, so a rendered row and a hand-written row compare the same. A code span whose
1131
- * own text carries a backtick or a boundary space is outside the compared form's fidelity in
1132
- * either direction, and this function writes it as text rather than guessing a delimiter.
1133
- *
1134
- * @param text - The cell's compared text, as {@link extractCellText} returns it
1135
- * @returns The cell's inline nodes, in text order
1136
- *
1137
- * @example
1138
- * ```ts
1139
- * buildCell('Holds a `Widget`.')
1140
- * // [{ element: 'text', value: 'Holds a ' }, { element: 'codeSpan', value: 'Widget' }, { element: 'text', value: '.' }]
1141
- * ```
1142
- */
1143
- function buildCell(text) {
1144
- const nodes = [];
1145
- const spans = /`([^`]+)`/g;
1146
- let cursor = 0;
1147
- let span;
1148
- while ((span = spans.exec(text)) !== null) {
1149
- const value = span[1];
1150
- if (value === void 0) continue;
1151
- if (span.index > cursor) nodes.push({
1152
- element: "text",
1153
- value: text.slice(cursor, span.index)
1154
- });
1155
- if (value.trim() === value) nodes.push({
1156
- element: "codeSpan",
1157
- value
1158
- });
1159
- else nodes.push({
1160
- element: "text",
1161
- value: span[0]
1162
- });
1163
- cursor = span.index + span[0].length;
1164
- }
1165
- if (cursor < text.length) nodes.push({
1166
- element: "text",
1167
- value: text.slice(cursor)
1168
- });
1169
- return coalesceText(nodes);
1170
- }
1171
- /**
1172
- * Finds the index of the column whose header text is `header` so a table's columns survive
1173
- * reordering. The match is exact and case-sensitive — a table without that exact header
1174
- * contributes nothing to the projection reading it, so a `## Surface` table with no
1175
- * {@link SUMMARY} column leaves every row's summary absent and {@link findDrift} reports each
1176
- * of those rows, never agreement.
1177
- *
1178
- * @param table - The table to inspect
1179
- * @param header - The exact header text to locate, for example `Kind`
1180
- * @returns The column's index, or `undefined` when the table has no such header
1181
- *
1182
- * @example
1183
- * ```ts
1184
- * findColumnIndex(table, 'Kind') // 1, or undefined
1185
- * ```
1186
- */
1187
- function findColumnIndex(table, header) {
1188
- for (let index = 0; index < table.header.length; index += 1) {
1189
- const cell = table.header[index];
1190
- if (cell !== void 0 && flattenText({
1191
- element: "paragraph",
1192
- children: cell
1193
- }).trim() === header) return index;
1194
- }
1195
- }
1196
- /**
1197
- * Extracts the module-scope exports declared in one file's source text — the declaration keys
1198
- * {@link collectKeys} reports, each split back into the keyword and name that built it, deduped by
1199
- * (keyword, name).
1200
- *
1201
- * @remarks
1202
- * That one grammar matches `export (async)? (function(\*)?|class|const|interface|type) Name`; a
1203
- * generator export (`export function* walk`) keys as the `function` keyword, its trailing `*`
1204
- * stripped before the {@link ExportKeyword} check. Scanning uses {@link extractSourceLines}, so
1205
- * comment and template payload is excluded while its uninterrupted column-zero head remains
1206
- * required; preserved columns do not grant membership to leading/interrupted comment forms. The
1207
- * population is exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is outside
1208
- * this reflection contract, not forbidden by general package policy.
1209
- *
1210
- * @param source - The file's source text
1211
- * @returns The file's exported symbols, in file order
1212
- *
1213
- * @example
1214
- * ```ts
1215
- * extractExports('export class Markdown {}\n') // [{ name: 'Markdown', keyword: 'class' }]
1216
- * extractExports('export function* walk() {}\n') // [{ name: 'walk', keyword: 'function' }]
1217
- * ```
1218
- */
1219
- function extractExports(source) {
1220
- const symbols = [];
1221
- const seen = /* @__PURE__ */ new Set();
1222
- const lines = extractSourceLines(source);
1223
- const summaries = collectSummaries(lines);
1224
- const keys = collectKeys(lines);
1225
- for (const line of lines) {
1226
- const key = keys.get(line);
1227
- if (key === void 0 || seen.has(key)) continue;
1228
- const space = key.indexOf(" ");
1229
- const keyword = key.slice(0, Math.max(space, 0));
1230
- if (!isExportKeyword(keyword)) continue;
1231
- seen.add(key);
1232
- const name = key.slice(space + 1);
1233
- const summary = summaries.get(line);
1234
- symbols.push({
1235
- name,
1236
- keyword,
1237
- ...summary === void 0 ? {} : { summary }
1238
- });
1239
- }
1240
- return symbols;
1241
- }
1242
- /**
1243
- * Extracts the module-scope declarations lacking the `export` keyword in one file's source text —
1244
- * the mirror image of {@link extractExports}'s grammar, anchored the same way (column 0, so an
1245
- * indented inner declaration never matches).
1246
- *
1247
- * @remarks
1248
- * Scans only the {@link ExportKeyword} keywords (`function` / `class` / `const` / `interface` /
1249
- * `type`) — a module-scope `let` or `var` is outside this scanner's declaration-keyword grammar
1250
- * and out of this check's contract. Scanning uses {@link extractSourceLines}, so comment and
1251
- * template payload is excluded while its uninterrupted column-zero head remains required;
1252
- * preserved columns do not widen membership. `enum` is likewise outside this reflection
1253
- * population, not forbidden by general package policy.
1254
- *
1255
- * @param source - The file's source text
1256
- * @returns The file's hidden (non-exported) symbols, in file order
1257
- *
1258
- * @example
1259
- * ```ts
1260
- * extractHidden('function secretHelper() {}\n') // [{ name: 'secretHelper', keyword: 'function' }]
1261
- * extractHidden('export class X {}\n') // []
1262
- * ```
1263
- */
1264
- function extractHidden(source) {
1265
- const symbols = [];
1266
- const seen = /* @__PURE__ */ new Set();
1267
- const lines = extractSourceLines(source);
1268
- const summaries = collectSummaries(lines);
1269
- for (const line of lines) {
1270
- if (line.code.startsWith("export ")) continue;
1271
- const match = line.code.match(/^(?:async )?(function\*?|class|const|interface|type) (\w+)/);
1272
- const rawKeyword = match?.[1];
1273
- const name = match?.[2];
1274
- const keyword = rawKeyword === void 0 ? void 0 : rawKeyword.replace(/\*$/, "");
1275
- if (!isNonEmptyString(keyword) || !isNonEmptyString(name) || !isExportKeyword(keyword)) continue;
1276
- const key = `${keyword} ${name}`;
1277
- if (seen.has(key)) continue;
1278
- seen.add(key);
1279
- const summary = summaries.get(line);
1280
- symbols.push({
1281
- name,
1282
- keyword,
1283
- ...summary === void 0 ? {} : { summary }
1284
- });
1285
- }
1286
- return symbols;
1287
- }
1288
- /**
1289
- * Joins the declaration head starting at `start` into one space-separated
1290
- * line, consuming lines until the first that opens a body: one that ends with
1291
- * `{`, or one that closes an empty body with `{}` or `{ }`.
1292
- *
1293
- * @remarks
1294
- * A line ending with `{}` closes an empty body only when every angle, round,
1295
- * and square bracket the head opened outside quoted text has closed; inside
1296
- * one, `{}` is a type or an argument, and an arrow's `=>` closes nothing. A
1297
- * head that reaches the next column-zero `export` line opens no body.
1298
- *
1299
- * @param lines - The file's source lines
1300
- * @param start - The index of the head's first line
1301
- * @returns The joined head, or `undefined` when no line opens a body
1302
- *
1303
- * @example
1304
- * ```ts
1305
- * joinHead(['export class X {'], 0) // { text: 'export class X {', end: 0 }
1306
- * joinHead(['export interface Y extends X {}'], 0) // { text: 'export interface Y extends X {}', end: 0 }
1307
- * ```
1308
- */
1309
- function joinHead(lines, start) {
1310
- const parts = [];
1311
- for (let index = start; index < lines.length; index += 1) {
1312
- const line = lines[index];
1313
- if (line === void 0) break;
1314
- const text = line.trimEnd();
1315
- if (index > start && text.startsWith("export ")) return void 0;
1316
- parts.push(index === start ? text : text.trimStart());
1317
- if (text.endsWith("{")) return {
1318
- text: parts.join(" "),
1319
- end: index
1320
- };
1321
- const bare = parts.join(" ").replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g, "");
1322
- if ((bare.match(/</g)?.length ?? 0) <= (bare.match(/(?<!=)>/g)?.length ?? 0) && (bare.match(/\(/g)?.length ?? 0) <= (bare.match(/\)/g)?.length ?? 0) && (bare.match(/\[/g)?.length ?? 0) <= (bare.match(/\]/g)?.length ?? 0) && /\{\s*\}$/.test(text)) return {
1323
- text: parts.join(" "),
1324
- end: index
1325
- };
1326
- }
1327
- }
1328
- /**
1329
- * Escapes every regex metacharacter in a literal string so it reads as text
1330
- * inside a larger `RegExp` source rather than as syntax.
1331
- *
1332
- * @remarks
1333
- * A caller-supplied name reaches a `RegExp` through this: {@link
1334
- * findUnexampled} splices it into a word-boundary search, so a name carrying
1335
- * `$`, `(`, `[`, or `.` matches that character literally instead of throwing or
1336
- * matching text it does not name. Pure and total; never throws.
1337
- *
1338
- * @param value - The literal string to escape
1339
- * @returns `value` with every regex metacharacter backslash-escaped
1340
- *
1341
- * @example
1342
- * ```ts
1343
- * escapeRegExp('A.B') // 'A\\.B'
1344
- * new RegExp(`^${escapeRegExp('A.B')}$`).test('AxB') // false
1345
- * ```
1346
- */
1347
- function escapeRegExp(value) {
1348
- return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
1349
- }
1350
- /**
1351
- * Collects every `export class` / `export interface` declaration one file's source text declares,
1352
- * each keyed `${keyword} ${name}` and carrying the body lines and the base identifiers read from
1353
- * its own head, so a body and a heritage clause always come from the same declaration.
1354
- *
1355
- * @remarks
1356
- * The whole file is projected once through {@link extractSourceLines} and every head is read from
1357
- * that one projection, so a scope resolving many names reads each file once rather than once per
1358
- * name. A head is a column-zero `export class` / `export interface` line, an oxfmt-wrapped
1359
- * signature joined through {@link joinHead}, with an optional generic parameter list and an
1360
- * optional heritage clause between the identifier and the opening `{`; the identifier is the head's
1361
- * own run up to that list or clause, so it enters the key as literal text and no name reaches a
1362
- * `RegExp`. Body lines are the raw source between the head and the first projected column-zero `}`,
1363
- * keeping JSDoc evidence intact; a head whose last line closes its own body with `{}` or `{ }`
1364
- * records an empty body. Every balanced `<...>` span is removed from the head before its
1365
- * `extends` clause is read, so a `T extends Base` type parameter is never a base and `Base<T>`
1366
- * reads as `Base`; a class's `implements` clause and everything after it is excluded, and a
1367
- * qualified base such as `namespace.Base` is returned verbatim. The first head of a key that opens
1368
- * a column-zero close answers for that key: a head that opens none records nothing, and a later
1369
- * head of a key already collected adds nothing unless the earlier head recorded neither a body
1370
- * nor bases, which declares nothing as {@link Source} reads it, so the later head replaces it.
1371
- *
1372
- * @param source - The file's source text to read
1373
- * @returns One entry per collected declaration, keyed `${keyword} ${name}`
1374
- *
1375
- * @example
1376
- * ```ts
1377
- * collectDeclarations('export interface X extends Y {\n\twalk(): void\n}\n').get('interface X')
1378
- * // { body: ['\twalk(): void'], bases: ['Y'] }
1379
- * ```
1380
- */
1381
- function collectDeclarations(source) {
1382
- const declarations = /* @__PURE__ */ new Map();
1383
- const opener = /^export (?:class|interface) /;
1384
- const grammar = /^export (class|interface) ([^\s<]+)(?:<.*>)?(?: .*)? \{(?:\s*\})?$/;
1385
- const lines = extractSourceLines(source);
1386
- const projected = lines.map((line) => line.code);
1387
- for (let index = 0; index < projected.length; index += 1) {
1388
- const line = projected[index];
1389
- if (line === void 0 || !opener.test(line)) continue;
1390
- const head = joinHead(projected, index);
1391
- if (head === void 0) continue;
1392
- const declared = grammar.exec(head.text);
1393
- const keyword = declared?.[1];
1394
- const name = declared?.[2];
1395
- if (keyword === void 0 || name === void 0) continue;
1396
- const key = `${keyword} ${name}`;
1397
- const known = declarations.get(key);
1398
- if (known !== void 0 && (known.body.length > 0 || known.bases.length > 0)) continue;
1399
- let depth = 0;
1400
- let flat = "";
1401
- for (const character of head.text.slice(`export ${key}`.length, head.text.lastIndexOf("{"))) if (character === "<") depth += 1;
1402
- else if (character === ">") depth = Math.max(0, depth - 1);
1403
- else if (depth === 0) flat += character;
1404
- const clause = flat.replace(/\bimplements\b[\s\S]*$/, "").match(/\bextends\b([\s\S]*)$/)?.[1];
1405
- const bases = clause === void 0 ? [] : clause.split(",").map((base) => base.trim()).filter(isNonEmptyString);
1406
- if (head.text.endsWith("}")) {
1407
- declarations.set(key, {
1408
- body: [],
1409
- bases
1410
- });
1411
- continue;
1412
- }
1413
- for (let close = head.end + 1; close < projected.length; close += 1) {
1414
- if (projected[close] !== "}") continue;
1415
- declarations.set(key, {
1416
- body: lines.slice(head.end + 1, close).map((record) => record.source),
1417
- bases
1418
- });
1419
- break;
1420
- }
1421
- }
1422
- return declarations;
1423
- }
1424
- /**
1425
- * Selects the member lines declaring a callable member: plain, `async`, generator
1426
- * (`*`), and optional (`records?(`) methods all count; getters, setters,
1427
- * `static` members, and `#` privates never do (their keyword or `#` breaks
1428
- * the `name(` shape). The grammar is {@link collectKeys}'s, read once over
1429
- * {@link extractBodyLines}'s projection of the body, so commented method-like payload never
1430
- * becomes eligible and each member keys to the owner head that projection supplies. Each member
1431
- * carries its own doc block's description paragraph, read through {@link collectSummaries}; the
1432
- * first declaration of a name answers for it.
1433
- *
1434
- * @param lines - A declaration's body lines
1435
- * @returns The declared members, deduplicated by name and sorted by name
1436
- *
1437
- * @example
1438
- * ```ts
1439
- * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // [{ name: 'filter' }, { name: 'map' }]
1440
- * ```
1441
- */
1442
- function extractMemberMethods(lines) {
1443
- const methods = /* @__PURE__ */ new Map();
1444
- const projected = extractBodyLines(lines);
1445
- const summaries = collectSummaries(projected);
1446
- const keys = collectKeys(projected);
1447
- for (const line of projected) {
1448
- const key = keys.get(line) ?? "";
1449
- const dot = key.indexOf(".");
1450
- if (dot < 0) continue;
1451
- const name = key.slice(dot + 1);
1452
- if (methods.has(name)) continue;
1453
- const summary = summaries.get(line);
1454
- methods.set(name, {
1455
- name,
1456
- ...summary === void 0 ? {} : { summary }
1457
- });
1458
- }
1459
- return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1460
- }
1461
- /**
1462
- * Selects the block nodes under the named `##` heading, up to the next `##`-or-higher
1463
- * heading (or the document's end) — the section-scoping window `extractSurface` /
1464
- * `extractMethods` walk over.
1465
- *
1466
- * @param document - The parsed guide document
1467
- * @param heading - The `##` heading text to scope to, for example `Surface`
1468
- * @returns The blocks belonging to that section, in document order
1469
- *
1470
- * @example
1471
- * ```ts
1472
- * selectSectionBlocks(document, 'Surface') // the blocks between `## Surface` and the next `##`
1473
- * ```
1474
- */
1475
- function selectSectionBlocks(document, heading) {
1476
- const blocks = [];
1477
- let active = false;
1478
- for (const block of document.children) {
1479
- if (isHeadingNode(block) && block.level <= 2) {
1480
- if (block.level === 2 && flattenText(block).trim() === heading) {
1481
- active = true;
1482
- continue;
1483
- }
1484
- if (active) break;
1485
- }
1486
- if (active) blocks.push(block);
1487
- }
1488
- return blocks;
1489
- }
1490
- /**
1491
- * Extracts one `## Surface` table row's symbol — its column 0 code span as the name, its
1492
- * {@link KIND} column as the keyword, and its {@link SUMMARY} column as the compared summary
1493
- * when the table has that column. A row with no code-span name and a row whose `Kind` text is
1494
- * no {@link ExportKeyword} have no symbol to key, so each returns `undefined`.
1495
- *
1496
- * @param table - The table to read
1497
- * @param row - The index of the row within {@link TableNode.rows}
1498
- * @returns The row's symbol, or `undefined` when the row keys none
1499
- *
1500
- * @example
1501
- * ```ts
1502
- * extractRowSymbol(table, 0) // { name: 'walk', keyword: 'function', summary: 'Walks the tree.' }
1503
- * ```
1504
- */
1505
- function extractRowSymbol(table, row) {
1506
- const cells = table.rows[row];
1507
- if (cells === void 0) return void 0;
1508
- const nameCell = cells[0];
1509
- const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1510
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1511
- if (name === void 0) return void 0;
1512
- const column = findColumnIndex(table, KIND);
1513
- const kindCell = column === void 0 ? void 0 : cells[column];
1514
- const keyword = kindCell === void 0 ? "" : flattenText({
1515
- element: "paragraph",
1516
- children: kindCell
1517
- }).trim();
1518
- if (!isExportKeyword(keyword)) return void 0;
1519
- const summary = extractRowSummary(table, row);
1520
- return {
1521
- name,
1522
- keyword,
1523
- ...summary === void 0 ? {} : { summary }
1524
- };
1525
- }
1526
- /**
1527
- * Extracts one `## Methods` table row's entry — its column 0 code span as the name and its
1528
- * {@link SUMMARY} column as the compared summary when the table has that column. A row with no
1529
- * code-span name has no member to key, so it returns `undefined`.
1530
- *
1531
- * @param table - The table to read
1532
- * @param row - The index of the row within {@link TableNode.rows}
1533
- * @returns The row's entry, or `undefined` when the row keys none
1534
- *
1535
- * @example
1536
- * ```ts
1537
- * extractRowEntry(table, 0) // { name: 'walk', summary: 'Walks the tree.' }
1538
- * ```
1539
- */
1540
- function extractRowEntry(table, row) {
1541
- const cells = table.rows[row];
1542
- if (cells === void 0) return void 0;
1543
- const cell = cells[0];
1544
- const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1545
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1546
- if (name === void 0) return void 0;
1547
- const summary = extractRowSummary(table, row);
1548
- return {
1549
- name,
1550
- ...summary === void 0 ? {} : { summary }
1551
- };
1552
- }
1553
- /**
1554
- * Extracts one row's compared summary — its {@link SUMMARY} column read through
1555
- * {@link extractCellText} and {@link normalizeSummary}. A table with no such column and a row
1556
- * whose cell is empty each carry no summary and return `undefined` rather than an empty string,
1557
- * so {@link findDrift} reports the absence.
1558
- *
1559
- * @param table - The table to read
1560
- * @param row - The index of the row within {@link TableNode.rows}
1561
- * @returns The row's compared summary, or `undefined` when it carries none
1562
- *
1563
- * @example
1564
- * ```ts
1565
- * extractRowSummary(table, 0) // 'Walks the tree.'
1566
- * ```
1567
- */
1568
- function extractRowSummary(table, row) {
1569
- const described = findColumnIndex(table, SUMMARY);
1570
- const cells = table.rows[row];
1571
- const cell = described === void 0 || cells === void 0 ? void 0 : cells[described];
1572
- const summary = cell === void 0 ? "" : normalizeSummary(extractCellText(cell));
1573
- return summary.length === 0 ? void 0 : summary;
1574
- }
1575
- /**
1576
- * Extracts every `## Surface` identifier the guide documents — each table row's column 0
1577
- * code span (the name) paired with its `Kind` column (located by header text), unioned with every
1578
- * H3 entity heading whose trimmed compared inline content is exactly its backticked code-span
1579
- * name, deduped by {@link computeSymbolKey}. A row with no code-span name has no name to key a
1580
- * symbol on, so this reader skips it and {@link extractUnnamed} reports it; a row with an
1581
- * unrecognized `Kind` text is skipped. A row also carries its {@link SUMMARY} column's compared
1582
- * text when the table has that column; a table without it leaves every row's summary absent,
1583
- * which {@link findDrift} reports.
1584
- *
1585
- * @remarks
1586
- * The heading boundary compares {@link extractCellText} with the raw value from
1587
- * {@link findFirstCode} before {@link normalizeIdentifier} strips a generic annotation.
1588
- * Surrounding spaces, emphasis, and links preserve that identity. This reader refuses a heading
1589
- * carrying any other visible text or an additional code span. Entries retain encounter order, and
1590
- * the first-seen name + keyword wins: a genuine heading before its table row keeps the heading's
1591
- * summary-less class entry, while a table row before that heading keeps its `Summary`.
1592
- *
1593
- * @param document - The parsed guide document
1594
- * @returns The documented surface, in encounter order
1595
- *
1596
- * @example
1597
- * ```ts
1598
- * extractSurface(document) // [{ name: 'Markdown', keyword: 'class' }, ...]
1599
- * ```
1600
- */
1601
- function extractSurface(document) {
1602
- const symbols = [];
1603
- const seen = /* @__PURE__ */ new Set();
1604
- for (const block of selectSectionBlocks(document, SURFACE)) {
1605
- if (isTableNode(block)) {
1606
- for (let row = 0; row < block.rows.length; row += 1) {
1607
- const symbol = extractRowSymbol(block, row);
1608
- if (symbol === void 0) continue;
1609
- const key = computeSymbolKey(symbol);
1610
- if (seen.has(key)) continue;
1611
- seen.add(key);
1612
- symbols.push(symbol);
1613
- }
1614
- continue;
1615
- }
1616
- if (isHeadingNode(block) && block.level === 3) {
1617
- const rawName = findFirstCode(block.children);
1618
- if (rawName === void 0 || extractCellText(block.children).trim() !== `\`${rawName}\``) continue;
1619
- const symbol = {
1620
- name: normalizeIdentifier(rawName),
1621
- keyword: "class"
1622
- };
1623
- const key = computeSymbolKey(symbol);
1624
- if (seen.has(key)) continue;
1625
- seen.add(key);
1626
- symbols.push(symbol);
1627
- }
1628
- }
1629
- return symbols;
1630
- }
1631
- /**
1632
- * Extracts one {@link MethodGroup} per documented behavioral interface in `## Methods` —
1633
- * an H4 with a code span sets the current interface, and the table immediately
1634
- * following becomes its documented methods. A row with no code-span name has no name to key a
1635
- * member on, so this reader skips it and {@link extractUnnamed} reports it. Each row carries its
1636
- * {@link SUMMARY} column's compared text when the table has that column.
1637
- *
1638
- * @param document - The parsed guide document
1639
- * @returns The documented method groups, in document order
1640
- *
1641
- * @example
1642
- * ```ts
1643
- * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }]
1644
- * ```
1645
- */
1646
- function extractMethods(document) {
1647
- const groups = [];
1648
- for (const [table, name] of collectGroups(document)) {
1649
- const methods = [];
1650
- for (let row = 0; row < table.rows.length; row += 1) {
1651
- const entry = extractRowEntry(table, row);
1652
- if (entry !== void 0) methods.push(entry);
1653
- }
1654
- groups.push({
1655
- interface: name,
1656
- methods
1657
- });
1658
- }
1659
- return groups;
1660
- }
1661
- /**
1662
- * Collects each `## Methods` table keyed to the interface its `####` heading names — an H4
1663
- * carrying a code span sets the current interface and the table immediately following claims it,
1664
- * so a heading with no table and a table with no heading before it contribute nothing. The map
1665
- * iterates in document order and a node keys itself, so a repeated identical table keeps its own
1666
- * entry.
1667
- *
1668
- * @param document - The parsed guide document
1669
- * @returns One entry per documented `## Methods` table, in document order
1670
- *
1671
- * @example
1672
- * ```ts
1673
- * collectGroups(document).values().next().value // 'GuideInterface'
1674
- * ```
1675
- */
1676
- function collectGroups(document) {
1677
- const groups = /* @__PURE__ */ new Map();
1678
- let current;
1679
- for (const block of selectSectionBlocks(document, METHODS)) {
1680
- if (isHeadingNode(block) && block.level === 4) {
1681
- const rawInterface = findFirstCode(block.children);
1682
- current = rawInterface === void 0 ? void 0 : normalizeIdentifier(rawInterface);
1683
- continue;
1684
- }
1685
- if (isTableNode(block) && current !== void 0) {
1686
- groups.set(block, current);
1687
- current = void 0;
1688
- }
1689
- }
1690
- return groups;
1691
- }
1692
- /**
1693
- * Extracts every `## Surface` or `## Methods` table row whose first cell carries no code span.
1694
- * {@link extractSurface} and {@link extractMethods} skip such a row, because a row with no
1695
- * name gives them nothing to key a symbol or a member on, and this projection is what reports
1696
- * the skip. Each entry is the row's cells read through {@link extractCellText} and joined
1697
- * by ` | `, so a reader can locate the row in the guide; the `## Surface` rows come first,
1698
- * then the `## Methods` rows, each in document order. {@link GuideInterface.unnamed} caches it.
1699
- *
1700
- * @param document - The parsed guide document
1701
- * @returns One entry per row carrying no code-span name
1702
- *
1703
- * @example
1704
- * ```ts
1705
- * extractUnnamed(document) // ['Widget | class | Represents a widget.']
1706
- * ```
1707
- */
1708
- function extractUnnamed(document) {
1709
- const unnamed = [];
1710
- for (const heading of [SURFACE, METHODS]) for (const block of selectSectionBlocks(document, heading)) {
1711
- if (!isTableNode(block)) continue;
1712
- for (const row of block.rows) {
1713
- const cell = row[0];
1714
- if (cell !== void 0 && findFirstCode(cell) !== void 0) continue;
1715
- unnamed.push(row.map((content) => extractCellText(content)).join(" | "));
1716
- }
1717
- }
1718
- return unnamed;
1719
- }
1720
- /**
1721
- * Extracts every link href in the guide document, including table cells — a full,
1722
- * depth-first walk of the whole AST.
1723
- *
1724
- * @param document - The parsed guide document
1725
- * @returns Every link's href, in walk order
1726
- *
1727
- * @example
1728
- * ```ts
1729
- * extractLinks(document) // ['../../src/core/helpers.ts', 'https://example.com']
1730
- * ```
1731
- */
1732
- function extractLinks(document) {
1733
- const links = [];
1734
- for (const node of walkNodes(document)) if (isLinkNode(node)) links.push(node.href);
1735
- return links;
1736
- }
1737
- /**
1738
- * Extracts the relative test links declared under `## Tests` — every link href found
1739
- * within that section only.
1740
- *
1741
- * @param document - The parsed guide document
1742
- * @returns The `## Tests` section's link hrefs, in walk order
1743
- *
1744
- * @example
1745
- * ```ts
1746
- * extractTests(document) // ['../../tests/src/core/Markdown.test.ts', ...]
1747
- * ```
1748
- */
1749
- function extractTests(document) {
1750
- const links = [];
1751
- for (const block of selectSectionBlocks(document, TESTS)) for (const node of walkNodes(block)) if (isLinkNode(node)) links.push(node.href);
1752
- return links;
1753
- }
1754
- /**
1755
- * Returns the canonical body of one genuine JSDoc span — the `/**` opener, the closing
1756
- * marker, each line's continuation marker, and the block's leading indentation removed,
1757
- * with per-line trailing whitespace trimmed and the surrounding blank lines dropped. A
1758
- * line's own indentation beyond the marker is kept, so an `@example` fence body keeps the
1759
- * shape it was written in.
1760
- *
1761
- * @param comment - One complete genuine JSDoc span's raw text
1762
- * @returns The span's unwrapped body
1763
- *
1764
- * @example
1765
- * ```ts
1766
- * normalizeComment('/**' + ' Creates a widget. *' + '/') // 'Creates a widget.'
1767
- * ```
1768
- */
1769
- function normalizeComment(comment) {
1770
- return unwrapComment(comment).join("\n").replace(/^\n+/, "").replace(/\n+$/, "");
1771
- }
1772
- /**
1773
- * Unwraps one genuine JSDoc span into one content line per physical line — the `/**` opener,
1774
- * the closing marker, each line's continuation marker, and per-line trailing whitespace removed,
1775
- * with a line's own indentation past the marker kept. The result is aligned with
1776
- * `comment.split('\n')`, so an index found in it addresses the same physical line of the span it
1777
- * was built from, which is what lets a rewrite keep every line it does not replace.
1778
- * {@link normalizeComment} is this projection joined and trimmed at its ends.
1779
- *
1780
- * @param comment - One complete genuine JSDoc span's raw text
1781
- * @returns One content line per physical line of the span
1782
- *
1783
- * @example
1784
- * ```ts
1785
- * unwrapComment('/**' + '\n * Walks.\n *' + '/') // ['', 'Walks.', '']
1786
- * ```
1787
- */
1788
- function unwrapComment(comment) {
1789
- return (/^[ \t]*\/\*([\s\S]*?)\*\/[ \t]*$/.exec(comment)?.[1] ?? comment).split("\n").map((line) => line.replace(/^[ \t]*\*[ \t]?/, "").replace(/[ \t]+$/, ""));
1790
- }
1791
- /**
1792
- * Returns the canonical compared form of a description paragraph. `{@link Target}` and
1793
- * `{@link Target | label}` become the code token of the target text, or of the label where one is
1794
- * written; a target's module part — the inline import form `import('./module.js').` and TSDoc's
1795
- * package-qualified form `@scope/pkg#` — is dropped first. Every run of whitespace, including a
1796
- * collapsed continuation marker and a line break, becomes one space, the ends trim, and a code
1797
- * span keeps its delimiters while its own boundary whitespace goes. The guide's side and the
1798
- * source's side read through this one form.
1799
- *
1800
- * @remarks
1801
- * The clauses land in a fixed order, because each one decides what the next one sees. Every
1802
- * single-backtick code span — one backtick per side, no inner backtick, no adjacent backtick —
1803
- * is located first, so a delimiter the `{@link}` expansion inserts afterwards is never mistaken
1804
- * for an authored one. The expansion then runs outside those spans
1805
- * only, so a `{@link}` written inside a code span stays literal on both sides. Whitespace
1806
- * collapses next, which is what makes a span wrapped across two physical lines comparable at
1807
- * all. The boundary trim runs last, inside each located span: the markdown parser strips one
1808
- * space from each end of a code span it reads, and this trim is the symmetric rule that meets
1809
- * it, so `` ` | ` ``, `` ` |` ``, and `` `|` `` all reach `` `|` `` from either side. A span
1810
- * whose content is all whitespace keeps one space, because a parser strips nothing from that
1811
- * one.
1812
- *
1813
- * A target's module part is the inline import form `import('./module.js').` or TSDoc's
1814
- * package-qualified form `@scope/pkg#`, and the expansion drops it, so a cross-file link and the
1815
- * code token a guide cell documents it with reach the same text. A package qualifier carries `@`
1816
- * or `/`; text before a `#` carrying neither is JSDoc's member reference, so `{@link Owner#member}`
1817
- * and `{@link #member}` travel whole and a guide cell documents each as written. An unscoped
1818
- * package name is spelled like an owner, so `{@link pkg#Name}` travels whole too — write the
1819
- * scoped or the path form where a cell must drop the package. Everything after a module part
1820
- * travels: `Owner.member` keeps its owner, and a dotted target no module part precedes is
1821
- * untouched. A label is text rather than a target, so `{@link Target | label}` renders its label
1822
- * whole.
1823
- *
1824
- * A code span delimited by more than one backtick is outside the compared form's representable
1825
- * set and travels untouched, as does a code span whose own text carries a backtick: the form
1826
- * spells every span with one backtick per side, so neither can be written back. A summary that
1827
- * needs one of those constructs takes another shape: name the construct in prose rather than
1828
- * expecting the comparison to converge it.
1829
- *
1830
- * @param text - A doc block's description paragraph, or a guide cell's flattened text
1831
- * @returns The compared form of that text
1832
- *
1833
- * @example
1834
- * ```ts
1835
- * normalizeSummary('Creates a\n{@link Widget}.') // 'Creates a `Widget`.'
1836
- * normalizeSummary("Reads {@link import('./widgets.js').Widget}.") // 'Reads `Widget`.'
1837
- * normalizeSummary('Reads {@link @scope/widgets#Widget}.') // 'Reads `Widget`.'
1838
- * normalizeSummary('Reads {@link Widget#render}.') // 'Reads `Widget#render`.'
1839
- * normalizeSummary('cells joined by ` | `.') // 'cells joined by `|`.'
1840
- * ```
1841
- */
1842
- function normalizeSummary(text) {
1843
- const parts = text.split(/((?<!`)`[^`]+`(?!`))/);
1844
- let normalized = "";
1845
- for (let index = 0; index < parts.length; index += 1) {
1846
- const part = parts[index] ?? "";
1847
- if (index % 2 === 0) {
1848
- normalized += part.replace(/\{@link\s+[^}|]*\|\s*([^}]*?)\s*\}/g, "`$1`").replace(/\{@link\s+(?:import\([^)]*\)\.|[^}|#\s]*[@/][^}|#\s]*#)?([^}|]*?)\s*\}/g, "`$1`");
1849
- continue;
1850
- }
1851
- const value = part.slice(1, -1).replace(/\s+/g, " ").trim();
1852
- normalized += `\`${value.length === 0 ? " " : value}\``;
1853
- }
1854
- return normalized.replace(/\s+/g, " ").trim();
1855
- }
1856
- /**
1857
- * Wraps one paragraph into greedy lines no longer than `width` characters. Every run of
1858
- * whitespace separates words, and a word longer than `width` takes its own line rather than
1859
- * being split, so a long code token or URL survives the wrap intact.
1860
- *
1861
- * @param text - The paragraph to wrap
1862
- * @param width - The greatest length a returned line may reach
1863
- * @returns The wrapped lines, in order, or an empty list when `text` carries no word
1864
- *
1865
- * @example
1866
- * ```ts
1867
- * wrapText('one two three', 8) // ['one two', 'three']
1868
- * ```
1869
- */
1870
- function wrapText(text, width) {
1871
- const lines = [];
1872
- let current = "";
1873
- for (const word of text.split(/\s+/)) {
1874
- if (word.length === 0) continue;
1875
- if (current.length === 0) current = word;
1876
- else if (current.length + 1 + word.length <= width) current += ` ${word}`;
1877
- else {
1878
- lines.push(current);
1879
- current = word;
1880
- }
1881
- }
1882
- if (current.length > 0) lines.push(current);
1883
- return lines;
1884
- }
1885
- /**
1886
- * Builds one genuine JSDoc span from its content lines — the inverse of {@link unwrapComment}.
1887
- * Each line is emitted at `indent` behind a continuation marker, an empty line as the bare
1888
- * marker so no line carries trailing whitespace, and the leading and trailing empty lines are
1889
- * dropped because the opener and the closer take those physical lines.
1890
- *
1891
- * @param lines - The span's content lines, as {@link unwrapComment} returns them
1892
- * @param indent - The whitespace the span opens at
1893
- * @returns The span's raw text, opener and closer included
1894
- *
1895
- * @example
1896
- * ```ts
1897
- * buildComment(['Walks.'], '') // '/**\n * Walks.\n *' + '/'
1898
- * ```
1899
- */
1900
- function buildComment(lines, indent) {
1901
- const content = [...lines];
1902
- while (content[0] === "") content.shift();
1903
- while (content[content.length - 1] === "") content.pop();
1904
- const raw = [`${indent}/**`];
1905
- for (const line of content) raw.push(line.length === 0 ? `${indent} *` : `${indent} * ${line}`);
1906
- raw.push(`${indent} */`);
1907
- return raw.join("\n");
1908
- }
1909
- /**
1910
- * Returns one doc block's unwrapped text with every fenced body replaced by aligned spaces,
1911
- * so a tag search reads the block's structure and never its example code. A line opening with
1912
- * three or more backticks or tildes opens a body, the first line opening with a run of the same
1913
- * character at least as long closes it, an unclosed body runs to the end, and the marker lines
1914
- * themselves stay. The projection preserves every line and every column, so an index found in
1915
- * it addresses the same character of the text it was built from.
1916
- *
1917
- * @param text - One doc block's unwrapped text, as {@link normalizeComment} returns it
1918
- * @returns The same text with each fenced body's characters replaced by spaces
1919
- *
1920
- * @example
1921
- * ```ts
1922
- * maskFences('@example\n~~~\n@decorator()\n~~~').split('\n')[2] // ' '
1923
- * ```
1924
- */
1925
- function maskFences(text) {
1926
- const masked = [];
1927
- let marker;
1928
- for (const line of text.split("\n")) {
1929
- const fence = /^[ \t]*(`{3,}|~{3,})/.exec(line)?.[1];
1930
- if (marker === void 0) {
1931
- masked.push(line);
1932
- marker = fence;
1933
- continue;
1934
- }
1935
- const closing = fence !== void 0 && fence.startsWith(marker);
1936
- masked.push(closing ? line : " ".repeat(line.length));
1937
- if (closing) marker = void 0;
1938
- }
1939
- return masked.join("\n");
1940
- }
1941
- /**
1942
- * Extracts every eligible genuine JSDoc block paired with the physical record it documents.
1943
- *
1944
- * @remarks
1945
- * An opener is eligible only when it is the first non-whitespace source material of its record; a
1946
- * leading whitespace-separated span chain is last-span authoritative; intervening source material
1947
- * severs association, while a leading JSDoc on the next record replaces pending state. Any other
1948
- * next physical record is returned once and consumes it. This parser walks aligned records without
1949
- * rescanning source syntax or applying declaration/member grammar, and every reader of a doc
1950
- * block's text — the description paragraph, the `@example` blocks, the member summaries — reads it
1951
- * through this one walk.
1952
- *
1953
- * @param lines - Aligned physical source-line records
1954
- * @returns One record per documented physical line, in source order
1955
- *
1956
- * @example
1957
- * ```ts
1958
- * extractSourceComments(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}'))
1959
- * // [{ text: 'Walks.', line: the `export function walk() {}` SourceLine }]
1960
- * ```
1961
- */
1962
- function extractSourceComments(lines) {
1963
- const comments = [];
1964
- let block = false;
1965
- let eligible = false;
1966
- let span = [];
1967
- let pending;
1968
- for (const line of lines) {
1969
- const projection = line.jsdoc;
1970
- const first = projection?.indexOf("/**") ?? -1;
1971
- if (pending !== void 0) {
1972
- if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = void 0;
1973
- else {
1974
- comments.push({
1975
- text: pending,
1976
- line
1977
- });
1978
- pending = void 0;
1979
- }
1980
- }
1981
- if (projection === void 0) continue;
1982
- let cursor = 0;
1983
- if (block) {
1984
- const close = projection.indexOf("*/");
1985
- const end = close < 0 ? projection.length : close + 2;
1986
- span.push(projection.slice(0, end));
1987
- if (close < 0) continue;
1988
- block = false;
1989
- const opener = projection.indexOf("/**", close + 2);
1990
- const endOfGap = opener < 0 ? line.source.length : opener;
1991
- const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1992
- if (opener < 0) {
1993
- pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1994
- continue;
1995
- }
1996
- eligible = eligible && whitespace;
1997
- span = [];
1998
- cursor = opener;
1999
- } else {
2000
- if (first < 0) continue;
2001
- eligible = line.source.slice(0, first).trim() === "";
2002
- span = [];
2003
- cursor = first;
2004
- }
2005
- while (cursor < projection.length) {
2006
- const close = projection.indexOf("*/", cursor + 2);
2007
- const end = close < 0 ? projection.length : close + 2;
2008
- span.push(projection.slice(cursor, end));
2009
- if (close < 0) {
2010
- block = true;
2011
- break;
2012
- }
2013
- const opener = projection.indexOf("/**", close + 2);
2014
- const endOfGap = opener < 0 ? line.source.length : opener;
2015
- const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
2016
- if (opener < 0) {
2017
- pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
2018
- break;
2019
- }
2020
- eligible = eligible && whitespace;
2021
- span = [];
2022
- cursor = opener;
2023
- }
2024
- }
2025
- return comments;
2026
- }
2027
- /**
2028
- * Collects the description paragraph of every documented physical record — a doc block's
2029
- * text before its first block tag, in {@link normalizeSummary}'s compared form — keyed by the
2030
- * record it documents. A record whose block carries no description contributes no entry, so
2031
- * an absent summary stays absent rather than becoming an empty string.
2032
- *
2033
- * @param lines - Aligned physical source-line records
2034
- * @returns One entry per documented record carrying a description paragraph
2035
- *
2036
- * @example
2037
- * ```ts
2038
- * collectSummaries(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}')).size // 1
2039
- * ```
2040
- */
2041
- function collectSummaries(lines) {
2042
- const summaries = /* @__PURE__ */ new Map();
2043
- for (const comment of extractSourceComments(lines)) {
2044
- const tag = maskFences(comment.text).search(/^[ \t]*@\w/m);
2045
- const summary = normalizeSummary(tag < 0 ? comment.text : comment.text.slice(0, tag));
2046
- if (summary.length > 0) summaries.set(comment.line, summary);
2047
- }
2048
- return summaries;
2049
- }
2050
- /**
2051
- * Extracts the aligned physical records of a declaration's body, read inside an owner head this
2052
- * function supplies, so a callable member in the body carries the `Owner.member` key
2053
- * {@link collectKeys} reports for it, and that head's own record opens the projection. A body
2054
- * read on its own carries no head, and the member grammar attaches a member to the head
2055
- * enclosing it.
2056
- *
2057
- * @remarks
2058
- * The supplied head is an `export interface` line, so the projection opens with that head's own
2059
- * record and every body line follows it in order. A column-zero `}` among the body lines closes
2060
- * the supplied head and leaves every later member unkeyed; a body {@link extractDeclaration}
2061
- * returns carries none, because that reader ends a body at the first one.
2062
- *
2063
- * @param lines - A declaration's body lines
2064
- * @returns The supplied head's record, then one record per body line
2065
- *
2066
- * @example
2067
- * ```ts
2068
- * extractBodyLines(['\twalk(): void'])[1]?.code // '\twalk(): void'
2069
- * ```
2070
- */
2071
- function extractBodyLines(lines) {
2072
- return extractSourceLines(["export interface Owner {", ...lines].join("\n"));
2073
- }
2074
- /**
2075
- * Collects the compared key of every physical record a key names — a {@link computeSymbolKey}
2076
- * symbol key for a column-zero `export` declaration head, an `Owner.member` key for a one-tab
2077
- * callable member inside one — keyed by the record itself. The owner closes at the first
2078
- * column-zero `}` or at a column-zero `export` declaration carrying another keyword, and a
2079
- * record no key names contributes no entry.
2080
- *
2081
- * @remarks
2082
- * This is the package's one key grammar, and each keyed reader projects its own part back out of
2083
- * it: {@link extractExports} splits a declaration key at its one space,
2084
- * {@link extractMemberMethods} and {@link extractExampleMethods} split a member key at its dot,
2085
- * and {@link locateComment} matches a caller's key against the whole map. A change to the head
2086
- * shape or to the member shape reaches every one of them at once.
2087
- *
2088
- * An owner opens at a column-zero `export class`, `export abstract class`, or `export interface`
2089
- * head and closes at the
2090
- * first column-zero `}`, so a member declared past that brace keys nothing. A column-zero `export` declaration carrying any other keyword closes the owner it follows,
2091
- * because a member belongs to the head enclosing it. Reading runs over {@link extractSourceLines}'s
2092
- * projection, so a head or
2093
- * a member written inside a comment or a template literal keys nothing.
2094
- *
2095
- * @param lines - Aligned physical source-line records
2096
- * @returns One entry per record a key names, in file order
2097
- *
2098
- * @example
2099
- * ```ts
2100
- * const keys = collectKeys(extractSourceLines('export class Widget {\n\twalk(): void\n}'))
2101
- * Array.from(keys.values()) // ['class Widget', 'Widget.walk']
2102
- * ```
2103
- */
2104
- function collectKeys(lines) {
2105
- const keys = /* @__PURE__ */ new Map();
2106
- let owner;
2107
- for (const line of lines) {
2108
- const head = /^export (?:async )?(?:abstract )?(function\*?|class|const|interface|type) (\w+)/.exec(line.code);
2109
- const keyword = head?.[1]?.replace(/\*$/, "");
2110
- const name = head?.[2];
2111
- if (isNonEmptyString(keyword) && isNonEmptyString(name) && isExportKeyword(keyword)) {
2112
- keys.set(line, computeSymbolKey({
2113
- name,
2114
- keyword
2115
- }));
2116
- owner = keyword === "class" || keyword === "interface" ? name : void 0;
2117
- continue;
2118
- }
2119
- if (line.code === "}") {
2120
- owner = void 0;
2121
- continue;
2122
- }
2123
- const member = /^\t(?:async )?\*?(\w+)\??(?:<.*>)?\(/.exec(line.code)?.[1];
2124
- if (owner !== void 0 && isNonEmptyString(member)) keys.set(line, `${owner}.${member}`);
2125
- }
2126
- return keys;
2127
- }
2128
- /**
2129
- * Collects the `@example` blocks one doc block's unwrapped text carries, each named for the
2130
- * declaration or member the block documents. The text after the tag becomes the block's
2131
- * `title`; a body opening with a fence contributes that fence's language and its verbatim
2132
- * body, and a body with no fence contributes its own trimmed text as the code.
2133
- *
2134
- * @param comment - One doc block's unwrapped text, as {@link normalizeComment} returns it
2135
- * @param name - The declaration or member the block documents
2136
- * @returns The block's `@example` entries, in block order
2137
- *
2138
- * @example
2139
- * ```ts
2140
- * collectExamples('@example Walking\n```ts\nwalk()\n```', 'walk')
2141
- * // [{ name: 'walk', title: 'Walking', code: 'walk()', language: 'ts' }]
2142
- * ```
2143
- */
2144
- function collectExamples(comment, name) {
2145
- const examples = [];
2146
- const masked = maskFences(comment);
2147
- const tags = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/gm;
2148
- let tag;
2149
- while ((tag = tags.exec(masked)) !== null) {
2150
- const title = (tag[1] ?? "").trim();
2151
- const start = tag.index + tag[0].length;
2152
- const rest = comment.slice(start).replace(/^\n/, "");
2153
- const next = masked.slice(start).replace(/^\n/, "").search(/^[ \t]*@\w+/m);
2154
- const body = (next < 0 ? rest : rest.slice(0, next)).replace(/^\n+/, "").replace(/\n+$/, "");
2155
- const fence = /^```(\S*)\n([\s\S]*?)\n?```/.exec(body);
2156
- const language = fence?.[1] ?? "";
2157
- const code = fence?.[2] ?? body;
2158
- examples.push({
2159
- name,
2160
- ...title.length === 0 ? {} : { title },
2161
- code,
2162
- ...language.length === 0 ? {} : { language }
2163
- });
2164
- }
2165
- return examples;
2166
- }
2167
- /**
2168
- * Extracts the `@example` blocks carried by the exported declaration heads in one file's source
2169
- * text, each named for the declaration its block documents. Shared adjacency comes from
2170
- * {@link extractSourceComments} and each block is read by {@link collectExamples}; head
2171
- * membership is the {@link collectKeys} key of the documented record under every keyword that
2172
- * grammar admits at column zero, so comment and template payload cannot qualify and the head
2173
- * grammar stays the one every reader here shares. A member key carries a dot and a head key
2174
- * does not, so a member's block belongs to {@link extractExampleMethods} instead. A head
2175
- * carrying several blocks contributes each.
2176
- *
2177
- * @param source - The file's source text
2178
- * @returns The exported declaration heads' `@example` blocks, in file order, deduplicated by name and title
2179
- *
2180
- * @example
2181
- * ```ts
2182
- * const block = ['/**', ' * @example', ' * new Widget()', ' *' + '/', 'export class Widget {}', ''].join('\n')
2183
- * extractExamples(block) // [{ name: 'Widget', code: 'new Widget()' }]
2184
- * extractExamples('export class Widget {}\n') // []
2185
- * ```
2186
- */
2187
- function extractExamples(source) {
2188
- const examples = [];
2189
- const seen = /* @__PURE__ */ new Set();
2190
- const lines = extractSourceLines(source);
2191
- const keys = collectKeys(lines);
2192
- for (const comment of extractSourceComments(lines)) {
2193
- const key = keys.get(comment.line);
2194
- if (key === void 0 || key.includes(".")) continue;
2195
- const name = key.slice(key.indexOf(" ") + 1);
2196
- for (const example of collectExamples(comment.text, name)) {
2197
- const entry = `${name}\n${example.title ?? ""}`;
2198
- if (seen.has(entry)) continue;
2199
- seen.add(entry);
2200
- examples.push(example);
2201
- }
2202
- }
2203
- return examples;
2204
- }
2205
- /**
2206
- * Extracts the `@example` blocks carried by the callable members of a declaration body (per
2207
- * {@link collectKeys}' grammar, the same one {@link extractMemberMethods} reads), each named for
2208
- * the member its block documents. Shared adjacency comes from {@link extractSourceComments} and
2209
- * each block is read by {@link collectExamples}; member membership is the key
2210
- * {@link extractBodyLines}'s projection gives the documented record.
2211
- *
2212
- * @param lines - A declaration's body lines
2213
- * @returns The members' `@example` blocks, deduplicated by name and title and sorted by name
2214
- *
2215
- * @example
2216
- * ```ts
2217
- * extractExampleMethods(['\t/**', '\t * @example', '\t * walk()', '\t *' + '/', '\twalk(): void'])
2218
- * // [{ name: 'walk', code: 'walk()' }]
2219
- * ```
2220
- */
2221
- function extractExampleMethods(lines) {
2222
- const examples = [];
2223
- const seen = /* @__PURE__ */ new Set();
2224
- const projected = extractBodyLines(lines);
2225
- const keys = collectKeys(projected);
2226
- for (const comment of extractSourceComments(projected)) {
2227
- const key = keys.get(comment.line) ?? "";
2228
- const dot = key.indexOf(".");
2229
- if (dot < 0) continue;
2230
- const name = key.slice(dot + 1);
2231
- for (const example of collectExamples(comment.text, name)) {
2232
- const entry = `${name}\n${example.title ?? ""}`;
2233
- if (seen.has(entry)) continue;
2234
- seen.add(entry);
2235
- examples.push(example);
2236
- }
2237
- }
2238
- return examples.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
2239
- }
2240
- /**
2241
- * Extracts every fenced code block anywhere in the guide document. A full AST walk
2242
- * includes fences nested inside blockquotes and lists, and the same walk carries each
2243
- * fence's nearest preceding heading as its `title` — the key an `@example` block pairs on.
2244
- * A heading's text is flattened, so a title written with a code span pairs with a plain
2245
- * `@example` title.
2246
- *
2247
- * @param document - The parsed guide document
2248
- * @returns Every fence's language, verbatim code, and title, in document order
2249
- *
2250
- * @example
2251
- * ```ts
2252
- * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2253
- * ```
2254
- */
2255
- function extractFences(document) {
2256
- return Array.from(collectFences(document).values());
2257
- }
2258
- /**
2259
- * Collects each fenced code block keyed by its own node, paired with the {@link GuideFence}
2260
- * {@link extractFences} reports for it — the node-addressed form a rewrite needs, so a caller
2261
- * that located a fence by title can read that node's source region back from the parser. The map
2262
- * iterates in document order and a node keys itself, so a repeated identical fence keeps its own
2263
- * entry.
2264
- *
2265
- * @param document - The parsed guide document
2266
- * @returns One entry per fenced code block, in document order
2267
- *
2268
- * @example
2269
- * ```ts
2270
- * Array.from(collectFences(document).values()) // [{ language: 'ts', code: 'walk()' }]
2271
- * ```
2272
- */
2273
- function collectFences(document) {
2274
- const fences = /* @__PURE__ */ new Map();
2275
- let title = "";
2276
- for (const node of walkNodes(document)) {
2277
- if (isHeadingNode(node)) {
2278
- title = flattenText(node).trim();
2279
- continue;
2280
- }
2281
- if (isCodeBlockNode(node)) fences.set(node, {
2282
- language: node.lang,
2283
- code: node.code,
2284
- ...title.length === 0 ? {} : { title }
2285
- });
2286
- }
2287
- return fences;
2288
- }
2289
- /**
2290
- * Extracts the guide's tagline — the text of the blockquote following the document's H1,
2291
- * with every code span kept as a code span and whitespace collapsed. A heading before the
2292
- * blockquote ends the window, so a blockquote elsewhere in the document is not the tagline.
2293
- *
2294
- * @param document - The parsed guide document
2295
- * @returns The tagline, or `undefined` when no blockquote follows an H1 before the next heading
2296
- *
2297
- * @example
2298
- * ```ts
2299
- * extractTagline(document) // 'A pure, I/O-free guides-parity toolkit'
2300
- * ```
2301
- */
2302
- function extractTagline(document) {
2303
- let opened = false;
2304
- for (const block of document.children) {
2305
- if (isHeadingNode(block)) {
2306
- if (opened) return void 0;
2307
- opened = block.level === 1;
2308
- continue;
2309
- }
2310
- if (!opened || !isBlockquoteNode(block)) continue;
2311
- const text = normalizeSummary(block.children.filter(isParagraphNode).map((paragraph) => extractCellText(paragraph.children)).join(" "));
2312
- return text.length === 0 ? void 0 : text;
2313
- }
2314
- }
2315
- /**
2316
- * Computes the drift between one compared key's guide text and source text. A pair agrees
2317
- * only when both sides carry the same text, and every other state is a drift: guide text
2318
- * alone reports the guide's side, source text alone reports the source's, and neither side
2319
- * carrying text reports the key by itself. A side carrying no text is absent from the result,
2320
- * so a documented symbol with no doc block reports as a drift naming the guide's text alone,
2321
- * and a row a table has no `Summary` column for against a declaration with no doc block
2322
- * reports as `{ key }`.
2323
- *
2324
- * @param key - The compared pair's key
2325
- * @param category - The compared site the drift came from
2326
- * @param guide - The guide's text there, or `undefined` when it carries none
2327
- * @param source - The source's text there, or `undefined` when it carries none
2328
- * @returns The drift, or `undefined` when both sides carry the same text
2329
- *
2330
- * @example
2331
- * ```ts
2332
- * computeDrift('function walk', 'summary', 'Walks the tree.', 'Walks a tree.')
2333
- * // { key: 'function walk', category: 'summary', guide: 'Walks the tree.', source: 'Walks a tree.' }
2334
- * ```
2335
- */
2336
- function computeDrift(key, category, guide, source) {
2337
- if (guide !== void 0 && guide === source) return void 0;
2338
- return {
2339
- key,
2340
- category,
2341
- ...guide === void 0 ? {} : { guide },
2342
- ...source === void 0 ? {} : { source }
2343
- };
2344
- }
2345
- /**
2346
- * Compares documented and declared membership exactly after sorting copies, preserving duplicates.
2347
- *
2348
- * @param spec - The guide inventory key the finding belongs to
2349
- * @param name - The declaration whose membership is compared
2350
- * @param documented - The documented member names
2351
- * @param declared - The declared member names
2352
- * @returns The membership finding, or `undefined` when the sorted populations match
2353
- *
2354
- * @example Compare declaration membership
2355
- * ```ts
2356
- * import { compareMembership } from '@orkestrel/guide'
2357
- *
2358
- * compareMembership('guides/widget.md', 'WidgetInterface', ['open'], ['open']) // undefined
2359
- * ```
2360
- */
2361
- function compareMembership(spec, name, documented, declared) {
2362
- const left = [...documented].sort();
2363
- const right = [...declared].sort();
2364
- if (JSON.stringify(left) === JSON.stringify(right)) return void 0;
2365
- return {
2366
- spec,
2367
- text: `${spec} ${name} documents ${JSON.stringify(left)} and declares ${JSON.stringify(right)}.`
2368
- };
2369
- }
2370
- /**
2371
- * Computes a category-separated identity for a guide finding.
2372
- *
2373
- * @param spec - The guide inventory key the drift belongs to
2374
- * @param drift - The categorized disagreement
2375
- * @returns The inventory key, category, and compared key separated by line feeds
2376
- *
2377
- * @example Identify categorized drift
2378
- * ```ts
2379
- * import { identifyDrift } from '@orkestrel/guide'
2380
- *
2381
- * identifyDrift('guides/widget.md', { category: 'summary', key: 'function open' })
2382
- * // 'guides/widget.md\nsummary\nfunction open'
2383
- * ```
2384
- */
2385
- function identifyDrift(spec, drift) {
2386
- return `${spec}\n${drift.category}\n${drift.key}`;
2387
- }
2388
- /**
2389
- * Formats present parity text as a JSON string and absent text as `absent`.
2390
- *
2391
- * @param value - The compared side's text, or `undefined` when absent
2392
- * @returns The developer-facing side text
2393
- *
2394
- * @example Format a parity side
2395
- * ```ts
2396
- * import { formatSide } from '@orkestrel/guide'
2397
- *
2398
- * formatSide('Walks.') // '"Walks."'
2399
- * formatSide(undefined) // 'absent'
2400
- * ```
2401
- */
2402
- function formatSide(value) {
2403
- return value === void 0 ? "absent" : JSON.stringify(value);
2404
- }
2405
- /**
2406
- * Formats a categorized drift with its guide and source sides.
2407
- *
2408
- * @param drift - The categorized disagreement to format
2409
- * @returns The complete developer-facing drift text
2410
- *
2411
- * @example Format categorized drift
2412
- * ```ts
2413
- * import { formatDrift } from '@orkestrel/guide'
2414
- *
2415
- * formatDrift({ category: 'summary', key: 'function walk', guide: 'Walks.', source: 'Walks a tree.' })
2416
- * // 'summary function walk: guide "Walks." source "Walks a tree."'
2417
- * ```
2418
- */
2419
- function formatDrift(drift) {
2420
- return `${drift.category} ${drift.key}: guide ${formatSide(drift.guide)} source ${formatSide(drift.source)}`;
2421
- }
2422
- /**
2423
- * Finds every disagreement between a guide and the source it documents, naming both sites:
2424
- * each `## Surface` row against its declaration's description paragraph, each `## Methods`
2425
- * row against its member's, and the first titled guide fence of a heading against the
2426
- * `@example` block of the same title. An example's compared text is its language on the first
2427
- * line and its body beneath, so a fence that names another language drifts on its own.
2428
- *
2429
- * @remarks
2430
- * Only a pair present on both sides is compared, so a symbol, a member, or a title one side
2431
- * lacks entirely is left to the bijection checks that own it and is never reported twice.
2432
- * {@link computeDrift} rules each compared pair, so a pair whose sides carry different text, a
2433
- * pair where one side carries none, and a pair where neither side carries text are all drift.
2434
- * The pairing is per title across the whole document, not per heading: the first fence a title
2435
- * reaches is the compared one, and every later fence of that title is outside the comparison,
2436
- * whether it sits under the same heading or under a second heading of the same text.
2437
- *
2438
- * @param guide - The parsed guide
2439
- * @param source - The reflected source the guide documents
2440
- * @returns One entry per disagreement: Surface rows, then Methods rows, then examples
2441
- *
2442
- * @example
2443
- * ```ts
2444
- * findDrift(guide, source) // [{ key: 'function walk', category: 'summary', guide: 'Walks.', source: 'Walks a tree.' }]
2445
- * ```
2446
- */
2447
- function findDrift(guide, source) {
2448
- const drifts = [];
2449
- const declared = new Map(source.surface().map((symbol) => [computeSymbolKey(symbol), symbol]));
2450
- for (const symbol of guide.surface()) {
2451
- const key = computeSymbolKey(symbol);
2452
- const match = declared.get(key);
2453
- if (match === void 0) continue;
2454
- const drift = computeDrift(key, "summary", symbol.summary, match.summary);
2455
- if (drift !== void 0) drifts.push(drift);
2456
- }
2457
- for (const group of guide.methods()) {
2458
- const members = new Map(source.methods(group.interface).map((entry) => [entry.name, entry]));
2459
- for (const entry of group.methods) {
2460
- const member = members.get(entry.name);
2461
- if (member === void 0) continue;
2462
- const drift = computeDrift(`${group.interface}.${entry.name}`, "summary", entry.summary, member.summary);
2463
- if (drift !== void 0) drifts.push(drift);
2464
- }
2465
- }
2466
- const examples = collectTitles(guide, source);
2467
- const compared = /* @__PURE__ */ new Set();
2468
- for (const fence of guide.fences()) {
2469
- if (fence.title === void 0 || compared.has(fence.title)) continue;
2470
- compared.add(fence.title);
2471
- const example = examples.get(fence.title);
2472
- if (example === void 0) continue;
2473
- const drift = computeDrift(fence.title, "example", `${fence.language ?? ""}\n${fence.code}`, `${example.language ?? ""}\n${example.code}`);
2474
- if (drift !== void 0) drifts.push(drift);
2475
- }
2476
- return drifts;
2477
- }
2478
- /**
2479
- * Collects the titled `@example` blocks a guide's documented surface reaches — the module's
2480
- * exported declaration heads, plus the own members of every documented `class` and `interface` —
2481
- * keyed by title, the first block of a title answering for it.
2482
- *
2483
- * @param guide - The parsed guide naming the documented declarations
2484
- * @param source - The reflected source to read the blocks from
2485
- * @returns One entry per distinct `@example` title
2486
- *
2487
- * @example
2488
- * ```ts
2489
- * collectTitles(guide, source).get('Walk a tree') // { name: 'walk', title: 'Walk a tree', code: 'walk()' }
2490
- * ```
2491
- */
2492
- function collectTitles(guide, source) {
2493
- const titled = /* @__PURE__ */ new Map();
2494
- const owners = guide.surface().filter((symbol) => symbol.keyword === "class" || symbol.keyword === "interface");
2495
- const examples = [...source.examples(), ...owners.flatMap((symbol) => source.examples(symbol.name))];
2496
- for (const example of examples) {
2497
- if (example.title === void 0 || titled.has(example.title)) continue;
2498
- titled.set(example.title, example);
2499
- }
2500
- return titled;
2501
- }
2502
- /**
2503
- * Builds a copy of `table` with one cell's inline content rebuilt from `text` through
2504
- * {@link buildCell}. Every other cell keeps its own nodes, so a rewrite touches the one cell it
2505
- * names and the header and the alignment row travel unchanged.
2506
- *
2507
- * @param table - The table to copy
2508
- * @param row - The index of the row to rewrite within {@link TableNode.rows}
2509
- * @param column - The index of the cell to rewrite within that row
2510
- * @param text - The cell's new compared text
2511
- * @returns The rewritten table
2512
- *
2513
- * @example
2514
- * ```ts
2515
- * buildTable(table, 0, 2, 'Walks the tree.').rows[0]?.[2] // [{ element: 'text', value: 'Walks the tree.' }]
2516
- * ```
2517
- */
2518
- function buildTable(table, row, column, text) {
2519
- return {
2520
- element: "table",
2521
- header: table.header,
2522
- rows: table.rows.map((cells, index) => index === row ? cells.map((cell, position) => position === column ? buildCell(text) : cell) : cells),
2523
- align: table.align
2524
- };
2525
- }
2526
- /**
2527
- * Builds the fenced code block one `@example` block renders as — its code inside a fence
2528
- * carrying its language, and an untagged fence when the block names none.
2529
- *
2530
- * @param example - The block to render
2531
- * @returns The fence node
2532
- *
2533
- * @example
2534
- * ```ts
2535
- * buildFence({ name: 'walk', code: 'walk()', language: 'ts' }) // { element: 'codeBlock', code: 'walk()', lang: 'ts' }
2536
- * ```
2537
- */
2538
- function buildFence(example) {
2539
- return {
2540
- element: "codeBlock",
2541
- code: example.code,
2542
- ...example.language === void 0 ? {} : { lang: example.language }
2543
- };
2544
- }
2545
- /**
2546
- * Splices `replacement` into `source` over the region `span` addresses, and returns the result.
2547
- * The text before the region and the text after it travel byte for byte, so a rewrite that
2548
- * addresses one node's region changes nothing else in the document.
2549
- *
2550
- * @param source - The text to rewrite
2551
- * @param span - The half-open region to replace: the region `MarkdownInterface.span` reports
2552
- * for a markdown node, or the one {@link locateComment} reports for a doc block
2553
- * @param replacement - The text to write over that region
2554
- * @returns The rewritten text
2555
- *
2556
- * @example
2557
- * ```ts
2558
- * spliceSpan('one two three', { start: 4, end: 7 }, 'TWO') // 'one TWO three'
2559
- * ```
2560
- */
2561
- function spliceSpan(source, span, replacement) {
2562
- return source.slice(0, span.start) + replacement + source.slice(span.end);
2563
- }
2564
- /**
2565
- * Replaces one compared cell in a guide's text and returns the whole guide back. `key` names the
2566
- * row the way {@link findDrift} names it — a {@link computeSymbolKey} key for a `## Surface` row,
2567
- * an `Owner.member` key for a `## Methods` row — and the row's {@link SUMMARY} cell becomes
2568
- * `summary`. Only the table's own source region is rewritten, so every byte outside it travels
2569
- * unchanged; a key reaching no cell returns `undefined`, and a row already carrying the summary
2570
- * returns the guide byte for byte.
2571
- *
2572
- * @remarks
2573
- * A row the key does not reach, a table carrying no {@link SUMMARY} column, and a document whose
2574
- * parse recorded no region for the table are each a miss, and a miss returns `undefined` rather
2575
- * than throwing, so a caller reports the key it could not place — the one meaning `undefined`
2576
- * carries in every replacer here. A row already carrying `summary` returns the guide byte for
2577
- * byte, because a rewrite would re-pad the whole table for no change; that identity reads both
2578
- * sides through {@link normalizeSummary}, so a caller passing text the compared form still moves
2579
- * is a fixed point on the second run rather than a row rewritten forever. The rewritten table
2580
- * renders one-space padded whatever padding it carried, so the checkout's formatter re-aligns it.
2581
- *
2582
- * @param guide - The guide's markdown source
2583
- * @param key - The compared key naming the row
2584
- * @param summary - The row's new compared text
2585
- * @returns The guide's text with that cell replaced, or `undefined` when the key reaches no cell
2586
- *
2587
- * @example
2588
- * ```ts
2589
- * replaceCell('## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks. |', 'function walk', 'Walks a tree.')
2590
- * // '## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks a tree. |'
2591
- * ```
2592
- */
2593
- function replaceCell(guide, key, summary) {
2594
- const markdown = createMarkdown(guide);
2595
- const document = markdown.document;
2596
- let located;
2597
- let index = -1;
2598
- for (const block of selectSectionBlocks(document, SURFACE)) {
2599
- if (located !== void 0 || !isTableNode(block)) continue;
2600
- for (let row = 0; row < block.rows.length && located === void 0; row += 1) {
2601
- const symbol = extractRowSymbol(block, row);
2602
- if (symbol === void 0 || computeSymbolKey(symbol) !== key) continue;
2603
- located = block;
2604
- index = row;
2605
- }
2606
- }
2607
- for (const [table, owner] of collectGroups(document)) {
2608
- if (located !== void 0) break;
2609
- for (let row = 0; row < table.rows.length && located === void 0; row += 1) {
2610
- const entry = extractRowEntry(table, row);
2611
- if (entry === void 0 || `${owner}.${entry.name}` !== key) continue;
2612
- located = table;
2613
- index = row;
2614
- }
2615
- }
2616
- if (located === void 0) return void 0;
2617
- const column = findColumnIndex(located, SUMMARY);
2618
- if (column === void 0) return void 0;
2619
- if ((extractRowSummary(located, index) ?? "") === normalizeSummary(summary)) return guide;
2620
- const span = markdown.span(located);
2621
- if (span === void 0) return void 0;
2622
- return spliceSpan(guide, span, renderMarkdown(buildTable(located, index, column, summary)));
2623
- }
2624
- /**
2625
- * Replaces one titled fence in a guide's text and returns the whole guide back. The first fence
2626
- * carrying `title` — the pairing {@link findDrift} compares on — takes `example`'s language and
2627
- * code. Only the fence's own source region is rewritten, so every byte outside it travels
2628
- * unchanged; a title no fence carries returns `undefined`, and a fence already carrying that
2629
- * body returns the guide byte for byte.
2630
- *
2631
- * @remarks
2632
- * A title no fence carries and a document whose parse recorded no region for the fence are each a
2633
- * miss, and a miss returns `undefined` rather than throwing — the one meaning `undefined` carries
2634
- * in every replacer here. A fence already carrying that language and code returns the guide
2635
- * byte for byte. A later fence of the same title is outside the pairing and is never rewritten,
2636
- * which is the rule {@link findDrift} compares under.
2637
- *
2638
- * @param guide - The guide's markdown source
2639
- * @param title - The heading text the fence pairs on
2640
- * @param example - The block whose language and code the fence takes
2641
- * @returns The guide's text with that fence replaced, or `undefined` when no fence carries the title
2642
- *
2643
- * @example
2644
- * ```ts
2645
- * replaceFence(guide, 'Walk', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2646
- * // the guide's text with the fence under its `### Walk` heading carrying `walk()`
2647
- * ```
2648
- */
2649
- function replaceFence(guide, title, example) {
2650
- const markdown = createMarkdown(guide);
2651
- let located;
2652
- let current;
2653
- for (const [node, fence] of collectFences(markdown.document)) {
2654
- if (located !== void 0 || fence.title !== title) continue;
2655
- located = node;
2656
- current = fence;
2657
- }
2658
- if (located === void 0 || current === void 0) return void 0;
2659
- if (current.code === example.code && current.language === example.language) return guide;
2660
- const span = markdown.span(located);
2661
- if (span === void 0) return void 0;
2662
- return spliceSpan(guide, span, renderMarkdown(buildFence(example)));
2663
- }
2664
- /**
2665
- * Replaces one doc block's description paragraph with `summary` and returns the whole block back.
2666
- * The paragraph is the block's text before its first block tag, and it re-wraps inside `width`;
2667
- * the blank line before the first tag, every tag line, the block's indentation, and its
2668
- * continuation markers all survive. A block already carrying the summary returns byte for byte,
2669
- * and a text that is no doc block and a summary carrying no word each return `undefined`.
2670
- *
2671
- * @remarks
2672
- * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2673
- * caller reports the block it could not rewrite. Text that opens with no
2674
- * `/**` is no doc block: a single-star `/*` comment reaches this function only by a caller's
2675
- * mistake, and reshaping it into a doc block would be a silent edit. A `summary` carrying no word
2676
- * names no paragraph to write, and deleting the block's description on that argument would erase
2677
- * documentation on the strength of an absent value — a caller with nothing to write writes
2678
- * nothing.
2679
- *
2680
- * A block already carrying `summary` returns byte for byte, which is what keeps a propagation
2681
- * that finds no drift from rewriting the file: a doc block's own wrapping is not recoverable from
2682
- * its text, so re-wrapping an unchanged paragraph would move most blocks this package's source
2683
- * carries. That identity reads both sides through {@link normalizeSummary}, and it holds for a
2684
- * block carrying no tag as much as for a block carrying several. A block written on one physical
2685
- * line stays on one line while `summary` still fits inside `width`, and expands otherwise.
2686
- *
2687
- * `width` counts characters from the line's first, a tab counting as one, so a wrapped line reads
2688
- * `${indent} * ${text}` and never passes that count. A caller whose formatter measures a tab as
2689
- * more than one column passes a smaller width rather than taking the default.
2690
- *
2691
- * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2692
- * @param summary - The block's new description paragraph
2693
- * @param width - The character budget a re-wrapped line stays inside. Default: {@link WRAP_WIDTH}
2694
- * @returns The block's raw text with that paragraph replaced, or `undefined` for a text that is
2695
- * no doc block and for a `summary` carrying no word
2696
- *
2697
- * @example
2698
- * ```ts
2699
- * replaceSummary('/**' + ' Walks. *' + '/', 'Walks a tree.') // '/**' + ' Walks a tree. *' + '/'
2700
- * ```
2701
- */
2702
- function replaceSummary(comment, summary, width = 100) {
2703
- if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2704
- const content = unwrapComment(comment);
2705
- const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2706
- const wrapped = wrapText(summary, width - indent.length - 3);
2707
- if (wrapped.length === 0) return void 0;
2708
- const masked = maskFences(content.join("\n")).split("\n");
2709
- let tag = -1;
2710
- for (let index = 0; index < masked.length && tag < 0; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) tag = index;
2711
- if (normalizeSummary(content.slice(0, tag < 0 ? content.length : tag).join("\n")) === normalizeSummary(summary)) return comment;
2712
- const tail = tag < 0 ? [] : content.slice(tag);
2713
- if (tail.length === 0 && wrapped.length === 1 && content.length === 1) {
2714
- const single = `${indent}/** ${wrapped[0] ?? ""} */`;
2715
- if (single.length <= width) return single;
2716
- }
2717
- const lines = [...wrapped];
2718
- if (tail.length > 0) lines.push("");
2719
- return buildComment([...lines, ...tail], indent);
2720
- }
2721
- /**
2722
- * Replaces the body of one titled `@example` tag in a doc block's raw text and returns the whole
2723
- * block back. The tag carrying `example`'s title takes a fence of its language and its code;
2724
- * every other tag, the description paragraph, the block's indentation, and its continuation
2725
- * markers all survive. A text that is no doc block, a title no tag carries, and a language or
2726
- * code the emitted three-backtick fence cannot enclose or the doc block cannot hold each return
2727
- * `undefined`.
2728
- *
2729
- * @remarks
2730
- * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2731
- * caller reports the block it could not rewrite. Text that opens with no
2732
- * `/**` is no doc block, for the reason {@link replaceSummary} states. A block carrying no
2733
- * `@example` tag of that title has nowhere to write, so an untitled tag and a tag carrying
2734
- * another title are each left alone, and an `example` naming no title misses a block whose tags
2735
- * all carry one. Code carrying a run of three or more backticks is a body the emitted fence
2736
- * cannot enclose: the fence is three backticks, {@link maskFences} ends a body at the first line
2737
- * opening a run at least as long, and {@link collectExamples} reads to the first such run
2738
- * whatever column it sits at, so writing that body would truncate it and turn a following
2739
- * `@`-line into a tag. A language or code carrying the doc-comment terminator is a body the
2740
- * block itself cannot hold: the terminator closes the block where it lands and the file stops
2741
- * parsing there. Refusing keeps the rewrite total over the bodies it can spell.
2742
- *
2743
- * A tag already carrying that language and code returns byte for byte. {@link maskFences} keeps
2744
- * the current body's own lines out of the tag search, so a fenced body carrying a tag-shaped line
2745
- * does not end the body early. The body ends at its last line carrying text, so the blank line
2746
- * separating it from the next tag survives.
2747
- *
2748
- * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2749
- * @param example - The block whose language and code the tag's body takes
2750
- * @returns The block's raw text with that body replaced, or `undefined` for a text that is no
2751
- * doc block, for a title no `@example` tag carries, and for a language or code the emitted
2752
- * fence cannot enclose or the doc block cannot hold — a body carrying the doc-comment terminator
2753
- *
2754
- * @example
2755
- * ```ts
2756
- * replaceExample('/**' + '\n * @example Walk\n * old()\n *' + '/', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2757
- * // the same block, its `@example Walk` body now a fence tagged `ts` carrying `walk()`
2758
- * ```
2759
- */
2760
- function replaceExample(comment, example) {
2761
- if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2762
- if ([example.language ?? "", ...example.code.split("\n")].some((line) => line.includes("```") || line.includes("*/"))) return void 0;
2763
- const content = unwrapComment(comment);
2764
- const masked = maskFences(content.join("\n")).split("\n");
2765
- const title = example.title ?? "";
2766
- let start = -1;
2767
- for (let index = 0; index < masked.length && start < 0; index += 1) {
2768
- const tag = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/.exec(masked[index] ?? "");
2769
- if (tag !== null && (tag[1] ?? "").trim() === title) start = index;
2770
- }
2771
- if (start < 0) return void 0;
2772
- const current = collectExamples(content.join("\n"), example.name).find((entry) => (entry.title ?? "") === title);
2773
- if (current !== void 0 && current.code === example.code && current.language === example.language) return comment;
2774
- let end = content.length;
2775
- for (let index = start + 1; index < masked.length && end === content.length; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) end = index;
2776
- while (end > start + 1 && (content[end - 1] ?? "").length === 0) end -= 1;
2777
- const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2778
- const body = [
2779
- `\`\`\`${example.language ?? ""}`,
2780
- ...example.code.split("\n"),
2781
- "```"
2782
- ];
2783
- return buildComment([
2784
- ...content.slice(0, start + 1),
2785
- ...body,
2786
- ...content.slice(end)
2787
- ], indent);
2788
- }
2789
- /**
2790
- * Locates the doc block a compared key attaches to inside one file's text and returns the block's
2791
- * own character region, so a caller can `slice` the block, rewrite it through
2792
- * {@link replaceSummary} or {@link replaceExample}, and write the result back through
2793
- * {@link spliceSpan}. `key` names the pair the way {@link findDrift} names it — a
2794
- * {@link computeSymbolKey} key for a declaration, an `Owner.member` key for an interface or class
2795
- * member; the region covers the block's own indentation, and no block carrying the key returns
2796
- * `undefined`.
2797
- *
2798
- * @remarks
2799
- * Attachment is {@link extractSourceComments}'s, not a second reading of the file: that walk
2800
- * pairs each eligible block with the physical record it documents, and this function keeps the
2801
- * record {@link collectKeys} gives `key`. The keys are that one grammar's — the map
2802
- * {@link extractExports} and {@link extractMemberMethods} each read their own part out of — so
2803
- * this function runs no head pattern, no member pattern, and no owner-close rule of its own, and
2804
- * a change to any of them reaches the locator too. Every block {@link collectSummaries} reports
2805
- * a summary for is reachable by its key, and a block carrying only block tags is reachable too although it carries no summary.
2806
- * A block it misses is one the comparison never had: a block a blank line separates from its
2807
- * declaration attaches to the blank line, and a block written inside a template literal or a
2808
- * string is no genuine span at all. The first block whose record carries the key answers for it,
2809
- * as the first declaration of a name does everywhere else.
2810
- *
2811
- * The region runs from the start of the opener's line, the block's indentation included, to the
2812
- * character past its closing marker — the raw text {@link replaceSummary} and
2813
- * {@link replaceExample} each document as the span "as it sits in the file", so a caller slices,
2814
- * rewrites, and splices with no adjustment and the rewrite keeps the indentation it found. A
2815
- * block that source material precedes on its own line starts at the opener instead. The region
2816
- * is read off the aligned JSDoc projection rather than searched for in the text, so an opener
2817
- * written inside a string never yields one, and line offsets come from
2818
- * {@link extractSourceLines}'s own records under its stated LF-or-CRLF terminator rule, so a
2819
- * CRLF file reports the offsets its own bytes carry.
2820
- *
2821
- * @param text - One file's whole source text
2822
- * @param key - The compared key naming the declaration or the member
2823
- * @returns The block's half-open character region, or `undefined` when no block carries the key
2824
- *
2825
- * @example
2826
- * ```ts
2827
- * const text = '/**' + ' Walks. *' + '/\nexport function walk(): void {}\n'
2828
- * locateComment(text, 'function walk') // { start: 0, end: 13 }
2829
- * ```
2830
- */
2831
- function locateComment(text, key) {
2832
- const lines = extractSourceLines(text);
2833
- const keys = collectKeys(lines);
2834
- const offsets = [];
2835
- const positions = /* @__PURE__ */ new Map();
2836
- let offset = 0;
2837
- for (let index = 0; index < lines.length; index += 1) {
2838
- const line = lines[index];
2839
- if (line === void 0) continue;
2840
- offsets.push(offset);
2841
- positions.set(line, index);
2842
- const after = offset + line.source.length;
2843
- offset = after + (text.startsWith("\r\n", after) ? 2 : 1);
2844
- }
2845
- for (const comment of extractSourceComments(lines)) {
2846
- if (keys.get(comment.line) !== key) continue;
2847
- const close = (positions.get(comment.line) ?? 0) - 1;
2848
- const closing = lines[close]?.jsdoc;
2849
- const end = closing === void 0 ? -1 : closing.lastIndexOf("*/");
2850
- if (end < 0) continue;
2851
- let first = close;
2852
- while (first > 0 && lines[first - 1]?.jsdoc !== void 0) first -= 1;
2853
- let inside = false;
2854
- let line = -1;
2855
- let column = -1;
2856
- for (let index = first; index <= close; index += 1) {
2857
- const projection = lines[index]?.jsdoc ?? "";
2858
- let cursor = 0;
2859
- while (cursor < projection.length) {
2860
- const at = projection.indexOf(inside ? "*/" : "/**", cursor);
2861
- if (at < 0) break;
2862
- if (!inside) {
2863
- line = index;
2864
- column = at;
2865
- }
2866
- cursor = at + (inside ? 2 : 3);
2867
- inside = !inside;
2868
- }
2869
- }
2870
- if (line < 0) continue;
2871
- const start = (lines[line]?.source ?? "").slice(0, column).trim() === "" ? 0 : column;
2872
- return {
2873
- start: (offsets[line] ?? 0) + start,
2874
- end: (offsets[close] ?? 0) + end + 2
2875
- };
2876
- }
2877
- }
2878
- //#endregion
2879
- //#region src/core/Guide.ts
2880
- /**
2881
- * Presents a pure, structured view over one parsed guide — the documented
2882
- * projections (`sections` / `tagline` / `surface` / `methods` / `unnamed` / `links` /
2883
- * `tests` / `fences`) are extracted once at construction and cached.
2884
- *
2885
- * @remarks
2886
- * Parses `source` once through `@orkestrel/markdown` and never touches the
2887
- * filesystem — `Guide` reads only the markdown text it is given and records
2888
- * nothing about where the guide came from. Every accessor returns the same
2889
- * cached, readonly array on every call.
2890
- *
2891
- * @example
2892
- * ```ts
2893
- * import { Guide } from '@orkestrel/guide'
2894
- *
2895
- * const guide = new Guide('## Surface\n\n| Name | Kind |\n| --- | --- |\n| `X` | class |')
2896
- * guide.surface() // [{ name: 'X', keyword: 'class' }]
2897
- * ```
2898
- */
2899
- var Guide = class {
2900
- #sections;
2901
- #tagline;
2902
- #surface;
2903
- #methods;
2904
- #unnamed;
2905
- #links;
2906
- #tests;
2907
- #fences;
2908
- constructor(source) {
2909
- const document = createMarkdown(source).document;
2910
- this.#sections = document.children.filter(isHeadingNode).filter((heading) => heading.level === 2).map((heading) => flattenText(heading).trim());
2911
- this.#tagline = extractTagline(document);
2912
- this.#surface = extractSurface(document);
2913
- this.#methods = extractMethods(document);
2914
- this.#unnamed = extractUnnamed(document);
2915
- this.#links = extractLinks(document);
2916
- this.#tests = extractTests(document);
2917
- this.#fences = extractFences(document);
2918
- }
2919
- sections() {
2920
- return this.#sections;
2921
- }
2922
- tagline() {
2923
- return this.#tagline;
2924
- }
2925
- surface() {
2926
- return this.#surface;
2927
- }
2928
- methods() {
2929
- return this.#methods;
2930
- }
2931
- unnamed() {
2932
- return this.#unnamed;
2933
- }
2934
- links() {
2935
- return this.#links;
2936
- }
2937
- tests() {
2938
- return this.#tests;
2939
- }
2940
- fences() {
2941
- return this.#fences;
2942
- }
2943
- };
2944
- //#endregion
2945
- //#region src/core/sources/Source.ts
2946
- /**
2947
- * Reflects, as a pure `SourceInterface`, a module scope's intentional direct declarations,
2948
- * conventional barrel-reachable surface, and member methods over a consumer-supplied file
2949
- * inventory, using text-only line scanners rather than the TypeScript compiler API or the
2950
- * filesystem. `Source` never touches disk:
2951
- * the consumer gathers the inventory however their environment allows
2952
- * (`node:fs` in a Node script, `import.meta.glob` in a browser/vitest run) and
2953
- * passes it in as `files`.
2954
- *
2955
- * @remarks
2956
- * Conventional barrel traversal recurses through both
2957
- * exact workspace-root `index.ts` and nested `/index.ts` targets. `'.'` is the
2958
- * canonical workspace-root module, module spellings normalize once at
2959
- * construction, and exact opaque inventory keys are never rewritten; keys with
2960
- * empty, `.` or `..` segments stay outside both initial and resolved barrel
2961
- * inventory entrances after relative-row reduction; canonical parent hops
2962
- * remain valid. `methods` resolves a declaration's members through its
2963
- * `extends` chain within the same module scope, keeping the keyword it started
2964
- * from; a base the scope does not declare contributes nothing. One declaration
2965
- * answers under each keyword: the first file in sorted key order that declares
2966
- * the head supplies its members and its bases, and a second file declaring the
2967
- * same name under that keyword adds nothing. The interface answers for a name,
2968
- * and the class when no interface declares it; one file declaring the name as
2969
- * both shapes, a TypeScript declaration merge, answers with both, own members
2970
- * ahead of inherited ones and the interface's own first. Every reading derives once per instance from the immutable
2971
- * inventory and is reused — the scope's declaration map on the first `methods`
2972
- * or `examples` lookup, then each name's members and each example collection
2973
- * under the name asked for — so a reader asking twice reads the files once and
2974
- * receives the same records, and a second instance over the same inventory
2975
- * derives the same readings of its own. Source projection preserves columns
2976
- * without widening direct/hidden column-zero heads. Literal ECMAScript Unicode
2977
- * identifiers participate in bounded slash-state recognition without escape
2978
- * decoding. Regex recognition is bounded: slash after bare `}` is division, so
2979
- * a post-brace regex statement requires an explicit `;`. General semicolonless
2980
- * declaration/ASI classification is also outside the finite projector, so a
2981
- * slash-leading statement after such a declaration requires an explicit `;`.
2982
- *
2983
- * @example
2984
- * ```ts
2985
- * import { Source } from '@orkestrel/guide'
2986
- *
2987
- * const source = new Source({
2988
- * files: {
2989
- * 'src/core/index.ts': "export * from './Guide.js'\nexport * from './types.js'\n",
2990
- * 'src/core/Guide.ts': 'export class Guide {}\n',
2991
- * 'src/core/types.ts': 'export interface GuideInterface {\n\tsections(): void\n}\n',
2992
- * },
2993
- * module: 'src/core',
2994
- * })
2995
- * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
2996
- * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
2997
- * source.methods('GuideInterface') // [{ name: 'sections' }]
2998
- * source.exists('src/core/Guide.ts') // true
2999
- * ```
3000
- */
3001
- var Source = class {
3002
- #files;
3003
- #directories;
3004
- #methods = /* @__PURE__ */ new Map();
3005
- #examples = /* @__PURE__ */ new Map();
3006
- #exports;
3007
- #surface;
3008
- #hidden;
3009
- #declarations;
3010
- #origins = /* @__PURE__ */ new Map();
3011
- constructor(options) {
3012
- this.#files = options.files;
3013
- this.#directories = normalizeDirectories(options.module);
3014
- }
3015
- exports() {
3016
- if (this.#exports === void 0) this.#exports = this.#scanSymbols(extractExports);
3017
- return this.#exports;
3018
- }
3019
- surface() {
3020
- if (this.#surface === void 0) this.#surface = this.#scanSurface();
3021
- return this.#surface;
3022
- }
3023
- methods(name) {
3024
- const cached = this.#methods.get(name);
3025
- if (cached !== void 0) return cached;
3026
- const members = this.#scanMethods(name);
3027
- this.#methods.set(name, members);
3028
- return members;
3029
- }
3030
- exists(relative) {
3031
- return Object.keys(this.#files).some((key) => key === relative || key.startsWith(`${relative}/`));
3032
- }
3033
- hidden() {
3034
- if (this.#hidden === void 0) this.#hidden = this.#scanSymbols(extractHidden);
3035
- return this.#hidden;
3036
- }
3037
- examples(name) {
3038
- const cached = this.#examples.get(name);
3039
- if (cached !== void 0) return cached;
3040
- const examples = name === void 0 ? this.#scanExamples() : this.#exampleMembers(name);
3041
- this.#examples.set(name, examples);
3042
- return examples;
3043
- }
3044
- #scanMethods(name) {
3045
- const fromInterface = this.#members("interface", name, /* @__PURE__ */ new Set());
3046
- const fromClass = this.#members("class", name, /* @__PURE__ */ new Set())?.filter((entry) => entry.name !== "constructor");
3047
- const origin = this.#origin("interface", name);
3048
- if (origin === void 0 || origin !== this.#origin("class", name)) return fromInterface ?? fromClass ?? [];
3049
- const methods = /* @__PURE__ */ new Map();
3050
- for (const entry of [
3051
- ...extractMemberMethods(this.#locate("interface", name)?.body ?? []),
3052
- ...extractMemberMethods(this.#locate("class", name)?.body ?? []),
3053
- ...fromInterface ?? [],
3054
- ...fromClass ?? []
3055
- ]) if (entry.name !== "constructor" && !methods.has(entry.name)) methods.set(entry.name, entry);
3056
- return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3057
- }
3058
- #scanExamples() {
3059
- const examples = [];
3060
- const seen = /* @__PURE__ */ new Set();
3061
- for (const key of selectModuleKeys(this.#files, this.#directories)) {
3062
- const text = this.#files[key];
3063
- if (text === void 0) continue;
3064
- for (const example of extractExamples(text)) {
3065
- const identity = `${example.name}\n${example.title ?? ""}`;
3066
- if (seen.has(identity)) continue;
3067
- seen.add(identity);
3068
- examples.push(example);
3069
- }
3070
- }
3071
- return examples;
3072
- }
3073
- #scanSurface() {
3074
- const symbols = [];
3075
- const seen = /* @__PURE__ */ new Set();
3076
- const visited = /* @__PURE__ */ new Set();
3077
- for (const directory of this.#directories) this.#collectSurface(resolvePath(directory, "index.ts"), visited, symbols, seen);
3078
- return symbols.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3079
- }
3080
- #collectSurface(index, visited, symbols, seen) {
3081
- if (!hasCanonicalSegments(index)) return;
3082
- if (visited.has(index)) return;
3083
- visited.add(index);
3084
- const source = this.#files[index];
3085
- if (source === void 0) return;
3086
- for (const line of extractSourceLines(source)) {
3087
- const row = line.code.match(/^\s*export\s+\*\s+from\s+(?:'(\.\.?\/[^']+\.js)'|"(\.\.?\/[^"]+\.js)")\s*;?\s*(?:\/\/.*)?$/);
3088
- const target = row?.[1] ?? row?.[2];
3089
- if (target === void 0) continue;
3090
- const path = resolveLink(index, `${target.slice(0, -3)}.ts`);
3091
- if (!hasCanonicalSegments(path)) continue;
3092
- if (path === "index.ts" || path.endsWith("/index.ts")) {
3093
- this.#collectSurface(path, visited, symbols, seen);
3094
- continue;
3095
- }
3096
- if (visited.has(path)) continue;
3097
- visited.add(path);
3098
- const text = this.#files[path];
3099
- if (text === void 0) continue;
3100
- for (const symbol of extractExports(text)) {
3101
- const identity = computeSymbolKey(symbol);
3102
- if (seen.has(identity)) continue;
3103
- seen.add(identity);
3104
- symbols.push(symbol);
3105
- }
3106
- }
3107
- }
3108
- #exampleMembers(name) {
3109
- const members = /* @__PURE__ */ new Map();
3110
- for (const example of [...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]) {
3111
- const identity = `${example.name}\n${example.title ?? ""}`;
3112
- if (members.has(identity)) continue;
3113
- members.set(identity, example);
3114
- }
3115
- return Array.from(members.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3116
- }
3117
- #scanSymbols(scan) {
3118
- const symbols = [];
3119
- const seen = /* @__PURE__ */ new Set();
3120
- for (const key of selectModuleKeys(this.#files, this.#directories)) {
3121
- const text = this.#files[key];
3122
- if (text === void 0) continue;
3123
- for (const symbol of scan(text)) {
3124
- const identity = computeSymbolKey(symbol);
3125
- if (seen.has(identity)) continue;
3126
- seen.add(identity);
3127
- symbols.push(symbol);
3128
- }
3129
- }
3130
- return symbols.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3131
- }
3132
- #members(keyword, name, visited) {
3133
- if (visited.has(name)) return [];
3134
- visited.add(name);
3135
- const declaration = this.#locate(keyword, name);
3136
- if (declaration === void 0) return void 0;
3137
- const methods = /* @__PURE__ */ new Map();
3138
- for (const entry of extractMemberMethods(declaration.body)) methods.set(entry.name, entry);
3139
- for (const base of declaration.bases) for (const member of this.#members(keyword, base, visited) ?? []) if (!methods.has(member.name)) methods.set(member.name, member);
3140
- return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
3141
- }
3142
- #locate(keyword, name) {
3143
- if (this.#declarations === void 0) this.#declarations = this.#scanDeclarations();
3144
- return this.#declarations.get(`${keyword} ${name}`);
3145
- }
3146
- #origin(keyword, name) {
3147
- return this.#locate(keyword, name) === void 0 ? void 0 : this.#origins.get(`${keyword} ${name}`);
3148
- }
3149
- #scanDeclarations() {
3150
- const declarations = /* @__PURE__ */ new Map();
3151
- for (const key of selectModuleKeys(this.#files, this.#directories)) {
3152
- const text = this.#files[key];
3153
- if (text === void 0) continue;
3154
- for (const [identity, declaration] of collectDeclarations(text)) {
3155
- if (declarations.has(identity)) continue;
3156
- if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
3157
- declarations.set(identity, declaration);
3158
- this.#origins.set(identity, key);
3159
- }
3160
- }
3161
- return declarations;
3162
- }
3163
- };
3164
- //#endregion
3165
- //#region src/core/sources/SourceManager.ts
3166
- /**
3167
- * Resolves a consumer-owned import-specifier policy into pure source views and
3168
- * caches those views by module, so aliases for one module share one entity.
3169
- * Unmapped specifiers remain foreign to the consumer and return `undefined`.
3170
- * `sources()` enumerates the same shared views, one per distinct module the
3171
- * policy maps.
3172
- *
3173
- * @example
3174
- * ```ts
3175
- * import { SourceManager } from '@orkestrel/guide'
3176
- *
3177
- * const sources = new SourceManager({
3178
- * files: { 'src/core/index.ts': "export * from './types.js'" },
3179
- * modules: { '@scope/package': 'src/core' },
3180
- * })
3181
- * sources.source('@scope/package')?.surface()
3182
- * sources.sources() // [the same shared view]
3183
- * ```
3184
- */
3185
- var SourceManager = class {
3186
- #files;
3187
- #modules;
3188
- #sources = /* @__PURE__ */ new Map();
3189
- constructor(options) {
3190
- this.#files = options.files;
3191
- this.#modules = options.modules;
3192
- }
3193
- source(specifier) {
3194
- if (!Object.hasOwn(this.#modules, specifier)) return void 0;
3195
- const module = this.#modules[specifier];
3196
- if (module === void 0) return void 0;
3197
- const key = computeModuleKey(module);
3198
- const existing = this.#sources.get(key);
3199
- if (existing !== void 0) return existing;
3200
- const source = new Source({
3201
- files: this.#files,
3202
- module
3203
- });
3204
- this.#sources.set(key, source);
3205
- return source;
3206
- }
3207
- sources() {
3208
- const views = [];
3209
- const seen = /* @__PURE__ */ new Set();
3210
- for (const specifier of Object.keys(this.#modules)) {
3211
- const view = this.source(specifier);
3212
- if (view === void 0 || seen.has(view)) continue;
3213
- seen.add(view);
3214
- views.push(view);
3215
- }
3216
- return views;
3217
- }
3218
- };
3219
- //#endregion
3220
- //#region src/core/Parity.ts
3221
- /**
3222
- * Composes generic guide-parity inspection and explicit in-memory rewrites over a caller inventory.
3223
- */
3224
- var Parity = class Parity {
3225
- #options;
3226
- #rows;
3227
- constructor(options) {
3228
- this.#options = {
3229
- files: { ...options.files },
3230
- entries: options.entries.map((entry) => ({ ...entry })),
3231
- modules: { ...options.modules },
3232
- languages: [...options.languages],
3233
- language: options.language,
3234
- ...options.pitch === void 0 ? {} : { pitch: { ...options.pitch } }
3235
- };
3236
- this.#rows = this.#createRows(this.#options.files);
3237
- }
3238
- rows() {
3239
- return this.#rows;
3240
- }
3241
- inspect() {
3242
- const input = [];
3243
- const sections = [];
3244
- const surface = [];
3245
- const methods = [];
3246
- const declarations = [];
3247
- const links = [];
3248
- const tests = [];
3249
- const fences = [];
3250
- const exampleFences = [];
3251
- const exampleFunctions = [];
3252
- const exampleMethods = [];
3253
- const exampleTitles = [];
3254
- const examples = {
3255
- fences: exampleFences,
3256
- functions: exampleFunctions,
3257
- methods: exampleMethods,
3258
- titles: exampleTitles
3259
- };
3260
- const imports = [];
3261
- const drift = [];
3262
- const pitch = [];
3263
- this.#inspectInput(input);
3264
- for (const row of this.#rows) {
3265
- this.#inspectSections(row, sections);
3266
- this.#inspectSurface(row, surface);
3267
- this.#inspectMethods(row, methods);
3268
- this.#inspectDeclarations(row, declarations);
3269
- this.#inspectLinks(row, links, tests);
3270
- this.#inspectFences(row, fences);
3271
- this.#inspectExamples(row, exampleFences, exampleFunctions, exampleMethods, exampleTitles);
3272
- this.#inspectImports(row, imports);
3273
- this.#inspectDrift(row, drift);
3274
- }
3275
- this.#inspectPitch(pitch);
3276
- return {
3277
- input,
3278
- sections,
3279
- surface,
3280
- methods,
3281
- declarations,
3282
- links,
3283
- tests,
3284
- fences,
3285
- examples,
3286
- imports,
3287
- drift,
3288
- pitch
3289
- };
3290
- }
3291
- document() {
3292
- return this.#rewrite((row, drift, files) => this.#rewriteGuide(row, drift, files));
3293
- }
3294
- annotate() {
3295
- return this.#rewrite((row, drift, files) => this.#rewriteSource(row, drift, files));
3296
- }
3297
- #rewrite(apply) {
3298
- const files = new Map(Object.entries(this.#options.files));
3299
- const reasons = /* @__PURE__ */ new Map();
3300
- const requested = /* @__PURE__ */ new Set();
3301
- for (const row of this.#rows) for (const drift of findDrift(row.guide, row.source)) {
3302
- const identity = identifyDrift(row.entry.spec, drift);
3303
- requested.add(identity);
3304
- const reason = apply(row, drift, files);
3305
- if (reason !== void 0) reasons.set(identity, reason);
3306
- }
3307
- const inventory = Object.fromEntries(files);
3308
- const remaining = [];
3309
- const result = new Parity({
3310
- ...this.#options,
3311
- files: inventory
3312
- });
3313
- remaining.push(...result.inspect().input);
3314
- for (const row of result.rows()) for (const drift of findDrift(row.guide, row.source)) {
3315
- const identity = identifyDrift(row.entry.spec, drift);
3316
- if (!requested.has(identity)) continue;
3317
- remaining.push({
3318
- spec: row.entry.spec,
3319
- text: `${formatDrift(drift)}; ${reasons.get(identity) ?? "the requested destination still disagrees"}`
3320
- });
3321
- }
3322
- return {
3323
- changes: Array.from(files.entries()).filter(([path, content]) => this.#options.files[path] !== content).sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
3324
- path,
3325
- content
3326
- })),
3327
- findings: remaining
3328
- };
3329
- }
3330
- #createRows(files) {
3331
- const rows = [];
3332
- for (const entry of this.#options.entries) {
3333
- const text = files[entry.spec];
3334
- if (text === void 0) continue;
3335
- rows.push({
3336
- entry,
3337
- guide: new Guide(text),
3338
- source: new Source({
3339
- files,
3340
- module: entry.source
3341
- })
3342
- });
3343
- }
3344
- return rows;
3345
- }
3346
- #inspectInput(findings) {
3347
- if (this.#options.entries.length === 0) findings.push({ text: "The manifest has no guide entries." });
3348
- for (const entry of this.#options.entries) {
3349
- if (this.#options.files[entry.spec] !== void 0) continue;
3350
- findings.push({
3351
- spec: entry.spec,
3352
- text: `${entry.spec} is absent from the inventory.`
3353
- });
3354
- }
3355
- }
3356
- #inspectSections(row, findings) {
3357
- const sections = row.guide.sections();
3358
- for (const heading of [
3359
- SURFACE,
3360
- METHODS,
3361
- TESTS
3362
- ]) {
3363
- if (sections.includes(heading)) continue;
3364
- findings.push({
3365
- spec: row.entry.spec,
3366
- text: `${row.entry.spec} has no ## ${heading} section.`
3367
- });
3368
- }
3369
- if (row.guide.methods().length === 0 && hasBehaviouralSurface(row.source)) findings.push({
3370
- spec: row.entry.spec,
3371
- text: `${row.entry.spec} has no documented method groups.`
3372
- });
3373
- }
3374
- #inspectSurface(row, findings) {
3375
- if (row.guide.surface().length === 0) findings.push({
3376
- spec: row.entry.spec,
3377
- text: `${row.entry.spec} has no documented surface.`
3378
- });
3379
- for (const unnamed of row.guide.unnamed()) findings.push({
3380
- spec: row.entry.spec,
3381
- text: `${row.entry.spec} has an unnamed row: ${unnamed}`
3382
- });
3383
- for (const key of findMissingSymbols(row.source.exports(), row.source.surface())) findings.push({
3384
- spec: row.entry.spec,
3385
- text: `${row.entry.spec} does not re-export ${key}.`
3386
- });
3387
- for (const key of findMissingSymbols(row.source.surface(), row.source.exports())) findings.push({
3388
- spec: row.entry.spec,
3389
- text: `${row.entry.spec} barrel exposes no direct ${key}.`
3390
- });
3391
- for (const key of findMissingSymbols(row.source.surface(), row.guide.surface())) findings.push({
3392
- spec: row.entry.spec,
3393
- text: `${row.entry.spec} does not document ${key}.`
3394
- });
3395
- for (const key of findMissingSymbols(row.guide.surface(), row.source.surface())) findings.push({
3396
- spec: row.entry.spec,
3397
- text: `${row.entry.spec} documents no barrel ${key}.`
3398
- });
3399
- for (const symbol of row.source.hidden()) findings.push({
3400
- spec: row.entry.spec,
3401
- text: `${row.entry.spec} source hides ${computeSymbolKey(symbol)}.`
3402
- });
3403
- }
3404
- #inspectMethods(row, findings) {
3405
- for (const group of row.guide.methods()) {
3406
- const documented = group.methods.map((entry) => entry.name);
3407
- const declared = row.source.methods(group.interface).map((entry) => entry.name);
3408
- if (documented.length === 0) findings.push({
3409
- spec: row.entry.spec,
3410
- text: `${row.entry.spec} ${group.interface} has no documented methods.`
3411
- });
3412
- for (const name of findMissing(declared, documented)) findings.push({
3413
- spec: row.entry.spec,
3414
- text: `${row.entry.spec} does not document ${group.interface}.${name}.`
3415
- });
3416
- for (const name of findMissing(documented, declared)) findings.push({
3417
- spec: row.entry.spec,
3418
- text: `${row.entry.spec} documents no source ${group.interface}.${name}.`
3419
- });
3420
- const entity = group.interface.replace(/Interface$/, "");
3421
- if (entity === group.interface) continue;
3422
- for (const name of findMissing(row.source.methods(entity).map((entry) => entry.name), documented)) findings.push({
3423
- spec: row.entry.spec,
3424
- text: `${row.entry.spec} ${entity}.${name} is outside the ${group.interface} contract.`
3425
- });
3426
- }
3427
- }
3428
- #inspectDeclarations(row, findings) {
3429
- const groups = row.guide.methods();
3430
- const documented = groups.map((group) => group.interface);
3431
- const declared = new Set(row.source.surface().map((symbol) => symbol.name));
3432
- const classes = new Set(row.source.surface().filter((symbol) => symbol.keyword === "class").map((symbol) => symbol.name));
3433
- for (const group of groups) {
3434
- const finding = compareMembership(row.entry.spec, group.interface, group.methods.map((entry) => entry.name), row.source.methods(group.interface).map((entry) => entry.name));
3435
- if (finding !== void 0) findings.push(finding);
3436
- }
3437
- for (const symbol of row.source.surface()) {
3438
- if (symbol.keyword !== "interface" && symbol.keyword !== "class") continue;
3439
- if (symbol.keyword === "interface" && classes.has(symbol.name)) continue;
3440
- const members = row.source.methods(symbol.name).map((entry) => entry.name);
3441
- if (members.length === 0) continue;
3442
- const contract = `${symbol.name}Interface`;
3443
- if (symbol.keyword === "class" && declared.has(contract)) {
3444
- const finding = compareMembership(row.entry.spec, symbol.name, row.source.methods(contract).map((entry) => entry.name), members);
3445
- if (finding !== void 0) findings.push(finding);
3446
- continue;
3447
- }
3448
- if (documented.includes(symbol.name)) continue;
3449
- findings.push({
3450
- spec: row.entry.spec,
3451
- text: `${row.entry.spec} ${symbol.name} declares members and carries no method table.`
3452
- });
3453
- }
3454
- }
3455
- #inspectLinks(row, links, tests) {
3456
- if (row.guide.links().length === 0) links.push({
3457
- spec: row.entry.spec,
3458
- text: `${row.entry.spec} has no links.`
3459
- });
3460
- for (const href of row.guide.links()) {
3461
- if (isExternalLink(href)) continue;
3462
- const path = resolveLink(row.entry.spec, href);
3463
- if (row.source.exists(path)) continue;
3464
- links.push({
3465
- spec: row.entry.spec,
3466
- text: `${row.entry.spec} has a broken link: ${href}.`
3467
- });
3468
- }
3469
- if (row.guide.tests().length === 0) tests.push({
3470
- spec: row.entry.spec,
3471
- text: `${row.entry.spec} has no test links.`
3472
- });
3473
- for (const href of row.guide.tests()) {
3474
- const path = resolveLink(row.entry.spec, href);
3475
- if (row.source.exists(path)) continue;
3476
- tests.push({
3477
- spec: row.entry.spec,
3478
- text: `${row.entry.spec} has a missing test: ${href}.`
3479
- });
3480
- }
3481
- }
3482
- #inspectFences(row, findings) {
3483
- for (const fence of findUnlisted(row.guide.fences(), this.#options.languages)) findings.push({
3484
- spec: row.entry.spec,
3485
- text: `${row.entry.spec} has an unlisted fence language under ${fence.title ?? "no heading"}: ${fence.language ?? "absent"}.`
3486
- });
3487
- }
3488
- #inspectExamples(row, fencesFindings, functionFindings, methodFindings, titleFindings) {
3489
- const fences = row.guide.fences().filter((fence) => fence.language === this.#options.language).map((fence) => fence.code);
3490
- if (fences.length === 0) fencesFindings.push({
3491
- spec: row.entry.spec,
3492
- text: `${row.entry.spec} has no ${this.#options.language} example fence.`
3493
- });
3494
- const functions = row.guide.surface().filter((symbol) => symbol.keyword === "function").map((symbol) => symbol.name);
3495
- for (const name of findUnexampled(functions, fences, row.source.examples().map((example) => example.name))) functionFindings.push({
3496
- spec: row.entry.spec,
3497
- text: `${row.entry.spec} has no example for ${name}.`
3498
- });
3499
- for (const group of row.guide.methods()) {
3500
- const entity = group.interface.replace(/Interface$/, "");
3501
- const examples = row.source.examples(group.interface).map((example) => example.name);
3502
- if (entity !== group.interface) examples.push(...row.source.examples(entity).map((example) => example.name));
3503
- for (const name of findUnexampled(group.methods.map((entry) => entry.name), fences, examples)) methodFindings.push({
3504
- spec: row.entry.spec,
3505
- text: `${row.entry.spec} has no example for ${group.interface}.${name}.`
3506
- });
3507
- }
3508
- const guide = row.guide.fences().map((fence) => fence.title).filter(isNonEmptyString);
3509
- const source = row.source.examples().map((example) => example.title).filter(isNonEmptyString);
3510
- if (!guide.some((title) => source.includes(title))) titleFindings.push({
3511
- spec: row.entry.spec,
3512
- text: `${row.entry.spec} has no top-level example-title pair: guide ${JSON.stringify(guide)} source ${JSON.stringify(source)}.`
3513
- });
3514
- }
3515
- #inspectImports(row, findings) {
3516
- const sources = new SourceManager({
3517
- files: this.#options.files,
3518
- modules: this.#options.modules
3519
- });
3520
- let compared = false;
3521
- for (const fence of row.guide.fences()) {
3522
- if (fence.language !== this.#options.language) continue;
3523
- for (const imported of extractFenceImports(fence.code)) {
3524
- const source = sources.source(imported.specifier);
3525
- if (source === void 0) continue;
3526
- compared = true;
3527
- const surface = source.surface().map((symbol) => symbol.name);
3528
- for (const name of findMissing(imported.names, surface)) findings.push({
3529
- spec: row.entry.spec,
3530
- text: `${row.entry.spec} imports missing ${name} from ${imported.specifier}.`
3531
- });
3532
- }
3533
- }
3534
- if (!compared) findings.push({
3535
- spec: row.entry.spec,
3536
- text: `${row.entry.spec} has no mapped self import.`
3537
- });
3538
- }
3539
- #inspectDrift(row, findings) {
3540
- for (const drift of findDrift(row.guide, row.source)) findings.push({
3541
- spec: row.entry.spec,
3542
- text: formatDrift(drift)
3543
- });
3544
- }
3545
- #inspectPitch(findings) {
3546
- const pitch = this.#options.pitch;
3547
- if (pitch === void 0) return;
3548
- const readme = this.#options.files[pitch.readme];
3549
- const spec = this.#options.files[pitch.spec];
3550
- if (readme === void 0) {
3551
- findings.push({
3552
- spec: pitch.readme,
3553
- text: `${pitch.readme} is absent from the inventory.`
3554
- });
3555
- return;
3556
- }
3557
- if (spec === void 0) {
3558
- findings.push({
3559
- spec: pitch.spec,
3560
- text: `${pitch.spec} is absent from the inventory.`
3561
- });
3562
- return;
3563
- }
3564
- const left = new Guide(readme).tagline();
3565
- const right = new Guide(spec).tagline();
3566
- if (left !== void 0 && left === right) return;
3567
- findings.push({
3568
- spec: pitch.spec,
3569
- text: `${pitch.spec} pitch: README ${formatSide(left)} guide ${formatSide(right)}.`
3570
- });
3571
- }
3572
- #rewriteGuide(row, drift, files) {
3573
- if (drift.source === void 0) return "source authority is absent";
3574
- const current = files.get(row.entry.spec);
3575
- if (current === void 0) return "the guide inventory text is absent";
3576
- if (drift.category === "summary") {
3577
- const replacement = replaceCell(current, drift.key, drift.source);
3578
- if (replacement === void 0) return "the guide summary cell or its provenance is unavailable";
3579
- files.set(row.entry.spec, replacement);
3580
- return;
3581
- }
3582
- const example = collectTitles(row.guide, row.source).get(drift.key);
3583
- if (example === void 0) return "the paired source example is unavailable";
3584
- const replacement = replaceFence(current, drift.key, example);
3585
- if (replacement === void 0) return "the titled guide fence or its provenance is unavailable";
3586
- files.set(row.entry.spec, replacement);
3587
- }
3588
- #rewriteSource(row, drift, files) {
3589
- if (drift.guide === void 0) return "guide authority is absent";
3590
- if (drift.category === "summary") {
3591
- const located = this.#locateSource(row.entry, drift.key, files);
3592
- if (located === void 0) return "the source doc block or its provenance is unavailable";
3593
- const replacement = replaceSummary(located.text.slice(located.span.start, located.span.end), drift.guide);
3594
- if (replacement === void 0) return "the source summary cannot be represented safely";
3595
- files.set(located.path, spliceSpan(located.text, located.span, replacement));
3596
- return;
3597
- }
3598
- const fence = row.guide.fences().find((entry) => entry.title === drift.key);
3599
- const located = this.#locateExample(row, drift.key, files);
3600
- if (fence === void 0 || located === void 0) return "the paired source example or its provenance is unavailable";
3601
- const replacement = replaceExample(located.text.slice(located.span.start, located.span.end), {
3602
- name: located.example.name,
3603
- title: drift.key,
3604
- code: fence.code,
3605
- ...fence.language === void 0 ? {} : { language: fence.language }
3606
- });
3607
- if (replacement === void 0) return "the guide example cannot be represented safely";
3608
- files.set(located.path, spliceSpan(located.text, located.span, replacement));
3609
- }
3610
- #locateSource(entry, key, files) {
3611
- const inventory = Object.fromEntries(files);
3612
- for (const path of selectModuleKeys(inventory, normalizeDirectories(entry.source))) {
3613
- const text = files.get(path);
3614
- if (text === void 0) continue;
3615
- const span = locateComment(text, key);
3616
- if (span !== void 0) return {
3617
- path,
3618
- text,
3619
- span
3620
- };
3621
- }
3622
- }
3623
- #locateExample(row, title, files) {
3624
- const target = collectTitles(row.guide, row.source).get(title);
3625
- if (target === void 0) return void 0;
3626
- const keys = [];
3627
- for (const symbol of row.source.exports()) if (symbol.name === target.name) keys.push(computeSymbolKey(symbol));
3628
- for (const owner of row.guide.surface()) {
3629
- if (owner.keyword !== "class" && owner.keyword !== "interface") continue;
3630
- if (row.source.examples(owner.name).some((example) => example.name === target.name && example.title === title)) keys.push(`${owner.name}.${target.name}`);
3631
- }
3632
- const inventory = Object.fromEntries(files);
3633
- for (const path of selectModuleKeys(inventory, normalizeDirectories(row.entry.source))) {
3634
- const text = files.get(path);
3635
- if (text === void 0) continue;
3636
- let selected;
3637
- for (const key of keys) {
3638
- const span = locateComment(text, key);
3639
- if (span === void 0) continue;
3640
- const example = collectExamples(normalizeComment(text.slice(span.start, span.end)), target.name).find((entry) => entry.title === title);
3641
- if (example === void 0) continue;
3642
- if (selected === void 0 || span.start < selected.span.start) selected = {
3643
- span,
3644
- example
3645
- };
3646
- }
3647
- if (selected !== void 0) return {
3648
- path,
3649
- text,
3650
- ...selected
3651
- };
3652
- }
3653
- }
3654
- };
3655
- //#endregion
3656
- //#region src/core/parsers.ts
3657
- /**
3658
- * Parses a `## By concept` manifest table into its {@link ManifestEntry} rows —
3659
- * each row's Concept cell (flattened text), Spec / Tests cells (a single link
3660
- * href, resolved against `directory`), and Source cell (every link href,
3661
- * resolved against `directory`; Source links canonicalize through
3662
- * {@link normalizeDirectories}, one directory collapses to a `string`, and several become
3663
- * a `readonly string[]`). A row missing a concept, spec link, tests link, or
3664
- * source link is skipped as malformed.
3665
- *
3666
- * @param markdown - The manifest markdown source, for example the content of `guides/README.md`
3667
- * @param directory - The root-relative directory containing the manifest
3668
- * @returns The manifest's entries, in row order
3669
- *
3670
- * @example
3671
- * ```ts
3672
- * parseManifest(readme, 'guides') // [{ concept: 'Markdown', spec: 'guides/src/markdown.md', ... }]
3673
- * ```
3674
- */
3675
- function parseManifest(markdown, directory) {
3676
- const document = createMarkdown(markdown).document;
3677
- const entries = [];
3678
- for (const block of selectSectionBlocks(document, MANIFEST)) {
3679
- if (!isTableNode(block)) continue;
3680
- for (const row of block.rows) {
3681
- const conceptCell = row[0];
3682
- const specCell = row[1];
3683
- const sourceCell = row[2];
3684
- const testsCell = row[3];
3685
- if (conceptCell === void 0 || specCell === void 0 || sourceCell === void 0 || testsCell === void 0) continue;
3686
- const concept = flattenText({
3687
- element: "paragraph",
3688
- children: conceptCell
3689
- }).trim();
3690
- if (isEmptyString(concept)) continue;
3691
- const specHref = extractCellLinks(specCell)[0];
3692
- const testsHref = extractCellLinks(testsCell)[0];
3693
- if (specHref === void 0 || testsHref === void 0) continue;
3694
- const sourceHrefs = normalizeDirectories(extractCellLinks(sourceCell).map((href) => resolvePath(directory, href)));
3695
- if (!isNonEmptyArray(sourceHrefs)) continue;
3696
- const [firstSource] = sourceHrefs;
3697
- const source = sourceHrefs.length === 1 ? firstSource : sourceHrefs;
3698
- entries.push({
3699
- concept,
3700
- spec: resolvePath(directory, specHref),
3701
- source,
3702
- tests: resolvePath(directory, testsHref)
3703
- });
3704
- }
3705
- }
3706
- return entries;
3707
- }
3708
- //#endregion
3709
- //#region src/server/GuideCommand.ts
123
+ // src/server/GuideCommand.ts
3710
124
  /**
3711
125
  * Drives native checking and explicit rewrites or registers package assertions in the guides
3712
126
  * worker.
@@ -3887,7 +301,6 @@ var GuideCommand = class {
3887
301
  if (!isFiniteNumber(numeric) || numeric < code) process.exitCode = code;
3888
302
  }
3889
303
  };
3890
- //#endregion
3891
304
  export { GUIDE_INDEX, GUIDE_MANIFEST, GUIDE_README, GUIDE_USAGE, GuideCommand, formatGuideFinding, matchesGuideResult, parseGuideDirection, parsePackageName, resolveGuideRoot, selectGuidePitch };
3892
305
 
3893
306
  //# sourceMappingURL=index.js.map