@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
package/README.md ADDED
@@ -0,0 +1,380 @@
1
+ # @doikayt/tooling-core
2
+
3
+ Shared logic and CLI framework for the JavaScript tooling ecosystem in this repository.
4
+
5
+ This package is the foundation on which all CLI plugins in this workspace are built —
6
+ [`update-markdown-toc`](../update-markdown-toc/README.md),
7
+ [`nx-graph-to-mermaid`](../nx-graph-to-mermaid/README.md), and
8
+ [`update-markdown-uml`](../update-markdown-uml/README.md) all depend on it.
9
+ It can also be used independently to build your own Node.js CLI tools that follow the same
10
+ conventions.
11
+
12
+ ---
13
+
14
+ ## Overview
15
+
16
+ `tooling-core` provides:
17
+
18
+ - **CLI framework** — argument parsing, help generation, plugin descriptor wiring, and
19
+ exit code management via `runCli` and `PluginDescriptor`
20
+ - **File processing** — recursive directory traversal, single-file and recursive modes,
21
+ deterministic ordering via `walkFiles` and `listFilesToProcess`
22
+ - **Markdown utilities** — marker-based content injection (`injectBetweenMarkers`),
23
+ heading extraction, link extraction, fragment and relative link validation
24
+ - **Repository runner** — orchestrates file processing with policy-driven error handling
25
+ and output formatting via `RepositoryRunner`
26
+ - **Shared types** — see below
27
+
28
+ ---
29
+
30
+ ## Shared Types
31
+
32
+ - [`RunConfig`](src/repository/types.ts) — base configuration passed to every file processor;
33
+ carries mode, verbosity, debug, exclude list, and run mode (`update` vs `check`)
34
+ - [`ProcessingStatus`](src/repository/types.ts) — return value from a `FileProcessor`;
35
+ one of `"updated"`, `"unchanged"`, `"needsUpdate"`, or `"skipped"`
36
+ - [`FileProcessor`](src/repository/types.ts) — interface a plugin implements;
37
+ single `process(filePath, config)` method
38
+ - [`PluginDescriptor`](src/cli/types.ts) — declarative plugin metadata;
39
+ name, description, options, optional `parseOptions`, `validate`, and `afterRun` hooks
40
+ - [`PluginOption`](src/cli/types.ts) — describes a single custom CLI flag declared by a plugin
41
+ - [`ParsedCliResult`](src/cli/types.ts) — result returned by `parseStandardCli`;
42
+ carries parsed config, positionals, passthrough flags (those custom to your tool), and help/version booleans
43
+ - [`RunMode`](src/cli/types.ts) — `"update"` or `"check"`
44
+ - [`RunnerPolicy`](src/policy/RunnerPolicy.ts) — interface controlling per-file processing decisions and
45
+ error handling strategy in `RepositoryRunner`
46
+ - [`RunnerDecision`](src/policy/RunnerPolicy.ts) — `"abort"` or `"continue"`;
47
+ returned by `RunnerPolicy.handleProcessorError`
48
+ - [`RepositoryStats`](src/repository/RepositoryRunner.ts) — counts of updated, unchanged,
49
+ needs update, and skipped files returned by `RepositoryRunner.run`
50
+
51
+ ---
52
+
53
+ ## Installation
54
+ ```bash
55
+ npm install @doikayt/tooling-core
56
+ ```
57
+
58
+ > Node.js ≥ 18 required. ESM only.
59
+
60
+ ---
61
+
62
+ ## Usage
63
+
64
+ The primary entry point for plugin authors is `runCli`. A minimal plugin looks like this:
65
+ ```typescript
66
+ import { runCli } from "@doikayt/tooling-core";
67
+ import type {
68
+ PluginDescriptor,
69
+ FileProcessor,
70
+ RunConfig,
71
+ ProcessingStatus,
72
+ } from "@doikayt/tooling-core";
73
+
74
+ // 1. Extend RunConfig to carry your plugin-specific options.
75
+ interface MyPluginConfig extends RunConfig {
76
+ skipJs: boolean; // skip processing of Javascript files
77
+ }
78
+
79
+ // 2. Declare your plugin's metadata and custom CLI flags.
80
+ const descriptor: PluginDescriptor<MyPluginConfig> = {
81
+ name: "my-plugin",
82
+ description: "do something with all non-Javascript files ",
83
+ options: [
84
+ {
85
+ flag: "--skip-js",
86
+ description: "Skip processing and log Skipped: <file> instead",
87
+ },
88
+ {
89
+ flag: "-s",
90
+ description: "Short form of --skip-js",
91
+ },
92
+ ],
93
+ parseOptions(standard, passthrough): MyPluginConfig {
94
+ const skipJs =
95
+ passthrough.get("--skip-js") === true ||
96
+ passthrough.get("-s") === true;
97
+ return {
98
+ ...standard,
99
+ skipJs: skipJs,
100
+ };
101
+ },
102
+ };
103
+
104
+ // 3. Implement your file processor.
105
+ const processor: FileProcessor<MyPluginConfig> = {
106
+ process(filePath: string, config: MyPluginConfig): ProcessingStatus {
107
+ if (config.skipJs && filePath.endsWith(".js")) {
108
+ return "skipped";
109
+ }
110
+ // ... transform filePath content here ...
111
+ return "updated";
112
+ },
113
+ };
114
+
115
+ // 4. Wire everything together.
116
+ await runCli({ descriptor: descriptor, processor: processor });
117
+ ```
118
+
119
+ This gives your plugin standard `--check`, `--recursive`, `--verbose`, `--quiet`,
120
+ `--debug`, and `--help` flags with no additional configuration, plus your own
121
+ `--skip-js` / `-s` flag wired through automatically.
122
+
123
+ For a complete real-world example see
124
+ [`update-markdown-toc`](../update-markdown-toc/README.md).
125
+
126
+ ---
127
+ ## Package Structure
128
+
129
+ <!-- UML:components:START -->
130
+ ```mermaid
131
+ flowchart TB
132
+ subgraph cli["cli"]
133
+ end
134
+ subgraph markdown["markdown"]
135
+ end
136
+ subgraph policy["policy"]
137
+ end
138
+ subgraph repository["repository"]
139
+ end
140
+ subgraph util["util"]
141
+ end
142
+
143
+ cli --> markdown
144
+ cli --> policy
145
+ cli --> repository
146
+ cli --> util
147
+ markdown --> util
148
+ policy --> cli
149
+ policy --> markdown
150
+ policy --> repository
151
+ policy --> util
152
+ repository --> cli
153
+ repository --> markdown
154
+ repository --> policy
155
+ repository --> util
156
+ ```
157
+ <!-- UML:components:END -->
158
+
159
+ <!-- UML:components-table:START -->
160
+ | Component | Description |
161
+ |-----------|-------------|
162
+ | [cli](#cli) | CLI framework for tooling-core plugins: parses arguments via `parseStandardCli`, validates and wires plugin-declared flags, generates help output, resolves target file lists, and drives the full CLI lifecycle through `runCli` |
163
+ | [markdown](#markdown) | Markdown utilities: marker-based content injection (`injectBetweenMarkers`), heading extraction, link extraction, fragment/relative/external link validation, and GitHub-compatible slug generation |
164
+ | [policy](#policy) | Execution policy interface (`RunnerPolicy`) that controls per-file output decisions and error-handling strategy (abort vs |
165
+ | [repository](#repository) | Repository orchestration layer: `RepositoryRunner` drives a `FileProcessor` over a list of files, accumulates `RepositoryStats`, and delegates per-file output and error decisions to a `RunnerPolicy` |
166
+ | [util](#util) | Low-level utilities: deterministic lexicographic filesystem walker (`walkFiles`), `debugLog` helper, and concurrency primitives |
167
+ <!-- UML:components-table:END -->
168
+
169
+ <!-- UML:component-details:START -->
170
+ #### cli
171
+ ```mermaid
172
+ classDiagram
173
+ direction TB
174
+ class ResolvedTargets {
175
+ <<type>>
176
+ }
177
+ class RunCliOptions {
178
+ <<interface>>
179
+ +descriptor PluginDescriptor<TConfig>
180
+ +processor FileProcessor<TConfig>
181
+ +argv? string[]
182
+ }
183
+ class PluginOption {
184
+ <<interface>>
185
+ +flag string
186
+ +description string
187
+ +requiresValue? boolean
188
+ +valueName? string
189
+ }
190
+ class PluginDescriptor {
191
+ <<interface>>
192
+ +name string
193
+ +description string
194
+ +options PluginOption[]
195
+ +parseOptions(this, standard, passthrough) TConfig
196
+ +validate(this, config) void
197
+ +afterRun(this, files, config) Promise<void>
198
+ }
199
+ class ParsedCliResult {
200
+ <<interface>>
201
+ +config TConfig
202
+ +positionals string[]
203
+ +passthrough string[]
204
+ +help boolean
205
+ +version boolean
206
+ }
207
+ class RunMode {
208
+ <<type>>
209
+ }
210
+ ```
211
+
212
+ #### markdown
213
+ ```mermaid
214
+ classDiagram
215
+ direction TB
216
+ class MarkerLocation {
217
+ <<interface>>
218
+ +startMarker string
219
+ +endMarker string
220
+ +startLine number
221
+ +endLine number
222
+ +startIndex number
223
+ +endIndex number
224
+ }
225
+ class LinkRecord {
226
+ <<interface>>
227
+ +href string
228
+ +line number
229
+ +kind LinkKind
230
+ }
231
+ class HeadingRecord {
232
+ <<interface>>
233
+ +line number
234
+ +rawText string
235
+ +slug string
236
+ +level number
237
+ }
238
+ class FileLineRef {
239
+ <<interface>>
240
+ +file string
241
+ +line number
242
+ }
243
+ class LinkValidationError {
244
+ <<interface>>
245
+ +link string
246
+ +reason string
247
+ }
248
+ class LinkValidationWarning {
249
+ <<interface>>
250
+ +link string
251
+ +reason string
252
+ }
253
+ class LinkValidationResult {
254
+ <<interface>>
255
+ +errors LinkValidationError[]
256
+ +warnings LinkValidationWarning[]
257
+ +validatedCount number
258
+ +skippedCount number
259
+ }
260
+ class LinkValidationOptions {
261
+ <<interface>>
262
+ +validateExternal? boolean
263
+ +timeoutMs? number
264
+ +concurrency? number
265
+ +managedBlockStartMarker? string
266
+ +managedBlockEndMarker? string
267
+ +verbose? boolean
268
+ +onVerbose? (message: string) => void
269
+ +onDebug? (message: string) => void
270
+ }
271
+ class LinkKind {
272
+ <<type>>
273
+ }
274
+ class ExternalLinkStatus {
275
+ <<type>>
276
+ }
277
+
278
+ LinkValidationError ..|> FileLineRef
279
+ LinkValidationWarning ..|> FileLineRef
280
+ ```
281
+
282
+ #### policy
283
+ ```mermaid
284
+ classDiagram
285
+ direction TB
286
+ class RunnerPolicy {
287
+ <<interface>>
288
+ +shouldPrint(status) boolean
289
+ +shouldPrintSummary() boolean
290
+ +handleProcessorError(file, error) RunnerDecision
291
+ }
292
+ class RunnerDecision {
293
+ <<type>>
294
+ }
295
+ ```
296
+
297
+ #### repository
298
+ ```mermaid
299
+ classDiagram
300
+ direction TB
301
+ class RepositoryRunner {
302
+ -processor FileProcessor<TConfig>
303
+ -config TConfig
304
+ -policy RunnerPolicy
305
+ +run(files) RepositoryStats
306
+ -updateCounters(result, stats) void
307
+ -printFileStatus(result, file) void
308
+ -getInitCounterState() RepositoryStats
309
+ -printSummary(stats) void
310
+ }
311
+ class RepositoryRunnerOptions {
312
+ <<interface>>
313
+ +processor FileProcessor<TConfig>
314
+ +config TConfig
315
+ +policy RunnerPolicy
316
+ }
317
+ class RepositoryStats {
318
+ <<interface>>
319
+ +updated number
320
+ +unchanged number
321
+ +needsUpdate number
322
+ +skipped number
323
+ }
324
+ class FileProcessor {
325
+ <<interface>>
326
+ +process(filePath, config) ProcessingStatus
327
+ }
328
+ class RunConfig {
329
+ <<interface>>
330
+ +runMode RunMode
331
+ +mode "single" | "recursive"
332
+ +recursivePath? string
333
+ +exclude? string[]
334
+ +verbose boolean
335
+ +quiet boolean
336
+ +debug boolean
337
+ +validateExternalLinks boolean
338
+ +linkTimeoutMs number
339
+ }
340
+ class ProcessingStatus {
341
+ <<type>>
342
+ }
343
+ ```
344
+
345
+ #### util
346
+ ```mermaid
347
+ classDiagram
348
+ direction TB
349
+ class WalkOptions {
350
+ <<interface>>
351
+ +rootDir string
352
+ +extensions? string[]
353
+ +excludeDirs? string[]
354
+ }
355
+ ```
356
+ <!-- UML:component-details:END -->
357
+
358
+
359
+
360
+ ## Tech Stack
361
+
362
+ For the full workspace tech stack see: [TECH-STACK.md](../TECH-STACK.md)
363
+
364
+ ---
365
+
366
+ ## Contributing
367
+
368
+ For code overview, development setup, build workflow, and release procedures (including how to
369
+ trigger a publish via Changesets), see
370
+ [CONTRIBUTING.md](./docs/CONTRIBUTING.md).
371
+
372
+
373
+ ---
374
+
375
+ ## Packaging, Publishing, and Inter-relationship with Other Plugins
376
+
377
+ This package is one component of a small ecosystem of JavaScript tooling plugins
378
+ maintained as individual npm packages in this repository. The versioning and release
379
+ of these packages is governed by a coordinated release policy, and the packages adhere
380
+ to common design and architectural principles described [here](../README.md).
@@ -0,0 +1,2 @@
1
+ import type { PluginDescriptor } from "./types.js";
2
+ export declare function generateHelp(descriptor: PluginDescriptor): string;
@@ -0,0 +1,53 @@
1
+ const STANDARD_OPTIONS = [
2
+ {
3
+ flag: "-c, --check",
4
+ description: "Do not write files; exit non-zero if stale",
5
+ },
6
+ {
7
+ flag: "-r, --recursive <path>",
8
+ description: "Recursively process all .md files under the given folder",
9
+ },
10
+ {
11
+ flag: "-e, --exclude <dir1,dir2...>",
12
+ description: "Directory names to exclude",
13
+ },
14
+ {
15
+ flag: "-n, --no-external-link-check",
16
+ description: "Skip external link validation in check mode",
17
+ },
18
+ {
19
+ flag: "-l, --link-timeout-ms <ms>",
20
+ description: "Timeout in milliseconds for external link requests (default: 3000)",
21
+ },
22
+ {
23
+ flag: "-v, --verbose",
24
+ description: "Print status for every file processed",
25
+ },
26
+ { flag: "-q, --quiet", description: "Suppress all non-error output" },
27
+ { flag: "-d, --debug", description: "Print debug diagnostics to stderr" },
28
+ { flag: "-h, --help", description: "Show this help message and exit" },
29
+ ];
30
+ export function generateHelp(descriptor) {
31
+ const lines = [];
32
+ lines.push(`${descriptor.name}`);
33
+ lines.push(` ${descriptor.description}`);
34
+ lines.push("");
35
+ lines.push("Usage:");
36
+ lines.push(` ${descriptor.name} [options] [file]`);
37
+ lines.push("");
38
+ lines.push("Options:");
39
+ const allOptions = [
40
+ ...descriptor.options.map((o) => ({
41
+ flag: o.requiresValue === true
42
+ ? `${o.flag} <${o.valueName ?? "value"}>`
43
+ : o.flag,
44
+ description: o.description,
45
+ })),
46
+ ...STANDARD_OPTIONS,
47
+ ];
48
+ const flagWidth = Math.max(...allOptions.map((o) => o.flag.length));
49
+ for (const option of allOptions) {
50
+ lines.push(` ${option.flag.padEnd(flagWidth)} ${option.description}`);
51
+ }
52
+ return lines.join("\n");
53
+ }
@@ -0,0 +1,9 @@
1
+ import type { RunConfig } from "../repository/types.js";
2
+ export type ResolvedTargets = {
3
+ mode: "single";
4
+ files: string[];
5
+ } | {
6
+ mode: "recursive";
7
+ files: string[];
8
+ };
9
+ export declare function listFilesToProcess(config: RunConfig, positionals: string[]): ResolvedTargets;
@@ -0,0 +1,47 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { walkFiles } from "../util/walkFiles.js";
4
+ export function listFilesToProcess(config, positionals) {
5
+ const cwd = process.cwd();
6
+ /*
7
+ SINGLE MODE
8
+ */
9
+ if (config.mode === "single") {
10
+ const target = positionals[0] ?? "README.md";
11
+ const resolved = path.resolve(cwd, target);
12
+ if (!fs.existsSync(resolved)) {
13
+ throw new Error(`File does not exist: ${resolved}`);
14
+ }
15
+ const stat = fs.statSync(resolved);
16
+ if (!stat.isFile()) {
17
+ throw new Error(`Not a file: ${resolved}`);
18
+ }
19
+ return {
20
+ mode: "single",
21
+ files: [resolved],
22
+ };
23
+ }
24
+ /*
25
+ RECURSIVE MODE
26
+ */
27
+ const root = config.recursivePath ?? ".";
28
+ const resolvedRoot = path.resolve(cwd, root);
29
+ if (!fs.existsSync(resolvedRoot)) {
30
+ throw new Error(`Directory does not exist: ${resolvedRoot}`);
31
+ }
32
+ if (!fs.statSync(resolvedRoot).isDirectory()) {
33
+ throw new Error(`Not a directory: ${resolvedRoot}`);
34
+ }
35
+ if (positionals.length > 0) {
36
+ throw new Error(`Cannot use positional file arguments with --recursive: ${positionals.join(", ")}`);
37
+ }
38
+ const files = walkFiles({
39
+ rootDir: resolvedRoot,
40
+ extensions: [".md"],
41
+ excludeDirs: config.exclude,
42
+ });
43
+ return {
44
+ mode: "recursive",
45
+ files,
46
+ };
47
+ }
@@ -0,0 +1,10 @@
1
+ import type { RunConfig } from "../repository/types.js";
2
+ import type { PluginOption } from "./types.js";
3
+ import type { ParsedCliResult } from "./types.js";
4
+ export declare function validateConfig(config: RunConfig, _positionals: string[]): void;
5
+ export declare function parseStandardCli(argv: string[], pluginOptions?: PluginOption[]): ParsedCliResult<RunConfig>;
6
+ export declare function buildPassthroughMap(options: PluginOption[], passthrough: string[]): Map<string, string | boolean>;
7
+ export declare function parseStringOption(flag: string, map: Map<string, string | boolean>): string | undefined;
8
+ export declare function parseBooleanOption(flag: string, map: Map<string, string | boolean>): boolean;
9
+ export declare function parseNumberOption(flag: string, map: Map<string, string | boolean>): number | undefined;
10
+ export declare function buildConfig<TConfig extends RunConfig>(standard: RunConfig, passthroughMap: Map<string, string | boolean>, parseOptions?: (standard: RunConfig, passthrough: Map<string, string | boolean>) => TConfig): TConfig;
@@ -0,0 +1,197 @@
1
+ import { debugLog } from "../util/debugLog.js";
2
+ // Option B: PluginOption[] is passed into parseStandardCli so the parser
3
+ // knows upfront which unknown flags require values. This eliminates the
4
+ // need for a peek heuristic in the default case and correctly handles
5
+ // all flag/positional combinations.
6
+ const DEFAULT_LINK_TIMEOUT_MS = 3000;
7
+ export function validateConfig(config, _positionals) {
8
+ if (config.verbose && config.quiet) {
9
+ throw new Error("Cannot use --verbose and --quiet together");
10
+ }
11
+ }
12
+ export function parseStandardCli(argv, pluginOptions) {
13
+ const args = argv;
14
+ // Build a lookup of which unknown flags require a value so the default
15
+ // case can consume the next token correctly without a fragile peek heuristic.
16
+ const valueRequiringFlags = new Set((pluginOptions ?? [])
17
+ .filter((o) => o.requiresValue === true)
18
+ .map((o) => o.flag));
19
+ let help = false;
20
+ let version = false;
21
+ let verbose = false;
22
+ let quiet = false;
23
+ let debug = false;
24
+ let runMode = "update";
25
+ let mode = "single";
26
+ let recursivePath = undefined;
27
+ let exclude = undefined;
28
+ let validateExternalLinks = true;
29
+ let linkTimeoutMs = DEFAULT_LINK_TIMEOUT_MS;
30
+ const positionals = [];
31
+ const passthrough = [];
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = args[i];
34
+ switch (arg) {
35
+ case "-h":
36
+ case "--help":
37
+ help = true;
38
+ continue;
39
+ case "--version":
40
+ version = true;
41
+ continue;
42
+ case "-v":
43
+ case "--verbose":
44
+ verbose = true;
45
+ continue;
46
+ case "-q":
47
+ case "--quiet":
48
+ quiet = true;
49
+ continue;
50
+ case "-d":
51
+ case "--debug":
52
+ debug = true;
53
+ continue;
54
+ case "-c":
55
+ case "--check":
56
+ runMode = "check";
57
+ continue;
58
+ case "-r":
59
+ case "--recursive": {
60
+ const next = args[i + 1];
61
+ if (next === undefined || next.startsWith("-")) {
62
+ throw new Error("--recursive requires a path");
63
+ }
64
+ mode = "recursive";
65
+ recursivePath = next;
66
+ i++;
67
+ continue;
68
+ }
69
+ case "-n":
70
+ case "--no-external-link-check":
71
+ validateExternalLinks = false;
72
+ continue;
73
+ case "-l":
74
+ case "--link-timeout-ms": {
75
+ const next = args[i + 1];
76
+ if (next === undefined || next.startsWith("-")) {
77
+ throw new Error("--link-timeout-ms requires a numeric value in milliseconds");
78
+ }
79
+ const n = Number(next);
80
+ if (isNaN(n)) {
81
+ throw new Error("--link-timeout-ms requires a numeric value in milliseconds");
82
+ }
83
+ linkTimeoutMs = n;
84
+ i++;
85
+ continue;
86
+ }
87
+ case "-e":
88
+ case "--exclude": {
89
+ const next = args[i + 1];
90
+ if (next === undefined) {
91
+ throw new Error("--exclude requires a comma-separated list (or empty string)");
92
+ }
93
+ if (next !== "" && next.startsWith("-")) {
94
+ throw new Error("--exclude requires a comma-separated list (or empty string)");
95
+ }
96
+ exclude =
97
+ next === ""
98
+ ? []
99
+ : next
100
+ .split(",")
101
+ .map((s) => s.trim())
102
+ .filter((s) => s.length > 0);
103
+ i++;
104
+ continue;
105
+ }
106
+ default:
107
+ if (arg.startsWith("-")) {
108
+ passthrough.push(arg);
109
+ if (valueRequiringFlags.has(arg)) {
110
+ const next = args[i + 1];
111
+ if (next === undefined || next.startsWith("-")) {
112
+ throw new Error(`Option ${arg} requires a value`);
113
+ }
114
+ passthrough.push(next);
115
+ i++;
116
+ }
117
+ continue;
118
+ }
119
+ positionals.push(arg);
120
+ }
121
+ }
122
+ if (!help && !version) {
123
+ if (verbose && quiet) {
124
+ throw new Error("Cannot use --verbose and --quiet together");
125
+ }
126
+ }
127
+ const config = {
128
+ runMode: runMode,
129
+ mode: mode,
130
+ recursivePath: recursivePath,
131
+ exclude: exclude,
132
+ verbose: verbose,
133
+ quiet: quiet,
134
+ debug: debug,
135
+ validateExternalLinks: validateExternalLinks,
136
+ linkTimeoutMs: linkTimeoutMs,
137
+ };
138
+ validateConfig(config, positionals);
139
+ const retval = {
140
+ config: config,
141
+ positionals: positionals,
142
+ passthrough: passthrough,
143
+ help: help,
144
+ version: version,
145
+ };
146
+ // Same caveat as runCli: if RunConfig gains credential fields, redact before logging.
147
+ debugLog(config, `parseStandardCli: result=${JSON.stringify(retval)}`);
148
+ return retval;
149
+ }
150
+ export function buildPassthroughMap(options, passthrough) {
151
+ const known = new Map(options.map((o) => [o.flag, o]));
152
+ const result = new Map();
153
+ for (let i = 0; i < passthrough.length; i++) {
154
+ const arg = passthrough[i];
155
+ const option = known.get(arg);
156
+ if (option === undefined) {
157
+ throw new Error(`Unknown option: ${arg}`);
158
+ }
159
+ if (option.requiresValue === true) {
160
+ const next = passthrough[i + 1];
161
+ if (next === undefined || next.startsWith("-")) {
162
+ throw new Error(`Option ${arg} requires a value`);
163
+ }
164
+ result.set(arg, next);
165
+ i++;
166
+ }
167
+ else {
168
+ result.set(arg, true);
169
+ }
170
+ }
171
+ return result;
172
+ }
173
+ export function parseStringOption(flag, map) {
174
+ const value = map.get(flag);
175
+ if (value === undefined)
176
+ return undefined;
177
+ if (typeof value !== "string")
178
+ throw new Error(`Option ${flag} requires a string value`);
179
+ return value;
180
+ }
181
+ export function parseBooleanOption(flag, map) {
182
+ return map.get(flag) === true;
183
+ }
184
+ export function parseNumberOption(flag, map) {
185
+ const value = map.get(flag);
186
+ if (value === undefined)
187
+ return undefined;
188
+ const n = Number(value);
189
+ if (isNaN(n))
190
+ throw new Error(`Option ${flag} requires a numeric value`);
191
+ return n;
192
+ }
193
+ export function buildConfig(standard, passthroughMap, parseOptions) {
194
+ return parseOptions
195
+ ? parseOptions(standard, passthroughMap)
196
+ : standard;
197
+ }