@orkestrel/guide 0.0.16 → 0.0.18

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.
@@ -3,15 +3,14 @@ let _orkestrel_markdown = require("@orkestrel/markdown");
3
3
  let _orkestrel_contract = require("@orkestrel/contract");
4
4
  //#region src/core/constants.ts
5
5
  /**
6
- * Lists the declaration keywords a documented or exported symbol carries, in
7
- * the order the reflection grammar names them.
6
+ * Lists the declaration keywords a documented or exported symbol carries, in the order the
7
+ * reflection grammar names them — the frozen population `ExportKeyword`, `isExportKeyword`, and
8
+ * `surfaceSymbolShape` all derive from.
8
9
  *
9
10
  * @remarks
10
- * One frozen list feeds the `ExportKeyword` type, the `isExportKeyword` guard, and
11
- * `surfaceSymbolShape`, so a keyword cannot be admitted by one and refused by
12
- * another. Comment and template payload is excluded before reflection, and
13
- * `enum` is outside this population rather than forbidden by general package
14
- * policy.
11
+ * One frozen list feeds the type, the guard, and the shape, so a keyword cannot be admitted by one
12
+ * and refused by another. Comment and template payload is excluded before reflection, and `enum`
13
+ * is outside this population rather than forbidden by general package policy.
15
14
  */
16
15
  var EXPORT_KEYWORDS = Object.freeze([
17
16
  "type",
@@ -21,6 +20,10 @@ var EXPORT_KEYWORDS = Object.freeze([
21
20
  "class"
22
21
  ]);
23
22
  /**
23
+ * Lists the compared sites a {@link Drift} can describe.
24
+ */
25
+ var DRIFT_CATEGORIES = Object.freeze(["summary", "example"]);
26
+ /**
24
27
  * Names the `## Surface` heading text a guide's documented exports section is keyed on.
25
28
  */
26
29
  var SURFACE = "Surface";
@@ -33,10 +36,34 @@ var METHODS = "Methods";
33
36
  */
34
37
  var TESTS = "Tests";
35
38
  /**
39
+ * Names the header text of the column a `## Surface` table's declaration keyword is read from.
40
+ */
41
+ var KIND = "Kind";
42
+ /**
43
+ * Names the header text of the column a `## Surface` or `## Methods` table's compared
44
+ * description paragraph is read from.
45
+ */
46
+ var SUMMARY = "Summary";
47
+ /**
36
48
  * Names the `## By concept` heading text the manifest's run-map table is keyed on.
37
49
  */
38
50
  var MANIFEST = "By concept";
39
51
  /**
52
+ * Holds the default character budget a rewritten doc block's description paragraph wraps
53
+ * inside — the greatest number of characters a re-wrapped line may carry, counted from the
54
+ * line's first character with a tab counting as one, so a wrapped line reads
55
+ * `${indent} * ${text}` and never passes that count.
56
+ *
57
+ * @remarks
58
+ * The budget counts characters, not rendered columns. A block indented with tabs therefore
59
+ * measures each tab as one character, and a formatter that renders a tab wider reads the same
60
+ * line as longer; a caller whose formatter measures differently passes its own width instead of
61
+ * taking this default. A doc block's own wrapping is not recoverable from its text either — the
62
+ * blocks this package's own source carries are hand-wrapped, and no single greedy width
63
+ * reproduces them — so a rewrite cannot infer a per-block width and falls back to this budget.
64
+ */
65
+ var WRAP_WIDTH = 100;
66
+ /**
40
67
  * Lists the link `href` schemes a guides-parity link check skips as external — a link
41
68
  * with one of these prefixes (or a bare `#` anchor, handled separately in
42
69
  * `isExternalLink`) is never resolved against the filesystem.
@@ -64,9 +91,11 @@ var EXTERNAL_SCHEMES = Object.freeze([
64
91
  * ```
65
92
  */
66
93
  var isExportKeyword = (0, _orkestrel_contract.literalOf)(EXPORT_KEYWORDS);
94
+ /** Checks whether `value` names a supported drift category. */
95
+ var isDriftCategory = (0, _orkestrel_contract.literalOf)(DRIFT_CATEGORIES);
67
96
  /**
68
97
  * Checks whether `value` is a well-formed {@link SurfaceSymbol} — a `name`
69
- * string paired with a valid {@link ExportKeyword}.
98
+ * string paired with a valid {@link ExportKeyword}, and an optional `summary`.
70
99
  *
71
100
  * @param value - The value to test
72
101
  * @returns True if `value` is a well-formed {@link SurfaceSymbol}; false otherwise
@@ -79,24 +108,80 @@ var isExportKeyword = (0, _orkestrel_contract.literalOf)(EXPORT_KEYWORDS);
79
108
  */
80
109
  var isSurfaceSymbol = (0, _orkestrel_contract.recordOf)({
81
110
  name: _orkestrel_contract.isString,
82
- keyword: isExportKeyword
83
- });
111
+ keyword: isExportKeyword,
112
+ summary: _orkestrel_contract.isString
113
+ }, ["summary"]);
114
+ /**
115
+ * Checks whether `value` is a well-formed {@link MethodEntry} — a `name` string with an
116
+ * optional `summary`.
117
+ *
118
+ * @param value - The value to test
119
+ * @returns True if `value` is a well-formed {@link MethodEntry}; false otherwise
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * isMethodEntry({ name: 'walk' }) // true
124
+ * isMethodEntry({ name: 1 }) // false
125
+ * ```
126
+ */
127
+ var isMethodEntry = (0, _orkestrel_contract.recordOf)({
128
+ name: _orkestrel_contract.isString,
129
+ summary: _orkestrel_contract.isString
130
+ }, ["summary"]);
131
+ /**
132
+ * Checks whether `value` is a well-formed {@link SourceExample} — a `name` and `code`
133
+ * string with an optional `title` and `language`.
134
+ *
135
+ * @param value - The value to test
136
+ * @returns True if `value` is a well-formed {@link SourceExample}; false otherwise
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * isSourceExample({ name: 'walk', code: 'walk()' }) // true
141
+ * isSourceExample({ name: 'walk' }) // false
142
+ * ```
143
+ */
144
+ var isSourceExample = (0, _orkestrel_contract.recordOf)({
145
+ name: _orkestrel_contract.isString,
146
+ title: _orkestrel_contract.isString,
147
+ code: _orkestrel_contract.isString,
148
+ language: _orkestrel_contract.isString
149
+ }, ["title", "language"]);
150
+ /**
151
+ * Checks whether `value` is a well-formed {@link Drift} — a compared `key` with an optional
152
+ * `guide` and `source` text.
153
+ *
154
+ * @param value - The value to test
155
+ * @returns True if `value` is a well-formed {@link Drift}; false otherwise
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * isDrift({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
160
+ * isDrift({ guide: 'A widget.' }) // false
161
+ * ```
162
+ */
163
+ var isDrift = (0, _orkestrel_contract.recordOf)({
164
+ key: _orkestrel_contract.isString,
165
+ category: isDriftCategory,
166
+ guide: _orkestrel_contract.isString,
167
+ source: _orkestrel_contract.isString
168
+ }, ["guide", "source"]);
84
169
  /**
85
170
  * Checks whether `value` is a well-formed {@link MethodGroup} — a backticked
86
- * `interface` name paired with its documented `methods`.
171
+ * `interface` name paired with its documented {@link MethodEntry} rows.
87
172
  *
88
173
  * @param value - The value to test
89
174
  * @returns True if `value` is a well-formed {@link MethodGroup}; false otherwise
90
175
  *
91
176
  * @example
92
177
  * ```ts
93
- * isMethodGroup({ interface: 'MarkdownInterface', methods: ['walk'] }) // true
94
- * isMethodGroup({ interface: 'MarkdownInterface', methods: [1] }) // false
178
+ * isMethodGroup({ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }) // true
179
+ * isMethodGroup({ interface: 'MarkdownInterface', methods: [1] }) // false
95
180
  * ```
96
181
  */
97
182
  var isMethodGroup = (0, _orkestrel_contract.recordOf)({
98
183
  interface: _orkestrel_contract.isString,
99
- methods: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString)
184
+ methods: (0, _orkestrel_contract.arrayOf)(isMethodEntry)
100
185
  });
101
186
  /**
102
187
  * Checks whether `value` is a well-formed {@link ManifestEntry} — a
@@ -142,10 +227,13 @@ var isManifestEntry = (0, _orkestrel_contract.recordOf)({
142
227
  * @param source - The TypeScript source text to project
143
228
  * @returns One aligned terminator-free record per LF or CRLF physical line, including the final line
144
229
  *
145
- * @example
230
+ * @example Project source into physical code lines
146
231
  * ```ts
232
+ * import { extractSourceLines } from '@orkestrel/guide'
233
+ *
147
234
  * extractSourceLines('export const visible = true // note\n')
148
- * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }, ...]
235
+ * // [{ source: 'export const visible = true // note', code: 'export const visible = true ', jsdoc: undefined }]
236
+ * // … one record per remaining line
149
237
  * ```
150
238
  */
151
239
  function extractSourceLines(source) {
@@ -697,8 +785,8 @@ function selectModuleKeys(files, module) {
697
785
  return keys.sort();
698
786
  }
699
787
  /**
700
- * Computes the bijection key for a surface symbol — its keyword and name combined — so a
701
- * symbol-set comparison diffs (name, keyword) pairs rather than names alone.
788
+ * Computes the bijection key for a surface symbol — `${keyword} ${name}` — so a symbol-set
789
+ * comparison diffs (name, keyword) pairs rather than names alone.
702
790
  *
703
791
  * @param symbol - The symbol to key
704
792
  * @returns The `${keyword} ${name}` key
@@ -788,10 +876,11 @@ function findUnexampled(names, fences, examples) {
788
876
  });
789
877
  }
790
878
  /**
791
- * Parses a fence's `import` statements into per-specifier imported identifier
792
- * names — handles `import type`, mixed multiline braces, and `x as y` aliases,
793
- * resolving each alias to the exported name `x` because that is the name the
794
- * checked barrel surface must hold.
879
+ * Parses a fence's brace `import` statements into per-specifier imported identifier names —
880
+ * `import type`, mixed multiline braces, and `x as y` aliases all count, each alias resolved to
881
+ * the exported name `x` because that is the name the checked barrel surface must hold. Brace
882
+ * bindings only: a default, namespace, side-effect, or mixed `import Default, { named }`
883
+ * statement is not surfaced.
795
884
  *
796
885
  * @param fence - A ```ts Patterns fence's verbatim body text
797
886
  * @returns One entry per `import ... from 'specifier'` statement, in fence order
@@ -909,7 +998,7 @@ function findFirstCode(nodes) {
909
998
  }
910
999
  }
911
1000
  /**
912
- * Extracts the link hrefs within one table cell's inline content.
1001
+ * Extracts the link hrefs within one table cell's inline content, in walk order.
913
1002
  *
914
1003
  * @param cell - The cell's inline nodes
915
1004
  * @returns The cell's link hrefs, in walk order
@@ -948,38 +1037,117 @@ function normalizeIdentifier(code) {
948
1037
  return (index < 0 ? code : code.slice(0, index)).trim();
949
1038
  }
950
1039
  /**
951
- * Finds the index of a table's `Kind` column by its header text so it survives
952
- * column reordering. The match is exact and case-sensitive (`'Kind'`) — a table
953
- * without that exact header contributes no symbols to the surface it feeds.
1040
+ * Extracts compared inline content — the text of a table cell or candidate entity heading
1041
+ * flattened with every code span kept as a code span, so `` `Widget` `` reads the same wherever
1042
+ * the parity reader compares it. Emphasis drops to its text, a link drops to its text, an image
1043
+ * drops to its alternative text, and the markdown parser has already unescaped `\|`.
1044
+ *
1045
+ * @param cell - The inline nodes to flatten
1046
+ * @returns The compared text, code spans included
1047
+ *
1048
+ * @example
1049
+ * ```ts
1050
+ * extractCellText([{ element: 'codeSpan', value: 'Widget' }]) // '`Widget`'
1051
+ * ```
1052
+ */
1053
+ function extractCellText(cell) {
1054
+ let text = "";
1055
+ for (const node of cell) if ((0, _orkestrel_markdown.isCodeSpanNode)(node)) text += `\`${node.value}\``;
1056
+ else if ((0, _orkestrel_markdown.isEmphasisNode)(node) || (0, _orkestrel_markdown.isLinkNode)(node) || (0, _orkestrel_markdown.isImageNode)(node)) text += extractCellText(node.children);
1057
+ else text += (0, _orkestrel_markdown.flattenText)(node);
1058
+ return text;
1059
+ }
1060
+ /**
1061
+ * Builds one table cell's inline content from its compared text — the inverse of
1062
+ * {@link extractCellText}. A single-backtick run whose text carries no inner backtick and
1063
+ * neither a leading nor a trailing space becomes a code span; every other character, a backtick
1064
+ * included, becomes literal text, which `renderMarkdown` escapes so the rendered cell parses back
1065
+ * to the text this function was given.
1066
+ *
1067
+ * @remarks
1068
+ * The compared form spells every code span with one backtick per side, because
1069
+ * {@link extractCellText} emits `` `${value}` `` whatever delimiter the source used. A run this
1070
+ * function refuses is therefore a run no parsed cell produced, and emitting it as text is what
1071
+ * keeps the projection total: reading the rendered cell back through {@link extractCellText}
1072
+ * returns the text, so a rendered row and a hand-written row compare the same. A code span whose
1073
+ * own text carries a backtick or a boundary space is outside the compared form's fidelity in
1074
+ * either direction, and this function writes it as text rather than guessing a delimiter.
1075
+ *
1076
+ * @param text - The cell's compared text, as {@link extractCellText} returns it
1077
+ * @returns The cell's inline nodes, in text order
1078
+ *
1079
+ * @example
1080
+ * ```ts
1081
+ * buildCell('Holds a `Widget`.')
1082
+ * // [{ element: 'text', value: 'Holds a ' }, { element: 'codeSpan', value: 'Widget' }, { element: 'text', value: '.' }]
1083
+ * ```
1084
+ */
1085
+ function buildCell(text) {
1086
+ const nodes = [];
1087
+ const spans = /`([^`]+)`/g;
1088
+ let cursor = 0;
1089
+ let span;
1090
+ while ((span = spans.exec(text)) !== null) {
1091
+ const value = span[1];
1092
+ if (value === void 0) continue;
1093
+ if (span.index > cursor) nodes.push({
1094
+ element: "text",
1095
+ value: text.slice(cursor, span.index)
1096
+ });
1097
+ if (value.trim() === value) nodes.push({
1098
+ element: "codeSpan",
1099
+ value
1100
+ });
1101
+ else nodes.push({
1102
+ element: "text",
1103
+ value: span[0]
1104
+ });
1105
+ cursor = span.index + span[0].length;
1106
+ }
1107
+ if (cursor < text.length) nodes.push({
1108
+ element: "text",
1109
+ value: text.slice(cursor)
1110
+ });
1111
+ return (0, _orkestrel_markdown.coalesceText)(nodes);
1112
+ }
1113
+ /**
1114
+ * Finds the index of the column whose header text is `header` so a table's columns survive
1115
+ * reordering. The match is exact and case-sensitive — a table without that exact header
1116
+ * contributes nothing to the projection reading it, so a `## Surface` table with no
1117
+ * {@link SUMMARY} column leaves every row's summary absent and {@link findDrift} reports each
1118
+ * of those rows, never agreement.
954
1119
  *
955
1120
  * @param table - The table to inspect
956
- * @returns The `Kind` column's index, or `undefined` when the table has no `Kind` header
1121
+ * @param header - The exact header text to locate, for example `Kind`
1122
+ * @returns The column's index, or `undefined` when the table has no such header
957
1123
  *
958
1124
  * @example
959
1125
  * ```ts
960
- * findKindIndex(table) // 1, or undefined
1126
+ * findColumnIndex(table, 'Kind') // 1, or undefined
961
1127
  * ```
962
1128
  */
963
- function findKindIndex(table) {
1129
+ function findColumnIndex(table, header) {
964
1130
  for (let index = 0; index < table.header.length; index += 1) {
965
1131
  const cell = table.header[index];
966
1132
  if (cell !== void 0 && (0, _orkestrel_markdown.flattenText)({
967
1133
  element: "paragraph",
968
1134
  children: cell
969
- }).trim() === "Kind") return index;
1135
+ }).trim() === header) return index;
970
1136
  }
971
1137
  }
972
1138
  /**
973
- * Extracts the module-scope exports declared in one file's source text — matches
974
- * `export (async)? (function(\*)?|class|const|interface|type) Name`, deduped
975
- * by (keyword, name). A generator export (`export function* walk`) scans as the
976
- * `function` keyword — its trailing `*` is stripped before the
977
- * {@link ExportKeyword} check.
978
- * Scanning uses {@link extractSourceLines}, so comment and template payload is
979
- * excluded while its uninterrupted column-zero head remains required; preserved
980
- * columns do not grant membership to leading/interrupted comment forms. The population is
981
- * exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is
982
- * outside this reflection contract, not forbidden by general package policy.
1139
+ * Extracts the module-scope exports declared in one file's source text — the declaration keys
1140
+ * {@link collectKeys} reports, each split back into the keyword and name that built it, deduped by
1141
+ * (keyword, name).
1142
+ *
1143
+ * @remarks
1144
+ * That one grammar matches `export (async)? (function(\*)?|class|const|interface|type) Name`; a
1145
+ * generator export (`export function* walk`) keys as the `function` keyword, its trailing `*`
1146
+ * stripped before the {@link ExportKeyword} check. Scanning uses {@link extractSourceLines}, so
1147
+ * comment and template payload is excluded while its uninterrupted column-zero head remains
1148
+ * required; preserved columns do not grant membership to leading/interrupted comment forms. The
1149
+ * population is exactly `type`, `interface`, `const`, `function`, and `class`; `enum` is outside
1150
+ * this reflection contract, not forbidden by general package policy.
983
1151
  *
984
1152
  * @param source - The file's source text
985
1153
  * @returns The file's exported symbols, in file order
@@ -993,33 +1161,38 @@ function findKindIndex(table) {
993
1161
  function extractExports(source) {
994
1162
  const symbols = [];
995
1163
  const seen = /* @__PURE__ */ new Set();
996
- for (const line of extractSourceLines(source)) {
997
- const match = line.code.match(/^export (?:async )?(function\*?|class|const|interface|type) (\w+)/);
998
- const rawKeyword = match?.[1];
999
- const name = match?.[2];
1000
- const keyword = rawKeyword === void 0 ? void 0 : rawKeyword.replace(/\*$/, "");
1001
- if (!(0, _orkestrel_contract.isNonEmptyString)(keyword) || !(0, _orkestrel_contract.isNonEmptyString)(name) || !isExportKeyword(keyword)) continue;
1002
- const key = `${keyword} ${name}`;
1003
- if (seen.has(key)) continue;
1164
+ const lines = extractSourceLines(source);
1165
+ const summaries = collectSummaries(lines);
1166
+ const keys = collectKeys(lines);
1167
+ for (const line of lines) {
1168
+ const key = keys.get(line);
1169
+ if (key === void 0 || seen.has(key)) continue;
1170
+ const space = key.indexOf(" ");
1171
+ const keyword = key.slice(0, Math.max(space, 0));
1172
+ if (!isExportKeyword(keyword)) continue;
1004
1173
  seen.add(key);
1174
+ const name = key.slice(space + 1);
1175
+ const summary = summaries.get(line);
1005
1176
  symbols.push({
1006
1177
  name,
1007
- keyword
1178
+ keyword,
1179
+ ...summary === void 0 ? {} : { summary }
1008
1180
  });
1009
1181
  }
1010
1182
  return symbols;
1011
1183
  }
1012
1184
  /**
1013
- * Extracts the module-scope declarations lacking the `export` keyword in one file's
1014
- * source text — the mirror image of {@link extractExports}'s grammar, anchored
1015
- * the same way (column 0, so an indented inner declaration never matches).
1016
- * Scans only the {@link ExportKeyword} keywords (`function` / `class` /
1017
- * `const` / `interface` / `type`) — a module-scope `let` or `var` is outside
1018
- * this scanner's declaration-keyword grammar and out of this check's contract.
1019
- * Scanning uses {@link extractSourceLines}, so comment
1020
- * and template payload is excluded while its uninterrupted column-zero head
1021
- * remains required; preserved columns do not widen membership. `enum` is likewise outside this reflection population, not
1022
- * forbidden by general package policy.
1185
+ * Extracts the module-scope declarations lacking the `export` keyword in one file's source text —
1186
+ * the mirror image of {@link extractExports}'s grammar, anchored the same way (column 0, so an
1187
+ * indented inner declaration never matches).
1188
+ *
1189
+ * @remarks
1190
+ * Scans only the {@link ExportKeyword} keywords (`function` / `class` / `const` / `interface` /
1191
+ * `type`) — a module-scope `let` or `var` is outside this scanner's declaration-keyword grammar
1192
+ * and out of this check's contract. Scanning uses {@link extractSourceLines}, so comment and
1193
+ * template payload is excluded while its uninterrupted column-zero head remains required;
1194
+ * preserved columns do not widen membership. `enum` is likewise outside this reflection
1195
+ * population, not forbidden by general package policy.
1023
1196
  *
1024
1197
  * @param source - The file's source text
1025
1198
  * @returns The file's hidden (non-exported) symbols, in file order
@@ -1033,7 +1206,9 @@ function extractExports(source) {
1033
1206
  function extractHidden(source) {
1034
1207
  const symbols = [];
1035
1208
  const seen = /* @__PURE__ */ new Set();
1036
- for (const line of extractSourceLines(source)) {
1209
+ const lines = extractSourceLines(source);
1210
+ const summaries = collectSummaries(lines);
1211
+ for (const line of lines) {
1037
1212
  if (line.code.startsWith("export ")) continue;
1038
1213
  const match = line.code.match(/^(?:async )?(function\*?|class|const|interface|type) (\w+)/);
1039
1214
  const rawKeyword = match?.[1];
@@ -1043,9 +1218,11 @@ function extractHidden(source) {
1043
1218
  const key = `${keyword} ${name}`;
1044
1219
  if (seen.has(key)) continue;
1045
1220
  seen.add(key);
1221
+ const summary = summaries.get(line);
1046
1222
  symbols.push({
1047
1223
  name,
1048
- keyword
1224
+ keyword,
1225
+ ...summary === void 0 ? {} : { summary }
1049
1226
  });
1050
1227
  }
1051
1228
  return symbols;
@@ -1080,11 +1257,10 @@ function joinHead(lines, start) {
1080
1257
  * inside a larger `RegExp` source rather than as syntax.
1081
1258
  *
1082
1259
  * @remarks
1083
- * Every caller-supplied name reaches a `RegExp` through this: {@link
1084
- * extractDeclaration} splices it into the head grammar and {@link
1085
- * findUnexampled} into a word-boundary search, so a name carrying `$`, `(`,
1086
- * `[`, or `.` matches that character literally instead of throwing or matching
1087
- * text it does not name. Pure and total; never throws.
1260
+ * A caller-supplied name reaches a `RegExp` through this: {@link
1261
+ * findUnexampled} splices it into a word-boundary search, so a name carrying
1262
+ * `$`, `(`, `[`, or `.` matches that character literally instead of throwing or
1263
+ * matching text it does not name. Pure and total; never throws.
1088
1264
  *
1089
1265
  * @param value - The literal string to escape
1090
1266
  * @returns `value` with every regex metacharacter backslash-escaped
@@ -1099,84 +1275,134 @@ function escapeRegExp(value) {
1099
1275
  return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
1100
1276
  }
1101
1277
  /**
1102
- * Locates the named `export class` / `export interface` declaration in one
1103
- * file's source text and returns its body lines and its base identifiers read
1104
- * from that one head, so a body and a heritage clause always come from the same
1105
- * declaration.
1278
+ * Collects every `export class` / `export interface` declaration one file's source text declares,
1279
+ * each keyed `${keyword} ${name}` and carrying the body lines and the base identifiers read from
1280
+ * its own head, so a body and a heritage clause always come from the same declaration.
1106
1281
  *
1107
1282
  * @remarks
1108
- * The head is matched on projected lines (column 0, an oxfmt-wrapped signature
1109
- * joined through {@link joinHead}), with an optional generic parameter list and
1110
- * an optional heritage clause between the identifier and the opening `{`; the
1111
- * identifier matches exactly and is escaped through {@link escapeRegExp}, so a
1112
- * metacharacter in `name` is literal text. The returned body lines are the raw
1113
- * source between that head and the first projected column-zero `}`, keeping
1114
- * JSDoc evidence intact. Every balanced `<...>` span is removed from the head
1115
- * before its `extends` clause is read, so a `T extends Base` type parameter is
1116
- * never a base and `Base<T>` reads as `Base`; a class's `implements` clause and
1117
- * everything after it is excluded, and a qualified base such as
1118
- * `namespace.Base` is returned verbatim. A head that opens no column-zero close
1119
- * is skipped and the scan continues, so a later real declaration still answers.
1283
+ * The whole file is projected once through {@link extractSourceLines} and every head is read from
1284
+ * that one projection, so a scope resolving many names reads each file once rather than once per
1285
+ * name. A head is a column-zero `export class` / `export interface` line, an oxfmt-wrapped
1286
+ * signature joined through {@link joinHead}, with an optional generic parameter list and an
1287
+ * optional heritage clause between the identifier and the opening `{`; the identifier is the head's
1288
+ * own run up to that list or clause, so it enters the key as literal text and no name reaches a
1289
+ * `RegExp`. Body lines are the raw source between the head and the first projected column-zero `}`,
1290
+ * keeping JSDoc evidence intact. Every balanced `<...>` span is removed from the head before its
1291
+ * `extends` clause is read, so a `T extends Base` type parameter is never a base and `Base<T>`
1292
+ * reads as `Base`; a class's `implements` clause and everything after it is excluded, and a
1293
+ * qualified base such as `namespace.Base` is returned verbatim. The first head of a key that opens
1294
+ * a column-zero close answers for that key: a head that opens none records nothing, and a later
1295
+ * head of a key already collected adds nothing.
1120
1296
  *
1121
- * @param source - The file's source text to search
1122
- * @param keyword - Whether to look for a `class` or an `interface`
1123
- * @param name - The declaration's identifier
1124
- * @returns Its body and bases, or `undefined` when `source` declares no such head
1297
+ * @param source - The file's source text to read
1298
+ * @returns One entry per collected declaration, keyed `${keyword} ${name}`
1125
1299
  *
1126
1300
  * @example
1127
1301
  * ```ts
1128
- * extractDeclaration('export interface X extends Y {\n\twalk(): void\n}\n', 'interface', 'X')
1302
+ * collectDeclarations('export interface X extends Y {\n\twalk(): void\n}\n').get('interface X')
1129
1303
  * // { body: ['\twalk(): void'], bases: ['Y'] }
1130
1304
  * ```
1131
1305
  */
1132
- function extractDeclaration(source, keyword, name) {
1133
- const opener = `export ${keyword} ${name}`;
1134
- const grammar = new RegExp(`^${escapeRegExp(opener)}(?:<.*>)?(?: .*)? \\{$`);
1306
+ function collectDeclarations(source) {
1307
+ const declarations = /* @__PURE__ */ new Map();
1308
+ const opener = /^export (?:class|interface) /;
1309
+ const grammar = /^export (class|interface) ([^\s<]+)(?:<.*>)?(?: .*)? \{$/;
1135
1310
  const lines = extractSourceLines(source);
1136
1311
  const projected = lines.map((line) => line.code);
1137
1312
  for (let index = 0; index < projected.length; index += 1) {
1138
1313
  const line = projected[index];
1139
- if (line === void 0 || !line.startsWith(opener)) continue;
1314
+ if (line === void 0 || !opener.test(line)) continue;
1140
1315
  const head = joinHead(projected, index);
1141
- if (head === void 0 || !grammar.test(head.text)) continue;
1316
+ if (head === void 0) continue;
1317
+ const declared = grammar.exec(head.text);
1318
+ const keyword = declared?.[1];
1319
+ const name = declared?.[2];
1320
+ if (keyword === void 0 || name === void 0) continue;
1321
+ const key = `${keyword} ${name}`;
1322
+ if (declarations.has(key)) continue;
1142
1323
  let depth = 0;
1143
1324
  let flat = "";
1144
- for (const character of head.text.slice(opener.length, -1)) if (character === "<") depth += 1;
1325
+ for (const character of head.text.slice(`export ${key}`.length, -1)) if (character === "<") depth += 1;
1145
1326
  else if (character === ">") depth = Math.max(0, depth - 1);
1146
1327
  else if (depth === 0) flat += character;
1147
1328
  const clause = flat.replace(/\bimplements\b[\s\S]*$/, "").match(/\bextends\b([\s\S]*)$/)?.[1];
1148
1329
  const bases = clause === void 0 ? [] : clause.split(",").map((base) => base.trim()).filter(_orkestrel_contract.isNonEmptyString);
1149
1330
  for (let close = head.end + 1; close < projected.length; close += 1) {
1150
1331
  if (projected[close] !== "}") continue;
1151
- return {
1332
+ declarations.set(key, {
1152
1333
  body: lines.slice(head.end + 1, close).map((record) => record.source),
1153
1334
  bases
1154
- };
1335
+ });
1336
+ break;
1155
1337
  }
1156
1338
  }
1339
+ return declarations;
1340
+ }
1341
+ /**
1342
+ * Locates the named `export class` / `export interface` declaration in one file's source text
1343
+ * and returns its body lines and its base identifiers read from that one head, so a body and a
1344
+ * heritage clause always come from the same declaration, or `undefined` when the file declares
1345
+ * no such head.
1346
+ *
1347
+ * @remarks
1348
+ * The one named lookup over {@link collectDeclarations}, which owns the head grammar, the body
1349
+ * window, and the base reading. This lookup spells the map's `${keyword} ${name}` key for its
1350
+ * caller, so a consumer reading one name never writes that convention itself. `name` is compared
1351
+ * as literal text against the identifier the head itself carries, so a metacharacter in `name`
1352
+ * names that character rather than matching text it does not name. Every call collects the whole
1353
+ * file afresh: a consumer reading many names from one file calls {@link collectDeclarations} once
1354
+ * and reads the map, and {@link Source} holds one such map per module scope.
1355
+ *
1356
+ * @param source - The file's source text to search
1357
+ * @param keyword - Whether to look for a `class` or an `interface`
1358
+ * @param name - The declaration's identifier
1359
+ * @returns Its body and bases, or `undefined` when `source` declares no such head
1360
+ *
1361
+ * @example
1362
+ * ```ts
1363
+ * extractDeclaration('export interface X extends Y {\n\twalk(): void\n}\n', 'interface', 'X')
1364
+ * // { body: ['\twalk(): void'], bases: ['Y'] }
1365
+ * ```
1366
+ */
1367
+ function extractDeclaration(source, keyword, name) {
1368
+ return collectDeclarations(source).get(`${keyword} ${name}`);
1157
1369
  }
1158
1370
  /**
1159
1371
  * Selects the member lines declaring a callable member: plain, `async`, generator
1160
1372
  * (`*`), and optional (`records?(`) methods all count; getters, setters,
1161
1373
  * `static` members, and `#` privates never do (their keyword or `#` breaks
1162
- * the `name(` shape). Matching runs once over projected lines so commented
1163
- * method-like payload never becomes eligible.
1374
+ * the `name(` shape). The grammar is {@link collectKeys}'s, read once over
1375
+ * {@link extractBodyLines}'s projection of the body, so commented method-like payload never
1376
+ * becomes eligible and each member keys to the owner head that projection supplies. Each member
1377
+ * carries its own doc block's description paragraph, read through {@link collectSummaries}; the
1378
+ * first declaration of a name answers for it.
1164
1379
  *
1165
1380
  * @param lines - A declaration's body lines
1166
- * @returns The declared method names, deduped and sorted
1381
+ * @returns The declared members, deduplicated by name and sorted by name
1167
1382
  *
1168
1383
  * @example
1169
1384
  * ```ts
1170
- * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // ['filter', 'map']
1385
+ * extractMemberMethods(['\tmap(): void', '\tfilter(): void']) // [{ name: 'filter' }, { name: 'map' }]
1171
1386
  * ```
1172
1387
  */
1173
1388
  function extractMemberMethods(lines) {
1174
- const methods = [];
1175
- for (const line of extractSourceLines(lines.join("\n"))) {
1176
- const method = line.code.match(/^\t(?:async )?\*?(\w+)\??(<.*>)?\(/);
1177
- if (method?.[1] !== void 0) methods.push(method[1]);
1389
+ const methods = /* @__PURE__ */ new Map();
1390
+ const projected = extractBodyLines(lines);
1391
+ const summaries = collectSummaries(projected);
1392
+ const keys = collectKeys(projected);
1393
+ for (const line of projected) {
1394
+ const key = keys.get(line) ?? "";
1395
+ const dot = key.indexOf(".");
1396
+ if (dot < 0) continue;
1397
+ const name = key.slice(dot + 1);
1398
+ if (methods.has(name)) continue;
1399
+ const summary = summaries.get(line);
1400
+ methods.set(name, {
1401
+ name,
1402
+ ...summary === void 0 ? {} : { summary }
1403
+ });
1178
1404
  }
1179
- return Array.from(new Set(methods)).sort();
1405
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1180
1406
  }
1181
1407
  /**
1182
1408
  * Selects the block nodes under the named `##` heading, up to the next `##`-or-higher
@@ -1208,11 +1434,107 @@ function selectSectionBlocks(document, heading) {
1208
1434
  return blocks;
1209
1435
  }
1210
1436
  /**
1437
+ * Extracts one `## Surface` table row's symbol — its column 0 code span as the name, its
1438
+ * {@link KIND} column as the keyword, and its {@link SUMMARY} column as the compared summary
1439
+ * when the table has that column. A row with no code-span name and a row whose `Kind` text is
1440
+ * no {@link ExportKeyword} have no symbol to key, so each returns `undefined`.
1441
+ *
1442
+ * @param table - The table to read
1443
+ * @param row - The index of the row within {@link TableNode.rows}
1444
+ * @returns The row's symbol, or `undefined` when the row keys none
1445
+ *
1446
+ * @example
1447
+ * ```ts
1448
+ * extractRowSymbol(table, 0) // { name: 'walk', keyword: 'function', summary: 'Walks the tree.' }
1449
+ * ```
1450
+ */
1451
+ function extractRowSymbol(table, row) {
1452
+ const cells = table.rows[row];
1453
+ if (cells === void 0) return void 0;
1454
+ const nameCell = cells[0];
1455
+ const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1456
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1457
+ if (name === void 0) return void 0;
1458
+ const column = findColumnIndex(table, KIND);
1459
+ const kindCell = column === void 0 ? void 0 : cells[column];
1460
+ const keyword = kindCell === void 0 ? "" : (0, _orkestrel_markdown.flattenText)({
1461
+ element: "paragraph",
1462
+ children: kindCell
1463
+ }).trim();
1464
+ if (!isExportKeyword(keyword)) return void 0;
1465
+ const summary = extractRowSummary(table, row);
1466
+ return {
1467
+ name,
1468
+ keyword,
1469
+ ...summary === void 0 ? {} : { summary }
1470
+ };
1471
+ }
1472
+ /**
1473
+ * Extracts one `## Methods` table row's entry — its column 0 code span as the name and its
1474
+ * {@link SUMMARY} column as the compared summary when the table has that column. A row with no
1475
+ * code-span name has no member to key, so it returns `undefined`.
1476
+ *
1477
+ * @param table - The table to read
1478
+ * @param row - The index of the row within {@link TableNode.rows}
1479
+ * @returns The row's entry, or `undefined` when the row keys none
1480
+ *
1481
+ * @example
1482
+ * ```ts
1483
+ * extractRowEntry(table, 0) // { name: 'walk', summary: 'Walks the tree.' }
1484
+ * ```
1485
+ */
1486
+ function extractRowEntry(table, row) {
1487
+ const cells = table.rows[row];
1488
+ if (cells === void 0) return void 0;
1489
+ const cell = cells[0];
1490
+ const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1491
+ const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1492
+ if (name === void 0) return void 0;
1493
+ const summary = extractRowSummary(table, row);
1494
+ return {
1495
+ name,
1496
+ ...summary === void 0 ? {} : { summary }
1497
+ };
1498
+ }
1499
+ /**
1500
+ * Extracts one row's compared summary — its {@link SUMMARY} column read through
1501
+ * {@link extractCellText} and {@link normalizeSummary}. A table with no such column and a row
1502
+ * whose cell is empty each carry no summary and return `undefined` rather than an empty string,
1503
+ * so {@link findDrift} reports the absence.
1504
+ *
1505
+ * @param table - The table to read
1506
+ * @param row - The index of the row within {@link TableNode.rows}
1507
+ * @returns The row's compared summary, or `undefined` when it carries none
1508
+ *
1509
+ * @example
1510
+ * ```ts
1511
+ * extractRowSummary(table, 0) // 'Walks the tree.'
1512
+ * ```
1513
+ */
1514
+ function extractRowSummary(table, row) {
1515
+ const described = findColumnIndex(table, SUMMARY);
1516
+ const cells = table.rows[row];
1517
+ const cell = described === void 0 || cells === void 0 ? void 0 : cells[described];
1518
+ const summary = cell === void 0 ? "" : normalizeSummary(extractCellText(cell));
1519
+ return summary.length === 0 ? void 0 : summary;
1520
+ }
1521
+ /**
1211
1522
  * Extracts every `## Surface` identifier the guide documents — each table row's column 0
1212
- * code span (the name) paired with its `Kind` column (located by header text)
1213
- * unioned with every backticked H3 entity heading in the section
1214
- * (`{name: <codeSpan>, keyword: 'class'}`), deduped by {@link computeSymbolKey}. A row with
1215
- * no code-span name, or an unrecognized `Kind` text, is skipped.
1523
+ * code span (the name) paired with its `Kind` column (located by header text), unioned with every
1524
+ * H3 entity heading whose trimmed compared inline content is exactly its backticked code-span
1525
+ * name, deduped by {@link computeSymbolKey}. A row with no code-span name has no name to key a
1526
+ * symbol on, so this reader skips it and {@link extractUnnamed} reports it; a row with an
1527
+ * unrecognized `Kind` text is skipped. A row also carries its {@link SUMMARY} column's compared
1528
+ * text when the table has that column; a table without it leaves every row's summary absent,
1529
+ * which {@link findDrift} reports.
1530
+ *
1531
+ * @remarks
1532
+ * The heading boundary compares {@link extractCellText} with the raw value from
1533
+ * {@link findFirstCode} before {@link normalizeIdentifier} strips a generic annotation.
1534
+ * Surrounding spaces, emphasis, and links preserve that identity. This reader refuses a heading
1535
+ * carrying any other visible text or an additional code span. Entries retain encounter order, and
1536
+ * the first-seen name + keyword wins: a genuine heading before its table row keeps the heading's
1537
+ * summary-less class entry, while a table row before that heading keeps its `Summary`.
1216
1538
  *
1217
1539
  * @param document - The parsed guide document
1218
1540
  * @returns The documented surface, in encounter order
@@ -1227,22 +1549,9 @@ function extractSurface(document) {
1227
1549
  const seen = /* @__PURE__ */ new Set();
1228
1550
  for (const block of selectSectionBlocks(document, SURFACE)) {
1229
1551
  if ((0, _orkestrel_markdown.isTableNode)(block)) {
1230
- const column = findKindIndex(block);
1231
- for (const row of block.rows) {
1232
- const nameCell = row[0];
1233
- const rawName = nameCell === void 0 ? void 0 : findFirstCode(nameCell);
1234
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1235
- if (name === void 0) continue;
1236
- const kindCell = column === void 0 ? void 0 : row[column];
1237
- const kindText = kindCell === void 0 ? "" : (0, _orkestrel_markdown.flattenText)({
1238
- element: "paragraph",
1239
- children: kindCell
1240
- }).trim();
1241
- if (!isExportKeyword(kindText)) continue;
1242
- const symbol = {
1243
- name,
1244
- keyword: kindText
1245
- };
1552
+ for (let row = 0; row < block.rows.length; row += 1) {
1553
+ const symbol = extractRowSymbol(block, row);
1554
+ if (symbol === void 0) continue;
1246
1555
  const key = computeSymbolKey(symbol);
1247
1556
  if (seen.has(key)) continue;
1248
1557
  seen.add(key);
@@ -1252,10 +1561,9 @@ function extractSurface(document) {
1252
1561
  }
1253
1562
  if ((0, _orkestrel_markdown.isHeadingNode)(block) && block.level === 3) {
1254
1563
  const rawName = findFirstCode(block.children);
1255
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1256
- if (name === void 0) continue;
1564
+ if (rawName === void 0 || extractCellText(block.children).trim() !== `\`${rawName}\``) continue;
1257
1565
  const symbol = {
1258
- name,
1566
+ name: normalizeIdentifier(rawName),
1259
1567
  keyword: "class"
1260
1568
  };
1261
1569
  const key = computeSymbolKey(symbol);
@@ -1269,18 +1577,50 @@ function extractSurface(document) {
1269
1577
  /**
1270
1578
  * Extracts one {@link MethodGroup} per documented behavioral interface in `## Methods` —
1271
1579
  * an H4 with a code span sets the current interface, and the table immediately
1272
- * following becomes its documented methods.
1580
+ * following becomes its documented methods. A row with no code-span name has no name to key a
1581
+ * member on, so this reader skips it and {@link extractUnnamed} reports it. Each row carries its
1582
+ * {@link SUMMARY} column's compared text when the table has that column.
1273
1583
  *
1274
1584
  * @param document - The parsed guide document
1275
1585
  * @returns The documented method groups, in document order
1276
1586
  *
1277
1587
  * @example
1278
1588
  * ```ts
1279
- * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: ['walk', ...] }]
1589
+ * extractMethods(document) // [{ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }]
1280
1590
  * ```
1281
1591
  */
1282
1592
  function extractMethods(document) {
1283
1593
  const groups = [];
1594
+ for (const [table, name] of collectGroups(document)) {
1595
+ const methods = [];
1596
+ for (let row = 0; row < table.rows.length; row += 1) {
1597
+ const entry = extractRowEntry(table, row);
1598
+ if (entry !== void 0) methods.push(entry);
1599
+ }
1600
+ groups.push({
1601
+ interface: name,
1602
+ methods
1603
+ });
1604
+ }
1605
+ return groups;
1606
+ }
1607
+ /**
1608
+ * Collects each `## Methods` table keyed to the interface its `####` heading names — an H4
1609
+ * carrying a code span sets the current interface and the table immediately following claims it,
1610
+ * so a heading with no table and a table with no heading before it contribute nothing. The map
1611
+ * iterates in document order and a node keys itself, so a repeated identical table keeps its own
1612
+ * entry.
1613
+ *
1614
+ * @param document - The parsed guide document
1615
+ * @returns One entry per documented `## Methods` table, in document order
1616
+ *
1617
+ * @example
1618
+ * ```ts
1619
+ * collectGroups(document).values().next().value // 'GuideInterface'
1620
+ * ```
1621
+ */
1622
+ function collectGroups(document) {
1623
+ const groups = /* @__PURE__ */ new Map();
1284
1624
  let current;
1285
1625
  for (const block of selectSectionBlocks(document, METHODS)) {
1286
1626
  if ((0, _orkestrel_markdown.isHeadingNode)(block) && block.level === 4) {
@@ -1289,23 +1629,41 @@ function extractMethods(document) {
1289
1629
  continue;
1290
1630
  }
1291
1631
  if ((0, _orkestrel_markdown.isTableNode)(block) && current !== void 0) {
1292
- const methods = [];
1293
- for (const row of block.rows) {
1294
- const cell = row[0];
1295
- const rawName = cell === void 0 ? void 0 : findFirstCode(cell);
1296
- const name = rawName === void 0 ? void 0 : normalizeIdentifier(rawName);
1297
- if (name !== void 0) methods.push(name);
1298
- }
1299
- groups.push({
1300
- interface: current,
1301
- methods
1302
- });
1632
+ groups.set(block, current);
1303
1633
  current = void 0;
1304
1634
  }
1305
1635
  }
1306
1636
  return groups;
1307
1637
  }
1308
1638
  /**
1639
+ * Extracts every `## Surface` or `## Methods` table row whose first cell carries no code span.
1640
+ * {@link extractSurface} and {@link extractMethods} skip such a row, because a row with no
1641
+ * name gives them nothing to key a symbol or a member on, and this projection is what reports
1642
+ * the skip. Each entry is the row's cells read through {@link extractCellText} and joined
1643
+ * by ` | `, so a reader can locate the row in the guide; the `## Surface` rows come first,
1644
+ * then the `## Methods` rows, each in document order. {@link GuideInterface.unnamed} caches it.
1645
+ *
1646
+ * @param document - The parsed guide document
1647
+ * @returns One entry per row carrying no code-span name
1648
+ *
1649
+ * @example
1650
+ * ```ts
1651
+ * extractUnnamed(document) // ['Widget | class | Represents a widget.']
1652
+ * ```
1653
+ */
1654
+ function extractUnnamed(document) {
1655
+ const unnamed = [];
1656
+ for (const heading of [SURFACE, METHODS]) for (const block of selectSectionBlocks(document, heading)) {
1657
+ if (!(0, _orkestrel_markdown.isTableNode)(block)) continue;
1658
+ for (const row of block.rows) {
1659
+ const cell = row[0];
1660
+ if (cell !== void 0 && findFirstCode(cell) !== void 0) continue;
1661
+ unnamed.push(row.map((content) => extractCellText(content)).join(" | "));
1662
+ }
1663
+ }
1664
+ return unnamed;
1665
+ }
1666
+ /**
1309
1667
  * Extracts every link href in the guide document, including table cells — a full,
1310
1668
  * depth-first walk of the whole AST.
1311
1669
  *
@@ -1340,38 +1698,230 @@ function extractTests(document) {
1340
1698
  return links;
1341
1699
  }
1342
1700
  /**
1343
- * Selects the next physical record after an eligible genuine JSDoc whose final
1344
- * authoritative span carries an exact block-position `@example` tag. Title
1345
- * text is allowed. A leading whitespace-separated span chain is last-span
1346
- * authoritative; intervening source material severs association, while a
1347
- * leading JSDoc on the next record replaces pending state. Any other next
1348
- * physical record is returned once and consumes it. This parser walks aligned
1349
- * records without rescanning source syntax or applying declaration/member
1350
- * grammar.
1701
+ * Returns the canonical body of one genuine JSDoc span — the `/**` opener, the closing
1702
+ * marker, each line's continuation marker, and the block's leading indentation removed,
1703
+ * with per-line trailing whitespace trimmed and the surrounding blank lines dropped. A
1704
+ * line's own indentation beyond the marker is kept, so an `@example` fence body keeps the
1705
+ * shape it was written in.
1706
+ *
1707
+ * @param comment - One complete genuine JSDoc span's raw text
1708
+ * @returns The span's unwrapped body
1709
+ *
1710
+ * @example
1711
+ * ```ts
1712
+ * normalizeComment('/**' + ' Creates a widget. *' + '/') // 'Creates a widget.'
1713
+ * ```
1714
+ */
1715
+ function normalizeComment(comment) {
1716
+ return unwrapComment(comment).join("\n").replace(/^\n+/, "").replace(/\n+$/, "");
1717
+ }
1718
+ /**
1719
+ * Unwraps one genuine JSDoc span into one content line per physical line — the `/**` opener,
1720
+ * the closing marker, each line's continuation marker, and per-line trailing whitespace removed,
1721
+ * with a line's own indentation past the marker kept. The result is aligned with
1722
+ * `comment.split('\n')`, so an index found in it addresses the same physical line of the span it
1723
+ * was built from, which is what lets a rewrite keep every line it does not replace.
1724
+ * {@link normalizeComment} is this projection joined and trimmed at its ends.
1725
+ *
1726
+ * @param comment - One complete genuine JSDoc span's raw text
1727
+ * @returns One content line per physical line of the span
1728
+ *
1729
+ * @example
1730
+ * ```ts
1731
+ * unwrapComment('/**' + '\n * Walks.\n *' + '/') // ['', 'Walks.', '']
1732
+ * ```
1733
+ */
1734
+ function unwrapComment(comment) {
1735
+ return (/^[ \t]*\/\*([\s\S]*?)\*\/[ \t]*$/.exec(comment)?.[1] ?? comment).split("\n").map((line) => line.replace(/^[ \t]*\*[ \t]?/, "").replace(/[ \t]+$/, ""));
1736
+ }
1737
+ /**
1738
+ * Returns the canonical compared form of a description paragraph. `{@link Target}` and
1739
+ * `{@link Target | label}` become the code token of the target text, or of the label where one is
1740
+ * written; a target's module part — the inline import form `import('./module.js').` and TSDoc's
1741
+ * package-qualified form `@scope/pkg#` — is dropped first. Every run of whitespace, including a
1742
+ * collapsed continuation marker and a line break, becomes one space, the ends trim, and a code
1743
+ * span keeps its delimiters while its own boundary whitespace goes. The guide's side and the
1744
+ * source's side read through this one form.
1745
+ *
1746
+ * @remarks
1747
+ * The clauses land in a fixed order, because each one decides what the next one sees. Every
1748
+ * single-backtick code span — one backtick per side, no inner backtick, no adjacent backtick —
1749
+ * is located first, so a delimiter the `{@link}` expansion inserts afterwards is never mistaken
1750
+ * for an authored one. The expansion then runs outside those spans
1751
+ * only, so a `{@link}` written inside a code span stays literal on both sides. Whitespace
1752
+ * collapses next, which is what makes a span wrapped across two physical lines comparable at
1753
+ * all. The boundary trim runs last, inside each located span: the markdown parser strips one
1754
+ * space from each end of a code span it reads, and this trim is the symmetric rule that meets
1755
+ * it, so `` ` | ` ``, `` ` |` ``, and `` `|` `` all reach `` `|` `` from either side. A span
1756
+ * whose content is all whitespace keeps one space, because a parser strips nothing from that
1757
+ * one.
1758
+ *
1759
+ * A target's module part is the inline import form `import('./module.js').` or TSDoc's
1760
+ * package-qualified form `@scope/pkg#`, and the expansion drops it, so a cross-file link and the
1761
+ * code token a guide cell documents it with reach the same text. A package qualifier carries `@`
1762
+ * or `/`; text before a `#` carrying neither is JSDoc's member reference, so `{@link Owner#member}`
1763
+ * and `{@link #member}` travel whole and a guide cell documents each as written. An unscoped
1764
+ * package name is spelled like an owner, so `{@link pkg#Name}` travels whole too — write the
1765
+ * scoped or the path form where a cell must drop the package. Everything after a module part
1766
+ * travels: `Owner.member` keeps its owner, and a dotted target no module part precedes is
1767
+ * untouched. A label is text rather than a target, so `{@link Target | label}` renders its label
1768
+ * whole.
1769
+ *
1770
+ * A code span delimited by more than one backtick is outside the compared form's representable
1771
+ * set and travels untouched, as does a code span whose own text carries a backtick: the form
1772
+ * spells every span with one backtick per side, so neither can be written back. A summary that
1773
+ * needs one of those constructs takes another shape: name the construct in prose rather than
1774
+ * expecting the comparison to converge it.
1775
+ *
1776
+ * @param text - A doc block's description paragraph, or a guide cell's flattened text
1777
+ * @returns The compared form of that text
1778
+ *
1779
+ * @example
1780
+ * ```ts
1781
+ * normalizeSummary('Creates a\n{@link Widget}.') // 'Creates a `Widget`.'
1782
+ * normalizeSummary("Reads {@link import('./widgets.js').Widget}.") // 'Reads `Widget`.'
1783
+ * normalizeSummary('Reads {@link @scope/widgets#Widget}.') // 'Reads `Widget`.'
1784
+ * normalizeSummary('Reads {@link Widget#render}.') // 'Reads `Widget#render`.'
1785
+ * normalizeSummary('cells joined by ` | `.') // 'cells joined by `|`.'
1786
+ * ```
1787
+ */
1788
+ function normalizeSummary(text) {
1789
+ const parts = text.split(/((?<!`)`[^`]+`(?!`))/);
1790
+ let normalized = "";
1791
+ for (let index = 0; index < parts.length; index += 1) {
1792
+ const part = parts[index] ?? "";
1793
+ if (index % 2 === 0) {
1794
+ normalized += part.replace(/\{@link\s+[^}|]*\|\s*([^}]*?)\s*\}/g, "`$1`").replace(/\{@link\s+(?:import\([^)]*\)\.|[^}|#\s]*[@/][^}|#\s]*#)?([^}|]*?)\s*\}/g, "`$1`");
1795
+ continue;
1796
+ }
1797
+ const value = part.slice(1, -1).replace(/\s+/g, " ").trim();
1798
+ normalized += `\`${value.length === 0 ? " " : value}\``;
1799
+ }
1800
+ return normalized.replace(/\s+/g, " ").trim();
1801
+ }
1802
+ /**
1803
+ * Wraps one paragraph into greedy lines no longer than `width` characters. Every run of
1804
+ * whitespace separates words, and a word longer than `width` takes its own line rather than
1805
+ * being split, so a long code token or URL survives the wrap intact.
1806
+ *
1807
+ * @param text - The paragraph to wrap
1808
+ * @param width - The greatest length a returned line may reach
1809
+ * @returns The wrapped lines, in order, or an empty list when `text` carries no word
1810
+ *
1811
+ * @example
1812
+ * ```ts
1813
+ * wrapText('one two three', 8) // ['one two', 'three']
1814
+ * ```
1815
+ */
1816
+ function wrapText(text, width) {
1817
+ const lines = [];
1818
+ let current = "";
1819
+ for (const word of text.split(/\s+/)) {
1820
+ if (word.length === 0) continue;
1821
+ if (current.length === 0) current = word;
1822
+ else if (current.length + 1 + word.length <= width) current += ` ${word}`;
1823
+ else {
1824
+ lines.push(current);
1825
+ current = word;
1826
+ }
1827
+ }
1828
+ if (current.length > 0) lines.push(current);
1829
+ return lines;
1830
+ }
1831
+ /**
1832
+ * Builds one genuine JSDoc span from its content lines — the inverse of {@link unwrapComment}.
1833
+ * Each line is emitted at `indent` behind a continuation marker, an empty line as the bare
1834
+ * marker so no line carries trailing whitespace, and the leading and trailing empty lines are
1835
+ * dropped because the opener and the closer take those physical lines.
1836
+ *
1837
+ * @param lines - The span's content lines, as {@link unwrapComment} returns them
1838
+ * @param indent - The whitespace the span opens at
1839
+ * @returns The span's raw text, opener and closer included
1840
+ *
1841
+ * @example
1842
+ * ```ts
1843
+ * buildComment(['Walks.'], '') // '/**\n * Walks.\n *' + '/'
1844
+ * ```
1845
+ */
1846
+ function buildComment(lines, indent) {
1847
+ const content = [...lines];
1848
+ while (content[0] === "") content.shift();
1849
+ while (content[content.length - 1] === "") content.pop();
1850
+ const raw = [`${indent}/**`];
1851
+ for (const line of content) raw.push(line.length === 0 ? `${indent} *` : `${indent} * ${line}`);
1852
+ raw.push(`${indent} */`);
1853
+ return raw.join("\n");
1854
+ }
1855
+ /**
1856
+ * Returns one doc block's unwrapped text with every fenced body replaced by aligned spaces,
1857
+ * so a tag search reads the block's structure and never its example code. A line opening with
1858
+ * three or more backticks or tildes opens a body, the first line opening with a run of the same
1859
+ * character at least as long closes it, an unclosed body runs to the end, and the marker lines
1860
+ * themselves stay. The projection preserves every line and every column, so an index found in
1861
+ * it addresses the same character of the text it was built from.
1862
+ *
1863
+ * @param text - One doc block's unwrapped text, as {@link normalizeComment} returns it
1864
+ * @returns The same text with each fenced body's characters replaced by spaces
1865
+ *
1866
+ * @example
1867
+ * ```ts
1868
+ * maskFences('@example\n~~~\n@decorator()\n~~~').split('\n')[2] // ' '
1869
+ * ```
1870
+ */
1871
+ function maskFences(text) {
1872
+ const masked = [];
1873
+ let marker;
1874
+ for (const line of text.split("\n")) {
1875
+ const fence = /^[ \t]*(`{3,}|~{3,})/.exec(line)?.[1];
1876
+ if (marker === void 0) {
1877
+ masked.push(line);
1878
+ marker = fence;
1879
+ continue;
1880
+ }
1881
+ const closing = fence !== void 0 && fence.startsWith(marker);
1882
+ masked.push(closing ? line : " ".repeat(line.length));
1883
+ if (closing) marker = void 0;
1884
+ }
1885
+ return masked.join("\n");
1886
+ }
1887
+ /**
1888
+ * Extracts every eligible genuine JSDoc block paired with the physical record it documents.
1889
+ *
1890
+ * @remarks
1891
+ * An opener is eligible only when it is the first non-whitespace source material of its record; a
1892
+ * leading whitespace-separated span chain is last-span authoritative; intervening source material
1893
+ * severs association, while a leading JSDoc on the next record replaces pending state. Any other
1894
+ * next physical record is returned once and consumes it. This parser walks aligned records without
1895
+ * rescanning source syntax or applying declaration/member grammar, and every reader of a doc
1896
+ * block's text — the description paragraph, the `@example` blocks, the member summaries — reads it
1897
+ * through this one walk.
1351
1898
  *
1352
1899
  * @param lines - Aligned physical source-line records
1353
- * @returns The immediately following candidate lines, in source order
1900
+ * @returns One record per documented physical line, in source order
1354
1901
  *
1355
1902
  * @example
1356
1903
  * ```ts
1357
- * extractExampleLines(extractSourceLines('/** @example *' + '/\nexport function walk() {}'))
1358
- * // the `export function walk() {}` SourceLine
1904
+ * extractSourceComments(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}'))
1905
+ * // [{ text: 'Walks.', line: the `export function walk() {}` SourceLine }]
1359
1906
  * ```
1360
1907
  */
1361
- function extractExampleLines(lines) {
1362
- const examples = [];
1908
+ function extractSourceComments(lines) {
1909
+ const comments = [];
1363
1910
  let block = false;
1364
1911
  let eligible = false;
1365
- let example = false;
1366
- let pending = false;
1912
+ let span = [];
1913
+ let pending;
1367
1914
  for (const line of lines) {
1368
1915
  const projection = line.jsdoc;
1369
1916
  const first = projection?.indexOf("/**") ?? -1;
1370
- if (pending) {
1371
- if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = false;
1917
+ if (pending !== void 0) {
1918
+ if (!block && first >= 0 && line.source.slice(0, first).trim() === "") pending = void 0;
1372
1919
  else {
1373
- examples.push(line);
1374
- pending = false;
1920
+ comments.push({
1921
+ text: pending,
1922
+ line
1923
+ });
1924
+ pending = void 0;
1375
1925
  }
1376
1926
  }
1377
1927
  if (projection === void 0) continue;
@@ -1379,29 +1929,29 @@ function extractExampleLines(lines) {
1379
1929
  if (block) {
1380
1930
  const close = projection.indexOf("*/");
1381
1931
  const end = close < 0 ? projection.length : close + 2;
1382
- if (eligible && /^\s*\*?\s*@example(?=\s|\*\/|$)/.test(projection.slice(0, end))) example = true;
1932
+ span.push(projection.slice(0, end));
1383
1933
  if (close < 0) continue;
1384
1934
  block = false;
1385
1935
  const opener = projection.indexOf("/**", close + 2);
1386
1936
  const endOfGap = opener < 0 ? line.source.length : opener;
1387
1937
  const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1388
1938
  if (opener < 0) {
1389
- pending = eligible && example && whitespace;
1939
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1390
1940
  continue;
1391
1941
  }
1392
1942
  eligible = eligible && whitespace;
1393
- example = false;
1943
+ span = [];
1394
1944
  cursor = opener;
1395
1945
  } else {
1396
1946
  if (first < 0) continue;
1397
1947
  eligible = line.source.slice(0, first).trim() === "";
1398
- example = false;
1948
+ span = [];
1399
1949
  cursor = first;
1400
1950
  }
1401
1951
  while (cursor < projection.length) {
1402
1952
  const close = projection.indexOf("*/", cursor + 2);
1403
1953
  const end = close < 0 ? projection.length : close + 2;
1404
- if (eligible && /^\s*\*?\s*@example(?=\s|\*\/|$)/.test(projection.slice(cursor + 3, end))) example = true;
1954
+ span.push(projection.slice(cursor, end));
1405
1955
  if (close < 0) {
1406
1956
  block = true;
1407
1957
  break;
@@ -1410,90 +1960,1021 @@ function extractExampleLines(lines) {
1410
1960
  const endOfGap = opener < 0 ? line.source.length : opener;
1411
1961
  const whitespace = line.source.slice(close + 2, endOfGap).trim() === "";
1412
1962
  if (opener < 0) {
1413
- pending = eligible && example && whitespace;
1963
+ pending = eligible && whitespace ? normalizeComment(span.join("\n")) : void 0;
1414
1964
  break;
1415
1965
  }
1416
1966
  eligible = eligible && whitespace;
1417
- example = false;
1967
+ span = [];
1418
1968
  cursor = opener;
1419
1969
  }
1420
1970
  }
1421
- return examples;
1971
+ return comments;
1422
1972
  }
1423
1973
  /**
1424
- * Extracts the exported functions in one file's source text whose immediately preceding
1425
- * eligible genuine JSDoc block carries `@example`. Shared adjacency comes from
1426
- * {@link extractExampleLines}; exported-function membership is matched against
1427
- * the aligned code projection, so comment and template payload cannot qualify.
1974
+ * Selects the next physical record after an eligible genuine JSDoc whose final
1975
+ * authoritative span carries an `@example` tag opening a line at its first non-blank column —
1976
+ * the {@link extractSourceComments} walk filtered to the blocks that carry one. Title
1977
+ * text is allowed, and {@link maskFences} keeps a fenced body's own lines out of the search.
1428
1978
  *
1429
- * @param source - The file's source text
1430
- * @returns The exported function names with an `@example`, in file order
1979
+ * @param lines - Aligned physical source-line records
1980
+ * @returns The immediately following candidate lines, in source order
1431
1981
  *
1432
1982
  * @example
1433
1983
  * ```ts
1434
- * const block = ['/**', ' * @example', ' *' + '/', 'export function walk() {}', ''].join('\n')
1435
- * extractExamples(block) // ['walk']
1436
- * extractExamples('export function walk() {}\n') // []
1984
+ * extractExampleLines(extractSourceLines('/**' + ' @example *' + '/\nexport function walk() {}'))
1985
+ * // the `export function walk() {}` SourceLine
1437
1986
  * ```
1438
1987
  */
1439
- function extractExamples(source) {
1440
- const names = [];
1441
- const seen = /* @__PURE__ */ new Set();
1442
- for (const line of extractExampleLines(extractSourceLines(source))) {
1443
- const name = line.code.match(/^export (?:async )?function\*? (\w+)/)?.[1];
1444
- if ((0, _orkestrel_contract.isNonEmptyString)(name) && !seen.has(name)) {
1445
- seen.add(name);
1446
- names.push(name);
1447
- }
1448
- }
1449
- return names;
1988
+ function extractExampleLines(lines) {
1989
+ return extractSourceComments(lines).filter((comment) => /^[ \t]*@example(?=[ \t]|$)/m.test(maskFences(comment.text))).map((comment) => comment.line);
1450
1990
  }
1451
1991
  /**
1452
- * Extracts the callable-member names in a declaration body (per {@link extractMemberMethods}'
1453
- * grammar) whose immediately preceding eligible genuine JSDoc block, within
1454
- * the same body, carries `@example`. Shared adjacency comes from
1455
- * {@link extractExampleLines}; member membership is matched against aligned
1456
- * projected code.
1992
+ * Collects the description paragraph of every documented physical record — a doc block's
1993
+ * text before its first block tag, in {@link normalizeSummary}'s compared form — keyed by the
1994
+ * record it documents. A record whose block carries no description contributes no entry, so
1995
+ * an absent summary stays absent rather than becoming an empty string.
1457
1996
  *
1458
- * @param lines - A declaration's body lines
1459
- * @returns The exemplified member names, deduped and sorted
1997
+ * @param lines - Aligned physical source-line records
1998
+ * @returns One entry per documented record carrying a description paragraph
1460
1999
  *
1461
2000
  * @example
1462
2001
  * ```ts
1463
- * extractExampleMethods(['\t/**', '\t * @example', '\t *' + '/', '\twalk(): void']) // ['walk']
2002
+ * collectSummaries(extractSourceLines('/**' + ' Walks. *' + '/\nexport function walk() {}')).size // 1
1464
2003
  * ```
1465
2004
  */
1466
- function extractExampleMethods(lines) {
1467
- const methods = [];
1468
- const seen = /* @__PURE__ */ new Set();
1469
- for (const line of extractExampleLines(extractSourceLines(lines.join("\n")))) {
1470
- const name = line.code.match(/^\t(?:async )?\*?(\w+)\??(<.*>)?\(/)?.[1];
1471
- if ((0, _orkestrel_contract.isNonEmptyString)(name) && !seen.has(name)) {
1472
- seen.add(name);
1473
- methods.push(name);
1474
- }
2005
+ function collectSummaries(lines) {
2006
+ const summaries = /* @__PURE__ */ new Map();
2007
+ for (const comment of extractSourceComments(lines)) {
2008
+ const tag = maskFences(comment.text).search(/^[ \t]*@\w/m);
2009
+ const summary = normalizeSummary(tag < 0 ? comment.text : comment.text.slice(0, tag));
2010
+ if (summary.length > 0) summaries.set(comment.line, summary);
1475
2011
  }
1476
- return Array.from(new Set(methods)).sort();
2012
+ return summaries;
1477
2013
  }
1478
2014
  /**
1479
- * Extracts every fenced code block anywhere in the guide document. A full AST walk
1480
- * includes fences nested inside blockquotes and lists.
2015
+ * Extracts the aligned physical records of a declaration's body, read inside an owner head this
2016
+ * function supplies, so a callable member in the body carries the `Owner.member` key
2017
+ * {@link collectKeys} reports for it, and that head's own record opens the projection. A body
2018
+ * read on its own carries no head, and the member grammar attaches a member to the head
2019
+ * enclosing it.
1481
2020
  *
1482
- * @param document - The parsed guide document
1483
- * @returns Every fence's language and verbatim code, in document order
2021
+ * @remarks
2022
+ * The supplied head is an `export interface` line, so the projection opens with that head's own
2023
+ * record and every body line follows it in order. A column-zero `}` among the body lines closes
2024
+ * the supplied head and leaves every later member unkeyed; a body {@link extractDeclaration}
2025
+ * returns carries none, because that reader ends a body at the first one.
2026
+ *
2027
+ * @param lines - A declaration's body lines
2028
+ * @returns The supplied head's record, then one record per body line
1484
2029
  *
1485
2030
  * @example
1486
2031
  * ```ts
1487
- * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2032
+ * extractBodyLines(['\twalk(): void'])[1]?.code // '\twalk(): void'
1488
2033
  * ```
1489
2034
  */
1490
- function extractFences(document) {
1491
- const fences = [];
1492
- for (const node of (0, _orkestrel_markdown.walkNodes)(document)) if ((0, _orkestrel_markdown.isCodeBlockNode)(node)) fences.push({
1493
- language: node.lang,
1494
- code: node.code
1495
- });
1496
- return fences;
2035
+ function extractBodyLines(lines) {
2036
+ return extractSourceLines(["export interface Owner {", ...lines].join("\n"));
2037
+ }
2038
+ /**
2039
+ * Collects the compared key of every physical record a key names — a {@link computeSymbolKey}
2040
+ * symbol key for a column-zero `export` declaration head, an `Owner.member` key for a one-tab
2041
+ * callable member inside one — keyed by the record itself. The owner closes at the first
2042
+ * column-zero `}` or at a column-zero `export` declaration carrying another keyword, and a
2043
+ * record no key names contributes no entry.
2044
+ *
2045
+ * @remarks
2046
+ * This is the package's one key grammar, and each keyed reader projects its own part back out of
2047
+ * it: {@link extractExports} splits a declaration key at its one space,
2048
+ * {@link extractMemberMethods} and {@link extractExampleMethods} split a member key at its dot,
2049
+ * and {@link locateComment} matches a caller's key against the whole map. A change to the head
2050
+ * shape or to the member shape reaches every one of them at once.
2051
+ *
2052
+ * An owner opens at a column-zero `export class` or `export interface` head and closes at the
2053
+ * 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,
2054
+ * because a member belongs to the head enclosing it. Reading runs over {@link extractSourceLines}'s
2055
+ * projection, so a head or
2056
+ * a member written inside a comment or a template literal keys nothing.
2057
+ *
2058
+ * @param lines - Aligned physical source-line records
2059
+ * @returns One entry per record a key names, in file order
2060
+ *
2061
+ * @example
2062
+ * ```ts
2063
+ * const keys = collectKeys(extractSourceLines('export class Widget {\n\twalk(): void\n}'))
2064
+ * Array.from(keys.values()) // ['class Widget', 'Widget.walk']
2065
+ * ```
2066
+ */
2067
+ function collectKeys(lines) {
2068
+ const keys = /* @__PURE__ */ new Map();
2069
+ let owner;
2070
+ for (const line of lines) {
2071
+ const head = /^export (?:async )?(function\*?|class|const|interface|type) (\w+)/.exec(line.code);
2072
+ const keyword = head?.[1]?.replace(/\*$/, "");
2073
+ const name = head?.[2];
2074
+ if ((0, _orkestrel_contract.isNonEmptyString)(keyword) && (0, _orkestrel_contract.isNonEmptyString)(name) && isExportKeyword(keyword)) {
2075
+ keys.set(line, computeSymbolKey({
2076
+ name,
2077
+ keyword
2078
+ }));
2079
+ owner = keyword === "class" || keyword === "interface" ? name : void 0;
2080
+ continue;
2081
+ }
2082
+ if (line.code === "}") {
2083
+ owner = void 0;
2084
+ continue;
2085
+ }
2086
+ const member = /^\t(?:async )?\*?(\w+)\??(?:<.*>)?\(/.exec(line.code)?.[1];
2087
+ if (owner !== void 0 && (0, _orkestrel_contract.isNonEmptyString)(member)) keys.set(line, `${owner}.${member}`);
2088
+ }
2089
+ return keys;
2090
+ }
2091
+ /**
2092
+ * Collects the `@example` blocks one doc block's unwrapped text carries, each named for the
2093
+ * declaration or member the block documents. The text after the tag becomes the block's
2094
+ * `title`; a body opening with a fence contributes that fence's language and its verbatim
2095
+ * body, and a body with no fence contributes its own trimmed text as the code.
2096
+ *
2097
+ * @param comment - One doc block's unwrapped text, as {@link normalizeComment} returns it
2098
+ * @param name - The declaration or member the block documents
2099
+ * @returns The block's `@example` entries, in block order
2100
+ *
2101
+ * @example
2102
+ * ```ts
2103
+ * collectExamples('@example Walking\n```ts\nwalk()\n```', 'walk')
2104
+ * // [{ name: 'walk', title: 'Walking', code: 'walk()', language: 'ts' }]
2105
+ * ```
2106
+ */
2107
+ function collectExamples(comment, name) {
2108
+ const examples = [];
2109
+ const masked = maskFences(comment);
2110
+ const tags = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/gm;
2111
+ let tag;
2112
+ while ((tag = tags.exec(masked)) !== null) {
2113
+ const title = (tag[1] ?? "").trim();
2114
+ const start = tag.index + tag[0].length;
2115
+ const rest = comment.slice(start).replace(/^\n/, "");
2116
+ const next = masked.slice(start).replace(/^\n/, "").search(/^[ \t]*@\w+/m);
2117
+ const body = (next < 0 ? rest : rest.slice(0, next)).replace(/^\n+/, "").replace(/\n+$/, "");
2118
+ const fence = /^```(\S*)\n([\s\S]*?)\n?```/.exec(body);
2119
+ const language = fence?.[1] ?? "";
2120
+ const code = fence?.[2] ?? body;
2121
+ examples.push({
2122
+ name,
2123
+ ...title.length === 0 ? {} : { title },
2124
+ code,
2125
+ ...language.length === 0 ? {} : { language }
2126
+ });
2127
+ }
2128
+ return examples;
2129
+ }
2130
+ /**
2131
+ * Extracts the `@example` blocks carried by the exported declaration heads in one file's source
2132
+ * text, each named for the declaration its block documents. Shared adjacency comes from
2133
+ * {@link extractSourceComments} and each block is read by {@link collectExamples}; head
2134
+ * membership is the {@link collectKeys} key of the documented record under every keyword that
2135
+ * grammar admits at column zero, so comment and template payload cannot qualify and the head
2136
+ * grammar stays the one every reader here shares. A member key carries a dot and a head key
2137
+ * does not, so a member's block belongs to {@link extractExampleMethods} instead. A head
2138
+ * carrying several blocks contributes each.
2139
+ *
2140
+ * @param source - The file's source text
2141
+ * @returns The exported declaration heads' `@example` blocks, in file order, deduplicated by name and title
2142
+ *
2143
+ * @example
2144
+ * ```ts
2145
+ * const block = ['/**', ' * @example', ' * new Widget()', ' *' + '/', 'export class Widget {}', ''].join('\n')
2146
+ * extractExamples(block) // [{ name: 'Widget', code: 'new Widget()' }]
2147
+ * extractExamples('export class Widget {}\n') // []
2148
+ * ```
2149
+ */
2150
+ function extractExamples(source) {
2151
+ const examples = [];
2152
+ const seen = /* @__PURE__ */ new Set();
2153
+ const lines = extractSourceLines(source);
2154
+ const keys = collectKeys(lines);
2155
+ for (const comment of extractSourceComments(lines)) {
2156
+ const key = keys.get(comment.line);
2157
+ if (key === void 0 || key.includes(".")) continue;
2158
+ const name = key.slice(key.indexOf(" ") + 1);
2159
+ for (const example of collectExamples(comment.text, name)) {
2160
+ const entry = `${name}\n${example.title ?? ""}`;
2161
+ if (seen.has(entry)) continue;
2162
+ seen.add(entry);
2163
+ examples.push(example);
2164
+ }
2165
+ }
2166
+ return examples;
2167
+ }
2168
+ /**
2169
+ * Extracts the `@example` blocks carried by the callable members of a declaration body (per
2170
+ * {@link collectKeys}' grammar, the same one {@link extractMemberMethods} reads), each named for
2171
+ * the member its block documents. Shared adjacency comes from {@link extractSourceComments} and
2172
+ * each block is read by {@link collectExamples}; member membership is the key
2173
+ * {@link extractBodyLines}'s projection gives the documented record.
2174
+ *
2175
+ * @param lines - A declaration's body lines
2176
+ * @returns The members' `@example` blocks, deduplicated by name and title and sorted by name
2177
+ *
2178
+ * @example
2179
+ * ```ts
2180
+ * extractExampleMethods(['\t/**', '\t * @example', '\t * walk()', '\t *' + '/', '\twalk(): void'])
2181
+ * // [{ name: 'walk', code: 'walk()' }]
2182
+ * ```
2183
+ */
2184
+ function extractExampleMethods(lines) {
2185
+ const examples = [];
2186
+ const seen = /* @__PURE__ */ new Set();
2187
+ const projected = extractBodyLines(lines);
2188
+ const keys = collectKeys(projected);
2189
+ for (const comment of extractSourceComments(projected)) {
2190
+ const key = keys.get(comment.line) ?? "";
2191
+ const dot = key.indexOf(".");
2192
+ if (dot < 0) continue;
2193
+ const name = key.slice(dot + 1);
2194
+ for (const example of collectExamples(comment.text, name)) {
2195
+ const entry = `${name}\n${example.title ?? ""}`;
2196
+ if (seen.has(entry)) continue;
2197
+ seen.add(entry);
2198
+ examples.push(example);
2199
+ }
2200
+ }
2201
+ return examples.sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
2202
+ }
2203
+ /**
2204
+ * Extracts every fenced code block anywhere in the guide document. A full AST walk
2205
+ * includes fences nested inside blockquotes and lists, and the same walk carries each
2206
+ * fence's nearest preceding heading as its `title` — the key an `@example` block pairs on.
2207
+ * A heading's text is flattened, so a title written with a code span pairs with a plain
2208
+ * `@example` title.
2209
+ *
2210
+ * @param document - The parsed guide document
2211
+ * @returns Every fence's language, verbatim code, and title, in document order
2212
+ *
2213
+ * @example
2214
+ * ```ts
2215
+ * extractFences(document) // [{ language: 'ts', code: "import { X } from './x.js'\nX()" }]
2216
+ * ```
2217
+ */
2218
+ function extractFences(document) {
2219
+ return Array.from(collectFences(document).values());
2220
+ }
2221
+ /**
2222
+ * Collects each fenced code block keyed by its own node, paired with the {@link GuideFence}
2223
+ * {@link extractFences} reports for it — the node-addressed form a rewrite needs, so a caller
2224
+ * that located a fence by title can read that node's source region back from the parser. The map
2225
+ * iterates in document order and a node keys itself, so a repeated identical fence keeps its own
2226
+ * entry.
2227
+ *
2228
+ * @param document - The parsed guide document
2229
+ * @returns One entry per fenced code block, in document order
2230
+ *
2231
+ * @example
2232
+ * ```ts
2233
+ * Array.from(collectFences(document).values()) // [{ language: 'ts', code: 'walk()' }]
2234
+ * ```
2235
+ */
2236
+ function collectFences(document) {
2237
+ const fences = /* @__PURE__ */ new Map();
2238
+ let title = "";
2239
+ for (const node of (0, _orkestrel_markdown.walkNodes)(document)) {
2240
+ if ((0, _orkestrel_markdown.isHeadingNode)(node)) {
2241
+ title = (0, _orkestrel_markdown.flattenText)(node).trim();
2242
+ continue;
2243
+ }
2244
+ if ((0, _orkestrel_markdown.isCodeBlockNode)(node)) fences.set(node, {
2245
+ language: node.lang,
2246
+ code: node.code,
2247
+ ...title.length === 0 ? {} : { title }
2248
+ });
2249
+ }
2250
+ return fences;
2251
+ }
2252
+ /**
2253
+ * Extracts the guide's tagline — the text of the blockquote following the document's H1,
2254
+ * with every code span kept as a code span and whitespace collapsed. A heading before the
2255
+ * blockquote ends the window, so a blockquote elsewhere in the document is not the tagline.
2256
+ *
2257
+ * @param document - The parsed guide document
2258
+ * @returns The tagline, or `undefined` when no blockquote follows an H1 before the next heading
2259
+ *
2260
+ * @example
2261
+ * ```ts
2262
+ * extractTagline(document) // 'A pure, I/O-free guides-parity toolkit'
2263
+ * ```
2264
+ */
2265
+ function extractTagline(document) {
2266
+ let opened = false;
2267
+ for (const block of document.children) {
2268
+ if ((0, _orkestrel_markdown.isHeadingNode)(block)) {
2269
+ if (opened) return void 0;
2270
+ opened = block.level === 1;
2271
+ continue;
2272
+ }
2273
+ if (!opened || !(0, _orkestrel_markdown.isBlockquoteNode)(block)) continue;
2274
+ const text = normalizeSummary(block.children.filter(_orkestrel_markdown.isParagraphNode).map((paragraph) => extractCellText(paragraph.children)).join(" "));
2275
+ return text.length === 0 ? void 0 : text;
2276
+ }
2277
+ }
2278
+ /**
2279
+ * Computes the drift between one compared key's guide text and source text. A pair agrees
2280
+ * only when both sides carry the same text, and every other state is a drift: guide text
2281
+ * alone reports the guide's side, source text alone reports the source's, and neither side
2282
+ * carrying text reports the key by itself. A side carrying no text is absent from the result,
2283
+ * so a documented symbol with no doc block reports as a drift naming the guide's text alone,
2284
+ * and a row a table has no `Summary` column for against a declaration with no doc block
2285
+ * reports as `{ key }`.
2286
+ *
2287
+ * @param key - The compared pair's key
2288
+ * @param category - The compared site the drift came from
2289
+ * @param guide - The guide's text there, or `undefined` when it carries none
2290
+ * @param source - The source's text there, or `undefined` when it carries none
2291
+ * @returns The drift, or `undefined` when both sides carry the same text
2292
+ *
2293
+ * @example
2294
+ * ```ts
2295
+ * computeDrift('function walk', 'summary', 'Walks the tree.', 'Walks a tree.')
2296
+ * // { key: 'function walk', category: 'summary', guide: 'Walks the tree.', source: 'Walks a tree.' }
2297
+ * ```
2298
+ */
2299
+ function computeDrift(key, category, guide, source) {
2300
+ if (guide !== void 0 && guide === source) return void 0;
2301
+ return {
2302
+ key,
2303
+ category,
2304
+ ...guide === void 0 ? {} : { guide },
2305
+ ...source === void 0 ? {} : { source }
2306
+ };
2307
+ }
2308
+ /**
2309
+ * Compares documented and declared membership exactly after sorting copies, preserving duplicates.
2310
+ *
2311
+ * @param spec - The guide inventory key the finding belongs to
2312
+ * @param name - The declaration whose membership is compared
2313
+ * @param documented - The documented member names
2314
+ * @param declared - The declared member names
2315
+ * @returns The membership finding, or `undefined` when the sorted populations match
2316
+ *
2317
+ * @example Compare declaration membership
2318
+ * ```ts
2319
+ * import { compareMembership } from '@orkestrel/guide'
2320
+ *
2321
+ * compareMembership('guides/widget.md', 'WidgetInterface', ['open'], ['open']) // undefined
2322
+ * ```
2323
+ */
2324
+ function compareMembership(spec, name, documented, declared) {
2325
+ const left = [...documented].sort();
2326
+ const right = [...declared].sort();
2327
+ if (JSON.stringify(left) === JSON.stringify(right)) return void 0;
2328
+ return {
2329
+ spec,
2330
+ text: `${spec} ${name} documents ${JSON.stringify(left)} and declares ${JSON.stringify(right)}.`
2331
+ };
2332
+ }
2333
+ /**
2334
+ * Computes a category-separated identity for a guide finding.
2335
+ *
2336
+ * @param spec - The guide inventory key the drift belongs to
2337
+ * @param drift - The categorized disagreement
2338
+ * @returns The inventory key, category, and compared key separated by line feeds
2339
+ *
2340
+ * @example Identify categorized drift
2341
+ * ```ts
2342
+ * import { identifyDrift } from '@orkestrel/guide'
2343
+ *
2344
+ * identifyDrift('guides/widget.md', { category: 'summary', key: 'function open' })
2345
+ * // 'guides/widget.md\nsummary\nfunction open'
2346
+ * ```
2347
+ */
2348
+ function identifyDrift(spec, drift) {
2349
+ return `${spec}\n${drift.category}\n${drift.key}`;
2350
+ }
2351
+ /**
2352
+ * Formats present parity text as a JSON string and absent text as `absent`.
2353
+ *
2354
+ * @param value - The compared side's text, or `undefined` when absent
2355
+ * @returns The developer-facing side text
2356
+ *
2357
+ * @example Format a parity side
2358
+ * ```ts
2359
+ * import { formatSide } from '@orkestrel/guide'
2360
+ *
2361
+ * formatSide('Walks.') // '"Walks."'
2362
+ * formatSide(undefined) // 'absent'
2363
+ * ```
2364
+ */
2365
+ function formatSide(value) {
2366
+ return value === void 0 ? "absent" : JSON.stringify(value);
2367
+ }
2368
+ /**
2369
+ * Formats a categorized drift with its guide and source sides.
2370
+ *
2371
+ * @param drift - The categorized disagreement to format
2372
+ * @returns The complete developer-facing drift text
2373
+ *
2374
+ * @example Format categorized drift
2375
+ * ```ts
2376
+ * import { formatDrift } from '@orkestrel/guide'
2377
+ *
2378
+ * formatDrift({ category: 'summary', key: 'function walk', guide: 'Walks.', source: 'Walks a tree.' })
2379
+ * // 'summary function walk: guide "Walks." source "Walks a tree."'
2380
+ * ```
2381
+ */
2382
+ function formatDrift(drift) {
2383
+ return `${drift.category} ${drift.key}: guide ${formatSide(drift.guide)} source ${formatSide(drift.source)}`;
2384
+ }
2385
+ /**
2386
+ * Finds every disagreement between a guide and the source it documents, naming both sites:
2387
+ * each `## Surface` row against its declaration's description paragraph, each `## Methods`
2388
+ * row against its member's, and the first titled guide fence of a heading against the
2389
+ * `@example` block of the same title. An example's compared text is its language on the first
2390
+ * line and its body beneath, so a fence that names another language drifts on its own.
2391
+ *
2392
+ * @remarks
2393
+ * Only a pair present on both sides is compared, so a symbol, a member, or a title one side
2394
+ * lacks entirely is left to the bijection checks that own it and is never reported twice.
2395
+ * {@link computeDrift} rules each compared pair, so a pair whose sides carry different text, a
2396
+ * pair where one side carries none, and a pair where neither side carries text are all drift.
2397
+ * The pairing is per title across the whole document, not per heading: the first fence a title
2398
+ * reaches is the compared one, and every later fence of that title is outside the comparison,
2399
+ * whether it sits under the same heading or under a second heading of the same text.
2400
+ *
2401
+ * @param guide - The parsed guide
2402
+ * @param source - The reflected source the guide documents
2403
+ * @returns One entry per disagreement: Surface rows, then Methods rows, then examples
2404
+ *
2405
+ * @example
2406
+ * ```ts
2407
+ * findDrift(guide, source) // [{ key: 'function walk', category: 'summary', guide: 'Walks.', source: 'Walks a tree.' }]
2408
+ * ```
2409
+ */
2410
+ function findDrift(guide, source) {
2411
+ const drifts = [];
2412
+ const declared = new Map(source.surface().map((symbol) => [computeSymbolKey(symbol), symbol]));
2413
+ for (const symbol of guide.surface()) {
2414
+ const key = computeSymbolKey(symbol);
2415
+ const match = declared.get(key);
2416
+ if (match === void 0) continue;
2417
+ const drift = computeDrift(key, "summary", symbol.summary, match.summary);
2418
+ if (drift !== void 0) drifts.push(drift);
2419
+ }
2420
+ for (const group of guide.methods()) {
2421
+ const members = new Map(source.methods(group.interface).map((entry) => [entry.name, entry]));
2422
+ for (const entry of group.methods) {
2423
+ const member = members.get(entry.name);
2424
+ if (member === void 0) continue;
2425
+ const drift = computeDrift(`${group.interface}.${entry.name}`, "summary", entry.summary, member.summary);
2426
+ if (drift !== void 0) drifts.push(drift);
2427
+ }
2428
+ }
2429
+ const examples = collectTitles(guide, source);
2430
+ const compared = /* @__PURE__ */ new Set();
2431
+ for (const fence of guide.fences()) {
2432
+ if (fence.title === void 0 || compared.has(fence.title)) continue;
2433
+ compared.add(fence.title);
2434
+ const example = examples.get(fence.title);
2435
+ if (example === void 0) continue;
2436
+ const drift = computeDrift(fence.title, "example", `${fence.language ?? ""}\n${fence.code}`, `${example.language ?? ""}\n${example.code}`);
2437
+ if (drift !== void 0) drifts.push(drift);
2438
+ }
2439
+ return drifts;
2440
+ }
2441
+ /**
2442
+ * Collects the titled `@example` blocks a guide's documented surface reaches — the module's
2443
+ * exported declaration heads, plus the own members of every documented `class` and `interface` —
2444
+ * keyed by title, the first block of a title answering for it.
2445
+ *
2446
+ * @param guide - The parsed guide naming the documented declarations
2447
+ * @param source - The reflected source to read the blocks from
2448
+ * @returns One entry per distinct `@example` title
2449
+ *
2450
+ * @example
2451
+ * ```ts
2452
+ * collectTitles(guide, source).get('Walk a tree') // { name: 'walk', title: 'Walk a tree', code: 'walk()' }
2453
+ * ```
2454
+ */
2455
+ function collectTitles(guide, source) {
2456
+ const titled = /* @__PURE__ */ new Map();
2457
+ const owners = guide.surface().filter((symbol) => symbol.keyword === "class" || symbol.keyword === "interface");
2458
+ const examples = [...source.examples(), ...owners.flatMap((symbol) => source.examples(symbol.name))];
2459
+ for (const example of examples) {
2460
+ if (example.title === void 0 || titled.has(example.title)) continue;
2461
+ titled.set(example.title, example);
2462
+ }
2463
+ return titled;
2464
+ }
2465
+ /**
2466
+ * Builds a copy of `table` with one cell's inline content rebuilt from `text` through
2467
+ * {@link buildCell}. Every other cell keeps its own nodes, so a rewrite touches the one cell it
2468
+ * names and the header and the alignment row travel unchanged.
2469
+ *
2470
+ * @param table - The table to copy
2471
+ * @param row - The index of the row to rewrite within {@link TableNode.rows}
2472
+ * @param column - The index of the cell to rewrite within that row
2473
+ * @param text - The cell's new compared text
2474
+ * @returns The rewritten table
2475
+ *
2476
+ * @example
2477
+ * ```ts
2478
+ * buildTable(table, 0, 2, 'Walks the tree.').rows[0]?.[2] // [{ element: 'text', value: 'Walks the tree.' }]
2479
+ * ```
2480
+ */
2481
+ function buildTable(table, row, column, text) {
2482
+ return {
2483
+ element: "table",
2484
+ header: table.header,
2485
+ rows: table.rows.map((cells, index) => index === row ? cells.map((cell, position) => position === column ? buildCell(text) : cell) : cells),
2486
+ align: table.align
2487
+ };
2488
+ }
2489
+ /**
2490
+ * Builds the fenced code block one `@example` block renders as — its code inside a fence
2491
+ * carrying its language, and an untagged fence when the block names none.
2492
+ *
2493
+ * @param example - The block to render
2494
+ * @returns The fence node
2495
+ *
2496
+ * @example
2497
+ * ```ts
2498
+ * buildFence({ name: 'walk', code: 'walk()', language: 'ts' }) // { element: 'codeBlock', code: 'walk()', lang: 'ts' }
2499
+ * ```
2500
+ */
2501
+ function buildFence(example) {
2502
+ return {
2503
+ element: "codeBlock",
2504
+ code: example.code,
2505
+ ...example.language === void 0 ? {} : { lang: example.language }
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Splices `replacement` into `source` over the region `span` addresses, and returns the result.
2510
+ * The text before the region and the text after it travel byte for byte, so a rewrite that
2511
+ * addresses one node's region changes nothing else in the document.
2512
+ *
2513
+ * @param source - The text to rewrite
2514
+ * @param span - The half-open region to replace: the region `MarkdownInterface.span` reports
2515
+ * for a markdown node, or the one {@link locateComment} reports for a doc block
2516
+ * @param replacement - The text to write over that region
2517
+ * @returns The rewritten text
2518
+ *
2519
+ * @example
2520
+ * ```ts
2521
+ * spliceSpan('one two three', { start: 4, end: 7 }, 'TWO') // 'one TWO three'
2522
+ * ```
2523
+ */
2524
+ function spliceSpan(source, span, replacement) {
2525
+ return source.slice(0, span.start) + replacement + source.slice(span.end);
2526
+ }
2527
+ /**
2528
+ * Renders a `## Surface` table from the symbols a source declares — a `Name`, {@link KIND}, and
2529
+ * {@link SUMMARY} table with one row per symbol, the name as a code span, the keyword as its
2530
+ * text, and the summary through {@link buildCell}. A symbol carrying no summary renders an empty
2531
+ * cell, which {@link extractSurface} reads back as an absent summary.
2532
+ *
2533
+ * @remarks
2534
+ * The render carries no `## Surface` heading, because a guide documents its surface in several
2535
+ * tables under their own sub-headings and one of them is what this function produces. Reading the
2536
+ * render back therefore parses it under that heading. `renderMarkdown` pads every cell to one
2537
+ * space, so the render is not the committed column-aligned bytes; the checkout's formatter
2538
+ * re-aligns the table and the reader compares parsed entries rather than bytes.
2539
+ *
2540
+ * @param symbols - The symbols to document, in row order
2541
+ * @returns The table's markdown source, with no trailing newline
2542
+ *
2543
+ * @example
2544
+ * ```ts
2545
+ * renderSurface([{ name: 'walk', keyword: 'function', summary: 'Walks the tree.' }])
2546
+ * // '| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks the tree. |'
2547
+ * ```
2548
+ */
2549
+ function renderSurface(symbols) {
2550
+ return (0, _orkestrel_markdown.renderMarkdown)({
2551
+ element: "table",
2552
+ header: [
2553
+ [{
2554
+ element: "text",
2555
+ value: "Name"
2556
+ }],
2557
+ [{
2558
+ element: "text",
2559
+ value: KIND
2560
+ }],
2561
+ [{
2562
+ element: "text",
2563
+ value: SUMMARY
2564
+ }]
2565
+ ],
2566
+ rows: symbols.map((symbol) => [
2567
+ [{
2568
+ element: "codeSpan",
2569
+ value: symbol.name
2570
+ }],
2571
+ [{
2572
+ element: "text",
2573
+ value: symbol.keyword
2574
+ }],
2575
+ buildCell(symbol.summary ?? "")
2576
+ ]),
2577
+ align: [
2578
+ null,
2579
+ null,
2580
+ null
2581
+ ]
2582
+ });
2583
+ }
2584
+ /**
2585
+ * Renders one `## Methods` group — the `####` heading naming the interface as a code span, then
2586
+ * a `Name` and {@link SUMMARY} table with one row per documented member. A member carrying no
2587
+ * summary renders an empty cell, which {@link extractMethods} reads back as an absent summary.
2588
+ *
2589
+ * @remarks
2590
+ * The render carries no `## Methods` heading, for the reason {@link renderSurface} states:
2591
+ * a guide documents one group per interface under that one section heading.
2592
+ *
2593
+ * @param group - The interface and its members
2594
+ * @returns The heading and table's markdown source, with no trailing newline
2595
+ *
2596
+ * @example
2597
+ * ```ts
2598
+ * renderMethods({ interface: 'WidgetInterface', methods: [{ name: 'walk', summary: 'Walks.' }] })
2599
+ * // '#### `WidgetInterface`\n\n| Name | Summary |\n| --- | --- |\n| `walk` | Walks. |'
2600
+ * ```
2601
+ */
2602
+ function renderMethods(group) {
2603
+ return (0, _orkestrel_markdown.renderMarkdown)({
2604
+ element: "document",
2605
+ children: [{
2606
+ element: "heading",
2607
+ level: 4,
2608
+ children: [{
2609
+ element: "codeSpan",
2610
+ value: group.interface
2611
+ }]
2612
+ }, {
2613
+ element: "table",
2614
+ header: [[{
2615
+ element: "text",
2616
+ value: "Name"
2617
+ }], [{
2618
+ element: "text",
2619
+ value: SUMMARY
2620
+ }]],
2621
+ rows: group.methods.map((entry) => [[{
2622
+ element: "codeSpan",
2623
+ value: entry.name
2624
+ }], buildCell(entry.summary ?? "")]),
2625
+ align: [null, null]
2626
+ }]
2627
+ });
2628
+ }
2629
+ /**
2630
+ * Renders one `@example` block as the guide fence it pairs with — an H3 heading carrying the
2631
+ * block's title, then a fence carrying its language and its code. An untitled block renders the
2632
+ * fence alone, because a fence pairs on its nearest preceding heading and an untitled block
2633
+ * claims none.
2634
+ *
2635
+ * @remarks
2636
+ * The title renders as literal text rather than markdown, so a title carrying backticks or
2637
+ * emphasis reads back through {@link extractFences} as the text the `@example` tag carried.
2638
+ * The heading level is 3 because a guide documents its examples one level under a `##` section;
2639
+ * {@link extractFences} pairs on the nearest preceding heading of any level, so the level is
2640
+ * presentation rather than pairing.
2641
+ *
2642
+ * @param example - The block to render
2643
+ * @returns The heading and fence's markdown source, with no trailing newline
2644
+ *
2645
+ * @example
2646
+ * ```ts
2647
+ * renderExample({ name: 'walk', title: 'Walk a tree', code: 'walk()', language: 'ts' })
2648
+ * // an H3 heading of 'Walk a tree', then a fence tagged `ts` carrying `walk()`
2649
+ * ```
2650
+ */
2651
+ function renderExample(example) {
2652
+ const fence = buildFence(example);
2653
+ return (0, _orkestrel_markdown.renderMarkdown)({
2654
+ element: "document",
2655
+ children: example.title === void 0 ? [fence] : [{
2656
+ element: "heading",
2657
+ level: 3,
2658
+ children: [{
2659
+ element: "text",
2660
+ value: example.title
2661
+ }]
2662
+ }, fence]
2663
+ });
2664
+ }
2665
+ /**
2666
+ * Replaces one compared cell in a guide's text and returns the whole guide back. `key` names the
2667
+ * row the way {@link findDrift} names it — a {@link computeSymbolKey} key for a `## Surface` row,
2668
+ * an `Owner.member` key for a `## Methods` row — and the row's {@link SUMMARY} cell becomes
2669
+ * `summary`. Only the table's own source region is rewritten, so every byte outside it travels
2670
+ * unchanged; a key reaching no cell returns `undefined`, and a row already carrying the summary
2671
+ * returns the guide byte for byte.
2672
+ *
2673
+ * @remarks
2674
+ * A row the key does not reach, a table carrying no {@link SUMMARY} column, and a document whose
2675
+ * parse recorded no region for the table are each a miss, and a miss returns `undefined` rather
2676
+ * than throwing, so a caller reports the key it could not place — the one meaning `undefined`
2677
+ * carries in every replacer here. A row already carrying `summary` returns the guide byte for
2678
+ * byte, because a rewrite would re-pad the whole table for no change; that identity reads both
2679
+ * sides through {@link normalizeSummary}, so a caller passing text the compared form still moves
2680
+ * is a fixed point on the second run rather than a row rewritten forever. The rewritten table
2681
+ * renders one-space padded whatever padding it carried, so the checkout's formatter re-aligns it.
2682
+ *
2683
+ * @param guide - The guide's markdown source
2684
+ * @param key - The compared key naming the row
2685
+ * @param summary - The row's new compared text
2686
+ * @returns The guide's text with that cell replaced, or `undefined` when the key reaches no cell
2687
+ *
2688
+ * @example
2689
+ * ```ts
2690
+ * replaceCell('## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks. |', 'function walk', 'Walks a tree.')
2691
+ * // '## Surface\n\n| Name | Kind | Summary |\n| --- | --- | --- |\n| `walk` | function | Walks a tree. |'
2692
+ * ```
2693
+ */
2694
+ function replaceCell(guide, key, summary) {
2695
+ const markdown = (0, _orkestrel_markdown.createMarkdown)(guide);
2696
+ const document = markdown.document;
2697
+ let located;
2698
+ let index = -1;
2699
+ for (const block of selectSectionBlocks(document, SURFACE)) {
2700
+ if (located !== void 0 || !(0, _orkestrel_markdown.isTableNode)(block)) continue;
2701
+ for (let row = 0; row < block.rows.length && located === void 0; row += 1) {
2702
+ const symbol = extractRowSymbol(block, row);
2703
+ if (symbol === void 0 || computeSymbolKey(symbol) !== key) continue;
2704
+ located = block;
2705
+ index = row;
2706
+ }
2707
+ }
2708
+ for (const [table, owner] of collectGroups(document)) {
2709
+ if (located !== void 0) break;
2710
+ for (let row = 0; row < table.rows.length && located === void 0; row += 1) {
2711
+ const entry = extractRowEntry(table, row);
2712
+ if (entry === void 0 || `${owner}.${entry.name}` !== key) continue;
2713
+ located = table;
2714
+ index = row;
2715
+ }
2716
+ }
2717
+ if (located === void 0) return void 0;
2718
+ const column = findColumnIndex(located, SUMMARY);
2719
+ if (column === void 0) return void 0;
2720
+ if ((extractRowSummary(located, index) ?? "") === normalizeSummary(summary)) return guide;
2721
+ const span = markdown.span(located);
2722
+ if (span === void 0) return void 0;
2723
+ return spliceSpan(guide, span, (0, _orkestrel_markdown.renderMarkdown)(buildTable(located, index, column, summary)));
2724
+ }
2725
+ /**
2726
+ * Replaces one titled fence in a guide's text and returns the whole guide back. The first fence
2727
+ * carrying `title` — the pairing {@link findDrift} compares on — takes `example`'s language and
2728
+ * code. Only the fence's own source region is rewritten, so every byte outside it travels
2729
+ * unchanged; a title no fence carries returns `undefined`, and a fence already carrying that
2730
+ * body returns the guide byte for byte.
2731
+ *
2732
+ * @remarks
2733
+ * A title no fence carries and a document whose parse recorded no region for the fence are each a
2734
+ * miss, and a miss returns `undefined` rather than throwing — the one meaning `undefined` carries
2735
+ * in every replacer here. A fence already carrying that language and code returns the guide
2736
+ * byte for byte. A later fence of the same title is outside the pairing and is never rewritten,
2737
+ * which is the rule {@link findDrift} compares under.
2738
+ *
2739
+ * @param guide - The guide's markdown source
2740
+ * @param title - The heading text the fence pairs on
2741
+ * @param example - The block whose language and code the fence takes
2742
+ * @returns The guide's text with that fence replaced, or `undefined` when no fence carries the title
2743
+ *
2744
+ * @example
2745
+ * ```ts
2746
+ * replaceFence(guide, 'Walk', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2747
+ * // the guide's text with the fence under its `### Walk` heading carrying `walk()`
2748
+ * ```
2749
+ */
2750
+ function replaceFence(guide, title, example) {
2751
+ const markdown = (0, _orkestrel_markdown.createMarkdown)(guide);
2752
+ let located;
2753
+ let current;
2754
+ for (const [node, fence] of collectFences(markdown.document)) {
2755
+ if (located !== void 0 || fence.title !== title) continue;
2756
+ located = node;
2757
+ current = fence;
2758
+ }
2759
+ if (located === void 0 || current === void 0) return void 0;
2760
+ if (current.code === example.code && current.language === example.language) return guide;
2761
+ const span = markdown.span(located);
2762
+ if (span === void 0) return void 0;
2763
+ return spliceSpan(guide, span, (0, _orkestrel_markdown.renderMarkdown)(buildFence(example)));
2764
+ }
2765
+ /**
2766
+ * Replaces one doc block's description paragraph with `summary` and returns the whole block back.
2767
+ * The paragraph is the block's text before its first block tag, and it re-wraps inside `width`;
2768
+ * the blank line before the first tag, every tag line, the block's indentation, and its
2769
+ * continuation markers all survive. A block already carrying the summary returns byte for byte,
2770
+ * and a text that is no doc block and a summary carrying no word each return `undefined`.
2771
+ *
2772
+ * @remarks
2773
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2774
+ * caller reports the block it could not rewrite. Text that opens with no
2775
+ * `/**` is no doc block: a single-star `/*` comment reaches this function only by a caller's
2776
+ * mistake, and reshaping it into a doc block would be a silent edit. A `summary` carrying no word
2777
+ * names no paragraph to write, and deleting the block's description on that argument would erase
2778
+ * documentation on the strength of an absent value — a caller with nothing to write writes
2779
+ * nothing.
2780
+ *
2781
+ * A block already carrying `summary` returns byte for byte, which is what keeps a propagation
2782
+ * that finds no drift from rewriting the file: a doc block's own wrapping is not recoverable from
2783
+ * its text, so re-wrapping an unchanged paragraph would move most blocks this package's source
2784
+ * carries. That identity reads both sides through {@link normalizeSummary}, and it holds for a
2785
+ * block carrying no tag as much as for a block carrying several. A block written on one physical
2786
+ * line stays on one line while `summary` still fits inside `width`, and expands otherwise.
2787
+ *
2788
+ * `width` counts characters from the line's first, a tab counting as one, so a wrapped line reads
2789
+ * `${indent} * ${text}` and never passes that count. A caller whose formatter measures a tab as
2790
+ * more than one column passes a smaller width rather than taking the default.
2791
+ *
2792
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2793
+ * @param summary - The block's new description paragraph
2794
+ * @param width - The character budget a re-wrapped line stays inside. Default: {@link WRAP_WIDTH}
2795
+ * @returns The block's raw text with that paragraph replaced, or `undefined` for a text that is
2796
+ * no doc block and for a `summary` carrying no word
2797
+ *
2798
+ * @example
2799
+ * ```ts
2800
+ * replaceSummary('/**' + ' Walks. *' + '/', 'Walks a tree.') // '/**' + ' Walks a tree. *' + '/'
2801
+ * ```
2802
+ */
2803
+ function replaceSummary(comment, summary, width = 100) {
2804
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2805
+ const content = unwrapComment(comment);
2806
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2807
+ const wrapped = wrapText(summary, width - indent.length - 3);
2808
+ if (wrapped.length === 0) return void 0;
2809
+ const masked = maskFences(content.join("\n")).split("\n");
2810
+ let tag = -1;
2811
+ for (let index = 0; index < masked.length && tag < 0; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) tag = index;
2812
+ if (normalizeSummary(content.slice(0, tag < 0 ? content.length : tag).join("\n")) === normalizeSummary(summary)) return comment;
2813
+ const tail = tag < 0 ? [] : content.slice(tag);
2814
+ if (tail.length === 0 && wrapped.length === 1 && content.length === 1) {
2815
+ const single = `${indent}/** ${wrapped[0] ?? ""} */`;
2816
+ if (single.length <= width) return single;
2817
+ }
2818
+ const lines = [...wrapped];
2819
+ if (tail.length > 0) lines.push("");
2820
+ return buildComment([...lines, ...tail], indent);
2821
+ }
2822
+ /**
2823
+ * Replaces the body of one titled `@example` tag in a doc block's raw text and returns the whole
2824
+ * block back. The tag carrying `example`'s title takes a fence of its language and its code;
2825
+ * every other tag, the description paragraph, the block's indentation, and its continuation
2826
+ * markers all survive. A text that is no doc block, a title no tag carries, and a language or
2827
+ * code the emitted three-backtick fence cannot enclose or the doc block cannot hold each return
2828
+ * `undefined`.
2829
+ *
2830
+ * @remarks
2831
+ * A miss returns `undefined`, the one meaning `undefined` carries in every replacer here, so a
2832
+ * caller reports the block it could not rewrite. Text that opens with no
2833
+ * `/**` is no doc block, for the reason {@link replaceSummary} states. A block carrying no
2834
+ * `@example` tag of that title has nowhere to write, so an untitled tag and a tag carrying
2835
+ * another title are each left alone, and an `example` naming no title misses a block whose tags
2836
+ * all carry one. Code carrying a run of three or more backticks is a body the emitted fence
2837
+ * cannot enclose: the fence is three backticks, {@link maskFences} ends a body at the first line
2838
+ * opening a run at least as long, and {@link collectExamples} reads to the first such run
2839
+ * whatever column it sits at, so writing that body would truncate it and turn a following
2840
+ * `@`-line into a tag. A language or code carrying the doc-comment terminator is a body the
2841
+ * block itself cannot hold: the terminator closes the block where it lands and the file stops
2842
+ * parsing there. Refusing keeps the rewrite total over the bodies it can spell.
2843
+ *
2844
+ * A tag already carrying that language and code returns byte for byte. {@link maskFences} keeps
2845
+ * the current body's own lines out of the tag search, so a fenced body carrying a tag-shaped line
2846
+ * does not end the body early. The body ends at its last line carrying text, so the blank line
2847
+ * separating it from the next tag survives.
2848
+ *
2849
+ * @param comment - One complete genuine JSDoc span's raw text, as it sits in the file
2850
+ * @param example - The block whose language and code the tag's body takes
2851
+ * @returns The block's raw text with that body replaced, or `undefined` for a text that is no
2852
+ * doc block, for a title no `@example` tag carries, and for a language or code the emitted
2853
+ * fence cannot enclose or the doc block cannot hold — a body carrying the doc-comment terminator
2854
+ *
2855
+ * @example
2856
+ * ```ts
2857
+ * replaceExample('/**' + '\n * @example Walk\n * old()\n *' + '/', { name: 'walk', title: 'Walk', code: 'walk()', language: 'ts' })
2858
+ * // the same block, its `@example Walk` body now a fence tagged `ts` carrying `walk()`
2859
+ * ```
2860
+ */
2861
+ function replaceExample(comment, example) {
2862
+ if (!/^[ \t]*\/\*\*/.test(comment)) return void 0;
2863
+ if ([example.language ?? "", ...example.code.split("\n")].some((line) => line.includes("```") || line.includes("*/"))) return void 0;
2864
+ const content = unwrapComment(comment);
2865
+ const masked = maskFences(content.join("\n")).split("\n");
2866
+ const title = example.title ?? "";
2867
+ let start = -1;
2868
+ for (let index = 0; index < masked.length && start < 0; index += 1) {
2869
+ const tag = /^[ \t]*@example(?=[ \t]|$)[ \t]*(.*)$/.exec(masked[index] ?? "");
2870
+ if (tag !== null && (tag[1] ?? "").trim() === title) start = index;
2871
+ }
2872
+ if (start < 0) return void 0;
2873
+ const current = collectExamples(content.join("\n"), example.name).find((entry) => (entry.title ?? "") === title);
2874
+ if (current !== void 0 && current.code === example.code && current.language === example.language) return comment;
2875
+ let end = content.length;
2876
+ for (let index = start + 1; index < masked.length && end === content.length; index += 1) if (/^[ \t]*@\w/.test(masked[index] ?? "")) end = index;
2877
+ while (end > start + 1 && (content[end - 1] ?? "").length === 0) end -= 1;
2878
+ const indent = /^[ \t]*/.exec(comment)?.[0] ?? "";
2879
+ const body = [
2880
+ `\`\`\`${example.language ?? ""}`,
2881
+ ...example.code.split("\n"),
2882
+ "```"
2883
+ ];
2884
+ return buildComment([
2885
+ ...content.slice(0, start + 1),
2886
+ ...body,
2887
+ ...content.slice(end)
2888
+ ], indent);
2889
+ }
2890
+ /**
2891
+ * Locates the doc block a compared key attaches to inside one file's text and returns the block's
2892
+ * own character region, so a caller can `slice` the block, rewrite it through
2893
+ * {@link replaceSummary} or {@link replaceExample}, and write the result back through
2894
+ * {@link spliceSpan}. `key` names the pair the way {@link findDrift} names it — a
2895
+ * {@link computeSymbolKey} key for a declaration, an `Owner.member` key for an interface or class
2896
+ * member; the region covers the block's own indentation, and no block carrying the key returns
2897
+ * `undefined`.
2898
+ *
2899
+ * @remarks
2900
+ * Attachment is {@link extractSourceComments}'s, not a second reading of the file: that walk
2901
+ * pairs each eligible block with the physical record it documents, and this function keeps the
2902
+ * record {@link collectKeys} gives `key`. The keys are that one grammar's — the map
2903
+ * {@link extractExports} and {@link extractMemberMethods} each read their own part out of — so
2904
+ * this function runs no head pattern, no member pattern, and no owner-close rule of its own, and
2905
+ * a change to any of them reaches the locator too. Every block {@link collectSummaries} reports
2906
+ * a summary for is reachable by its key, and a block carrying only block tags is reachable too although it carries no summary.
2907
+ * A block it misses is one the comparison never had: a block a blank line separates from its
2908
+ * declaration attaches to the blank line, and a block written inside a template literal or a
2909
+ * string is no genuine span at all. The first block whose record carries the key answers for it,
2910
+ * as the first declaration of a name does everywhere else.
2911
+ *
2912
+ * The region runs from the start of the opener's line, the block's indentation included, to the
2913
+ * character past its closing marker — the raw text {@link replaceSummary} and
2914
+ * {@link replaceExample} each document as the span "as it sits in the file", so a caller slices,
2915
+ * rewrites, and splices with no adjustment and the rewrite keeps the indentation it found. A
2916
+ * block that source material precedes on its own line starts at the opener instead. The region
2917
+ * is read off the aligned JSDoc projection rather than searched for in the text, so an opener
2918
+ * written inside a string never yields one, and line offsets come from
2919
+ * {@link extractSourceLines}'s own records under its stated LF-or-CRLF terminator rule, so a
2920
+ * CRLF file reports the offsets its own bytes carry.
2921
+ *
2922
+ * @param text - One file's whole source text
2923
+ * @param key - The compared key naming the declaration or the member
2924
+ * @returns The block's half-open character region, or `undefined` when no block carries the key
2925
+ *
2926
+ * @example
2927
+ * ```ts
2928
+ * const text = '/**' + ' Walks. *' + '/\nexport function walk(): void {}\n'
2929
+ * locateComment(text, 'function walk') // { start: 0, end: 13 }
2930
+ * ```
2931
+ */
2932
+ function locateComment(text, key) {
2933
+ const lines = extractSourceLines(text);
2934
+ const keys = collectKeys(lines);
2935
+ const offsets = [];
2936
+ const positions = /* @__PURE__ */ new Map();
2937
+ let offset = 0;
2938
+ for (let index = 0; index < lines.length; index += 1) {
2939
+ const line = lines[index];
2940
+ if (line === void 0) continue;
2941
+ offsets.push(offset);
2942
+ positions.set(line, index);
2943
+ const after = offset + line.source.length;
2944
+ offset = after + (text.startsWith("\r\n", after) ? 2 : 1);
2945
+ }
2946
+ for (const comment of extractSourceComments(lines)) {
2947
+ if (keys.get(comment.line) !== key) continue;
2948
+ const close = (positions.get(comment.line) ?? 0) - 1;
2949
+ const closing = lines[close]?.jsdoc;
2950
+ const end = closing === void 0 ? -1 : closing.lastIndexOf("*/");
2951
+ if (end < 0) continue;
2952
+ let first = close;
2953
+ while (first > 0 && lines[first - 1]?.jsdoc !== void 0) first -= 1;
2954
+ let inside = false;
2955
+ let line = -1;
2956
+ let column = -1;
2957
+ for (let index = first; index <= close; index += 1) {
2958
+ const projection = lines[index]?.jsdoc ?? "";
2959
+ let cursor = 0;
2960
+ while (cursor < projection.length) {
2961
+ const at = projection.indexOf(inside ? "*/" : "/**", cursor);
2962
+ if (at < 0) break;
2963
+ if (!inside) {
2964
+ line = index;
2965
+ column = at;
2966
+ }
2967
+ cursor = at + (inside ? 2 : 3);
2968
+ inside = !inside;
2969
+ }
2970
+ }
2971
+ if (line < 0) continue;
2972
+ const start = (lines[line]?.source ?? "").slice(0, column).trim() === "" ? 0 : column;
2973
+ return {
2974
+ start: (offsets[line] ?? 0) + start,
2975
+ end: (offsets[close] ?? 0) + end + 2
2976
+ };
2977
+ }
1497
2978
  }
1498
2979
  //#endregion
1499
2980
  //#region src/core/parsers.ts
@@ -1552,7 +3033,7 @@ function parseManifest(markdown, directory) {
1552
3033
  //#region src/core/shapers.ts
1553
3034
  /**
1554
3035
  * Shapes a {@link SurfaceSymbol} — a documented / exported symbol's `name`
1555
- * paired with its {@link ExportKeyword}.
3036
+ * paired with its {@link ExportKeyword} and its optional compared `summary`.
1556
3037
  *
1557
3038
  * @example
1558
3039
  * ```ts
@@ -1565,7 +3046,63 @@ function parseManifest(markdown, directory) {
1565
3046
  */
1566
3047
  var surfaceSymbolShape = (0, _orkestrel_contract.objectShape)({
1567
3048
  name: (0, _orkestrel_contract.stringShape)(),
1568
- keyword: (0, _orkestrel_contract.literalShape)(EXPORT_KEYWORDS)
3049
+ keyword: (0, _orkestrel_contract.literalShape)(EXPORT_KEYWORDS),
3050
+ summary: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
3051
+ });
3052
+ /**
3053
+ * Shapes a {@link MethodEntry} — one documented method's `name` paired with its optional
3054
+ * compared `summary`.
3055
+ *
3056
+ * @example
3057
+ * ```ts
3058
+ * import { createContract } from '@orkestrel/contract'
3059
+ * import { methodEntryShape } from '@orkestrel/guide'
3060
+ *
3061
+ * const methodEntry = createContract(methodEntryShape)
3062
+ * methodEntry.is({ name: 'walk' }) // true
3063
+ * ```
3064
+ */
3065
+ var methodEntryShape = (0, _orkestrel_contract.objectShape)({
3066
+ name: (0, _orkestrel_contract.stringShape)(),
3067
+ summary: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
3068
+ });
3069
+ /**
3070
+ * Shapes a {@link SourceExample} — one `@example` block's `name`, its optional pairing
3071
+ * `title`, its `code`, and its optional fence `language`.
3072
+ *
3073
+ * @example
3074
+ * ```ts
3075
+ * import { createContract } from '@orkestrel/contract'
3076
+ * import { sourceExampleShape } from '@orkestrel/guide'
3077
+ *
3078
+ * const sourceExample = createContract(sourceExampleShape)
3079
+ * sourceExample.is({ name: 'walk', code: 'walk()' }) // true
3080
+ * ```
3081
+ */
3082
+ var sourceExampleShape = (0, _orkestrel_contract.objectShape)({
3083
+ name: (0, _orkestrel_contract.stringShape)(),
3084
+ title: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
3085
+ code: (0, _orkestrel_contract.stringShape)(),
3086
+ language: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
3087
+ });
3088
+ /**
3089
+ * Shapes a {@link Drift} — one disagreement's compared `key` with the optional text each
3090
+ * side carries there.
3091
+ *
3092
+ * @example
3093
+ * ```ts
3094
+ * import { createContract } from '@orkestrel/contract'
3095
+ * import { driftShape } from '@orkestrel/guide'
3096
+ *
3097
+ * const drift = createContract(driftShape)
3098
+ * drift.is({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
3099
+ * ```
3100
+ */
3101
+ var driftShape = (0, _orkestrel_contract.objectShape)({
3102
+ key: (0, _orkestrel_contract.stringShape)(),
3103
+ category: (0, _orkestrel_contract.literalShape)(DRIFT_CATEGORIES),
3104
+ guide: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
3105
+ source: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
1569
3106
  });
1570
3107
  /**
1571
3108
  * Shapes a {@link MethodGroup} — a backticked `interface` name paired with
@@ -1582,7 +3119,7 @@ var surfaceSymbolShape = (0, _orkestrel_contract.objectShape)({
1582
3119
  */
1583
3120
  var methodGroupShape = (0, _orkestrel_contract.objectShape)({
1584
3121
  interface: (0, _orkestrel_contract.stringShape)(),
1585
- methods: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.stringShape)())
3122
+ methods: (0, _orkestrel_contract.arrayShape)(methodEntryShape)
1586
3123
  });
1587
3124
  /**
1588
3125
  * Shapes a {@link ManifestEntry} — one `## By concept` manifest row, `source`
@@ -1607,8 +3144,8 @@ var manifestEntryShape = (0, _orkestrel_contract.objectShape)({
1607
3144
  //#region src/core/Guide.ts
1608
3145
  /**
1609
3146
  * Presents a pure, structured view over one parsed guide — the documented
1610
- * projections (`sections` / `surface` / `methods` / `links` / `tests` /
1611
- * `fences`) are extracted once at construction and cached.
3147
+ * projections (`sections` / `tagline` / `surface` / `methods` / `unnamed` / `links` /
3148
+ * `tests` / `fences`) are extracted once at construction and cached.
1612
3149
  *
1613
3150
  * @remarks
1614
3151
  * Parses `source` once through `@orkestrel/markdown` and never touches the
@@ -1626,16 +3163,20 @@ var manifestEntryShape = (0, _orkestrel_contract.objectShape)({
1626
3163
  */
1627
3164
  var Guide = class {
1628
3165
  #sections;
3166
+ #tagline;
1629
3167
  #surface;
1630
3168
  #methods;
3169
+ #unnamed;
1631
3170
  #links;
1632
3171
  #tests;
1633
3172
  #fences;
1634
3173
  constructor(source) {
1635
3174
  const document = (0, _orkestrel_markdown.createMarkdown)(source).document;
1636
3175
  this.#sections = document.children.filter(_orkestrel_markdown.isHeadingNode).filter((heading) => heading.level === 2).map((heading) => (0, _orkestrel_markdown.flattenText)(heading).trim());
3176
+ this.#tagline = extractTagline(document);
1637
3177
  this.#surface = extractSurface(document);
1638
3178
  this.#methods = extractMethods(document);
3179
+ this.#unnamed = extractUnnamed(document);
1639
3180
  this.#links = extractLinks(document);
1640
3181
  this.#tests = extractTests(document);
1641
3182
  this.#fences = extractFences(document);
@@ -1643,12 +3184,18 @@ var Guide = class {
1643
3184
  sections() {
1644
3185
  return this.#sections;
1645
3186
  }
3187
+ tagline() {
3188
+ return this.#tagline;
3189
+ }
1646
3190
  surface() {
1647
3191
  return this.#surface;
1648
3192
  }
1649
3193
  methods() {
1650
3194
  return this.#methods;
1651
3195
  }
3196
+ unnamed() {
3197
+ return this.#unnamed;
3198
+ }
1652
3199
  links() {
1653
3200
  return this.#links;
1654
3201
  }
@@ -1668,7 +3215,10 @@ var Guide = class {
1668
3215
  * filesystem. `Source` never touches disk:
1669
3216
  * the consumer gathers the inventory however their environment allows
1670
3217
  * (`node:fs` in a Node script, `import.meta.glob` in a browser/vitest run) and
1671
- * passes it in as `files`. Conventional barrel traversal recurses through both
3218
+ * passes it in as `files`.
3219
+ *
3220
+ * @remarks
3221
+ * Conventional barrel traversal recurses through both
1672
3222
  * exact workspace-root `index.ts` and nested `/index.ts` targets. `'.'` is the
1673
3223
  * canonical workspace-root module, module spellings normalize once at
1674
3224
  * construction, and exact opaque inventory keys are never rewritten; keys with
@@ -1679,11 +3229,16 @@ var Guide = class {
1679
3229
  * from; a base the scope does not declare contributes nothing. One declaration
1680
3230
  * answers for a name: the first file in sorted key order that declares the head
1681
3231
  * supplies its members and its bases, and a second file declaring the same name
1682
- * adds nothing. Source projection preserves columns without widening
1683
- * direct/hidden column-zero heads. Literal ECMAScript Unicode identifiers
1684
- * participate in bounded slash-state recognition without escape decoding.
1685
- * Regex recognition is bounded: slash after bare `}` is division, so a
1686
- * post-brace regex statement requires an explicit `;`. General semicolonless
3232
+ * adds nothing. Every reading derives once per instance from the immutable
3233
+ * inventory and is reused — the scope's declaration map on the first `methods`
3234
+ * or `examples` lookup, then each name's members and each example collection
3235
+ * under the name asked for — so a reader asking twice reads the files once and
3236
+ * receives the same records, and a second instance over the same inventory
3237
+ * derives the same readings of its own. Source projection preserves columns
3238
+ * without widening direct/hidden column-zero heads. Literal ECMAScript Unicode
3239
+ * identifiers participate in bounded slash-state recognition without escape
3240
+ * decoding. Regex recognition is bounded: slash after bare `}` is division, so
3241
+ * a post-brace regex statement requires an explicit `;`. General semicolonless
1687
3242
  * declaration/ASI classification is also outside the finite projector, so a
1688
3243
  * slash-leading statement after such a declaration requires an explicit `;`.
1689
3244
  *
@@ -1701,17 +3256,19 @@ var Guide = class {
1701
3256
  * })
1702
3257
  * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
1703
3258
  * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
1704
- * source.methods('GuideInterface') // ['sections']
3259
+ * source.methods('GuideInterface') // [{ name: 'sections' }]
1705
3260
  * source.exists('src/core/Guide.ts') // true
1706
3261
  * ```
1707
3262
  */
1708
3263
  var Source = class {
1709
3264
  #files;
1710
3265
  #directories;
3266
+ #methods = /* @__PURE__ */ new Map();
3267
+ #examples = /* @__PURE__ */ new Map();
1711
3268
  #exports;
1712
3269
  #surface;
1713
3270
  #hidden;
1714
- #examples;
3271
+ #declarations;
1715
3272
  constructor(options) {
1716
3273
  this.#files = options.files;
1717
3274
  this.#directories = normalizeDirectories(options.module);
@@ -1725,10 +3282,11 @@ var Source = class {
1725
3282
  return this.#surface;
1726
3283
  }
1727
3284
  methods(name) {
1728
- const declared = this.#members("interface", name, /* @__PURE__ */ new Set());
1729
- if (declared !== void 0) return declared;
1730
- const inherited = this.#members("class", name, /* @__PURE__ */ new Set());
1731
- return inherited === void 0 ? [] : inherited.filter((method) => method !== "constructor");
3285
+ const cached = this.#methods.get(name);
3286
+ if (cached !== void 0) return cached;
3287
+ const members = this.#scanMethods(name);
3288
+ this.#methods.set(name, members);
3289
+ return members;
1732
3290
  }
1733
3291
  exists(relative) {
1734
3292
  return Object.keys(this.#files).some((key) => key === relative || key.startsWith(`${relative}/`));
@@ -1738,25 +3296,32 @@ var Source = class {
1738
3296
  return this.#hidden;
1739
3297
  }
1740
3298
  examples(name) {
1741
- if (name === void 0) {
1742
- if (this.#examples === void 0) this.#examples = this.#scanExamples();
1743
- return this.#examples;
1744
- }
1745
- return this.#exampleMembers(name);
3299
+ const cached = this.#examples.get(name);
3300
+ if (cached !== void 0) return cached;
3301
+ const examples = name === void 0 ? this.#scanExamples() : this.#exampleMembers(name);
3302
+ this.#examples.set(name, examples);
3303
+ return examples;
3304
+ }
3305
+ #scanMethods(name) {
3306
+ const declared = this.#members("interface", name, /* @__PURE__ */ new Set());
3307
+ if (declared !== void 0) return declared;
3308
+ const inherited = this.#members("class", name, /* @__PURE__ */ new Set());
3309
+ return inherited === void 0 ? [] : inherited.filter((entry) => entry.name !== "constructor");
1746
3310
  }
1747
3311
  #scanExamples() {
1748
- const names = [];
3312
+ const examples = [];
1749
3313
  const seen = /* @__PURE__ */ new Set();
1750
3314
  for (const key of selectModuleKeys(this.#files, this.#directories)) {
1751
3315
  const text = this.#files[key];
1752
3316
  if (text === void 0) continue;
1753
- for (const name of extractExamples(text)) {
1754
- if (seen.has(name)) continue;
1755
- seen.add(name);
1756
- names.push(name);
3317
+ for (const example of extractExamples(text)) {
3318
+ const identity = `${example.name}\n${example.title ?? ""}`;
3319
+ if (seen.has(identity)) continue;
3320
+ seen.add(identity);
3321
+ examples.push(example);
1757
3322
  }
1758
3323
  }
1759
- return names;
3324
+ return examples;
1760
3325
  }
1761
3326
  #scanSurface() {
1762
3327
  const symbols = [];
@@ -1794,8 +3359,13 @@ var Source = class {
1794
3359
  }
1795
3360
  }
1796
3361
  #exampleMembers(name) {
1797
- const members = /* @__PURE__ */ new Set([...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]);
1798
- return Array.from(members).sort();
3362
+ const members = /* @__PURE__ */ new Map();
3363
+ for (const example of [...extractExampleMethods(this.#locate("interface", name)?.body ?? []), ...extractExampleMethods(this.#locate("class", name)?.body ?? [])]) {
3364
+ const identity = `${example.name}\n${example.title ?? ""}`;
3365
+ if (members.has(identity)) continue;
3366
+ members.set(identity, example);
3367
+ }
3368
+ return Array.from(members.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1799
3369
  }
1800
3370
  #scanSymbols(scan) {
1801
3371
  const symbols = [];
@@ -1817,19 +3387,27 @@ var Source = class {
1817
3387
  visited.add(name);
1818
3388
  const declaration = this.#locate(keyword, name);
1819
3389
  if (declaration === void 0) return void 0;
1820
- const methods = new Set(extractMemberMethods(declaration.body));
1821
- for (const base of declaration.bases) for (const member of this.#members(keyword, base, visited) ?? []) methods.add(member);
1822
- return Array.from(methods).sort();
3390
+ const methods = /* @__PURE__ */ new Map();
3391
+ for (const entry of extractMemberMethods(declaration.body)) methods.set(entry.name, entry);
3392
+ 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);
3393
+ return Array.from(methods.values()).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1);
1823
3394
  }
1824
3395
  #locate(keyword, name) {
3396
+ if (this.#declarations === void 0) this.#declarations = this.#scanDeclarations();
3397
+ return this.#declarations.get(`${keyword} ${name}`);
3398
+ }
3399
+ #scanDeclarations() {
3400
+ const declarations = /* @__PURE__ */ new Map();
1825
3401
  for (const key of selectModuleKeys(this.#files, this.#directories)) {
1826
3402
  const text = this.#files[key];
1827
3403
  if (text === void 0) continue;
1828
- const declaration = extractDeclaration(text, keyword, name);
1829
- if (declaration === void 0) continue;
1830
- if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
1831
- return declaration;
3404
+ for (const [identity, declaration] of collectDeclarations(text)) {
3405
+ if (declarations.has(identity)) continue;
3406
+ if (declaration.body.length === 0 && declaration.bases.length === 0) continue;
3407
+ declarations.set(identity, declaration);
3408
+ }
1832
3409
  }
3410
+ return declarations;
1833
3411
  }
1834
3412
  };
1835
3413
  //#endregion
@@ -1888,6 +3466,440 @@ var SourceManager = class {
1888
3466
  }
1889
3467
  };
1890
3468
  //#endregion
3469
+ //#region src/core/Parity.ts
3470
+ /**
3471
+ * Composes generic guide-parity inspection and explicit in-memory rewrites over a caller inventory.
3472
+ */
3473
+ var Parity = class Parity {
3474
+ #options;
3475
+ #rows;
3476
+ constructor(options) {
3477
+ this.#options = {
3478
+ files: { ...options.files },
3479
+ entries: options.entries.map((entry) => ({ ...entry })),
3480
+ modules: { ...options.modules },
3481
+ languages: [...options.languages],
3482
+ language: options.language,
3483
+ ...options.pitch === void 0 ? {} : { pitch: { ...options.pitch } }
3484
+ };
3485
+ this.#rows = this.#createRows(this.#options.files);
3486
+ }
3487
+ rows() {
3488
+ return this.#rows;
3489
+ }
3490
+ inspect() {
3491
+ const input = [];
3492
+ const sections = [];
3493
+ const surface = [];
3494
+ const methods = [];
3495
+ const declarations = [];
3496
+ const links = [];
3497
+ const tests = [];
3498
+ const fences = [];
3499
+ const exampleFences = [];
3500
+ const exampleFunctions = [];
3501
+ const exampleMethods = [];
3502
+ const exampleTitles = [];
3503
+ const examples = {
3504
+ fences: exampleFences,
3505
+ functions: exampleFunctions,
3506
+ methods: exampleMethods,
3507
+ titles: exampleTitles
3508
+ };
3509
+ const imports = [];
3510
+ const drift = [];
3511
+ const pitch = [];
3512
+ this.#inspectInput(input);
3513
+ for (const row of this.#rows) {
3514
+ this.#inspectSections(row, sections);
3515
+ this.#inspectSurface(row, surface);
3516
+ this.#inspectMethods(row, methods);
3517
+ this.#inspectDeclarations(row, declarations);
3518
+ this.#inspectLinks(row, links, tests);
3519
+ this.#inspectFences(row, fences);
3520
+ this.#inspectExamples(row, exampleFences, exampleFunctions, exampleMethods, exampleTitles);
3521
+ this.#inspectImports(row, imports);
3522
+ this.#inspectDrift(row, drift);
3523
+ }
3524
+ this.#inspectPitch(pitch);
3525
+ return {
3526
+ input,
3527
+ sections,
3528
+ surface,
3529
+ methods,
3530
+ declarations,
3531
+ links,
3532
+ tests,
3533
+ fences,
3534
+ examples,
3535
+ imports,
3536
+ drift,
3537
+ pitch
3538
+ };
3539
+ }
3540
+ document() {
3541
+ return this.#rewrite((row, drift, files) => this.#rewriteGuide(row, drift, files));
3542
+ }
3543
+ annotate() {
3544
+ return this.#rewrite((row, drift, files) => this.#rewriteSource(row, drift, files));
3545
+ }
3546
+ #rewrite(apply) {
3547
+ const files = new Map(Object.entries(this.#options.files));
3548
+ const reasons = /* @__PURE__ */ new Map();
3549
+ const requested = /* @__PURE__ */ new Set();
3550
+ for (const row of this.#rows) for (const drift of findDrift(row.guide, row.source)) {
3551
+ const identity = identifyDrift(row.entry.spec, drift);
3552
+ requested.add(identity);
3553
+ const reason = apply(row, drift, files);
3554
+ if (reason !== void 0) reasons.set(identity, reason);
3555
+ }
3556
+ const inventory = Object.fromEntries(files);
3557
+ const remaining = [];
3558
+ const result = new Parity({
3559
+ ...this.#options,
3560
+ files: inventory
3561
+ });
3562
+ remaining.push(...result.inspect().input);
3563
+ for (const row of result.rows()) for (const drift of findDrift(row.guide, row.source)) {
3564
+ const identity = identifyDrift(row.entry.spec, drift);
3565
+ if (!requested.has(identity)) continue;
3566
+ remaining.push({
3567
+ spec: row.entry.spec,
3568
+ text: `${formatDrift(drift)}; ${reasons.get(identity) ?? "the requested destination still disagrees"}`
3569
+ });
3570
+ }
3571
+ return {
3572
+ changes: Array.from(files.entries()).filter(([path, content]) => this.#options.files[path] !== content).sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
3573
+ path,
3574
+ content
3575
+ })),
3576
+ findings: remaining
3577
+ };
3578
+ }
3579
+ #createRows(files) {
3580
+ const rows = [];
3581
+ for (const entry of this.#options.entries) {
3582
+ const text = files[entry.spec];
3583
+ if (text === void 0) continue;
3584
+ rows.push({
3585
+ entry,
3586
+ guide: new Guide(text),
3587
+ source: new Source({
3588
+ files,
3589
+ module: entry.source
3590
+ })
3591
+ });
3592
+ }
3593
+ return rows;
3594
+ }
3595
+ #inspectInput(findings) {
3596
+ if (this.#options.entries.length === 0) findings.push({ text: "The manifest has no guide entries." });
3597
+ for (const entry of this.#options.entries) {
3598
+ if (this.#options.files[entry.spec] !== void 0) continue;
3599
+ findings.push({
3600
+ spec: entry.spec,
3601
+ text: `${entry.spec} is absent from the inventory.`
3602
+ });
3603
+ }
3604
+ }
3605
+ #inspectSections(row, findings) {
3606
+ const sections = row.guide.sections();
3607
+ for (const heading of [
3608
+ SURFACE,
3609
+ METHODS,
3610
+ TESTS
3611
+ ]) {
3612
+ if (sections.includes(heading)) continue;
3613
+ findings.push({
3614
+ spec: row.entry.spec,
3615
+ text: `${row.entry.spec} has no ## ${heading} section.`
3616
+ });
3617
+ }
3618
+ if (row.guide.methods().length === 0) findings.push({
3619
+ spec: row.entry.spec,
3620
+ text: `${row.entry.spec} has no documented method groups.`
3621
+ });
3622
+ }
3623
+ #inspectSurface(row, findings) {
3624
+ if (row.guide.surface().length === 0) findings.push({
3625
+ spec: row.entry.spec,
3626
+ text: `${row.entry.spec} has no documented surface.`
3627
+ });
3628
+ for (const unnamed of row.guide.unnamed()) findings.push({
3629
+ spec: row.entry.spec,
3630
+ text: `${row.entry.spec} has an unnamed row: ${unnamed}`
3631
+ });
3632
+ for (const key of findMissingSymbols(row.source.exports(), row.source.surface())) findings.push({
3633
+ spec: row.entry.spec,
3634
+ text: `${row.entry.spec} does not re-export ${key}.`
3635
+ });
3636
+ for (const key of findMissingSymbols(row.source.surface(), row.source.exports())) findings.push({
3637
+ spec: row.entry.spec,
3638
+ text: `${row.entry.spec} barrel exposes no direct ${key}.`
3639
+ });
3640
+ for (const key of findMissingSymbols(row.source.surface(), row.guide.surface())) findings.push({
3641
+ spec: row.entry.spec,
3642
+ text: `${row.entry.spec} does not document ${key}.`
3643
+ });
3644
+ for (const key of findMissingSymbols(row.guide.surface(), row.source.surface())) findings.push({
3645
+ spec: row.entry.spec,
3646
+ text: `${row.entry.spec} documents no barrel ${key}.`
3647
+ });
3648
+ for (const symbol of row.source.hidden()) findings.push({
3649
+ spec: row.entry.spec,
3650
+ text: `${row.entry.spec} source hides ${computeSymbolKey(symbol)}.`
3651
+ });
3652
+ }
3653
+ #inspectMethods(row, findings) {
3654
+ for (const group of row.guide.methods()) {
3655
+ const documented = group.methods.map((entry) => entry.name);
3656
+ const declared = row.source.methods(group.interface).map((entry) => entry.name);
3657
+ if (documented.length === 0) findings.push({
3658
+ spec: row.entry.spec,
3659
+ text: `${row.entry.spec} ${group.interface} has no documented methods.`
3660
+ });
3661
+ for (const name of findMissing(declared, documented)) findings.push({
3662
+ spec: row.entry.spec,
3663
+ text: `${row.entry.spec} does not document ${group.interface}.${name}.`
3664
+ });
3665
+ for (const name of findMissing(documented, declared)) findings.push({
3666
+ spec: row.entry.spec,
3667
+ text: `${row.entry.spec} documents no source ${group.interface}.${name}.`
3668
+ });
3669
+ const entity = group.interface.replace(/Interface$/, "");
3670
+ if (entity === group.interface) continue;
3671
+ for (const name of findMissing(row.source.methods(entity).map((entry) => entry.name), documented)) findings.push({
3672
+ spec: row.entry.spec,
3673
+ text: `${row.entry.spec} ${entity}.${name} is outside the ${group.interface} contract.`
3674
+ });
3675
+ }
3676
+ }
3677
+ #inspectDeclarations(row, findings) {
3678
+ const groups = row.guide.methods();
3679
+ const documented = groups.map((group) => group.interface);
3680
+ const declared = new Set(row.source.surface().map((symbol) => symbol.name));
3681
+ for (const group of groups) {
3682
+ const finding = compareMembership(row.entry.spec, group.interface, group.methods.map((entry) => entry.name), row.source.methods(group.interface).map((entry) => entry.name));
3683
+ if (finding !== void 0) findings.push(finding);
3684
+ }
3685
+ for (const symbol of row.source.surface()) {
3686
+ if (symbol.keyword !== "interface" && symbol.keyword !== "class") continue;
3687
+ const members = row.source.methods(symbol.name).map((entry) => entry.name);
3688
+ if (members.length === 0) continue;
3689
+ const contract = `${symbol.name}Interface`;
3690
+ if (symbol.keyword === "class" && declared.has(contract)) {
3691
+ const finding = compareMembership(row.entry.spec, symbol.name, row.source.methods(contract).map((entry) => entry.name), members);
3692
+ if (finding !== void 0) findings.push(finding);
3693
+ continue;
3694
+ }
3695
+ if (documented.includes(symbol.name)) continue;
3696
+ findings.push({
3697
+ spec: row.entry.spec,
3698
+ text: `${row.entry.spec} ${symbol.name} declares members and carries no method table.`
3699
+ });
3700
+ }
3701
+ }
3702
+ #inspectLinks(row, links, tests) {
3703
+ if (row.guide.links().length === 0) links.push({
3704
+ spec: row.entry.spec,
3705
+ text: `${row.entry.spec} has no links.`
3706
+ });
3707
+ for (const href of row.guide.links()) {
3708
+ if (isExternalLink(href)) continue;
3709
+ const path = resolveLink(row.entry.spec, href);
3710
+ if (row.source.exists(path)) continue;
3711
+ links.push({
3712
+ spec: row.entry.spec,
3713
+ text: `${row.entry.spec} has a broken link: ${href}.`
3714
+ });
3715
+ }
3716
+ if (row.guide.tests().length === 0) tests.push({
3717
+ spec: row.entry.spec,
3718
+ text: `${row.entry.spec} has no test links.`
3719
+ });
3720
+ for (const href of row.guide.tests()) {
3721
+ const path = resolveLink(row.entry.spec, href);
3722
+ if (row.source.exists(path)) continue;
3723
+ tests.push({
3724
+ spec: row.entry.spec,
3725
+ text: `${row.entry.spec} has a missing test: ${href}.`
3726
+ });
3727
+ }
3728
+ }
3729
+ #inspectFences(row, findings) {
3730
+ for (const fence of findUnlisted(row.guide.fences(), this.#options.languages)) findings.push({
3731
+ spec: row.entry.spec,
3732
+ text: `${row.entry.spec} has an unlisted fence language under ${fence.title ?? "no heading"}: ${fence.language ?? "absent"}.`
3733
+ });
3734
+ }
3735
+ #inspectExamples(row, fencesFindings, functionFindings, methodFindings, titleFindings) {
3736
+ const fences = row.guide.fences().filter((fence) => fence.language === this.#options.language).map((fence) => fence.code);
3737
+ if (fences.length === 0) fencesFindings.push({
3738
+ spec: row.entry.spec,
3739
+ text: `${row.entry.spec} has no ${this.#options.language} example fence.`
3740
+ });
3741
+ const functions = row.guide.surface().filter((symbol) => symbol.keyword === "function").map((symbol) => symbol.name);
3742
+ for (const name of findUnexampled(functions, fences, row.source.examples().map((example) => example.name))) functionFindings.push({
3743
+ spec: row.entry.spec,
3744
+ text: `${row.entry.spec} has no example for ${name}.`
3745
+ });
3746
+ for (const group of row.guide.methods()) {
3747
+ const entity = group.interface.replace(/Interface$/, "");
3748
+ const examples = row.source.examples(group.interface).map((example) => example.name);
3749
+ if (entity !== group.interface) examples.push(...row.source.examples(entity).map((example) => example.name));
3750
+ for (const name of findUnexampled(group.methods.map((entry) => entry.name), fences, examples)) methodFindings.push({
3751
+ spec: row.entry.spec,
3752
+ text: `${row.entry.spec} has no example for ${group.interface}.${name}.`
3753
+ });
3754
+ }
3755
+ const guide = row.guide.fences().map((fence) => fence.title).filter(_orkestrel_contract.isNonEmptyString);
3756
+ const source = row.source.examples().map((example) => example.title).filter(_orkestrel_contract.isNonEmptyString);
3757
+ if (!guide.some((title) => source.includes(title))) titleFindings.push({
3758
+ spec: row.entry.spec,
3759
+ text: `${row.entry.spec} has no top-level example-title pair: guide ${JSON.stringify(guide)} source ${JSON.stringify(source)}.`
3760
+ });
3761
+ }
3762
+ #inspectImports(row, findings) {
3763
+ const sources = new SourceManager({
3764
+ files: this.#options.files,
3765
+ modules: this.#options.modules
3766
+ });
3767
+ let compared = false;
3768
+ for (const fence of row.guide.fences()) {
3769
+ if (fence.language !== this.#options.language) continue;
3770
+ for (const imported of extractFenceImports(fence.code)) {
3771
+ const source = sources.source(imported.specifier);
3772
+ if (source === void 0) continue;
3773
+ compared = true;
3774
+ const surface = source.surface().map((symbol) => symbol.name);
3775
+ for (const name of findMissing(imported.names, surface)) findings.push({
3776
+ spec: row.entry.spec,
3777
+ text: `${row.entry.spec} imports missing ${name} from ${imported.specifier}.`
3778
+ });
3779
+ }
3780
+ }
3781
+ if (!compared) findings.push({
3782
+ spec: row.entry.spec,
3783
+ text: `${row.entry.spec} has no mapped self import.`
3784
+ });
3785
+ }
3786
+ #inspectDrift(row, findings) {
3787
+ for (const drift of findDrift(row.guide, row.source)) findings.push({
3788
+ spec: row.entry.spec,
3789
+ text: formatDrift(drift)
3790
+ });
3791
+ }
3792
+ #inspectPitch(findings) {
3793
+ const pitch = this.#options.pitch;
3794
+ if (pitch === void 0) return;
3795
+ const readme = this.#options.files[pitch.readme];
3796
+ const spec = this.#options.files[pitch.spec];
3797
+ if (readme === void 0) {
3798
+ findings.push({
3799
+ spec: pitch.readme,
3800
+ text: `${pitch.readme} is absent from the inventory.`
3801
+ });
3802
+ return;
3803
+ }
3804
+ if (spec === void 0) {
3805
+ findings.push({
3806
+ spec: pitch.spec,
3807
+ text: `${pitch.spec} is absent from the inventory.`
3808
+ });
3809
+ return;
3810
+ }
3811
+ const left = new Guide(readme).tagline();
3812
+ const right = new Guide(spec).tagline();
3813
+ if (left !== void 0 && left === right) return;
3814
+ findings.push({
3815
+ spec: pitch.spec,
3816
+ text: `${pitch.spec} pitch: README ${formatSide(left)} guide ${formatSide(right)}.`
3817
+ });
3818
+ }
3819
+ #rewriteGuide(row, drift, files) {
3820
+ if (drift.source === void 0) return "source authority is absent";
3821
+ const current = files.get(row.entry.spec);
3822
+ if (current === void 0) return "the guide inventory text is absent";
3823
+ if (drift.category === "summary") {
3824
+ const replacement = replaceCell(current, drift.key, drift.source);
3825
+ if (replacement === void 0) return "the guide summary cell or its provenance is unavailable";
3826
+ files.set(row.entry.spec, replacement);
3827
+ return;
3828
+ }
3829
+ const example = collectTitles(row.guide, row.source).get(drift.key);
3830
+ if (example === void 0) return "the paired source example is unavailable";
3831
+ const replacement = replaceFence(current, drift.key, example);
3832
+ if (replacement === void 0) return "the titled guide fence or its provenance is unavailable";
3833
+ files.set(row.entry.spec, replacement);
3834
+ }
3835
+ #rewriteSource(row, drift, files) {
3836
+ if (drift.guide === void 0) return "guide authority is absent";
3837
+ if (drift.category === "summary") {
3838
+ const located = this.#locateSource(row.entry, drift.key, files);
3839
+ if (located === void 0) return "the source doc block or its provenance is unavailable";
3840
+ const replacement = replaceSummary(located.text.slice(located.span.start, located.span.end), drift.guide);
3841
+ if (replacement === void 0) return "the source summary cannot be represented safely";
3842
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3843
+ return;
3844
+ }
3845
+ const fence = row.guide.fences().find((entry) => entry.title === drift.key);
3846
+ const located = this.#locateExample(row, drift.key, files);
3847
+ if (fence === void 0 || located === void 0) return "the paired source example or its provenance is unavailable";
3848
+ const replacement = replaceExample(located.text.slice(located.span.start, located.span.end), {
3849
+ name: located.example.name,
3850
+ title: drift.key,
3851
+ code: fence.code,
3852
+ ...fence.language === void 0 ? {} : { language: fence.language }
3853
+ });
3854
+ if (replacement === void 0) return "the guide example cannot be represented safely";
3855
+ files.set(located.path, spliceSpan(located.text, located.span, replacement));
3856
+ }
3857
+ #locateSource(entry, key, files) {
3858
+ const inventory = Object.fromEntries(files);
3859
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(entry.source))) {
3860
+ const text = files.get(path);
3861
+ if (text === void 0) continue;
3862
+ const span = locateComment(text, key);
3863
+ if (span !== void 0) return {
3864
+ path,
3865
+ text,
3866
+ span
3867
+ };
3868
+ }
3869
+ }
3870
+ #locateExample(row, title, files) {
3871
+ const target = collectTitles(row.guide, row.source).get(title);
3872
+ if (target === void 0) return void 0;
3873
+ const keys = [];
3874
+ for (const symbol of row.source.exports()) if (symbol.name === target.name) keys.push(computeSymbolKey(symbol));
3875
+ for (const owner of row.guide.surface()) {
3876
+ if (owner.keyword !== "class" && owner.keyword !== "interface") continue;
3877
+ if (row.source.examples(owner.name).some((example) => example.name === target.name && example.title === title)) keys.push(`${owner.name}.${target.name}`);
3878
+ }
3879
+ const inventory = Object.fromEntries(files);
3880
+ for (const path of selectModuleKeys(inventory, normalizeDirectories(row.entry.source))) {
3881
+ const text = files.get(path);
3882
+ if (text === void 0) continue;
3883
+ let selected;
3884
+ for (const key of keys) {
3885
+ const span = locateComment(text, key);
3886
+ if (span === void 0) continue;
3887
+ const example = collectExamples(normalizeComment(text.slice(span.start, span.end)), target.name).find((entry) => entry.title === title);
3888
+ if (example === void 0) continue;
3889
+ if (selected === void 0 || span.start < selected.span.start) selected = {
3890
+ span,
3891
+ example
3892
+ };
3893
+ }
3894
+ if (selected !== void 0) return {
3895
+ path,
3896
+ text,
3897
+ ...selected
3898
+ };
3899
+ }
3900
+ }
3901
+ };
3902
+ //#endregion
1891
3903
  //#region src/core/factories.ts
1892
3904
  /**
1893
3905
  * Creates a structured {@link GuideInterface} view over one guide's markdown
@@ -1897,12 +3909,13 @@ var SourceManager = class {
1897
3909
  * @param source - The guide's markdown source text
1898
3910
  * @returns A working {@link GuideInterface}
1899
3911
  *
1900
- * @example
3912
+ * @example Construct a Guide from markdown text
1901
3913
  * ```ts
1902
3914
  * import { createGuide } from '@orkestrel/guide'
1903
3915
  *
1904
3916
  * const guide = createGuide('## Surface\n\n| Name | Kind |\n| --- | --- |\n| `X` | class |')
1905
3917
  * guide.surface() // [{ name: 'X', keyword: 'class' }]
3918
+ * guide.sections() // ['Surface']
1906
3919
  * ```
1907
3920
  */
1908
3921
  function createGuide(source) {
@@ -1915,15 +3928,23 @@ function createGuide(source) {
1915
3928
  * @param options - The file inventory and module scope to reflect
1916
3929
  * @returns A `SourceInterface` reflecting the given module scope
1917
3930
  *
1918
- * @example
3931
+ * @example Construct a Source from an inline files record
1919
3932
  * ```ts
1920
3933
  * import { createSource } from '@orkestrel/guide'
1921
3934
  *
1922
3935
  * const source = createSource({
1923
- * files: { 'src/core/Guide.ts': 'export class Guide {}\n' },
3936
+ * files: {
3937
+ * 'src/core/index.ts': "export * from './Guide.js'\nexport * from './types.js'\n",
3938
+ * 'src/core/Guide.ts': 'export class Guide {}\n',
3939
+ * 'src/core/types.ts': 'export interface GuideInterface {\n\tsections(): void\n}\n',
3940
+ * },
1924
3941
  * module: 'src/core',
1925
3942
  * })
1926
- * source.exports() // [{ name: 'Guide', keyword: 'class' }]
3943
+ * source.exports() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
3944
+ * source.surface() // [{ name: 'Guide', keyword: 'class' }, { name: 'GuideInterface', keyword: 'interface' }]
3945
+ * source.methods('GuideInterface') // [{ name: 'sections' }]
3946
+ * source.exists('src/core/Guide.ts') // true
3947
+ * source.exists('src/core') // true — a directory any inventory key sits beneath
1927
3948
  * ```
1928
3949
  */
1929
3950
  function createSource(options) {
@@ -1936,15 +3957,22 @@ function createSource(options) {
1936
3957
  * @param options - The shared file inventory and specifier-to-module policy
1937
3958
  * @returns A source manager over the supplied policy
1938
3959
  *
1939
- * @example
3960
+ * @example Resolve a fence's import specifier to the right Source
1940
3961
  * ```ts
1941
3962
  * import { createSourceManager } from '@orkestrel/guide'
1942
3963
  *
1943
3964
  * const sources = createSourceManager({
1944
- * files: { 'src/core/index.ts': "export * from './types.js'" },
1945
- * modules: { '@scope/package': 'src/core' },
3965
+ * files: {
3966
+ * 'src/core/index.ts': "export * from './Guide.js'\n",
3967
+ * 'src/core/Guide.ts': 'export class Guide {}\n',
3968
+ * },
3969
+ * modules: { '@scope/package': 'src/core', '@scope/package/core': 'src/core' },
1946
3970
  * })
1947
- * sources.source('@scope/package')?.surface()
3971
+ *
3972
+ * sources.source('@scope/package')?.surface() // [{ name: 'Guide', keyword: 'class' }]
3973
+ * sources.source('node:fs') // undefined — a foreign import, which a fence check skips
3974
+ * sources.source('@scope/package') === sources.source('@scope/package/core') // true
3975
+ * sources.sources() // [the one shared view both specifiers name]
1948
3976
  * ```
1949
3977
  */
1950
3978
  function createSourceManager(options) {
@@ -1969,6 +3997,60 @@ function createSurfaceSymbolContract() {
1969
3997
  return (0, _orkestrel_contract.createContract)(surfaceSymbolShape);
1970
3998
  }
1971
3999
  /**
4000
+ * Compiles the {@link methodEntryShape} into a {@link ContractInterface} for
4001
+ * {@link MethodEntry} — a guard, coercing parser, JSON Schema, and seeded
4002
+ * generator from one shape declaration (AGENTS.md § Design laws).
4003
+ *
4004
+ * @returns A `MethodEntry` contract bundling `schema` / `is` / `parse` / `generate`
4005
+ *
4006
+ * @example
4007
+ * ```ts
4008
+ * import { createMethodEntryContract } from '@orkestrel/guide'
4009
+ *
4010
+ * const methodEntry = createMethodEntryContract()
4011
+ * methodEntry.is({ name: 'walk' }) // true
4012
+ * ```
4013
+ */
4014
+ function createMethodEntryContract() {
4015
+ return (0, _orkestrel_contract.createContract)(methodEntryShape);
4016
+ }
4017
+ /**
4018
+ * Compiles the {@link sourceExampleShape} into a {@link ContractInterface} for
4019
+ * {@link SourceExample} — a guard, coercing parser, JSON Schema, and seeded
4020
+ * generator from one shape declaration (AGENTS.md § Design laws).
4021
+ *
4022
+ * @returns A `SourceExample` contract bundling `schema` / `is` / `parse` / `generate`
4023
+ *
4024
+ * @example
4025
+ * ```ts
4026
+ * import { createSourceExampleContract } from '@orkestrel/guide'
4027
+ *
4028
+ * const sourceExample = createSourceExampleContract()
4029
+ * sourceExample.is({ name: 'walk', code: 'walk()' }) // true
4030
+ * ```
4031
+ */
4032
+ function createSourceExampleContract() {
4033
+ return (0, _orkestrel_contract.createContract)(sourceExampleShape);
4034
+ }
4035
+ /**
4036
+ * Compiles the {@link driftShape} into a {@link ContractInterface} for
4037
+ * {@link Drift} — a guard, coercing parser, JSON Schema, and seeded
4038
+ * generator from one shape declaration (AGENTS.md § Design laws).
4039
+ *
4040
+ * @returns A `Drift` contract bundling `schema` / `is` / `parse` / `generate`
4041
+ *
4042
+ * @example
4043
+ * ```ts
4044
+ * import { createDriftContract } from '@orkestrel/guide'
4045
+ *
4046
+ * const drift = createDriftContract()
4047
+ * drift.is({ key: 'class Widget', category: 'summary', guide: 'A widget.' }) // true
4048
+ * ```
4049
+ */
4050
+ function createDriftContract() {
4051
+ return (0, _orkestrel_contract.createContract)(driftShape);
4052
+ }
4053
+ /**
1972
4054
  * Compiles the {@link methodGroupShape} into a {@link ContractInterface} for
1973
4055
  * {@link MethodGroup} — a guard, coercing parser, JSON Schema, and seeded
1974
4056
  * generator from one shape declaration (AGENTS.md § Design laws).
@@ -1980,7 +4062,7 @@ function createSurfaceSymbolContract() {
1980
4062
  * import { createMethodGroupContract } from '@orkestrel/guide'
1981
4063
  *
1982
4064
  * const methodGroup = createMethodGroupContract()
1983
- * methodGroup.is({ interface: 'MarkdownInterface', methods: ['walk'] }) // true
4065
+ * methodGroup.is({ interface: 'MarkdownInterface', methods: [{ name: 'walk' }] }) // true
1984
4066
  * ```
1985
4067
  */
1986
4068
  function createMethodGroupContract() {
@@ -2005,25 +4087,49 @@ function createManifestEntryContract() {
2005
4087
  return (0, _orkestrel_contract.createContract)(manifestEntryShape);
2006
4088
  }
2007
4089
  //#endregion
4090
+ exports.DRIFT_CATEGORIES = DRIFT_CATEGORIES;
2008
4091
  exports.EXPORT_KEYWORDS = EXPORT_KEYWORDS;
2009
4092
  exports.EXTERNAL_SCHEMES = EXTERNAL_SCHEMES;
2010
4093
  exports.Guide = Guide;
4094
+ exports.KIND = KIND;
2011
4095
  exports.MANIFEST = MANIFEST;
2012
4096
  exports.METHODS = METHODS;
4097
+ exports.Parity = Parity;
4098
+ exports.SUMMARY = SUMMARY;
2013
4099
  exports.SURFACE = SURFACE;
2014
4100
  exports.Source = Source;
2015
4101
  exports.SourceManager = SourceManager;
2016
4102
  exports.TESTS = TESTS;
4103
+ exports.WRAP_WIDTH = WRAP_WIDTH;
4104
+ exports.buildCell = buildCell;
4105
+ exports.buildComment = buildComment;
4106
+ exports.buildFence = buildFence;
4107
+ exports.buildTable = buildTable;
4108
+ exports.collectDeclarations = collectDeclarations;
4109
+ exports.collectExamples = collectExamples;
4110
+ exports.collectFences = collectFences;
4111
+ exports.collectGroups = collectGroups;
4112
+ exports.collectKeys = collectKeys;
4113
+ exports.collectSummaries = collectSummaries;
4114
+ exports.collectTitles = collectTitles;
4115
+ exports.compareMembership = compareMembership;
4116
+ exports.computeDrift = computeDrift;
2017
4117
  exports.computeModuleKey = computeModuleKey;
2018
4118
  exports.computeSymbolKey = computeSymbolKey;
4119
+ exports.createDriftContract = createDriftContract;
2019
4120
  exports.createGuide = createGuide;
2020
4121
  exports.createManifestEntryContract = createManifestEntryContract;
4122
+ exports.createMethodEntryContract = createMethodEntryContract;
2021
4123
  exports.createMethodGroupContract = createMethodGroupContract;
2022
4124
  exports.createSource = createSource;
4125
+ exports.createSourceExampleContract = createSourceExampleContract;
2023
4126
  exports.createSourceManager = createSourceManager;
2024
4127
  exports.createSurfaceSymbolContract = createSurfaceSymbolContract;
4128
+ exports.driftShape = driftShape;
2025
4129
  exports.escapeRegExp = escapeRegExp;
4130
+ exports.extractBodyLines = extractBodyLines;
2026
4131
  exports.extractCellLinks = extractCellLinks;
4132
+ exports.extractCellText = extractCellText;
2027
4133
  exports.extractDeclaration = extractDeclaration;
2028
4134
  exports.extractExampleLines = extractExampleLines;
2029
4135
  exports.extractExampleMethods = extractExampleMethods;
@@ -2035,31 +4141,61 @@ exports.extractHidden = extractHidden;
2035
4141
  exports.extractLinks = extractLinks;
2036
4142
  exports.extractMemberMethods = extractMemberMethods;
2037
4143
  exports.extractMethods = extractMethods;
4144
+ exports.extractRowEntry = extractRowEntry;
4145
+ exports.extractRowSummary = extractRowSummary;
4146
+ exports.extractRowSymbol = extractRowSymbol;
4147
+ exports.extractSourceComments = extractSourceComments;
2038
4148
  exports.extractSourceLines = extractSourceLines;
2039
4149
  exports.extractSurface = extractSurface;
4150
+ exports.extractTagline = extractTagline;
2040
4151
  exports.extractTests = extractTests;
4152
+ exports.extractUnnamed = extractUnnamed;
4153
+ exports.findColumnIndex = findColumnIndex;
4154
+ exports.findDrift = findDrift;
2041
4155
  exports.findFirstCode = findFirstCode;
2042
- exports.findKindIndex = findKindIndex;
2043
4156
  exports.findMissing = findMissing;
2044
4157
  exports.findMissingSymbols = findMissingSymbols;
2045
4158
  exports.findUnexampled = findUnexampled;
2046
4159
  exports.findUnlisted = findUnlisted;
4160
+ exports.formatDrift = formatDrift;
4161
+ exports.formatSide = formatSide;
2047
4162
  exports.hasCanonicalSegments = hasCanonicalSegments;
4163
+ exports.identifyDrift = identifyDrift;
4164
+ exports.isDrift = isDrift;
4165
+ exports.isDriftCategory = isDriftCategory;
2048
4166
  exports.isExportKeyword = isExportKeyword;
2049
4167
  exports.isExternalLink = isExternalLink;
2050
4168
  exports.isManifestEntry = isManifestEntry;
4169
+ exports.isMethodEntry = isMethodEntry;
2051
4170
  exports.isMethodGroup = isMethodGroup;
4171
+ exports.isSourceExample = isSourceExample;
2052
4172
  exports.isSurfaceSymbol = isSurfaceSymbol;
2053
4173
  exports.joinHead = joinHead;
4174
+ exports.locateComment = locateComment;
2054
4175
  exports.manifestEntryShape = manifestEntryShape;
4176
+ exports.maskFences = maskFences;
4177
+ exports.methodEntryShape = methodEntryShape;
2055
4178
  exports.methodGroupShape = methodGroupShape;
4179
+ exports.normalizeComment = normalizeComment;
2056
4180
  exports.normalizeDirectories = normalizeDirectories;
2057
4181
  exports.normalizeIdentifier = normalizeIdentifier;
4182
+ exports.normalizeSummary = normalizeSummary;
2058
4183
  exports.parseManifest = parseManifest;
4184
+ exports.renderExample = renderExample;
4185
+ exports.renderMethods = renderMethods;
4186
+ exports.renderSurface = renderSurface;
4187
+ exports.replaceCell = replaceCell;
4188
+ exports.replaceExample = replaceExample;
4189
+ exports.replaceFence = replaceFence;
4190
+ exports.replaceSummary = replaceSummary;
2059
4191
  exports.resolveLink = resolveLink;
2060
4192
  exports.resolvePath = resolvePath;
2061
4193
  exports.selectModuleKeys = selectModuleKeys;
2062
4194
  exports.selectSectionBlocks = selectSectionBlocks;
4195
+ exports.sourceExampleShape = sourceExampleShape;
4196
+ exports.spliceSpan = spliceSpan;
2063
4197
  exports.surfaceSymbolShape = surfaceSymbolShape;
4198
+ exports.unwrapComment = unwrapComment;
4199
+ exports.wrapText = wrapText;
2064
4200
 
2065
4201
  //# sourceMappingURL=index.cjs.map