@whil/guardrails 0.0.0-stage → 0.2.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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +222 -2
  3. package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
  4. package/catalog-assets/eslint-guardrails/config.mjs +21 -0
  5. package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
  6. package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
  7. package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
  8. package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
  9. package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
  10. package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
  11. package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
  12. package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
  13. package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
  14. package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
  15. package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
  16. package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
  17. package/catalog-assets/eslint-rules/no-let.mjs +14 -0
  18. package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
  19. package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
  20. package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
  21. package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
  22. package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
  23. package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
  24. package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
  25. package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
  26. package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
  27. package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
  28. package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
  29. package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
  30. package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
  31. package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
  32. package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
  33. package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
  34. package/catalog-assets/githooks/commit-msg +13 -0
  35. package/catalog-assets/githooks/pre-commit +26 -0
  36. package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
  37. package/dist/cli.js +57 -0
  38. package/dist/config/runtime.js +15 -0
  39. package/dist/core/app/analysis.js +74 -0
  40. package/dist/core/app/args.js +46 -0
  41. package/dist/core/app/catalog.js +20 -0
  42. package/dist/core/app/ci-plan.js +14 -0
  43. package/dist/core/app/claude.js +37 -0
  44. package/dist/core/app/commands/add-rule.js +32 -0
  45. package/dist/core/app/commands/agents-md.js +13 -0
  46. package/dist/core/app/commands/apply.js +74 -0
  47. package/dist/core/app/commands/audit.js +38 -0
  48. package/dist/core/app/commands/check.js +33 -0
  49. package/dist/core/app/commands/detect.js +16 -0
  50. package/dist/core/app/commands/init.js +127 -0
  51. package/dist/core/app/commands/learn.js +48 -0
  52. package/dist/core/app/commands/plan.js +40 -0
  53. package/dist/core/app/commands/pr-status.js +66 -0
  54. package/dist/core/app/commands/self-check.js +20 -0
  55. package/dist/core/app/git.js +75 -0
  56. package/dist/core/app/github.js +146 -0
  57. package/dist/core/app/hooks-script.js +27 -0
  58. package/dist/core/app/output.js +17 -0
  59. package/dist/core/app/run.js +32 -0
  60. package/dist/core/app/session.js +18 -0
  61. package/dist/core/app/timing.js +11 -0
  62. package/dist/core/domain/agents-md.js +104 -0
  63. package/dist/core/domain/audit-report.js +7 -0
  64. package/dist/core/domain/changes.js +8 -0
  65. package/dist/core/domain/check-report.js +23 -0
  66. package/dist/core/domain/claude-settings.js +42 -0
  67. package/dist/core/domain/constraint.js +7 -0
  68. package/dist/core/domain/diagnostics.js +3 -0
  69. package/dist/core/domain/errors.js +21 -0
  70. package/dist/core/domain/facts.js +18 -0
  71. package/dist/core/domain/init-report.js +28 -0
  72. package/dist/core/domain/json.js +43 -0
  73. package/dist/core/domain/learn.js +78 -0
  74. package/dist/core/domain/log-parse.js +99 -0
  75. package/dist/core/domain/pack-defaults.js +17 -0
  76. package/dist/core/domain/pack.js +1 -0
  77. package/dist/core/domain/perf.js +65 -0
  78. package/dist/core/domain/pr-comment.js +45 -0
  79. package/dist/core/domain/pr-loop.js +85 -0
  80. package/dist/core/domain/profile.js +25 -0
  81. package/dist/core/domain/protection.js +43 -0
  82. package/dist/core/domain/ratchet.js +40 -0
  83. package/dist/core/domain/registry.js +32 -0
  84. package/dist/core/domain/remote.js +4 -0
  85. package/dist/core/domain/result.js +25 -0
  86. package/dist/core/domain/thresholds.js +9 -0
  87. package/dist/core/domain/types.js +1 -0
  88. package/dist/core/domain/workflows.js +252 -0
  89. package/dist/core/infra/assets.js +7 -0
  90. package/dist/core/infra/backup.js +31 -0
  91. package/dist/core/infra/baseline.js +8 -0
  92. package/dist/core/infra/changes.js +17 -0
  93. package/dist/core/infra/exec.js +15 -0
  94. package/dist/core/infra/facts.js +61 -0
  95. package/dist/core/infra/fs.js +87 -0
  96. package/dist/core/infra/gh.js +32 -0
  97. package/dist/core/infra/hash.js +10 -0
  98. package/dist/core/infra/hooks.js +31 -0
  99. package/dist/core/infra/learn-sources.js +40 -0
  100. package/dist/core/infra/lock.js +102 -0
  101. package/dist/core/infra/pr.js +48 -0
  102. package/dist/core/infra/result-cache.js +49 -0
  103. package/dist/packs/index.js +6 -0
  104. package/dist/packs/js-ts/app/add-rule.js +116 -0
  105. package/dist/packs/js-ts/app/analysis.js +111 -0
  106. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  107. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  108. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  109. package/dist/packs/js-ts/app/fixes.js +3 -0
  110. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  111. package/dist/packs/js-ts/app/project.js +87 -0
  112. package/dist/packs/js-ts/app/tests.js +63 -0
  113. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  114. package/dist/packs/js-ts/domain/ci.js +47 -0
  115. package/dist/packs/js-ts/domain/data.js +34 -0
  116. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  117. package/dist/packs/js-ts/domain/disables.js +11 -0
  118. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  119. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  120. package/dist/packs/js-ts/domain/hooks.js +49 -0
  121. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  122. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  123. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  124. package/dist/packs/js-ts/domain/profile.js +112 -0
  125. package/dist/packs/js-ts/domain/report.js +74 -0
  126. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  127. package/dist/packs/js-ts/domain/signals.js +14 -0
  128. package/dist/packs/js-ts/domain/testing.js +33 -0
  129. package/dist/packs/js-ts/domain/ts-options.js +16 -0
  130. package/dist/packs/js-ts/index.js +50 -0
  131. package/dist/packs/js-ts/infra/eslint.js +50 -0
  132. package/dist/packs/js-ts/infra/scan.js +25 -0
  133. package/dist/packs/js-ts/infra/tsc.js +29 -0
  134. package/dist/packs/nextjs/domain/data.js +9 -0
  135. package/dist/packs/nextjs/domain/profile.js +21 -0
  136. package/dist/packs/nextjs/domain/specs.js +33 -0
  137. package/dist/packs/nextjs/index.js +23 -0
  138. package/dist/packs/node/domain/specs.js +23 -0
  139. package/dist/packs/node/index.js +26 -0
  140. package/dist/packs/react/domain/data.js +9 -0
  141. package/dist/packs/react/domain/specs.js +63 -0
  142. package/dist/packs/react/index.js +30 -0
  143. package/dist/packs/react-native/domain/specs.js +29 -0
  144. package/dist/packs/react-native/domain/testing.js +20 -0
  145. package/dist/packs/react-native/index.js +30 -0
  146. package/package.json +60 -4
@@ -0,0 +1,56 @@
1
+ import { PLUGIN_DIR, RULES_JSON, newConfigText, parseRulesState, renderPluginIndex, serializeState, wireConfigText } from "../domain/eslint-state.js";
2
+ import { appError } from "../../../core/domain/errors.js";
3
+ import { collect, err, ok } from "../../../core/domain/result.js";
4
+ import { readAsset } from "../../../core/infra/assets.js";
5
+ import { listDir, readText, writeManaged } from "../../../core/infra/fs.js";
6
+ import { jsTs } from "../domain/data.js";
7
+ export function readState(root) {
8
+ const parsed = parseRulesState(readText(root, RULES_JSON));
9
+ if (parsed.ok)
10
+ return parsed;
11
+ return err(appError("unsupported-config", `${RULES_JSON} is not valid JSON`, { file: RULES_JSON, fix: `Fix the JSON syntax in ${RULES_JSON}; guardrails owns this file and keeps one entry per rule.` }));
12
+ }
13
+ export function writeState(root, state) {
14
+ return writeManaged(root, RULES_JSON, serializeState(state));
15
+ }
16
+ export function installedRuleIds(root) {
17
+ return listDir(root, `${PLUGIN_DIR}/rules`)
18
+ .filter((file) => file.endsWith(".mjs") && !file.endsWith(".test.mjs") && !file.startsWith("_"))
19
+ .map((file) => file.slice(0, -".mjs".length));
20
+ }
21
+ export function copyOwnRule(root, id) {
22
+ return [
23
+ writeManaged(root, `${PLUGIN_DIR}/rules/${id}.mjs`, readAsset(`eslint-rules/${id}.mjs`)),
24
+ writeManaged(root, `${PLUGIN_DIR}/rules/_rule-tester.mjs`, readAsset("eslint-rules/_rule-tester.mjs")),
25
+ ];
26
+ }
27
+ export function writeIndexAndConfig(root) {
28
+ return [
29
+ writeManaged(root, `${PLUGIN_DIR}/index.mjs`, renderPluginIndex(installedRuleIds(root))),
30
+ writeManaged(root, `${PLUGIN_DIR}/config.mjs`, readAsset("eslint-guardrails/config.mjs")),
31
+ ];
32
+ }
33
+ export function wireEslintConfig(ctx) {
34
+ const { root, profile } = ctx;
35
+ const data = jsTs(profile);
36
+ const config = data.eslint.config;
37
+ if (config === null) {
38
+ const created = newConfigText(data);
39
+ return created === null
40
+ ? err(appError("missing-dependency", "no ESLint config and typescript-eslint is not a dependency, so guardrails cannot create one", { file: "package.json", fix: "Install eslint and typescript-eslint as exact devDependencies, then run apply again." }))
41
+ : ok([writeManaged(root, "eslint.config.mjs", created)]);
42
+ }
43
+ if (data.eslint.guardrailsWired)
44
+ return ok([]);
45
+ const wired = config.endsWith(".mjs") || config.endsWith(".js") ? wireConfigText(readText(root, config) ?? "") : null;
46
+ return wired === null
47
+ ? err(appError("unsupported-config", `cannot add the guardrails config to ${config} automatically`, {
48
+ file: config,
49
+ fix: `Add \`import { guardrailsConfig } from "./eslint/guardrails/config.mjs";\` and spread \`...guardrailsConfig\` into the exported array of ${config} (.mjs or .js with \`export default [...]\` or defineConfig([...])), then run apply again.`,
50
+ }))
51
+ : ok([writeManaged(root, config, wired)]);
52
+ }
53
+ export function allWritten(results) {
54
+ const collected = collect(results);
55
+ return collected.ok ? ok(collected.value.flat()) : collected;
56
+ }
@@ -0,0 +1,3 @@
1
+ export function fixesFor(packs) {
2
+ return packs.reduce((all, pack) => ({ ...all, ...pack.fixes }), {});
3
+ }
@@ -0,0 +1,30 @@
1
+ import { BASELINE_PATH, coverageLowered, evaluateCoverage, parseBaseline } from "../../../core/domain/ratchet.js";
2
+ import { baseRef, changedFiles, readAtRef } from "../../../core/infra/changes.js";
3
+ import { readBaseline, writeBaseline } from "../../../core/infra/baseline.js";
4
+ import { exists, readText } from "../../../core/infra/fs.js";
5
+ import { parseJsonc } from "../../../core/domain/json.js";
6
+ import { coverageDiagnostic, loweredDiagnostic, missingTestDiagnostic } from "../domain/pr-diagnostics.js";
7
+ import { missingTests } from "../domain/pr-tests.js";
8
+ import { measuredLines, pickTesting } from "../domain/testing.js";
9
+ function loweredAgainstBase(ctx, ref) {
10
+ const before = ref === null ? null : readAtRef(ctx.root, ref, BASELINE_PATH);
11
+ const previous = before === null ? undefined : parseBaseline(parseJsonc(before)).coverage;
12
+ const current = readBaseline(ctx.root).coverage;
13
+ return previous !== undefined && coverageLowered(previous, current) ? [loweredDiagnostic(previous, current, BASELINE_PATH)] : [];
14
+ }
15
+ function coverageStep(ctx) {
16
+ const spec = pickTesting(ctx.packs);
17
+ const measured = spec === null ? null : measuredLines(readText(ctx.root, spec.coverageSummary));
18
+ const baseline = readBaseline(ctx.root);
19
+ const result = evaluateCoverage(baseline.coverage, measured);
20
+ if (result.next !== undefined && result.next !== baseline.coverage && ctx.readOnly !== true)
21
+ writeBaseline(ctx.root, { ...baseline, coverage: result.next });
22
+ return result.regression === null || measured === null ? [] : [coverageDiagnostic(result.regression.floor, measured, BASELINE_PATH)];
23
+ }
24
+ export function prRuleDiagnostics(ctx, paths) {
25
+ if (paths.length > 0)
26
+ return [];
27
+ const ref = baseRef(ctx.root, ctx.profile.git.baseBranch);
28
+ const missing = ref === null ? [] : missingTests(changedFiles(ctx.root, ref), (path) => exists(ctx.root, path), (path) => readText(ctx.root, path) ?? "").map(missingTestDiagnostic);
29
+ return [...missing, ...loweredAgainstBase(ctx, ref), ...coverageStep(ctx)];
30
+ }
@@ -0,0 +1,87 @@
1
+ import { STRICT_OPTIONS, missingStrictOptions } from "../domain/ts-options.js";
2
+ import { jsTs } from "../domain/data.js";
3
+ import { objectAt } from "../../../core/domain/json.js";
4
+ import { readAsset } from "../../../core/infra/assets.js";
5
+ import { editJsonFile, exists, readJsonRecord, writeIfAbsent } from "../../../core/infra/fs.js";
6
+ import { runNodeScript } from "../../../core/infra/hooks.js";
7
+ import { runTsc } from "../infra/tsc.js";
8
+ import { installDevCommand } from "../domain/profile-pure.js";
9
+ import { andThen, map, ok } from "../../../core/domain/result.js";
10
+ const strictMissing = (root) => {
11
+ const tsconfig = readJsonRecord(root, "tsconfig.json");
12
+ return missingStrictOptions(tsconfig === null ? {} : objectAt(tsconfig, "compilerOptions"));
13
+ };
14
+ export const tsStrictMax = {
15
+ id: "ts-strict-max",
16
+ title: "tsconfig at maximum strictness",
17
+ layer: "types",
18
+ why: "strict plus noUncheckedIndexedAccess, exactOptionalPropertyTypes and noImplicitOverride turn whole classes of agent mistakes into compile errors.",
19
+ notApplicable: (profile) => (jsTs(profile).typescript.tsconfig === null ? "no tsconfig.json" : null),
20
+ requires: () => [],
21
+ isInstalled: ({ root }) => readJsonRecord(root, "tsconfig.json") !== null && strictMissing(root).length === 0,
22
+ install: (ctx) => {
23
+ const before = ctx.gradual === true ? runTsc(ctx.root).diagnostics.length : 0;
24
+ const original = readJsonRecord(ctx.root, "tsconfig.json");
25
+ return andThen(editJsonFile(ctx.root, "tsconfig.json", (value) => ({ ...value, compilerOptions: { ...objectAt(value, "compilerOptions"), ...STRICT_OPTIONS } }), false), (change) => {
26
+ const after = ctx.gradual === true ? runTsc(ctx.root).diagnostics.length : 0;
27
+ if (ctx.gradual === true && after > before && original !== null) {
28
+ return map(editJsonFile(ctx.root, "tsconfig.json", () => original, false), () => ({
29
+ changes: [{ path: "tsconfig.json", action: "unchanged" }],
30
+ notes: [`deferred: the strict options add ${String(after - before)} type errors. Fix them in a branch with the options on, then run \`guardrails apply ts-strict-max\`.`],
31
+ violations: [],
32
+ levels: { "ts-strict-max": "deferred" },
33
+ }));
34
+ }
35
+ return ok({ changes: [change], notes: ["Stricter options can surface new type errors: run the typecheck and fix them at the source."], violations: [], levels: {} });
36
+ });
37
+ },
38
+ verify: ({ root }) => {
39
+ const missing = strictMissing(root);
40
+ const tsc = runTsc(root);
41
+ return [
42
+ { name: "tsconfig strict options", ok: missing.length === 0, detail: missing.length === 0 ? "all set" : `missing: ${missing.join(", ")}` },
43
+ { name: "typecheck under the new options", ok: true, detail: tsc.ran ? `${tsc.diagnostics.length} type errors to fix (run guardrails check)` : `skipped: ${tsc.error ?? "tsc unavailable"}` },
44
+ ];
45
+ },
46
+ };
47
+ function missingScripts(profile) {
48
+ const data = jsTs(profile);
49
+ return {
50
+ ...(!data.scripts.typecheck && data.typescript.present ? { typecheck: "tsc --noEmit" } : {}),
51
+ ...(!data.scripts.lint && data.eslint.version !== null ? { lint: "eslint ." } : {}),
52
+ };
53
+ }
54
+ export const pkgScripts = {
55
+ id: "pkg-scripts",
56
+ title: "package.json has lint and typecheck scripts",
57
+ layer: "api",
58
+ why: "Hooks, CI and the agent all call the same two scripts; one definition keeps them identical.",
59
+ notApplicable: (profile) => (!jsTs(profile).typescript.present && jsTs(profile).eslint.version === null ? "no TypeScript and no ESLint to script" : null),
60
+ requires: () => [],
61
+ isInstalled: ({ profile }) => Object.keys(missingScripts(profile)).length === 0,
62
+ install: ({ root, profile }) => map(editJsonFile(root, "package.json", (value) => ({ ...value, scripts: { ...objectAt(value, "scripts"), ...missingScripts(profile) } }), false), (change) => ({ changes: [change], notes: [], violations: [], levels: {} })),
63
+ verify: ({ root }) => {
64
+ const scripts = objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts");
65
+ return ["lint", "typecheck"].map((name) => ({ name: `script ${name}`, ok: name in scripts, detail: name in scripts ? "present" : "missing" }));
66
+ },
67
+ };
68
+ const hasExactScript = (root) => typeof objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts")["check-exact-deps"] === "string";
69
+ export const exactDeps = {
70
+ id: "exact-deps",
71
+ title: "Dependencies pinned to exact versions",
72
+ layer: "api",
73
+ why: "An update must be an explicit change; ranges let an install silently change what runs.",
74
+ notApplicable: () => null,
75
+ requires: () => [],
76
+ isInstalled: ({ root }) => exists(root, "scripts/check-exact-deps.mjs") && hasExactScript(root),
77
+ install: ({ root, profile }) => andThen(writeIfAbsent(root, "scripts/check-exact-deps.mjs", readAsset("scripts/check-exact-deps.mjs"), "exact-deps"), (copy) => map(editJsonFile(root, "package.json", (value) => ({ ...value, scripts: { "check-exact-deps": "node scripts/check-exact-deps.mjs", ...objectAt(value, "scripts") } }), false), (script) => ({
78
+ changes: [copy, script],
79
+ notes: jsTs(profile).exactDeps.ok ? [] : [`${jsTs(profile).exactDeps.loose.length} dependencies use ranges; pin them: ${installDevCommand(jsTs(profile).packageManager, ["<pkg>@<exact version>"])}`],
80
+ violations: [],
81
+ levels: {},
82
+ }))),
83
+ verify: ({ root }) => {
84
+ const status = runNodeScript(root, "scripts/check-exact-deps.mjs");
85
+ return [{ name: "check-exact-deps runs", ok: status === 0 || status === 1, detail: status === 0 ? "no loose dependencies" : "script works; loose dependencies listed by guardrails check" }];
86
+ },
87
+ };
@@ -0,0 +1,63 @@
1
+ import { appError } from "../../../core/domain/errors.js";
2
+ import { objectAt } from "../../../core/domain/json.js";
3
+ import { andThen, err, map, ok } from "../../../core/domain/result.js";
4
+ import { CI_FILE, ensureCiStep } from "../../../core/domain/workflows.js";
5
+ import { editJsonFile, exists, readJsonRecord, readText, writeIfAbsent, writeManaged } from "../../../core/infra/fs.js";
6
+ import { jsTs } from "../domain/data.js";
7
+ import { packageRunCommand } from "../domain/profile-pure.js";
8
+ import { pickTesting } from "../domain/testing.js";
9
+ const stepOf = (ctx) => ` - run: ${packageRunCommand(jsTs(ctx.profile).packageManager, "test")}`;
10
+ const testScript = (root) => {
11
+ const script = objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts")["test"];
12
+ return typeof script === "string" ? script : "";
13
+ };
14
+ function noRunner() {
15
+ return appError("not-applicable", "no active pack declares a test runner", { rule: "tests", fix: "Activate a js-ts based pack (`guardrails detect`)." });
16
+ }
17
+ function configChange(ctx, spec) {
18
+ return exists(ctx.root, spec.configFile) ? ok({ path: spec.configFile, action: "unchanged" }) : writeIfAbsent(ctx.root, spec.configFile, spec.config(ctx.profile), "tests");
19
+ }
20
+ function ciChange(ctx) {
21
+ const text = readText(ctx.root, CI_FILE);
22
+ return text === null ? { path: CI_FILE, action: "unchanged" } : writeManaged(ctx.root, CI_FILE, ensureCiStep(text, stepOf(ctx), "guardrails check --json"));
23
+ }
24
+ function install(ctx) {
25
+ const spec = pickTesting(ctx.packs);
26
+ if (spec === null)
27
+ return err(noRunner());
28
+ return andThen(configChange(ctx, spec), (config) => map(editJsonFile(ctx.root, "package.json", (value) => ({ ...value, scripts: { test: spec.script, ...objectAt(value, "scripts") } }), false), (script) => ({
29
+ changes: [config, script, ciChange(ctx)],
30
+ notes: [`Tests run in CI (${spec.runner}); run them locally only when asked. Coverage floor lives in .guardrails/baseline.json and only goes up.`],
31
+ violations: [],
32
+ levels: {},
33
+ })));
34
+ }
35
+ function verify(ctx) {
36
+ const spec = pickTesting(ctx.packs);
37
+ if (spec === null)
38
+ return [{ name: "test runner declared", ok: false, detail: "no pack declares one" }];
39
+ const config = readText(ctx.root, spec.configFile) ?? "";
40
+ const ci = readText(ctx.root, CI_FILE);
41
+ return [
42
+ { name: `${spec.configFile} reports json-summary coverage`, ok: config.includes("json-summary"), detail: spec.configFile },
43
+ { name: `script test runs ${spec.runner} with coverage`, ok: testScript(ctx.root).includes(spec.runner) && testScript(ctx.root).includes("--coverage"), detail: testScript(ctx.root) || "missing" },
44
+ { name: "CI runs the test script", ok: ci === null || ci.includes(stepOf(ctx).trim()), detail: ci === null ? "no CI workflow yet; ci-workflow adds the step" : CI_FILE },
45
+ ];
46
+ }
47
+ export const testsConstraint = {
48
+ id: "tests",
49
+ title: "Test runner with coverage, run in CI",
50
+ layer: "tests",
51
+ why: "CI is where tests run for every PR; the pack picks the runner (Vitest, or Jest with jest-expo on React Native) so the agent never chooses one.",
52
+ notApplicable: () => null,
53
+ requires: (profile, packs) => {
54
+ const spec = pickTesting(packs);
55
+ return spec === null ? [] : spec.packages.filter((pkg) => !jsTs(profile).dependencies.includes(pkg)).map((pkg) => ({ pkg, reason: `${spec.runner} runner with coverage` }));
56
+ },
57
+ isInstalled: (ctx) => {
58
+ const spec = pickTesting(ctx.packs);
59
+ return spec !== null && exists(ctx.root, spec.configFile) && verify(ctx).every((check) => check.ok);
60
+ },
61
+ install,
62
+ verify,
63
+ };
@@ -0,0 +1,147 @@
1
+ import { THRESHOLDS } from "../../../core/domain/thresholds.js";
2
+ import { jsTs, routeGlobsOf } from "./data.js";
3
+ export const OWN_PREFIX = "guardrails/";
4
+ export const own = (id) => `${OWN_PREFIX}${id}`;
5
+ const DOMAIN_MESSAGE = "A domain folder is pure: it may import only domain files and node:path. Move the I/O to the infra folder and call it from app.";
6
+ const INFRA_MESSAGE = "An infra folder is the thin I/O edge: it may import domain but never app. Move the orchestration to the app folder.";
7
+ const NODE_IO = "^node:(fs|fs/promises|child_process|os|process|net|http|https)$";
8
+ function layerEntries(roots) {
9
+ const alt = roots.join("|");
10
+ return [
11
+ { files: `^(${alt})/domain/`, forbid: [{ source: `^(${alt})/(app|infra)/`, allowTypeImports: false, message: DOMAIN_MESSAGE }, { source: NODE_IO, allowTypeImports: false, message: DOMAIN_MESSAGE }] },
12
+ { files: `^(${alt})/infra/`, forbid: [{ source: `^(${alt})/app/`, allowTypeImports: false, message: INFRA_MESSAGE }] },
13
+ ];
14
+ }
15
+ export function boundaryOptions(profile) {
16
+ const { paths, layerRules } = jsTs(profile);
17
+ const features = paths.featuresDir === null ? [] : [{ files: "^src/(?!features/[^/]+/)", forbid: [{ source: "^src/features/[^/]+/", allowTypeImports: false, message: BOUNDARY_MESSAGE }] }];
18
+ const layers = paths.layerRoots.length === 0 ? [] : layerEntries(paths.layerRoots);
19
+ const custom = layerRules.map((rule) => ({ files: rule.files, forbid: [{ source: rule.source, allowTypeImports: false, message: rule.message }] }));
20
+ return [[...features, ...layers, ...custom]];
21
+ }
22
+ const BOUNDARY_MESSAGE = "Import a feature only through its public entry point (`@/features/<name>`), never from its internal folders. If what you need is not exported there, add it to that entry point.";
23
+ export const JS_TS_SPECS = Object.freeze([
24
+ {
25
+ id: "no-comments",
26
+ title: "No comments in code",
27
+ why: "A comment means the name is wrong or the code does too much. Intent goes in names and types.",
28
+ rules: [{ name: own("no-comments"), fix: "Delete the comment and rename the variable or function until it says the same, or extract a named function. Allowed: eslint directives with `-- reason`, `/// <reference`, `@ts-expect-error <reason>`.", probe: "// hi\nexport const a = 1;\n" }],
29
+ },
30
+ {
31
+ id: "no-any",
32
+ title: "No any (explicit or `as any`)",
33
+ why: "`any` switches the type checker off for everything it touches.",
34
+ rules: [{ name: "@typescript-eslint/no-explicit-any", fix: "Replace `any` with the real type, `unknown` plus a type guard, or a generic. Never cast through `as any`." }],
35
+ },
36
+ {
37
+ id: "no-ts-ignore",
38
+ title: "No @ts-ignore; @ts-expect-error only with a reason",
39
+ why: "`@ts-ignore` hides errors forever, even after the code is fixed.",
40
+ rules: [
41
+ {
42
+ name: "@typescript-eslint/ban-ts-comment",
43
+ fix: "Fix the type error. If it is truly unavoidable use `// @ts-expect-error <reason of 10+ characters>`; `@ts-ignore` and `@ts-nocheck` are banned.",
44
+ options: () => [{ "ts-ignore": true, "ts-nocheck": true, "ts-check": false, "ts-expect-error": "allow-with-description", minimumDescriptionLength: 10 }],
45
+ },
46
+ ],
47
+ },
48
+ {
49
+ id: "no-non-null-assertion",
50
+ title: "No non-null assertions (`!`)",
51
+ why: "`value!` asserts what the code never checked.",
52
+ rules: [{ name: "@typescript-eslint/no-non-null-assertion", fix: "Narrow the value (`if (value === null) return ...`) or fix the type so the value cannot be missing." }],
53
+ },
54
+ {
55
+ id: "no-enum",
56
+ title: "No enums",
57
+ why: "Enums emit runtime code and break tree shaking.",
58
+ rules: [{ name: own("no-enum"), fix: 'Use an `as const` array or object and derive the union type: `export const STATUSES = ["idle", "done"] as const; export type Status = (typeof STATUSES)[number];`.', probe: "export enum A { B }\n" }],
59
+ },
60
+ {
61
+ id: "no-let",
62
+ title: "No let",
63
+ why: "`let` invites reassignment and hidden state.",
64
+ rules: [{ name: own("no-let"), fix: "Build the value with an expression (`map`, `filter`, `reduce`, `Object.fromEntries`) or a function with early returns and bind it with `const`.", probe: "let a = 1;\nexport { a };\n" }],
65
+ },
66
+ {
67
+ id: "no-console",
68
+ title: "No console",
69
+ why: "Stray logs leak data and hide real diagnostics.",
70
+ rules: [{ name: "no-console", fix: "Remove the console call. Use the project logger or surface the error in the UI.", probe: "console.log(1);\n" }],
71
+ },
72
+ {
73
+ id: "max-complexity",
74
+ title: "Cyclomatic complexity at most 10",
75
+ why: "Branchy functions are where agents introduce bugs.",
76
+ rules: [{ name: "complexity", options: () => [THRESHOLDS.complexity.value], fix: "Split the function: extract each branch into a named function, replace if/else chains with a lookup object or early returns.", probe: "export function f(a: number) {\n" + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((n) => ` if (a === ${n}) return ${n};`).join("\n") + "\n return 0;\n}\n" }],
77
+ },
78
+ {
79
+ id: "max-function-length",
80
+ title: "Functions at most 40 lines",
81
+ why: "Long functions hide multiple responsibilities.",
82
+ rules: [{ name: "max-lines-per-function", options: () => [{ max: THRESHOLDS.functionLines.value, skipBlankLines: true, skipComments: true }], fix: "Extract cohesive blocks into named module-level functions until each is under 40 lines." }],
83
+ },
84
+ {
85
+ id: "no-mutation",
86
+ title: "No mutation of state, props, arguments, arrays or objects",
87
+ why: "Mutation makes data flow untraceable and breaks React and query-cache change detection.",
88
+ rules: [
89
+ { name: own("no-mutating-array-methods"), typed: true, fix: "Use the copying method: `toSorted`, `toReversed`, `toSpliced`, `with`, or spread into a new array." },
90
+ { name: own("no-member-assignment"), fix: "Return a new value: `{ ...value, field: next }`. Only `ref.current` and `module.exports` may be assigned.", probe: "const a = { b: 1 };\na.b = 2;\n" },
91
+ { name: own("no-delete"), fix: "Build a new object without the key: `const { [key]: _removed, ...rest } = value;`.", probe: "const a: { b?: number } = { b: 1 };\ndelete a.b;\n" },
92
+ { name: "no-param-reassign", options: () => [{ props: true }], fix: "Do not assign to a parameter or its properties; copy it into a new local value first." },
93
+ ],
94
+ },
95
+ {
96
+ id: "readonly-by-default",
97
+ title: "Class members readonly when never reassigned",
98
+ why: "Readonly by default makes accidental reassignment a type error.",
99
+ rules: [{ name: "@typescript-eslint/prefer-readonly", typed: true, fix: "Mark the private member `readonly`; it is never reassigned." }],
100
+ },
101
+ {
102
+ id: "require-disable-reason",
103
+ title: "eslint-disable needs a reason",
104
+ why: "A bare disable is the cheapest way for an agent to silence a rule.",
105
+ rules: [{ name: own("require-disable-reason"), fix: "Write `eslint-disable-next-line <rule> -- <why the rule cannot be satisfied here>`, or fix the code so no disable is needed.", probe: "// eslint-disable-next-line no-console\nconsole.log(1);\n" }],
106
+ },
107
+ {
108
+ id: "no-default-export",
109
+ title: "No default exports (except routes and config files)",
110
+ why: "Named exports keep imports greppable and renames safe.",
111
+ rules: [{ name: own("no-default-export"), ignores: routeGlobsOf, fix: "Use a named export: `export function ProjectCard() {}` and update the importers.", probe: "export default function A() {}\n" }],
112
+ },
113
+ {
114
+ id: "import-boundaries",
115
+ title: "Layer limits: features only through their entry point; domain stays pure, infra never imports app",
116
+ why: "Layer limits keep features independent, the domain free of I/O, and refactors local.",
117
+ applies: (profile) => (jsTs(profile).paths.featuresDir === null && jsTs(profile).paths.layerRoots.length === 0 && jsTs(profile).layerRules.length === 0 ? "no src/features, no domain|app|infra layers and no .guardrails/layers.json" : null),
118
+ rules: [{ name: own("import-boundaries"), options: boundaryOptions, fix: BOUNDARY_MESSAGE }],
119
+ },
120
+ {
121
+ id: "readonly-params",
122
+ title: "Parameters are deeply readonly",
123
+ why: "Readonly parameter types make mutating an argument a compile error.",
124
+ rules: [
125
+ {
126
+ name: "@typescript-eslint/prefer-readonly-parameter-types",
127
+ typed: true,
128
+ options: () => [{ ignoreInferredTypes: true, treatMethodsAsReadonly: true, allow: [{ from: "lib", name: ["RegExp", "Error"] }] }],
129
+ fix: "Declare the parameter with a readonly type: `readonly T[]`, `Readonly<T>` or a type whose fields are all `readonly`.",
130
+ },
131
+ ],
132
+ },
133
+ {
134
+ id: "no-floating-promises",
135
+ title: "Promises must be awaited or handled",
136
+ why: "A floating promise swallows its error.",
137
+ rules: [{ name: "@typescript-eslint/no-floating-promises", typed: true, fix: "`await` the promise, return it, or handle rejection with `.catch(...)`; use `void` only for deliberate fire-and-forget." }],
138
+ },
139
+ ]);
140
+ export const fixesOf = (specs) => Object.fromEntries(specs.flatMap((spec) => spec.rules.map((rule) => [rule.name, rule.fix])));
141
+ export function sampleFile(glob) {
142
+ return glob
143
+ .replace(/^\*\*\//, "")
144
+ .replace(/\/\*\*\//g, "/")
145
+ .replace(/\{([^},]+)[^}]*\}/g, "$1")
146
+ .replace(/\*/g, "__guardrails_probe__");
147
+ }
@@ -0,0 +1,47 @@
1
+ import { appError } from "../../../core/domain/errors.js";
2
+ import { jsTs } from "./data.js";
3
+ import { execCommand, installDevCommand, packageRunCommand } from "./profile-pure.js";
4
+ function installCommand(pm) {
5
+ if (pm === "pnpm")
6
+ return "pnpm install --frozen-lockfile --ignore-scripts";
7
+ if (pm === "yarn")
8
+ return "yarn install --frozen-lockfile --ignore-scripts";
9
+ if (pm === "bun")
10
+ return "bun install --frozen-lockfile";
11
+ return "npm ci --ignore-scripts";
12
+ }
13
+ export const JS_TS_COMMANDS = {
14
+ installDev: (profile, packages) => installDevCommand(jsTs(profile).packageManager, packages),
15
+ exec: (profile, bin, args) => execCommand(jsTs(profile).packageManager, bin, args),
16
+ cliRequirement: (profile) => (jsTs(profile).guardrails.installed ? [] : [{ pkg: "@whil/guardrails", reason: "the CI step runs `guardrails check --json`; add this CLI as a devDependency" }]),
17
+ };
18
+ export const JS_TS_CI = {
19
+ setup: (profile) => {
20
+ const pm = jsTs(profile).packageManager;
21
+ return [
22
+ ...(pm === "pnpm" ? [" - uses: pnpm/action-setup@v4"] : []),
23
+ ...(pm === "bun" ? [" - uses: oven-sh/setup-bun@v2"] : []),
24
+ " - uses: actions/setup-node@v4",
25
+ " with:",
26
+ " node-version: lts/*",
27
+ ...(pm === "bun" ? [] : [` cache: ${pm}`]),
28
+ ` - run: ${installCommand(pm)}`,
29
+ ];
30
+ },
31
+ steps: (profile) => {
32
+ const data = jsTs(profile);
33
+ const run = (script) => ` - run: ${packageRunCommand(data.packageManager, script)}`;
34
+ return [
35
+ ...(data.exactDeps.script ? [" - run: node scripts/check-exact-deps.mjs"] : []),
36
+ ...["lint", "typecheck", "test", "build"].filter((name) => data.scripts[name]).map(run),
37
+ ];
38
+ },
39
+ dependabot: () => [{ ecosystem: "npm", directory: "/" }],
40
+ preflight: (profile) => {
41
+ const data = jsTs(profile);
42
+ if (data.packageManager === "pnpm" && !data.packageManagerPinned) {
43
+ return appError("unsupported-config", "pnpm/action-setup needs the pnpm version in package.json", { file: "package.json", rule: "ci-workflow", fix: 'Add `"packageManager": "pnpm@<version>"` to package.json (see `pnpm --version`), then run apply again.' });
44
+ }
45
+ return !data.scripts.lint && !data.scripts.typecheck ? appError("not-applicable", "ci-workflow needs lint and typecheck scripts in package.json", { file: "package.json", rule: "ci-workflow", fix: "Run `guardrails apply pkg-scripts` first." }) : null;
46
+ },
47
+ };
@@ -0,0 +1,34 @@
1
+ import { isRecord } from "../../../core/domain/json.js";
2
+ export const EMPTY_JS_TS = {
3
+ name: "unnamed",
4
+ packageManager: "npm",
5
+ packageManagerPinned: false,
6
+ typescript: { present: false, version: null, tsconfig: null, strict: null },
7
+ eslint: { installed: false, version: null, config: null, flat: false, typescriptPlugin: false, typescriptEslintPackage: false, guardrailsWired: false },
8
+ dependencies: [],
9
+ tests: { runner: null },
10
+ paths: { srcDir: null, featuresDir: null, layerRoots: [], sourceGlobs: [], routeGlobs: [], hookGlobs: [] },
11
+ scripts: { lint: false, typecheck: false, test: false, build: false },
12
+ guardrails: { installed: false },
13
+ exactDeps: { ok: true, loose: [], script: false },
14
+ layerRules: [],
15
+ };
16
+ function isJsTsData(value) {
17
+ return isRecord(value) && typeof value["packageManager"] === "string" && isRecord(value["paths"]) && isRecord(value["eslint"]) && isRecord(value["scripts"]);
18
+ }
19
+ export function jsTs(profile) {
20
+ const value = profile.stack["js-ts"];
21
+ return isJsTsData(value) ? value : EMPTY_JS_TS;
22
+ }
23
+ export function hasDependency(profile, name) {
24
+ return jsTs(profile).dependencies.includes(name);
25
+ }
26
+ function globsOf(profile, key) {
27
+ return Object.values(profile.stack).flatMap((entry) => {
28
+ const value = entry[key];
29
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
30
+ });
31
+ }
32
+ export const routeGlobsOf = (profile) => [...jsTs(profile).paths.routeGlobs, ...globsOf(profile, "routeGlobs")];
33
+ export const hookGlobsOf = (profile) => [...jsTs(profile).paths.hookGlobs, ...globsOf(profile, "hookGlobs")];
34
+ export const isActive = (profile, id) => profile.packs.some((pack) => pack.id === id);
@@ -0,0 +1,17 @@
1
+ const GENERIC_ESLINT_FIX = "Change the code so the rule passes. Do not add eslint-disable, @ts-ignore or any to silence it.";
2
+ const TSC_FIX = "Fix the type error at its source (correct the type or the value). Do not cast through any or use @ts-ignore.";
3
+ export function eslintDiagnostic(violation, fixes) {
4
+ return { ...violation, tool: "eslint", fix: fixes[violation.rule] ?? GENERIC_ESLINT_FIX };
5
+ }
6
+ export function tscDiagnostic(diagnostic) {
7
+ return { file: diagnostic.file, line: diagnostic.line, column: diagnostic.column, tool: "tsc", rule: diagnostic.code, message: diagnostic.message, severity: "error", fix: TSC_FIX };
8
+ }
9
+ const TSC_LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
10
+ export function parseTscOutput(output) {
11
+ return output.split("\n").flatMap((raw) => {
12
+ const match = TSC_LINE.exec(raw.trim());
13
+ if (match === null)
14
+ return [];
15
+ return [{ file: match[1] ?? "", line: Number(match[2]), column: Number(match[3]), code: match[4] ?? "", message: match[5] ?? "" }];
16
+ });
17
+ }
@@ -0,0 +1,11 @@
1
+ const DIRECTIVE = /eslint-disable(?:-next-line|-line)?\b/;
2
+ const REASON = /\s--\s+\S/;
3
+ const TOKEN = /"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`|\/\/([^\n]*)|\/\*([\s\S]*?)\*\//g;
4
+ export function findDisableDirectives(text) {
5
+ return [...text.matchAll(TOKEN)].flatMap((match) => {
6
+ const body = match[1] ?? match[2];
7
+ if (body === undefined || !DIRECTIVE.test(body))
8
+ return [];
9
+ return [{ line: text.slice(0, match.index).split("\n").length, hasReason: REASON.test(body) }];
10
+ });
11
+ }
@@ -0,0 +1,46 @@
1
+ import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
2
+ export const UNUSED_DIRECTIVE_RULE = "unused-disable-directive";
3
+ export const LINT_NOT_RUN = (error) => ({ ran: false, error, violations: [], fatal: [] });
4
+ function relative(root, file) {
5
+ return file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
6
+ }
7
+ function entryOf(file, message) {
8
+ const text = typeof message["message"] === "string" ? message["message"] : "";
9
+ const rule = typeof message["ruleId"] === "string" ? message["ruleId"] : text.startsWith("Unused eslint-disable directive") ? UNUSED_DIRECTIVE_RULE : null;
10
+ return {
11
+ rule,
12
+ violation: {
13
+ file,
14
+ line: typeof message["line"] === "number" ? message["line"] : 0,
15
+ column: typeof message["column"] === "number" ? message["column"] : 0,
16
+ rule: rule ?? "parse-error",
17
+ message: text,
18
+ severity: message["severity"] === 1 ? "warn" : "error",
19
+ },
20
+ };
21
+ }
22
+ function entriesOf(root, result) {
23
+ if (!isRecord(result) || typeof result["filePath"] !== "string" || !Array.isArray(result["messages"]))
24
+ return [];
25
+ const file = relative(root, result["filePath"]);
26
+ return result["messages"].filter(isRecord).map((message) => entryOf(file, message));
27
+ }
28
+ export function parseEslintJson(root, stdout) {
29
+ const parsed = parseStrictJson(stdout);
30
+ if (!parsed.ok || !Array.isArray(parsed.value))
31
+ return null;
32
+ const entries = parsed.value.flatMap((result) => entriesOf(root, result));
33
+ return {
34
+ violations: entries.filter((entry) => entry.rule !== null).map((entry) => entry.violation),
35
+ fatal: entries.filter((entry) => entry.rule === null).map((entry) => entry.violation),
36
+ };
37
+ }
38
+ export function violationsOf(outcome, rule) {
39
+ return outcome.violations.filter((violation) => violation.rule === rule);
40
+ }
41
+ export function severityOf(configured) {
42
+ const value = Array.isArray(configured) ? configured[0] : configured;
43
+ if (value === 2 || value === "error")
44
+ return "error";
45
+ return value === 1 || value === "warn" ? "warn" : "off";
46
+ }
@@ -0,0 +1,80 @@
1
+ import { GUARDRAILS_CONFIG_IMPORT } from "./profile.js";
2
+ import { isRecord, parseRecordStrict, stringifyJson } from "../../../core/domain/json.js";
3
+ import { err, ok } from "../../../core/domain/result.js";
4
+ export const PLUGIN_DIR = "eslint/guardrails";
5
+ export const RULES_JSON = `${PLUGIN_DIR}/rules.json`;
6
+ export const EMPTY_STATE = Object.freeze({ version: 1, typedParser: false, linterOptions: Object.freeze({}), rules: Object.freeze({}) });
7
+ function isLevel(value) {
8
+ return value === "error" || value === "warn" || value === "off";
9
+ }
10
+ function strings(value) {
11
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
12
+ }
13
+ function parseEntry(value) {
14
+ if (!isRecord(value) || !isLevel(value["level"]))
15
+ return null;
16
+ const ignores = strings(value["ignores"]);
17
+ const options = Array.isArray(value["options"]) ? value["options"] : undefined;
18
+ return {
19
+ level: value["level"],
20
+ files: strings(value["files"]) ?? [],
21
+ ...(ignores === undefined ? {} : { ignores }),
22
+ ...(options === undefined ? {} : { options }),
23
+ ...(value["typed"] === true ? { typed: true } : {}),
24
+ };
25
+ }
26
+ function parseState(parsed) {
27
+ const rules = isRecord(parsed["rules"]) ? parsed["rules"] : {};
28
+ const entries = Object.entries(rules).flatMap(([name, value]) => {
29
+ const entry = parseEntry(value);
30
+ return entry === null ? [] : [[name, entry]];
31
+ });
32
+ const linter = isRecord(parsed["linterOptions"]) ? parsed["linterOptions"] : {};
33
+ const unused = linter["reportUnusedDisableDirectives"];
34
+ return {
35
+ version: 1,
36
+ typedParser: parsed["typedParser"] === true,
37
+ linterOptions: unused === "error" || unused === "warn" ? { reportUnusedDisableDirectives: unused } : {},
38
+ rules: Object.fromEntries(entries),
39
+ };
40
+ }
41
+ export function parseRulesState(text) {
42
+ if (text === null)
43
+ return ok(EMPTY_STATE);
44
+ const parsed = parseRecordStrict(text);
45
+ return parsed.ok ? ok(parseState(parsed.value)) : err(parsed.error);
46
+ }
47
+ export function serializeState(state) {
48
+ const sorted = Object.fromEntries(Object.entries(state.rules).toSorted(([a], [b]) => a.localeCompare(b)));
49
+ return stringifyJson({ ...state, rules: sorted });
50
+ }
51
+ export function withRule(state, name, entry) {
52
+ return { ...state, rules: { ...state.rules, [name]: entry } };
53
+ }
54
+ export function withLevel(state, name, level) {
55
+ const entry = state.rules[name];
56
+ return entry === undefined ? state : withRule(state, name, { ...entry, level });
57
+ }
58
+ export function renderPluginIndex(ruleIds) {
59
+ const sorted = ruleIds.toSorted();
60
+ const imports = sorted.map((id, index) => `import * as rule${index} from "./rules/${id}.mjs";`);
61
+ const entries = sorted.map((id, index) => ` ${JSON.stringify(id)}: Object.values(rule${index})[0],`);
62
+ return [...imports, "", "export const guardrailsPlugin = {", ' meta: { name: "guardrails" },', " rules: {", ...entries, " },", "};", ""].join("\n");
63
+ }
64
+ const FLAT_ARRAY_START = /export default\s+(?:[A-Za-z_$][\w$.]*\()?\s*\[/;
65
+ const WIRING_IMPORT = `import { guardrailsConfig } from "./${GUARDRAILS_CONFIG_IMPORT}";\n`;
66
+ export function wireConfigText(source) {
67
+ const match = FLAT_ARRAY_START.exec(source);
68
+ if (match === null)
69
+ return null;
70
+ const at = match.index + match[0].length;
71
+ return `${WIRING_IMPORT}${source.slice(0, at)}\n ...guardrailsConfig,${source.slice(at)}`;
72
+ }
73
+ export function newConfigText(data) {
74
+ return data.eslint.typescriptEslintPackage
75
+ ? `import tseslint from "typescript-eslint";\n${WIRING_IMPORT}\nexport default [tseslint.configs.base, ...guardrailsConfig];\n`
76
+ : null;
77
+ }
78
+ export function userConfigHasTypedParser(configText) {
79
+ return configText.includes("projectService") || /\bproject\s*:/.test(configText);
80
+ }