@doikayt/tooling-core 1.4.15

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 (61) hide show
  1. package/README.md +380 -0
  2. package/dist/cli/generateHelp.d.ts +2 -0
  3. package/dist/cli/generateHelp.js +53 -0
  4. package/dist/cli/listFilesToProcess.d.ts +9 -0
  5. package/dist/cli/listFilesToProcess.js +47 -0
  6. package/dist/cli/parseStandardCli.d.ts +10 -0
  7. package/dist/cli/parseStandardCli.js +197 -0
  8. package/dist/cli/printHelp.d.ts +2 -0
  9. package/dist/cli/printHelp.js +4 -0
  10. package/dist/cli/runCli.d.ts +9 -0
  11. package/dist/cli/runCli.js +93 -0
  12. package/dist/cli/runLinkValidation.d.ts +2 -0
  13. package/dist/cli/runLinkValidation.js +32 -0
  14. package/dist/cli/runPlugin.d.ts +3 -0
  15. package/dist/cli/runPlugin.js +13 -0
  16. package/dist/cli/types.d.ts +23 -0
  17. package/dist/cli/types.js +1 -0
  18. package/dist/index.d.ts +29 -0
  19. package/dist/index.js +22 -0
  20. package/dist/markdown/extractLinks.d.ts +9 -0
  21. package/dist/markdown/extractLinks.js +71 -0
  22. package/dist/markdown/findMarker.d.ts +31 -0
  23. package/dist/markdown/findMarker.js +72 -0
  24. package/dist/markdown/injectBetweenMarkers.d.ts +1 -0
  25. package/dist/markdown/injectBetweenMarkers.js +10 -0
  26. package/dist/markdown/parseHeadings.d.ts +2 -0
  27. package/dist/markdown/parseHeadings.js +31 -0
  28. package/dist/markdown/slugHeading.d.ts +8 -0
  29. package/dist/markdown/slugHeading.js +9 -0
  30. package/dist/markdown/types.d.ts +51 -0
  31. package/dist/markdown/types.js +1 -0
  32. package/dist/markdown/validateExternalLink.d.ts +2 -0
  33. package/dist/markdown/validateExternalLink.js +82 -0
  34. package/dist/markdown/validateFragmentLink.d.ts +8 -0
  35. package/dist/markdown/validateFragmentLink.js +19 -0
  36. package/dist/markdown/validateMarkdownLinks.d.ts +2 -0
  37. package/dist/markdown/validateMarkdownLinks.js +84 -0
  38. package/dist/markdown/validateRelativeLink.d.ts +12 -0
  39. package/dist/markdown/validateRelativeLink.js +62 -0
  40. package/dist/policy/RunnerPolicy.d.ts +7 -0
  41. package/dist/policy/RunnerPolicy.js +1 -0
  42. package/dist/policy/createRunnerPolicy.d.ts +3 -0
  43. package/dist/policy/createRunnerPolicy.js +36 -0
  44. package/dist/repository/RepositoryRunner.d.ts +24 -0
  45. package/dist/repository/RepositoryRunner.js +93 -0
  46. package/dist/repository/createTransformProcessor.d.ts +5 -0
  47. package/dist/repository/createTransformProcessor.js +17 -0
  48. package/dist/repository/types.d.ts +16 -0
  49. package/dist/repository/types.js +1 -0
  50. package/dist/tsconfig.tsbuildinfo +1 -0
  51. package/dist/util/concurrency.d.ts +6 -0
  52. package/dist/util/concurrency.js +18 -0
  53. package/dist/util/debugLog.d.ts +7 -0
  54. package/dist/util/debugLog.js +9 -0
  55. package/dist/util/extractFirstSentence.d.ts +12 -0
  56. package/dist/util/extractFirstSentence.js +25 -0
  57. package/dist/util/toErrorMessage.d.ts +1 -0
  58. package/dist/util/toErrorMessage.js +3 -0
  59. package/dist/util/walkFiles.d.ts +18 -0
  60. package/dist/util/walkFiles.js +49 -0
  61. package/package.json +47 -0
@@ -0,0 +1,2 @@
1
+ import type { PluginDescriptor } from "./types.js";
2
+ export declare function printHelp(descriptor: PluginDescriptor): void;
@@ -0,0 +1,4 @@
1
+ import { generateHelp } from "./generateHelp.js";
2
+ export function printHelp(descriptor) {
3
+ console.log(generateHelp(descriptor));
4
+ }
@@ -0,0 +1,9 @@
1
+ import type { PluginDescriptor } from "./types.js";
2
+ import type { FileProcessor, RunConfig } from "../repository/types.js";
3
+ import type { RepositoryStats } from "../repository/RepositoryRunner.js";
4
+ export interface RunCliOptions<TConfig extends RunConfig = RunConfig> {
5
+ descriptor: PluginDescriptor<TConfig>;
6
+ processor: FileProcessor<TConfig>;
7
+ argv?: string[];
8
+ }
9
+ export declare function runCli<TConfig extends RunConfig = RunConfig>(options: RunCliOptions<TConfig>): Promise<RepositoryStats>;
@@ -0,0 +1,93 @@
1
+ import { parseStandardCli, buildPassthroughMap, buildConfig, } from "./parseStandardCli.js";
2
+ import { listFilesToProcess } from "./listFilesToProcess.js";
3
+ import { printHelp } from "./printHelp.js";
4
+ import { runPlugin } from "./runPlugin.js";
5
+ import { debugLog } from "../util/debugLog.js";
6
+ import { toErrorMessage } from "../util/toErrorMessage.js";
7
+ import { readFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { dirname, join } from "node:path";
10
+ function attempt(fn) {
11
+ try {
12
+ return fn();
13
+ }
14
+ catch (err) {
15
+ const message = toErrorMessage(err);
16
+ console.error(`ERROR: ${message}`);
17
+ process.exit(1);
18
+ }
19
+ }
20
+ const STANDARD_FLAGS = new Set([
21
+ "-h",
22
+ "--help",
23
+ "--version",
24
+ "-v",
25
+ "--verbose",
26
+ "-q",
27
+ "--quiet",
28
+ "-d",
29
+ "--debug",
30
+ "-c",
31
+ "--check",
32
+ "-r",
33
+ "--recursive",
34
+ "-e",
35
+ "--exclude",
36
+ "-n",
37
+ "--no-external-link-check",
38
+ "-l",
39
+ "--link-timeout-ms",
40
+ ]);
41
+ function validateDescriptorOptions(descriptor) {
42
+ for (const option of descriptor.options) {
43
+ if (STANDARD_FLAGS.has(option.flag)) {
44
+ throw new Error(`Plugin option "${option.flag}" collides with a standard tooling-core flag`);
45
+ }
46
+ }
47
+ }
48
+ export async function runCli(options) {
49
+ attempt(() => validateDescriptorOptions(options.descriptor));
50
+ const argv = options.argv ?? process.argv.slice(2);
51
+ // Pass plugin-specific options into parseStandardCli so it knows which
52
+ // unknown flags require values — avoids peek heuristics in the parser.
53
+ const parsed = attempt(() => parseStandardCli(argv, options.descriptor.options));
54
+ const positionals = parsed.positionals ?? [];
55
+ const passthroughMap = attempt(() => buildPassthroughMap(options.descriptor.options, parsed.passthrough ?? []));
56
+ if (parsed.help) {
57
+ printHelp(options.descriptor);
58
+ process.exit(0); // Sets process exit code for when we terminate, but does not itself cause termination
59
+ return Promise.resolve({
60
+ updated: 0,
61
+ unchanged: 0,
62
+ needsUpdate: 0,
63
+ skipped: 0,
64
+ });
65
+ }
66
+ if (parsed.version) {
67
+ // All packages in this workspace are co-versioned via Changesets, so
68
+ // tooling-core's package.json version is authoritative for every plugin.
69
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "../../package.json");
70
+ const { version } = JSON.parse(readFileSync(pkgPath, "utf-8"));
71
+ console.log(`${options.descriptor.name} ${version}`);
72
+ process.exit(0);
73
+ return Promise.resolve({
74
+ updated: 0,
75
+ unchanged: 0,
76
+ needsUpdate: 0,
77
+ skipped: 0,
78
+ });
79
+ }
80
+ const config = attempt(() => buildConfig(parsed.config, passthroughMap, options.descriptor.parseOptions));
81
+ // If RunConfig ever holds credentials (tokens, auth headers, etc.), redact them here
82
+ // before logging — JSON.stringify(config) would expose them to stderr in --debug mode.
83
+ debugLog(config, `runCli: argv=${JSON.stringify(argv)} | config=${JSON.stringify(config)}`);
84
+ attempt(() => options.descriptor.validate?.(config));
85
+ const targets = attempt(() => listFilesToProcess(config, positionals));
86
+ debugLog(config, `runCli: targets=${JSON.stringify(targets.files)}`);
87
+ const stats = runPlugin(targets.files, options.processor, config);
88
+ debugLog(config, `runCli: stats=${JSON.stringify(stats)}`);
89
+ if (options.descriptor.afterRun !== undefined) {
90
+ await options.descriptor.afterRun(targets.files, config);
91
+ }
92
+ return stats;
93
+ }
@@ -0,0 +1,2 @@
1
+ import type { RunConfig } from "../repository/types.js";
2
+ export declare function runLinkValidation(files: string[], config: RunConfig): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { validateMarkdownLinks } from "../markdown/validateMarkdownLinks.js";
2
+ import { debugLog } from "../util/debugLog.js";
3
+ export async function runLinkValidation(files, config) {
4
+ debugLog(config, `runLinkValidation: starting, fileCount=${files.length}, validateExternal=${config.validateExternalLinks}`);
5
+ const onDebug = config.debug
6
+ ? (msg) => process.stderr.write(`[debug] ${msg}\n`)
7
+ : undefined;
8
+ const results = await Promise.all(files.map((file) => validateMarkdownLinks(file, {
9
+ validateExternal: config.validateExternalLinks,
10
+ timeoutMs: config.linkTimeoutMs,
11
+ verbose: config.verbose,
12
+ onVerbose: config.verbose ? (msg) => console.log(msg) : undefined,
13
+ onDebug: onDebug,
14
+ })));
15
+ let hasErrors = false;
16
+ for (const result of results) {
17
+ debugLog(config, `runLinkValidation: result=${JSON.stringify(result)}`);
18
+ for (const error of result.errors) {
19
+ console.log(`✗ Broken link in ${error.file}:${error.line} → ${error.link} (${error.reason})`);
20
+ hasErrors = true;
21
+ }
22
+ if (!config.quiet) {
23
+ for (const warning of result.warnings) {
24
+ console.log(`⚠ Link warning in ${warning.file}:${warning.line} → ${warning.link} (${warning.reason})`);
25
+ }
26
+ }
27
+ }
28
+ if (hasErrors) {
29
+ process.exitCode = 1;
30
+ }
31
+ debugLog(config, `runLinkValidation: complete hasErrors=${hasErrors}`);
32
+ }
@@ -0,0 +1,3 @@
1
+ import type { RunConfig, FileProcessor } from "../repository/types.js";
2
+ import type { RepositoryStats } from "../repository/RepositoryRunner.js";
3
+ export declare function runPlugin<TConfig extends RunConfig>(files: string[], processor: FileProcessor<TConfig>, config: TConfig): RepositoryStats;
@@ -0,0 +1,13 @@
1
+ import { RepositoryRunner } from "../repository/RepositoryRunner.js";
2
+ import { createRunnerPolicy } from "../policy/createRunnerPolicy.js";
3
+ import { debugLog } from "../util/debugLog.js";
4
+ export function runPlugin(files, processor, config) {
5
+ debugLog(config, `runPlugin: fileCount=${files.length}`);
6
+ const policy = createRunnerPolicy(config);
7
+ const runner = new RepositoryRunner({
8
+ processor: processor,
9
+ config: config,
10
+ policy: policy,
11
+ });
12
+ return runner.run(files);
13
+ }
@@ -0,0 +1,23 @@
1
+ import type { RunConfig } from "../repository/types.js";
2
+ export type RunMode = "update" | "check";
3
+ export interface PluginOption {
4
+ flag: string;
5
+ description: string;
6
+ requiresValue?: boolean;
7
+ valueName?: string;
8
+ }
9
+ export interface PluginDescriptor<TConfig extends RunConfig = RunConfig> {
10
+ name: string;
11
+ description: string;
12
+ options: PluginOption[];
13
+ parseOptions?(this: void, standard: RunConfig, passthrough: Map<string, string | boolean>): TConfig;
14
+ validate?(this: void, config: TConfig): void;
15
+ afterRun?(this: void, files: string[], config: TConfig): Promise<void>;
16
+ }
17
+ export interface ParsedCliResult<TConfig extends RunConfig = RunConfig> {
18
+ config: TConfig;
19
+ positionals: string[];
20
+ passthrough: string[];
21
+ help: boolean;
22
+ version: boolean;
23
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ export { runPlugin } from "./cli/runPlugin.js";
2
+ export { parseStandardCli, buildPassthroughMap, buildConfig, parseStringOption, parseBooleanOption, parseNumberOption, } from "./cli/parseStandardCli.js";
3
+ export { listFilesToProcess } from "./cli/listFilesToProcess.js";
4
+ export type { ProcessingStatus, FileProcessor, RunConfig, } from "./repository/types.js";
5
+ export type { ParsedCliResult, PluginDescriptor, PluginOption, RunMode, } from "./cli/types.js";
6
+ export { injectBetweenMarkers } from "./markdown/injectBetweenMarkers.js";
7
+ export { findMarker, findMarkers } from "./markdown/findMarker.js";
8
+ export type { MarkerLocation } from "./markdown/findMarker.js";
9
+ export { createTransformProcessor } from "./repository/createTransformProcessor.js";
10
+ export type { RunnerPolicy, RunnerDecision } from "./policy/RunnerPolicy.js";
11
+ export { createRunnerPolicy } from "./policy/createRunnerPolicy.js";
12
+ export { generateHelp } from "./cli/generateHelp.js";
13
+ export { printHelp } from "./cli/printHelp.js";
14
+ export { runCli } from "./cli/runCli.js";
15
+ export type { RunCliOptions } from "./cli/runCli.js";
16
+ export { extractLinks } from "./markdown/extractLinks.js";
17
+ export { parseHeadings } from "./markdown/parseHeadings.js";
18
+ export type { LinkKind, LinkRecord, HeadingRecord, LinkValidationError, LinkValidationWarning, LinkValidationResult, LinkValidationOptions, ExternalLinkStatus, } from "./markdown/types.js";
19
+ export { slugHeading } from "./markdown/slugHeading.js";
20
+ export { validateFragmentLink } from "./markdown/validateFragmentLink.js";
21
+ export { validateRelativeLink } from "./markdown/validateRelativeLink.js";
22
+ export { validateExternalLink } from "./markdown/validateExternalLink.js";
23
+ export { validateMarkdownLinks } from "./markdown/validateMarkdownLinks.js";
24
+ export { debugLog } from "./util/debugLog.js";
25
+ export { toErrorMessage } from "./util/toErrorMessage.js";
26
+ export { extractFirstSentence } from "./util/extractFirstSentence.js";
27
+ export { runLinkValidation } from "./cli/runLinkValidation.js";
28
+ export type { RepositoryStats } from "./repository/RepositoryRunner.js";
29
+ export { runWithConcurrency } from "./util/concurrency.js";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ export { runPlugin } from "./cli/runPlugin.js";
2
+ export { parseStandardCli, buildPassthroughMap, buildConfig, parseStringOption, parseBooleanOption, parseNumberOption, } from "./cli/parseStandardCli.js";
3
+ export { listFilesToProcess } from "./cli/listFilesToProcess.js";
4
+ export { injectBetweenMarkers } from "./markdown/injectBetweenMarkers.js";
5
+ export { findMarker, findMarkers } from "./markdown/findMarker.js";
6
+ export { createTransformProcessor } from "./repository/createTransformProcessor.js";
7
+ export { createRunnerPolicy } from "./policy/createRunnerPolicy.js";
8
+ export { generateHelp } from "./cli/generateHelp.js";
9
+ export { printHelp } from "./cli/printHelp.js";
10
+ export { runCli } from "./cli/runCli.js";
11
+ export { extractLinks } from "./markdown/extractLinks.js";
12
+ export { parseHeadings } from "./markdown/parseHeadings.js";
13
+ export { slugHeading } from "./markdown/slugHeading.js";
14
+ export { validateFragmentLink } from "./markdown/validateFragmentLink.js";
15
+ export { validateRelativeLink } from "./markdown/validateRelativeLink.js";
16
+ export { validateExternalLink } from "./markdown/validateExternalLink.js";
17
+ export { validateMarkdownLinks } from "./markdown/validateMarkdownLinks.js";
18
+ export { debugLog } from "./util/debugLog.js";
19
+ export { toErrorMessage } from "./util/toErrorMessage.js";
20
+ export { extractFirstSentence } from "./util/extractFirstSentence.js";
21
+ export { runLinkValidation } from "./cli/runLinkValidation.js";
22
+ export { runWithConcurrency } from "./util/concurrency.js";
@@ -0,0 +1,9 @@
1
+ import type { LinkRecord } from "./types.js";
2
+ export declare function extractLinks(markdownText: string, options?: {
3
+ managedBlockStartMarker?: string;
4
+ managedBlockEndMarker?: string;
5
+ onDebug?: (message: string) => void;
6
+ }): {
7
+ links: LinkRecord[];
8
+ skippedCount: number;
9
+ };
@@ -0,0 +1,71 @@
1
+ import { unified } from "unified";
2
+ import remarkParse from "remark-parse";
3
+ import { visit } from "unist-util-visit";
4
+ const IGNORED_SCHEMES = ["mailto:", "tel:", "data:", "javascript:"];
5
+ function classifyHref(href) {
6
+ for (const scheme of IGNORED_SCHEMES) {
7
+ if (href.startsWith(scheme)) {
8
+ return null;
9
+ }
10
+ }
11
+ if (href.startsWith("http://") || href.startsWith("https://")) {
12
+ return "external";
13
+ }
14
+ if (href.startsWith("#")) {
15
+ return "fragment";
16
+ }
17
+ return "relative";
18
+ }
19
+ function findManagedBlockRanges(markdownText, startMarker, endMarker) {
20
+ const lines = markdownText.split("\n");
21
+ const ranges = [];
22
+ let blockStart = null;
23
+ for (let i = 0; i < lines.length; i++) {
24
+ const line = lines[i];
25
+ if (line.includes(startMarker) && blockStart === null) {
26
+ blockStart = i + 1;
27
+ }
28
+ else if (line.includes(endMarker) && blockStart !== null) {
29
+ ranges.push({ start: blockStart, end: i + 1 });
30
+ blockStart = null;
31
+ }
32
+ }
33
+ return ranges;
34
+ }
35
+ function isInManagedBlock(line, ranges) {
36
+ return ranges.some((range) => line >= range.start && line <= range.end);
37
+ }
38
+ export function extractLinks(markdownText, options) {
39
+ const startMarker = options?.managedBlockStartMarker ?? "<!-- TOC:START -->";
40
+ const endMarker = options?.managedBlockEndMarker ?? "<!-- TOC:END -->";
41
+ const onDebug = options?.onDebug;
42
+ const managedRanges = findManagedBlockRanges(markdownText, startMarker, endMarker);
43
+ const tree = unified().use(remarkParse).parse(markdownText);
44
+ const links = [];
45
+ let skippedCount = 0;
46
+ function processNode(href, line) {
47
+ if (isInManagedBlock(line, managedRanges)) {
48
+ onDebug?.(`extractLinks: SKIPPED (managed block) href=${href} line=${line}`);
49
+ skippedCount++;
50
+ return;
51
+ }
52
+ const kind = classifyHref(href);
53
+ if (kind === null) {
54
+ onDebug?.(`extractLinks: SKIPPED (ignored scheme) href=${href} line=${line}`);
55
+ skippedCount++;
56
+ return;
57
+ }
58
+ onDebug?.(`extractLinks: ADDED kind=${kind} href=${href} line=${line}`);
59
+ links.push({ href: href, line: line, kind: kind });
60
+ }
61
+ visit(tree, "link", (node) => {
62
+ processNode(node.url, node.position?.start.line ?? 0);
63
+ });
64
+ visit(tree, "image", (node) => {
65
+ processNode(node.url, node.position?.start.line ?? 0);
66
+ });
67
+ visit(tree, "definition", (node) => {
68
+ processNode(node.url, node.position?.start.line ?? 0);
69
+ });
70
+ return { links: links, skippedCount: skippedCount };
71
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Describes the location of a marker pair within a content string.
3
+ * startIndex: index of the first character after the start tag.
4
+ * endIndex: index of the first character of the end tag.
5
+ * So content.slice(startIndex, endIndex) yields the current content
6
+ * between the markers.
7
+ */
8
+ export interface MarkerLocation {
9
+ startMarker: string;
10
+ endMarker: string;
11
+ startLine: number;
12
+ endLine: number;
13
+ startIndex: number;
14
+ endIndex: number;
15
+ }
16
+ /**
17
+ * Locates a single marker pair within a content string.
18
+ * Returns null if either marker is not found or if end precedes start.
19
+ */
20
+ export declare function findMarker(content: string, startMarker: string, endMarker: string): MarkerLocation | null;
21
+ /**
22
+ * Locates multiple named marker pairs in a single pass over the content.
23
+ * Returns a Map keyed by startMarker string.
24
+ * Marker pairs not found in the content are absent from the result map.
25
+ * Throws if any start or end marker appears more than once — duplicate
26
+ * markers indicate a malformed document and are always a fatal error.
27
+ */
28
+ export declare function findMarkers(content: string, pairs: Array<{
29
+ startMarker: string;
30
+ endMarker: string;
31
+ }>): Map<string, MarkerLocation>;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Locates a single marker pair within a content string.
3
+ * Returns null if either marker is not found or if end precedes start.
4
+ */
5
+ export function findMarker(content, startMarker, endMarker) {
6
+ const startTagIndex = content.indexOf(startMarker);
7
+ if (startTagIndex === -1)
8
+ return null;
9
+ const endTagIndex = content.indexOf(endMarker);
10
+ if (endTagIndex === -1)
11
+ return null;
12
+ const startIndex = startTagIndex + startMarker.length;
13
+ const endIndex = endTagIndex;
14
+ if (endIndex <= startTagIndex)
15
+ return null;
16
+ const startLine = lineNumberAt(content, startTagIndex);
17
+ const endLine = lineNumberAt(content, endTagIndex);
18
+ return {
19
+ startMarker: startMarker,
20
+ endMarker: endMarker,
21
+ startLine: startLine,
22
+ endLine: endLine,
23
+ startIndex: startIndex,
24
+ endIndex: endIndex,
25
+ };
26
+ }
27
+ /**
28
+ * Locates multiple named marker pairs in a single pass over the content.
29
+ * Returns a Map keyed by startMarker string.
30
+ * Marker pairs not found in the content are absent from the result map.
31
+ * Throws if any start or end marker appears more than once — duplicate
32
+ * markers indicate a malformed document and are always a fatal error.
33
+ */
34
+ export function findMarkers(content, pairs) {
35
+ // Check for duplicate markers before locating any
36
+ for (const { startMarker, endMarker } of pairs) {
37
+ if (countOccurrences(content, startMarker) > 1) {
38
+ throw new Error(`Duplicate marker found: "${startMarker}" appears more than once`);
39
+ }
40
+ if (countOccurrences(content, endMarker) > 1) {
41
+ throw new Error(`Duplicate marker found: "${endMarker}" appears more than once`);
42
+ }
43
+ }
44
+ const result = new Map();
45
+ for (const { startMarker, endMarker } of pairs) {
46
+ const location = findMarker(content, startMarker, endMarker);
47
+ if (location !== null) {
48
+ result.set(startMarker, location);
49
+ }
50
+ }
51
+ return result;
52
+ }
53
+ function lineNumberAt(content, index) {
54
+ let line = 1;
55
+ for (let i = 0; i < index; i++) {
56
+ if (content[i] === "\n")
57
+ line++;
58
+ }
59
+ return line;
60
+ }
61
+ function countOccurrences(content, marker) {
62
+ let count = 0;
63
+ let pos = 0;
64
+ while (true) {
65
+ const found = content.indexOf(marker, pos);
66
+ if (found === -1)
67
+ break;
68
+ count++;
69
+ pos = found + marker.length;
70
+ }
71
+ return count;
72
+ }
@@ -0,0 +1 @@
1
+ export declare function injectBetweenMarkers(markdown: string, content: string, startTag: string, endTag: string): string;
@@ -0,0 +1,10 @@
1
+ import { findMarker } from "./findMarker.js";
2
+ export function injectBetweenMarkers(markdown, content, startTag, endTag) {
3
+ const location = findMarker(markdown, startTag, endTag);
4
+ if (location === null) {
5
+ throw new Error(`Markers not found or invalid: ${startTag}`);
6
+ }
7
+ const before = markdown.substring(0, location.startIndex);
8
+ const after = markdown.substring(location.endIndex);
9
+ return `${before}\n${content}\n${after}`;
10
+ }
@@ -0,0 +1,2 @@
1
+ import type { HeadingRecord } from "./types.js";
2
+ export declare function parseHeadings(markdownText: string): HeadingRecord[];
@@ -0,0 +1,31 @@
1
+ import { unified } from "unified";
2
+ import remarkParse from "remark-parse";
3
+ import { visit } from "unist-util-visit";
4
+ import GithubSlugger from "github-slugger";
5
+ function extractHeadingText(node) {
6
+ const parts = [];
7
+ visit(node, (child) => {
8
+ if (child.type === "text")
9
+ parts.push(child.value);
10
+ if (child.type === "inlineCode")
11
+ parts.push(`\`${child.value}\``);
12
+ });
13
+ return parts.join("");
14
+ }
15
+ export function parseHeadings(markdownText) {
16
+ const tree = unified().use(remarkParse).parse(markdownText);
17
+ const slugger = new GithubSlugger();
18
+ const headings = [];
19
+ visit(tree, "heading", (node) => {
20
+ const rawText = extractHeadingText(node);
21
+ const slug = slugger.slug(rawText);
22
+ const line = node.position?.start.line ?? 0;
23
+ headings.push({
24
+ line: line,
25
+ rawText: rawText,
26
+ slug: slug,
27
+ level: node.depth,
28
+ });
29
+ });
30
+ return headings;
31
+ }
@@ -0,0 +1,8 @@
1
+ import GithubSlugger from "github-slugger";
2
+ /**
3
+ * Converts a heading's raw text to a GitHub-style anchor slug.
4
+ *
5
+ * A new GithubSlugger instance must be passed per document so that
6
+ * duplicate-heading counters are scoped correctly to that document.
7
+ */
8
+ export declare function slugHeading(rawText: string, slugger: GithubSlugger): string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Converts a heading's raw text to a GitHub-style anchor slug.
3
+ *
4
+ * A new GithubSlugger instance must be passed per document so that
5
+ * duplicate-heading counters are scoped correctly to that document.
6
+ */
7
+ export function slugHeading(rawText, slugger) {
8
+ return slugger.slug(rawText);
9
+ }
@@ -0,0 +1,51 @@
1
+ export type LinkKind = "relative" | "external" | "fragment";
2
+ export interface LinkRecord {
3
+ href: string;
4
+ line: number;
5
+ kind: LinkKind;
6
+ }
7
+ export interface HeadingRecord {
8
+ line: number;
9
+ rawText: string;
10
+ slug: string;
11
+ /** Heading depth 1–6 (number of # characters). Used by consumers such as TOC generators to compute indentation. */
12
+ level: number;
13
+ }
14
+ interface FileLineRef {
15
+ file: string;
16
+ line: number;
17
+ }
18
+ export interface LinkValidationError extends FileLineRef {
19
+ link: string;
20
+ reason: string;
21
+ }
22
+ export interface LinkValidationWarning extends FileLineRef {
23
+ link: string;
24
+ reason: string;
25
+ }
26
+ export interface LinkValidationResult {
27
+ errors: LinkValidationError[];
28
+ warnings: LinkValidationWarning[];
29
+ validatedCount: number;
30
+ skippedCount: number;
31
+ }
32
+ export interface LinkValidationOptions {
33
+ validateExternal?: boolean;
34
+ timeoutMs?: number;
35
+ concurrency?: number;
36
+ managedBlockStartMarker?: string;
37
+ managedBlockEndMarker?: string;
38
+ verbose?: boolean;
39
+ onVerbose?: (message: string) => void;
40
+ onDebug?: (message: string) => void;
41
+ }
42
+ export type ExternalLinkStatus = {
43
+ kind: "valid";
44
+ } | {
45
+ kind: "warning";
46
+ reason: string;
47
+ } | {
48
+ kind: "error";
49
+ reason: string;
50
+ };
51
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { LinkRecord, LinkValidationError, LinkValidationWarning, LinkValidationOptions } from "./types.js";
2
+ export declare function validateExternalLink(filePath: string, link: LinkRecord, options?: LinkValidationOptions): Promise<LinkValidationError | LinkValidationWarning | null>;
@@ -0,0 +1,82 @@
1
+ const USER_AGENT = "Mozilla/5.0 (compatible; link-checker/1.0)";
2
+ export async function validateExternalLink(filePath, link, options = {}) {
3
+ const timeoutMs = options.timeoutMs ?? 3000;
4
+ const controller = new AbortController();
5
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
6
+ const headers = { "User-Agent": USER_AGENT };
7
+ let status;
8
+ options.onDebug?.(`validateExternalLink: fetching href=${link.href} timeoutMs=${timeoutMs}`);
9
+ try {
10
+ const response = await fetch(link.href, {
11
+ method: "HEAD",
12
+ signal: controller.signal,
13
+ headers: headers,
14
+ redirect: "manual",
15
+ });
16
+ status = response.status;
17
+ if (status === 405) {
18
+ options.onDebug?.(`validateExternalLink: 405 HEAD, retrying with GET href=${link.href}`);
19
+ const getResponse = await fetch(link.href, {
20
+ method: "GET",
21
+ signal: controller.signal,
22
+ headers: headers,
23
+ });
24
+ status = getResponse.status;
25
+ }
26
+ }
27
+ catch (err) {
28
+ clearTimeout(timer);
29
+ const isAbort = err instanceof Error && err.name === "AbortError";
30
+ const reason = isAbort ? "timeout" : "unreachable";
31
+ options.onDebug?.(`validateExternalLink: fetch error href=${link.href} reason=${reason}`);
32
+ return {
33
+ file: filePath,
34
+ line: link.line,
35
+ link: link.href,
36
+ reason: reason,
37
+ };
38
+ }
39
+ clearTimeout(timer);
40
+ options.onDebug?.(`validateExternalLink: status=${status} href=${link.href}`);
41
+ if (status >= 200 && status < 300) {
42
+ options.onVerbose?.(`✓ ${link.href}`);
43
+ return null;
44
+ }
45
+ if (status === 301) {
46
+ return {
47
+ file: filePath,
48
+ line: link.line,
49
+ link: link.href,
50
+ reason: "permanent redirect (301)",
51
+ };
52
+ }
53
+ if (status === 302 || status === 307 || status === 308) {
54
+ options.onVerbose?.(`✓ ${link.href}`);
55
+ return null;
56
+ }
57
+ if (status === 403) {
58
+ return {
59
+ file: filePath,
60
+ line: link.line,
61
+ link: link.href,
62
+ reason: "access forbidden (403) — resource may exist but requests are blocked",
63
+ };
64
+ }
65
+ if (status >= 400 && status < 500) {
66
+ return {
67
+ file: filePath,
68
+ line: link.line,
69
+ link: link.href,
70
+ reason: `HTTP ${status}`,
71
+ };
72
+ }
73
+ if (status >= 500) {
74
+ return {
75
+ file: filePath,
76
+ line: link.line,
77
+ link: link.href,
78
+ reason: `server error (${status})`,
79
+ };
80
+ }
81
+ return null;
82
+ }
@@ -0,0 +1,8 @@
1
+ import type { LinkRecord, HeadingRecord, LinkValidationError } from "./types.js";
2
+ /**
3
+ * Validates a fragment-only link (e.g. #my-heading) against the headings
4
+ * of the current file.
5
+ *
6
+ * Pure function — no I/O.
7
+ */
8
+ export declare function validateFragmentLink(sourceFilePath: string, link: LinkRecord, headings: HeadingRecord[]): LinkValidationError | null;