@neuledge/context 1.3.6 → 1.4.0

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.
@@ -0,0 +1,86 @@
1
+ export function createIngestionReport(diagnostics) {
2
+ const summary = {
3
+ discoveredFiles: 0,
4
+ selectedFiles: 0,
5
+ indexedDocuments: 0,
6
+ indexedSections: 0,
7
+ excludedFiles: 0,
8
+ excludedDirectories: 0,
9
+ duplicateFiles: 0,
10
+ unreadableFiles: 0,
11
+ unreadableDirectories: 0,
12
+ parseFailures: 0,
13
+ emptyFiles: 0,
14
+ };
15
+ for (const entry of diagnostics) {
16
+ if (entry.kind === "directory") {
17
+ if (entry.outcome === "excluded")
18
+ summary.excludedDirectories++;
19
+ if (entry.outcome === "read-error")
20
+ summary.unreadableDirectories++;
21
+ continue;
22
+ }
23
+ summary.discoveredFiles++;
24
+ if (entry.outcome !== "excluded" && entry.outcome !== "duplicate") {
25
+ summary.selectedFiles++;
26
+ }
27
+ switch (entry.outcome) {
28
+ case "excluded":
29
+ summary.excludedFiles++;
30
+ break;
31
+ case "duplicate":
32
+ summary.duplicateFiles++;
33
+ break;
34
+ case "read-error":
35
+ summary.unreadableFiles++;
36
+ break;
37
+ case "parse-error":
38
+ summary.parseFailures++;
39
+ break;
40
+ case "empty":
41
+ summary.emptyFiles++;
42
+ break;
43
+ case "indexed":
44
+ summary.indexedDocuments++;
45
+ summary.indexedSections += entry.sections ?? 0;
46
+ break;
47
+ }
48
+ }
49
+ const entries = diagnostics
50
+ .map((entry) => ({ ...entry }))
51
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
52
+ return { schemaVersion: 1, summary, entries };
53
+ }
54
+ /** Keep filesystem error codes useful without leaking checkout paths. */
55
+ export function ingestionErrorReason(error) {
56
+ const code = error?.code;
57
+ return typeof code === "string"
58
+ ? code
59
+ : error instanceof Error
60
+ ? error.message
61
+ : String(error);
62
+ }
63
+ export function formatIngestionSummary(report) {
64
+ const s = report.summary;
65
+ const count = (value, singular, plural = `${singular}s`) => `${value} ${value === 1 ? singular : plural}`;
66
+ return `Ingestion: ${count(s.discoveredFiles, "documentation file")} discovered, ${s.selectedFiles} selected, ${s.indexedDocuments} indexed, ${count(s.indexedSections, "section")}; excluded ${count(s.excludedFiles, "file")}/${count(s.excludedDirectories, "directory", "directories")}, ${count(s.duplicateFiles, "duplicate")}, unreadable ${count(s.unreadableFiles, "file")}/${count(s.unreadableDirectories, "directory", "directories")}, ${count(s.parseFailures, "parse failure")}, ${count(s.emptyFiles, "empty file")}`;
67
+ }
68
+ export class IngestionError extends Error {
69
+ diagnostics;
70
+ constructor(message, diagnostics) {
71
+ super(message);
72
+ this.name = "IngestionError";
73
+ this.diagnostics = createIngestionReport(diagnostics);
74
+ }
75
+ }
76
+ export function validateIngestion(report) {
77
+ const s = report.summary;
78
+ if (s.unreadableFiles +
79
+ s.unreadableDirectories +
80
+ s.parseFailures +
81
+ s.emptyFiles >
82
+ 0) {
83
+ throw new IngestionError("Strict ingestion validation failed: unreadable, unparseable, or empty documentation", report.entries);
84
+ }
85
+ }
86
+ //# sourceMappingURL=ingestion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ingestion.js","sourceRoot":"","sources":["../src/ingestion.ts"],"names":[],"mappings":"AAqCA,MAAM,UAAU,qBAAqB,CACnC,WAA2C;IAE3C,MAAM,OAAO,GAA+B;QAC1C,eAAe,EAAE,CAAC;QAClB,aAAa,EAAE,CAAC;QAChB,gBAAgB,EAAE,CAAC;QACnB,eAAe,EAAE,CAAC;QAClB,aAAa,EAAE,CAAC;QAChB,mBAAmB,EAAE,CAAC;QACtB,cAAc,EAAE,CAAC;QACjB,eAAe,EAAE,CAAC;QAClB,qBAAqB,EAAE,CAAC;QACxB,aAAa,EAAE,CAAC;QAChB,UAAU,EAAE,CAAC;KACd,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,WAAW,EAAE,CAAC;QAChC,IAAI,KAAK,CAAC,IAA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K,KAAK,CAAC,CAAC,CAAC,aAAa,EAAE,eAAe,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,UAAU,EAAE,YAAY,CAAC,EAAE,CAAC;AACxgB,CAAC;AAED,MAAM,OAAO,cAAe,SAAQ,KAAK;IAC9B,WAAW,CAAkB;IAEtC,YAAY,OAAe,EAAE,WAA2C;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,qBAAqB,CAAC,WAAW,CAAC,CAAC;IACxD,CAAC;CACF;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAuB;IACvD,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC;IACzB,IACE,CAAC,CAAC,eAAe;QACf,CAAC,CAAC,qBAAqB;QACvB,CAAC,CAAC,aAAa;QACf,CAAC,CAAC,UAAU;QACd,CAAC,EACD,CAAC;QACD,MAAM,IAAI,cAAc,CACtB,qFAAqF,EACrF,MAAM,CAAC,OAAO,CACf,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -9,6 +9,7 @@
9
9
  * llms-full.txt, by contrast, already inlines the full documentation and
10
10
  * doesn't need link following.
11
11
  */
12
+ import { type IngestionDiagnostic } from "./ingestion.js";
12
13
  import type { MarkdownFile } from "./package-builder.js";
13
14
  /** A link extracted from an llms.txt index. */
14
15
  export interface LlmsTxtLink {
@@ -37,9 +38,12 @@ export interface FetchLinkedDocsOptions {
37
38
  fetchImpl?: typeof fetch;
38
39
  /** Optional logger for progress messages. */
39
40
  log?: (message: string) => void;
41
+ /** Collect failed or empty linked pages for diagnostics and strict validation. */
42
+ diagnostics?: IngestionDiagnostic[];
40
43
  }
41
44
  /**
42
45
  * Fetch all links from an llms.txt index and return them as MarkdownFile entries
43
- * ready to be passed to `buildPackage`. Failed fetches are skipped silently.
46
+ * ready to be passed to `buildPackage`. Failed fetches are omitted and reported
47
+ * through the optional diagnostics collector.
44
48
  */
45
49
  export declare function fetchLinkedDocs(content: string, baseUrl: string, options?: FetchLinkedDocsOptions): Promise<MarkdownFile[]>;
package/dist/llms-txt.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * doesn't need link following.
11
11
  */
12
12
  import { buildFetchOptions, fetchWithTimeout } from "./fetch.js";
13
+ import { ingestionErrorReason } from "./ingestion.js";
13
14
  /**
14
15
  * Parse markdown link list items grouped by H2 section from an llms.txt file.
15
16
  * Resolves relative URLs against `baseUrl`. Invalid URLs are skipped silently.
@@ -42,14 +43,21 @@ export function parseLlmsTxtLinks(content, baseUrl) {
42
43
  return links;
43
44
  }
44
45
  /** Fetch a single URL and convert it to a MarkdownFile, or return null on failure. */
45
- async function fetchLink(url, fetchImpl, timeoutMs) {
46
+ async function fetchLink(url, fetchImpl, timeoutMs, diagnostics) {
46
47
  try {
47
48
  const response = await fetchWithTimeout(fetchImpl, url, buildFetchOptions(url), timeoutMs);
48
49
  if (!response.ok)
49
- return null;
50
+ throw new Error(`HTTP ${response.status}`);
50
51
  const text = await response.text();
51
- if (!text.trim())
52
+ if (!text.trim()) {
53
+ diagnostics?.push({
54
+ path: pathFromUrl(url, ".md"),
55
+ kind: "file",
56
+ outcome: "empty",
57
+ reason: "Linked page returned no content",
58
+ });
52
59
  return null;
60
+ }
53
61
  // Choose an extension so parseDocument routes to the right parser.
54
62
  const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
55
63
  const isHtml = contentType.includes("text/html") ||
@@ -59,7 +67,13 @@ async function fetchLink(url, fetchImpl, timeoutMs) {
59
67
  const path = pathFromUrl(url, isHtml ? ".html" : ".md");
60
68
  return { url, file: { path, content: text } };
61
69
  }
62
- catch {
70
+ catch (error) {
71
+ diagnostics?.push({
72
+ path: pathFromUrl(url, ".md"),
73
+ kind: "file",
74
+ outcome: "read-error",
75
+ reason: ingestionErrorReason(error),
76
+ });
63
77
  return null;
64
78
  }
65
79
  }
@@ -75,7 +89,8 @@ function pathFromUrl(url, defaultExt) {
75
89
  }
76
90
  /**
77
91
  * Fetch all links from an llms.txt index and return them as MarkdownFile entries
78
- * ready to be passed to `buildPackage`. Failed fetches are skipped silently.
92
+ * ready to be passed to `buildPackage`. Failed fetches are omitted and reported
93
+ * through the optional diagnostics collector.
79
94
  */
80
95
  export async function fetchLinkedDocs(content, baseUrl, options = {}) {
81
96
  const { concurrency = 5, timeoutMs = 30_000, maxLinks = 500, sameOriginOnly = true, fetchImpl = fetch, log, } = options;
@@ -109,7 +124,7 @@ export async function fetchLinkedDocs(content, baseUrl, options = {}) {
109
124
  const link = links[i];
110
125
  if (!link)
111
126
  return;
112
- const fetched = await fetchLink(link.url, fetchImpl, timeoutMs);
127
+ const fetched = await fetchLink(link.url, fetchImpl, timeoutMs, options.diagnostics);
113
128
  completed++;
114
129
  if (fetched) {
115
130
  results.push(fetched.file);
@@ -1 +1 @@
1
- {"version":3,"file":"llms-txt.js","sourceRoot":"","sources":["../src/llms-txt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAajE;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAe,EACf,OAAe;IAEf,MAAM,KAAK,GAAkB,EAAE,CAAC;IAChC,IAAI,cAAc,GAAkB,IAAI,CAAC;IAEzC,+EAA+E;IAC/E,MAAM,SAAS,GAAG,qDAAqD,CAAC;IAExE,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1C,2BAA2B;QAC3B,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACnD,IAAI,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACtB,cAAc,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACxC,SAAS;QACX,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAA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/**
2
+ * Fenced code blocks in Markdown, read from the lines of the text.
3
+ *
4
+ * The heading splitter, the paragraph splitter and the `hasCode` flag all use this, so
5
+ * they agree on where a block starts and ends. Two splitters with their own rules could
6
+ * disagree, and one would cut a block the other kept whole.
7
+ *
8
+ * Fences follow CommonMark: an opening fence is three or more backticks or tildes and may
9
+ * carry an info string (with no backtick, for a backtick fence), and only a bare run of
10
+ * the same character, at least as long, closes it. List items are not parsed, so two
11
+ * rules stand in for them: any indent opens a fence, and so does a list marker before it
12
+ * (`1. ```bash`), because fences in list items are indented; a closing fence has no list
13
+ * marker and sits at most 3 columns right of where its opening fence starts (tabs stop
14
+ * every 4 columns), so a fence shown inside a code example does not close the block
15
+ * around it.
16
+ *
17
+ * A fence that never closes is read as text, so a stray one does not swallow the rest of
18
+ * the document. CommonMark runs it to the end instead.
19
+ *
20
+ * This reads the text rather than remark's tree on purpose: without MDX support remark
21
+ * reads a fence under a JSX line such as `<Section>` as part of an HTML block, which
22
+ * would leave most code in MDX docs unprotected.
23
+ */
24
+ /**
25
+ * Whether `line` opens a fenced code block, closed or not (see `fencedBlocks` for
26
+ * `tildes`). A fence in a blockquote counts here (`> ```js`, which turndown writes for
27
+ * some Sphinx examples), though `fencedBlocks` does not pair quoted fences: a quote can
28
+ * end before its block closes, so a bare fence after it would close the wrong block.
29
+ */
30
+ export declare function opensFence(line: string, tildes?: boolean): boolean;
31
+ /**
32
+ * The fenced code blocks in `lines`, as `[first, last]` line indexes, in order.
33
+ *
34
+ * Pass `tildes: false` for AsciiDoc and reStructuredText, which underline headings with
35
+ * `~~~` and do not fence code with it.
36
+ */
37
+ export declare function fencedBlocks(lines: readonly string[], tildes?: boolean): [number, number][];
38
+ /** For each of `lines`, whether it is part of a fenced code block, fences included. */
39
+ export declare function fencedLines(lines: readonly string[]): boolean[];
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Fenced code blocks in Markdown, read from the lines of the text.
3
+ *
4
+ * The heading splitter, the paragraph splitter and the `hasCode` flag all use this, so
5
+ * they agree on where a block starts and ends. Two splitters with their own rules could
6
+ * disagree, and one would cut a block the other kept whole.
7
+ *
8
+ * Fences follow CommonMark: an opening fence is three or more backticks or tildes and may
9
+ * carry an info string (with no backtick, for a backtick fence), and only a bare run of
10
+ * the same character, at least as long, closes it. List items are not parsed, so two
11
+ * rules stand in for them: any indent opens a fence, and so does a list marker before it
12
+ * (`1. ```bash`), because fences in list items are indented; a closing fence has no list
13
+ * marker and sits at most 3 columns right of where its opening fence starts (tabs stop
14
+ * every 4 columns), so a fence shown inside a code example does not close the block
15
+ * around it.
16
+ *
17
+ * A fence that never closes is read as text, so a stray one does not swallow the rest of
18
+ * the document. CommonMark runs it to the end instead.
19
+ *
20
+ * This reads the text rather than remark's tree on purpose: without MDX support remark
21
+ * reads a fence under a JSX line such as `<Section>` as part of an HTML block, which
22
+ * would leave most code in MDX docs unprotected.
23
+ */
24
+ /** A fence line: indent, an optional list marker it opens behind, the run, the rest. */
25
+ const FENCE_LINE = /^([ \t]*)((?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})(.*)$/;
26
+ /** The column after `text` when it starts at column `from`, with tab stops every 4. */
27
+ function columnAfter(text, from = 0) {
28
+ let column = from;
29
+ for (const char of text)
30
+ column = char === "\t" ? column + 4 - (column % 4) : column + 1;
31
+ return column;
32
+ }
33
+ function parseFence(line, tildes) {
34
+ const [, indent = "", item = "", run, info = ""] = FENCE_LINE.exec(line) ?? [];
35
+ if (!run || (!tildes && run[0] === "~"))
36
+ return null;
37
+ return {
38
+ char: run[0],
39
+ length: run.length,
40
+ column: columnAfter(item, columnAfter(indent)),
41
+ item: item !== "",
42
+ info,
43
+ };
44
+ }
45
+ function canOpen(fence) {
46
+ // A backtick fence's info string can't hold a backtick: ```npm i``` is inline code.
47
+ return fence !== null && (fence.char !== "`" || !fence.info.includes("`"));
48
+ }
49
+ /** Blockquote markers in front of a line. */
50
+ const QUOTE_MARKERS = /^[ \t]*(?:>[ \t]?)+/;
51
+ /**
52
+ * Whether `line` opens a fenced code block, closed or not (see `fencedBlocks` for
53
+ * `tildes`). A fence in a blockquote counts here (`> ```js`, which turndown writes for
54
+ * some Sphinx examples), though `fencedBlocks` does not pair quoted fences: a quote can
55
+ * end before its block closes, so a bare fence after it would close the wrong block.
56
+ */
57
+ export function opensFence(line, tildes = true) {
58
+ return canOpen(parseFence(line.replace(QUOTE_MARKERS, ""), tildes));
59
+ }
60
+ function canClose(fence) {
61
+ return !fence.item && !fence.info.trim();
62
+ }
63
+ function closes(fence, open) {
64
+ return (fence !== null &&
65
+ canClose(fence) &&
66
+ fence.char === open.char &&
67
+ fence.length >= open.length &&
68
+ fence.column <= open.column + 3);
69
+ }
70
+ /**
71
+ * The fenced code blocks in `lines`, as `[first, last]` line indexes, in order.
72
+ *
73
+ * Pass `tildes: false` for AsciiDoc and reStructuredText, which underline headings with
74
+ * `~~~` and do not fence code with it.
75
+ */
76
+ export function fencedBlocks(lines, tildes = true) {
77
+ const fences = lines.map((line) => parseFence(line, tildes));
78
+ // The longest bare run of each character after each line. A fence with no run as
79
+ // long after it can never close, so it is text without scanning ahead; the scan is
80
+ // left for a fence whose only closers are indented too far.
81
+ const longest = [];
82
+ let after = { "`": 0, "~": 0 };
83
+ for (let i = lines.length - 1; i >= 0; i--) {
84
+ longest[i] = after;
85
+ const fence = fences[i];
86
+ if (fence && canClose(fence) && fence.length > after[fence.char]) {
87
+ after = { ...after, [fence.char]: fence.length };
88
+ }
89
+ }
90
+ const blocks = [];
91
+ const failed = [];
92
+ for (let i = 0; i < lines.length; i++) {
93
+ const open = fences[i] ?? null;
94
+ if (!canOpen(open) ||
95
+ (longest[i]?.[open.char] ?? 0) < open.length ||
96
+ // Its closers are among those of a fence that already failed to close.
97
+ failed.some((f) => f.char === open.char &&
98
+ f.length <= open.length &&
99
+ f.column >= open.column)) {
100
+ continue;
101
+ }
102
+ let last = i + 1;
103
+ while (last < lines.length && !closes(fences[last] ?? null, open))
104
+ last++;
105
+ if (last === lines.length) {
106
+ failed.push(open);
107
+ continue;
108
+ }
109
+ blocks.push([i, last]);
110
+ i = last;
111
+ }
112
+ return blocks;
113
+ }
114
+ /** For each of `lines`, whether it is part of a fenced code block, fences included. */
115
+ export function fencedLines(lines) {
116
+ const inside = lines.map(() => false);
117
+ for (const [first, last] of fencedBlocks(lines)) {
118
+ inside.fill(true, first, last + 1);
119
+ }
120
+ return inside;
121
+ }
122
+ //# sourceMappingURL=markdown-fences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown-fences.js","sourceRoot":"","sources":["../src/markdown-fences.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,wFAAwF;AACxF,MAAM,UAAU,GAAG,2DAA2D,CAAC;AAc/E,uFAAuF;AACvF,SAAS,WAAW,CAAC,IAAY,EAAE,IAAI,GAAG,CAAC;IACzC,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,KAAK,MAAM,IAAI,IAAI,IAAI;QACrB,MAAM,GAAG,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,UAAU,CAAC,IAAY,EAAE,MAAe;IAC/C,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE,IAAI,GAAG,EAAE,CAAC,GAC9C,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,OAAO;QACL,IAAI,EAAE,GAAG,CAAC,CAAC,CAAc;QACzB,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,MAAM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I,CAAC,MAAM,CAC1B,EACD,CAAC;YACD,SAAS;QACX,CAAC;QAED,IAAI,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACjB,OAAO,IAAI,GAAG,KAAK,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,IAAI,CAAC;YAAE,IAAI,EAAE,CAAC;QAC1E,IAAI,IAAI,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC;YAC1B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClB,SAAS;QACX,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;QACvB,CAAC,GAAG,IAAI,CAAC;IACX,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,WAAW,CAAC,KAAwB;IAClD,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;IACtC,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QAChD,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Package builder for creating documentation packages from markdown files.
3
3
  */
4
+ import { type IngestionDiagnostic, type IngestionReport } from "./ingestion.js";
4
5
  export interface PackageBuildOptions {
5
6
  name: string;
6
7
  version: string;
@@ -12,6 +13,10 @@ export interface PackageBuildOptions {
12
13
  buildFingerprint?: string;
13
14
  /** Automatically generated revision of the ingestion implementation. */
14
15
  ingestionRevision?: string;
16
+ /** Outcomes collected while selecting and reading source documents. */
17
+ diagnostics?: readonly IngestionDiagnostic[];
18
+ /** Reject read/parse failures and empty documents before changing outputPath. */
19
+ strict?: boolean;
15
20
  }
16
21
  export interface MarkdownFile {
17
22
  path: string;
@@ -23,14 +28,14 @@ export interface BuildResult {
23
28
  totalTokens: number;
24
29
  /** Files dropped whole because splitting or parsing them threw. */
25
30
  skippedFiles: number;
31
+ /** Optional for compatibility with existing result objects and mocks. */
32
+ diagnostics?: IngestionReport;
26
33
  }
27
34
  /**
28
35
  * Split markdown into one chunk per `##` section.
29
36
  *
30
- * Fenced code blocks are tracked so that `## ` lines inside them — common in docs that
31
- * demonstrate markdown — aren't mistaken for headings and split mid-fence. Fence
32
- * handling follows CommonMark: an opening fence may carry an info string, a closing
33
- * fence may not, and only the same character in at least the same run length closes.
37
+ * Fenced code blocks (`fencedLines`) are skipped so that `## ` lines inside them, common
38
+ * in docs that demonstrate markdown, aren't mistaken for headings and split mid-fence.
34
39
  */
35
40
  export declare function splitMarkdownByHeadings(file: MarkdownFile): MarkdownFile[];
36
41
  /**
@@ -6,6 +6,8 @@ import { dirname } from "node:path";
6
6
  import { fileTitle, parseDocument } from "./build.js";
7
7
  import { openDatabase } from "./database.js";
8
8
  import { REMOVED_TAGS } from "./html.js";
9
+ import { createIngestionReport, ingestionErrorReason, validateIngestion, } from "./ingestion.js";
10
+ import { fencedLines } from "./markdown-fences.js";
9
11
  import { createPackageTempFile } from "./package-file.js";
10
12
  /**
11
13
  * Generate a content hash for section deduplication.
@@ -34,33 +36,21 @@ const MAX_CARRIED_HEADING = 1024;
34
36
  /**
35
37
  * Split markdown into one chunk per `##` section.
36
38
  *
37
- * Fenced code blocks are tracked so that `## ` lines inside them — common in docs that
38
- * demonstrate markdown — aren't mistaken for headings and split mid-fence. Fence
39
- * handling follows CommonMark: an opening fence may carry an info string, a closing
40
- * fence may not, and only the same character in at least the same run length closes.
39
+ * Fenced code blocks (`fencedLines`) are skipped so that `## ` lines inside them, common
40
+ * in docs that demonstrate markdown, aren't mistaken for headings and split mid-fence.
41
41
  */
42
42
  export function splitMarkdownByHeadings(file) {
43
+ const lines = file.content.split("\n");
44
+ const inCode = fencedLines(lines);
43
45
  const parts = [];
44
46
  let current = [];
45
- let openFence = null;
46
- for (const line of file.content.split("\n")) {
47
- const [, marker, info] = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line) ?? [];
48
- if (marker) {
49
- if (openFence === null) {
50
- // Backtick fences can't have a backtick in the info string; that isn't a fence.
51
- if (marker[0] !== "`" || !info?.includes("`"))
52
- openFence = marker;
53
- }
54
- else if (marker.startsWith(openFence) && !info?.trim()) {
55
- openFence = null;
56
- }
57
- }
58
- else if (openFence === null && H2_LINE.test(line) && current.length) {
47
+ lines.forEach((line, i) => {
48
+ if (!inCode[i] && H2_LINE.test(line) && current.length) {
59
49
  parts.push(current.join("\n"));
60
50
  current = [];
61
51
  }
62
52
  current.push(line);
63
- }
53
+ });
64
54
  if (current.length)
65
55
  parts.push(current.join("\n"));
66
56
  if (parts.length <= 1)
@@ -474,10 +464,12 @@ function parseChunks(file) {
474
464
  * Build a documentation package from markdown files.
475
465
  */
476
466
  export function buildPackage(outputPath, files, options) {
467
+ const parsed = parsePackageFiles(files, options.diagnostics);
468
+ if (options.strict)
469
+ validateIngestion(parsed.diagnostics);
477
470
  const temp = createPackageTempFile(dirname(outputPath));
478
471
  try {
479
- const result = writePackage(temp.path, files, options);
480
- // writePackage closes the database before validation and replacement.
472
+ const result = writePackage(temp.path, parsed, options);
481
473
  temp.install(outputPath);
482
474
  return { ...result, path: outputPath };
483
475
  }
@@ -485,7 +477,66 @@ export function buildPackage(outputPath, files, options) {
485
477
  temp.cleanup();
486
478
  }
487
479
  }
488
- function writePackage(outputPath, files, options) {
480
+ /** Parse and report before opening a database or staging a replacement. */
481
+ function parsePackageFiles(files, sourceDiagnostics = []) {
482
+ const allSections = [];
483
+ const seenHashes = new Map();
484
+ const entries = [...sourceDiagnostics];
485
+ let skippedFiles = 0;
486
+ // Parse before opening the output so strict validation never replaces an
487
+ // installed package with an incomplete build. Keep only one file's split
488
+ // chunks alive at a time, as before.
489
+ for (const file of files) {
490
+ try {
491
+ const sections = parseChunks(file);
492
+ let indexed = 0;
493
+ let duplicateOf;
494
+ for (const section of sections) {
495
+ const hash = contentHash(section.content);
496
+ if (seenHashes.has(hash)) {
497
+ duplicateOf ??= seenHashes.get(hash);
498
+ }
499
+ else {
500
+ seenHashes.set(hash, file.path);
501
+ allSections.push(section);
502
+ indexed++;
503
+ }
504
+ }
505
+ entries.push({
506
+ path: file.path,
507
+ kind: "file",
508
+ outcome: !sections.length ? "empty" : indexed ? "indexed" : "duplicate",
509
+ ...(!sections.length
510
+ ? { reason: "Document produced no sections" }
511
+ : indexed
512
+ ? {
513
+ sections: indexed,
514
+ duplicateSections: sections.length - indexed,
515
+ }
516
+ : {
517
+ reason: "All sections duplicate earlier content",
518
+ duplicateOf,
519
+ }),
520
+ });
521
+ }
522
+ catch (error) {
523
+ skippedFiles++;
524
+ entries.push({
525
+ path: file.path,
526
+ kind: "file",
527
+ outcome: "parse-error",
528
+ reason: ingestionErrorReason(error),
529
+ });
530
+ }
531
+ }
532
+ return {
533
+ sections: allSections,
534
+ skippedFiles,
535
+ diagnostics: createIngestionReport(entries),
536
+ };
537
+ }
538
+ function writePackage(outputPath, parsed, options) {
539
+ const { sections: allSections, skippedFiles, diagnostics } = parsed;
489
540
  const db = openDatabase(outputPath);
490
541
  try {
491
542
  // Create schema
@@ -530,32 +581,6 @@ function writePackage(outputPath, files, options) {
530
581
  INSERT INTO chunks (doc_path, doc_title, section_title, content, tokens, has_code)
531
582
  VALUES (?, ?, ?, ?, ?, ?)
532
583
  `);
533
- const allSections = [];
534
- const seenHashes = new Set();
535
- let skippedFiles = 0;
536
- for (const file of files) {
537
- try {
538
- // Splitting is inside the guard on purpose: it walks untrusted markup, so a
539
- // throw there has to cost one file rather than the whole registry build. Doing
540
- // it per file also keeps only one file's chunks alive at a time.
541
- const sections = parseChunks(file);
542
- for (const section of sections) {
543
- // Deduplicate sections with identical content (ignore titles)
544
- const hash = contentHash(section.content);
545
- if (!seenHashes.has(hash)) {
546
- seenHashes.add(hash);
547
- allSections.push(section);
548
- }
549
- }
550
- }
551
- catch {
552
- // A file that cannot be split or parsed is dropped whole, so a half-indexed
553
- // document never reaches the package. The failure is counted rather than
554
- // logged: `buildPackage` has no logger, and a silent skip is how a registry
555
- // build loses documents without anyone noticing.
556
- skippedFiles++;
557
- }
558
- }
559
584
  // Insert all sections in a transaction
560
585
  const insertAll = db.transaction((sections) => {
561
586
  for (const section of sections) {
@@ -571,6 +596,7 @@ function writePackage(outputPath, files, options) {
571
596
  sectionCount: allSections.length,
572
597
  totalTokens,
573
598
  skippedFiles,
599
+ diagnostics,
574
600
  };
575
601
  }
576
602
  finally {