@open-livex-wiki/core 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/coverage/handles.d.ts +5 -0
  2. package/dist/coverage/handles.d.ts.map +1 -0
  3. package/dist/coverage/handles.js +116 -0
  4. package/dist/coverage/handles.js.map +1 -0
  5. package/dist/coverage/targets.d.ts +22 -0
  6. package/dist/coverage/targets.d.ts.map +1 -0
  7. package/dist/coverage/targets.js +117 -0
  8. package/dist/coverage/targets.js.map +1 -0
  9. package/dist/coverage/visuals.d.ts +19 -0
  10. package/dist/coverage/visuals.d.ts.map +1 -0
  11. package/dist/coverage/visuals.js +103 -0
  12. package/dist/coverage/visuals.js.map +1 -0
  13. package/dist/coverage.d.ts.map +1 -1
  14. package/dist/coverage.js +36 -233
  15. package/dist/coverage.js.map +1 -1
  16. package/dist/discover/designators.d.ts +26 -0
  17. package/dist/discover/designators.d.ts.map +1 -0
  18. package/dist/discover/designators.js +361 -0
  19. package/dist/discover/designators.js.map +1 -0
  20. package/dist/discover/document-types.d.ts +90 -0
  21. package/dist/discover/document-types.d.ts.map +1 -0
  22. package/dist/discover/document-types.js +2 -0
  23. package/dist/discover/document-types.js.map +1 -0
  24. package/dist/discover/index-builder.d.ts +28 -0
  25. package/dist/discover/index-builder.d.ts.map +1 -0
  26. package/dist/discover/index-builder.js +286 -0
  27. package/dist/discover/index-builder.js.map +1 -0
  28. package/dist/discover/postings.d.ts +9 -0
  29. package/dist/discover/postings.d.ts.map +1 -0
  30. package/dist/discover/postings.js +183 -0
  31. package/dist/discover/postings.js.map +1 -0
  32. package/dist/discover/query-expansion.d.ts +4 -0
  33. package/dist/discover/query-expansion.d.ts.map +1 -0
  34. package/dist/discover/query-expansion.js +109 -0
  35. package/dist/discover/query-expansion.js.map +1 -0
  36. package/dist/discover/scene-document.d.ts +40 -0
  37. package/dist/discover/scene-document.d.ts.map +1 -0
  38. package/dist/discover/scene-document.js +417 -0
  39. package/dist/discover/scene-document.js.map +1 -0
  40. package/dist/discover/scene-ranking.d.ts +14 -0
  41. package/dist/discover/scene-ranking.d.ts.map +1 -0
  42. package/dist/discover/scene-ranking.js +217 -0
  43. package/dist/discover/scene-ranking.js.map +1 -0
  44. package/dist/discover/scoring.d.ts +34 -0
  45. package/dist/discover/scoring.d.ts.map +1 -0
  46. package/dist/discover/scoring.js +425 -0
  47. package/dist/discover/scoring.js.map +1 -0
  48. package/dist/discover/subscene.d.ts +11 -0
  49. package/dist/discover/subscene.d.ts.map +1 -0
  50. package/dist/discover/subscene.js +121 -0
  51. package/dist/discover/subscene.js.map +1 -0
  52. package/dist/discover/term-scoring.d.ts +25 -0
  53. package/dist/discover/term-scoring.d.ts.map +1 -0
  54. package/dist/discover/term-scoring.js +374 -0
  55. package/dist/discover/term-scoring.js.map +1 -0
  56. package/dist/discover/tokenizer.d.ts +35 -0
  57. package/dist/discover/tokenizer.d.ts.map +1 -0
  58. package/dist/discover/tokenizer.js +282 -0
  59. package/dist/discover/tokenizer.js.map +1 -0
  60. package/dist/discover.d.ts +5 -61
  61. package/dist/discover.d.ts.map +1 -1
  62. package/dist/discover.js +54 -2733
  63. package/dist/discover.js.map +1 -1
  64. package/dist/loader/config.d.ts +29 -0
  65. package/dist/loader/config.d.ts.map +1 -0
  66. package/dist/loader/config.js +80 -0
  67. package/dist/loader/config.js.map +1 -0
  68. package/dist/loader/domain.d.ts +19 -0
  69. package/dist/loader/domain.d.ts.map +1 -0
  70. package/dist/loader/domain.js +152 -0
  71. package/dist/loader/domain.js.map +1 -0
  72. package/dist/loader/paths.d.ts +4 -0
  73. package/dist/loader/paths.d.ts.map +1 -0
  74. package/dist/loader/paths.js +29 -0
  75. package/dist/loader/paths.js.map +1 -0
  76. package/dist/loader/scene.d.ts +16 -0
  77. package/dist/loader/scene.d.ts.map +1 -0
  78. package/dist/loader/scene.js +266 -0
  79. package/dist/loader/scene.js.map +1 -0
  80. package/dist/loader.d.ts +2 -2
  81. package/dist/loader.d.ts.map +1 -1
  82. package/dist/loader.js +11 -506
  83. package/dist/loader.js.map +1 -1
  84. package/dist/schemas.d.ts +14 -11
  85. package/dist/schemas.d.ts.map +1 -1
  86. package/dist/schemas.js +2 -1
  87. package/dist/schemas.js.map +1 -1
  88. package/dist/types.d.ts +2 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/utils/markdown-scanner.d.ts +20 -0
  91. package/dist/utils/markdown-scanner.d.ts.map +1 -0
  92. package/dist/utils/markdown-scanner.js +303 -0
  93. package/dist/utils/markdown-scanner.js.map +1 -0
  94. package/dist/utils/markdown.d.ts +48 -0
  95. package/dist/utils/markdown.d.ts.map +1 -0
  96. package/dist/utils/markdown.js +370 -0
  97. package/dist/utils/markdown.js.map +1 -0
  98. package/dist/utils/paths.d.ts +38 -0
  99. package/dist/utils/paths.d.ts.map +1 -0
  100. package/dist/utils/paths.js +257 -0
  101. package/dist/utils/paths.js.map +1 -0
  102. package/dist/utils/regexp.d.ts +2 -0
  103. package/dist/utils/regexp.d.ts.map +1 -0
  104. package/dist/utils/regexp.js +4 -0
  105. package/dist/utils/regexp.js.map +1 -0
  106. package/dist/utils/symbols.d.ts +9 -0
  107. package/dist/utils/symbols.d.ts.map +1 -0
  108. package/dist/utils/symbols.js +324 -0
  109. package/dist/utils/symbols.js.map +1 -0
  110. package/dist/utils.d.ts +4 -96
  111. package/dist/utils.d.ts.map +1 -1
  112. package/dist/utils.js +3 -1250
  113. package/dist/utils.js.map +1 -1
  114. package/dist/validator/anchor-checker.d.ts +26 -0
  115. package/dist/validator/anchor-checker.d.ts.map +1 -0
  116. package/dist/validator/anchor-checker.js +299 -0
  117. package/dist/validator/anchor-checker.js.map +1 -0
  118. package/dist/validator/git-remotes.d.ts +12 -0
  119. package/dist/validator/git-remotes.d.ts.map +1 -0
  120. package/dist/validator/git-remotes.js +223 -0
  121. package/dist/validator/git-remotes.js.map +1 -0
  122. package/dist/validator/source-resolver.d.ts +29 -0
  123. package/dist/validator/source-resolver.d.ts.map +1 -0
  124. package/dist/validator/source-resolver.js +315 -0
  125. package/dist/validator/source-resolver.js.map +1 -0
  126. package/dist/validator.d.ts +3 -45
  127. package/dist/validator.d.ts.map +1 -1
  128. package/dist/validator.js +6 -823
  129. package/dist/validator.js.map +1 -1
  130. package/package.json +1 -1
package/dist/utils.js CHANGED
@@ -1,1251 +1,4 @@
1
- export const KEBAB_CASE_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2
- export const SCENE_REF_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
- export const COMMIT_SHA_REGEX = /^[0-9a-f]{7,40}$/i;
4
- export const SHA256_HEX_REGEX = /^[0-9a-f]{64}$/i;
5
- /**
6
- * Normalizes filesystem path separators (`\`) to POSIX forward slashes (`/`).
7
- */
8
- export function toPosixPath(p) {
9
- return p.replace(/\\/g, "/");
10
- }
11
- function hasAsciiControlChars(value) {
12
- for (let i = 0; i < value.length; i++) {
13
- const code = value.charCodeAt(i);
14
- if (code <= 0x1f || code === 0x7f) {
15
- return true;
16
- }
17
- }
18
- return false;
19
- }
20
- /**
21
- * Returns `true` iff `rawPath` is a non-empty relative path strictly contained inside a root
22
- * directory (rejects POSIX/Windows absolute paths, UNC paths, NUL/control chars, `.` root alias,
23
- * and `..` traversal segments). Browser-safe (zero `node:*` imports).
24
- */
25
- export function isSafeContainedRelativePath(rawPath) {
26
- if (typeof rawPath !== "string") {
27
- return false;
28
- }
29
- const trimmed = rawPath.trim();
30
- if (trimmed.length === 0 || hasAsciiControlChars(trimmed)) {
31
- return false;
32
- }
33
- const posix = toPosixPath(trimmed);
34
- if (posix.startsWith("/") || /^[a-zA-Z]:/.test(posix)) {
35
- return false;
36
- }
37
- const rawSegments = posix.split("/");
38
- let meaningfulCount = 0;
39
- for (const seg of rawSegments) {
40
- if (seg === "..") {
41
- return false;
42
- }
43
- if (seg.length > 0 && seg !== ".") {
44
- meaningfulCount += 1;
45
- }
46
- }
47
- return meaningfulCount > 0;
48
- }
49
- function stripInlineDecorations(text) {
50
- return text
51
- .trim()
52
- .replace(/^(?:\*\*|__|\*|_)+|(?:\*\*|__|\*|_)+$/g, "")
53
- .trim();
54
- }
55
- function updateFenceState(rawLine, state) {
56
- const firstNonSpaceIdx = rawLine.search(/[^ ]/);
57
- if (firstNonSpaceIdx === -1 || firstNonSpaceIdx > 3) {
58
- return false;
59
- }
60
- const ch0 = rawLine[firstNonSpaceIdx];
61
- if (ch0 !== "`" && ch0 !== "~") {
62
- return false;
63
- }
64
- if (!state.inFence) {
65
- // CommonMark fenced code blocks allow 0..3 leading spaces (4+ spaces is an indented code block)
66
- const openMatch = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(rawLine);
67
- if (openMatch?.[1]) {
68
- const marker = openMatch[1];
69
- const info = openMatch[2] ?? "";
70
- const ch = marker[0] ?? "`";
71
- if (ch === "`" && info.includes("`")) {
72
- return false;
73
- }
74
- state.inFence = true;
75
- state.fenceChar = ch;
76
- state.fenceLen = marker.length;
77
- return true;
78
- }
79
- return false;
80
- }
81
- const closeMatch = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(rawLine);
82
- if (closeMatch?.[1] &&
83
- closeMatch[1][0] === state.fenceChar &&
84
- closeMatch[1].length >= state.fenceLen) {
85
- state.inFence = false;
86
- state.fenceChar = "";
87
- state.fenceLen = 0;
88
- return true;
89
- }
90
- return false;
91
- }
92
- function hasFourColumnIndent(rawLine) {
93
- let cols = 0;
94
- for (let i = 0; i < rawLine.length; i++) {
95
- const ch = rawLine[i];
96
- if (ch === " ") {
97
- cols += 1;
98
- }
99
- else if (ch === "\t") {
100
- cols += 4 - (cols % 4);
101
- }
102
- else {
103
- break;
104
- }
105
- if (cols >= 4) {
106
- return true;
107
- }
108
- }
109
- return false;
110
- }
111
- /**
112
- * Strips `<!-- ... -->` HTML comments on a single line while respecting inline backtick code spans
113
- * when not already inside a multi-line HTML comment. Mutates `commentState.inHtmlComment`.
114
- */
115
- function stripHtmlCommentsFromLine(line, commentState) {
116
- if (!commentState.inHtmlComment && !line.includes("<!--")) {
117
- return line;
118
- }
119
- let out = "";
120
- let i = 0;
121
- let inBackticks = 0;
122
- while (i < line.length) {
123
- if (commentState.inHtmlComment) {
124
- const closeIdx = line.indexOf("-->", i);
125
- if (closeIdx === -1) {
126
- return out;
127
- }
128
- i = closeIdx + 3;
129
- commentState.inHtmlComment = false;
130
- continue;
131
- }
132
- if (line[i] === "`") {
133
- let tickLen = 1;
134
- while (i + tickLen < line.length && line[i + tickLen] === "`") {
135
- tickLen += 1;
136
- }
137
- if (inBackticks === 0) {
138
- // Only enter inline code span if a matching closing backtick run exists on the same line
139
- let searchPos = i + tickLen;
140
- let hasClosing = false;
141
- while (searchPos < line.length) {
142
- const nextTick = line.indexOf("`", searchPos);
143
- if (nextTick === -1) {
144
- break;
145
- }
146
- let closeLen = 1;
147
- while (nextTick + closeLen < line.length && line[nextTick + closeLen] === "`") {
148
- closeLen += 1;
149
- }
150
- if (closeLen === tickLen) {
151
- hasClosing = true;
152
- break;
153
- }
154
- searchPos = nextTick + closeLen;
155
- }
156
- if (hasClosing) {
157
- inBackticks = tickLen;
158
- }
159
- }
160
- else if (inBackticks === tickLen) {
161
- inBackticks = 0;
162
- }
163
- out += line.slice(i, i + tickLen);
164
- i += tickLen;
165
- continue;
166
- }
167
- if (inBackticks === 0 && line.startsWith("<!--", i)) {
168
- const closeIdx = line.indexOf("-->", i + 4);
169
- if (closeIdx === -1) {
170
- commentState.inHtmlComment = true;
171
- return out;
172
- }
173
- i = closeIdx + 3;
174
- continue;
175
- }
176
- out += line[i];
177
- i += 1;
178
- }
179
- return out;
180
- }
181
- const HTML_BLOCK_TYPE1_OPEN_REGEX = /^ {0,3}<(?:pre|script|style|textarea)(?:[\s>]|$)/i;
182
- const HTML_BLOCK_TYPE1_CLOSE_REGEX = /<\/(?:pre|script|style|textarea)>/i;
183
- const HTML_BLOCK_TYPE2_OPEN_REGEX = /^ {0,3}<!--/;
184
- const HTML_BLOCK_TYPE3_OPEN_REGEX = /^ {0,3}<\?/;
185
- const HTML_BLOCK_TYPE4_OPEN_REGEX = /^ {0,3}<![A-Za-z]/;
186
- const HTML_BLOCK_TYPE5_OPEN_REGEX = /^ {0,3}<!\[CDATA\[/;
187
- const HTML_BLOCK_TYPE6_OPEN_REGEX = /^ {0,3}<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:[\s/>]|$)/i;
188
- const HTML_BLOCK_TYPE7_OPEN_REGEX = /^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*\/?>|<\/[A-Za-z][A-Za-z0-9-]*\s*>)[ \t]*$/;
189
- function detectHtmlBlockStart(rawLine, canInterrupt) {
190
- if (!rawLine.includes("<")) {
191
- return null;
192
- }
193
- if (HTML_BLOCK_TYPE1_OPEN_REGEX.test(rawLine)) {
194
- return "type1";
195
- }
196
- if (HTML_BLOCK_TYPE2_OPEN_REGEX.test(rawLine)) {
197
- return "type2";
198
- }
199
- if (HTML_BLOCK_TYPE3_OPEN_REGEX.test(rawLine)) {
200
- return "type3";
201
- }
202
- if (HTML_BLOCK_TYPE5_OPEN_REGEX.test(rawLine)) {
203
- return "type5";
204
- }
205
- if (HTML_BLOCK_TYPE4_OPEN_REGEX.test(rawLine)) {
206
- return "type4";
207
- }
208
- if (HTML_BLOCK_TYPE6_OPEN_REGEX.test(rawLine)) {
209
- return "blank";
210
- }
211
- if (canInterrupt && HTML_BLOCK_TYPE7_OPEN_REGEX.test(rawLine)) {
212
- return "blank";
213
- }
214
- return null;
215
- }
216
- function isHtmlBlockClosedOnLine(rawLine, condition) {
217
- switch (condition) {
218
- case "type1":
219
- return HTML_BLOCK_TYPE1_CLOSE_REGEX.test(rawLine);
220
- case "type2":
221
- return rawLine.includes("-->");
222
- case "type3":
223
- return rawLine.includes("?>");
224
- case "type4":
225
- return rawLine.includes(">");
226
- case "type5":
227
- return rawLine.includes("]]>");
228
- case "blank":
229
- return false;
230
- }
231
- }
232
- /**
233
- * Scans Markdown line-by-line following CommonMark block precedence so fenced code blocks,
234
- * CommonMark HTML blocks (Types 1-7: `<pre|script|style|textarea>`, `<!--`, `<?`, `<!`, `<![CDATA[`,
235
- * `<div>`/`<details>`/`<table>`/etc.), inline HTML comments, and indented code blocks (4+ spaces / `\t`)
236
- * can never spoof ATX headings or section bodies.
237
- */
238
- function scanMarkdownDocument(markdown) {
239
- const lines = markdown.split(/\r?\n/);
240
- const result = [];
241
- const fenceState = { inFence: false, fenceChar: "", fenceLen: 0 };
242
- const inlineCommentState = { inHtmlComment: false };
243
- let htmlBlockEnd = null;
244
- let inIndentedCode = false;
245
- let canStartIndentedCode = true;
246
- for (let idx = 0; idx < lines.length; idx++) {
247
- const rawLine = lines[idx] ?? "";
248
- const lineNumber = idx + 1;
249
- const isBlankRaw = rawLine.trim().length === 0;
250
- // 1. Active CommonMark HTML block (Types 1-7)
251
- if (htmlBlockEnd !== null) {
252
- if (htmlBlockEnd === "blank") {
253
- if (isBlankRaw) {
254
- htmlBlockEnd = null;
255
- canStartIndentedCode = true;
256
- result.push({ lineNumber, rawLine, proseLine: "", heading: null });
257
- }
258
- else {
259
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
260
- }
261
- }
262
- else {
263
- if (isHtmlBlockClosedOnLine(rawLine, htmlBlockEnd)) {
264
- htmlBlockEnd = null;
265
- canStartIndentedCode = true;
266
- }
267
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
268
- }
269
- continue;
270
- }
271
- // 2. Active multi-line inline HTML comment started mid-line on an earlier prose line
272
- if (inlineCommentState.inHtmlComment) {
273
- const remainder = stripHtmlCommentsFromLine(rawLine, inlineCommentState);
274
- const remTrimmed = remainder.trim();
275
- if (remTrimmed.length === 0) {
276
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
277
- continue;
278
- }
279
- result.push({ lineNumber, rawLine, proseLine: remainder, heading: null });
280
- canStartIndentedCode = false;
281
- continue;
282
- }
283
- // 3. Fenced code block open/close/body
284
- if (!inIndentedCode && updateFenceState(rawLine, fenceState)) {
285
- canStartIndentedCode = true;
286
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
287
- continue;
288
- }
289
- if (fenceState.inFence) {
290
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
291
- continue;
292
- }
293
- // 4. Indented code block (4+ columns after blank line / start / heading / fence / HTML block)
294
- if (inIndentedCode) {
295
- if (isBlankRaw || hasFourColumnIndent(rawLine)) {
296
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
297
- continue;
298
- }
299
- inIndentedCode = false;
300
- }
301
- else if (!isBlankRaw && canStartIndentedCode && hasFourColumnIndent(rawLine)) {
302
- inIndentedCode = true;
303
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
304
- continue;
305
- }
306
- if (isBlankRaw) {
307
- canStartIndentedCode = true;
308
- result.push({ lineNumber, rawLine, proseLine: "", heading: null });
309
- continue;
310
- }
311
- // 5. CommonMark HTML block start (Types 1-7)
312
- const startedHtmlBlock = detectHtmlBlockStart(rawLine, canStartIndentedCode);
313
- if (startedHtmlBlock !== null) {
314
- if (startedHtmlBlock === "blank" || !isHtmlBlockClosedOnLine(rawLine, startedHtmlBlock)) {
315
- htmlBlockEnd = startedHtmlBlock;
316
- }
317
- else {
318
- canStartIndentedCode = true;
319
- }
320
- result.push({ lineNumber, rawLine, proseLine: null, heading: null });
321
- continue;
322
- }
323
- // 6. Strip any inline `<!-- ... -->` comments on prose/heading lines
324
- const commentStripped = stripHtmlCommentsFromLine(rawLine, inlineCommentState);
325
- // 7. CommonMark ATX heading: strictly 0..3 leading spaces before `#` (never 4+ spaces or `\t`)
326
- if (commentStripped.includes("#") && !hasFourColumnIndent(rawLine)) {
327
- const headingMatch = /^ {0,3}(#{1,6})(?:[ \t]+(.+?))?[ \t]*#*[ \t]*$/.exec(commentStripped);
328
- if (headingMatch?.[2]) {
329
- const level = (headingMatch[1] ?? "#").length;
330
- const text = stripInlineDecorations(headingMatch[2]);
331
- if (text.length > 0) {
332
- canStartIndentedCode = true;
333
- const heading = { level, text, line: lineNumber };
334
- result.push({ lineNumber, rawLine, proseLine: commentStripped, heading });
335
- continue;
336
- }
337
- }
338
- }
339
- // Horizontal rules also allow indented code blocks immediately following
340
- const trimmedProse = commentStripped.trim();
341
- canStartIndentedCode = /^(?:-\s*){3,}$|^(?:\*\s*){3,}$|^(?:_\s*){3,}$/.test(trimmedProse);
342
- result.push({
343
- lineNumber,
344
- rawLine,
345
- proseLine: trimmedProse.length > 0 ? commentStripped : null,
346
- heading: null,
347
- });
348
- }
349
- return result;
350
- }
351
- /**
352
- * Extracts ATX Markdown headings (`#` .. `######`), ignoring fenced code blocks,
353
- * HTML comments (`<!-- ... -->`), and indented code blocks (4+ spaces / `\t`).
354
- */
355
- export function extractMarkdownHeadings(markdown) {
356
- const scanned = scanMarkdownDocument(markdown);
357
- const headings = [];
358
- for (const entry of scanned) {
359
- if (entry.heading) {
360
- headings.push(entry.heading);
361
- }
362
- }
363
- return headings;
364
- }
365
- function slugifyChainId(input, fallbackIndex) {
366
- const cleaned = input.replace(/^[`"']+|[`"']+$/g, "").trim();
367
- const apiMatch = /([a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_/-]+)+|\/[a-zA-Z0-9_/-]+)/.exec(cleaned);
368
- if (apiMatch?.[1]) {
369
- return apiMatch[1];
370
- }
371
- const normalized = cleaned
372
- .toLowerCase()
373
- .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, "-")
374
- .replace(/^-+|-+$/g, "");
375
- return normalized || `chain-${fallbackIndex + 1}`;
376
- }
377
- function extractEntryPointFromTitle(title) {
378
- const colonSplit = /[::]\s*(.+)$/.exec(title);
379
- if (colonSplit?.[1]) {
380
- const cleaned = colonSplit[1].replace(/^[`"']+|[`"']+$/g, "").trim();
381
- if (cleaned) {
382
- return cleaned;
383
- }
384
- }
385
- const inlineCode = /`([^`]+)`/.exec(title);
386
- if (inlineCode?.[1]?.trim()) {
387
- return inlineCode[1].trim();
388
- }
389
- const rpcOrPath = /([a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_-]+){2,}|\/[a-zA-Z0-9_/-]{2,})/.exec(title);
390
- return rpcOrPath?.[1];
391
- }
392
- const CHAIN_SECTION_HEADING_REGEX = /^(?:3\s*[.、::)\]]\s*)?(?:链路详解|Chain Details)(?:$|\s|[::(/(-])/i;
393
- const LAYER_BULLET_NAME_REGEX = /^(?:L[1-4](?:\b|\s|[-_—::])|Step\s*\d+\b|阶段\s*\d+|步骤\s*\d+|入口接口|服务编排|核心模块|下游依赖|配置|实验|数据库(?:表)?)/i;
394
- /**
395
- * Checks whether Section 3 (`3. 链路详解` / `3. Chain Details`) contains at least one explicit
396
- * chain subheading (`###` under `## 3.`, or `##`/`###` under `# 3.`), ignoring fenced code blocks,
397
- * HTML comments, and indented code blocks.
398
- */
399
- export function hasExplicitChainSubheadings(markdown) {
400
- const scanned = scanMarkdownDocument(markdown);
401
- let inChainSection = false;
402
- let chainSectionLevel = 2;
403
- for (const entry of scanned) {
404
- if (!entry.heading) {
405
- continue;
406
- }
407
- const { level, text: plainText } = entry.heading;
408
- if (!inChainSection) {
409
- if (CHAIN_SECTION_HEADING_REGEX.test(plainText)) {
410
- inChainSection = true;
411
- chainSectionLevel = level;
412
- }
413
- continue;
414
- }
415
- if (level <= chainSectionLevel) {
416
- break;
417
- }
418
- if (level <= Math.max(3, chainSectionLevel + 1)) {
419
- return true;
420
- }
421
- }
422
- return false;
423
- }
424
- /**
425
- * Extracts core interface chains from Section 3 (`3. 链路详解` / `3. Chain Details`).
426
- * Supports `# 3. 链路详解` or `## 3. 链路详解` with `##` or `###` chain headings (as in `img-10.png`),
427
- * ignoring headings inside fenced code blocks, HTML comments, or indented code blocks.
428
- * Falls back to named `- **Chain Name**: ...` bullets or a single Section 3 overview chain when
429
- * Section 3 contains non-empty prose without explicit `###` chain subheadings.
430
- */
431
- export function extractSceneChains(markdown) {
432
- return extractSceneChainsFromScanned(scanMarkdownDocument(markdown));
433
- }
434
- function extractSceneChainsFromScanned(scanned) {
435
- let inChainSection = false;
436
- let chainSectionLevel = 2;
437
- let chainHeadingLevel = null;
438
- const rawSubsections = [];
439
- let currentSub = null;
440
- const sectionEntries = [];
441
- for (const entry of scanned) {
442
- if (entry.heading) {
443
- const { level, text: plainText } = entry.heading;
444
- if (!inChainSection) {
445
- if (CHAIN_SECTION_HEADING_REGEX.test(plainText)) {
446
- inChainSection = true;
447
- chainSectionLevel = level;
448
- }
449
- continue;
450
- }
451
- if (level <= chainSectionLevel) {
452
- break;
453
- }
454
- sectionEntries.push(entry);
455
- if (level <= Math.max(3, chainSectionLevel + 1) &&
456
- (chainHeadingLevel === null || level <= chainHeadingLevel)) {
457
- chainHeadingLevel = level;
458
- if (currentSub) {
459
- rawSubsections.push(currentSub);
460
- }
461
- currentSub = { title: plainText, lines: [entry.rawLine] };
462
- continue;
463
- }
464
- }
465
- else if (inChainSection) {
466
- sectionEntries.push(entry);
467
- }
468
- if (inChainSection && currentSub) {
469
- currentSub.lines.push(entry.rawLine);
470
- }
471
- }
472
- if (currentSub) {
473
- rawSubsections.push(currentSub);
474
- }
475
- if (rawSubsections.length > 0) {
476
- return rawSubsections.map((sub, idx) => {
477
- const entryPoint = extractEntryPointFromTitle(sub.title);
478
- return {
479
- id: slugifyChainId(entryPoint ?? sub.title, idx),
480
- title: sub.title,
481
- ...(entryPoint ? { entryPoint } : {}),
482
- markdown: sub.lines.join("\n").trim(),
483
- };
484
- });
485
- }
486
- if (!inChainSection) {
487
- return [];
488
- }
489
- const hasVisibleProse = sectionEntries.some((e) => e.proseLine !== null && e.proseLine.trim().length > 0);
490
- if (!hasVisibleProse) {
491
- return [];
492
- }
493
- // Fallback 1: Named top-level `- **Name**: ...` chain bullets (excluding L1..L4 layer bullets)
494
- const bulletChains = [];
495
- let currentBullet = null;
496
- let allBulletsAreNamedNonLayer = true;
497
- for (const entry of sectionEntries) {
498
- if (entry.proseLine === null) {
499
- if (currentBullet) {
500
- currentBullet.lines.push(entry.rawLine);
501
- }
502
- continue;
503
- }
504
- const trimmed = entry.proseLine.trim();
505
- if (!trimmed) {
506
- if (currentBullet) {
507
- currentBullet.lines.push(entry.rawLine);
508
- }
509
- continue;
510
- }
511
- const isTopLevelBullet = /^(?:[-*+]|\d+[.)、])\s+/.test(entry.proseLine);
512
- if (isTopLevelBullet) {
513
- const namedBulletMatch = /^(?:[-*+]|\d+[.)、])\s+\*\*([^*]+)\*\*\s*(?:[::—-]\s*(.*))?$/.exec(entry.proseLine.trim());
514
- const rawName = namedBulletMatch?.[1]?.trim();
515
- if (!rawName || LAYER_BULLET_NAME_REGEX.test(rawName)) {
516
- allBulletsAreNamedNonLayer = false;
517
- break;
518
- }
519
- if (currentBullet) {
520
- bulletChains.push(currentBullet);
521
- }
522
- currentBullet = { title: rawName, lines: [entry.rawLine] };
523
- continue;
524
- }
525
- if (currentBullet && /^\s+/.test(entry.rawLine)) {
526
- currentBullet.lines.push(entry.rawLine);
527
- }
528
- else if (!currentBullet) {
529
- allBulletsAreNamedNonLayer = false;
530
- break;
531
- }
532
- }
533
- if (currentBullet && allBulletsAreNamedNonLayer) {
534
- bulletChains.push(currentBullet);
535
- }
536
- if (allBulletsAreNamedNonLayer && bulletChains.length > 0) {
537
- return bulletChains.map((b, idx) => {
538
- const entryPoint = extractEntryPointFromTitle(b.title);
539
- return {
540
- id: slugifyChainId(entryPoint ?? b.title, idx),
541
- title: b.title,
542
- ...(entryPoint ? { entryPoint } : {}),
543
- markdown: b.lines.join("\n").trim(),
544
- };
545
- });
546
- }
547
- // Fallback 2: Single Section 3 overview chain so `scene.chains` is never empty on legacy prose
548
- const sectionBody = sectionEntries
549
- .map((e) => e.rawLine)
550
- .join("\n")
551
- .trim();
552
- if (!sectionBody) {
553
- return [];
554
- }
555
- return [
556
- {
557
- id: "section-3-overview",
558
- title: "Section 3 Overview (missing ### chain subheadings)",
559
- markdown: sectionBody,
560
- },
561
- ];
562
- }
563
- const PENDING_SECTION_HEADING_REGEX = /^(?:4\s*[.、::)\]]\s*)?(?:待确认项|Pending Confirmations)(?:$|\s|[::(/(-])/i;
564
- const CLEAN_PENDING_VALUES = new Set([
565
- "无",
566
- "暂无",
567
- "无待确认项",
568
- "暂无待确认项",
569
- "none",
570
- "n/a",
571
- "na",
572
- "nil",
573
- "null",
574
- "no pending confirmations",
575
- "no pending items",
576
- "nothing pending",
577
- ]);
578
- function normalizePendingToken(value) {
579
- return value
580
- .replace(/^(?:\*\*|__|\*|_)+|(?:\*\*|__|\*|_)+$/g, "")
581
- .replace(/^[((]\s*|\s*[))]$/g, "")
582
- .replace(/^[>.`\s]+|[.`\s。!!;;]+$/g, "")
583
- .trim()
584
- .toLowerCase();
585
- }
586
- /**
587
- * Parses Section 4 (`4. 待确认项` / `4. Pending Confirmations`) and determines whether
588
- * active unresolved confirmation items remain. Ignores headings and body lines inside
589
- * HTML comments (`<!-- ... -->`), fenced code blocks, and indented code blocks (4+ spaces / `\t`).
590
- */
591
- export function extractPendingConfirmations(markdown) {
592
- return extractPendingConfirmationsFromScanned(scanMarkdownDocument(markdown));
593
- }
594
- export function parseSceneMarkdownStructure(markdown) {
595
- const scanned = scanMarkdownDocument(markdown);
596
- const headings = [];
597
- for (const entry of scanned) {
598
- if (entry.heading) {
599
- headings.push(entry.heading.text);
600
- }
601
- }
602
- return {
603
- headings,
604
- chains: extractSceneChainsFromScanned(scanned),
605
- pending: extractPendingConfirmationsFromScanned(scanned),
606
- };
607
- }
608
- function extractPendingConfirmationsFromScanned(scanned) {
609
- let inPendingSection = false;
610
- let pendingLevel = 2;
611
- const nonEmptyLines = [];
612
- for (const entry of scanned) {
613
- if (entry.heading) {
614
- const { level, text: plainText } = entry.heading;
615
- if (!inPendingSection) {
616
- if (PENDING_SECTION_HEADING_REGEX.test(plainText)) {
617
- inPendingSection = true;
618
- pendingLevel = level;
619
- }
620
- continue;
621
- }
622
- if (level <= pendingLevel) {
623
- break;
624
- }
625
- }
626
- if (inPendingSection && entry.proseLine !== null) {
627
- const trimmed = entry.proseLine.trim();
628
- if (trimmed.length > 0) {
629
- nonEmptyLines.push(trimmed);
630
- }
631
- }
632
- }
633
- if (!inPendingSection) {
634
- return { sectionFound: false, items: [], hasActiveItems: false };
635
- }
636
- if (nonEmptyLines.length === 0) {
637
- return { sectionFound: true, items: [], hasActiveItems: false, isEmptyBody: true };
638
- }
639
- const items = [];
640
- for (let i = 0; i < nonEmptyLines.length; i++) {
641
- const rawLine = nonEmptyLines[i] ?? "";
642
- // Ignore Markdown horizontal rules (`---`, `***`, `___`)
643
- if (/^(?:-\s*){3,}$|^(?:\*\s*){3,}$|^(?:_\s*){3,}$/.test(rawLine)) {
644
- continue;
645
- }
646
- // Ignore Markdown table separator lines (`| --- | --- |`)
647
- const isTableSep = /^\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-{2,}:?\s*\|?$/.test(rawLine);
648
- if (isTableSep) {
649
- continue;
650
- }
651
- // Ignore Markdown table header row immediately preceding a separator line
652
- const nextLine = nonEmptyLines[i + 1] ?? "";
653
- if (rawLine.includes("|") && /^\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-{2,}:?\s*\|?$/.test(nextLine)) {
654
- continue;
655
- }
656
- // Handle Markdown table data rows (`| col1 | col2 |`)
657
- if (rawLine.startsWith("|") && rawLine.endsWith("|")) {
658
- const cells = rawLine
659
- .slice(1, -1)
660
- .split("|")
661
- .map((c) => c.trim())
662
- .filter((c) => c.length > 0 && c !== "-");
663
- if (cells.length === 0) {
664
- continue;
665
- }
666
- const firstCellNorm = normalizePendingToken(cells[0] ?? "");
667
- if (CLEAN_PENDING_VALUES.has(firstCellNorm)) {
668
- continue;
669
- }
670
- items.push(cells.join(" — "));
671
- continue;
672
- }
673
- // Completed markdown checkboxes (`- [x] ...`) are resolved
674
- if (/^[-*+]\s+\[[xX]\]\s+/.test(rawLine)) {
675
- continue;
676
- }
677
- const stripped = rawLine
678
- .replace(/^[-*+]\s+(?:\[\s*\]\s+)?/, "")
679
- .replace(/^\d+[.)、]\s+/, "")
680
- .replace(/^[>.`\s]+|[.`\s。]+$/g, "")
681
- .trim();
682
- if (!stripped) {
683
- continue;
684
- }
685
- if (CLEAN_PENDING_VALUES.has(normalizePendingToken(stripped))) {
686
- continue;
687
- }
688
- items.push(stripped);
689
- }
690
- return {
691
- sectionFound: true,
692
- items,
693
- hasActiveItems: items.length > 0,
694
- };
695
- }
696
- function escapeRegExp(str) {
697
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
698
- }
699
- const IDENTIFIER_ONLY_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
700
- const OWNER_MEMBER_SYMBOL_REGEX = /^([A-Za-z_$][A-Za-z0-9_$]*)[#.]([A-Za-z_$][A-Za-z0-9_$]*)$/;
701
- const STATEMENT_STARTER_REGEX = /^(?:export|import|function|async|class|abstract|interface|type|enum|namespace|module|const|let|var|return|if|for|while|switch|try|throw)\b/;
702
- /**
703
- * Masks `//...` line comments, `/*...*\/` block comments, and string/template literal contents
704
- * with spaces while preserving line breaks, `${...}` template expressions, and `{ ... }` braces.
705
- */
706
- function stripCodeCommentsAndStrings(source) {
707
- const out = new Array(source.length);
708
- let state = "code";
709
- const templateBraceStack = [];
710
- let i = 0;
711
- while (i < source.length) {
712
- const ch = source[i];
713
- const next = source[i + 1];
714
- if (state === "code") {
715
- if (ch === "/" && next === "/") {
716
- out[i] = " ";
717
- out[i + 1] = " ";
718
- state = "line_comment";
719
- i += 2;
720
- continue;
721
- }
722
- if (ch === "/" && next === "*") {
723
- out[i] = " ";
724
- out[i + 1] = " ";
725
- state = "block_comment";
726
- i += 2;
727
- continue;
728
- }
729
- if (ch === "'") {
730
- out[i] = "'";
731
- state = "single_quote";
732
- i += 1;
733
- continue;
734
- }
735
- if (ch === '"') {
736
- out[i] = '"';
737
- state = "double_quote";
738
- i += 1;
739
- continue;
740
- }
741
- if (ch === "`") {
742
- out[i] = "`";
743
- state = "template";
744
- i += 1;
745
- continue;
746
- }
747
- if (templateBraceStack.length > 0) {
748
- const topIdx = templateBraceStack.length - 1;
749
- if (ch === "{") {
750
- templateBraceStack[topIdx] += 1;
751
- }
752
- else if (ch === "}") {
753
- const depth = templateBraceStack[topIdx];
754
- if (depth === 0) {
755
- templateBraceStack.pop();
756
- out[i] = " ";
757
- state = "template";
758
- i += 1;
759
- continue;
760
- }
761
- templateBraceStack[topIdx] = depth - 1;
762
- }
763
- }
764
- out[i] = ch;
765
- i += 1;
766
- continue;
767
- }
768
- if (state === "line_comment") {
769
- if (ch === "\n" || ch === "\r") {
770
- out[i] = ch;
771
- if (ch === "\n") {
772
- state = "code";
773
- }
774
- }
775
- else {
776
- out[i] = " ";
777
- }
778
- i += 1;
779
- continue;
780
- }
781
- if (state === "block_comment") {
782
- if (ch === "*" && next === "/") {
783
- out[i] = " ";
784
- out[i + 1] = " ";
785
- state = "code";
786
- i += 2;
787
- continue;
788
- }
789
- out[i] = ch === "\n" || ch === "\r" ? ch : " ";
790
- i += 1;
791
- continue;
792
- }
793
- if (state === "single_quote" || state === "double_quote") {
794
- const quoteChar = state === "single_quote" ? "'" : '"';
795
- if (ch === "\\" && next !== undefined) {
796
- out[i] = " ";
797
- out[i + 1] = next === "\n" || next === "\r" ? next : " ";
798
- i += 2;
799
- continue;
800
- }
801
- if (ch === quoteChar) {
802
- out[i] = quoteChar;
803
- state = "code";
804
- i += 1;
805
- continue;
806
- }
807
- if (ch === "\n" || ch === "\r") {
808
- out[i] = ch;
809
- if (ch === "\n") {
810
- state = "code";
811
- }
812
- i += 1;
813
- continue;
814
- }
815
- out[i] = " ";
816
- i += 1;
817
- continue;
818
- }
819
- // state === "template"
820
- if (ch === "\\" && next !== undefined) {
821
- out[i] = " ";
822
- out[i + 1] = next === "\n" || next === "\r" ? next : " ";
823
- i += 2;
824
- continue;
825
- }
826
- if (ch === "$" && next === "{") {
827
- out[i] = " ";
828
- out[i + 1] = " ";
829
- templateBraceStack.push(0);
830
- state = "code";
831
- i += 2;
832
- continue;
833
- }
834
- if (ch === "`") {
835
- out[i] = "`";
836
- state = "code";
837
- i += 1;
838
- continue;
839
- }
840
- out[i] = ch === "\n" || ch === "\r" ? ch : " ";
841
- i += 1;
842
- }
843
- return out.join("");
844
- }
845
- function hasIdentifier(cleanedText, ident) {
846
- const idRegex = new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(ident)}(?![A-Za-z0-9_$])`);
847
- return idRegex.test(cleanedText);
848
- }
849
- function readBalancedBraceBlock(cleaned, openBraceIndex) {
850
- if (cleaned[openBraceIndex] !== "{") {
851
- return undefined;
852
- }
853
- let depth = 0;
854
- for (let i = openBraceIndex; i < cleaned.length; i++) {
855
- const ch = cleaned[i];
856
- if (ch === "{") {
857
- depth += 1;
858
- }
859
- else if (ch === "}") {
860
- depth -= 1;
861
- if (depth === 0) {
862
- return {
863
- block: cleaned.slice(openBraceIndex, i + 1),
864
- endIndex: i + 1,
865
- };
866
- }
867
- }
868
- }
869
- return undefined;
870
- }
871
- function extractOwnerDeclarationBlocks(cleaned, owner) {
872
- const blocks = [];
873
- const escapedOwner = escapeRegExp(owner);
874
- // 1. Nominal block declarations: class / interface / enum / namespace / module / struct
875
- const blockDeclRegex = new RegExp(`(?<![A-Za-z0-9_$])(?:class|interface|enum|namespace|module|struct)\\s+${escapedOwner}(?![A-Za-z0-9_$])`, "g");
876
- for (const match of cleaned.matchAll(blockDeclRegex)) {
877
- const startIdx = (match.index ?? 0) + match[0].length;
878
- let angleDepth = 0;
879
- let parenDepth = 0;
880
- for (let i = startIdx; i < cleaned.length; i++) {
881
- const ch = cleaned[i];
882
- if (angleDepth === 0 && parenDepth === 0) {
883
- if (ch === ";") {
884
- break;
885
- }
886
- if (ch === "{") {
887
- const extracted = readBalancedBraceBlock(cleaned, i);
888
- if (extracted) {
889
- blocks.push(extracted.block);
890
- }
891
- break;
892
- }
893
- }
894
- if (ch === "<") {
895
- angleDepth += 1;
896
- }
897
- else if (ch === ">" && angleDepth > 0 && cleaned[i - 1] !== "=") {
898
- angleDepth -= 1;
899
- }
900
- else if (ch === "(") {
901
- parenDepth += 1;
902
- }
903
- else if (ch === ")" && parenDepth > 0) {
904
- parenDepth -= 1;
905
- }
906
- }
907
- }
908
- // 2. Type alias & value declarations: type / const / let / var Owner = ... { ... }
909
- const assignDeclRegex = new RegExp(`(?<![A-Za-z0-9_$])(?:type|const|let|var)\\s+${escapedOwner}(?![A-Za-z0-9_$])`, "g");
910
- for (const match of cleaned.matchAll(assignDeclRegex)) {
911
- const startIdx = (match.index ?? 0) + match[0].length;
912
- let angleDepth = 0;
913
- let parenDepth = 0;
914
- let bracketDepth = 0;
915
- let seenEquals = false;
916
- let seenRhsToken = false;
917
- let i = startIdx;
918
- while (i < cleaned.length) {
919
- const ch = cleaned[i];
920
- if (angleDepth === 0 && parenDepth === 0 && bracketDepth === 0) {
921
- if (ch === ";") {
922
- break;
923
- }
924
- if (!seenEquals &&
925
- ch === "=" &&
926
- cleaned[i + 1] !== "=" &&
927
- cleaned[i + 1] !== ">" &&
928
- cleaned[i - 1] !== "!" &&
929
- cleaned[i - 1] !== "<" &&
930
- cleaned[i - 1] !== ">") {
931
- seenEquals = true;
932
- i += 1;
933
- continue;
934
- }
935
- if (ch === "{") {
936
- const extracted = readBalancedBraceBlock(cleaned, i);
937
- if (!extracted) {
938
- break;
939
- }
940
- blocks.push(extracted.block);
941
- if (seenEquals) {
942
- seenRhsToken = true;
943
- }
944
- i = extracted.endIndex;
945
- continue;
946
- }
947
- if (seenEquals && seenRhsToken && ch === "\n") {
948
- const restTrimmed = cleaned.slice(i + 1).trimStart();
949
- if (STATEMENT_STARTER_REGEX.test(restTrimmed)) {
950
- break;
951
- }
952
- }
953
- }
954
- if (ch === "<" && !seenEquals) {
955
- angleDepth += 1;
956
- }
957
- else if (ch === ">" && angleDepth > 0 && cleaned[i - 1] !== "=") {
958
- angleDepth -= 1;
959
- }
960
- else if (ch === "(") {
961
- parenDepth += 1;
962
- if (seenEquals) {
963
- seenRhsToken = true;
964
- }
965
- }
966
- else if (ch === ")" && parenDepth > 0) {
967
- parenDepth -= 1;
968
- }
969
- else if (ch === "[") {
970
- bracketDepth += 1;
971
- if (seenEquals) {
972
- seenRhsToken = true;
973
- }
974
- }
975
- else if (ch === "]" && bracketDepth > 0) {
976
- bracketDepth -= 1;
977
- }
978
- else if (seenEquals && !/\s/.test(ch)) {
979
- seenRhsToken = true;
980
- }
981
- i += 1;
982
- }
983
- }
984
- return blocks;
985
- }
986
- /**
987
- * Checks whether `symbol` exists in live source `content`.
988
- * - Strips `//...` line comments, `/*...*\/` block comments, and string literals first so dead code
989
- * or log strings never pass anchor verification.
990
- * - For `Owner#member` or `Owner.member`, extracts `Owner`'s balanced `{ ... }` declaration block
991
- * (`class` / `interface` / `type` / `const` / etc.) and verifies `member` is declared inside `Owner`.
992
- */
993
- export function containsSymbol(content, symbol) {
994
- const trimmed = symbol.trim();
995
- if (!trimmed) {
996
- return true;
997
- }
998
- const cleaned = stripCodeCommentsAndStrings(content);
999
- if (IDENTIFIER_ONLY_REGEX.test(trimmed)) {
1000
- return hasIdentifier(cleaned, trimmed);
1001
- }
1002
- const ownerMemberMatch = OWNER_MEMBER_SYMBOL_REGEX.exec(trimmed);
1003
- if (ownerMemberMatch) {
1004
- const owner = ownerMemberMatch[1];
1005
- const member = ownerMemberMatch[2];
1006
- const ownerBlocks = extractOwnerDeclarationBlocks(cleaned, owner);
1007
- if (ownerBlocks.some((block) => hasIdentifier(block, member))) {
1008
- return true;
1009
- }
1010
- // Support explicit static/prototype assignment (`Owner.member = ...` / `Owner.prototype.member = ...`)
1011
- const propAssignRegex = new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(owner)}\\s*\\.(?:\\s*prototype\\s*\\.)?\\s*${escapeRegExp(member)}(?![A-Za-z0-9_$])\\s*=`);
1012
- if (propAssignRegex.test(cleaned)) {
1013
- return true;
1014
- }
1015
- // Support Go receiver methods (`func (r *Owner) member(...)`)
1016
- const goReceiverRegex = new RegExp(`(?<![A-Za-z0-9_$])func\\s*\\(\\s*(?:[A-Za-z_$][A-Za-z0-9_$]*\\s+)?\\*?\\s*${escapeRegExp(owner)}\\s*\\)\\s*${escapeRegExp(member)}(?![A-Za-z0-9_$])`);
1017
- return goReceiverRegex.test(cleaned);
1018
- }
1019
- return cleaned.includes(trimmed);
1020
- }
1021
- function globToRegExp(globPattern) {
1022
- let regexStr = "^";
1023
- let i = 0;
1024
- while (i < globPattern.length) {
1025
- const ch = globPattern[i];
1026
- if (ch === "*") {
1027
- if (globPattern[i + 1] === "*") {
1028
- if (globPattern[i + 2] === "/") {
1029
- // `**/` matches zero or more directories
1030
- regexStr += "(?:.+/)?";
1031
- i += 3;
1032
- continue;
1033
- }
1034
- if (i > 0 && globPattern[i - 1] === "/" && i + 2 === globPattern.length) {
1035
- // Trailing `/**` matches anything inside directory
1036
- regexStr += ".*";
1037
- i += 2;
1038
- continue;
1039
- }
1040
- regexStr += ".*";
1041
- i += 2;
1042
- continue;
1043
- }
1044
- regexStr += "[^/]*";
1045
- i += 1;
1046
- continue;
1047
- }
1048
- if (ch === "?") {
1049
- regexStr += "[^/]";
1050
- i += 1;
1051
- continue;
1052
- }
1053
- if (ch === "{") {
1054
- const closeBrace = globPattern.indexOf("}", i + 1);
1055
- if (closeBrace !== -1) {
1056
- const alternatives = globPattern
1057
- .slice(i + 1, closeBrace)
1058
- .split(",")
1059
- .map((alt) => escapeRegExp(alt.trim()));
1060
- regexStr += `(?:${alternatives.join("|")})`;
1061
- i = closeBrace + 1;
1062
- continue;
1063
- }
1064
- }
1065
- regexStr += escapeRegExp(ch);
1066
- i += 1;
1067
- }
1068
- regexStr += "$";
1069
- return new RegExp(regexStr);
1070
- }
1071
- /**
1072
- * Matches a POSIX-normalized changed file path against optional `RepositoryRef.paths`
1073
- * entries, supporting both directory/file prefixes (`src/checkin`) and globs (`src/checkin/**`, `*.yaml`).
1074
- */
1075
- export function matchesWatchPaths(changedFile, watchPaths) {
1076
- if (!watchPaths || watchPaths.length === 0) {
1077
- return true;
1078
- }
1079
- const normalizedChanged = toPosixPath(changedFile).replace(/^(?:\.\/|\/)+/, "");
1080
- return watchPaths.some((rawPattern) => {
1081
- const normalizedPattern = toPosixPath(rawPattern)
1082
- .trim()
1083
- .replace(/^(?:\.\/|\/)+/, "")
1084
- .replace(/\/+$/, "");
1085
- if (!normalizedPattern || normalizedPattern === "." || normalizedPattern === "**") {
1086
- return true;
1087
- }
1088
- if (/[*?[{]/.test(normalizedPattern)) {
1089
- if (normalizedPattern.endsWith("/**")) {
1090
- const baseDir = normalizedPattern.slice(0, -3).replace(/\/+$/, "");
1091
- if (!baseDir ||
1092
- normalizedChanged === baseDir ||
1093
- normalizedChanged.startsWith(`${baseDir}/`)) {
1094
- return true;
1095
- }
1096
- }
1097
- return globToRegExp(normalizedPattern).test(normalizedChanged);
1098
- }
1099
- return (normalizedChanged === normalizedPattern ||
1100
- normalizedChanged.startsWith(`${normalizedPattern}/`));
1101
- });
1102
- }
1103
- const SCAFFOLD_PLACEHOLDER_PATTERNS = [
1104
- { token: "<API / Handler>", label: "<API / Handler>" },
1105
- { token: "<Service / Coordinator>", label: "<Service / Coordinator>" },
1106
- ];
1107
- /**
1108
- * Detects unedited scaffold placeholder tokens (`<API / Handler>`, `<Service / Coordinator>`)
1109
- * in visible Markdown headings/prose while ignoring fenced code blocks and HTML comments.
1110
- */
1111
- export function detectSceneContentPlaceholders(markdown) {
1112
- const scanned = scanMarkdownDocument(markdown);
1113
- const found = new Set();
1114
- for (const entry of scanned) {
1115
- if (entry.proseLine === null) {
1116
- continue;
1117
- }
1118
- for (const item of SCAFFOLD_PLACEHOLDER_PATTERNS) {
1119
- if (entry.proseLine.includes(item.token)) {
1120
- found.add(item.label);
1121
- }
1122
- }
1123
- }
1124
- return Array.from(found);
1125
- }
1126
- /**
1127
- * Strips embedded credentials (`username` / `password` / PAT tokens) from Git remote URLs
1128
- * so sanitized URLs are safe to persist in `wiki.config.yaml`, frontmatter, JSON, and logs.
1129
- * Browser-safe (zero `node:*` imports).
1130
- *
1131
- * - For `http://`, `https://`, `ssh://`, `git://` (and `git+...://`) URLs: parses via `new URL(...)`,
1132
- * clears `username` and `password`, and returns the clean URL string.
1133
- * - For SCP-style SSH URLs (`user@host:path` or `user:secret@host:path`): preserves `user@host:path`
1134
- * (e.g. `git@github.com:org/repo.git`) while stripping `:secret`!
1135
- */
1136
- export function sanitizeGitRemoteUrl(rawUrl) {
1137
- if (typeof rawUrl !== "string") {
1138
- return "";
1139
- }
1140
- const trimmed = rawUrl.trim();
1141
- if (!trimmed) {
1142
- return "";
1143
- }
1144
- // 1. Standard scheme:// URLs (http://, https://, ssh://, git://, git+https://, etc.)
1145
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
1146
- try {
1147
- const parsed = new URL(trimmed);
1148
- parsed.username = "";
1149
- parsed.password = "";
1150
- return parsed.toString();
1151
- }
1152
- catch {
1153
- return trimmed.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)(?:[^@/\s]+@)+/, "$1");
1154
- }
1155
- }
1156
- // 2. SCP-style SSH URLs: [user[:secret]@]host:path (excluding Windows drive paths like E:\... or C:/...)
1157
- if (!/^[a-zA-Z]:[\\/]/.test(trimmed)) {
1158
- const scpWithUser = /^([^@/\s]*)@([a-zA-Z0-9.-]+|\[[^\]]+\]):(.+)$/.exec(trimmed);
1159
- if (scpWithUser) {
1160
- const rawUserInfo = scpWithUser[1] ?? "";
1161
- const host = scpWithUser[2] ?? "";
1162
- const repoPath = scpWithUser[3] ?? "";
1163
- const cleanUser = (rawUserInfo.split(":")[0] ?? "").trim();
1164
- return cleanUser ? `${cleanUser}@${host}:${repoPath}` : `${host}:${repoPath}`;
1165
- }
1166
- }
1167
- return trimmed;
1168
- }
1169
- function decodeUriPathSafe(pathname) {
1170
- try {
1171
- return decodeURIComponent(pathname);
1172
- }
1173
- catch {
1174
- return pathname;
1175
- }
1176
- }
1177
- function isDefaultPortForScheme(baseScheme, port) {
1178
- return ((baseScheme === "http" && port === "80") ||
1179
- (baseScheme === "https" && port === "443") ||
1180
- (baseScheme === "ssh" && port === "22") ||
1181
- (baseScheme === "git" && port === "9418"));
1182
- }
1183
- /**
1184
- * Normalizes a Git remote URL or `<org>/<repo>` identifier into a canonical lowercase key
1185
- * so SSH (`git@host:group/sub/repo.git`), HTTPS (`https://host/group/sub/repo.git`), and `ssh://`
1186
- * URLs compare identically (`host/group/sub/repo`), while preserving explicit non-default ports
1187
- * (`host:port/group/sub/repo`) and full multi-segment namespace paths.
1188
- */
1189
- export function normalizeGitUrlKey(url) {
1190
- const sanitized = sanitizeGitRemoteUrl(url);
1191
- if (!sanitized) {
1192
- return "";
1193
- }
1194
- // 1. Standard protocol URLs: https://, http://, ssh://, git://, git+https://, git+ssh://
1195
- const schemeMatch = /^(?:git\+)?(https?|ssh|git):\/\//i.exec(sanitized);
1196
- if (schemeMatch?.[1]) {
1197
- const baseScheme = schemeMatch[1].toLowerCase();
1198
- try {
1199
- const parsed = new URL(sanitized);
1200
- const hostname = parsed.hostname.toLowerCase();
1201
- const port = parsed.port;
1202
- const hostPart = port && !isDefaultPortForScheme(baseScheme, port) ? `${hostname}:${port}` : hostname;
1203
- const repoPath = toPosixPath(decodeUriPathSafe(parsed.pathname))
1204
- .replace(/^\/+|\/+$/g, "")
1205
- .replace(/\.git$/i, "")
1206
- .toLowerCase();
1207
- return repoPath ? `${hostPart}/${repoPath}` : hostPart;
1208
- }
1209
- catch {
1210
- const protoFallback = /^(?:git\+)?(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^/:\s]+)(?::(\d+))?\/(.+)$/i.exec(sanitized);
1211
- if (protoFallback?.[1] && protoFallback[3]) {
1212
- const hostname = protoFallback[1].toLowerCase();
1213
- const port = protoFallback[2] ?? "";
1214
- const hostPart = port && !isDefaultPortForScheme(baseScheme, port) ? `${hostname}:${port}` : hostname;
1215
- const repoPath = toPosixPath(protoFallback[3])
1216
- .replace(/^\/+|\/+$/g, "")
1217
- .replace(/\.git$/i, "")
1218
- .toLowerCase();
1219
- return repoPath ? `${hostPart}/${repoPath}` : hostPart;
1220
- }
1221
- }
1222
- }
1223
- // 2. Already-normalized `host:port/namespace/repo` key (without `user@`): keep `:port` intact!
1224
- if (!sanitized.includes("@") && /^[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+:\d+\/.+$/.test(sanitized)) {
1225
- const idx = sanitized.indexOf("/");
1226
- const hostPort = sanitized.slice(0, idx).toLowerCase();
1227
- const repoPath = toPosixPath(sanitized.slice(idx + 1))
1228
- .replace(/^\/+|\/+$/g, "")
1229
- .replace(/\.git$/i, "")
1230
- .toLowerCase();
1231
- return repoPath ? `${hostPort}/${repoPath}` : hostPort;
1232
- }
1233
- // 3. SCP-style SSH URLs: git@host:group/subgroup/repo.git (excluding Windows drive paths like E:\... or C:/...)
1234
- if (!/^[a-zA-Z]:[\\/]/.test(sanitized)) {
1235
- const scpMatch = /^(?:[^@/\s]+@)?([a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+):(.+)$/.exec(sanitized);
1236
- if (scpMatch?.[1] && scpMatch[2]) {
1237
- const host = scpMatch[1].toLowerCase();
1238
- const repoPath = toPosixPath(scpMatch[2])
1239
- .replace(/^\/+|\/+$/g, "")
1240
- .replace(/\.git$/i, "")
1241
- .toLowerCase();
1242
- return repoPath ? `${host}/${repoPath}` : host;
1243
- }
1244
- }
1245
- // 4. Plain `<org>/<repo>` or `<group>/<subgroup>/<repo>` identifier
1246
- return toPosixPath(sanitized)
1247
- .replace(/^\/+|\/+$/g, "")
1248
- .replace(/\.git$/i, "")
1249
- .toLowerCase();
1250
- }
1
+ export { detectSceneContentPlaceholders, extractMarkdownHeadings, extractPendingConfirmations, extractSceneChains, hasExplicitChainSubheadings, parseSceneMarkdownStructure, } from "./utils/markdown.js";
2
+ export { COMMIT_SHA_REGEX, isSafeContainedRelativePath, KEBAB_CASE_REGEX, matchesWatchPaths, normalizeGitUrlKey, SCENE_REF_REGEX, SHA256_HEX_REGEX, sanitizeGitRemoteUrl, toPosixPath, } from "./utils/paths.js";
3
+ export { containsSymbol } from "./utils/symbols.js";
1251
4
  //# sourceMappingURL=utils.js.map