@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,15 +1,14 @@
1
- // Config parsing layer: the zero-dependency YAML-subset parser, the file reader, the shared
2
- // user-facing suggestion strings, and the value-narrowing helpers. Split out of `config.ts` so the
3
- // config semantics module (defaults, validation, profile resolution) stays under the size budget and
4
- // so both `config.ts` and the profile resolver can read files without a circular import. This module
5
- // depends only on Node IO and `ConfigLoadError`; it never imports `config.ts` or `profiles.ts`.
1
+ // Reads the JSON and supported YAML syntax used by project settings and profiles.
2
+ //
3
+ // When a user passes `--config`, this layer turns the file into values the settings loader can validate.
4
+ // Syntax errors tell the user which part of the file to edit before trying the command again.
6
5
  import { readFileSync } from "node:fs";
7
6
  import { extname } from "node:path";
8
7
  import { ConfigLoadError } from "./config-load-error.ts";
9
8
 
10
9
  // Two common suggestion strings reused across the validators. Hoisted out so a future doc-link
11
10
  // or wording tweak lands in one place instead of N throw sites.
12
- const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `minimumSeverity:` entries).";
11
+ const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `failOn:` entries).";
13
12
  const SUGGEST_EDIT_CONFIG = "Edit `.gruff-ts.yaml` to use a valid value, or run `gruff-ts init --force` to regenerate from defaults.";
14
13
 
15
14
  const YAML_KEYWORD_SCALARS = new Map<string, boolean | null>([
@@ -29,47 +28,57 @@ interface ParsedYamlScalar {
29
28
 
30
29
  const UNMATCHED_YAML_SCALAR: ParsedYamlScalar = { isMatched: false, value: undefined };
31
30
 
32
- /*
33
- * Reads YAML or JSON config and rejects unknown extensions. Raw IO failures (e.g. `--config <path>`
34
- * pointing at a missing file) and JSON parse failures are rewrapped as ConfigLoadError so the CLI
35
- * surface stays uniform - a bare ENOENT or SyntaxError would otherwise bypass the formatted
36
- * "gruff-ts: config error" stderr path in `runWithConfigErrorHandling`.
31
+ /**
32
+ * Reads YAML or JSON config so that runWithConfigErrorHandling can present missing or malformed configs as CLI usage errors.
37
33
  *
38
- * Throws ConfigLoadError when: the file is missing (ENOENT), the contents are not valid JSON, the
39
- * YAML subset rejects the file (see parseYamlConfig), or the top-level value is not a mapping.
34
+ * @param path - File selected by --config <path> or default lookup. Its extension determines the parser.
35
+ * @param shownPath - Name used in diagnostics and error envelopes. Defaults to path.
36
+ * @returns The parsed top-level configuration mapping.
37
+ * @throws {ConfigLoadError} - The file is missing, has an unsupported extension, fails parsing, or does not contain a mapping.
38
+ * @throws {Error} - Other filesystem read errors propagate unchanged.
40
39
  */
41
- function parseConfigFile(path: string): Record<string, unknown> {
42
- const source = readConfigSource(path);
40
+ function parseConfigFile(path: string, shownPath: string = path): Record<string, unknown> {
41
+ const source = readConfigSource(path, shownPath);
43
42
  const extension = extname(path).toLowerCase();
44
- const parsed = parseConfigSource(source, extension, path);
43
+ const parsed = parseConfigSource(source, extension, shownPath);
45
44
  const config = objectValue(parsed);
46
45
  if (!config) {
47
- throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`, SUGGEST_INIT_FORCE);
46
+ throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${shownPath}`, SUGGEST_INIT_FORCE);
48
47
  }
49
48
  return config;
50
49
  }
51
50
 
52
- /*
53
- * Reads the raw config bytes. Explicit `--config <path>` skips the `defaultConfigPath` existence
54
- * check, so a typo here would otherwise dump a raw Node stack. Throws ConfigLoadError on ENOENT
55
- * with a user-actionable suggestion; rethrows every other filesystem error unchanged so an
56
- * unexpected IO failure still surfaces its native stack for debugging.
51
+ /**
52
+ * Reads config text and gives users a path-selection hint if the file is missing.
53
+ *
54
+ * @param path - Filesystem path to read.
55
+ * @param shownPath - Path label to display if the file is missing.
56
+ * @returns Decoded UTF-8 config text with any leading byte order mark removed.
57
+ * @throws {ConfigLoadError} - When the file does not exist.
58
+ * @throws {Error} - Propagates other filesystem read failures unchanged.
57
59
  */
58
- function readConfigSource(path: string): string {
60
+ function readConfigSource(path: string, shownPath: string): string {
59
61
  try {
60
62
  return readFileSync(path, "utf8").replace(/^\uFEFF/, "");
61
63
  } catch (error) {
62
64
  if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") {
63
- throw new ConfigLoadError(`Config file not found: ${path}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
65
+ throw new ConfigLoadError(`Config file not found: ${shownPath}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
64
66
  }
65
67
  throw error;
66
68
  }
67
69
  }
68
70
 
69
- // Routes to the YAML subset parser or the native JSON parser. Wraps `JSON.parse`'s SyntaxError so
70
- // a malformed `.gruff.json` surfaces through the same ConfigLoadError channel as YAML failures
71
- // (parseYamlConfig already throws ConfigLoadError on its own malformed inputs).
72
- function parseConfigSource(source: string, extension: string, path: string): unknown {
71
+ /**
72
+ * Parses config text as YAML or JSON according to its file extension so the caller can validate or reject unsupported formats.
73
+ *
74
+ * @param source - Decoded config file contents to parse.
75
+ * @param extension - Lowercase file extension selecting YAML (`.yaml`, `.yml`) or JSON (`.json`) parsing.
76
+ * @param shownPath - Display path included in invalid JSON errors on the shared CLI error channel.
77
+ * @returns The parsed config value, or `undefined` when the extension is unsupported.
78
+ * @throws {ConfigLoadError} - For invalid JSON syntax or input rejected by the YAML parser.
79
+ * @throws {Error} - Propagates other JSON parser errors unchanged.
80
+ */
81
+ function parseConfigSource(source: string, extension: string, shownPath: string): unknown {
73
82
  if (extension === ".yaml" || extension === ".yml") {
74
83
  return parseYamlConfig(source);
75
84
  }
@@ -80,7 +89,7 @@ function parseConfigSource(source: string, extension: string, path: string): unk
80
89
  return JSON.parse(source) as unknown;
81
90
  } catch (error) {
82
91
  if (error instanceof SyntaxError) {
83
- throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${path}).`, SUGGEST_EDIT_CONFIG);
92
+ throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${shownPath}).`, SUGGEST_EDIT_CONFIG);
84
93
  }
85
94
  throw error;
86
95
  }
@@ -100,10 +109,12 @@ interface YamlParser {
100
109
  index: number;
101
110
  }
102
111
 
103
- /*
104
- * Custom YAML parser that intentionally supports only a documented subset (mappings, arrays,
105
- * scalars, inline `[]`/`{}`) - keeps gruff free of a yaml dependency. Throws on malformed input
106
- * because silently misparsing config would produce wrong findings and a stable but broken baseline.
112
+ /**
113
+ * Parses the supported YAML configuration subset of mappings, sequences and scalar values.
114
+ *
115
+ * @param source - Config text to split into YAML lines and parse.
116
+ * @returns The top-level mapping. Blank or comment-only input yields an empty mapping.
117
+ * @throws {ConfigLoadError} - For a non-mapping root, a missing mapping separator, excess indentation or tabs in retained line indentation.
107
118
  */
108
119
  function parseYamlConfig(source: string): Record<string, unknown> {
109
120
  const parser = { lines: yamlLines(source), index: 0 };
@@ -115,8 +126,13 @@ function parseYamlConfig(source: string): Record<string, unknown> {
115
126
  return config;
116
127
  }
117
128
 
118
- // Dispatch entry for a block. Empty (no lines at this indent) returns `{}`; sequence lines lead
119
- // into the array parser; everything else is an object/mapping.
129
+ /**
130
+ * Parses the next YAML sequence or mapping block at or beyond the minimum indentation, advancing the cursor through it.
131
+ *
132
+ * @param parser - Mutable YAML line cursor positioned at the start of the candidate block.
133
+ * @param indent - Minimum column indentation required to continue into a nested block.
134
+ * @returns The parsed sequence or mapping, or an empty object when no line remains at or above `indent`.
135
+ */
120
136
  function parseYamlBlock(parser: YamlParser, indent: number): unknown {
121
137
  const line = parser.lines[parser.index];
122
138
  if (!line || line.indent < indent) {
@@ -125,8 +141,14 @@ function parseYamlBlock(parser: YamlParser, indent: number): unknown {
125
141
  return isYamlArrayLine(line) ? parseYamlArray(parser, line.indent) : parseYamlObject(parser, line.indent);
126
142
  }
127
143
 
128
- // Walks mapping entries at one indent level, stopping when the next line dedents or switches to
129
- // sequence form. Throws on unexpected indent so a missed key isn't silently swallowed.
144
+ /**
145
+ * Parses a YAML mapping block at the supplied indentation until a dedent, sequence item, or end of input stops it.
146
+ *
147
+ * @param parser - Mutable YAML line cursor positioned at the first entry of the mapping.
148
+ * @param indent - Expected indentation column for entries belonging to this mapping.
149
+ * @returns The parsed key-value mapping, or an empty object if no entry was consumed.
150
+ * @throws {ConfigLoadError} - When an entry is over-indented (so a misaligned entry cannot be read here) or has a duplicate/invalid key.
151
+ */
130
152
  function parseYamlObject(parser: YamlParser, indent: number): Record<string, unknown> {
131
153
  const result: Record<string, unknown> = {};
132
154
  while (parser.index < parser.lines.length) {
@@ -140,17 +162,44 @@ function parseYamlObject(parser: YamlParser, indent: number): Record<string, unk
140
162
  return result;
141
163
  }
142
164
 
143
- // Inline scalar after the colon → leaf value; bare key → recurse into nested block. Keys are
144
- // unquoted so `"foo"` and `foo` produce the same result key.
165
+ /**
166
+ * Reads one YAML key-value entry and records it on the target mapping so the settings loader can validate it.
167
+ * An empty value with no indented block represents an empty mapping, and quoting a key keeps the same meaning.
168
+ *
169
+ * @param parser - Mutable YAML line cursor positioned on `line`; advances past the entry and any nested block.
170
+ * @param indent - Indentation column of the enclosing mapping, used to detect nested blocks.
171
+ * @param line - Current YAML mapping line to split and unquote into a key and value.
172
+ * @param result - Mapping object mutated with the parsed property via `Object.defineProperty`.
173
+ * @returns Nothing. Mutates `result` with the parsed entry and advances `parser`.
174
+ * @throws {ConfigLoadError} - When the mapping contains an invalid or duplicate key.
175
+ */
145
176
  function addYamlObjectEntry(parser: YamlParser, indent: number, line: YamlLine, result: Record<string, unknown>): void {
146
177
  const [rawKey, rawValue] = yamlKeyValuePair(line.content);
178
+ const key = unquoteYaml(rawKey.trim());
179
+ // Two copies of `failOn` could come from a config merge. Ask the user to reconcile them before scanning.
180
+ if (Object.hasOwn(result, key)) {
181
+ throw new ConfigLoadError(`Duplicate configuration key ${JSON.stringify(key)}.`, SUGGEST_EDIT_CONFIG);
182
+ }
147
183
  const scalarText = rawValue.trim();
148
184
  parser.index += 1;
149
- result[unquoteYaml(rawKey.trim())] = scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {});
185
+ // A key followed by an indented block, such as `failOn:`, gets its settings from those lines.
186
+ Object.defineProperty(result, key, {
187
+ value: scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {}),
188
+ enumerable: true,
189
+ configurable: true,
190
+ writable: true,
191
+ });
150
192
  }
151
193
 
152
- // Block-style YAML sequence. Inline `[...]` arrays are handled by `parseYamlCollectionScalar`;
153
- // this walks the `- item` lines and recurses into nested values for empty `-` openers.
194
+ /**
195
+ * Parses a block YAML sequence at the supplied indentation until a dedent, non-sequence line, or end of input stops it.
196
+ * Inline arrays are handled separately by `parseYamlCollectionScalar`.
197
+ *
198
+ * @param parser - Mutable YAML line cursor positioned at the first sequence item.
199
+ * @param indent - Expected dash indentation column for items in this sequence.
200
+ * @returns The parsed sequence items, or an empty array if no item was consumed.
201
+ * @throws {ConfigLoadError} - When a sequence item is over-indented or a nested mapping entry is invalid.
202
+ */
154
203
  function parseYamlArray(parser: YamlParser, indent: number): unknown[] {
155
204
  const result: unknown[] = [];
156
205
  while (parser.index < parser.lines.length) {
@@ -164,8 +213,14 @@ function parseYamlArray(parser: YamlParser, indent: number): unknown[] {
164
213
  return result;
165
214
  }
166
215
 
167
- // Three branches: bare `-` (recurse for nested), `- key: value` (mapping item), `- scalar`.
168
- // Bare-dash items return null when the nested block is empty so the array entry isn't elided.
216
+ /**
217
+ * Parses one YAML sequence item on `line` and advances `parser` past the item and any continuation lines it consumes.
218
+ *
219
+ * @param parser - Mutable YAML line cursor positioned at `line`.
220
+ * @param indent - Dash indentation column used to distinguish nested blocks from outer or sibling lines.
221
+ * @param line - Current sequence entry beginning with `-` or `- `.
222
+ * @returns A nested value, a mapping for `- key: value`, a scalar, or `null` for a bare dash with no deeper block so that its slot is kept.
223
+ */
169
224
  function parseYamlArrayItem(parser: YamlParser, indent: number, line: YamlLine): unknown {
170
225
  const itemText = line.content === "-" ? "" : line.content.slice(2).trim();
171
226
  parser.index += 1;
@@ -177,26 +232,67 @@ function parseYamlArrayItem(parser: YamlParser, indent: number, line: YamlLine):
177
232
  return pair ? parseYamlArrayMappingItem(parser, indent, pair) : parseYamlScalar(itemText);
178
233
  }
179
234
 
180
- // `- key: value` form: the first key is on the dash line, subsequent keys live as a nested object.
181
- // Mirrors the inline-vs-nested split of `addYamlObjectEntry`.
235
+ /**
236
+ * Builds a sequence item mapping from the key-value pair on its dash line and consumes any nested values or sibling keys.
237
+ *
238
+ * @param parser - Mutable YAML line cursor positioned immediately after the dash line.
239
+ * @param indent - Dash indentation column used to locate nested values and sibling keys.
240
+ * @param pair - Raw key and value slices split from the dash line after `- `.
241
+ * @returns The sequence item mapping, using an empty object when the first value is blank and has no deeper block.
242
+ */
182
243
  function parseYamlArrayMappingItem(parser: YamlParser, indent: number, pair: [string, string]): Record<string, unknown> {
183
244
  const [rawKey, rawValue] = pair;
184
245
  const scalarText = rawValue.trim();
185
- return {
246
+ const mappingItem: Record<string, unknown> = {
186
247
  [unquoteYaml(rawKey.trim())]: scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {}),
187
248
  };
249
+ addYamlArrayItemSiblingKeys(parser, indent, mappingItem);
250
+ return mappingItem;
188
251
  }
189
252
 
190
- // Returns the nested block if the next line indents further, otherwise the caller's `fallback`.
191
- // `fallback` is `{}` for mappings (empty value → empty object) and `null` for sequences.
253
+ /**
254
+ * Reads sibling keys at the first continuation's indentation so that YAML entries such as sensitiveExclusions: can span lines.
255
+ *
256
+ * @param parser - YAML cursor positioned after the item's first entry
257
+ * @param indent - indentation of the item's dash line, which continuations must exceed
258
+ * @param mappingItem - mapping that receives the sibling entries
259
+ * @returns - nothing. Adds the sibling entries and advances the cursor past them, if present.
260
+ */
261
+ function addYamlArrayItemSiblingKeys(parser: YamlParser, indent: number, mappingItem: Record<string, unknown>): void {
262
+ const keyIndent = parser.lines[parser.index]?.indent;
263
+ // Nothing deeper than the dash line means the item ended with its first key.
264
+ if (keyIndent === undefined || keyIndent <= indent) {
265
+ return;
266
+ }
267
+ while (parser.index < parser.lines.length) {
268
+ const line = parser.lines[parser.index];
269
+ // A change in indentation or the start of the next sequence item ends this item's key list.
270
+ if (!line || line.indent !== keyIndent || isYamlArrayLine(line)) {
271
+ break;
272
+ }
273
+ addYamlObjectEntry(parser, keyIndent, line, mappingItem);
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Parses a deeper nested YAML block if present, or returns the supplied fallback when no nested lines follow.
279
+ *
280
+ * @param parser - Mutable YAML line cursor positioned at the candidate nested block.
281
+ * @param indent - Parent indentation column that a nested block must strictly exceed.
282
+ * @param fallback - Value returned when no deeper line follows, such as `{}` for a bare mapping value or `null` for a bare sequence item.
283
+ * @returns The parsed nested block value, or `fallback` when the next line is absent or not indented deeper.
284
+ */
192
285
  function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unknown): unknown {
193
286
  const nestedIndent = parser.lines[parser.index]?.indent;
194
287
  return nestedIndent !== undefined && nestedIndent > indent ? parseYamlBlock(parser, nestedIndent) : fallback;
195
288
  }
196
289
 
197
- /*
198
- * Throws when a mapping line has no `:` separator - the parser cannot recover, and a silent skip
199
- * would hide a real config typo from the user.
290
+ /**
291
+ * Requires a valid mapping separator so a malformed entry produces a config error.
292
+ *
293
+ * @param content - YAML mapping line to split into a key and value.
294
+ * @returns Raw key and value slices on either side of the separator.
295
+ * @throws {ConfigLoadError} - When no unquoted colon is followed by whitespace or the end of the line.
200
296
  */
201
297
  function yamlKeyValuePair(content: string): [string, string] {
202
298
  const pair = splitYamlKeyValue(content);
@@ -206,14 +302,23 @@ function yamlKeyValuePair(content: string): [string, string] {
206
302
  return pair;
207
303
  }
208
304
 
209
- // `- ` or bare `-` only - two-dash openers and ambiguous variants are not sequence entries.
305
+ /**
306
+ * Checks whether a YAML line starts a block sequence entry (`- ` or a single `-`).
307
+ *
308
+ * @param line - Comment-stripped YAML line to inspect.
309
+ * @returns `true` when `line.content` starts with `"- "` or equals `"-"`; otherwise `false`.
310
+ */
210
311
  function isYamlArrayLine(line: YamlLine): boolean {
211
312
  return line.content.startsWith("- ") || line.content === "-";
212
313
  }
213
314
 
214
- /*
215
- * Throws when a line is indented more than expected at this scope. Without this guard, a stray
216
- * indent would silently produce a sub-mapping and the user's config would mean something different.
315
+ /**
316
+ * Rejects excess indentation before a misaligned entry can be consumed at the current block level.
317
+ *
318
+ * @param line - Candidate entry in the current YAML block.
319
+ * @param indent - Expected indentation for entries at this block level.
320
+ * @returns Nothing. Lets the caller continue parsing when the line is within the indentation limit.
321
+ * @throws {ConfigLoadError} - When the line is indented deeper than the current block level.
217
322
  */
218
323
  function assertYamlIndent(line: YamlLine, indent: number): void {
219
324
  if (line.indent > indent) {
@@ -221,10 +326,12 @@ function assertYamlIndent(line: YamlLine, indent: number): void {
221
326
  }
222
327
  }
223
328
 
224
- /*
225
- * Pre-pass that drops blank/comment lines and rejects tab-indented input. Tabs are forbidden
226
- * because mixing them with spaces is the canonical YAML footgun, so the parser throws rather than
227
- * guess at the user's intent.
329
+ /**
330
+ * Prepares meaningful YAML lines for indentation-based parsing by stripping comments and skipping blank lines.
331
+ *
332
+ * @param source - YAML document text to split into lines.
333
+ * @returns Retained lines with their indentation width and trimmed content, or an empty array if none remain.
334
+ * @throws {ConfigLoadError} - When a retained line contains a tab in its leading whitespace.
228
335
  */
229
336
  function yamlLines(source: string): YamlLine[] {
230
337
  const lines: YamlLine[] = [];
@@ -242,15 +349,24 @@ function yamlLines(source: string): YamlLine[] {
242
349
  return lines;
243
350
  }
244
351
 
245
- // Drops `# comment` text but only when the `#` is not inside quotes - `foo: "a # b"` keeps the
246
- // comment-like substring as part of the string value, matching YAML semantics.
352
+ /**
353
+ * Strips any trailing YAML comment starting at an unquoted `#` at line start or after whitespace.
354
+ * Hashes inside quotes or unquoted words remain part of the value.
355
+ *
356
+ * @param line - Raw YAML line text to trim of comments.
357
+ * @returns Substring before the comment `#`, or the full `line` when no comment marker is present.
358
+ */
247
359
  function stripYamlComment(line: string): string {
248
360
  const commentIndex = firstUnquotedIndex(line, (character, index) => character === "#" && (index === 0 || /\s/.test(line[index - 1] ?? "")));
249
361
  return commentIndex === undefined ? line : line.slice(0, commentIndex);
250
362
  }
251
363
 
252
- // Finds the first `:<space>` outside quotes. Required because a quoted value can legitimately
253
- // contain `:` (`url: "https://..."`) and the parser must not split at the first occurrence.
364
+ /**
365
+ * Splits candidate YAML mapping text at the first unquoted colon followed by whitespace or the end of the text.
366
+ *
367
+ * @param mappingText - Candidate YAML mapping content to split.
368
+ * @returns Raw `[key, value]` slices on either side of the separator, or `undefined` when no mapping separator exists.
369
+ */
254
370
  function splitYamlKeyValue(mappingText: string): [string, string] | undefined {
255
371
  const separatorIndex = firstUnquotedIndex(mappingText, (character, index) => {
256
372
  const next = mappingText[index + 1];
@@ -259,8 +375,13 @@ function splitYamlKeyValue(mappingText: string): [string, string] | undefined {
259
375
  return separatorIndex === undefined ? undefined : [mappingText.slice(0, separatorIndex), mappingText.slice(separatorIndex + 1)];
260
376
  }
261
377
 
262
- // Tries each scalar parser in order; the first to claim a match wins. Bare strings are the
263
- // fallback so callers never end up with `undefined` for a non-empty scalar.
378
+ /**
379
+ * Trims a YAML scalar and decodes it with the first matching collection, quoted, keyword, or number parser.
380
+ * When no parser matches, returns the trimmed text (so a blank scalar becomes an empty string).
381
+ *
382
+ * @param scalarText - Raw scalar slice to trim and decode.
383
+ * @returns The decoded JS value from the first matching parser, or the trimmed string fallback.
384
+ */
264
385
  function parseYamlScalar(scalarText: string): unknown {
265
386
  const trimmed = scalarText.trim();
266
387
  for (const parser of [parseYamlCollectionScalar, parseYamlQuotedScalar, parseYamlKeywordScalar, parseYamlNumberScalar]) {
@@ -272,7 +393,12 @@ function parseYamlScalar(scalarText: string): unknown {
272
393
  return trimmed;
273
394
  }
274
395
 
275
- // Parses YAML collection scalar from source text.
396
+ /**
397
+ * Parses trimmed YAML text in square brackets or an empty brace mapping (`{}`) into a matched scalar result.
398
+ *
399
+ * @param trimmed - Pre-trimmed YAML scalar text to test for inline collection syntax.
400
+ * @returns A matched result for an inline array or `{}`, or `UNMATCHED_YAML_SCALAR` so another parser can try it.
401
+ */
276
402
  function parseYamlCollectionScalar(trimmed: string): ParsedYamlScalar {
277
403
  if (trimmed === "[]") {
278
404
  return matchedYamlScalar([]);
@@ -286,8 +412,12 @@ function parseYamlCollectionScalar(trimmed: string): ParsedYamlScalar {
286
412
  return UNMATCHED_YAML_SCALAR;
287
413
  }
288
414
 
289
- // `"..."` or `'...'` wrapped. Calls `unquoteYaml` so the resulting value matches what a real YAML
290
- // engine would produce; matched-state flag separates "empty quoted string" from "not a quoted scalar".
415
+ /**
416
+ * Parses trimmed YAML text enclosed in matching outer single or double quotes and decodes supported escapes.
417
+ *
418
+ * @param trimmed - Pre-trimmed YAML scalar text to test for matching outer quotes.
419
+ * @returns A matched string (including empty quoted text `""`), or `UNMATCHED_YAML_SCALAR` without matching quotes.
420
+ */
291
421
  function parseYamlQuotedScalar(trimmed: string): ParsedYamlScalar {
292
422
  if (isQuotedYaml(trimmed)) {
293
423
  return matchedYamlScalar(unquoteYaml(trimmed));
@@ -295,8 +425,12 @@ function parseYamlQuotedScalar(trimmed: string): ParsedYamlScalar {
295
425
  return UNMATCHED_YAML_SCALAR;
296
426
  }
297
427
 
298
- // Recognises `true`/`false`/`null`/`~` (case-insensitive). The keyword table is shared so the
299
- // parser produces consistent JS values (`null` instead of the string "null").
428
+ /**
429
+ * Matches YAML boolean and null keywords (`true`, `false`, `null`, `~`) case-insensitively.
430
+ *
431
+ * @param trimmed - Pre-trimmed YAML scalar text to look up in `YAML_KEYWORD_SCALARS`.
432
+ * @returns A matched result holding a boolean or `null`, or `UNMATCHED_YAML_SCALAR` so number or plain-text parsing can handle it.
433
+ */
300
434
  function parseYamlKeywordScalar(trimmed: string): ParsedYamlScalar {
301
435
  const normalized = trimmed.toLowerCase();
302
436
  if (YAML_KEYWORD_SCALARS.has(normalized)) {
@@ -305,8 +439,12 @@ function parseYamlKeywordScalar(trimmed: string): ParsedYamlScalar {
305
439
  return UNMATCHED_YAML_SCALAR;
306
440
  }
307
441
 
308
- // Strict numeric pattern - no octals, no special floats. Numbers that don't fit fall through to
309
- // bare-string handling, so `0xFF` or `1e10` stay as strings rather than producing surprising values.
442
+ /**
443
+ * Parses decimal numbers matching `YAML_NUMBER_SCALAR`; hexadecimal and exponent forms fall through as strings.
444
+ *
445
+ * @param trimmed - Pre-trimmed YAML scalar text to test against decimal number syntax.
446
+ * @returns A matched result containing the `Number` value, or `UNMATCHED_YAML_SCALAR` for non-decimal text.
447
+ */
310
448
  function parseYamlNumberScalar(trimmed: string): ParsedYamlScalar {
311
449
  if (YAML_NUMBER_SCALAR.test(trimmed)) {
312
450
  return matchedYamlScalar(Number(trimmed));
@@ -314,14 +452,22 @@ function parseYamlNumberScalar(trimmed: string): ParsedYamlScalar {
314
452
  return UNMATCHED_YAML_SCALAR;
315
453
  }
316
454
 
317
- // Returns a "matched" result with the parsed value, distinguishing real matches from the shared
318
- // `UNMATCHED_YAML_SCALAR` sentinel used by every parser that failed.
455
+ /**
456
+ * Wraps a parsed scalar value as matched to distinguish real `null` or empty matches from `UNMATCHED_YAML_SCALAR`.
457
+ *
458
+ * @param scalarValue - Decoded scalar or inline collection value produced by a scalar parser.
459
+ * @returns A `ParsedYamlScalar` with `isMatched: true` and `value` set to `scalarValue`.
460
+ */
319
461
  function matchedYamlScalar(scalarValue: unknown): ParsedYamlScalar {
320
462
  return { isMatched: true, value: scalarValue };
321
463
  }
322
464
 
323
- // Inline `[a, b, c]` arrays. Items are split on unquoted commas and each item recurses through
324
- // `parseYamlScalar` so nested types resolve correctly.
465
+ /**
466
+ * Parses an inline `[a, b, c]` YAML array, splitting on unquoted commas and recursing through `parseYamlScalar` so nested types resolve correctly.
467
+ *
468
+ * @param arrayText - Bracket-delimited inline YAML array text.
469
+ * @returns Array of decoded item values, or an empty array when only whitespace sits inside the brackets.
470
+ */
325
471
  function parseYamlInlineArray(arrayText: string): unknown[] {
326
472
  const inner = arrayText.slice(1, -1).trim();
327
473
  if (inner.length === 0) {
@@ -330,8 +476,13 @@ function parseYamlInlineArray(arrayText: string): unknown[] {
330
476
  return splitYamlInlineItems(inner).map((item) => parseYamlScalar(item));
331
477
  }
332
478
 
333
- // Quote-aware split on commas. Treating a quoted comma as a separator would corrupt entries like
334
- // `["a, b", "c"]` - same reason `splitYamlKeyValue` is also quote-aware.
479
+ /**
480
+ * Splits inline array body text on unquoted commas into trimmed item strings while keeping quoted commas inside their items.
481
+ * Empty fields are returned as empty strings so their array positions are preserved.
482
+ *
483
+ * @param itemsText - Inner text of an inline YAML array with outer brackets removed.
484
+ * @returns Array of trimmed item strings in positional order.
485
+ */
335
486
  function splitYamlInlineItems(itemsText: string): string[] {
336
487
  const items: string[] = [];
337
488
  let start = 0;
@@ -350,8 +501,13 @@ interface QuoteScanState {
350
501
  isEscaped: boolean;
351
502
  }
352
503
 
353
- // Walks `value` calling `predicate` only at quote-free positions. Used by both the comment
354
- // stripper and the colon splitter to keep quoted text inert.
504
+ /**
505
+ * Searches `sourceText` outside quotes, passing unquoted characters and indexes to `predicate` until one is accepted.
506
+ *
507
+ * @param sourceText - Text to scan while skipping single- and double-quoted regions.
508
+ * @param predicate - Test invoked with each unquoted character and its string index.
509
+ * @returns The first accepted unquoted index, or `undefined` when no unquoted position matches.
510
+ */
355
511
  function firstUnquotedIndex(sourceText: string, predicate: (character: string, index: number) => boolean): number | undefined {
356
512
  for (const index of unquotedIndexes(sourceText)) {
357
513
  const character = sourceText[index] ?? "";
@@ -362,8 +518,13 @@ function firstUnquotedIndex(sourceText: string, predicate: (character: string, i
362
518
  return undefined;
363
519
  }
364
520
 
365
- // All quote-free positions in `value`, optionally filtered by a specific character. The two-mode
366
- // shape lets the same lexer feed both `firstUnquotedIndex` and the inline-array splitter.
521
+ /**
522
+ * Collects character indexes outside quoted regions in `sourceText`, excluding the quote delimiters themselves.
523
+ *
524
+ * @param sourceText - Text to walk with the YAML quote state machine.
525
+ * @param expectedCharacter - Optional single-character filter; an omitted or empty filter keeps every eligible index.
526
+ * @returns Array of qualifying indexes in ascending order, or an empty array if none qualify.
527
+ */
367
528
  function unquotedIndexes(sourceText: string, expectedCharacter?: string): number[] {
368
529
  const indexes: number[] = [];
369
530
  const state: QuoteScanState = { quote: undefined, isEscaped: false };
@@ -383,8 +544,14 @@ function unquotedIndexes(sourceText: string, expectedCharacter?: string): number
383
544
  return indexes;
384
545
  }
385
546
 
386
- // Returns true and mutates `state` when the character was inside a quoted region. The escape
387
- // handling is double-quote-only because YAML single-quote strings have no `\` escapes.
547
+ /**
548
+ * Consumes one character inside an active quoted region and updates the quote and escape state in place.
549
+ * Backslash escapes apply only inside double quotes.
550
+ *
551
+ * @param character - Current character being scanned.
552
+ * @param state - Mutable quote and escape state updated when a quote closes or an escape begins.
553
+ * @returns `true` if `character` was consumed by an active quote; `false` with no active quote so the caller can handle the character.
554
+ */
388
555
  function consumeQuotedCharacter(character: string, state: QuoteScanState): boolean {
389
556
  if (!state.quote) {
390
557
  return false;
@@ -400,21 +567,34 @@ function consumeQuotedCharacter(character: string, state: QuoteScanState): boole
400
567
  return true;
401
568
  }
402
569
 
403
- // Single and double quotes only - YAML allows backticks elsewhere but they're not part of the
404
- // supported subset here, and the parser would have to reject them anyway.
570
+ /**
571
+ * Recognizes a character as a YAML quote delimiter when it is a single or double quote; backticks remain ordinary text.
572
+ *
573
+ * @param character - Single character from the source scan to test.
574
+ * @returns `true` for `"` or `'`; otherwise `false`.
575
+ */
405
576
  function isYamlQuote(character: string): boolean {
406
577
  return character === "\"" || character === "'";
407
578
  }
408
579
 
409
- // Both endpoints must use the same quote character; mismatched openers/closers are treated as
410
- // plain text rather than a parse error so a single stray quote in user prose doesn't fail the config.
580
+ /**
581
+ * Checks whether `scalarText` is enclosed in matching outer quotes; both endpoints must use the same quote character.
582
+ * Mismatched openers/closers are treated as plain text rather than a parse error so a stray quote in prose does not fail the config.
583
+ *
584
+ * @param scalarText - Trimmed YAML scalar text to inspect.
585
+ * @returns `true` when `scalarText` has length >= 2 and matching outer `"` or `'` quotes; otherwise `false`.
586
+ */
411
587
  function isQuotedYaml(scalarText: string): boolean {
412
588
  return scalarText.length >= 2 && ((scalarText.startsWith("\"") && scalarText.endsWith("\"")) || (scalarText.startsWith("'") && scalarText.endsWith("'")));
413
589
  }
414
590
 
415
- // Removes quotes and decodes the supported escapes: `''` doubling for single quotes, and `\n`,
416
- // `\r`, `\t`, `\"`, `\\` for double quotes. Anything else passes through unchanged so the parser
417
- // reports the user's exact intent rather than mangling unknown escape sequences.
591
+ /**
592
+ * Removes matching outer quotes from a YAML scalar and decodes `''` in single quotes or `\"`, `\\`, `\n`, `\r`, `\t` in double quotes.
593
+ * Unquoted input returns unchanged and unrecognized escapes inside quoted text are preserved.
594
+ *
595
+ * @param scalarText - Scalar or key text to unquote if enclosed in matching outer quotes.
596
+ * @returns The unquoted and unescaped string, or `scalarText` unchanged if not validly quoted.
597
+ */
418
598
  function unquoteYaml(scalarText: string): string {
419
599
  if (!isQuotedYaml(scalarText)) {
420
600
  return scalarText;
@@ -438,21 +618,34 @@ function unquoteYaml(scalarText: string): string {
438
618
  });
439
619
  }
440
620
 
441
- // Type narrowing for `Record<string, unknown>`. Returns undefined (not null) for non-objects so
442
- // the caller can use the standard optional-chaining pattern through the rest of the config layer.
621
+ /**
622
+ * Narrows a config value to a non-null, non-array object so callers can read named options with optional chaining for absent mappings.
623
+ *
624
+ * @param configValue - Parsed JSON or YAML value to check.
625
+ * @returns `configValue` cast as a record when it is a non-null, non-array object; `undefined` for null, arrays, and primitives.
626
+ */
443
627
  function objectValue(configValue: unknown): Record<string, unknown> | undefined {
444
628
  return typeof configValue === "object" && configValue !== null && !Array.isArray(configValue) ? (configValue as Record<string, unknown>) : undefined;
445
629
  }
446
630
 
447
- // Returns the array or an empty array - never undefined - so callers can iterate without a guard.
631
+ /**
632
+ * Returns the array or an empty array (never `undefined`) so callers can iterate without a guard.
633
+ *
634
+ * @param configValue - Parsed JSON or YAML value to normalize to an array.
635
+ * @returns `configValue` if it is an array; otherwise `[]`.
636
+ */
448
637
  function arrayValue(configValue: unknown): unknown[] {
449
638
  return Array.isArray(configValue) ? configValue : [];
450
639
  }
451
640
 
452
- // String type narrowing. Exported so other modules can share a single string-test that matches
453
- // the config-side semantics (rejects non-string truthy values like numbers).
641
+ /**
642
+ * Narrows a value to `string`, exported so other modules share a single string-test matching config semantics (rejects truthy numbers).
643
+ *
644
+ * @param configValue - Unknown value from parsed configuration to test.
645
+ * @returns `true` when `typeof configValue === "string"`; otherwise `false`.
646
+ */
454
647
  function isString(configValue: unknown): configValue is string {
455
648
  return typeof configValue === "string";
456
649
  }
457
650
 
458
- export { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE };
651
+ export { arrayValue, isString, objectValue, parseConfigFile, parseYamlConfig, stripYamlComment, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE };