politty 0.11.6 → 0.11.7

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 (50) hide show
  1. package/README.md +30 -1
  2. package/dist/augment.d.ts +1 -16
  3. package/dist/augment.js +2 -0
  4. package/dist/cli-run-DGe88d0G.js +14 -0
  5. package/dist/cli.d.ts +1 -1
  6. package/dist/cli.js +13 -9
  7. package/dist/compile-cache.d.ts +1 -79
  8. package/dist/compile-cache.js +2 -2
  9. package/dist/completion.d.ts +1 -0
  10. package/dist/completion.js +3 -0
  11. package/dist/docs.d.ts +1 -0
  12. package/dist/docs.js +3 -0
  13. package/dist/index.d.ts +10 -814
  14. package/dist/index.js +17 -8
  15. package/dist/prompt-clack.d.ts +1 -0
  16. package/dist/prompt-clack.js +3 -0
  17. package/dist/prompt-inquirer.d.ts +1 -0
  18. package/dist/prompt-inquirer.js +3 -0
  19. package/dist/prompt.d.ts +1 -0
  20. package/dist/prompt.js +3 -0
  21. package/dist/skill.d.ts +1 -0
  22. package/dist/skill.js +3 -0
  23. package/package.json +18 -45
  24. package/dist/arg-registry-SrNIsq-d.d.ts +0 -981
  25. package/dist/cli-main.d.ts +0 -1
  26. package/dist/cli-main.js +0 -86
  27. package/dist/command-B4yA4LXX.js +0 -43
  28. package/dist/compile-cache-NnTkjJMV.js +0 -101
  29. package/dist/completion/index.d.ts +0 -3
  30. package/dist/completion/index.js +0 -3
  31. package/dist/completion-D9SKGJad.js +0 -5610
  32. package/dist/docs/index.d.ts +0 -771
  33. package/dist/docs/index.js +0 -3024
  34. package/dist/index-qqwo5WZT.d.ts +0 -673
  35. package/dist/log-collector-DK32-73m.js +0 -115
  36. package/dist/logger-DbDkjdfO.js +0 -134
  37. package/dist/prompt/clack/index.d.ts +0 -17
  38. package/dist/prompt/clack/index.js +0 -32
  39. package/dist/prompt/index.d.ts +0 -107
  40. package/dist/prompt/index.js +0 -3
  41. package/dist/prompt/inquirer/index.d.ts +0 -17
  42. package/dist/prompt/inquirer/index.js +0 -47
  43. package/dist/prompt-Cc8Tfmdv.js +0 -172
  44. package/dist/runner-BGs_QMJM.js +0 -3
  45. package/dist/runner-xN7248Ph.js +0 -2966
  46. package/dist/schema-extractor-wzJ1cGon.js +0 -488
  47. package/dist/skill/index.d.ts +0 -584
  48. package/dist/skill/index.js +0 -1756
  49. package/dist/src-BiCtSNrn.js +0 -193
  50. package/dist/subcommand-router-CTzHPGzF.js +0 -135
@@ -1,3024 +0,0 @@
1
- import { r as getExtractedFields, t as extractFields } from "../schema-extractor-wzJ1cGon.js";
2
- import { r as resolveLazyCommand } from "../subcommand-router-CTzHPGzF.js";
3
- import { t as createLogCollector } from "../log-collector-DK32-73m.js";
4
- import * as fs from "node:fs";
5
- import * as path$1 from "node:path";
6
- import path from "node:path";
7
- import { z } from "zod";
8
- import { isDeepStrictEqual } from "node:util";
9
-
10
- //#region src/docs/option-rows.ts
11
- /** Canonical column order used when no explicit column subset is requested. */
12
- const DEFAULT_COLUMNS = [
13
- "option",
14
- "alias",
15
- "description",
16
- "required",
17
- "default"
18
- ];
19
- /**
20
- * Marker appended to a custom negation row/line so readers can see which
21
- * positive flag it negates (e.g. `--monochrome` → ``(↔ `--color`)``).
22
- */
23
- function negationRelationMarker(opt) {
24
- return `(↔ \`--${opt.cliName}\`)`;
25
- }
26
- /**
27
- * Resolve placeholder for an option (uses kebab-case cliName).
28
- */
29
- function resolvePlaceholder(opt) {
30
- return opt.placeholder ?? opt.cliName.toUpperCase().replace(/-/g, "_");
31
- }
32
- /**
33
- * Normalize a single {@link ResolvedFieldMeta} into an {@link OptionRow}.
34
- */
35
- function toOptionRow(opt) {
36
- const longFlag = opt.type === "boolean" ? `--${opt.cliName}` : `--${opt.cliName} <${resolvePlaceholder(opt)}>`;
37
- const aliases = [];
38
- if (opt.alias) for (const a of opt.alias) aliases.push(a.length === 1 ? `-${a}` : `--${a}`);
39
- const hasNegationDisplay = opt.type === "boolean" && !!opt.negationDisplay;
40
- const inlineNegation = hasNegationDisplay && !opt.negationDescription ? `--${opt.negationDisplay}` : void 0;
41
- const negationRow = hasNegationDisplay && opt.negationDescription ? {
42
- flag: `--${opt.negationDisplay}`,
43
- description: opt.negationDescription,
44
- relationMarker: negationRelationMarker(opt),
45
- required: opt.required
46
- } : void 0;
47
- return {
48
- longFlag,
49
- aliases,
50
- inlineNegation,
51
- description: opt.description,
52
- required: opt.required,
53
- hasDefault: opt.defaultValue !== void 0,
54
- defaultValue: opt.defaultValue,
55
- env: opt.env,
56
- negationRow
57
- };
58
- }
59
- /**
60
- * Build the normalized intermediate representation for a list of options.
61
- * This is the single source of truth for per-option display decisions; the
62
- * emitters below ({@link emitMarkdownTable}, {@link emitMarkdownList}) are pure
63
- * formatting.
64
- */
65
- function toOptionRows(options) {
66
- return options.map(toOptionRow);
67
- }
68
- /**
69
- * Escape markdown special characters in table cells.
70
- */
71
- function escapeTableCell$2(str) {
72
- return str.replace(/\|/g, "\\|").replace(/\n/g, " ");
73
- }
74
- function backtick(value) {
75
- return `\`${value}\``;
76
- }
77
- /**
78
- * Format default value for table display.
79
- */
80
- function formatDefaultValue(row) {
81
- if (!row.hasDefault) return "-";
82
- return `\`${JSON.stringify(row.defaultValue)}\``;
83
- }
84
- /**
85
- * Format env variable names for a markdown table cell.
86
- */
87
- function formatEnvNames(env) {
88
- if (!env) return "-";
89
- if (Array.isArray(env)) return env.map((e) => `\`${e}\``).join(", ");
90
- return `\`${env}\``;
91
- }
92
- /**
93
- * Format env variable info for a markdown list item (e.g. `[env: PORT, SERVER_PORT]`).
94
- */
95
- function formatEnvInfo(env) {
96
- if (!env) return "";
97
- return ` [env: ${(Array.isArray(env) ? env : [env]).join(", ")}]`;
98
- }
99
- /** Header label + separator dashes for each column, matching legacy widths. */
100
- const COLUMN_META = {
101
- option: {
102
- header: "Option",
103
- separator: "--------"
104
- },
105
- alias: {
106
- header: "Alias",
107
- separator: "-------"
108
- },
109
- description: {
110
- header: "Description",
111
- separator: "-------------"
112
- },
113
- required: {
114
- header: "Required",
115
- separator: "----------"
116
- },
117
- default: {
118
- header: "Default",
119
- separator: "---------"
120
- },
121
- env: {
122
- header: "Env",
123
- separator: "-----"
124
- }
125
- };
126
- /**
127
- * Render the table cell for a base option row in the given column.
128
- */
129
- function tableCell(row, col) {
130
- switch (col) {
131
- case "option": {
132
- const name = backtick(row.longFlag);
133
- return row.inlineNegation ? `${name} / ${backtick(row.inlineNegation)}` : name;
134
- }
135
- case "alias": return row.aliases.length > 0 ? row.aliases.map(backtick).join(", ") : "-";
136
- case "description": return escapeTableCell$2(row.description ?? "");
137
- case "required": return row.required ? "Yes" : "No";
138
- case "default": return formatDefaultValue(row);
139
- case "env": return formatEnvNames(row.env);
140
- }
141
- }
142
- /**
143
- * Render the table cell for a negation row in the given column.
144
- */
145
- function negationTableCell(neg, col) {
146
- switch (col) {
147
- case "option": return backtick(neg.flag);
148
- case "description": return `${escapeTableCell$2(neg.description)} ${neg.relationMarker}`;
149
- case "required": return neg.required ? "Yes" : "No";
150
- case "alias":
151
- case "default":
152
- case "env": return "-";
153
- }
154
- }
155
- /**
156
- * Emit option rows as a markdown table.
157
- *
158
- * When `columns` is omitted, the canonical column set is used and the `Env`
159
- * column is appended automatically iff any row has env configured. When
160
- * `columns` is provided, exactly those columns are emitted, in that order.
161
- *
162
- * The separator row always uses the canonical fixed-width dashes from
163
- * {@link COLUMN_META}, so every table — default or column-filtered — shares a
164
- * single, consistent format.
165
- */
166
- function emitMarkdownTable(rows, columns) {
167
- if (rows.length === 0) return "";
168
- const cols = columns ?? (rows.some((r) => r.env) ? [...DEFAULT_COLUMNS, "env"] : DEFAULT_COLUMNS);
169
- const lines = [];
170
- lines.push(`| ${cols.map((c) => COLUMN_META[c].header).join(" | ")} |`);
171
- lines.push(`|${cols.map((c) => COLUMN_META[c].separator).join("|")}|`);
172
- for (const row of rows) {
173
- lines.push(`| ${cols.map((c) => tableCell(row, c)).join(" | ")} |`);
174
- if (row.negationRow) lines.push(`| ${cols.map((c) => negationTableCell(row.negationRow, c)).join(" | ")} |`);
175
- }
176
- return lines.join("\n");
177
- }
178
- /**
179
- * Emit option rows as a markdown list.
180
- *
181
- * Aliases are joined with `, ` (short flags first, then the long flag, then
182
- * long aliases); the inline negation is appended with ` / ` so it stays
183
- * visually distinct from aliases.
184
- */
185
- function emitMarkdownList(rows) {
186
- if (rows.length === 0) return "";
187
- const lines = [];
188
- for (const row of rows) {
189
- const shortAliases = row.aliases.filter((a) => !a.startsWith("--"));
190
- const longAliases = row.aliases.filter((a) => a.startsWith("--"));
191
- let flags = [
192
- ...shortAliases,
193
- row.longFlag,
194
- ...longAliases
195
- ].map(backtick).join(", ");
196
- if (row.inlineNegation) flags += ` / ${backtick(row.inlineNegation)}`;
197
- const desc = row.description ? ` - ${row.description}` : "";
198
- const required = row.required ? " (required)" : "";
199
- const defaultVal = row.hasDefault ? ` (default: ${JSON.stringify(row.defaultValue)})` : "";
200
- const envInfo = formatEnvInfo(row.env);
201
- lines.push(`- ${flags}${desc}${required}${defaultVal}${envInfo}`);
202
- if (row.negationRow) lines.push(`- ${backtick(row.negationRow.flag)} - ${row.negationRow.description} ${row.negationRow.relationMarker}`);
203
- }
204
- return lines.join("\n");
205
- }
206
-
207
- //#endregion
208
- //#region src/docs/types.ts
209
- /**
210
- * Environment variable name for update mode
211
- */
212
- const UPDATE_GOLDEN_ENV = "POLITTY_DOCS_UPDATE";
213
- /**
214
- * Environment variable name for doctor mode.
215
- * When enabled alone, detects and reports missing section markers (read-only).
216
- * When combined with POLITTY_DOCS_UPDATE=true, auto-inserts missing markers.
217
- */
218
- const DOCTOR_ENV = "POLITTY_DOCS_DOCTOR";
219
- /**
220
- * All section types in rendering order
221
- */
222
- const SECTION_TYPES = [
223
- "heading",
224
- "description",
225
- "usage",
226
- "arguments",
227
- "options",
228
- "global-options-link",
229
- "subcommands",
230
- "examples",
231
- "notes"
232
- ];
233
- /**
234
- * Marker prefix for command section markers in generated documentation
235
- * Format: <!-- politty:command:<scope>:<type>:start --> ... <!-- politty:command:<scope>:<type>:end -->
236
- */
237
- const SECTION_MARKER_PREFIX = "politty:command";
238
- /**
239
- * Generate start marker for a command section
240
- */
241
- function sectionStartMarker(type, scope) {
242
- return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:start -->`;
243
- }
244
- /**
245
- * Generate end marker for a command section
246
- */
247
- function sectionEndMarker(type, scope) {
248
- return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:end -->`;
249
- }
250
- /**
251
- * Marker prefix for global options sections in generated documentation
252
- * Format: <!-- politty:global-options:start --> ... <!-- politty:global-options:end -->
253
- */
254
- const GLOBAL_OPTIONS_MARKER_PREFIX = "politty:global-options";
255
- /**
256
- * Generate start marker for a global options section
257
- */
258
- function globalOptionsStartMarker() {
259
- return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:start -->`;
260
- }
261
- /**
262
- * Generate end marker for a global options section
263
- */
264
- function globalOptionsEndMarker() {
265
- return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:end -->`;
266
- }
267
- /**
268
- * Marker prefix for root header sections in generated documentation
269
- */
270
- const ROOT_HEADER_MARKER_PREFIX = "politty:root-header";
271
- function rootHeaderStartMarker() {
272
- return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:start -->`;
273
- }
274
- function rootHeaderEndMarker() {
275
- return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:end -->`;
276
- }
277
- /**
278
- * Marker prefix for root footer sections in generated documentation
279
- */
280
- const ROOT_FOOTER_MARKER_PREFIX = "politty:root-footer";
281
- function rootFooterStartMarker() {
282
- return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:start -->`;
283
- }
284
- function rootFooterEndMarker() {
285
- return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:end -->`;
286
- }
287
- /**
288
- * Marker prefix for index sections in generated documentation
289
- * Format: <!-- politty:index:<scope>:start --> ... <!-- politty:index:<scope>:end -->
290
- */
291
- const INDEX_MARKER_PREFIX = "politty:index";
292
- /**
293
- * Generate start marker for an index section
294
- */
295
- function indexStartMarker(scope) {
296
- return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:start -->`;
297
- }
298
- /**
299
- * Generate end marker for an index section
300
- */
301
- function indexEndMarker(scope) {
302
- return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:end -->`;
303
- }
304
-
305
- //#endregion
306
- //#region src/docs/default-renderers.ts
307
- /**
308
- * Escape markdown special characters in table cells
309
- */
310
- function escapeTableCell$1(str) {
311
- return str.replace(/\|/g, "\\|").replace(/\n/g, " ");
312
- }
313
- /**
314
- * Render usage line
315
- */
316
- function renderUsage(info) {
317
- const parts = [info.fullCommandPath];
318
- if (info.options.length > 0) parts.push("[options]");
319
- if (info.subCommands.length > 0) if (info.command.run) parts.push("[command]");
320
- else parts.push("<command>");
321
- for (const arg of info.positionalArgs) if (arg.required) parts.push(`<${arg.name}>`);
322
- else parts.push(`[${arg.name}]`);
323
- return parts.join(" ");
324
- }
325
- /**
326
- * Render arguments as table
327
- */
328
- function renderArgumentsTable(info) {
329
- if (info.positionalArgs.length === 0) return "";
330
- const lines = [];
331
- lines.push("| Argument | Description | Required |");
332
- lines.push("|----------|-------------|----------|");
333
- for (const arg of info.positionalArgs) {
334
- const desc = escapeTableCell$1(arg.description ?? "");
335
- const required = arg.required ? "Yes" : "No";
336
- lines.push(`| \`${arg.name}\` | ${desc} | ${required} |`);
337
- }
338
- return lines.join("\n");
339
- }
340
- /**
341
- * Render arguments as list
342
- */
343
- function renderArgumentsList(info) {
344
- if (info.positionalArgs.length === 0) return "";
345
- const lines = [];
346
- for (const arg of info.positionalArgs) {
347
- const required = arg.required ? "(required)" : "(optional)";
348
- const desc = arg.description ? ` - ${arg.description}` : "";
349
- lines.push(`- \`${arg.name}\`${desc} ${required}`);
350
- }
351
- return lines.join("\n");
352
- }
353
- /**
354
- * Render options as markdown table
355
- *
356
- * Features:
357
- * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)
358
- * - Automatically adds Env column when any option has env configured
359
- * - Displays multiple env vars as comma-separated list
360
- *
361
- * @example
362
- * | Option | Alias | Description | Required | Default | Env |
363
- * |--------|-------|-------------|----------|---------|-----|
364
- * | `--dry-run` | `-d` | Dry run mode | No | `false` | - |
365
- * | `--port <PORT>` | - | Server port | Yes | - | `PORT`, `SERVER_PORT` |
366
- */
367
- function renderOptionsTable(info) {
368
- return emitMarkdownTable(toOptionRows(info.options));
369
- }
370
- /**
371
- * Render options as markdown list
372
- *
373
- * Features:
374
- * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)
375
- * - Appends env info at the end of each option (e.g., `[env: PORT, SERVER_PORT]`)
376
- *
377
- * @example
378
- * - `-d`, `--dry-run` - Dry run mode (default: false)
379
- * - `--port <PORT>` - Server port (required) [env: PORT, SERVER_PORT]
380
- */
381
- function renderOptionsList(info) {
382
- return emitMarkdownList(toOptionRows(info.options));
383
- }
384
- /**
385
- * Generate anchor from command path
386
- */
387
- function generateAnchor$1(commandPath) {
388
- return commandPath.join("-").toLowerCase();
389
- }
390
- /**
391
- * Generate relative path from one file to another.
392
- * Always emits forward slashes so Markdown links remain portable across OSes.
393
- */
394
- function getRelativePath(from, to) {
395
- const fromPosix = from.replace(/\\/g, "/");
396
- const toPosix = to.replace(/\\/g, "/");
397
- return path.posix.relative(path.posix.dirname(fromPosix), toPosix);
398
- }
399
- /**
400
- * Render subcommands as table
401
- */
402
- function renderSubcommandsTable(info, generateAnchors = true) {
403
- return renderSubcommandsTableFromArray(info.subCommands, info, generateAnchors);
404
- }
405
- /**
406
- * Render options from array as table
407
- */
408
- function renderOptionsTableFromArray(options) {
409
- return emitMarkdownTable(toOptionRows(options));
410
- }
411
- /**
412
- * Render union/xor options as markdown with variant grouping
413
- */
414
- function renderUnionOptionsMarkdown(extracted, style = "table") {
415
- const unionOptions = extracted.unionOptions ?? [];
416
- if (unionOptions.length === 0) return "";
417
- const sections = [];
418
- const allFieldNames = /* @__PURE__ */ new Set();
419
- for (const option of unionOptions) for (const field of option.fields) allFieldNames.add(field.name);
420
- const commonFieldNames = /* @__PURE__ */ new Set();
421
- for (const fieldName of allFieldNames) if (unionOptions.every((o) => o.fields.some((f) => f.name === fieldName))) commonFieldNames.add(fieldName);
422
- const commonFields = extracted.fields.filter((f) => commonFieldNames.has(f.name) && !f.positional);
423
- if (commonFields.length > 0) sections.push(style === "table" ? renderOptionsTableFromArray(commonFields) : renderOptionsListFromArray(commonFields));
424
- sections.push("> One of the following option groups is required:");
425
- for (let i = 0; i < unionOptions.length; i++) {
426
- const option = unionOptions[i];
427
- if (!option) continue;
428
- const uniqueFields = option.fields.filter((f) => !commonFieldNames.has(f.name) && !f.positional);
429
- const label = option.description ?? `Variant ${i + 1}`;
430
- if (uniqueFields.length === 0) {
431
- sections.push(`**${label}:**\n\n_no options_`);
432
- continue;
433
- }
434
- const rendered = style === "table" ? renderOptionsTableFromArray(uniqueFields) : renderOptionsListFromArray(uniqueFields);
435
- sections.push(`**${label}:**\n\n${rendered}`);
436
- }
437
- return sections.join("\n\n");
438
- }
439
- /**
440
- * Render discriminatedUnion options as markdown with variant grouping
441
- */
442
- function renderDiscriminatedUnionOptionsMarkdown(extracted, style = "table") {
443
- const discriminator = extracted.discriminator;
444
- const variants = extracted.variants ?? [];
445
- if (!discriminator || variants.length === 0) return "";
446
- const sections = [];
447
- const allFieldNames = /* @__PURE__ */ new Set();
448
- for (const variant of variants) for (const field of variant.fields) allFieldNames.add(field.name);
449
- const commonFieldNames = /* @__PURE__ */ new Set();
450
- for (const fieldName of allFieldNames) {
451
- if (fieldName === discriminator) continue;
452
- if (variants.every((v) => v.fields.some((f) => f.name === fieldName))) commonFieldNames.add(fieldName);
453
- }
454
- const discriminatorField = extracted.fields.find((f) => f.name === discriminator);
455
- const variantValues = variants.map((v) => v.discriminatorValue).join("\\|");
456
- const topFields = [];
457
- if (discriminatorField) topFields.push({
458
- ...discriminatorField,
459
- placeholder: variantValues
460
- });
461
- for (const fieldName of commonFieldNames) {
462
- const field = extracted.fields.find((f) => f.name === fieldName);
463
- if (field && !field.positional) topFields.push(field);
464
- }
465
- if (topFields.length > 0) sections.push(style === "table" ? renderOptionsTableFromArray(topFields) : renderOptionsListFromArray(topFields));
466
- for (const variant of variants) {
467
- const uniqueFields = variant.fields.filter((f) => f.name !== discriminator && !commonFieldNames.has(f.name) && !f.positional);
468
- if (uniqueFields.length === 0) continue;
469
- const descSuffix = variant.description ? ` ${variant.description}` : "";
470
- const label = `**When \`${discriminator}\` = \`${variant.discriminatorValue}\`:**${descSuffix}`;
471
- const rendered = style === "table" ? renderOptionsTableFromArray(uniqueFields) : renderOptionsListFromArray(uniqueFields);
472
- sections.push(`${label}\n\n${rendered}`);
473
- }
474
- return sections.join("\n\n");
475
- }
476
- /**
477
- * Render options from array as list
478
- */
479
- function renderOptionsListFromArray(options) {
480
- return emitMarkdownList(toOptionRows(options));
481
- }
482
- /**
483
- * Render arguments from array as table
484
- */
485
- function renderArgumentsTableFromArray(args) {
486
- if (args.length === 0) return "";
487
- const lines = [];
488
- lines.push("| Argument | Description | Required |");
489
- lines.push("|----------|-------------|----------|");
490
- for (const arg of args) {
491
- const desc = escapeTableCell$1(arg.description ?? "");
492
- const required = arg.required ? "Yes" : "No";
493
- lines.push(`| \`${arg.name}\` | ${desc} | ${required} |`);
494
- }
495
- return lines.join("\n");
496
- }
497
- /**
498
- * Render arguments from array as list
499
- */
500
- function renderArgumentsListFromArray(args) {
501
- if (args.length === 0) return "";
502
- const lines = [];
503
- for (const arg of args) {
504
- const required = arg.required ? "(required)" : "(optional)";
505
- const desc = arg.description ? ` - ${arg.description}` : "";
506
- lines.push(`- \`${arg.name}\`${desc} ${required}`);
507
- }
508
- return lines.join("\n");
509
- }
510
- /**
511
- * Render subcommands from array as table
512
- */
513
- function renderSubcommandsTableFromArray(subcommands, info, generateAnchors = true) {
514
- if (subcommands.length === 0) return "";
515
- const hasAliases = subcommands.some((s) => s.aliases && s.aliases.length > 0);
516
- const lines = [];
517
- if (hasAliases) {
518
- lines.push("| Command | Aliases | Description |");
519
- lines.push("|---------|---------|-------------|");
520
- } else {
521
- lines.push("| Command | Description |");
522
- lines.push("|---------|-------------|");
523
- }
524
- const currentFile = info.filePath;
525
- const fileMap = info.fileMap;
526
- for (const sub of subcommands) {
527
- const fullName = sub.fullPath.join(" ");
528
- const desc = escapeTableCell$1(sub.description ?? "");
529
- const subCommandPath = sub.fullPath.join(" ");
530
- const aliasCell = hasAliases ? sub.aliases && sub.aliases.length > 0 ? sub.aliases.map((a) => `\`${escapeTableCell$1(a)}\``).join(", ") : "-" : "";
531
- let cmdCell;
532
- if (generateAnchors) {
533
- const anchor = generateAnchor$1(sub.fullPath);
534
- const hasSubFile = fileMap !== void 0 && Object.prototype.hasOwnProperty.call(fileMap, subCommandPath);
535
- const subFile = hasSubFile ? fileMap[subCommandPath] : void 0;
536
- if (currentFile && subFile && currentFile !== subFile) cmdCell = `[\`${fullName}\`](${getRelativePath(currentFile, subFile)}#${anchor})`;
537
- else if (fileMap && !hasSubFile) cmdCell = `\`${fullName}\``;
538
- else cmdCell = `[\`${fullName}\`](#${anchor})`;
539
- } else cmdCell = `\`${fullName}\``;
540
- if (hasAliases) lines.push(`| ${cmdCell} | ${aliasCell} | ${desc} |`);
541
- else lines.push(`| ${cmdCell} | ${desc} |`);
542
- }
543
- return lines.join("\n");
544
- }
545
- /**
546
- * Render examples as markdown
547
- *
548
- * @example
549
- * **Basic usage**
550
- *
551
- * ```bash
552
- * $ greet World
553
- * ```
554
- *
555
- * Output:
556
- * ```
557
- * Hello, World!
558
- * ```
559
- */
560
- function renderExamplesDefault(examples, results, opts) {
561
- if (examples.length === 0) return "";
562
- const showOutput = opts?.showOutput ?? true;
563
- const prefix = opts?.commandPrefix ? `${opts.commandPrefix} ` : "";
564
- const lines = [];
565
- for (let i = 0; i < examples.length; i++) {
566
- const example = examples[i];
567
- if (!example) continue;
568
- const result = results?.[i];
569
- lines.push(`**${example.desc}**`);
570
- lines.push("");
571
- lines.push("```bash");
572
- lines.push(`$ ${prefix}${example.cmd}`);
573
- if (showOutput) {
574
- if (result) {
575
- if (result.stdout) lines.push(result.stdout);
576
- if (result.stderr) lines.push(`[stderr] ${result.stderr}`);
577
- } else if (example.output) lines.push(example.output);
578
- }
579
- lines.push("```");
580
- lines.push("");
581
- }
582
- while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
583
- return lines.join("\n");
584
- }
585
- /**
586
- * Wrap content with section markers
587
- */
588
- function wrapWithMarker(type, scope, content) {
589
- return `${sectionStartMarker(type, scope)}\n${content}\n${sectionEndMarker(type, scope)}`;
590
- }
591
- /**
592
- * Generate a "See Global Options" link for subcommand documentation.
593
- * Returns null for root command or when no global options exist.
594
- */
595
- function getGlobalOptionsLink(info) {
596
- if (!info.hasGlobalOptions || info.commandPath === "") return null;
597
- return `See [Global Options](${info.rootDocPath && info.filePath && info.filePath !== info.rootDocPath ? `${getRelativePath(info.filePath, info.rootDocPath)}#global-options` : "#global-options"}) for options available to all commands.`;
598
- }
599
- function createCommandRenderer(options = {}) {
600
- const { headingLevel = 1, optionStyle = "table", generateAnchors = true, includeSubcommandDetails = true, markerless = false, renderDescription: customRenderDescription, renderUsage: customRenderUsage, renderArguments: customRenderArguments, renderOptions: customRenderOptions, renderSubcommands: customRenderSubcommands, renderNotes: customRenderNotes, renderFooter: customRenderFooter, renderExamples: customRenderExamples } = options;
601
- const wrap = markerless ? (_type, _scope, content) => content : wrapWithMarker;
602
- return (info) => {
603
- const sections = [];
604
- const scope = info.commandPath;
605
- const effectiveLevel = Math.min(headingLevel + (info.depth - 1), 6);
606
- const h = "#".repeat(effectiveLevel);
607
- const title = info.commandPath || info.name;
608
- sections.push(wrap("heading", scope, `${h} ${title}`));
609
- {
610
- const parts = [];
611
- if (info.description) parts.push(info.description);
612
- if (info.aliases && info.aliases.length > 0) parts.push(`**Aliases:** ${info.aliases.map((a) => `\`${a}\``).join(", ")}`);
613
- if (parts.length > 0) {
614
- const context = {
615
- content: parts.join("\n\n"),
616
- heading: "",
617
- info
618
- };
619
- const content = customRenderDescription ? customRenderDescription(context) : context.content;
620
- if (content) sections.push(wrap("description", scope, content));
621
- }
622
- }
623
- {
624
- const context = {
625
- content: `**Usage**\n\n\`\`\`\n${renderUsage(info)}\n\`\`\``,
626
- heading: "**Usage**",
627
- info
628
- };
629
- const content = customRenderUsage ? customRenderUsage(context) : context.content;
630
- if (content) sections.push(wrap("usage", scope, content));
631
- }
632
- if (info.positionalArgs.length > 0) {
633
- const renderArgs = (args, opts) => {
634
- const style = opts?.style ?? optionStyle;
635
- const withHeading = opts?.withHeading ?? true;
636
- const content = style === "table" ? renderArgumentsTableFromArray(args) : renderArgumentsListFromArray(args);
637
- return withHeading ? `**Arguments**\n\n${content}` : content;
638
- };
639
- const context = {
640
- args: info.positionalArgs,
641
- render: renderArgs,
642
- heading: "**Arguments**",
643
- info
644
- };
645
- const content = customRenderArguments ? customRenderArguments(context) : renderArgs(context.args);
646
- if (content) sections.push(wrap("arguments", scope, content));
647
- }
648
- if (info.options.length > 0) {
649
- const renderOpts = (opts, renderOpts) => {
650
- const style = renderOpts?.style ?? optionStyle;
651
- const withHeading = renderOpts?.withHeading ?? true;
652
- const extracted = info.extracted;
653
- let content;
654
- if (extracted && (extracted.schemaType === "union" || extracted.schemaType === "xor") && extracted.unionOptions) content = renderUnionOptionsMarkdown(extracted, style);
655
- else if (extracted && extracted.schemaType === "discriminatedUnion" && extracted.discriminator) content = renderDiscriminatedUnionOptionsMarkdown(extracted, style);
656
- else content = style === "table" ? renderOptionsTableFromArray(opts) : renderOptionsListFromArray(opts);
657
- return withHeading ? `**Options**\n\n${content}` : content;
658
- };
659
- const context = {
660
- options: info.options,
661
- render: renderOpts,
662
- heading: "**Options**",
663
- info
664
- };
665
- const content = customRenderOptions ? customRenderOptions(context) : renderOpts(context.options);
666
- if (content) sections.push(wrap("options", scope, content));
667
- }
668
- {
669
- const globalLink = getGlobalOptionsLink(info);
670
- if (globalLink) sections.push(wrap("global-options-link", scope, globalLink));
671
- }
672
- if (info.subCommands.length > 0) {
673
- const effectiveAnchors = generateAnchors && includeSubcommandDetails;
674
- const renderSubs = (subs, opts) => {
675
- const anchors = opts?.generateAnchors ?? effectiveAnchors;
676
- const withHeading = opts?.withHeading ?? true;
677
- const content = renderSubcommandsTableFromArray(subs, info, anchors);
678
- return withHeading ? `**Commands**\n\n${content}` : content;
679
- };
680
- const context = {
681
- subcommands: info.subCommands,
682
- render: renderSubs,
683
- heading: "**Commands**",
684
- info
685
- };
686
- const content = customRenderSubcommands ? customRenderSubcommands(context) : renderSubs(context.subcommands);
687
- if (content) sections.push(wrap("subcommands", scope, content));
688
- }
689
- if (info.examples && info.examples.length > 0) {
690
- const renderEx = (examples, results, opts) => {
691
- const withHeading = opts?.withHeading ?? true;
692
- const content = renderExamplesDefault(examples, results, {
693
- commandPrefix: info.fullCommandPath,
694
- ...opts
695
- });
696
- return withHeading ? `**Examples**\n\n${content}` : content;
697
- };
698
- const context = {
699
- examples: info.examples,
700
- results: info.exampleResults,
701
- render: renderEx,
702
- heading: "**Examples**",
703
- info
704
- };
705
- const content = customRenderExamples ? customRenderExamples(context) : renderEx(context.examples, context.results);
706
- if (content) sections.push(wrap("examples", scope, content));
707
- }
708
- if (info.notes) {
709
- const context = {
710
- content: `**Notes**\n\n${info.notes}`,
711
- heading: "**Notes**",
712
- info
713
- };
714
- const content = customRenderNotes ? customRenderNotes(context) : context.content;
715
- if (content) sections.push(wrap("notes", scope, content));
716
- }
717
- {
718
- const context = {
719
- content: "",
720
- heading: "",
721
- info
722
- };
723
- const content = customRenderFooter ? customRenderFooter(context) : context.content;
724
- if (content) sections.push(content);
725
- }
726
- return sections.join("\n\n") + "\n";
727
- };
728
- }
729
- /**
730
- * Default renderers presets
731
- */
732
- const defaultRenderers = {
733
- /** Standard command documentation */
734
- command: (options) => createCommandRenderer(options),
735
- /** Table style options (default) */
736
- tableStyle: createCommandRenderer({ optionStyle: "table" }),
737
- /** List style options */
738
- listStyle: createCommandRenderer({ optionStyle: "list" })
739
- };
740
-
741
- //#endregion
742
- //#region src/docs/doc-comparator.ts
743
- /**
744
- * Compare generated content with existing file
745
- */
746
- function compareWithExisting(generatedContent, filePath) {
747
- const absolutePath = path$1.resolve(filePath);
748
- if (!fs.existsSync(absolutePath)) return {
749
- match: false,
750
- fileExists: false
751
- };
752
- const existingContent = fs.readFileSync(absolutePath, "utf-8");
753
- if (generatedContent === existingContent) return {
754
- match: true,
755
- fileExists: true
756
- };
757
- return {
758
- match: false,
759
- diff: formatDiff(existingContent, generatedContent),
760
- fileExists: true
761
- };
762
- }
763
- /**
764
- * Format diff between two strings in unified diff format
765
- */
766
- function formatDiff(expected, actual) {
767
- const expectedLines = expected.split("\n");
768
- const actualLines = actual.split("\n");
769
- const result = [];
770
- result.push("--- existing");
771
- result.push("+++ generated");
772
- result.push("");
773
- const maxLines = Math.max(expectedLines.length, actualLines.length);
774
- let inChunk = false;
775
- let chunkStart = 0;
776
- const chunk = [];
777
- const flushChunk = () => {
778
- if (chunk.length > 0) {
779
- result.push(`@@ -${chunkStart + 1},${chunk.length} @@`);
780
- result.push(...chunk);
781
- chunk.length = 0;
782
- }
783
- inChunk = false;
784
- };
785
- for (let i = 0; i < maxLines; i++) {
786
- const expectedLine = expectedLines[i];
787
- const actualLine = actualLines[i];
788
- if (expectedLine === actualLine) {
789
- if (inChunk) {
790
- chunk.push(` ${expectedLine ?? ""}`);
791
- const lastChangeIndex = chunk.findIndex((line, idx) => (line.startsWith("-") || line.startsWith("+")) && chunk.slice(idx + 1).every((l) => l.startsWith(" ")));
792
- if (lastChangeIndex !== -1 && chunk.length - lastChangeIndex > 3) flushChunk();
793
- }
794
- } else {
795
- if (!inChunk) {
796
- inChunk = true;
797
- chunkStart = i;
798
- const contextStart = Math.max(0, i - 3);
799
- for (let j = contextStart; j < i; j++) chunk.push(` ${expectedLines[j] ?? ""}`);
800
- }
801
- if (expectedLine !== void 0 && (actualLine === void 0 || expectedLine !== actualLine)) chunk.push(`-${expectedLine}`);
802
- if (actualLine !== void 0 && (expectedLine === void 0 || expectedLine !== actualLine)) chunk.push(`+${actualLine}`);
803
- }
804
- }
805
- flushChunk();
806
- return result.join("\n");
807
- }
808
- /**
809
- * Write content to file, creating directories if needed
810
- */
811
- function writeFile(filePath, content) {
812
- const absolutePath = path$1.resolve(filePath);
813
- const dir = path$1.dirname(absolutePath);
814
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
815
- fs.writeFileSync(absolutePath, content, "utf-8");
816
- }
817
- /**
818
- * Read file content if it exists
819
- * Returns null if file does not exist
820
- */
821
- function readFile(filePath) {
822
- const absolutePath = path$1.resolve(filePath);
823
- if (!fs.existsSync(absolutePath)) return null;
824
- return fs.readFileSync(absolutePath, "utf-8");
825
- }
826
- /**
827
- * Delete file if it exists
828
- * @param filePath - Path to the file to delete
829
- * @param fileSystem - Optional fs implementation (useful when fs is mocked)
830
- */
831
- function deleteFile(filePath, fileSystem = fs) {
832
- const absolutePath = path$1.resolve(filePath);
833
- if (fileSystem.existsSync(absolutePath)) fileSystem.unlinkSync(absolutePath);
834
- }
835
-
836
- //#endregion
837
- //#region src/docs/doc-generator.ts
838
- /**
839
- * Build CommandInfo from a command
840
- */
841
- async function buildCommandInfo(command, rootName, commandPath = []) {
842
- const extracted = getExtractedFields(command);
843
- const positionalArgs = extracted?.fields.filter((f) => f.positional) ?? [];
844
- const options = extracted?.fields.filter((f) => !f.positional) ?? [];
845
- const subCommands = [];
846
- if (command.subCommands) for (const [name, subCmd] of Object.entries(command.subCommands)) {
847
- const resolved = await resolveLazyCommand(subCmd);
848
- const fullPath = [...commandPath, name];
849
- subCommands.push({
850
- name,
851
- description: resolved.description,
852
- aliases: resolved.aliases,
853
- fullPath
854
- });
855
- }
856
- return {
857
- name: command.name ?? "",
858
- description: command.description,
859
- aliases: command.aliases,
860
- fullCommandPath: commandPath.length > 0 ? `${rootName} ${commandPath.join(" ")}` : rootName,
861
- commandPath: commandPath.join(" "),
862
- depth: commandPath.length + 1,
863
- positionalArgs,
864
- options,
865
- subCommands,
866
- extracted,
867
- command,
868
- notes: command.notes,
869
- examples: command.examples
870
- };
871
- }
872
- /**
873
- * Collect all commands with their paths
874
- * Returns a map of command path -> CommandInfo
875
- */
876
- async function collectAllCommands(command, rootName) {
877
- const root = rootName ?? command.name ?? "command";
878
- const result = /* @__PURE__ */ new Map();
879
- async function traverse(cmd, path) {
880
- const info = await buildCommandInfo(cmd, root, path);
881
- const pathKey = path.join(" ");
882
- result.set(pathKey, info);
883
- if (cmd.subCommands) for (const [name, subCmd] of Object.entries(cmd.subCommands)) await traverse(await resolveLazyCommand(subCmd), [...path, name]);
884
- }
885
- await traverse(command, []);
886
- return result;
887
- }
888
-
889
- //#endregion
890
- //#region src/docs/example-executor.ts
891
- /**
892
- * Execute examples for a command and capture output
893
- *
894
- * @param examples - Examples to execute
895
- * @param config - Execution configuration (mock setup/cleanup)
896
- * @param rootCommand - Root command to execute against
897
- * @param commandPath - Command path for subcommands (e.g., ["config", "get"])
898
- * @returns Array of execution results with captured stdout/stderr
899
- */
900
- async function executeExamples(examples, config, rootCommand, commandPath = []) {
901
- const results = [];
902
- if (config.mock) await config.mock();
903
- try {
904
- for (const example of examples) {
905
- const result = await executeSingleExample(example, rootCommand, commandPath);
906
- results.push(result);
907
- }
908
- } finally {
909
- if (config.cleanup) await config.cleanup();
910
- }
911
- return results;
912
- }
913
- /**
914
- * Execute a single example and capture output
915
- */
916
- async function executeSingleExample(example, rootCommand, commandPath) {
917
- const exampleArgs = parseExampleCmd(example.cmd);
918
- const argv = [...commandPath, ...exampleArgs];
919
- const collector = createLogCollector({ passthrough: false });
920
- collector.start();
921
- let success = true;
922
- try {
923
- const { runCommand } = await import("../runner-BGs_QMJM.js");
924
- const result = await runCommand(rootCommand, argv);
925
- success = result.success;
926
- if (!result.success && result.error) console.error(result.error.message);
927
- } catch (error) {
928
- success = false;
929
- console.error(error instanceof Error ? error.message : String(error));
930
- } finally {
931
- collector.stop();
932
- }
933
- const logs = collector.getLogs();
934
- const stdout = logs.entries.filter((e) => e.stream === "stdout").map((e) => e.message).join("\n");
935
- const stderr = logs.entries.filter((e) => e.stream === "stderr").map((e) => e.message).join("\n");
936
- return {
937
- cmd: example.cmd,
938
- desc: example.desc,
939
- expectedOutput: example.output,
940
- stdout,
941
- stderr,
942
- success
943
- };
944
- }
945
- /**
946
- * Parse example command string into argv array
947
- * Handles quoted strings (single and double quotes)
948
- *
949
- * @example
950
- * parseExampleCmd('World') // ['World']
951
- * parseExampleCmd('--name "John Doe"') // ['--name', 'John Doe']
952
- * parseExampleCmd("--greeting 'Hello World'") // ['--greeting', 'Hello World']
953
- */
954
- function parseExampleCmd(cmd) {
955
- const args = [];
956
- let current = "";
957
- let inQuote = false;
958
- let quoteChar = "";
959
- for (let i = 0; i < cmd.length; i++) {
960
- const char = cmd[i];
961
- if ((char === "\"" || char === "'") && !inQuote) {
962
- inQuote = true;
963
- quoteChar = char;
964
- } else if (char === quoteChar && inQuote) {
965
- inQuote = false;
966
- quoteChar = "";
967
- } else if (char === " " && !inQuote) {
968
- if (current) {
969
- args.push(current);
970
- current = "";
971
- }
972
- } else current += char;
973
- }
974
- if (current) args.push(current);
975
- return args;
976
- }
977
-
978
- //#endregion
979
- //#region src/docs/render-args.ts
980
- /**
981
- * Extract ResolvedFieldMeta array from ArgsShape
982
- *
983
- * This converts a raw args shape (like `commonArgs`) into the
984
- * ResolvedFieldMeta format used by politty's rendering functions.
985
- */
986
- function extractArgsFields(args) {
987
- return extractFields(z.object(args)).fields;
988
- }
989
- /**
990
- * Render args definition as a markdown options table
991
- *
992
- * This function takes raw args definitions (like `commonArgs`) and
993
- * renders them as a markdown table suitable for documentation.
994
- *
995
- * @example
996
- * import { renderArgsTable } from "politty/docs";
997
- * import { commonArgs, workspaceArgs } from "./args";
998
- *
999
- * const table = renderArgsTable({
1000
- * ...commonArgs,
1001
- * ...workspaceArgs,
1002
- * });
1003
- * // | Option | Alias | Description | Default |
1004
- * // |--------|-------|-------------|---------|
1005
- * // | `--env-file <ENV_FILE>` | `-e` | Path to environment file | - |
1006
- * // ...
1007
- *
1008
- * @param args - Args shape (Record of string keys to Zod schemas with arg() metadata)
1009
- * @param options - Rendering options
1010
- * @returns Rendered markdown table string
1011
- */
1012
- function renderArgsTable(args, options) {
1013
- const optionFields = extractArgsFields(args).filter((f) => !f.positional);
1014
- if (optionFields.length === 0) return "";
1015
- return emitMarkdownTable(toOptionRows(optionFields), options?.columns);
1016
- }
1017
-
1018
- //#endregion
1019
- //#region src/docs/render-index.ts
1020
- /**
1021
- * Escape markdown special characters in table cells
1022
- */
1023
- function escapeTableCell(str) {
1024
- return str.replace(/\|/g, "\\|").replace(/\n/g, " ");
1025
- }
1026
- /**
1027
- * Generate anchor from command path
1028
- */
1029
- function generateAnchor(commandPath) {
1030
- return commandPath.replace(/\s+/g, "-").toLowerCase();
1031
- }
1032
- /**
1033
- * Check if a command is a leaf (has no subcommands)
1034
- */
1035
- function isLeafCommand(info) {
1036
- return info.subCommands.length === 0;
1037
- }
1038
- function isSubcommandOf$1(childPath, parentPath) {
1039
- if (childPath === parentPath) return true;
1040
- if (parentPath === "") return childPath !== "";
1041
- return childPath.startsWith(parentPath + " ");
1042
- }
1043
- /**
1044
- * Expand commands to include their subcommands
1045
- * If a command has subcommands, recursively find all commands under it
1046
- *
1047
- * @param commandPaths - Command paths to expand
1048
- * @param allCommands - Map of all available commands
1049
- * @param leafOnly - If true, only include leaf commands; if false, include all commands
1050
- */
1051
- function expandCommands(commandPaths, allCommands, leafOnly) {
1052
- const result = [];
1053
- for (const cmdPath of commandPaths) {
1054
- const info = allCommands.get(cmdPath);
1055
- if (!info) continue;
1056
- if (isLeafCommand(info)) result.push(cmdPath);
1057
- else for (const [path, pathInfo] of allCommands) if (cmdPath === "" ? path.length > 0 : path.startsWith(cmdPath + " ") || path === cmdPath) {
1058
- if (isLeafCommand(pathInfo) || !leafOnly) result.push(path);
1059
- }
1060
- }
1061
- return result;
1062
- }
1063
- /**
1064
- * Render a single category section
1065
- */
1066
- function renderCategory(category, allCommands, headingLevel, leafOnly) {
1067
- const h = "#".repeat(headingLevel);
1068
- const lines = [];
1069
- lines.push(`${h} [${category.title}](${category.docPath})`);
1070
- lines.push("");
1071
- lines.push(category.description);
1072
- lines.push("");
1073
- const commandPaths = category.noExpand ? category.commands : expandCommands(category.commands, allCommands, leafOnly);
1074
- let visibleCommandPaths = commandPaths;
1075
- const fallbackCommandPaths = /* @__PURE__ */ new Set();
1076
- if (category.allowedCommands) {
1077
- const allowed = new Set(category.allowedCommands);
1078
- visibleCommandPaths = commandPaths.filter((cmdPath) => allowed.has(cmdPath));
1079
- for (const configuredPath of category.commands) if (allowed.has(configuredPath) && !visibleCommandPaths.some((cmdPath) => isSubcommandOf$1(cmdPath, configuredPath))) {
1080
- visibleCommandPaths.push(configuredPath);
1081
- fallbackCommandPaths.add(configuredPath);
1082
- }
1083
- }
1084
- lines.push("| Command | Description |");
1085
- lines.push("|---------|-------------|");
1086
- for (const cmdPath of visibleCommandPaths) {
1087
- const info = allCommands.get(cmdPath);
1088
- if (!info) continue;
1089
- if (!category.noExpand && leafOnly && !fallbackCommandPaths.has(cmdPath) && !isLeafCommand(info)) continue;
1090
- const displayName = cmdPath || info.name;
1091
- const anchor = generateAnchor(displayName);
1092
- const desc = escapeTableCell(info.description ?? "");
1093
- lines.push(`| [${displayName}](${category.docPath}#${anchor}) | ${desc} |`);
1094
- }
1095
- return lines.join("\n");
1096
- }
1097
- /**
1098
- * Render command index from categories
1099
- *
1100
- * Generates a category-based index of commands with links to documentation.
1101
- *
1102
- * @example
1103
- * const categories: CommandCategory[] = [
1104
- * {
1105
- * title: "Application Commands",
1106
- * description: "Commands for managing applications.",
1107
- * commands: ["init", "generate", "apply"],
1108
- * docPath: "./cli/application.md",
1109
- * },
1110
- * ];
1111
- *
1112
- * const index = await renderCommandIndex(mainCommand, categories);
1113
- * // ### [Application Commands](./cli/application.md)
1114
- * //
1115
- * // Commands for managing applications.
1116
- * //
1117
- * // | Command | Description |
1118
- * // |---------|-------------|
1119
- * // | [init](./cli/application.md#init) | Initialize a project |
1120
- * // ...
1121
- *
1122
- * @param command - Root command to extract command information from
1123
- * @param categories - Category definitions for grouping commands
1124
- * @param options - Rendering options
1125
- * @returns Rendered markdown string
1126
- */
1127
- async function renderCommandIndex(command, categories, options) {
1128
- const headingLevel = options?.headingLevel ?? 3;
1129
- const leafOnly = options?.leafOnly ?? true;
1130
- const allCommands = await collectAllCommands(command);
1131
- const sections = [];
1132
- for (const category of categories) {
1133
- const section = renderCategory(category, allCommands, headingLevel, leafOnly);
1134
- sections.push(section);
1135
- }
1136
- return sections.join("\n\n");
1137
- }
1138
-
1139
- //#endregion
1140
- //#region src/docs/golden-test.ts
1141
- /**
1142
- * Apply formatter to content if provided
1143
- * Supports both sync and async formatters
1144
- */
1145
- async function applyFormatter(content, formatter) {
1146
- if (!formatter) return content;
1147
- const formatted = await formatter(content);
1148
- if (!content.endsWith("\n") && formatted.endsWith("\n")) return formatted.slice(0, -1);
1149
- return formatted;
1150
- }
1151
- function isTruthyEnv(envKey) {
1152
- const value = process.env[envKey];
1153
- return value === "true" || value === "1";
1154
- }
1155
- function extractYamlFrontMatter(content) {
1156
- const lines = content.split(/\r?\n/);
1157
- if (lines[0] !== "---") return null;
1158
- const frontMatterLines = [];
1159
- for (let i = 1; i < lines.length; i++) {
1160
- const line = lines[i];
1161
- if (line === "---" || line === "...") return frontMatterLines.join("\n");
1162
- frontMatterLines.push(line ?? "");
1163
- }
1164
- return null;
1165
- }
1166
- function stripPolittyFrontMatterForOutput(content) {
1167
- const lineEnding = detectLineEnding(content);
1168
- const lines = content.split(/\r?\n/);
1169
- if (lines[0] !== "---") return content;
1170
- let endIndex = -1;
1171
- for (let i = 1; i < lines.length; i++) {
1172
- const line = lines[i];
1173
- if (line === "---" || line === "...") {
1174
- endIndex = i;
1175
- break;
1176
- }
1177
- }
1178
- if (endIndex === -1) return content;
1179
- const frontMatterLines = lines.slice(1, endIndex);
1180
- const keptFrontMatterLines = [];
1181
- for (let i = 0; i < frontMatterLines.length; i++) {
1182
- const line = frontMatterLines[i] ?? "";
1183
- if (!/^politty\s*:\s*(.*)$/.test(line)) {
1184
- keptFrontMatterLines.push(line);
1185
- continue;
1186
- }
1187
- while (i + 1 < frontMatterLines.length) {
1188
- const nextLine = frontMatterLines[i + 1] ?? "";
1189
- if (nextLine.trim() !== "" && !nextLine.startsWith(" ") && !nextLine.startsWith(" ")) break;
1190
- i++;
1191
- }
1192
- }
1193
- const bodyLines = lines.slice(endIndex + 1);
1194
- if (!keptFrontMatterLines.some((line) => line.trim() !== "")) return bodyLines.join(lineEnding).replace(new RegExp(`^${lineEnding}`), "");
1195
- return [
1196
- "---",
1197
- ...keptFrontMatterLines,
1198
- lines[endIndex] ?? "---",
1199
- ...bodyLines
1200
- ].join(lineEnding);
1201
- }
1202
- function stripYamlScalarQuotes(value) {
1203
- const trimmed = value.trim();
1204
- if (trimmed.length >= 2 && (trimmed.startsWith("\"") && trimmed.endsWith("\"") || trimmed.startsWith("'") && trimmed.endsWith("'"))) return trimmed.slice(1, -1);
1205
- return trimmed;
1206
- }
1207
- function normalizeTemplatePlaceholderKey(value) {
1208
- let normalized = stripYamlScalarQuotes(value);
1209
- if (normalized === "") return null;
1210
- const fullPlaceholder = normalized.match(/^\{\{politty:([^{}]*)\}\}$/);
1211
- if (fullPlaceholder) normalized = fullPlaceholder[1] ?? "";
1212
- else if (normalized.startsWith("politty:")) normalized = normalized.slice(8);
1213
- return normalized === "" ? null : normalized;
1214
- }
1215
- function templatePlaceholderKey(placeholder) {
1216
- return placeholder.slice(2, -2).slice(8);
1217
- }
1218
- function splitFrontMatterListValue(value) {
1219
- const trimmed = value.trim();
1220
- if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return [trimmed];
1221
- return trimmed.slice(1, -1).split(",").map((item) => item.trim()).filter((item) => item.length > 0);
1222
- }
1223
- function addTemplatePlaceholderExclusion(exclusions, value) {
1224
- const normalized = normalizeTemplatePlaceholderKey(value);
1225
- if (normalized !== null) exclusions.add(normalized);
1226
- }
1227
- function collectExcludedTemplatePlaceholders(templateContent) {
1228
- const exclusions = /* @__PURE__ */ new Set();
1229
- const frontMatter = extractYamlFrontMatter(templateContent);
1230
- if (frontMatter === null) return exclusions;
1231
- let inPolittyBlock = false;
1232
- let inExcludeList = false;
1233
- let excludeIndent = 0;
1234
- for (const line of frontMatter.split(/\r?\n/)) {
1235
- const trimmed = line.trim();
1236
- if (trimmed === "" || trimmed.startsWith("#")) continue;
1237
- const topLevelPolitty = line.match(/^politty\s*:\s*(.*)$/);
1238
- if (topLevelPolitty) {
1239
- inPolittyBlock = (topLevelPolitty[1]?.trim() ?? "") === "";
1240
- inExcludeList = false;
1241
- continue;
1242
- }
1243
- if (!line.startsWith(" ") && !line.startsWith(" ")) {
1244
- inPolittyBlock = false;
1245
- inExcludeList = false;
1246
- continue;
1247
- }
1248
- if (!inPolittyBlock) continue;
1249
- const excludeEntry = line.match(/^(\s+)(?:exclude|excludes)\s*:\s*(.*)$/);
1250
- if (excludeEntry) {
1251
- const value = excludeEntry[2]?.trim() ?? "";
1252
- if (value === "") {
1253
- inExcludeList = true;
1254
- excludeIndent = excludeEntry[1]?.length ?? 0;
1255
- } else {
1256
- inExcludeList = false;
1257
- for (const item of splitFrontMatterListValue(value)) addTemplatePlaceholderExclusion(exclusions, item);
1258
- }
1259
- continue;
1260
- }
1261
- if (!inExcludeList) continue;
1262
- const listItem = line.match(/^(\s*)-\s*(.+)$/);
1263
- if (!listItem || (listItem[1]?.length ?? 0) <= excludeIndent) {
1264
- inExcludeList = false;
1265
- continue;
1266
- }
1267
- addTemplatePlaceholderExclusion(exclusions, listItem[2] ?? "");
1268
- }
1269
- return exclusions;
1270
- }
1271
- function collectTemplateIndexMetadata(templateContent) {
1272
- const frontMatter = extractYamlFrontMatter(templateContent);
1273
- if (frontMatter === null) return {};
1274
- let inPolittyBlock = false;
1275
- let inIndexBlock = false;
1276
- let indexIndent = 0;
1277
- const metadata = {};
1278
- for (const line of frontMatter.split(/\r?\n/)) {
1279
- const trimmed = line.trim();
1280
- if (trimmed === "" || trimmed.startsWith("#")) continue;
1281
- const topLevelPolitty = line.match(/^politty\s*:\s*(.*)$/);
1282
- if (topLevelPolitty) {
1283
- inPolittyBlock = (topLevelPolitty[1]?.trim() ?? "") === "";
1284
- inIndexBlock = false;
1285
- continue;
1286
- }
1287
- if (!line.startsWith(" ") && !line.startsWith(" ")) {
1288
- inPolittyBlock = false;
1289
- inIndexBlock = false;
1290
- continue;
1291
- }
1292
- if (!inPolittyBlock) continue;
1293
- const indexEntry = line.match(/^(\s+)index\s*:\s*(.*)$/);
1294
- if (indexEntry) {
1295
- inIndexBlock = (indexEntry[2]?.trim() ?? "") === "";
1296
- indexIndent = indexEntry[1]?.length ?? 0;
1297
- continue;
1298
- }
1299
- if (!inIndexBlock) continue;
1300
- if ((line.match(/^(\s*)/)?.[1]?.length ?? 0) <= indexIndent) {
1301
- inIndexBlock = false;
1302
- continue;
1303
- }
1304
- const property = line.match(/^\s+(title|description)\s*:\s*(.+)$/);
1305
- if (!property) continue;
1306
- const key = property[1];
1307
- const value = stripYamlScalarQuotes(property[2] ?? "");
1308
- if (key === "title") metadata.title = value;
1309
- else if (key === "description") metadata.description = value;
1310
- }
1311
- return metadata;
1312
- }
1313
- function createTemplateExclusions(rawKeys) {
1314
- return {
1315
- rawKeys,
1316
- commandScopes: /* @__PURE__ */ new Set(),
1317
- commandSections: /* @__PURE__ */ new Map(),
1318
- globalOptions: false,
1319
- index: false
1320
- };
1321
- }
1322
- function setFileMapEntry(fileMap, commandPath, filePath) {
1323
- Object.defineProperty(fileMap, commandPath, {
1324
- value: filePath,
1325
- enumerable: true,
1326
- configurable: true,
1327
- writable: true
1328
- });
1329
- }
1330
- /**
1331
- * Normalize file mapping entry to FileConfig
1332
- */
1333
- function normalizeFileConfig(config) {
1334
- if (Array.isArray(config)) return { commands: config };
1335
- if (!("commands" in config) || !Array.isArray(config.commands)) throw new Error("Invalid file config: object form must include a \"commands\" array. Use [] to skip generation intentionally.");
1336
- return config;
1337
- }
1338
- /**
1339
- * Check if a command path is a subcommand of another
1340
- */
1341
- function isSubcommandOf(childPath, parentPath) {
1342
- if (parentPath === "") return true;
1343
- if (childPath === parentPath) return true;
1344
- return childPath.startsWith(parentPath + " ");
1345
- }
1346
- /**
1347
- * Check if a pattern contains wildcards
1348
- */
1349
- function containsWildcard(pattern) {
1350
- return pattern.includes("*");
1351
- }
1352
- /**
1353
- * Check if a command path matches a wildcard pattern
1354
- * - `*` matches any single command segment
1355
- * - Pattern segments are space-separated
1356
- *
1357
- * @example
1358
- * matchesWildcard("config get", "* *") // true
1359
- * matchesWildcard("config", "* *") // false
1360
- * matchesWildcard("config get", "config *") // true
1361
- * matchesWildcard("greet", "*") // true
1362
- */
1363
- function matchesWildcard(path, pattern) {
1364
- const pathSegments = path === "" ? [] : path.split(" ");
1365
- const patternSegments = pattern === "" ? [] : pattern.split(" ");
1366
- if (pathSegments.length !== patternSegments.length) return false;
1367
- for (let i = 0; i < patternSegments.length; i++) {
1368
- const patternSeg = patternSegments[i];
1369
- const pathSeg = pathSegments[i];
1370
- if (patternSeg !== "*" && patternSeg !== pathSeg) return false;
1371
- }
1372
- return true;
1373
- }
1374
- /**
1375
- * Expand a wildcard pattern to matching command paths
1376
- */
1377
- function expandWildcardPattern(pattern, allCommands) {
1378
- const matches = [];
1379
- for (const cmdPath of allCommands.keys()) if (matchesWildcard(cmdPath, pattern)) matches.push(cmdPath);
1380
- return matches;
1381
- }
1382
- /**
1383
- * Check if a path matches any ignore pattern (with wildcard support)
1384
- * For wildcard patterns, also ignores subcommands of matched commands
1385
- */
1386
- function matchesIgnorePattern(path, ignorePattern) {
1387
- if (containsWildcard(ignorePattern)) {
1388
- if (matchesWildcard(path, ignorePattern)) return true;
1389
- const pathSegments = path === "" ? [] : path.split(" ");
1390
- const patternSegments = ignorePattern === "" ? [] : ignorePattern.split(" ");
1391
- if (pathSegments.length > patternSegments.length) return matchesWildcard(pathSegments.slice(0, patternSegments.length).join(" "), ignorePattern);
1392
- return false;
1393
- }
1394
- return isSubcommandOf(path, ignorePattern);
1395
- }
1396
- /**
1397
- * Expand command paths to include all subcommands (with wildcard support)
1398
- */
1399
- function expandCommandPaths(commandPaths, allCommands) {
1400
- const expanded = /* @__PURE__ */ new Set();
1401
- const resolved = commandPaths.flatMap((cmdPath) => containsWildcard(cmdPath) ? expandWildcardPattern(cmdPath, allCommands) : [cmdPath]);
1402
- for (const cmdPath of resolved) for (const existingPath of allCommands.keys()) if (isSubcommandOf(existingPath, cmdPath)) expanded.add(existingPath);
1403
- return Array.from(expanded);
1404
- }
1405
- /**
1406
- * Filter out ignored commands (with wildcard support)
1407
- */
1408
- function filterIgnoredCommands(commandPaths, ignores) {
1409
- return commandPaths.filter((path) => {
1410
- return !ignores.some((ignorePattern) => matchesIgnorePattern(path, ignorePattern));
1411
- });
1412
- }
1413
- /**
1414
- * Resolve wildcards to direct matches without subcommand expansion.
1415
- * Returns the "top-level" commands for use in CommandCategory.commands,
1416
- * where expandCommands in render-index handles subcommand expansion.
1417
- */
1418
- function resolveTopLevelCommands(specifiedCommands, allCommands) {
1419
- const result = [];
1420
- for (const cmdPath of specifiedCommands) if (containsWildcard(cmdPath)) result.push(...expandWildcardPattern(cmdPath, allCommands));
1421
- else if (allCommands.has(cmdPath)) result.push(cmdPath);
1422
- return result;
1423
- }
1424
- /**
1425
- * Resolve file command configuration to concrete command paths.
1426
- * This applies wildcard/subcommand expansion and ignore filtering.
1427
- */
1428
- function resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores) {
1429
- const fileConfig = normalizeFileConfig(fileConfigRaw);
1430
- const specifiedCommands = fileConfig.commands;
1431
- return {
1432
- fileConfig,
1433
- specifiedCommands,
1434
- commandPaths: filterIgnoredCommands(fileConfig.noExpand ? specifiedCommands.filter((p) => allCommands.has(p)) : expandCommandPaths(specifiedCommands, allCommands), ignores),
1435
- topLevelCommands: filterIgnoredCommands(resolveTopLevelCommands(specifiedCommands, allCommands), ignores)
1436
- };
1437
- }
1438
- /**
1439
- * Validate that there are no conflicts between files and ignores (with wildcard support)
1440
- */
1441
- function validateNoConflicts(filesCommands, ignores, allCommands) {
1442
- const conflicts = [];
1443
- for (const filePattern of filesCommands) {
1444
- const filePaths = containsWildcard(filePattern) ? expandWildcardPattern(filePattern, allCommands) : [filePattern];
1445
- for (const filePath of filePaths) for (const ignorePattern of ignores) if (containsWildcard(ignorePattern)) {
1446
- if (matchesWildcard(filePath, ignorePattern)) conflicts.push(`"${filePath}" is both in files and ignored by "${ignorePattern}"`);
1447
- } else if (filePath === ignorePattern || isSubcommandOf(filePath, ignorePattern)) conflicts.push(`"${filePath}" is both in files and ignored by "${ignorePattern}"`);
1448
- }
1449
- if (conflicts.length > 0) throw new Error(`Conflict between files and ignores:\n - ${conflicts.join("\n - ")}`);
1450
- }
1451
- /**
1452
- * Validate that all ignored paths exist in the command tree (with wildcard support)
1453
- */
1454
- function validateIgnoresExist(ignores, allCommands) {
1455
- const nonExistent = [];
1456
- for (const ignorePattern of ignores) if (containsWildcard(ignorePattern)) {
1457
- if (expandWildcardPattern(ignorePattern, allCommands).length === 0) nonExistent.push(`"${ignorePattern}"`);
1458
- } else if (!allCommands.has(ignorePattern)) nonExistent.push(`"${ignorePattern}"`);
1459
- if (nonExistent.length > 0) throw new Error(`Ignored command paths do not exist: ${nonExistent.join(", ")}`);
1460
- }
1461
- /**
1462
- * Sort command paths in depth-first order while preserving the specified command order
1463
- * Parent commands are immediately followed by their subcommands
1464
- */
1465
- function sortDepthFirst(commandPaths, specifiedOrder) {
1466
- const pathSet = new Set(commandPaths);
1467
- const topLevelPaths = specifiedOrder.filter((cmd) => pathSet.has(cmd));
1468
- for (const path of commandPaths) if ((path === "" ? 0 : path.split(" ").length) === 1 && !topLevelPaths.includes(path)) topLevelPaths.push(path);
1469
- const result = [];
1470
- const visited = /* @__PURE__ */ new Set();
1471
- function addWithChildren(cmdPath) {
1472
- if (visited.has(cmdPath) || !pathSet.has(cmdPath)) return;
1473
- visited.add(cmdPath);
1474
- result.push(cmdPath);
1475
- const children = commandPaths.filter((p) => {
1476
- if (p === cmdPath || visited.has(p)) return false;
1477
- if (cmdPath === "") return p.split(" ").length === 1;
1478
- return p.startsWith(cmdPath + " ") && p.split(" ").length === cmdPath.split(" ").length + 1;
1479
- }).sort((a, b) => a.localeCompare(b));
1480
- for (const child of children) addWithChildren(child);
1481
- }
1482
- for (const topLevel of topLevelPaths) addWithChildren(topLevel);
1483
- for (const path of commandPaths) if (!visited.has(path)) result.push(path);
1484
- return result;
1485
- }
1486
- function generateFileHeader(fileConfig) {
1487
- if (!fileConfig.title && !fileConfig.description) return null;
1488
- const parts = [];
1489
- if (fileConfig.title) {
1490
- const heading = "#".repeat(fileConfig.headingLevel ?? 1);
1491
- parts.push(`${heading} ${fileConfig.title}`);
1492
- }
1493
- if (fileConfig.description) {
1494
- parts.push("");
1495
- parts.push(fileConfig.description);
1496
- }
1497
- parts.push("");
1498
- return parts.join("\n");
1499
- }
1500
- /**
1501
- * Extract a leading file header (title and optional description paragraph)
1502
- */
1503
- function extractFileHeader(content) {
1504
- if (!/^#{1,6} /.test(content)) return null;
1505
- const titleEnd = content.indexOf("\n");
1506
- if (titleEnd === -1) return content;
1507
- let cursor = titleEnd + 1;
1508
- if (content[cursor] === "\n") cursor += 1;
1509
- while (cursor < content.length) {
1510
- const lineEnd = content.indexOf("\n", cursor);
1511
- const line = lineEnd === -1 ? content.slice(cursor) : content.slice(cursor, lineEnd);
1512
- if (line.length === 0 || /^#{1,6}\s/.test(line) || line.startsWith("<!-- politty:")) break;
1513
- cursor = lineEnd === -1 ? content.length : lineEnd + 1;
1514
- }
1515
- return content.slice(0, cursor);
1516
- }
1517
- /**
1518
- * Validate and optionally update configured file header
1519
- */
1520
- function processFileHeader(existingContent, fileConfig, updateMode) {
1521
- const generatedHeader = generateFileHeader(fileConfig);
1522
- if (!generatedHeader) return {
1523
- content: existingContent,
1524
- hasError: false,
1525
- wasUpdated: false
1526
- };
1527
- if (existingContent.startsWith(generatedHeader)) return {
1528
- content: existingContent,
1529
- hasError: false,
1530
- wasUpdated: false
1531
- };
1532
- const existingHeader = extractFileHeader(existingContent) ?? "";
1533
- if (!updateMode) return {
1534
- content: existingContent,
1535
- diff: formatDiff(existingHeader, generatedHeader),
1536
- hasError: true,
1537
- wasUpdated: false
1538
- };
1539
- return {
1540
- content: `${generatedHeader}${(existingHeader ? existingContent.slice(existingHeader.length) : existingContent).replace(/^\n+/, "")}`,
1541
- hasError: false,
1542
- wasUpdated: true
1543
- };
1544
- }
1545
- function formatCommandPath(commandPath) {
1546
- return commandPath === "" ? "<root>" : commandPath;
1547
- }
1548
- /**
1549
- * Extract a section marker's content from document content.
1550
- * Returns the content between start and end markers (including markers).
1551
- */
1552
- function extractSectionMarker(content, type, scope) {
1553
- return extractMarkerSection(content, sectionStartMarker(type, scope), sectionEndMarker(type, scope));
1554
- }
1555
- /**
1556
- * Replace a section marker's content in document content.
1557
- * Returns updated content, or null if marker not found.
1558
- */
1559
- function replaceSectionMarker(content, type, scope, newContent) {
1560
- return replaceMarkerSection(content, sectionStartMarker(type, scope), sectionEndMarker(type, scope), newContent);
1561
- }
1562
- /**
1563
- * Insert a new section marker into existing content at the correct position
1564
- * relative to other section markers for the same command, based on SECTION_TYPES order.
1565
- * Preserves any existing content between adjacent markers by wrapping it with the new markers
1566
- * instead of replacing it with generated content.
1567
- * @throws If no adjacent marker is found (unreachable when at least one marker exists for the command)
1568
- */
1569
- function insertSectionMarkerAtOrder(content, type, scope, generatedSection) {
1570
- const typeIndex = SECTION_TYPES.indexOf(type);
1571
- const startMarker = sectionStartMarker(type, scope);
1572
- const endMarker = sectionEndMarker(type, scope);
1573
- let prevBoundary = null;
1574
- for (let i = typeIndex - 1; i >= 0; i--) {
1575
- const prevType = SECTION_TYPES[i];
1576
- const prevEnd = sectionEndMarker(prevType, scope);
1577
- const prevEndIdx = content.indexOf(prevEnd);
1578
- if (prevEndIdx !== -1) {
1579
- prevBoundary = prevEndIdx + prevEnd.length;
1580
- break;
1581
- }
1582
- }
1583
- let nextBoundary = null;
1584
- for (let i = typeIndex + 1; i < SECTION_TYPES.length; i++) {
1585
- const nextType = SECTION_TYPES[i];
1586
- const nextStart = sectionStartMarker(nextType, scope);
1587
- const nextStartIdx = content.indexOf(nextStart);
1588
- if (nextStartIdx !== -1) {
1589
- nextBoundary = nextStartIdx;
1590
- break;
1591
- }
1592
- }
1593
- if (prevBoundary != null && nextBoundary != null) {
1594
- const wrapped = startMarker + content.slice(prevBoundary, nextBoundary).replace(/^\n+/, "\n").replace(/\n+$/, "\n") + endMarker;
1595
- return content.slice(0, prevBoundary) + "\n\n" + wrapped + "\n\n" + content.slice(nextBoundary);
1596
- }
1597
- if (prevBoundary != null) {
1598
- let afterPos = prevBoundary;
1599
- while (afterPos < content.length && content[afterPos] === "\n") afterPos++;
1600
- return content.slice(0, prevBoundary) + "\n\n" + generatedSection + (afterPos < content.length ? "\n\n" : "\n") + content.slice(afterPos);
1601
- }
1602
- if (nextBoundary != null) {
1603
- let beforePos = nextBoundary;
1604
- while (beforePos > 0 && content[beforePos - 1] === "\n") beforePos--;
1605
- const prefix = beforePos === 0 ? "" : "\n\n";
1606
- return content.slice(0, beforePos) + prefix + generatedSection + "\n\n" + content.slice(nextBoundary);
1607
- }
1608
- throw new Error(`No insertion point found for section "${type}" (scope="${scope}"). This should be unreachable when at least one marker exists for the command.`);
1609
- }
1610
- /**
1611
- * Collect all section types that have markers for a given command path.
1612
- */
1613
- function collectSectionMarkers(content, commandPath) {
1614
- const found = [];
1615
- for (const type of SECTION_TYPES) if (extractSectionMarker(content, type, commandPath) !== null) found.push(type);
1616
- return found;
1617
- }
1618
- /**
1619
- * Collect all command paths that have any section markers in the content.
1620
- */
1621
- function collectSectionMarkerPaths(content) {
1622
- const sectionTypes = SECTION_TYPES.join("|");
1623
- const markerPattern = new RegExp(`<!--\\s*politty:command:(.*?):(?:${sectionTypes}):start\\s*-->`, "g");
1624
- const paths = /* @__PURE__ */ new Set();
1625
- for (const match of content.matchAll(markerPattern)) paths.add(match[1] ?? "");
1626
- return Array.from(paths);
1627
- }
1628
- /**
1629
- * Insert command section markers at the correct position based on specified order.
1630
- * Uses the heading marker of adjacent commands as reference points.
1631
- */
1632
- function insertCommandSections(content, commandPath, newSection, specifiedOrder) {
1633
- const targetIndex = specifiedOrder.indexOf(commandPath);
1634
- if (targetIndex === -1) return content.trimEnd() + "\n\n" + newSection + "\n";
1635
- for (let i = targetIndex + 1; i < specifiedOrder.length; i++) {
1636
- const nextCmd = specifiedOrder[i];
1637
- if (nextCmd === void 0) continue;
1638
- const nextMarker = sectionStartMarker("heading", nextCmd);
1639
- const nextIndex = content.indexOf(nextMarker);
1640
- if (nextIndex !== -1) {
1641
- let insertPos = nextIndex;
1642
- while (insertPos > 0 && content[insertPos - 1] === "\n") insertPos--;
1643
- if (insertPos < nextIndex) insertPos++;
1644
- return content.slice(0, insertPos) + newSection + "\n" + content.slice(nextIndex);
1645
- }
1646
- }
1647
- for (let i = targetIndex - 1; i >= 0; i--) {
1648
- const prevCmd = specifiedOrder[i];
1649
- if (prevCmd === void 0) continue;
1650
- const prevMarkers = collectSectionMarkers(content, prevCmd);
1651
- if (prevMarkers.length > 0) {
1652
- const lastType = prevMarkers[prevMarkers.length - 1];
1653
- const prevEndMarker = sectionEndMarker(lastType, prevCmd);
1654
- const prevEndIndex = content.indexOf(prevEndMarker);
1655
- if (prevEndIndex !== -1) {
1656
- const insertPos = prevEndIndex + prevEndMarker.length;
1657
- return content.slice(0, insertPos) + "\n" + newSection + content.slice(insertPos);
1658
- }
1659
- }
1660
- }
1661
- return content.trimEnd() + "\n" + newSection + "\n";
1662
- }
1663
- /**
1664
- * Remove all section markers for a command from content.
1665
- * Returns the content with all markers for the command removed and excess blank lines cleaned up.
1666
- */
1667
- function removeCommandSections(content, commandPath) {
1668
- const markers = collectSectionMarkers(content, commandPath);
1669
- for (const type of markers) {
1670
- const start = sectionStartMarker(type, commandPath);
1671
- const end = sectionEndMarker(type, commandPath);
1672
- let startIndex = content.indexOf(start);
1673
- while (startIndex !== -1) {
1674
- const endIndex = content.indexOf(end, startIndex);
1675
- if (endIndex === -1) break;
1676
- content = content.slice(0, startIndex) + content.slice(endIndex + end.length);
1677
- startIndex = content.indexOf(start, startIndex);
1678
- }
1679
- }
1680
- content = content.replace(/\n{3,}/g, "\n\n");
1681
- return content;
1682
- }
1683
- /**
1684
- * Strip politty marker lines from content, then collapse the blank-line gaps the removed markers
1685
- * leave behind (outside fenced code blocks only, so intentional blank lines inside generated
1686
- * example/code blocks are preserved) and trim leading/trailing blank lines.
1687
- */
1688
- function stripPolittyMarkers(content) {
1689
- let result = collapseBlankLinesOutsideCodeFences(content.split("\n").filter((line) => !/^<!-- politty:.*-->$/.test(line.trim())).join("\n"));
1690
- result = result.replace(/^\n+/, "").replace(/\n+$/, "");
1691
- return result;
1692
- }
1693
- /**
1694
- * Collapse runs of 3+ newlines to 2, but only outside fenced code blocks so that intentional
1695
- * blank lines inside handwritten code samples are preserved. Fences are lines whose trimmed
1696
- * content starts with ``` or ~~~.
1697
- */
1698
- function collapseBlankLinesOutsideCodeFences(content) {
1699
- const lines = content.split("\n");
1700
- const out = [];
1701
- let inFence = false;
1702
- let blankRun = 0;
1703
- for (const line of lines) {
1704
- const trimmed = line.trim();
1705
- if (trimmed.startsWith("```") || trimmed.startsWith("~~~")) {
1706
- inFence = !inFence;
1707
- blankRun = 0;
1708
- out.push(line);
1709
- continue;
1710
- }
1711
- if (!inFence && line.trim() === "") {
1712
- blankRun++;
1713
- if (blankRun >= 2) continue;
1714
- } else if (!inFence) blankRun = 0;
1715
- out.push(line);
1716
- }
1717
- return out.join("\n");
1718
- }
1719
- function detectLineEnding(content) {
1720
- return content.includes("\r\n") ? "\r\n" : "\n";
1721
- }
1722
- function countLineBreaks(value) {
1723
- return (value.match(/\n/g) ?? []).length;
1724
- }
1725
- /**
1726
- * Type guard for SectionType values parsed from template placeholders.
1727
- */
1728
- function isSectionType(value) {
1729
- return SECTION_TYPES.some((type) => type === value);
1730
- }
1731
- /**
1732
- * Clamp a numeric heading level to the valid HeadingLevel range (1–6).
1733
- * Uses a switch to return a literal union member, avoiding `as` assertions.
1734
- */
1735
- function clampHeadingLevel(level) {
1736
- switch (Math.min(6, Math.max(1, Math.trunc(level)))) {
1737
- case 1: return 1;
1738
- case 2: return 2;
1739
- case 3: return 3;
1740
- case 4: return 4;
1741
- case 5: return 5;
1742
- default: return 6;
1743
- }
1744
- }
1745
- function resolveTemplateCommandScope(tokens, allCommands) {
1746
- if (tokens.length === 0) return allCommands === void 0 || allCommands.has("") ? "" : null;
1747
- const exactScope = tokens.join(":");
1748
- if (allCommands?.has(exactScope)) return exactScope;
1749
- const colonSeparatedScope = tokens.join(" ");
1750
- if (allCommands?.has(colonSeparatedScope)) return colonSeparatedScope;
1751
- return allCommands === void 0 ? colonSeparatedScope : null;
1752
- }
1753
- function templateScopeFallback(tokens) {
1754
- return tokens.join(" ");
1755
- }
1756
- /**
1757
- * Parse a single {{politty:...}} placeholder string into a discriminated structure.
1758
- * The `placeholder` argument should be the full `{{politty:...}}` text.
1759
- *
1760
- * Uses String.match / String.replace internally (not .exec) to avoid lastIndex
1761
- * state issues from the shared TEMPLATE_PLACEHOLDER_REGEX constant.
1762
- */
1763
- function parsePlaceholder(placeholder, allCommands) {
1764
- const tokens = placeholder.slice(2, -2).split(":");
1765
- const directive = tokens[1];
1766
- if (directive === "command") {
1767
- const rest = tokens.slice(2);
1768
- if (rest.length === 1 && rest[0] === "") return {
1769
- kind: "invalid",
1770
- reason: `Trailing colon in "${placeholder}"; use {{politty:command}} for the root command.`
1771
- };
1772
- const fullScope = resolveTemplateCommandScope(rest, allCommands);
1773
- if (fullScope !== null) return {
1774
- kind: "command",
1775
- scope: fullScope,
1776
- type: void 0
1777
- };
1778
- if (rest.length >= 2) {
1779
- const last = rest[rest.length - 1];
1780
- const scopeTokens = rest.slice(0, -1);
1781
- const sectionScope = resolveTemplateCommandScope(scopeTokens, allCommands);
1782
- if (last !== void 0 && isSectionType(last)) return {
1783
- kind: "command",
1784
- scope: sectionScope ?? templateScopeFallback(scopeTokens),
1785
- type: last
1786
- };
1787
- if (last !== void 0 && sectionScope !== null) return {
1788
- kind: "invalid",
1789
- reason: `Unknown section type "${last}" for command scope "${formatCommandPath(sectionScope)}". Valid section types: ${SECTION_TYPES.join(", ")}`
1790
- };
1791
- }
1792
- return {
1793
- kind: "command",
1794
- scope: templateScopeFallback(rest),
1795
- type: void 0
1796
- };
1797
- }
1798
- if (directive === "global-options") {
1799
- if (tokens.length !== 2) return {
1800
- kind: "invalid",
1801
- reason: `Malformed placeholder "${placeholder}". Expected {{politty:global-options}}.`
1802
- };
1803
- return { kind: "global-options" };
1804
- }
1805
- if (directive === "index") {
1806
- if (tokens.length !== 2) return {
1807
- kind: "invalid",
1808
- reason: `Malformed placeholder "${placeholder}". Expected {{politty:index}}.`
1809
- };
1810
- return { kind: "index" };
1811
- }
1812
- return {
1813
- kind: "invalid",
1814
- reason: `Unknown politty directive "${directive ?? ""}" in "${placeholder}". Valid directives: command, global-options, index`
1815
- };
1816
- }
1817
- function buildTemplateExclusions(rawKeys, allCommands) {
1818
- const exclusions = createTemplateExclusions(rawKeys);
1819
- for (const key of rawKeys) {
1820
- const parsed = parsePlaceholder(`{{politty:${key}}}`, allCommands);
1821
- if (parsed.kind === "command") if (parsed.type === void 0) exclusions.commandScopes.add(parsed.scope);
1822
- else {
1823
- let sections = exclusions.commandSections.get(parsed.scope);
1824
- if (!sections) {
1825
- sections = /* @__PURE__ */ new Set();
1826
- exclusions.commandSections.set(parsed.scope, sections);
1827
- }
1828
- sections.add(parsed.type);
1829
- }
1830
- else if (parsed.kind === "global-options") exclusions.globalOptions = true;
1831
- else if (parsed.kind === "index") exclusions.index = true;
1832
- }
1833
- return exclusions;
1834
- }
1835
- function isCommandScopeExcluded(commandPath, excludedCommandScopes) {
1836
- for (const excludedScope of excludedCommandScopes) if (isSubcommandOf(commandPath, excludedScope)) return true;
1837
- return false;
1838
- }
1839
- function isCommandSectionExcluded(commandPath, sectionType, exclusions) {
1840
- if (isCommandScopeExcluded(commandPath, exclusions.commandScopes)) return true;
1841
- return exclusions.commandSections.get(commandPath)?.has(sectionType) ?? false;
1842
- }
1843
- function getTemplateCommandTreePaths(commandPath, allCommands, ignores, exclusions) {
1844
- return sortDepthFirst(filterIgnoredCommands(expandCommandPaths([commandPath], allCommands), ignores).filter((path) => !isCommandScopeExcluded(path, exclusions.commandScopes)), [commandPath]);
1845
- }
1846
- function shouldSkipTemplatePlaceholder(placeholder, parsed, exclusions) {
1847
- if (exclusions.rawKeys.has(templatePlaceholderKey(placeholder))) return true;
1848
- if (parsed.kind === "command") {
1849
- if (isCommandScopeExcluded(parsed.scope, exclusions.commandScopes)) return true;
1850
- return parsed.type !== void 0 && (exclusions.commandSections.get(parsed.scope)?.has(parsed.type) ?? false);
1851
- }
1852
- if (parsed.kind === "global-options") return exclusions.globalOptions;
1853
- if (parsed.kind === "index") return exclusions.index;
1854
- return false;
1855
- }
1856
- function isRawCommandPlaceholderUnderExcludedScope(key, exclusions) {
1857
- if (!key.startsWith("command:")) return false;
1858
- const tokens = key.slice(8).split(":");
1859
- for (const excludedScope of exclusions.commandScopes) {
1860
- if (excludedScope === "") return true;
1861
- const spaceTokens = excludedScope.split(" ");
1862
- if (tokens.slice(0, spaceTokens.length).join(" ") === excludedScope) return true;
1863
- const colonTokens = excludedScope.split(":");
1864
- if (tokens.slice(0, colonTokens.length).join(":") === excludedScope) return true;
1865
- }
1866
- return false;
1867
- }
1868
- /**
1869
- * Regex matching {{politty:...}} placeholders.
1870
- * NOTE: only use with String.match / String.replace, never with .exec in a loop,
1871
- * because the /g flag makes the regex stateful via lastIndex.
1872
- */
1873
- const TEMPLATE_PLACEHOLDER_REGEX = /\{\{politty:[^{}]*\}\}/g;
1874
- function validateTemplatePlaceholderSyntax(templateContent, templatePath) {
1875
- const validPlaceholderStarts = /* @__PURE__ */ new Set();
1876
- for (const match of templateContent.matchAll(TEMPLATE_PLACEHOLDER_REGEX)) {
1877
- const start = match.index;
1878
- const end = start + match[0].length;
1879
- if (templateContent[start - 1] === "{" || templateContent[end] === "}") {
1880
- const snippet = templateContent.slice(Math.max(0, start - 1), Math.min(templateContent.length, end + 1)).split("\n")[0];
1881
- throw new Error(`Malformed politty placeholder in template "${templatePath}": "${snippet}". Expected {{politty:...}}.`);
1882
- }
1883
- validPlaceholderStarts.add(start);
1884
- }
1885
- let searchIndex = 0;
1886
- while (true) {
1887
- const placeholderStart = templateContent.indexOf("{{politty:", searchIndex);
1888
- if (placeholderStart === -1) return;
1889
- if (!validPlaceholderStarts.has(placeholderStart)) {
1890
- const snippet = templateContent.slice(placeholderStart, placeholderStart + 80).split("\n")[0];
1891
- throw new Error(`Malformed politty placeholder in template "${templatePath}": "${snippet}". Expected {{politty:...}}.`);
1892
- }
1893
- searchIndex = placeholderStart + 10;
1894
- }
1895
- }
1896
- function getUnknownSectionTypeError(scope, allCommands) {
1897
- const separatorIndex = scope.lastIndexOf(":");
1898
- if (separatorIndex === -1) return null;
1899
- const commandScope = scope.slice(0, separatorIndex);
1900
- const sectionType = scope.slice(separatorIndex + 1);
1901
- if (sectionType === "" || !allCommands.has(commandScope)) return null;
1902
- return `Unknown section type "${sectionType}" for command scope "${formatCommandPath(commandScope)}". Valid section types: ${SECTION_TYPES.join(", ")}`;
1903
- }
1904
- /**
1905
- * Extract a marker section from content
1906
- * Returns the content between start and end markers (including markers)
1907
- */
1908
- function extractMarkerSection(content, startMarker, endMarker) {
1909
- const startIndex = content.indexOf(startMarker);
1910
- if (startIndex === -1) return null;
1911
- const endIndex = content.indexOf(endMarker, startIndex);
1912
- if (endIndex === -1) return null;
1913
- return content.slice(startIndex, endIndex + endMarker.length);
1914
- }
1915
- /**
1916
- * Replace a marker section in content
1917
- * Returns the updated content with the new section
1918
- */
1919
- function replaceMarkerSection(content, startMarker, endMarker, newSection) {
1920
- const startIndex = content.indexOf(startMarker);
1921
- if (startIndex === -1) return null;
1922
- const endIndex = content.indexOf(endMarker, startIndex);
1923
- if (endIndex === -1) return null;
1924
- return content.slice(0, startIndex) + newSection + content.slice(endIndex + endMarker.length);
1925
- }
1926
- /**
1927
- * Check if config is the { args, options? } shape (not shorthand ArgsShape)
1928
- *
1929
- * Distinguishes between:
1930
- * - { args: ArgsShape, options?: ArgsTableOptions } → returns true
1931
- * - ArgsShape (e.g., { verbose: ZodType, args: ZodType }) → returns false
1932
- *
1933
- * The key insight is that in the { args, options? } shape, config.args is an ArgsShape
1934
- * (Record of ZodTypes), while in shorthand, config itself is the ArgsShape and config.args
1935
- * would be a single ZodType if user has an option named "args".
1936
- */
1937
- function isGlobalOptionsConfigWithOptions(config) {
1938
- if (typeof config !== "object" || config === null || !("args" in config)) return false;
1939
- return !(config.args instanceof z.ZodType);
1940
- }
1941
- /**
1942
- * Collect option fields that are actually rendered by global options markers.
1943
- * Positional args are not rendered in args tables, so they must not be excluded.
1944
- */
1945
- function collectRenderableGlobalOptionFields(argsShape) {
1946
- return extractFields(z.object(argsShape)).fields.filter((field) => !field.positional);
1947
- }
1948
- /**
1949
- * Compare option definitions for global-options compatibility.
1950
- */
1951
- function areGlobalOptionsEquivalent(a, b) {
1952
- const { schema: _aSchema, ...aRest } = a;
1953
- const { schema: _bSchema, ...bRest } = b;
1954
- return isDeepStrictEqual(aRest, bRest);
1955
- }
1956
- /**
1957
- * Normalize rootDoc.globalOptions to { args, options? } form.
1958
- */
1959
- function normalizeGlobalOptions(config) {
1960
- if (!config) return void 0;
1961
- return isGlobalOptionsConfigWithOptions(config) ? config : { args: config };
1962
- }
1963
- /**
1964
- * Derive an ArgsShape from a globalArgs Zod schema, retaining only non-positional option fields.
1965
- * Returns undefined when globalArgs is undefined or contains no option fields.
1966
- * Used to build globalOptionDefinitions from globalArgs when rootDoc is not available.
1967
- */
1968
- function deriveGlobalArgsShape(globalArgs) {
1969
- if (!globalArgs) return void 0;
1970
- const optionFields = extractFields(globalArgs).fields.filter((f) => !f.positional);
1971
- if (optionFields.length === 0) return void 0;
1972
- return Object.fromEntries(optionFields.map((f) => [f.name, f.schema]));
1973
- }
1974
- /**
1975
- * Collect global option definitions from rootDoc.
1976
- * Global options are intentionally applied to all generated command sections.
1977
- */
1978
- function collectGlobalOptionDefinitions(rootDoc) {
1979
- const globalOptions = /* @__PURE__ */ new Map();
1980
- if (!rootDoc?.globalOptions) return globalOptions;
1981
- const normalized = normalizeGlobalOptions(rootDoc.globalOptions);
1982
- if (!normalized) return globalOptions;
1983
- for (const field of collectRenderableGlobalOptionFields(normalized.args)) globalOptions.set(field.name, field);
1984
- return globalOptions;
1985
- }
1986
- /**
1987
- * Derive CommandCategory[] from files mapping.
1988
- * Category title/description come from the first command in each file entry.
1989
- */
1990
- function deriveIndexFromFiles(files, rootDocPath, allCommands, ignores) {
1991
- const categories = [];
1992
- for (const [filePath, fileConfigRaw] of Object.entries(files)) {
1993
- const { commandPaths, topLevelCommands } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
1994
- if (commandPaths.length === 0) continue;
1995
- const docPath = "./" + path$1.relative(path$1.dirname(rootDocPath), filePath).replace(/\\/g, "/");
1996
- const firstCmdPath = commandPaths[0];
1997
- const cmdInfo = firstCmdPath !== void 0 ? allCommands.get(firstCmdPath) : void 0;
1998
- const fileConfig = Array.isArray(fileConfigRaw) ? void 0 : fileConfigRaw;
1999
- categories.push({
2000
- title: fileConfig?.title ?? cmdInfo?.name ?? path$1.basename(filePath, path$1.extname(filePath)),
2001
- description: fileConfig?.description ?? cmdInfo?.description ?? "",
2002
- commands: topLevelCommands,
2003
- allowedCommands: commandPaths,
2004
- docPath
2005
- });
2006
- }
2007
- return categories;
2008
- }
2009
- /**
2010
- * Build index categories for the {{politty:index}} placeholder from other template outputs.
2011
- * Each category lists exactly the heading-producing scopes of that output (noExpand), so the
2012
- * index never links to commands that template mode did not render.
2013
- */
2014
- function deriveIndexFromTemplateOutputs(templateMeta, currentOutputPath, indexFilePath, allCommands) {
2015
- const normalizedCurrent = normalizeDocPathForComparison(currentOutputPath);
2016
- const categories = [];
2017
- for (const [outputPath, meta] of templateMeta.entries()) {
2018
- if (normalizeDocPathForComparison(outputPath) === normalizedCurrent) continue;
2019
- const scopes = meta.headingScopes;
2020
- if (scopes.length === 0) continue;
2021
- const docPath = "./" + path$1.relative(path$1.dirname(indexFilePath), outputPath).replace(/\\/g, "/");
2022
- const firstScope = scopes[0];
2023
- const cmdInfo = firstScope !== void 0 ? allCommands.get(firstScope) : void 0;
2024
- categories.push({
2025
- title: meta.indexTitle ?? cmdInfo?.name ?? path$1.basename(outputPath, path$1.extname(outputPath)),
2026
- description: meta.indexDescription ?? cmdInfo?.description ?? "",
2027
- commands: scopes,
2028
- docPath,
2029
- noExpand: true
2030
- });
2031
- }
2032
- return categories;
2033
- }
2034
- /**
2035
- * Collect command paths that are actually documented in configured files.
2036
- */
2037
- function collectDocumentedCommandPaths(files, allCommands, ignores) {
2038
- const documentedCommandPaths = /* @__PURE__ */ new Set();
2039
- for (const fileConfigRaw of Object.values(files)) {
2040
- const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
2041
- for (const commandPath of commandPaths) documentedCommandPaths.add(commandPath);
2042
- }
2043
- return documentedCommandPaths;
2044
- }
2045
- /**
2046
- * Collect command paths that are targeted in configured files.
2047
- */
2048
- function collectTargetDocumentedCommandPaths(targetCommands, files, allCommands, ignores) {
2049
- const documentedTargetCommandPaths = /* @__PURE__ */ new Set();
2050
- for (const filePath of Object.keys(files)) {
2051
- const targetCommandsInFile = findTargetCommandsInFile(targetCommands, filePath, files, allCommands, ignores);
2052
- for (const commandPath of targetCommandsInFile) documentedTargetCommandPaths.add(commandPath);
2053
- }
2054
- return documentedTargetCommandPaths;
2055
- }
2056
- function commandPathMatchesTarget(commandPath, targetCommands) {
2057
- return targetCommands.some((targetCommand) => isSubcommandOf(commandPath, targetCommand));
2058
- }
2059
- function templateMetaReferencesCommandTarget(meta, targetCommands) {
2060
- return meta.referencedScopes.some((scope) => commandPathMatchesTarget(scope, targetCommands));
2061
- }
2062
- function templateMetaShouldProcessForTarget(meta, targetCommands) {
2063
- return meta.emitsIndex || meta.emitsGlobalOptions || templateMetaReferencesCommandTarget(meta, targetCommands);
2064
- }
2065
- /**
2066
- * Validate that excluded command options match globalOptions definitions.
2067
- */
2068
- function validateGlobalOptionCompatibility(documentedCommandPaths, allCommands, globalOptions) {
2069
- if (globalOptions.size === 0) return;
2070
- const conflicts = [];
2071
- for (const commandPath of documentedCommandPaths) {
2072
- const info = allCommands.get(commandPath);
2073
- if (!info) continue;
2074
- for (const option of info.options) {
2075
- const globalOption = globalOptions.get(option.name);
2076
- if (!globalOption) continue;
2077
- if (!areGlobalOptionsEquivalent(globalOption, option)) conflicts.push(`Command "${formatCommandPath(commandPath)}" option "--${option.cliName}" does not match globalOptions definition for "${option.name}".`);
2078
- }
2079
- }
2080
- if (conflicts.length > 0) throw new Error(`Invalid globalOptions configuration:\n - ${conflicts.join("\n - ")}`);
2081
- }
2082
- /**
2083
- * Build global options content (anchor + args table) without markers
2084
- */
2085
- function buildGlobalOptionsContent(config) {
2086
- return ["<a id=\"global-options\"></a>", renderArgsTable(config.args, config.options)].join("\n");
2087
- }
2088
- /**
2089
- * Generate global options section content with markers
2090
- */
2091
- function generateGlobalOptionsSection(config) {
2092
- return [
2093
- globalOptionsStartMarker(),
2094
- buildGlobalOptionsContent(config),
2095
- globalOptionsEndMarker()
2096
- ].join("\n");
2097
- }
2098
- /**
2099
- * Generate index section content with markers
2100
- */
2101
- async function generateIndexSection(categories, command, scope, options) {
2102
- const startMarker = indexStartMarker(scope);
2103
- const endMarker = indexEndMarker(scope);
2104
- return [
2105
- startMarker,
2106
- await renderCommandIndex(command, categories, options),
2107
- endMarker
2108
- ].join("\n");
2109
- }
2110
- /**
2111
- * Normalize a doc file path for equivalence checks.
2112
- */
2113
- function normalizeDocPathForComparison(filePath) {
2114
- return path$1.resolve(filePath);
2115
- }
2116
- /**
2117
- * Process global options marker in file content
2118
- * Returns result with updated content and any diffs
2119
- */
2120
- async function processGlobalOptionsMarker(existingContent, globalOptionsConfig, updateMode, formatter, autoInsertIfMissing) {
2121
- let content = existingContent;
2122
- const diffs = [];
2123
- let hasError = false;
2124
- let wasUpdated = false;
2125
- const startMarker = globalOptionsStartMarker();
2126
- const endMarker = globalOptionsEndMarker();
2127
- const generatedSection = await applyFormatter(generateGlobalOptionsSection(globalOptionsConfig), formatter);
2128
- const existingSection = extractMarkerSection(content, startMarker, endMarker);
2129
- if (!existingSection) {
2130
- if (updateMode && autoInsertIfMissing) {
2131
- content = content.trimEnd() + "\n\n" + generatedSection + "\n";
2132
- wasUpdated = true;
2133
- return {
2134
- content,
2135
- diffs,
2136
- hasError,
2137
- wasUpdated
2138
- };
2139
- }
2140
- hasError = true;
2141
- diffs.push(`Global options marker not found in file. Expected markers:\n${startMarker}\n...\n${endMarker}`);
2142
- return {
2143
- content,
2144
- diffs,
2145
- hasError,
2146
- wasUpdated
2147
- };
2148
- }
2149
- if (existingSection !== generatedSection) if (updateMode) {
2150
- const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);
2151
- if (updated) {
2152
- content = updated;
2153
- wasUpdated = true;
2154
- } else {
2155
- hasError = true;
2156
- diffs.push("Failed to replace global options section");
2157
- }
2158
- } else {
2159
- hasError = true;
2160
- diffs.push(formatDiff(existingSection, generatedSection));
2161
- }
2162
- return {
2163
- content,
2164
- diffs,
2165
- hasError,
2166
- wasUpdated
2167
- };
2168
- }
2169
- /**
2170
- * Process a static content marker (root-header or root-footer).
2171
- * Inserts/updates the marker section with the given content.
2172
- */
2173
- async function processStaticMarker(existingContent, markerLabel, startMarker, endMarker, rawContent, updateMode, formatter, autoInsertIfMissing) {
2174
- let content = existingContent;
2175
- const diffs = [];
2176
- let hasError = false;
2177
- let wasUpdated = false;
2178
- const generatedSection = [
2179
- startMarker,
2180
- await applyFormatter(rawContent, formatter),
2181
- endMarker
2182
- ].join("\n");
2183
- const existingSection = extractMarkerSection(content, startMarker, endMarker);
2184
- if (!existingSection) {
2185
- if (updateMode && autoInsertIfMissing) {
2186
- content = content.trimEnd() + "\n\n" + generatedSection + "\n";
2187
- wasUpdated = true;
2188
- return {
2189
- content,
2190
- diffs,
2191
- hasError,
2192
- wasUpdated
2193
- };
2194
- }
2195
- hasError = true;
2196
- diffs.push(`${markerLabel} marker not found in file. Expected markers:\n${startMarker}\n...\n${endMarker}`);
2197
- return {
2198
- content,
2199
- diffs,
2200
- hasError,
2201
- wasUpdated
2202
- };
2203
- }
2204
- if (existingSection !== generatedSection) if (updateMode) {
2205
- const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);
2206
- if (updated) {
2207
- content = updated;
2208
- wasUpdated = true;
2209
- } else {
2210
- hasError = true;
2211
- diffs.push(`Failed to replace ${markerLabel} section`);
2212
- }
2213
- } else {
2214
- hasError = true;
2215
- diffs.push(formatDiff(existingSection, generatedSection));
2216
- }
2217
- return {
2218
- content,
2219
- diffs,
2220
- hasError,
2221
- wasUpdated
2222
- };
2223
- }
2224
- /**
2225
- * Process index marker in file content
2226
- * Returns result with updated content and any diffs.
2227
- * If the marker is not present in the file, the section is silently skipped.
2228
- */
2229
- async function processIndexMarker(existingContent, categories, command, scope, updateMode, formatter, indexOptions) {
2230
- let content = existingContent;
2231
- const diffs = [];
2232
- let hasError = false;
2233
- let wasUpdated = false;
2234
- const startMarker = indexStartMarker(scope);
2235
- const endMarker = indexEndMarker(scope);
2236
- const hasStartMarker = content.includes(startMarker);
2237
- const hasEndMarker = content.includes(endMarker);
2238
- if (!hasStartMarker && !hasEndMarker) return {
2239
- content,
2240
- diffs,
2241
- hasError,
2242
- wasUpdated
2243
- };
2244
- if (!hasStartMarker || !hasEndMarker) {
2245
- hasError = true;
2246
- diffs.push("Index marker section is malformed: both start and end markers are required.");
2247
- return {
2248
- content,
2249
- diffs,
2250
- hasError,
2251
- wasUpdated
2252
- };
2253
- }
2254
- const existingSection = extractMarkerSection(content, startMarker, endMarker);
2255
- if (!existingSection) {
2256
- hasError = true;
2257
- diffs.push("Index marker section is malformed: start marker must appear before end marker.");
2258
- return {
2259
- content,
2260
- diffs,
2261
- hasError,
2262
- wasUpdated
2263
- };
2264
- }
2265
- const generatedSection = await applyFormatter(await generateIndexSection(categories, command, scope, indexOptions), formatter);
2266
- if (existingSection !== generatedSection) if (updateMode) {
2267
- const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);
2268
- if (updated) {
2269
- content = updated;
2270
- wasUpdated = true;
2271
- } else {
2272
- hasError = true;
2273
- diffs.push("Failed to replace index section");
2274
- }
2275
- } else {
2276
- hasError = true;
2277
- diffs.push(formatDiff(existingSection, generatedSection));
2278
- }
2279
- return {
2280
- content,
2281
- diffs,
2282
- hasError,
2283
- wasUpdated
2284
- };
2285
- }
2286
- /**
2287
- * Find which file contains a specific command
2288
- */
2289
- function findFileForCommand(commandPath, files, allCommands, ignores) {
2290
- for (const [filePath, fileConfigRaw] of Object.entries(files)) {
2291
- const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
2292
- if (commandPaths.includes(commandPath)) return filePath;
2293
- }
2294
- return null;
2295
- }
2296
- /**
2297
- * Find which target commands are contained in a file
2298
- * Also expands each target command to include subcommands that are NOT explicitly in specifiedCommands
2299
- */
2300
- function findTargetCommandsInFile(targetCommands, filePath, files, allCommands, ignores) {
2301
- const fileConfigRaw = files[filePath];
2302
- if (!fileConfigRaw) return [];
2303
- const { specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
2304
- const expandedTargets = /* @__PURE__ */ new Set();
2305
- for (const targetCmd of targetCommands) {
2306
- if (!commandPaths.includes(targetCmd)) continue;
2307
- expandedTargets.add(targetCmd);
2308
- for (const cmdPath of commandPaths) if (isSubcommandOf(cmdPath, targetCmd) && !specifiedCommands.includes(cmdPath)) expandedTargets.add(cmdPath);
2309
- }
2310
- return Array.from(expandedTargets);
2311
- }
2312
- /**
2313
- * Generate a single command section (already contains section markers from renderer)
2314
- */
2315
- function generateCommandSection(cmdPath, allCommands, render, filePath, fileMap, rootDocPath, hasGlobalOptions, ignores = [], excludeOptionNames, templateExclusions) {
2316
- const info = allCommands.get(cmdPath);
2317
- if (!info) return null;
2318
- if (templateExclusions && isCommandScopeExcluded(info.commandPath, templateExclusions.commandScopes)) return null;
2319
- const enriched = {
2320
- ...info,
2321
- filePath,
2322
- fileMap,
2323
- rootDocPath
2324
- };
2325
- if (ignores.length > 0 || templateExclusions && templateExclusions.commandScopes.size > 0) enriched.subCommands = info.subCommands.filter((sub) => {
2326
- const subCommandPath = sub.fullPath.join(" ");
2327
- if (ignores.some((pattern) => matchesIgnorePattern(subCommandPath, pattern))) return false;
2328
- return !(templateExclusions && isCommandScopeExcluded(subCommandPath, templateExclusions.commandScopes));
2329
- });
2330
- if (hasGlobalOptions !== void 0) enriched.hasGlobalOptions = hasGlobalOptions;
2331
- if (excludeOptionNames && excludeOptionNames.size > 0) {
2332
- enriched.options = info.options.filter((opt) => !excludeOptionNames.has(opt.name));
2333
- if (info.extracted) enriched.extracted = filterExtractedFields(info.extracted, excludeOptionNames);
2334
- }
2335
- let rendered = render(enriched);
2336
- if (templateExclusions) for (const [scope, sectionTypes] of templateExclusions.commandSections) {
2337
- if (scope !== info.commandPath) continue;
2338
- for (const sectionType of sectionTypes) {
2339
- const section = extractSectionMarker(rendered, sectionType, scope);
2340
- if (section !== null) rendered = rendered.replace(section, "");
2341
- }
2342
- rendered = collapseBlankLinesOutsideCodeFences(rendered);
2343
- }
2344
- return rendered;
2345
- }
2346
- function generateCommandTreeMarkdown(cmdPath, allCommands, render, ignores, filePath, fileMap, rootDocPath, hasGlobalOptions, excludeOptionNames, templateExclusions) {
2347
- const commandPaths = getTemplateCommandTreePaths(cmdPath, allCommands, ignores, templateExclusions);
2348
- const sections = [];
2349
- for (const commandPath of commandPaths) {
2350
- const section = generateCommandSection(commandPath, allCommands, render, filePath, fileMap, rootDocPath, hasGlobalOptions, ignores, excludeOptionNames, templateExclusions);
2351
- if (section !== null) sections.push(section);
2352
- }
2353
- return sections.length === 0 ? null : sections.join("\n");
2354
- }
2355
- /**
2356
- * Return a copy of ExtractedFields with the named options removed from every field collection
2357
- * (top-level fields, union options, and discriminated-union variants). Used to exclude global
2358
- * options from grouped option tables rendered directly from `extracted`.
2359
- */
2360
- function filterExtractedFields(extracted, excludeOptionNames) {
2361
- const result = {
2362
- ...extracted,
2363
- fields: extracted.fields.filter((f) => !excludeOptionNames.has(f.name))
2364
- };
2365
- if (extracted.unionOptions) result.unionOptions = extracted.unionOptions.map((opt) => filterExtractedFields(opt, excludeOptionNames));
2366
- if (extracted.variants) result.variants = extracted.variants.map((variant) => ({
2367
- ...variant,
2368
- fields: variant.fields.filter((f) => !excludeOptionNames.has(f.name))
2369
- }));
2370
- return result;
2371
- }
2372
- /**
2373
- * Generate markdown for a file containing multiple commands
2374
- * Each command section is wrapped with markers for partial validation
2375
- */
2376
- function generateFileMarkdown(commandPaths, allCommands, render, filePath, fileMap, specifiedOrder, fileConfig, rootDocPath, hasGlobalOptions, ignores = []) {
2377
- const sections = [];
2378
- const header = fileConfig ? generateFileHeader(fileConfig) : null;
2379
- if (header) sections.push(header);
2380
- const sortedPaths = sortDepthFirst(commandPaths, specifiedOrder ?? []);
2381
- for (const cmdPath of sortedPaths) {
2382
- const section = generateCommandSection(cmdPath, allCommands, render, filePath, fileMap, rootDocPath, hasGlobalOptions, ignores);
2383
- if (section) sections.push(section);
2384
- }
2385
- return `${sections.join("\n")}\n`;
2386
- }
2387
- /**
2388
- * Build a map of command path to file path
2389
- */
2390
- function buildFileMap(files, allCommands, ignores) {
2391
- const fileMap = {};
2392
- for (const [filePath, fileConfigRaw] of Object.entries(files)) {
2393
- const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
2394
- for (const cmdPath of commandPaths) setFileMapEntry(fileMap, cmdPath, filePath);
2395
- }
2396
- return fileMap;
2397
- }
2398
- /**
2399
- * Execute examples for commands based on configuration
2400
- */
2401
- async function executeConfiguredExamples(allCommands, examplesConfig, rootCommand) {
2402
- for (const [cmdPath, cmdConfig] of Object.entries(examplesConfig)) {
2403
- const commandInfo = allCommands.get(cmdPath);
2404
- if (!commandInfo?.examples?.length) continue;
2405
- const config = cmdConfig === true ? {} : cmdConfig;
2406
- const commandPath = cmdPath ? cmdPath.split(" ") : [];
2407
- commandInfo.exampleResults = await executeExamples(commandInfo.examples, config, rootCommand, commandPath);
2408
- }
2409
- }
2410
- /**
2411
- * Convert PathConfig to FileMapping with explicit command paths.
2412
- * Uses noExpand to prevent subcommand expansion since paths are pre-resolved.
2413
- */
2414
- function pathToFiles(pathConfig, allCommands) {
2415
- if (typeof pathConfig === "string") return {
2416
- files: { [pathConfig]: Array.from(allCommands.keys()) },
2417
- rootDocPath: pathConfig
2418
- };
2419
- const { root, commands = {} } = pathConfig;
2420
- const files = {};
2421
- const assignedToOtherFiles = /* @__PURE__ */ new Set();
2422
- const sortedEntries = Object.entries(commands).sort(([a], [b]) => b.split(" ").length - a.split(" ").length);
2423
- for (const [cmdPath, filePath] of sortedEntries) {
2424
- if (!files[filePath]) files[filePath] = {
2425
- commands: [],
2426
- noExpand: true
2427
- };
2428
- const fc = files[filePath];
2429
- for (const existingPath of allCommands.keys()) if ((existingPath === cmdPath || existingPath.startsWith(cmdPath + " ")) && !assignedToOtherFiles.has(existingPath)) {
2430
- fc.commands.push(existingPath);
2431
- assignedToOtherFiles.add(existingPath);
2432
- }
2433
- }
2434
- files[root] = {
2435
- commands: Array.from(allCommands.keys()).filter((p) => !assignedToOtherFiles.has(p)),
2436
- noExpand: true
2437
- };
2438
- return {
2439
- files,
2440
- rootDocPath: root
2441
- };
2442
- }
2443
- /**
2444
- * Generate documentation from command definition
2445
- */
2446
- async function generateDoc(config) {
2447
- const { command, ignores = [], format = {}, formatter, examples: examplesConfig, targetCommands, globalArgs, customizable = false } = config;
2448
- const allCommands = await collectAllCommands(command);
2449
- let files;
2450
- let usingPathConfig = false;
2451
- let resolvedRootDocPath;
2452
- if (config.path !== void 0) {
2453
- if (config.files !== void 0) throw new Error("Cannot specify both \"path\" and \"files\". Use one or the other.");
2454
- const converted = pathToFiles(config.path, allCommands);
2455
- files = converted.files;
2456
- resolvedRootDocPath = converted.rootDocPath;
2457
- usingPathConfig = true;
2458
- } else if (config.files !== void 0) files = config.files;
2459
- else if (config.templates !== void 0) files = {};
2460
- else throw new Error("Either \"path\", \"files\", or \"templates\" must be specified.");
2461
- let rootDoc = config.rootDoc;
2462
- if (!rootDoc && usingPathConfig && (globalArgs || config.rootInfo)) rootDoc = { path: resolvedRootDocPath };
2463
- if (globalArgs && rootDoc && !rootDoc.globalOptions) {
2464
- const optionFields = extractFields(globalArgs).fields.filter((f) => !f.positional);
2465
- if (optionFields.length > 0) {
2466
- const globalShape = Object.fromEntries(optionFields.map((f) => [f.name, f.schema]));
2467
- rootDoc = {
2468
- ...rootDoc,
2469
- globalOptions: globalShape
2470
- };
2471
- }
2472
- }
2473
- const updateMode = isTruthyEnv(UPDATE_GOLDEN_ENV);
2474
- const doctorMode = isTruthyEnv(DOCTOR_ENV);
2475
- let hasDoctorIssues = false;
2476
- if (rootDoc && !usingPathConfig) {
2477
- const normalizedRootDocPath = normalizeDocPathForComparison(rootDoc.path);
2478
- if (Object.keys(files).some((filePath) => normalizeDocPathForComparison(filePath) === normalizedRootDocPath)) throw new Error(`rootDoc.path "${rootDoc.path}" must not also appear as a key in files.`);
2479
- }
2480
- if (examplesConfig) await executeConfiguredExamples(allCommands, examplesConfig, command);
2481
- const hasTargetCommands = targetCommands !== void 0 && targetCommands.length > 0;
2482
- const globalOptionDefinitions = collectGlobalOptionDefinitions(rootDoc);
2483
- const templateGlobalOptionFields = /* @__PURE__ */ new Map();
2484
- if (config.templates) if (globalOptionDefinitions.size > 0) for (const [name, field] of globalOptionDefinitions) templateGlobalOptionFields.set(name, field);
2485
- else {
2486
- const shape = deriveGlobalArgsShape(globalArgs);
2487
- if (shape) for (const field of collectRenderableGlobalOptionFields(shape)) templateGlobalOptionFields.set(field.name, field);
2488
- }
2489
- const documentedCommandPaths = hasTargetCommands ? collectTargetDocumentedCommandPaths(targetCommands, files, allCommands, ignores) : collectDocumentedCommandPaths(files, allCommands, ignores);
2490
- const allFilesCommands = [];
2491
- for (const fileConfigRaw of Object.values(files)) {
2492
- const fileConfig = normalizeFileConfig(fileConfigRaw);
2493
- allFilesCommands.push(...fileConfig.commands);
2494
- }
2495
- validateIgnoresExist(ignores, allCommands);
2496
- validateNoConflicts(allFilesCommands, ignores, allCommands);
2497
- const fileMap = buildFileMap(files, allCommands, ignores);
2498
- const templateContents = /* @__PURE__ */ new Map();
2499
- const templateExclusions = /* @__PURE__ */ new Map();
2500
- if (config.templates) for (const [outputPath, templatePath] of Object.entries(config.templates)) {
2501
- const templateContent = readFile(templatePath);
2502
- templateContents.set(outputPath, templateContent);
2503
- if (templateContent !== null) templateExclusions.set(outputPath, buildTemplateExclusions(collectExcludedTemplatePlaceholders(templateContent), allCommands));
2504
- }
2505
- const templateEntries = Object.entries(config.templates ?? {});
2506
- const templateMeta = /* @__PURE__ */ new Map();
2507
- const templateValidationErrors = /* @__PURE__ */ new Map();
2508
- if (templateEntries.length > 0) {
2509
- const normalizedRootDocPath = rootDoc ? normalizeDocPathForComparison(rootDoc.path) : null;
2510
- const normalizedFileKeys = new Set(Object.keys(files).map(normalizeDocPathForComparison));
2511
- const normalizedTemplateOutputs = /* @__PURE__ */ new Set();
2512
- const allNormalizedTemplateOutputs = new Set(templateEntries.map(([outputPath]) => normalizeDocPathForComparison(outputPath)));
2513
- for (const [outputPath, templatePath] of templateEntries) {
2514
- const normalizedOutput = normalizeDocPathForComparison(outputPath);
2515
- const normalizedSource = normalizeDocPathForComparison(templatePath);
2516
- if (normalizedFileKeys.has(normalizedOutput)) throw new Error(`Template output path "${outputPath}" conflicts with an existing files key.`);
2517
- if (normalizedRootDocPath && normalizedOutput === normalizedRootDocPath) throw new Error(`Template output path "${outputPath}" conflicts with rootDoc.path "${rootDoc.path}".`);
2518
- if (normalizedTemplateOutputs.has(normalizedOutput)) throw new Error(`Duplicate template output path: "${outputPath}".`);
2519
- normalizedTemplateOutputs.add(normalizedOutput);
2520
- if (normalizedSource === normalizedOutput) throw new Error(`Template output path "${outputPath}" must not be the same as its source template path.`);
2521
- if (normalizedFileKeys.has(normalizedSource)) throw new Error(`Template source path "${templatePath}" conflicts with a files output key.`);
2522
- if (normalizedRootDocPath && normalizedSource === normalizedRootDocPath) throw new Error(`Template source path "${templatePath}" conflicts with rootDoc.path "${rootDoc.path}".`);
2523
- if (allNormalizedTemplateOutputs.has(normalizedSource)) throw new Error(`Template source path "${templatePath}" conflicts with a template output path.`);
2524
- }
2525
- const availableCommandPaths = Array.from(allCommands.keys()).join(", ");
2526
- for (const [outputPath, templatePath] of templateEntries) {
2527
- const templateContent = templateContents.get(outputPath) ?? null;
2528
- const validationErrors = [];
2529
- if (templateContent === null) {
2530
- templateMeta.set(outputPath, {
2531
- referencedScopes: [],
2532
- headingScopes: [],
2533
- commandTreeRoots: [],
2534
- emitsGlobalOptions: false,
2535
- emitsIndex: false
2536
- });
2537
- templateValidationErrors.set(outputPath, validationErrors);
2538
- continue;
2539
- }
2540
- try {
2541
- validateTemplatePlaceholderSyntax(templateContent, templatePath);
2542
- } catch (error) {
2543
- validationErrors.push(error instanceof Error ? error.message : String(error));
2544
- }
2545
- const placeholders = Array.from(new Set(templateContent.match(TEMPLATE_PLACEHOLDER_REGEX) ?? []));
2546
- const scopes = /* @__PURE__ */ new Set();
2547
- const headingScopes = /* @__PURE__ */ new Set();
2548
- const commandTreeRoots = /* @__PURE__ */ new Set();
2549
- let emitsGlobalOptions = false;
2550
- let emitsIndex = false;
2551
- const exclusions = templateExclusions.get(outputPath) ?? createTemplateExclusions(/* @__PURE__ */ new Set());
2552
- const indexMetadata = collectTemplateIndexMetadata(templateContent);
2553
- for (const placeholder of placeholders) {
2554
- const placeholderKey = templatePlaceholderKey(placeholder);
2555
- if (exclusions.rawKeys.has(placeholderKey) || isRawCommandPlaceholderUnderExcludedScope(placeholderKey, exclusions)) continue;
2556
- const parsed = parsePlaceholder(placeholder, allCommands);
2557
- if (shouldSkipTemplatePlaceholder(placeholder, parsed, exclusions)) continue;
2558
- if (parsed.kind === "invalid") {
2559
- validationErrors.push(`${parsed.reason} (in template "${templatePath}")`);
2560
- continue;
2561
- }
2562
- if (parsed.kind === "command") {
2563
- const { scope, type } = parsed;
2564
- if (!allCommands.has(scope)) {
2565
- const sectionTypeError = getUnknownSectionTypeError(scope, allCommands);
2566
- if (sectionTypeError) {
2567
- validationErrors.push(`${sectionTypeError} (in template "${templatePath}")`);
2568
- continue;
2569
- }
2570
- validationErrors.push(`Unknown command scope "${scope}" in template "${templatePath}". Available: ${availableCommandPaths}`);
2571
- continue;
2572
- }
2573
- if (ignores.some((pattern) => matchesIgnorePattern(scope, pattern))) {
2574
- validationErrors.push(`Command scope "${scope}" in template "${templatePath}" conflicts with ignores configuration.`);
2575
- continue;
2576
- }
2577
- if (type === void 0) {
2578
- const commandTreePaths = getTemplateCommandTreePaths(scope, allCommands, ignores, exclusions);
2579
- if (!isCommandSectionExcluded(scope, "heading", exclusions)) commandTreeRoots.add(scope);
2580
- for (const commandTreePath of commandTreePaths) {
2581
- scopes.add(commandTreePath);
2582
- if (!isCommandSectionExcluded(commandTreePath, "heading", exclusions)) headingScopes.add(commandTreePath);
2583
- }
2584
- } else {
2585
- scopes.add(scope);
2586
- if (type === "heading" && !isCommandSectionExcluded(scope, "heading", exclusions)) {
2587
- headingScopes.add(scope);
2588
- commandTreeRoots.add(scope);
2589
- }
2590
- }
2591
- } else if (parsed.kind === "global-options") emitsGlobalOptions = true;
2592
- else if (parsed.kind === "index") emitsIndex = true;
2593
- }
2594
- if (emitsGlobalOptions) {
2595
- if (!(!!rootDoc?.globalOptions || deriveGlobalArgsShape(globalArgs) !== void 0)) validationErrors.push(`Template "${templatePath}" uses {{politty:global-options}} but no global options are configured (neither rootDoc.globalOptions nor globalArgs with non-positional options).`);
2596
- }
2597
- templateMeta.set(outputPath, {
2598
- referencedScopes: Array.from(scopes),
2599
- headingScopes: Array.from(headingScopes),
2600
- commandTreeRoots: Array.from(commandTreeRoots),
2601
- emitsGlobalOptions,
2602
- emitsIndex,
2603
- ...indexMetadata.title !== void 0 ? { indexTitle: indexMetadata.title } : {},
2604
- ...indexMetadata.description !== void 0 ? { indexDescription: indexMetadata.description } : {}
2605
- });
2606
- templateValidationErrors.set(outputPath, validationErrors);
2607
- }
2608
- for (const meta of templateMeta.values()) {
2609
- if (hasTargetCommands && !templateMetaShouldProcessForTarget(meta, targetCommands)) continue;
2610
- for (const scope of meta.referencedScopes) documentedCommandPaths.add(scope);
2611
- }
2612
- }
2613
- if (hasTargetCommands) for (const targetCommand of targetCommands) {
2614
- const targetFilePath = findFileForCommand(targetCommand, files, allCommands, ignores);
2615
- const targetTemplatePath = Array.from(templateMeta.values()).some((meta) => templateMetaReferencesCommandTarget(meta, [targetCommand]));
2616
- if (!targetFilePath && !targetTemplatePath) throw new Error(`Target command "${targetCommand}" not found in any file or template configuration`);
2617
- }
2618
- const activeTemplateMeta = hasTargetCommands && config.templates ? new Map(Array.from(templateMeta.entries()).filter(([, meta]) => templateMetaShouldProcessForTarget(meta, targetCommands))) : templateMeta;
2619
- for (const [outputPath, validationErrors] of templateValidationErrors.entries()) if (validationErrors.length > 0 && activeTemplateMeta.has(outputPath)) throw new Error(validationErrors.join("\n"));
2620
- const templateGlobalOptionsProviderPaths = Array.from(templateMeta.entries()).filter(([, meta]) => meta.emitsGlobalOptions).map(([outputPath]) => outputPath);
2621
- const templateGlobalOptionsProviderPath = templateGlobalOptionsProviderPaths.length === 1 ? templateGlobalOptionsProviderPaths[0] : void 0;
2622
- validateGlobalOptionCompatibility(documentedCommandPaths, allCommands, globalOptionDefinitions);
2623
- if (globalOptionDefinitions.size === 0 && templateGlobalOptionFields.size > 0) {
2624
- const emittingTemplateScopes = /* @__PURE__ */ new Set();
2625
- for (const meta of activeTemplateMeta.values()) {
2626
- if (!meta.emitsGlobalOptions && templateGlobalOptionsProviderPath === void 0) continue;
2627
- for (const scope of meta.referencedScopes) emittingTemplateScopes.add(scope);
2628
- }
2629
- validateGlobalOptionCompatibility(emittingTemplateScopes, allCommands, templateGlobalOptionFields);
2630
- }
2631
- if (globalOptionDefinitions.size > 0) for (const info of allCommands.values()) {
2632
- info.options = info.options.filter((opt) => !globalOptionDefinitions.has(opt.name));
2633
- if (info.extracted) info.extracted = filterExtractedFields(info.extracted, new Set(globalOptionDefinitions.keys()));
2634
- }
2635
- const templateFileMap = {};
2636
- for (const [scope, outputPath] of Object.entries(fileMap)) setFileMapEntry(templateFileMap, scope, outputPath);
2637
- const scopeRootLength = (root) => root === "" ? 0 : root.split(" ").length;
2638
- const templateOwners = /* @__PURE__ */ new Map();
2639
- for (const [templateOutputPath, meta] of templateMeta.entries()) for (const scope of meta.headingScopes) {
2640
- if (Object.prototype.hasOwnProperty.call(fileMap, scope)) continue;
2641
- let bestRootLen = -1;
2642
- for (const root of meta.commandTreeRoots) if (isSubcommandOf(scope, root)) bestRootLen = Math.max(bestRootLen, scopeRootLength(root));
2643
- if (bestRootLen < 0) continue;
2644
- const existing = templateOwners.get(scope);
2645
- if (!existing || bestRootLen > existing.rootLen) templateOwners.set(scope, {
2646
- outputPath: templateOutputPath,
2647
- rootLen: bestRootLen
2648
- });
2649
- }
2650
- for (const [scope, { outputPath }] of templateOwners) setFileMapEntry(templateFileMap, scope, outputPath);
2651
- const results = [];
2652
- let hasError = false;
2653
- for (const [filePath, fileConfigRaw] of Object.entries(files)) {
2654
- const { fileConfig, specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);
2655
- if (specifiedCommands.length === 0) continue;
2656
- if (commandPaths.length === 0) continue;
2657
- const fileTargetCommands = hasTargetCommands ? findTargetCommandsInFile(targetCommands, filePath, files, allCommands, ignores) : [];
2658
- if (hasTargetCommands && fileTargetCommands.length === 0) continue;
2659
- let fileStatus = "match";
2660
- const diffs = [];
2661
- const minDepth = Math.min(...commandPaths.map((p) => allCommands.get(p)?.depth ?? 1));
2662
- const adjustedHeadingLevel = Math.max(1, (format?.headingLevel ?? 1) - (minDepth - 1));
2663
- const isRootDocFile = usingPathConfig && rootDoc && normalizeDocPathForComparison(filePath) === normalizeDocPathForComparison(rootDoc.path);
2664
- const fileUsesMarkers = usingPathConfig || customizable;
2665
- const fileRenderer = createCommandRenderer({
2666
- ...format,
2667
- headingLevel: adjustedHeadingLevel,
2668
- markerless: !fileUsesMarkers
2669
- });
2670
- const render = fileConfig.render ?? fileRenderer;
2671
- if (Boolean(isRootDocFile) || hasTargetCommands && fileUsesMarkers) {
2672
- let existingContent = readFile(filePath);
2673
- const sortedCommandPaths = sortDepthFirst(commandPaths, specifiedCommands);
2674
- const effectiveTargetCommands = hasTargetCommands ? fileTargetCommands : commandPaths;
2675
- for (const targetCommand of effectiveTargetCommands) {
2676
- const rawSection = generateCommandSection(targetCommand, allCommands, render, filePath, templateFileMap, rootDoc?.path, globalOptionDefinitions.size > 0, ignores);
2677
- if (!rawSection) throw new Error(`Target command "${targetCommand}" not found in commands`);
2678
- const generatedSection = await applyFormatter(rawSection, formatter);
2679
- if (!existingContent) {
2680
- if (updateMode) {
2681
- const header = targetCommand === "" && fileConfig ? generateFileHeader(fileConfig) : null;
2682
- const fullContent = header ? `${header}\n${generatedSection}` : generatedSection;
2683
- writeFile(filePath, fullContent);
2684
- existingContent = fullContent;
2685
- fileStatus = "created";
2686
- } else {
2687
- hasError = true;
2688
- fileStatus = "diff";
2689
- diffs.push(`File does not exist. Target command "${targetCommand}" section cannot be validated.`);
2690
- }
2691
- continue;
2692
- }
2693
- const existingMarkers = collectSectionMarkers(existingContent, targetCommand);
2694
- if (existingMarkers.length === 0) {
2695
- if (updateMode) {
2696
- existingContent = insertCommandSections(existingContent, targetCommand, generatedSection, sortedCommandPaths);
2697
- writeFile(filePath, existingContent);
2698
- if (fileStatus !== "created") fileStatus = "updated";
2699
- } else {
2700
- hasError = true;
2701
- fileStatus = "diff";
2702
- diffs.push(`Existing file does not contain section markers for command "${targetCommand}"`);
2703
- }
2704
- continue;
2705
- }
2706
- for (const sectionType of existingMarkers) {
2707
- const existingSection = extractSectionMarker(existingContent, sectionType, targetCommand);
2708
- const generatedSectionPart = extractSectionMarker(generatedSection, sectionType, targetCommand);
2709
- if (!existingSection) continue;
2710
- if (!generatedSectionPart) {
2711
- const emptyMarker = sectionStartMarker(sectionType, targetCommand) + "\n" + sectionEndMarker(sectionType, targetCommand);
2712
- if (existingSection !== emptyMarker) if (updateMode) {
2713
- const updated = replaceSectionMarker(existingContent, sectionType, targetCommand, emptyMarker);
2714
- if (!updated) throw new Error(`Failed to replace stale ${sectionType} section for command "${targetCommand}"`);
2715
- existingContent = updated.replace(/\n{3,}/g, "\n\n");
2716
- writeFile(filePath, existingContent);
2717
- if (fileStatus !== "created") fileStatus = "updated";
2718
- } else {
2719
- hasError = true;
2720
- fileStatus = "diff";
2721
- diffs.push(formatDiff(existingSection, emptyMarker));
2722
- }
2723
- continue;
2724
- }
2725
- if (existingSection !== generatedSectionPart) if (updateMode) {
2726
- const updated = replaceSectionMarker(existingContent, sectionType, targetCommand, generatedSectionPart);
2727
- if (updated) {
2728
- existingContent = updated;
2729
- writeFile(filePath, existingContent);
2730
- if (fileStatus !== "created") fileStatus = "updated";
2731
- } else throw new Error(`Failed to replace ${sectionType} section for command "${targetCommand}"`);
2732
- } else {
2733
- hasError = true;
2734
- fileStatus = "diff";
2735
- diffs.push(formatDiff(existingSection, generatedSectionPart));
2736
- }
2737
- }
2738
- if (doctorMode || customizable) {
2739
- const generatedMarkers = collectSectionMarkers(generatedSection, targetCommand);
2740
- const existingMarkerSet = new Set(existingMarkers);
2741
- for (const sectionType of generatedMarkers) {
2742
- if (existingMarkerSet.has(sectionType)) continue;
2743
- const generatedSectionPart = extractSectionMarker(generatedSection, sectionType, targetCommand);
2744
- if (!generatedSectionPart) continue;
2745
- if (doctorMode && updateMode) {
2746
- existingContent = insertSectionMarkerAtOrder(existingContent, sectionType, targetCommand, generatedSectionPart);
2747
- writeFile(filePath, existingContent);
2748
- if (fileStatus !== "created") fileStatus = "updated";
2749
- } else if (doctorMode) {
2750
- hasError = true;
2751
- hasDoctorIssues = true;
2752
- fileStatus = "diff";
2753
- diffs.push(`[doctor] Missing section marker "${sectionType}" for command "${formatCommandPath(targetCommand)}". Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to insert.\n${generatedSectionPart}`);
2754
- } else console.warn(`[politty] Missing "${sectionType}" section for command "${formatCommandPath(targetCommand)}" in ${filePath}. Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to insert it, or leave it removed to opt that section out.`);
2755
- }
2756
- }
2757
- }
2758
- if (existingContent) {
2759
- const existingMarkerPaths = collectSectionMarkerPaths(existingContent);
2760
- const commandPathSet = new Set(commandPaths);
2761
- if (updateMode) {
2762
- let removedAny = false;
2763
- for (const markerPath of existingMarkerPaths) if (!commandPathSet.has(markerPath)) {
2764
- existingContent = removeCommandSections(existingContent, markerPath);
2765
- removedAny = true;
2766
- }
2767
- if (removedAny) {
2768
- writeFile(filePath, existingContent);
2769
- if (fileStatus !== "created") fileStatus = "updated";
2770
- }
2771
- } else for (const markerPath of existingMarkerPaths) if (!commandPathSet.has(markerPath)) {
2772
- hasError = true;
2773
- fileStatus = "diff";
2774
- diffs.push(`Found orphaned section markers for deleted command "${formatCommandPath(markerPath)}"`);
2775
- }
2776
- }
2777
- } else {
2778
- const generatedMarkdown = await applyFormatter(generateFileMarkdown(commandPaths, allCommands, render, filePath, templateFileMap, specifiedCommands, fileConfig, rootDoc?.path, globalOptionDefinitions.size > 0, ignores), formatter);
2779
- const comparison = compareWithExisting(generatedMarkdown, filePath);
2780
- if (comparison.match) {} else if (updateMode) {
2781
- writeFile(filePath, generatedMarkdown);
2782
- fileStatus = comparison.fileExists ? "updated" : "created";
2783
- } else {
2784
- hasError = true;
2785
- fileStatus = "diff";
2786
- if (comparison.diff) diffs.push(comparison.diff);
2787
- }
2788
- }
2789
- if (diffs.length > 0) fileStatus = "diff";
2790
- results.push({
2791
- path: filePath,
2792
- status: fileStatus,
2793
- diff: diffs.length > 0 ? diffs.join("\n\n") : void 0
2794
- });
2795
- }
2796
- let normalizedTemplateGlobalOptions;
2797
- if (rootDoc?.globalOptions) normalizedTemplateGlobalOptions = normalizeGlobalOptions(rootDoc.globalOptions);
2798
- else {
2799
- const shape = deriveGlobalArgsShape(globalArgs);
2800
- if (shape) normalizedTemplateGlobalOptions = { args: shape };
2801
- }
2802
- for (const [outputPath, templatePath] of templateEntries) {
2803
- if (!activeTemplateMeta.has(outputPath)) continue;
2804
- const templateContent = templateContents.get(outputPath) ?? null;
2805
- if (templateContent === null) {
2806
- hasError = true;
2807
- results.push({
2808
- path: outputPath,
2809
- status: "diff",
2810
- diff: `Template file not found: ${templatePath}`
2811
- });
2812
- continue;
2813
- }
2814
- const meta = templateMeta.get(outputPath);
2815
- const templateLineEnding = detectLineEnding(templateContent);
2816
- const outputTemplateContent = stripPolittyFrontMatterForOutput(templateContent);
2817
- const headingDepths = (meta?.headingScopes ?? []).map((s) => allCommands.get(s)?.depth ?? 1);
2818
- const minDepth = headingDepths.length > 0 ? Math.min(...headingDepths) : 1;
2819
- const adjustedHeadingLevel = clampHeadingLevel((format?.headingLevel ?? 1) - (minDepth - 1));
2820
- const templateRenderer = createCommandRenderer({
2821
- ...format,
2822
- headingLevel: adjustedHeadingLevel
2823
- });
2824
- const outputEmitsGlobalOptions = meta?.emitsGlobalOptions ?? false;
2825
- const excludeOptionNames = (rootDoc !== void 0 && globalOptionDefinitions.size > 0 || outputEmitsGlobalOptions || templateGlobalOptionsProviderPath !== void 0) && templateGlobalOptionFields.size > 0 ? new Set(templateGlobalOptionFields.keys()) : void 0;
2826
- const sectionHasGlobalOptions = excludeOptionNames !== void 0;
2827
- const effectiveRootDocPath = outputEmitsGlobalOptions ? outputPath : rootDoc?.path ?? templateGlobalOptionsProviderPath;
2828
- const placeholders = Array.from(new Set(outputTemplateContent.match(TEMPLATE_PLACEHOLDER_REGEX) ?? []));
2829
- const replacements = /* @__PURE__ */ new Map();
2830
- const exclusions = templateExclusions.get(outputPath) ?? createTemplateExclusions(/* @__PURE__ */ new Set());
2831
- for (const placeholder of placeholders) {
2832
- const placeholderKey = templatePlaceholderKey(placeholder);
2833
- if (exclusions.rawKeys.has(placeholderKey) || isRawCommandPlaceholderUnderExcludedScope(placeholderKey, exclusions)) {
2834
- replacements.set(placeholder, "");
2835
- continue;
2836
- }
2837
- const parsed = parsePlaceholder(placeholder, allCommands);
2838
- if (shouldSkipTemplatePlaceholder(placeholder, parsed, exclusions)) {
2839
- replacements.set(placeholder, "");
2840
- continue;
2841
- }
2842
- if (parsed.kind === "invalid") throw new Error(`Internal error: unresolved placeholder "${placeholder}" in template "${templatePath}": ${parsed.reason}`);
2843
- if (parsed.kind === "command") {
2844
- const { scope, type } = parsed;
2845
- if (type === void 0) {
2846
- const rawSection = generateCommandTreeMarkdown(scope, allCommands, templateRenderer, ignores, outputPath, templateFileMap, effectiveRootDocPath, sectionHasGlobalOptions, excludeOptionNames, exclusions);
2847
- if (rawSection === null) {
2848
- replacements.set(placeholder, "");
2849
- continue;
2850
- }
2851
- replacements.set(placeholder, stripPolittyMarkers(rawSection));
2852
- } else {
2853
- const rawSection = generateCommandSection(scope, allCommands, templateRenderer, outputPath, templateFileMap, effectiveRootDocPath, sectionHasGlobalOptions, ignores, excludeOptionNames, exclusions);
2854
- if (rawSection === null) {
2855
- replacements.set(placeholder, "");
2856
- continue;
2857
- }
2858
- const extracted = extractSectionMarker(rawSection, type, scope);
2859
- replacements.set(placeholder, extracted === null ? "" : stripPolittyMarkers(extracted));
2860
- }
2861
- } else if (parsed.kind === "global-options") if (normalizedTemplateGlobalOptions) replacements.set(placeholder, buildGlobalOptionsContent(normalizedTemplateGlobalOptions));
2862
- else replacements.set(placeholder, "");
2863
- else if (parsed.kind === "index") {
2864
- const indexContent = await renderCommandIndex(command, [...deriveIndexFromFiles(files, outputPath, allCommands, ignores), ...deriveIndexFromTemplateOutputs(templateMeta, outputPath, outputPath, allCommands)], rootDoc?.index);
2865
- replacements.set(placeholder, indexContent);
2866
- }
2867
- }
2868
- let generated = outputTemplateContent.replace(/((?:\r?\n)*)([ \t]*)(\{\{politty:[^{}]*\}\})([ \t]*)((?:\r?\n)*)/g, (match, leadNl, leadWs, placeholder, trailWs, trailNl, offset, fullString) => {
2869
- const replacement = replacements.get(placeholder);
2870
- if (replacement === void 0) throw new Error(`Internal error: unresolved placeholder "${placeholder}" in template "${templatePath}".`);
2871
- const startsLine = leadNl !== "" || offset === 0 || fullString[offset - 1] === "\n";
2872
- const endsLine = trailNl !== "" || offset + match.length === fullString.length;
2873
- if (replacement === "" && startsLine && endsLine) {
2874
- if (leadNl === "" || trailNl === "") return "";
2875
- const leadBreaks = countLineBreaks(leadNl);
2876
- const trailBreaks = countLineBreaks(trailNl);
2877
- const widest = Math.max(leadBreaks, trailBreaks);
2878
- const lineEnding = leadBreaks >= trailBreaks ? detectLineEnding(leadNl) : detectLineEnding(trailNl);
2879
- return widest >= 2 ? lineEnding + lineEnding : widest === 1 ? lineEnding : "";
2880
- }
2881
- return `${leadNl}${leadWs}${replacement}${trailWs}${trailNl}`;
2882
- });
2883
- generated = `${generated.trimEnd()}${templateLineEnding}`;
2884
- generated = await applyFormatter(generated, formatter);
2885
- const comparison = compareWithExisting(generated, outputPath);
2886
- let templateStatus = "match";
2887
- let templateDiff;
2888
- if (comparison.match) {} else if (updateMode) {
2889
- writeFile(outputPath, generated);
2890
- templateStatus = comparison.fileExists ? "updated" : "created";
2891
- } else {
2892
- hasError = true;
2893
- templateStatus = "diff";
2894
- if (comparison.diff) templateDiff = comparison.diff;
2895
- }
2896
- results.push({
2897
- path: outputPath,
2898
- status: templateStatus,
2899
- diff: templateDiff
2900
- });
2901
- }
2902
- if (rootDoc) {
2903
- const rootDocFilePath = rootDoc.path;
2904
- let rootDocStatus = "match";
2905
- const rootDocDiffs = [];
2906
- const existingContent = readFile(rootDocFilePath);
2907
- if (existingContent === null) {
2908
- hasError = true;
2909
- rootDocStatus = "diff";
2910
- rootDocDiffs.push("File does not exist. Cannot validate rootDoc markers.");
2911
- } else {
2912
- let content = existingContent;
2913
- let markerUpdated = false;
2914
- const rootInfo = config.rootInfo;
2915
- const rootDocFileConfig = { title: rootInfo?.title ?? command.name };
2916
- if (rootDoc.headingLevel !== void 0) rootDocFileConfig.headingLevel = rootDoc.headingLevel;
2917
- const rootDescription = rootInfo?.description ?? command.description;
2918
- if (rootDescription !== void 0) rootDocFileConfig.description = rootDescription;
2919
- const headerResult = processFileHeader(content, rootDocFileConfig, updateMode);
2920
- content = headerResult.content;
2921
- if (headerResult.diff) rootDocDiffs.push(headerResult.diff);
2922
- if (headerResult.hasError) hasError = true;
2923
- if (headerResult.wasUpdated) markerUpdated = true;
2924
- if (rootInfo?.header) {
2925
- const headerMarkerResult = await processStaticMarker(content, "Root header", rootHeaderStartMarker(), rootHeaderEndMarker(), rootInfo.header, updateMode, formatter, usingPathConfig);
2926
- content = headerMarkerResult.content;
2927
- rootDocDiffs.push(...headerMarkerResult.diffs);
2928
- if (headerMarkerResult.hasError) hasError = true;
2929
- if (headerMarkerResult.wasUpdated) markerUpdated = true;
2930
- }
2931
- if (!usingPathConfig) {
2932
- const unexpectedSectionPaths = collectSectionMarkerPaths(content);
2933
- if (unexpectedSectionPaths.length > 0) if (updateMode) {
2934
- for (const commandPath of unexpectedSectionPaths) content = removeCommandSections(content, commandPath);
2935
- markerUpdated = true;
2936
- } else {
2937
- hasError = true;
2938
- rootDocDiffs.push(`Found unexpected section markers in rootDoc: ${unexpectedSectionPaths.map((commandPath) => `"${formatCommandPath(commandPath)}"`).join(", ")}.`);
2939
- }
2940
- }
2941
- const normalizedGlobalOptions = normalizeGlobalOptions(rootDoc.globalOptions);
2942
- if (normalizedGlobalOptions) {
2943
- const globalOptionsResult = await processGlobalOptionsMarker(content, normalizedGlobalOptions, updateMode, formatter, usingPathConfig);
2944
- content = globalOptionsResult.content;
2945
- rootDocDiffs.push(...globalOptionsResult.diffs);
2946
- if (globalOptionsResult.hasError) hasError = true;
2947
- if (globalOptionsResult.wasUpdated) markerUpdated = true;
2948
- }
2949
- const derivedCategories = deriveIndexFromFiles(files, rootDocFilePath, allCommands, ignores);
2950
- const indexScope = path$1.relative(process.cwd(), rootDocFilePath).replace(/\\/g, "/");
2951
- const indexResult = await processIndexMarker(content, derivedCategories, command, indexScope, updateMode, formatter, rootDoc.index);
2952
- content = indexResult.content;
2953
- rootDocDiffs.push(...indexResult.diffs);
2954
- if (indexResult.hasError) hasError = true;
2955
- if (indexResult.wasUpdated) markerUpdated = true;
2956
- if (rootInfo?.footer) {
2957
- const footerMarkerResult = await processStaticMarker(content, "Root footer", rootFooterStartMarker(), rootFooterEndMarker(), rootInfo.footer, updateMode, formatter, usingPathConfig);
2958
- content = footerMarkerResult.content;
2959
- rootDocDiffs.push(...footerMarkerResult.diffs);
2960
- if (footerMarkerResult.hasError) hasError = true;
2961
- if (footerMarkerResult.wasUpdated) markerUpdated = true;
2962
- }
2963
- if (updateMode && markerUpdated) {
2964
- writeFile(rootDocFilePath, content);
2965
- if (rootDocStatus === "match") rootDocStatus = "updated";
2966
- }
2967
- }
2968
- if (rootDocDiffs.length > 0) rootDocStatus = "diff";
2969
- results.push({
2970
- path: rootDocFilePath,
2971
- status: rootDocStatus,
2972
- diff: rootDocDiffs.length > 0 ? rootDocDiffs.join("\n\n") : void 0
2973
- });
2974
- }
2975
- const errorHint = hasDoctorIssues ? `Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to fix missing markers.` : `Run with ${UPDATE_GOLDEN_ENV}=true to update.`;
2976
- return {
2977
- success: !hasError,
2978
- files: results,
2979
- error: hasError ? `Documentation is out of date. ${errorHint}` : void 0
2980
- };
2981
- }
2982
- /**
2983
- * Assert that documentation matches golden files
2984
- * Throws an error if there are differences and update mode is not enabled
2985
- */
2986
- async function assertDocMatch(config) {
2987
- const result = await generateDoc(config);
2988
- if (!result.success) {
2989
- const diffMessages = result.files.filter((f) => f.status === "diff").map((f) => {
2990
- let msg = `File: ${f.path}\n`;
2991
- if (f.diff) msg += f.diff;
2992
- return msg;
2993
- }).join("\n\n");
2994
- throw new Error(`Documentation does not match golden files.\n\n${diffMessages}\n\n` + (result.error ?? `Run with ${"POLITTY_DOCS_UPDATE"}=true to update the documentation.`));
2995
- }
2996
- }
2997
- /**
2998
- * Initialize documentation files by deleting them
2999
- * Only deletes when update mode is enabled (POLITTY_DOCS_UPDATE=true)
3000
- * Use this in beforeAll to ensure skipped tests don't leave stale sections
3001
- * @param config - Config containing files to initialize, or a single file path
3002
- * @param fileSystem - Optional fs implementation (useful when fs is mocked)
3003
- */
3004
- function initDocFile(config, fileSystem) {
3005
- if (!isTruthyEnv("POLITTY_DOCS_UPDATE")) return;
3006
- if (typeof config === "string") deleteFile(config, fileSystem);
3007
- else {
3008
- const protectedPaths = new Set(Object.values(config.templates ?? {}).map(normalizeDocPathForComparison));
3009
- if (config.rootDoc) protectedPaths.add(normalizeDocPathForComparison(config.rootDoc.path));
3010
- const isProtectedPath = (p) => protectedPaths.has(normalizeDocPathForComparison(p));
3011
- if (config.files) for (const filePath of Object.keys(config.files)) {
3012
- if (isProtectedPath(filePath)) continue;
3013
- deleteFile(filePath, fileSystem);
3014
- }
3015
- if (config.templates) for (const outputPath of Object.keys(config.templates)) {
3016
- if (isProtectedPath(outputPath)) continue;
3017
- deleteFile(outputPath, fileSystem);
3018
- }
3019
- }
3020
- }
3021
-
3022
- //#endregion
3023
- export { DOCTOR_ENV, GLOBAL_OPTIONS_MARKER_PREFIX, INDEX_MARKER_PREFIX, ROOT_FOOTER_MARKER_PREFIX, ROOT_HEADER_MARKER_PREFIX, SECTION_MARKER_PREFIX, SECTION_TYPES, UPDATE_GOLDEN_ENV, assertDocMatch, buildCommandInfo, collectAllCommands, compareWithExisting, createCommandRenderer, defaultRenderers, executeExamples, formatDiff, generateDoc, globalOptionsEndMarker, globalOptionsStartMarker, indexEndMarker, indexStartMarker, initDocFile, renderArgsTable, renderArgumentsList, renderArgumentsListFromArray, renderArgumentsTable, renderArgumentsTableFromArray, renderCommandIndex, renderExamplesDefault, renderOptionsList, renderOptionsListFromArray, renderOptionsTable, renderOptionsTableFromArray, renderSubcommandsTable, renderSubcommandsTableFromArray, renderUsage, resolveLazyCommand, rootFooterEndMarker, rootFooterStartMarker, rootHeaderEndMarker, rootHeaderStartMarker, sectionEndMarker, sectionStartMarker, writeFile };
3024
- //# sourceMappingURL=index.js.map