@eserstack/codebase 0.0.0-stage → 5.0.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 (175) hide show
  1. package/README.md +301 -2
  2. package/dist/changelog-gen.d.ts +105 -0
  3. package/dist/changelog-gen.js +498 -0
  4. package/dist/changelog-text.d.ts +39 -0
  5. package/dist/changelog-text.js +82 -0
  6. package/dist/cli-support.d.ts +140 -0
  7. package/dist/cli-support.js +244 -0
  8. package/dist/cli-system/app-opts.d.ts +15 -0
  9. package/dist/cli-system/app-opts.js +13 -0
  10. package/dist/cli-system/app.d.ts +29 -0
  11. package/dist/cli-system/app.js +12 -0
  12. package/dist/cli-system/handlers/completions-setup.d.ts +14 -0
  13. package/dist/cli-system/handlers/completions-setup.js +139 -0
  14. package/dist/cli-system/handlers/completions.d.ts +3 -0
  15. package/dist/cli-system/handlers/completions.js +79 -0
  16. package/dist/cli-system/handlers/doctor.d.ts +8 -0
  17. package/dist/cli-system/handlers/doctor.js +146 -0
  18. package/dist/cli-system/handlers/info.d.ts +3 -0
  19. package/dist/cli-system/handlers/info.js +69 -0
  20. package/dist/cli-system/handlers/install.d.ts +8 -0
  21. package/dist/cli-system/handlers/install.js +137 -0
  22. package/dist/cli-system/handlers/mod.d.ts +12 -0
  23. package/dist/cli-system/handlers/mod.js +13 -0
  24. package/dist/cli-system/handlers/uninstall.d.ts +3 -0
  25. package/dist/cli-system/handlers/uninstall.js +60 -0
  26. package/dist/cli-system/handlers/update.d.ts +76 -0
  27. package/dist/cli-system/handlers/update.js +310 -0
  28. package/dist/cli-system/handlers/version-check.d.ts +16 -0
  29. package/dist/cli-system/handlers/version-check.js +176 -0
  30. package/dist/cli-system/handlers/version.d.ts +3 -0
  31. package/dist/cli-system/handlers/version.js +45 -0
  32. package/dist/cli-system/mod.d.ts +19 -0
  33. package/dist/cli-system/mod.js +52 -0
  34. package/dist/commitmsg.d.ts +28 -0
  35. package/dist/commitmsg.js +232 -0
  36. package/dist/directive-analysis.d.ts +75 -0
  37. package/dist/directive-analysis.js +223 -0
  38. package/dist/ffi-client.d.ts +11 -0
  39. package/dist/ffi-client.js +12 -0
  40. package/dist/file-tool.d.ts +96 -0
  41. package/dist/file-tool.js +274 -0
  42. package/dist/file-tools-shared.d.ts +81 -0
  43. package/dist/file-tools-shared.js +276 -0
  44. package/dist/gh-contributors.d.ts +89 -0
  45. package/dist/gh-contributors.js +205 -0
  46. package/dist/gh.d.ts +3 -0
  47. package/dist/gh.js +64 -0
  48. package/dist/git-listing.d.ts +27 -0
  49. package/dist/git-listing.js +69 -0
  50. package/dist/git.d.ts +172 -0
  51. package/dist/git.js +277 -0
  52. package/dist/install.d.ts +34 -0
  53. package/dist/install.js +421 -0
  54. package/dist/main.d.ts +22 -0
  55. package/dist/main.js +14 -0
  56. package/dist/mod.d.ts +25 -0
  57. package/dist/mod.js +8 -0
  58. package/dist/module.d.ts +10 -0
  59. package/dist/module.js +221 -0
  60. package/dist/native-functions.d.ts +1088 -0
  61. package/dist/native-functions.js +2 -0
  62. package/dist/npm-externals.d.ts +27 -0
  63. package/dist/npm-externals.js +34 -0
  64. package/dist/npm-workspace-specifiers.d.ts +6 -0
  65. package/dist/npm-workspace-specifiers.js +45 -0
  66. package/dist/package/loader.d.ts +34 -0
  67. package/dist/package/loader.js +203 -0
  68. package/dist/package/mod.d.ts +36 -0
  69. package/dist/package/mod.js +5 -0
  70. package/dist/package/types.d.ts +142 -0
  71. package/dist/package/types.js +32 -0
  72. package/dist/package/workspace.d.ts +33 -0
  73. package/dist/package/workspace.js +158 -0
  74. package/dist/package/writer.d.ts +52 -0
  75. package/dist/package/writer.js +278 -0
  76. package/dist/package.json +275 -0
  77. package/dist/release-notes.d.ts +90 -0
  78. package/dist/release-notes.js +236 -0
  79. package/dist/release-tag.d.ts +46 -0
  80. package/dist/release-tag.js +95 -0
  81. package/dist/release.d.ts +145 -0
  82. package/dist/release.js +584 -0
  83. package/dist/source-mask.d.ts +3 -0
  84. package/dist/source-mask.js +185 -0
  85. package/dist/validate-bom.d.ts +5 -0
  86. package/dist/validate-bom.js +43 -0
  87. package/dist/validate-case-conflict.d.ts +5 -0
  88. package/dist/validate-case-conflict.js +43 -0
  89. package/dist/validate-circular-deps.d.ts +11 -0
  90. package/dist/validate-circular-deps.js +53 -0
  91. package/dist/validate-code-conventions.d.ts +22 -0
  92. package/dist/validate-code-conventions.js +166 -0
  93. package/dist/validate-commit-msg.d.ts +50 -0
  94. package/dist/validate-commit-msg.js +182 -0
  95. package/dist/validate-docs.d.ts +20 -0
  96. package/dist/validate-docs.js +78 -0
  97. package/dist/validate-eof.d.ts +5 -0
  98. package/dist/validate-eof.js +61 -0
  99. package/dist/validate-error-coverage.d.ts +28 -0
  100. package/dist/validate-error-coverage.js +93 -0
  101. package/dist/validate-export-names.d.ts +17 -0
  102. package/dist/validate-export-names.js +56 -0
  103. package/dist/validate-filenames.d.ts +5 -0
  104. package/dist/validate-filenames.js +151 -0
  105. package/dist/validate-json.d.ts +5 -0
  106. package/dist/validate-json.js +71 -0
  107. package/dist/validate-large-files.d.ts +5 -0
  108. package/dist/validate-large-files.js +41 -0
  109. package/dist/validate-laroux-boundaries.d.ts +19 -0
  110. package/dist/validate-laroux-boundaries.js +59 -0
  111. package/dist/validate-licenses.d.ts +5 -0
  112. package/dist/validate-licenses.js +137 -0
  113. package/dist/validate-line-endings.d.ts +5 -0
  114. package/dist/validate-line-endings.js +47 -0
  115. package/dist/validate-merge-conflict.d.ts +5 -0
  116. package/dist/validate-merge-conflict.js +46 -0
  117. package/dist/validate-mod-exports.d.ts +16 -0
  118. package/dist/validate-mod-exports.js +56 -0
  119. package/dist/validate-naming-and-todos.d.ts +5 -0
  120. package/dist/validate-naming-and-todos.js +70 -0
  121. package/dist/validate-runtime-js-apis.d.ts +5 -0
  122. package/dist/validate-runtime-js-apis.js +78 -0
  123. package/dist/validate-secrets.d.ts +5 -0
  124. package/dist/validate-secrets.js +82 -0
  125. package/dist/validate-self-imports.d.ts +5 -0
  126. package/dist/validate-self-imports.js +78 -0
  127. package/dist/validate-server-loc.d.ts +32 -0
  128. package/dist/validate-server-loc.js +94 -0
  129. package/dist/validate-shebangs.d.ts +5 -0
  130. package/dist/validate-shebangs.js +33 -0
  131. package/dist/validate-stream.d.ts +25 -0
  132. package/dist/validate-stream.js +62 -0
  133. package/dist/validate-submodules.d.ts +5 -0
  134. package/dist/validate-submodules.js +43 -0
  135. package/dist/validate-symlinks.d.ts +5 -0
  136. package/dist/validate-symlinks.js +46 -0
  137. package/dist/validate-toml.d.ts +5 -0
  138. package/dist/validate-toml.js +40 -0
  139. package/dist/validate-trailing-whitespace.d.ts +5 -0
  140. package/dist/validate-trailing-whitespace.js +49 -0
  141. package/dist/validate-yaml.d.ts +5 -0
  142. package/dist/validate-yaml.js +40 -0
  143. package/dist/validation/config.d.ts +17 -0
  144. package/dist/validation/config.js +30 -0
  145. package/dist/validation/mod.d.ts +71 -0
  146. package/dist/validation/mod.js +479 -0
  147. package/dist/validation/registry.d.ts +57 -0
  148. package/dist/validation/registry.js +256 -0
  149. package/dist/validation/types.d.ts +101 -0
  150. package/dist/validation/types.js +2 -0
  151. package/dist/validation/validators/circular-deps.d.ts +7 -0
  152. package/dist/validation/validators/circular-deps.js +31 -0
  153. package/dist/validation/validators/docs.d.ts +7 -0
  154. package/dist/validation/validators/docs.js +38 -0
  155. package/dist/validation/validators/error-coverage.d.ts +2 -0
  156. package/dist/validation/validators/error-coverage.js +46 -0
  157. package/dist/validation/validators/export-names.d.ts +7 -0
  158. package/dist/validation/validators/export-names.js +31 -0
  159. package/dist/validation/validators/laroux-boundaries.d.ts +2 -0
  160. package/dist/validation/validators/laroux-boundaries.js +29 -0
  161. package/dist/validation/validators/mod-exports.d.ts +7 -0
  162. package/dist/validation/validators/mod-exports.js +32 -0
  163. package/dist/validation/validators/mod.d.ts +11 -0
  164. package/dist/validation/validators/mod.js +12 -0
  165. package/dist/validation/validators/server-loc.d.ts +2 -0
  166. package/dist/validation/validators/server-loc.js +48 -0
  167. package/dist/versions.d.ts +166 -0
  168. package/dist/versions.js +349 -0
  169. package/dist/violation-baseline.d.ts +58 -0
  170. package/dist/violation-baseline.js +144 -0
  171. package/dist/walk-stream.d.ts +24 -0
  172. package/dist/walk-stream.js +55 -0
  173. package/dist/workspace-discovery.d.ts +60 -0
  174. package/dist/workspace-discovery.js +130 -0
  175. package/package.json +222 -3
@@ -0,0 +1,479 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Validation system for codebase checks
4
+ *
5
+ * Provides a unified `validate()` function that runs all applicable validators
6
+ * based on the project's stack configuration in `.eser/manifest.yml`.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import * as validation from "@eserstack/codebase/validation";
11
+ *
12
+ * // Run all validators (defaults to all when no .eser/manifest.yml)
13
+ * const result = await validation.validate();
14
+ *
15
+ * if (!result.passed) {
16
+ * console.log("Validation failed:", result.results);
17
+ * }
18
+ *
19
+ * // Check skipped validators
20
+ * for (const skipped of result.skipped) {
21
+ * console.log(`Skipped ${skipped.name}: ${skipped.reason}`);
22
+ * }
23
+ * ```
24
+ *
25
+ * @module
26
+ */
27
+ import * as shellFlags from "@eserstack/shell/args/flags";
28
+ import * as results from "@eserstack/primitives/results";
29
+ import * as tui from "@eserstack/shell/tui";
30
+ import { runtime } from "@eserstack/standards/cross-runtime";
31
+ import * as streams from "@eserstack/streams";
32
+ import * as cliSupport from "../cli-support.js";
33
+ import * as config from "./config.js";
34
+ import * as registry from "./registry.js";
35
+ import * as ffiClient from "../ffi-client.js";
36
+ import * as gitListing from "../git-listing.js";
37
+ /** Maximum number of validators to run concurrently in read-only (non-fix) mode. */
38
+ const CONCURRENCY_LIMIT = 8;
39
+ // Re-export config functions
40
+ export { getProjectConfigPath, loadProjectConfig } from "./config.js";
41
+ export { getValidator, getValidatorNames, getValidators, getWorkflowTools, registerValidator, } from "./registry.js";
42
+ /**
43
+ * Run Go's built-in language-agnostic file validators.
44
+ *
45
+ * Covers: EOF newline, BOM markers, trailing whitespace, line endings,
46
+ * merge conflict markers, secret patterns, large file detection.
47
+ *
48
+ * Falls back to an empty result when the native library is unavailable.
49
+ * For the full TS validation registry (including JS/TS-specific checks),
50
+ * use `validate()` instead.
51
+ *
52
+ * @param options - Validator options
53
+ * @returns Array of validator results, one per built-in validator
54
+ */
55
+ export const runBuiltinValidators = async (options = {}) => {
56
+ await ffiClient.ensureLib();
57
+ const lib = ffiClient.getLib();
58
+ if (lib === null) {
59
+ return [];
60
+ }
61
+ try {
62
+ const parsed = lib.call("codebaseValidateFiles", {
63
+ dir: options.dir,
64
+ validators: options.validators !== undefined ? [...options.validators] : undefined,
65
+ extensions: options.extensions !== undefined ? [...options.extensions] : undefined,
66
+ ...(await gitListing.bridgeGitOptions(lib, options.dir, options.gitAware ?? true)),
67
+ });
68
+ if (!parsed.error && parsed.results !== undefined) {
69
+ return parsed.results;
70
+ }
71
+ }
72
+ catch {
73
+ /* library loaded but call failed — return empty */
74
+ }
75
+ return [];
76
+ };
77
+ /**
78
+ * Run all applicable validators
79
+ *
80
+ * Loads project configuration from `.eser/manifest.yml`, determines which validators
81
+ * to run based on the stack configuration, and returns aggregated results.
82
+ *
83
+ * When no `.eser/manifest.yml` exists, all validators are run by default.
84
+ *
85
+ * @param options - Validation options
86
+ * @returns Validation result with all validator outputs
87
+ */
88
+ export const validate = async (options = {}) => {
89
+ const root = options.root ?? runtime.process.cwd();
90
+ // Load project config
91
+ const projectConfig = await config.loadProjectConfig(root);
92
+ const projectStack = projectConfig?.stack ?? [];
93
+ const skipList = [...(options.skip ?? [])];
94
+ const onlyList = options.only ?? [];
95
+ // Get all validators
96
+ const validators = registry.getValidators();
97
+ const results = [];
98
+ const skipped = [];
99
+ const disabled = [];
100
+ for (const validator of validators) {
101
+ // Check if only specific validators should run
102
+ if (onlyList.length > 0 && !onlyList.includes(validator.name)) {
103
+ continue;
104
+ }
105
+ // Check if explicitly skipped
106
+ if (skipList.includes(validator.name)) {
107
+ disabled.push(validator.name);
108
+ continue;
109
+ }
110
+ // Check if required stack is present
111
+ // When projectStack is empty (no .eser/manifest.yml), run all validators
112
+ if (validator.requiredStacks.length > 0 && projectStack.length > 0) {
113
+ const hasStack = validator.requiredStacks.some((s) => projectStack.includes(s));
114
+ if (!hasStack) {
115
+ skipped.push({
116
+ name: validator.name,
117
+ reason: `Requires '${validator.requiredStacks.join("' or '")}' stack`,
118
+ });
119
+ continue;
120
+ }
121
+ }
122
+ // Run validator
123
+ const mergedOptions = {
124
+ ...(options.fix !== undefined ? { fix: options.fix } : {}),
125
+ };
126
+ // Validators run one at a time: with fix on, each one writes files that
127
+ // the next one reads.
128
+ // oxlint-disable-next-line no-await-in-loop
129
+ const result = await validator.validate({
130
+ root,
131
+ options: mergedOptions,
132
+ });
133
+ results.push(result);
134
+ }
135
+ return {
136
+ passed: results.every((r) => r.passed),
137
+ results,
138
+ skipped,
139
+ disabled,
140
+ };
141
+ };
142
+ const splitList = (value) => typeof value === "string" ? value.split(",").map((s) => s.trim()) : [];
143
+ /**
144
+ * Parse the validation CLI arguments: `--root`, `--only`, `--skip`, `--fix`,
145
+ * `--json`, `--yes` (`-y`), `--help` (`-h`).
146
+ */
147
+ export const parseCliArgs = (cliArgs) => {
148
+ const { values } = shellFlags.parseArgs(cliArgs, {
149
+ options: {
150
+ root: { type: "string" },
151
+ only: { type: "string" },
152
+ skip: { type: "string" },
153
+ fix: { type: "boolean" },
154
+ help: { type: "boolean", short: "h" },
155
+ json: { type: "boolean" },
156
+ yes: { type: "boolean", short: "y" },
157
+ },
158
+ });
159
+ const root = values["root"];
160
+ return {
161
+ help: values["help"] === true,
162
+ json: values["json"] === true,
163
+ yes: values["yes"] === true,
164
+ fix: values["fix"] === true,
165
+ root: typeof root === "string" ? root : undefined,
166
+ onlyList: splitList(values["only"]),
167
+ skipList: splitList(values["skip"]),
168
+ };
169
+ };
170
+ /**
171
+ * CLI main function for standalone usage.
172
+ *
173
+ * Displays a spinner while loading config, a progress bar while running
174
+ * validators, and streams per-validator results in real-time using TUI
175
+ * components from `@eserstack/shell/tui`.
176
+ */
177
+ export const main = async (cliArgs) => {
178
+ const args = parseCliArgs(cliArgs ?? runtime.process.args);
179
+ if (args.help) {
180
+ const { output: out } = cliSupport.createCliContext();
181
+ out.writeln("Usage: node ./validation/mod.ts [options]");
182
+ out.writeln();
183
+ out.writeln("Options:");
184
+ out.writeln(" --root <dir> Root directory (default: cwd)");
185
+ out.writeln(" --only <validators> Run only specific validators (comma-separated)");
186
+ out.writeln(" --skip <validators> Skip specific validators (comma-separated)");
187
+ out.writeln(" --fix Auto-fix issues where supported");
188
+ out.writeln(" -y, --yes Auto-confirm all fix prompts (no interactive prompts)");
189
+ out.writeln(" --json Output results as JSON (suppresses TUI output)");
190
+ out.writeln(" -h, --help Show this help message");
191
+ await out.flush();
192
+ return results.ok(undefined);
193
+ }
194
+ const { json: jsonMode, yes: autoYes, root, fix, onlyList, skipList } = args;
195
+ // --- JSON mode: force non-interactive, suppress all TUI output ---
196
+ const { ctx } = jsonMode
197
+ ? {
198
+ ctx: tui.createTuiContext({ interaction: "non-interactive" }),
199
+ }
200
+ : cliSupport.createCliContext();
201
+ const isInteractive = ctx.interaction === "interactive";
202
+ // --- Shared: load config and filter validators ---
203
+ const resolvedRoot = root ?? runtime.process.cwd();
204
+ if (!jsonMode) {
205
+ tui.intro(ctx, "Validating codebase...");
206
+ }
207
+ // --- Load project config with spinner ---
208
+ const spinner = jsonMode
209
+ ? undefined
210
+ : tui.createSpinner(ctx, "Loading config...");
211
+ spinner?.start();
212
+ const projectConfig = await config.loadProjectConfig(resolvedRoot);
213
+ const projectStack = projectConfig?.stack ?? [];
214
+ const stackInfo = projectStack.length > 0
215
+ ? projectStack.join(", ")
216
+ : "all (no .eser/manifest.yml)";
217
+ spinner?.succeed("Config loaded");
218
+ if (!jsonMode) {
219
+ tui.log.info(ctx, `Stack: ${stackInfo}`);
220
+ }
221
+ // --- Filter validators (mirrors validate() logic) ---
222
+ const allValidators = registry.getValidators();
223
+ const validatorsToRun = [];
224
+ const skippedValidators = [];
225
+ const disabledNames = [];
226
+ for (const validator of allValidators) {
227
+ // Check --only filter
228
+ if (onlyList.length > 0 && !onlyList.includes(validator.name)) {
229
+ continue;
230
+ }
231
+ // Check --skip filter
232
+ if (skipList.includes(validator.name)) {
233
+ disabledNames.push(validator.name);
234
+ continue;
235
+ }
236
+ // Check stack compatibility
237
+ if (validator.requiredStacks.length > 0 && projectStack.length > 0) {
238
+ const hasStack = validator.requiredStacks.some((s) => projectStack.includes(s));
239
+ if (!hasStack) {
240
+ skippedValidators.push({
241
+ name: validator.name,
242
+ reason: `Requires '${validator.requiredStacks.join("' or '")}' stack`,
243
+ });
244
+ continue;
245
+ }
246
+ }
247
+ validatorsToRun.push(validator);
248
+ }
249
+ // --- Run validators with progress bar ---
250
+ const validatorResults = [];
251
+ const progress = jsonMode
252
+ ? undefined
253
+ : tui.createProgress(ctx, {
254
+ total: validatorsToRun.length,
255
+ label: "Validating...",
256
+ });
257
+ progress?.start();
258
+ // Stream a single validator result to the TUI and advance the progress bar.
259
+ const streamResult = (result) => {
260
+ validatorResults.push(result);
261
+ if (!jsonMode) {
262
+ const stats = Object.entries(result.stats)
263
+ .map(([key, value]) => `${value} ${key}`)
264
+ .join(", ");
265
+ const label = `${result.name.padEnd(18)} (${stats})`;
266
+ if (result.passed) {
267
+ tui.log.success(ctx, `PASS ${label}`);
268
+ }
269
+ else {
270
+ tui.log.error(ctx, `FAIL ${label}`);
271
+ }
272
+ }
273
+ progress?.advance(1);
274
+ };
275
+ if (fix) {
276
+ // --- Sequential execution (fix mode) ---
277
+ // Fixes may depend on execution order and require interactive confirm prompts,
278
+ // so we must run validators one at a time.
279
+ for (const validator of validatorsToRun) {
280
+ // First pass: always run in check-only mode. Sequential, as above.
281
+ // oxlint-disable-next-line no-await-in-loop
282
+ const checkResult = await validator.validate({
283
+ root: resolvedRoot,
284
+ options: {},
285
+ });
286
+ let finalResult = checkResult;
287
+ // If fix is requested and issues were found, handle fix logic
288
+ if (!checkResult.passed) {
289
+ let shouldFix = true;
290
+ // In interactive mode without --yes, prompt for confirmation
291
+ if (isInteractive && !autoYes && !jsonMode) {
292
+ const issueCount = checkResult.issues.length;
293
+ // One prompt at a time, as above.
294
+ // oxlint-disable-next-line no-await-in-loop
295
+ const confirmed = await tui.confirm(ctx, {
296
+ message: `Fix ${issueCount} issue(s) found by ${validator.name}?`,
297
+ initialValue: true,
298
+ });
299
+ if (tui.isCancel(confirmed) || !confirmed) {
300
+ shouldFix = false;
301
+ }
302
+ }
303
+ if (shouldFix) {
304
+ // Re-run with fix enabled. Sequential, as above.
305
+ // oxlint-disable-next-line no-await-in-loop
306
+ finalResult = await validator.validate({
307
+ root: resolvedRoot,
308
+ options: { fix: true },
309
+ });
310
+ }
311
+ }
312
+ streamResult(finalResult);
313
+ }
314
+ }
315
+ else {
316
+ // --- Parallel execution (read-only mode) ---
317
+ // Bounded concurrency: up to CONCURRENCY_LIMIT validators run at once.
318
+ // Results stream in completion order; Promise.allSettled ensures one
319
+ // failure does not abort the rest.
320
+ let index = 0;
321
+ const executeWorker = async () => {
322
+ while (index < validatorsToRun.length) {
323
+ const currentIndex = index++;
324
+ const validator = validatorsToRun[currentIndex];
325
+ if (validator === undefined) {
326
+ break;
327
+ }
328
+ try {
329
+ // A worker runs one validator at a time; the worker count is what
330
+ // bounds the concurrency.
331
+ // oxlint-disable-next-line no-await-in-loop
332
+ const result = await validator.validate({
333
+ root: resolvedRoot,
334
+ options: {},
335
+ });
336
+ streamResult(result);
337
+ }
338
+ catch (error) {
339
+ // Validator threw — synthesise a failed result so the run continues.
340
+ const failedResult = {
341
+ name: validator.name,
342
+ passed: false,
343
+ issues: [
344
+ {
345
+ severity: "error",
346
+ message: String(error),
347
+ },
348
+ ],
349
+ stats: { filesChecked: 0, issuesFound: 1, fixedCount: 0 },
350
+ };
351
+ streamResult(failedResult);
352
+ }
353
+ }
354
+ };
355
+ const workerCount = Math.min(CONCURRENCY_LIMIT, validatorsToRun.length);
356
+ const workers = Array.from({ length: workerCount }, () => executeWorker());
357
+ await Promise.allSettled(workers);
358
+ }
359
+ progress?.stop("Validation complete");
360
+ // --- Print skipped validators ---
361
+ if (!jsonMode && skippedValidators.length > 0) {
362
+ tui.log.step(ctx, "Skipped (stack not configured):");
363
+ for (const skippedItem of skippedValidators) {
364
+ tui.log.step(ctx, ` - ${skippedItem.name}: ${skippedItem.reason}`);
365
+ }
366
+ }
367
+ // --- Print disabled validators ---
368
+ if (!jsonMode && disabledNames.length > 0) {
369
+ tui.log.step(ctx, "Disabled:");
370
+ for (const disabledItem of disabledNames) {
371
+ tui.log.step(ctx, ` - ${disabledItem}`);
372
+ }
373
+ }
374
+ // --- Print issues grouped by location ---
375
+ const allIssues = validatorResults.flatMap((r) => r.issues.map((i) => ({ validator: r.name, ...i })));
376
+ if (!jsonMode && allIssues.length > 0) {
377
+ tui.log.warn(ctx, `Issues (${allIssues.length}):`);
378
+ // Group issues by location (file path or validator name)
379
+ const grouped = new Map();
380
+ for (const issue of allIssues) {
381
+ const location = issue.file ?? issue.validator;
382
+ const existing = grouped.get(location) ?? [];
383
+ existing.push(issue);
384
+ grouped.set(location, existing);
385
+ }
386
+ for (const [location, issues] of grouped) {
387
+ tui.log.step(ctx, ` ${location}`);
388
+ for (const issue of issues) {
389
+ const severityTag = issue.severity === "error" ? "error" : "warning";
390
+ const lineInfo = issue.line !== undefined ? `:${issue.line}` : "";
391
+ if (issue.severity === "error") {
392
+ tui.log.error(ctx, ` ${severityTag}${lineInfo}: ${issue.message}`);
393
+ }
394
+ else {
395
+ tui.log.warn(ctx, ` ${severityTag}${lineInfo}: ${issue.message}`);
396
+ }
397
+ }
398
+ }
399
+ }
400
+ // --- Interactive error drill-down ---
401
+ const failedResults = validatorResults.filter((r) => !r.passed);
402
+ if (!jsonMode && isInteractive && failedResults.length > 0) {
403
+ while (true) {
404
+ const selectOptions = [
405
+ ...failedResults.map((r) => ({
406
+ value: r.name,
407
+ label: `${r.name} (${r.issues.length} issue(s))`,
408
+ })),
409
+ { value: "__done__", label: "Done" },
410
+ ];
411
+ // Interactive loop: each prompt waits for the previous answer.
412
+ // oxlint-disable-next-line no-await-in-loop
413
+ const selected = await tui.select(ctx, {
414
+ message: "View details for which validator?",
415
+ options: selectOptions,
416
+ });
417
+ if (tui.isCancel(selected) || selected === "__done__") {
418
+ break;
419
+ }
420
+ // Show detailed issues for the selected validator
421
+ const selectedResult = failedResults.find((r) => r.name === selected);
422
+ if (selectedResult !== undefined) {
423
+ tui.log.info(ctx, `Details for ${selectedResult.name} (${selectedResult.issues.length} issue(s)):`);
424
+ for (const issue of selectedResult.issues) {
425
+ const severityTag = issue.severity === "error" ? "error" : "warning";
426
+ const fileInfo = issue.file ?? selectedResult.name;
427
+ const lineInfo = issue.line !== undefined ? `:${issue.line}` : "";
428
+ if (issue.severity === "error") {
429
+ tui.log.error(ctx, ` ${fileInfo}${lineInfo} [${severityTag}]: ${issue.message}`);
430
+ }
431
+ else {
432
+ tui.log.warn(ctx, ` ${fileInfo}${lineInfo} [${severityTag}]: ${issue.message}`);
433
+ }
434
+ }
435
+ }
436
+ }
437
+ }
438
+ // --- JSON mode: output structured JSON and exit ---
439
+ if (jsonMode) {
440
+ const passed = validatorResults.every((r) => r.passed);
441
+ const jsonOutput = JSON.stringify({
442
+ passed,
443
+ results: validatorResults,
444
+ skipped: skippedValidators,
445
+ disabled: disabledNames,
446
+ }, null, 2);
447
+ // The JSON goes to stdout; the non-interactive context above writes to
448
+ // stderr. Closing the output flushes it before the command returns.
449
+ const jsonOut = streams.output({
450
+ renderer: streams.renderers.plain(),
451
+ sink: streams.sinks.stdout(),
452
+ });
453
+ jsonOut.writeln(jsonOutput);
454
+ await jsonOut.close();
455
+ if (!passed) {
456
+ return results.fail({
457
+ message: "",
458
+ exitCode: 1,
459
+ });
460
+ }
461
+ return results.ok(undefined);
462
+ }
463
+ // --- Summary ---
464
+ const failedCount = failedResults.length;
465
+ if (failedCount > 0) {
466
+ tui.outro(ctx, `${failedCount} check(s) failed with ${allIssues.length} issue(s)`);
467
+ return results.fail({
468
+ message: `${failedCount} check(s) failed with ${allIssues.length} issue(s)`,
469
+ exitCode: 1,
470
+ });
471
+ }
472
+ tui.outro(ctx, "All checks passed!");
473
+ return results.ok(undefined);
474
+ };
475
+ if (import.meta.main) {
476
+ // Entry point: the await only runs when this file is executed directly.
477
+ // oxlint-disable-next-line node/no-top-level-await
478
+ await cliSupport.exitCli(await main());
479
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Validator registry with lazy initialization.
3
+ *
4
+ * Also provides `getWorkflowTools()` — an adapter that returns all
5
+ * codebase tools in a shape structurally compatible with
6
+ * `WorkflowTool` from `@eserstack/workflows` (duck-typed, no import needed).
7
+ *
8
+ * @module
9
+ */
10
+ import type { Validator } from "./types.ts";
11
+ /**
12
+ * Register a validator in the registry.
13
+ */
14
+ export declare const registerValidator: (validator: Validator) => void;
15
+ /**
16
+ * Get a validator by name.
17
+ */
18
+ export declare const getValidator: (name: string) => Validator | null;
19
+ /**
20
+ * Get all registered validators.
21
+ */
22
+ export declare const getValidators: () => readonly Validator[];
23
+ /**
24
+ * Get all validator names.
25
+ */
26
+ export declare const getValidatorNames: () => readonly string[];
27
+ /**
28
+ * A tool compatible with the `@eserstack/workflows` engine.
29
+ * Structurally typed — no import from `@eserstack/workflows` required.
30
+ */
31
+ export type WorkflowCompatibleTool = {
32
+ readonly name: string;
33
+ readonly description: string;
34
+ readonly run: (options: Record<string, unknown>) => Promise<{
35
+ readonly name: string;
36
+ readonly passed: boolean;
37
+ readonly issues: readonly {
38
+ readonly path?: string;
39
+ readonly line?: number;
40
+ readonly message: string;
41
+ readonly fixed?: boolean;
42
+ }[];
43
+ readonly mutations: readonly {
44
+ readonly path: string;
45
+ readonly oldContent: string;
46
+ readonly newContent: string;
47
+ }[];
48
+ readonly stats: Record<string, number>;
49
+ }>;
50
+ };
51
+ /**
52
+ * Get all codebase tools adapted for the workflow engine.
53
+ *
54
+ * Returns duck-typed objects structurally compatible with
55
+ * `WorkflowTool` from `@eserstack/workflows`.
56
+ */
57
+ export declare const getWorkflowTools: () => readonly WorkflowCompatibleTool[];