diff --git a/biome.json b/biome.json index 3743641af..d48332f79 100644 --- a/biome.json +++ b/biome.json @@ -62,6 +62,10 @@ "includes": ["src/**", "!src/cli/inputs.ts"], "plugins": ["./lint/never-throw.grit"] }, + { + "includes": ["src/**", "!src/sections/shared/schema-helpers.ts"], + "plugins": ["./lint/rule-gate.grit"] + }, { "includes": ["src/action/**"], "linter": { diff --git a/lint/rule-gate.grit b/lint/rule-gate.grit new file mode 100644 index 000000000..6de8ba890 --- /dev/null +++ b/lint/rule-gate.grit @@ -0,0 +1,14 @@ +// Every refinement under src/ is authored through rule() (src/sections/shared/schema-helpers.ts): zod skips a bare +// .refine() or .superRefine() once a nested value failed, so a section's own rule would go silent exactly when the +// document has a second mistake. Reach and the one exemption are the plugin's `overrides` entry in biome.json (see +// never-throw.grit for why): +// src/sections/shared/schema-helpers.ts -> rule() itself is the one superRefine + +or { + `$_.superRefine($_)`, + `$_.superRefine<$_>($_)`, + `$_.refine($_)`, + `$_.refine<$_>($_)` +} as $call where { + register_diagnostic(span=$call, message="bare refinement: zod skips it once a nested value failed; wrap it in rule() so it runs beside nested failures") +} diff --git a/src/engine/validate.ts b/src/engine/validate.ts index 34a919ce0..3504e59ac 100644 --- a/src/engine/validate.ts +++ b/src/engine/validate.ts @@ -5,11 +5,7 @@ import { z } from "zod"; import { nonPlainKind } from "../plain-data.js"; import type { ProblemOf } from "../problem.js"; import { LIST_SECTIONS, type ListSection, SECTION_KEYS, type SettingsFile } from "../schema.js"; -import { - checksReportingBesideFailures, - type DeclaredIssue, - type DeclaredSecretValue, -} from "../sections/contract/module.js"; +import type { DeclaredIssue, DeclaredSecretValue } from "../sections/contract/module.js"; import { listLayering, sectionModule, sectionShape } from "../sections/registry.js"; import { valueAt } from "../sections/shared/list-section.js"; import { agree, countNoun } from "../text.js"; @@ -215,8 +211,7 @@ export function validateSectionShapes( problems.push(nonPlain); continue; } - // The section may compose a rule onto its loosened shape; loosen() itself covers every check beneath. - const parsed = checksReportingBesideFailures(shape).safeParse(declared); + const parsed = shape.safeParse(declared); if (!parsed.success) { const issues = parsed.error.issues; for (const issue of issues.slice(0, 5)) { diff --git a/src/sections/actions/schema.ts b/src/sections/actions/schema.ts index 0ce416537..b5fb1ec4d 100644 --- a/src/sections/actions/schema.ts +++ b/src/sections/actions/schema.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { describeValue } from "../../plain-data.js"; +import { rule } from "../shared/schema-helpers.js"; /** GitHub's rule for an OIDC claim key; the PUT 422s on anything else. */ const CLAIM_KEY = /^[A-Za-z0-9_]+$/; @@ -45,24 +46,26 @@ const ClaimKeys = z 'a claim key holds only letters, digits, and underscores (such as "repo" or "job_workflow_ref")', }), ) - .superRefine((keys, refineCtx) => { - // A raw item beside its own shape issue is passed over (see ../shared/raw-values.ts): a YAML alias repeats one - // mapping at two items, and rendering it into the message can throw. - const seen = new Set(); - keys.forEach((key, index) => { - if (typeof key !== "string") { - return; - } - if (seen.has(key)) { - refineCtx.addIssue({ - code: "custom", - path: [index], - message: `"${key}" repeats an earlier claim key; GitHub requires the keys to be unique`, - }); - } - seen.add(key); - }); - }); + .check( + rule((keys, refineCtx) => { + // A raw item beside its own shape issue is passed over (see ../shared/raw-values.ts): a YAML alias repeats one + // mapping at two items, and rendering it into the message can throw. + const seen = new Set(); + keys.forEach((key, index) => { + if (typeof key !== "string") { + return; + } + if (seen.has(key)) { + refineCtx.addIssue({ + code: "custom", + path: [index], + message: `"${key}" repeats an earlier claim key; GitHub requires the keys to be unique`, + }); + } + seen.add(key); + }); + }), + ); /** * The two templates are two variants, discriminated on use_default, so the claim-key list has no @@ -79,18 +82,20 @@ const OidcTemplate = z use_immutable_subject: z.boolean().optional(), }), ]) - .superRefine((declared, refineCtx) => { - // A raw use_default beside its own shape issue is truthy without being true and selects no template. - if (declared.use_default === true && Object.hasOwn(declared, "include_claim_keys")) { - refineCtx.addIssue({ - code: "custom", - path: ["include_claim_keys"], - message: - "GitHub ignores include_claim_keys under use_default: true, so the declared list could never take; " + - "set use_default: false for a custom template, or remove the list", - }); - } - }); + .check( + rule((declared, refineCtx) => { + // A raw use_default beside its own shape issue is truthy without being true and selects no template. + if (declared.use_default === true && Object.hasOwn(declared, "include_claim_keys")) { + refineCtx.addIssue({ + code: "custom", + path: ["include_claim_keys"], + message: + "GitHub ignores include_claim_keys under use_default: true, so the declared list could never take; " + + "set use_default: false for a custom template, or remove the list", + }); + } + }), + ); export const ActionsConfig = z .object({ @@ -139,20 +144,22 @@ export const ActionsConfig = z }) .optional(), }) - .superRefine((declared, refineCtx) => { - // Checked in the shape, not in plan(), so both modes reject the document before ANY section - // writes; a plan-time throw would fire after earlier sections already wrote. - refuseReportedOnly(refineCtx, declared); - if (declared.selected_actions === undefined || declared.allowed_actions === undefined) { - return; - } - if (declared.allowed_actions !== "selected") { - refineCtx.addIssue({ - code: "custom", - path: ["selected_actions"], - message: `selected_actions is declared together with allowed_actions: ${describeValue(declared.allowed_actions)}, but an allowlist only applies under allowed_actions: "selected". Set allowed_actions to "selected", or remove selected_actions`, - }); - } - }) + .check( + rule((declared, refineCtx) => { + // Checked in the shape, not in plan(), so both modes reject the document before ANY section + // writes; a plan-time throw would fire after earlier sections already wrote. + refuseReportedOnly(refineCtx, declared); + if (declared.selected_actions === undefined || declared.allowed_actions === undefined) { + return; + } + if (declared.allowed_actions !== "selected") { + refineCtx.addIssue({ + code: "custom", + path: ["selected_actions"], + message: `selected_actions is declared together with allowed_actions: ${describeValue(declared.allowed_actions)}, but an allowlist only applies under allowed_actions: "selected". Set allowed_actions to "selected", or remove selected_actions`, + }); + } + }), + ) .meta({ id: "ActionsConfig" }); export type ActionsConfig = z.infer; diff --git a/src/sections/branches/index.ts b/src/sections/branches/index.ts index 8d3bff985..d92b519c6 100644 --- a/src/sections/branches/index.ts +++ b/src/sections/branches/index.ts @@ -24,7 +24,7 @@ import { } from "../contract/module.js"; import type { SectionPermission } from "../contract/permissions.js"; import { plainData, type Read } from "../contract/plan.js"; -import { layeredList } from "../shared/schema-helpers.js"; +import { layeredList, rule } from "../shared/schema-helpers.js"; import { ENDPOINTS, MISSING_BRANCH } from "./endpoints.js"; import { type BranchesContext, @@ -261,61 +261,63 @@ export const branchesSection = { graphql: GRAPHQL, // The wildcard key sweep composes HERE, not in schema.ts: it reads the GraphQL translation tables, // which are this section's own machinery, and nothing outside them can reach a wildcard rule. - shape: loosen(layeredList(BranchesConfig)).superRefine((declared, refineCtx) => { - // The routed shape parsed one of the two forms; under the wrapper an issue's path starts at `entries`. - const wrapped = !Array.isArray(declared); - const entries = listEntries(declared as BranchConfig[] | { entries: BranchConfig[] }); - const at = (index: number, ...rest: string[]): (string | number)[] => [ - ...(wrapped ? ["entries"] : []), - index, - ...rest, - ]; - entries.forEach((entry: BranchConfig, index) => { - // The entry, its name, or its protection may be raw or missing beside its own shape issue; a regex would - // coerce the name (`[object Object]` wildcards), and a non-mapping protection holds no keys to sweep. - if ( - !isPlainObject(entry) || - typeof entry.name !== "string" || - !isWildcardPattern(entry.name) - ) { - return; - } - const protection = entry.protection; - if (!isPlainObject(protection)) { - return; - } - for (const key of Object.keys(protection)) { - if (!WILDCARD_KEY_SET.has(key)) { - refineCtx.addIssue({ - code: "custom", - path: at(index, "protection", key), - message: WILDCARD_KEY_ERROR(entry.name, key), - }); - } - } - // The structured pairs translate NAMED sub-keys only, so an unknown sub-key would be silently - // lost; the schema already holds each pair to a mapping or null. - const nested: Array<[string, Record]> = [ - ["required_status_checks", GRAPHQL_STATUS_CHECK_TWINS], - ["required_pull_request_reviews", GRAPHQL_REVIEW_TWINS], + shape: loosen(layeredList(BranchesConfig)).check( + rule((declared, refineCtx) => { + // The routed shape parsed one of the two forms; under the wrapper an issue's path starts at `entries`. + const wrapped = !Array.isArray(declared); + const entries = listEntries(declared as BranchConfig[] | { entries: BranchConfig[] }); + const at = (index: number, ...rest: string[]): (string | number)[] => [ + ...(wrapped ? ["entries"] : []), + index, + ...rest, ]; - for (const [key, twins] of nested) { - const value = protection[key]; - if (!isPlainObject(value)) { - continue; + entries.forEach((entry: BranchConfig, index) => { + // The entry, its name, or its protection may be raw or missing beside its own shape issue; a regex would + // coerce the name (`[object Object]` wildcards), and a non-mapping protection holds no keys to sweep. + if ( + !isPlainObject(entry) || + typeof entry.name !== "string" || + !isWildcardPattern(entry.name) + ) { + return; + } + const protection = entry.protection; + if (!isPlainObject(protection)) { + return; } - for (const subKey of Object.keys(value)) { - if (!(subKey in twins)) { + for (const key of Object.keys(protection)) { + if (!WILDCARD_KEY_SET.has(key)) { refineCtx.addIssue({ code: "custom", - path: at(index, "protection", key, subKey), - message: WILDCARD_KEY_ERROR(entry.name, `${key}.${subKey}`), + path: at(index, "protection", key), + message: WILDCARD_KEY_ERROR(entry.name, key), }); } } - } - }); - }), + // The structured pairs translate NAMED sub-keys only, so an unknown sub-key would be silently + // lost; the schema already holds each pair to a mapping or null. + const nested: Array<[string, Record]> = [ + ["required_status_checks", GRAPHQL_STATUS_CHECK_TWINS], + ["required_pull_request_reviews", GRAPHQL_REVIEW_TWINS], + ]; + for (const [key, twins] of nested) { + const value = protection[key]; + if (!isPlainObject(value)) { + continue; + } + for (const subKey of Object.keys(value)) { + if (!(subKey in twins)) { + refineCtx.addIssue({ + code: "custom", + path: at(index, "protection", key, subKey), + message: WILDCARD_KEY_ERROR(entry.name, `${key}.${subKey}`), + }); + } + } + } + }); + }), + ), async plan(ctx, desired): Promise> { const section = this; return safeTry(async function* () { diff --git a/src/sections/branches/schema.ts b/src/sections/branches/schema.ts index 7147d2950..5156bb6c3 100644 --- a/src/sections/branches/schema.ts +++ b/src/sections/branches/schema.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { isPlainObject } from "../../plain-data.js"; import { stringItems } from "../shared/raw-values.js"; +import { rule } from "../shared/schema-helpers.js"; import { BOOLEAN_CONTROL_SET, isGetOnlyKey, isUrlKey } from "./keys.js"; // --- Actor vocabulary (branches force_push_bypassers) ------------------------ @@ -182,11 +183,13 @@ const RequiredStatusChecks = z "required_status_checks must be a mapping of its keys (strict, then contexts or checks), or null to turn the requirement off", }, ) - .superRefine((status, refineCtx) => { - if (status.contexts === undefined && status.checks === undefined) { - refineCtx.addIssue({ code: "custom", message: CHECK_LIST_ERROR }); - } - }) + .check( + rule((status, refineCtx) => { + if (status.contexts === undefined && status.checks === undefined) { + refineCtx.addIssue({ code: "custom", message: CHECK_LIST_ERROR }); + } + }), + ) // The refinement's published-schema twin: zod refinements do not reach z.toJSONSchema, and // test/published-schema.test.ts holds the two sides to the same verdicts. .meta({ anyOf: [{ required: ["contexts"] }, { required: ["checks"] }] }); @@ -304,7 +307,13 @@ export const BranchProtectionConfig = z .optional(), force_push_bypassers: z .array( - z.string().refine((raw) => parseBypassActor(raw) !== null, { error: ACTOR_FORM_ERROR }), + z.string().check( + rule((raw, refineCtx) => { + if (parseBypassActor(raw) === null) { + refineCtx.addIssue({ code: "custom", message: ACTOR_FORM_ERROR }); + } + }), + ), ) .optional(), required_deployments: z @@ -313,9 +322,11 @@ export const BranchProtectionConfig = z .optional(), }) // Every depth: the wrappers sit under each control, and the links under the actor holders too. - .superRefine((protection, refineCtx) => { - refuseGetOnlyKeys(protection, [], refineCtx); - }) + .check( + rule((protection, refineCtx) => { + refuseGetOnlyKeys(protection, [], refineCtx); + }), + ) .meta({ id: "BranchProtectionConfig" }); export type BranchProtectionConfig = z.infer; @@ -324,30 +335,32 @@ export const BranchConfig = z name: z.string(), protection: BranchProtectionConfig.nullable(), }) - .superRefine((entry, refineCtx) => { - // GitHub canonicalizes actor and environment names case-insensitively and the routed lists - // replace wholesale, so a duplicate would apply "successfully" and then drift forever against - // the deduplicated read-back. - const routed = entry.protection; - if (isPlainObject(routed)) { - const duplicateActor = duplicateIn(routed.force_push_bypassers); - if (duplicateActor !== null) { - refineCtx.addIssue({ - code: "custom", - path: ["protection", "force_push_bypassers"], - message: `force_push_bypassers lists "${duplicateActor}" more than once (actor names are case-insensitive); keep one entry per actor`, - }); - } - const duplicateEnv = duplicateIn(routed.required_deployments?.environments); - if (duplicateEnv !== null) { - refineCtx.addIssue({ - code: "custom", - path: ["protection", "required_deployments", "environments"], - message: `required_deployments.environments lists "${duplicateEnv}" more than once (environment names are case-insensitive); keep one entry per environment`, - }); + .check( + rule((entry, refineCtx) => { + // GitHub canonicalizes actor and environment names case-insensitively and the routed lists + // replace wholesale, so a duplicate would apply "successfully" and then drift forever against + // the deduplicated read-back. + const routed = entry.protection; + if (isPlainObject(routed)) { + const duplicateActor = duplicateIn(routed.force_push_bypassers); + if (duplicateActor !== null) { + refineCtx.addIssue({ + code: "custom", + path: ["protection", "force_push_bypassers"], + message: `force_push_bypassers lists "${duplicateActor}" more than once (actor names are case-insensitive); keep one entry per actor`, + }); + } + const duplicateEnv = duplicateIn(routed.required_deployments?.environments); + if (duplicateEnv !== null) { + refineCtx.addIssue({ + code: "custom", + path: ["protection", "required_deployments", "environments"], + message: `required_deployments.environments lists "${duplicateEnv}" more than once (environment names are case-insensitive); keep one entry per environment`, + }); + } } - } - }) + }), + ) .meta({ id: "BranchConfig" }); export type BranchConfig = z.infer; diff --git a/src/sections/check_suite_preferences/schema.ts b/src/sections/check_suite_preferences/schema.ts index a3f3ec311..c216e02b2 100644 --- a/src/sections/check_suite_preferences/schema.ts +++ b/src/sections/check_suite_preferences/schema.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { isPlainObject } from "../../plain-data.js"; +import { rule } from "../shared/schema-helpers.js"; // No GitHub App has id 0, and GitHub rejects fractions. Parse refuses the id here; otherwise the PATCH reports whatever // GitHub answers, late and on every run. The duplicate below is the case nothing would ever report. @@ -21,30 +22,32 @@ export const CheckSuitePreferencesConfig = z auto_trigger_checks: z.array(AutoTriggerCheckConfig), }) .catchall(z.unknown()) - .superRefine((declared, refineCtx) => { - // GitHub keeps whichever entry for an app it reads last, on every run, and no read endpoint exists to show the other - // one lost; the file contradicts itself, so the pair is refused here. An entry whose app_id failed the bound still - // arrives (zod continues past it), so a document with both faults reports both. The list or an entry may be raw - // beside its own shape issue (see ../shared/raw-values.ts): a non-list holds no entries, and an entry without a - // numeric app_id names no app. - const firstAt = new Map(); - const entries: unknown = declared.auto_trigger_checks; - (Array.isArray(entries) ? entries : []).forEach((entry: unknown, index) => { - if (!isPlainObject(entry) || typeof entry.app_id !== "number") { - return; - } - const { app_id } = entry; - const first = firstAt.get(app_id); - if (first === undefined) { - firstAt.set(app_id, index); - return; - } - refineCtx.addIssue({ - code: "custom", - path: ["auto_trigger_checks", index, "app_id"], - message: `repeats app_id ${app_id} from auto_trigger_checks[${first}]; GitHub would keep whichever entry it reads last and nothing reads the result back, so declare one entry per app`, + .check( + rule((declared, refineCtx) => { + // GitHub keeps whichever entry for an app it reads last, on every run, and no read endpoint exists to show the other + // one lost; the file contradicts itself, so the pair is refused here. An entry whose app_id failed the bound still + // arrives (zod continues past it), so a document with both faults reports both. The list or an entry may be raw + // beside its own shape issue (see ../shared/raw-values.ts): a non-list holds no entries, and an entry without a + // numeric app_id names no app. + const firstAt = new Map(); + const entries: unknown = declared.auto_trigger_checks; + (Array.isArray(entries) ? entries : []).forEach((entry: unknown, index) => { + if (!isPlainObject(entry) || typeof entry.app_id !== "number") { + return; + } + const { app_id } = entry; + const first = firstAt.get(app_id); + if (first === undefined) { + firstAt.set(app_id, index); + return; + } + refineCtx.addIssue({ + code: "custom", + path: ["auto_trigger_checks", index, "app_id"], + message: `repeats app_id ${app_id} from auto_trigger_checks[${first}]; GitHub would keep whichever entry it reads last and nothing reads the result back, so declare one entry per app`, + }); }); - }); - }) + }), + ) .meta({ id: "CheckSuitePreferencesConfig" }); export type CheckSuitePreferencesConfig = z.infer; diff --git a/src/sections/code_quality_setup/schema.ts b/src/sections/code_quality_setup/schema.ts index 292d72a2a..b455ed694 100644 --- a/src/sections/code_quality_setup/schema.ts +++ b/src/sections/code_quality_setup/schema.ts @@ -3,6 +3,7 @@ import type { components } from "@octokit/openapi-types"; import { z } from "zod"; import type { MustBeNever } from "../../types.js"; +import { rule } from "../shared/schema-helpers.js"; import { languagesSchema, refineSetup, @@ -31,6 +32,6 @@ export const CodeQualitySetupConfig = z runner_label: z.string().nullable().optional(), ai_findings_option: z.enum(["disabled", "on_push"]).optional(), }) - .superRefine(refineSetup) + .check(rule(refineSetup)) .meta({ id: "CodeQualitySetupConfig" }); export type CodeQualitySetupConfig = z.infer; diff --git a/src/sections/code_scanning_default_setup/schema.ts b/src/sections/code_scanning_default_setup/schema.ts index b4bd97aa6..85288d927 100644 --- a/src/sections/code_scanning_default_setup/schema.ts +++ b/src/sections/code_scanning_default_setup/schema.ts @@ -3,6 +3,7 @@ import type { components } from "@octokit/openapi-types"; import { z } from "zod"; import type { MustBeNever } from "../../types.js"; +import { rule } from "../shared/schema-helpers.js"; import { languagesSchema, refineSetup, @@ -42,6 +43,6 @@ export const CodeScanningDefaultSetupConfig = z runner_label: z.string().nullable().optional(), threat_model: z.enum(["remote", "remote_and_local"]).optional(), }) - .superRefine(refineSetup) + .check(rule(refineSetup)) .meta({ id: "CodeScanningDefaultSetupConfig" }); export type CodeScanningDefaultSetupConfig = z.infer; diff --git a/src/sections/contract/module.ts b/src/sections/contract/module.ts index d906dd6b4..97d359851 100644 --- a/src/sections/contract/module.ts +++ b/src/sections/contract/module.ts @@ -14,7 +14,7 @@ import type { UndeclaredPolicy, UndeclaredPolicyList, } from "../../types.js"; -import type { Layering, UNDECLARED_POLICIES } from "../shared/schema-helpers.js"; +import { type Layering, rule, type UNDECLARED_POLICIES } from "../shared/schema-helpers.js"; import { type EndpointDecl, endpointKind, @@ -625,16 +625,12 @@ export interface SectionSnapshot { } /** - * plan() only READS (through the port in PlanContext) and returns the operations that would converge the - * repository, or the failure that ended it as a value (a denied read, a live state it cannot reconcile); the - * engine renders the operations as drift in check mode and executes them in apply mode. - * Modules register in ../registry.ts. + * plan() only READS (through the port in PlanContext) and returns the operations that would converge the repository, + * or the failure that ended it as a value; the engine renders them as drift in check mode and executes them in apply mode. * - * snapshot() required -> the section declares a read (a GET or a GraphQL query), so the live state it - * compares against can be read back; SnapshotFacet flags a module annotated over its - * literal dictionaries without one, and ../registry.ts flags every registrant without one - * snapshot() absent -> only a write-only section (no read at all), which snapshot reports unsupported - * (snapshotUnsupportedNote) + * snapshot() required -> the section declares a read (a GET or a GraphQL query); SnapshotFacet and ../registry.ts + * flag a module without one + * snapshot() absent -> a write-only section (no read at all), which snapshot reports unsupported (snapshotUnsupportedNote) */ export type SectionModule< K extends SectionKey = SectionKey, @@ -783,18 +779,20 @@ export function secretValuesOf( export function requirePlainMapping(shape: z.ZodType): z.ZodType { return z .unknown() - .superRefine((value, ctx) => { - if (value !== null && typeof value === "object" && !Array.isArray(value)) { - const proto = Object.getPrototypeOf(value); - if (proto !== Object.prototype && proto !== null) { - ctx.addIssue({ - code: "custom", - message: - "Invalid input: expected a plain mapping (a YAML-tagged value like !!timestamp parses to another type)", - }); + .check( + rule((value, ctx) => { + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) { + ctx.addIssue({ + code: "custom", + message: + "Invalid input: expected a plain mapping (a YAML-tagged value like !!timestamp parses to another type)", + }); + } } - } - }) + }), + ) .pipe(shape); } @@ -814,97 +812,21 @@ export function defOf(schema: z.ZodType): ZodDef { return (schema as unknown as { _zod: { def: ZodDef } })._zod.def; } -/** Every clone's own checks are rewired to report beside a failed nested value (reportingBesideFailures). */ function cloneWith(schema: z.ZodType, patch: Partial): z.ZodType { - const def = (schema as unknown as { _zod: { def: Record } })._zod.def; - const checks = (def.checks as readonly z.core.$ZodCheck[] | undefined)?.map( - reportingBesideFailures, - ); return z.util.clone( schema as unknown as Parameters[0], - { ...def, ...patch, checks } as never, + { ...defOf(schema), ...patch } as never, ) as unknown as z.ZodType; } -/** The rewire for a check attached AFTER loosen(): a section composing a rule onto its loosened shape. */ -export function checksReportingBesideFailures(schema: z.ZodType): z.ZodType { - return cloneWith(schema, {}); -} - -const REPORTS_BESIDE_FAILURES = new WeakSet(); - -let swallowedThrowObserver: ((error: unknown) => void) | null = null; - -/** Test seam for the swallowed throws below (test/sections/raw-sibling.test.ts); production leaves it null. */ -export function observeSwallowedThrows(observer: ((error: unknown) => void) | null): void { - swallowedThrowObserver = observer; -} - -/** The paths of the issues that abort a parse (a wrong type, a refused option); a rule's own finding and an unrecognized key do not. */ -function failedPaths(issues: readonly z.core.$ZodRawIssue[]): PropertyKey[][] { - return issues.flatMap((issue) => (issue.continue === true ? [] : [issue.path ?? []])); -} - -function isUnder(path: readonly PropertyKey[], failed: readonly PropertyKey[]): boolean { - return failed.length <= path.length && failed.every((step, index) => step === path[index]); -} - -/** - * zod skips a node's own checks once a nested value failed; rewired, a check runs unless the node itself was refused - * (a pathless failure). The contract for a rule, which then meets the raw value at a failed property: a finding under - * a failed path is dropped (the shape's issue stands there), a throw ends the rule with its findings so far, and a - * rule branching on a sibling's type guards that read itself, and a rule reading a property or the truth of a - * sibling asks for the type first (an empty string's length is zero, a number is truthy). With no failure a throw - * propagates. - */ -function reportingBesideFailures(check: z.core.$ZodCheck): z.core.$ZodCheck { - if (REPORTS_BESIDE_FAILURES.has(check)) { - return check; - } - const { when, ...def } = check._zod.def; - const inner = check._zod.check; - const clone: z.core.$ZodCheck = { - _zod: { - def: { - ...def, - when: (payload) => - (when?.(payload) ?? true) && !failedPaths(payload.issues).some((p) => p.length === 0), - }, - onattach: check._zod.onattach, - check: (payload) => { - const failed = failedPaths(payload.issues); - if (failed.length === 0) { - return inner(payload); - } - const before = payload.issues.length; - try { - inner(payload); - } catch (error) { - // The rule tripped on a raw value whose own shape issue is already listed. - swallowedThrowObserver?.(error); - } - const findings = payload.issues.splice(before); - payload.issues.push( - ...findings.filter((f) => !failed.some((path) => isUnder(f.path ?? [], path))), - ); - }, - }, - }; - REPORTS_BESIDE_FAILURES.add(clone); - return clone; -} - /** - * Every plain (strip) object becomes a passthrough looseObject, so unknown keys ride through to GitHub - * and superRefine checks reading undeclared keys can see them. Preserved as authored: + * Every plain (strip) object becomes a passthrough looseObject, so unknown keys ride through to GitHub and the + * rules reading undeclared keys can see them. Preserved as authored: * - * strictObject -> stays strict - * refine/superRefine -> survives (clones carry the checks); one on the knobbed union itself throws instead - * a leaf's own checks -> rewired like a rule (a min or max length runs, in zod, on any value with a length, - * so it would judge a raw list beside the leaf's own type issue) - * knobbed-section union -> rewrapped as a container-routed check, so a failing entry keeps its issue path - * (`labels[2].name`) instead of a plain union's pathless "Invalid input" - * unrecognized CONTAINER -> throws, rather than ship a shape that silently skipped loosening + * strictObject -> stays strict + * a node's own checks -> survive on the clone (rule() gates each beside a failed nested value); one on the knobbed union itself throws + * knobbed-section union -> rewrapped as a container-routed check, so a failing entry keeps its path (`labels[2].name`) + * unrecognized CONTAINER -> throws, rather than ship a shape that silently skipped loosening */ export function loosen(schema: z.ZodType): z.ZodType { const def = defOf(schema); @@ -945,7 +867,7 @@ export function loosen(schema: z.ZodType): z.ZodType { `BUG: loosen(): unhandled schema type "${def.type}" - teach loosen() its runtime derivation before authoring it in src/schema.ts`, ); } - return (def.checks?.length ?? 0) > 0 ? cloneWith(schema, {}) : schema; + return schema; } } @@ -1010,7 +932,7 @@ function routedListShape(list: z.ZodType, wrapper: z.ZodType): z.ZodType { ctx.addIssue({ ...issue }); } // The raw value, not z.NEVER: a rule the section composed onto the routed shape runs beside the failed - // entry (reportingBesideFailures) and must meet the entries, raw where they failed. The parse fails regardless. + // entry (rule() in ../shared/schema-helpers.ts) and must meet the entries, raw where they failed. The parse fails regardless. return value; } return parsed.data; diff --git a/src/sections/deploy_keys/schema.ts b/src/sections/deploy_keys/schema.ts index ad55fbe93..e76c47528 100644 --- a/src/sections/deploy_keys/schema.ts +++ b/src/sections/deploy_keys/schema.ts @@ -2,6 +2,7 @@ import { err, ok, type Result } from "neverthrow"; import { z } from "zod"; +import { rule } from "../shared/schema-helpers.js"; /** * The key types GitHub accepts for a deploy key; the docs field note lists them for the reader. DSA (ssh-dss) is @@ -159,22 +160,24 @@ export const DeployKeyConfig = z read_only: z.boolean().optional(), }) // Entry-level so the refusal can name the entry by title; the field-level form would know only the index. - .superRefine((entry, refineCtx) => { - // The key or the title may be raw beside its own shape issue (see ../shared/raw-values.ts): a non-string key is - // no material to read, and a bare rendering of the title can throw on a mapping. - const key: unknown = entry.key; - if (typeof key !== "string") { - return; - } - const parsed = parsePublicKey(key); - if (parsed.isErr()) { - const who = typeof entry.title === "string" ? `entry "${entry.title}"` : "this entry"; - refineCtx.addIssue({ - code: "custom", - path: ["key"], - message: `${who}: ${parsed.error}`, - }); - } - }) + .check( + rule((entry, refineCtx) => { + // The key or the title may be raw beside its own shape issue (see ../shared/raw-values.ts): a non-string key is + // no material to read, and a bare rendering of the title can throw on a mapping. + const key: unknown = entry.key; + if (typeof key !== "string") { + return; + } + const parsed = parsePublicKey(key); + if (parsed.isErr()) { + const who = typeof entry.title === "string" ? `entry "${entry.title}"` : "this entry"; + refineCtx.addIssue({ + code: "custom", + path: ["key"], + message: `${who}: ${parsed.error}`, + }); + } + }), + ) .meta({ id: "DeployKeyConfig" }); export type DeployKeyConfig = z.infer; diff --git a/src/sections/environments/schema.ts b/src/sections/environments/schema.ts index 19a7a0279..827001c82 100644 --- a/src/sections/environments/schema.ts +++ b/src/sections/environments/schema.ts @@ -20,7 +20,9 @@ export function environmentKey(name: string): EnvironmentKey { import { isPlainObject } from "../../plain-data.js"; import { conditional, + maxLength, nestedKnobbed, + rule, secretName, variableConfig, } from "../shared/schema-helpers.js"; @@ -69,23 +71,25 @@ const DeploymentBranchPolicyFlags = z protected_branches: z.boolean(), custom_branch_policies: z.boolean(), }) - .superRefine((flags, refineCtx) => { - // A raw flag beside its own shape issue is neither setting: two equal raw values (0 and 0, a YAML alias - // to one mapping) are not both false, nor both true. - if ( - typeof flags.protected_branches !== "boolean" || - typeof flags.custom_branch_policies !== "boolean" || - flags.protected_branches !== flags.custom_branch_policies - ) { - return; - } - refineCtx.addIssue({ - code: "custom", - message: flags.protected_branches - ? "deployment_branch_policy sets both protected_branches and custom_branch_policies to true, which GitHub rejects: the two flags are mutually exclusive, so set exactly one of them to true" - : "deployment_branch_policy sets both protected_branches and custom_branch_policies to false, which GitHub rejects: GitHub spells 'any branch may deploy' as deployment_branch_policy: null, so write null", - }); - }) + .check( + rule((flags, refineCtx) => { + // A raw flag beside its own shape issue is neither setting: two equal raw values (0 and 0, a YAML alias + // to one mapping) are not both false, nor both true. + if ( + typeof flags.protected_branches !== "boolean" || + typeof flags.custom_branch_policies !== "boolean" || + flags.protected_branches !== flags.custom_branch_policies + ) { + return; + } + refineCtx.addIssue({ + code: "custom", + message: flags.protected_branches + ? "deployment_branch_policy sets both protected_branches and custom_branch_policies to true, which GitHub rejects: the two flags are mutually exclusive, so set exactly one of them to true" + : "deployment_branch_policy sets both protected_branches and custom_branch_policies to false, which GitHub rejects: GitHub spells 'any branch may deploy' as deployment_branch_policy: null, so write null", + }); + }), + ) .meta( conditional( { properties: { protected_branches: { const: true } } }, @@ -111,9 +115,11 @@ export const EnvironmentConfig = z prevent_self_review: z.boolean().optional(), reviewers: z .array(z.object({ type: z.enum(["User", "Team"]), id: z.number() })) - .max( - MAX_REVIEWERS, - `GitHub allows at most ${MAX_REVIEWERS} required reviewers per environment; keep ${MAX_REVIEWERS} or fewer entries`, + .check( + maxLength( + MAX_REVIEWERS, + `GitHub allows at most ${MAX_REVIEWERS} required reviewers per environment; keep ${MAX_REVIEWERS} or fewer entries`, + ), ) .optional(), deployment_branch_policy: DeploymentBranchPolicyFlags.nullable().optional(), @@ -122,46 +128,48 @@ export const EnvironmentConfig = z variables: nestedKnobbed(EnvironmentVariableConfig).optional(), secrets: nestedKnobbed(EnvironmentSecretConfig).optional(), }) - .superRefine((entry, refineCtx) => { - // A singular `secret` would ride the passthrough PUT verbatim and configure nothing. The strict - // type hides the key; only the loosen()ed shape that parses documents lets it reach here. - if ((entry as Record).secret !== undefined) { - refineCtx.addIssue({ - code: "custom", - path: ["secret"], - message: - "environment secrets belong under the entry's `secrets` list, not a singular `secret` key; here it would pass through to the environment PUT verbatim and configure nothing", - }); - } - // The name may be raw beside its own shape issue, and a bare rendering can throw on a mapping. - const who = typeof entry.name === "string" ? `the "${entry.name}" entry` : "this entry"; - // The flag lives on the required-reviewers rule, and GitHub creates that rule only for a - // non-empty reviewer list: with none, the flag reads back false and drifts on every run. A - // reviewers value that is not a list is raw beside its own shape issue and declares nothing here. - const reviewers = entry.reviewers; - const noReviewers = - reviewers === undefined || (Array.isArray(reviewers) && reviewers.length === 0); - if (entry.prevent_self_review === true && noReviewers) { - refineCtx.addIssue({ - code: "custom", - path: ["prevent_self_review"], - message: `${who} declares prevent_self_review: true without reviewers; GitHub keeps the flag only on a required-reviewers rule, which needs at least one reviewer. Declare a reviewer, or write prevent_self_review: false`, - }); - } - // Checked in the shape rather than the section's validate hook: both run before ANY section - // writes, and a refinement reports the pair at zod's own path beside the entry's other shape - // issues. Unchecked, the pattern POST would 404 only once the environment PUT had landed. - if (entry.deployment_branch_policies === undefined) { - return; - } - if (entry.deployment_branch_policy?.custom_branch_policies !== true) { - refineCtx.addIssue({ - code: "custom", - path: ["deployment_branch_policies"], - message: `${who} declares deployment_branch_policies, so it must also declare deployment_branch_policy with custom_branch_policies: true - GitHub rejects every pattern write while the flag is off`, - }); - } - }) + .check( + rule((entry, refineCtx) => { + // A singular `secret` would ride the passthrough PUT verbatim and configure nothing. The strict + // type hides the key; only the loosen()ed shape that parses documents lets it reach here. + if ((entry as Record).secret !== undefined) { + refineCtx.addIssue({ + code: "custom", + path: ["secret"], + message: + "environment secrets belong under the entry's `secrets` list, not a singular `secret` key; here it would pass through to the environment PUT verbatim and configure nothing", + }); + } + // The name may be raw beside its own shape issue, and a bare rendering can throw on a mapping. + const who = typeof entry.name === "string" ? `the "${entry.name}" entry` : "this entry"; + // The flag lives on the required-reviewers rule, and GitHub creates that rule only for a + // non-empty reviewer list: with none, the flag reads back false and drifts on every run. A + // reviewers value that is not a list is raw beside its own shape issue and declares nothing here. + const reviewers = entry.reviewers; + const noReviewers = + reviewers === undefined || (Array.isArray(reviewers) && reviewers.length === 0); + if (entry.prevent_self_review === true && noReviewers) { + refineCtx.addIssue({ + code: "custom", + path: ["prevent_self_review"], + message: `${who} declares prevent_self_review: true without reviewers; GitHub keeps the flag only on a required-reviewers rule, which needs at least one reviewer. Declare a reviewer, or write prevent_self_review: false`, + }); + } + // Checked in the shape rather than the section's validate hook: both run before ANY section + // writes, and a refinement reports the pair at zod's own path beside the entry's other shape + // issues. Unchecked, the pattern POST would 404 only once the environment PUT had landed. + if (entry.deployment_branch_policies === undefined) { + return; + } + if (entry.deployment_branch_policy?.custom_branch_policies !== true) { + refineCtx.addIssue({ + code: "custom", + path: ["deployment_branch_policies"], + message: `${who} declares deployment_branch_policies, so it must also declare deployment_branch_policy with custom_branch_policies: true - GitHub rejects every pattern write while the flag is off`, + }); + } + }), + ) .meta({ id: "EnvironmentConfig", allOf: [ @@ -186,19 +194,23 @@ export const EnvironmentConfig = z }); export type EnvironmentConfig = z.infer; -export const EnvironmentsConfig = z.array(EnvironmentConfig).superRefine((entries, refineCtx) => { - // An entry may be raw beside its own shape issue (see ../shared/raw-values.ts); it declares no pin. - const pinnedIndexes = entries.flatMap((entry, index) => - isPlainObject(entry) && entry.pinned === true ? [index] : [], - ); - if (pinnedIndexes.length > MAX_PINNED_ENVIRONMENTS) { - refineCtx.addIssue({ - code: "custom", - path: [pinnedIndexes[MAX_PINNED_ENVIRONMENTS] as number, "pinned"], - message: `the settings file declares ${pinnedIndexes.length} environments with pinned: true, but GitHub allows at most ${MAX_PINNED_ENVIRONMENTS} pinned environments per repository. Declare pinned: true on at most ${MAX_PINNED_ENVIRONMENTS} entries`, - }); - } -}); +export const EnvironmentsConfig = z.array(EnvironmentConfig).check( + rule((entries, refineCtx) => { + // An entry may be raw beside its own shape issue (see ../shared/raw-values.ts); it declares no pin. + const pinnedIndexes = entries.flatMap((entry, index) => + isPlainObject(entry) && entry.pinned === true ? [index] : [], + ); + if (pinnedIndexes.length > MAX_PINNED_ENVIRONMENTS) { + refineCtx.addIssue({ + code: "custom", + path: [pinnedIndexes[MAX_PINNED_ENVIRONMENTS] as number, "pinned"], + message: + `the settings file declares ${pinnedIndexes.length} environments with pinned: true, but GitHub allows at most ` + + `${MAX_PINNED_ENVIRONMENTS} pinned environments per repository. Declare pinned: true on at most ${MAX_PINNED_ENVIRONMENTS} entries`, + }); + } + }), +); /** * Where routed-ness is DECLARED: a key here is a scalar the environment PUT does not accept, diff --git a/src/sections/interaction_limits/schema.ts b/src/sections/interaction_limits/schema.ts index 847aa9f6b..59e14f3ea 100644 --- a/src/sections/interaction_limits/schema.ts +++ b/src/sections/interaction_limits/schema.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { agree } from "../../text.js"; import { stringItems } from "../shared/raw-values.js"; +import { rule } from "../shared/schema-helpers.js"; const INTERACTION_GROUPS = ["existing_users", "contributors_only", "collaborators_only"] as const; const INTERACTION_EXPIRIES = [ @@ -59,58 +60,60 @@ const InteractionLimits = z }, { error: unknownKeyError }, ) - .superRefine((declared, refineCtx) => { - // Checked in the shape so both modes fail before ANY section writes. - if ( - declared.limit === undefined && - declared.expiry === undefined && - declared.pull_request_creation_cap === undefined && - declared.pull_request_creation_bypass === undefined - ) { - refineCtx.addIssue({ - code: "custom", - message: - "declare at least one of limit, pull_request_creation_cap, or pull_request_creation_bypass (or declare interaction_limits: null to clear the base limit)", - }); - } - if (declared.expiry !== undefined && declared.limit === undefined) { - // GitHub rejects the base PUT body without a limit, and a run that never issues the PUT would - // silently drop the expiry. - refineCtx.addIssue({ - code: "custom", - path: ["limit"], - message: - "expiry rides the base interaction-limits PUT, which requires a limit; declare limit alongside it, or remove expiry", - }); - } - // The list may be raw beside its own shape issue (see ../shared/raw-values.ts); a non-list holds no logins. - const bypass: unknown = declared.pull_request_creation_bypass; - if (!Array.isArray(bypass)) { - return; - } - if (bypass.length > BYPASS_MAX) { - refineCtx.addIssue({ - code: "custom", - path: ["pull_request_creation_bypass"], - message: `GitHub caps the bypass list at ${BYPASS_MAX} users, but ${bypass.length} logins are declared; trim the list`, - }); - } - const seen = new Map(); - // A raw item beside its own shape issue is passed over (see ../shared/raw-values.ts); the string items are judged. - for (const login of stringItems(bypass)) { - const key = login.toLowerCase(); - const first = seen.get(key); - if (first === undefined) { - seen.set(key, login); - } else { + .check( + rule((declared, refineCtx) => { + // Checked in the shape so both modes fail before ANY section writes. + if ( + declared.limit === undefined && + declared.expiry === undefined && + declared.pull_request_creation_cap === undefined && + declared.pull_request_creation_bypass === undefined + ) { + refineCtx.addIssue({ + code: "custom", + message: + "declare at least one of limit, pull_request_creation_cap, or pull_request_creation_bypass (or declare interaction_limits: null to clear the base limit)", + }); + } + if (declared.expiry !== undefined && declared.limit === undefined) { + // GitHub rejects the base PUT body without a limit, and a run that never issues the PUT would + // silently drop the expiry. + refineCtx.addIssue({ + code: "custom", + path: ["limit"], + message: + "expiry rides the base interaction-limits PUT, which requires a limit; declare limit alongside it, or remove expiry", + }); + } + // The list may be raw beside its own shape issue (see ../shared/raw-values.ts); a non-list holds no logins. + const bypass: unknown = declared.pull_request_creation_bypass; + if (!Array.isArray(bypass)) { + return; + } + if (bypass.length > BYPASS_MAX) { refineCtx.addIssue({ code: "custom", path: ["pull_request_creation_bypass"], - message: `"${first}" and "${login}" name the same login (logins are case-insensitive); keep exactly one`, + message: `GitHub caps the bypass list at ${BYPASS_MAX} users, but ${bypass.length} logins are declared; trim the list`, }); } - } - }) + const seen = new Map(); + // A raw item beside its own shape issue is passed over (see ../shared/raw-values.ts); the string items are judged. + for (const login of stringItems(bypass)) { + const key = login.toLowerCase(); + const first = seen.get(key); + if (first === undefined) { + seen.set(key, login); + } else { + refineCtx.addIssue({ + code: "custom", + path: ["pull_request_creation_bypass"], + message: `"${first}" and "${login}" name the same login (logins are case-insensitive); keep exactly one`, + }); + } + } + }), + ) .meta({ id: "InteractionLimitsConfig" }); export const InteractionLimitsConfig = InteractionLimits.nullable(); diff --git a/src/sections/pages/schema.ts b/src/sections/pages/schema.ts index 1b490ea79..d9566dde4 100644 --- a/src/sections/pages/schema.ts +++ b/src/sections/pages/schema.ts @@ -2,6 +2,7 @@ import type { components, operations } from "@octokit/openapi-types"; import { z } from "zod"; +import { rule } from "../shared/schema-helpers.js"; type PagesPutBody = NonNullable< operations["repos/update-information-about-pages-site"]["requestBody"] @@ -41,20 +42,22 @@ const PagesSite = z https_enforced: z.boolean().optional(), public: z.boolean().optional(), }) - .superRefine((site, refineCtx) => { - // The strict type hides these keys; only the loosen()ed shape that parses documents lets them reach here. - for (const [key, fix] of Object.entries(READ_ONLY_SITE_FIELDS)) { - if ((site as Record)[key] !== undefined) { - refineCtx.addIssue({ - code: "custom", - path: [key], - message: - "GitHub reports this field on the Pages site and the update has no such parameter, so the " + - `value would be sent, ignored, and reported as drift on every run (${fix}); remove it`, - }); + .check( + rule((site, refineCtx) => { + // The strict type hides these keys; only the loosen()ed shape that parses documents lets them reach here. + for (const [key, fix] of Object.entries(READ_ONLY_SITE_FIELDS)) { + if ((site as Record)[key] !== undefined) { + refineCtx.addIssue({ + code: "custom", + path: [key], + message: + "GitHub reports this field on the Pages site and the update has no such parameter, so the " + + `value would be sent, ignored, and reported as drift on every run (${fix}); remove it`, + }); + } } - } - }) + }), + ) .meta({ id: "PagesConfig", // The published schema carries the same refusal, so an editor flags the key as the file is written. diff --git a/src/sections/repository/schema.ts b/src/sections/repository/schema.ts index 134ec72db..29587a2ca 100644 --- a/src/sections/repository/schema.ts +++ b/src/sections/repository/schema.ts @@ -4,7 +4,7 @@ import type { components, operations } from "@octokit/openapi-types"; import { z } from "zod"; import { describeValue } from "../../plain-data.js"; import type { MustBeNever } from "../../types.js"; -import { conditional } from "../shared/schema-helpers.js"; +import { conditional, rule } from "../shared/schema-helpers.js"; /** A PATCH boolean; a null on it is the validator's general refusal (no empty state; write true or false), not this shape's. */ function repositoryToggle() { @@ -544,7 +544,7 @@ export const RepositoryConfig = z ...patchFieldShape, topics: z .union([topicList, z.array(topicName)]) - .superRefine(refineTopicCount) + .check(rule(refineTopicCount)) .optional(), enable_vulnerability_alerts: repositoryToggle(), enable_automated_security_fixes: repositoryToggle(), @@ -555,15 +555,17 @@ export const RepositoryConfig = z issue_creation_policy: creationPolicy(), }) .catchall(z.unknown()) - .superRefine((declared, ctx) => { - // A refusal here, not a strict object: a field GitHub adds to the PATCH tomorrow must still pass through. - for (const key of GET_ONLY_KEYS) { - if (Object.hasOwn(declared, key)) { - ctx.addIssue({ code: "custom", path: [key], message: getOnlyKeyMessage(key) }); + .check( + rule((declared, ctx) => { + // A refusal here, not a strict object: a field GitHub adds to the PATCH tomorrow must still pass through. + for (const key of GET_ONLY_KEYS) { + if (Object.hasOwn(declared, key)) { + ctx.addIssue({ code: "custom", path: [key], message: getOnlyKeyMessage(key) }); + } } - } - refineCommitMessagePairs(declared, ctx); - }) + refineCommitMessagePairs(declared, ctx); + }), + ) .meta({ id: "RepositoryConfig", allOf: commitMessagePairRules() }); export type RepositoryConfig = z.infer; diff --git a/src/sections/rulesets/schema.ts b/src/sections/rulesets/schema.ts index 5ead96c8e..fca944b03 100644 --- a/src/sections/rulesets/schema.ts +++ b/src/sections/rulesets/schema.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { isPlainObject } from "../../plain-data.js"; +import { rule as gatedRule } from "../shared/schema-helpers.js"; // --- Ref-name conditions ------------------------------------------------------ @@ -63,31 +64,33 @@ const BypassActorConfig = z actor_type: z.enum(BYPASS_ACTOR_TYPES), bypass_mode: z.enum(["always", "pull_request", "exempt"]).optional(), }) - .superRefine((actor, refineCtx) => { - if (IDENTIFIED_ACTOR_TYPES.has(actor.actor_type) && typeof actor.actor_id !== "number") { - refineCtx.addIssue({ - code: "custom", - path: ["actor_id"], - message: `a ${actor.actor_type} bypass actor needs its numeric actor_id (the id GitHub assigns the app, role, team, or user); GitHub rejects the ruleset without it`, - }); - } - if (actor.actor_type === "DeployKey" && typeof actor.actor_id === "number") { - refineCtx.addIssue({ - code: "custom", - path: ["actor_id"], - message: - "a DeployKey bypass actor takes no actor_id (GitHub documents it as null); remove the key or write null", - }); - } - if (actor.actor_type === "DeployKey" && actor.bypass_mode === "pull_request") { - refineCtx.addIssue({ - code: "custom", - path: ["bypass_mode"], - message: - 'bypass_mode "pull_request" does not apply to a DeployKey actor; use "always" or "exempt"', - }); - } - }) + .check( + gatedRule((actor, refineCtx) => { + if (IDENTIFIED_ACTOR_TYPES.has(actor.actor_type) && typeof actor.actor_id !== "number") { + refineCtx.addIssue({ + code: "custom", + path: ["actor_id"], + message: `a ${actor.actor_type} bypass actor needs its numeric actor_id (the id GitHub assigns the app, role, team, or user); GitHub rejects the ruleset without it`, + }); + } + if (actor.actor_type === "DeployKey" && typeof actor.actor_id === "number") { + refineCtx.addIssue({ + code: "custom", + path: ["actor_id"], + message: + "a DeployKey bypass actor takes no actor_id (GitHub documents it as null); remove the key or write null", + }); + } + if (actor.actor_type === "DeployKey" && actor.bypass_mode === "pull_request") { + refineCtx.addIssue({ + code: "custom", + path: ["bypass_mode"], + message: + 'bypass_mode "pull_request" does not apply to a DeployKey actor; use "always" or "exempt"', + }); + } + }), + ) .meta({ id: "BypassActorConfig" }); // --- Rules ------------------------------------------------------------------------ @@ -270,7 +273,13 @@ const UnknownRule = z .looseObject({ type: z .string() - .refine((type) => !KNOWN_RULE_TYPES.includes(type), { abort: true }) + .check( + gatedRule((type, refineCtx) => { + if (KNOWN_RULE_TYPES.includes(type)) { + refineCtx.addIssue({ code: "custom", continue: false }); + } + }), + ) .meta({ not: { enum: [...KNOWN_RULE_TYPES] } }), parameters: z.record(z.string(), z.unknown()).optional(), }) @@ -321,24 +330,26 @@ export const RulesetConfig = z rules: z.array(RuleConfig).optional(), bypass_actors: z.array(BypassActorConfig).optional(), }) - .superRefine((ruleset, refineCtx) => { - // The spec: `pull_request` bypass applies to branch rulesets only; the target defaults to branch upstream. The - // target, the actor list, or an actor may be raw beside its own shape issue (see ../shared/raw-values.ts): only - // the two other targets carry the restriction, a non-list holds no actors, and a non-mapping declares no mode. - const target: unknown = ruleset.target; - if (target !== "tag" && target !== "push") { - return; - } - const actors: unknown = ruleset.bypass_actors; - for (const [index, actor] of (Array.isArray(actors) ? actors : []).entries()) { - if (isPlainObject(actor) && actor.bypass_mode === "pull_request") { - refineCtx.addIssue({ - code: "custom", - path: ["bypass_actors", index, "bypass_mode"], - message: `bypass_mode "pull_request" applies to branch rulesets only, and this ruleset targets ${target}; use "always" or "exempt"`, - }); + .check( + gatedRule((ruleset, refineCtx) => { + // The spec: `pull_request` bypass applies to branch rulesets only; the target defaults to branch upstream. The + // target, the actor list, or an actor may be raw beside its own shape issue (see ../shared/raw-values.ts): only + // the two other targets carry the restriction, a non-list holds no actors, and a non-mapping declares no mode. + const target: unknown = ruleset.target; + if (target !== "tag" && target !== "push") { + return; } - } - }) + const actors: unknown = ruleset.bypass_actors; + for (const [index, actor] of (Array.isArray(actors) ? actors : []).entries()) { + if (isPlainObject(actor) && actor.bypass_mode === "pull_request") { + refineCtx.addIssue({ + code: "custom", + path: ["bypass_actors", index, "bypass_mode"], + message: `bypass_mode "pull_request" applies to branch rulesets only, and this ruleset targets ${target}; use "always" or "exempt"`, + }); + } + } + }), + ) .meta({ id: "RulesetConfig" }); export type RulesetConfig = z.infer; diff --git a/src/sections/secret_scanning_custom_patterns/schema.ts b/src/sections/secret_scanning_custom_patterns/schema.ts index cfdc1d2ff..1e8c46717 100644 --- a/src/sections/secret_scanning_custom_patterns/schema.ts +++ b/src/sections/secret_scanning_custom_patterns/schema.ts @@ -1,6 +1,7 @@ /** The `secret_scanning_custom_patterns:` section's schema slice; root src/schema.ts composes the SettingsFile property from it. */ import { z } from "zod"; +import { minLength, rule } from "../shared/schema-helpers.js"; import { compileFailure } from "./compilable-form.js"; const DELIMITER_CLEAR_ERROR = @@ -11,19 +12,21 @@ const REGEX_SYNTAX = "regexSyntax"; /** A regex field: the syntax check of compilable-form.ts, which refuses only what PCRE syntax refuses too. */ function regexSource(): z.ZodString { - return z.string().superRefine((source, refineCtx) => { - const reason = compileFailure(source); - if (reason !== undefined) { - refineCtx.addIssue({ - code: "custom", - message: - `cannot be compiled as a regular expression (${reason}); fix the expression, or report a documentation issue if ` + - "Hyperscan accepts it as written - the check translates the PCRE-only forms the field docs list before compiling, " + - "and GitHub can still refuse at apply what Hyperscan alone refuses", - params: { [REGEX_SYNTAX]: reason }, - }); - } - }); + return z.string().check( + rule((source, refineCtx) => { + const reason = compileFailure(source); + if (reason !== undefined) { + refineCtx.addIssue({ + code: "custom", + message: + `cannot be compiled as a regular expression (${reason}); fix the expression, or report a documentation issue if ` + + "Hyperscan accepts it as written - the check translates the PCRE-only forms the field docs list before compiling, " + + "and GitHub can still refuse at apply what Hyperscan alone refuses", + params: { [REGEX_SYNTAX]: reason }, + }); + } + }), + ); } function syntaxReason(issue: z.core.$ZodIssue): string | undefined { @@ -59,8 +62,8 @@ export const SecretScanningPatternConfig = z pattern: regexSource(), // "" cannot mean "clear the delimiter" (the PATCH updates provided fields only), so the spelling // fails at document validation, before any repository is touched. - start_delimiter: regexSource().min(1, DELIMITER_CLEAR_ERROR).optional(), - end_delimiter: regexSource().min(1, DELIMITER_CLEAR_ERROR).optional(), + start_delimiter: regexSource().check(minLength(1, DELIMITER_CLEAR_ERROR)).optional(), + end_delimiter: regexSource().check(minLength(1, DELIMITER_CLEAR_ERROR)).optional(), must_match: z.array(regexSource()).optional(), must_not_match: z.array(regexSource()).optional(), }) diff --git a/src/sections/shared/raw-values.ts b/src/sections/shared/raw-values.ts index 9d9014562..06afcb02b 100644 --- a/src/sections/shared/raw-values.ts +++ b/src/sections/shared/raw-values.ts @@ -1,6 +1,6 @@ /** - * Readers for a shape rule whose sibling failed its type and so holds the raw value (reportingBesideFailures in - * ../contract/module.ts states the contract): the rule judges what it can read and passes over the rest. + * Readers for a shape rule whose sibling failed its type and so holds the raw value (rule() in + * ./schema-helpers.ts states the contract): the rule judges what it can read and passes over the rest. */ /** The string items of a list; none for a value that is not a list, and a raw item is passed over. */ diff --git a/src/sections/shared/schema-helpers.ts b/src/sections/shared/schema-helpers.ts index 17c38a14a..8c3b66d7d 100644 --- a/src/sections/shared/schema-helpers.ts +++ b/src/sections/shared/schema-helpers.ts @@ -166,6 +166,72 @@ export function layeredList>(list: L) { })); } +/** The paths of the issues that abort a parse (a wrong type, a refused option); a rule's own finding and an unrecognized key do not. */ +function failedPaths(issues: readonly z.core.$ZodRawIssue[]): PropertyKey[][] { + return issues.flatMap((issue) => (issue.continue === true ? [] : [issue.path ?? []])); +} + +function isUnder(path: readonly PropertyKey[], failed: readonly PropertyKey[]): boolean { + return failed.length <= path.length && failed.every((step, index) => step === path[index]); +} + +/** + * The gate under which a rule and a length bound run: zod skips a check once a nested value failed, and runs a + * length bound on any value with a length; gated, both run unless the node itself was refused (a pathless failure). + */ +function notRefusedItself(payload: z.core.ParsePayload): boolean { + return !failedPaths(payload.issues).some((path) => path.length === 0); +} + +/** + * A schema's own rule, run beside a failed nested value, where `fn` meets the raw value at the failed property and + * asks for its type before reading it; lint/rule-gate.grit holds every refinement under src/ to this form. + * + * finding under a failed path -> dropped; the shape's issue stands there + * finding anywhere else -> kept beside the shape's issues + */ +export function rule( + fn: (value: T, ctx: z.core.$RefinementCtx) => void, + params: z.core.$ZodSuperRefineParams = {}, +): z.core.$ZodCheck { + const { when } = params; + return z.superRefine( + (value, ctx) => { + const failed = failedPaths(ctx.issues); + const before = ctx.issues.length; + fn(value, ctx); + if (failed.length === 0) { + return; + } + const findings = ctx.issues.splice(before); + ctx.issues.push( + ...findings.filter((finding) => !failed.some((path) => isUnder(finding.path ?? [], path))), + ); + }, + { ...params, when: (payload) => notRefusedItself(payload) && (when?.(payload) ?? true) }, + ); +} + +/** zod's own .min() on a string or a list, gated: bare, it judges a raw `[]` an empty delimiter beside the leaf's own type issue. */ +export function minLength(minimum: number, message: string): z.core.$ZodCheckMinLength { + return new z.core.$ZodCheckMinLength({ + check: "min_length", + minimum, + when: notRefusedItself, + error: () => message, + }); +} + +/** zod's own .max() on a string or a list, gated like minLength(). */ +export function maxLength(maximum: number, message: string): z.core.$ZodCheckMaxLength { + return new z.core.$ZodCheckMaxLength({ + check: "max_length", + maximum, + when: notRefusedItself, + error: () => message, + }); +} + /** A repository-scope sealed secret entry (name + `$NAME` reference value). */ export function sealedSecretConfig(id: string) { return z @@ -189,7 +255,7 @@ export function variableConfig(id: string) { /** * A string GitHub caps by size, refused past the cap with the measured size in the message. The check runs on * strings alone: zod's own `.max()` runs on any value with a `length`, so a YAML mapping `{length: 101}` reached the - * comparison and threw, while a refinement is skipped once the type check has failed. JSON Schema's maxLength counts + * comparison and threw, while a rule is skipped once the type check has failed. JSON Schema's maxLength counts * code points, so the published bound is exact for a code-point cap and, for a byte cap, the loosest bound an editor * can check without refusing a value GitHub accepts (a code point is at least one byte). */ @@ -205,9 +271,14 @@ export function boundedString( : (value: string) => [...value].length; return z .string() - .refine((value) => sizeOf(value) <= maximum, { - error: (issue: z.core.$ZodRawIssue) => message(sizeOf(issue.input as string)), - }) + .check( + rule((value, ctx) => { + const size = sizeOf(value); + if (size > maximum) { + ctx.addIssue({ code: "custom", message: message(size) }); + } + }), + ) .meta({ maxLength: maximum }); } diff --git a/src/sections/shared/setup-schema.ts b/src/sections/shared/setup-schema.ts index c73ef0b74..51606cad2 100644 --- a/src/sections/shared/setup-schema.ts +++ b/src/sections/shared/setup-schema.ts @@ -81,7 +81,7 @@ interface RunnerFields { } /** - * For the setup slice's `.superRefine`. Only the loosen()ed clone, which keeps unknown keys, parses + * The setup slice's rule(). Only the loosen()ed clone, which keeps unknown keys, parses * documents, so the GET-only keys are read off the parsed record. * * schedule / updated_at declared -> refused: the PATCH has no such field diff --git a/src/sections/webhooks/schema.ts b/src/sections/webhooks/schema.ts index 02268169c..0da74661a 100644 --- a/src/sections/webhooks/schema.ts +++ b/src/sections/webhooks/schema.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { describeValue } from "../../plain-data.js"; +import { rule } from "../shared/schema-helpers.js"; import { REPOSITORY_WEBHOOK_EVENTS, WEBHOOK_EVENTS_REFERENCE } from "./events.js"; // GitHub 422s each of these at apply time ("is not a valid event", "Url is not a valid URL"); the REST wire types are @@ -44,18 +45,20 @@ export const WebhookConfig = z events: z.array(WebhookEvent).optional(), active: z.boolean().optional(), }) - .superRefine((entry, refineCtx) => { - // An ENTRY-level secret would pass the loose shape, ship the raw reference text verbatim, and - // create a silently unauthenticated hook, the exact failure this feature exists to prevent. The - // strict type hides the key; only the loosen()ed shape that parses documents lets it reach here. - if ((entry as Record).secret !== undefined) { - refineCtx.addIssue({ - code: "custom", - path: ["secret"], - message: - "a webhook secret belongs under config.secret, not at the entry level; here it would pass through verbatim and the hook would be created without a working secret", - }); - } - }) + .check( + rule((entry, refineCtx) => { + // An ENTRY-level secret would pass the loose shape, ship the raw reference text verbatim, and + // create a silently unauthenticated hook, the exact failure this feature exists to prevent. The + // strict type hides the key; only the loosen()ed shape that parses documents lets it reach here. + if ((entry as Record).secret !== undefined) { + refineCtx.addIssue({ + code: "custom", + path: ["secret"], + message: + "a webhook secret belongs under config.secret, not at the entry level; here it would pass through verbatim and the hook would be created without a working secret", + }); + } + }), + ) .meta({ id: "WebhookConfig" }); export type WebhookConfig = z.infer; diff --git a/test/lint/fixture-lint.ts b/test/lint/fixture-lint.ts new file mode 100644 index 000000000..fe4b613a0 --- /dev/null +++ b/test/lint/fixture-lint.ts @@ -0,0 +1,68 @@ +/** + * Lints a fixture tree under the repository's own biome.json and every plugin it names, so a plugin's test pins the + * configuration's wiring (reach, exemptions) along with the pattern. + * + * the fixture tree is the root -> the `overrides` globs resolve against it; `vcs.useIgnoreFile` wants a git repository there + * the root sits under a `src/` parent -> a glob matching the absolute path would reach every file src/** excludes + */ + +import { spawnSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { ROOT } from "../root.js"; + +const BIOME = join(ROOT, "node_modules", ".bin", "biome"); + +interface BiomeConfiguration { + plugins?: string[]; + overrides?: { plugins?: string[] }[]; +} + +const CONFIGURATION = (() => { + const biomeJson = readFileSync(join(ROOT, "biome.json"), "utf8"); + const config = JSON.parse(biomeJson) as BiomeConfiguration; + const plugins = [ + ...(config.plugins ?? []), + ...(config.overrides ?? []).flatMap((override) => override.plugins ?? []), + ]; + const entries: [string, string][] = [ + ["biome.json", biomeJson], + ...plugins.map((path): [string, string] => [path, readFileSync(join(ROOT, path), "utf8")]), + ]; + return Object.fromEntries(entries); +})(); + +interface Diagnostic { + category: string; + message: string; + location: { path: string; start: { line: number } }; +} + +/** + * `path:line -> "category: message"`, one entry per line; when a line also carries a built-in rule's diagnostic + * (a throw inside finally trips noUnsafeFinally too), the plugin's wins, since the plugin is what these tests pin. + */ +export function lint(tmp: string, files: Record): Record { + const dir = join(tmp, "src", "checkout"); + for (const [path, text] of Object.entries({ ...CONFIGURATION, ...files })) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), text); + } + spawnSync("git", ["init", "--quiet"], { cwd: dir }); + const run = spawnSync(BIOME, ["lint", "--reporter=json", "--no-errors-on-unmatched", "."], { + cwd: dir, + encoding: "utf8", + }); + if (run.stdout === "") { + throw new Error(`biome wrote no report: ${run.stderr}`); + } + const { diagnostics } = JSON.parse(run.stdout) as { diagnostics: Diagnostic[] }; + const byLine: Record = {}; + for (const d of diagnostics) { + const key = `${d.location.path}:${d.location.start.line}`; + if (!(key in byLine) || d.category === "plugin") { + byLine[key] = `${d.category}: ${d.message}`; + } + } + return byLine; +} diff --git a/test/lint/never-throw.test.ts b/test/lint/never-throw.test.ts index 83f076b1e..b16ac388c 100644 --- a/test/lint/never-throw.test.ts +++ b/test/lint/never-throw.test.ts @@ -4,22 +4,12 @@ */ import { describe, expect, test } from "bun:test"; -import { spawnSync } from "node:child_process"; -import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { ROOT } from "../root.js"; import { withTempDir } from "../temp-dir.js"; +import { lint } from "./fixture-lint.js"; -const BIOME = join(ROOT, "node_modules", ".bin", "biome"); -/** The repository's own configuration and the plugin it names, copied so the fixture tree is the root its - * `overrides` globs are relative to; `vcs.useIgnoreFile` wants that root to be a git repository. The root sits - * under a `src/` parent, so a glob matching the absolute path would reach every excluded file. */ -const CONFIGURATION = Object.fromEntries( - ["biome.json", "lint/never-throw.grit"].map((path) => [ - path, - readFileSync(join(ROOT, path), "utf8"), - ]), -); const MESSAGE = "throw outside the never-throw rule: not a BUG: invariant (an Error whose message starts with BUG:) and not a bare rethrow of the catch binding; return a Result instead"; @@ -311,39 +301,6 @@ export function hidden(): never { const OUTSIDE_THE_RULE = 'export function outside(): never {\n throw new Error("x");\n}\n'; const CONTRACT_FILE = "src/cli/inputs.ts"; -interface Diagnostic { - category: string; - message: string; - location: { path: string; start: { line: number } }; -} - -function lint(tmp: string, files: Record): Record { - const dir = join(tmp, "src", "checkout"); - for (const [path, text] of Object.entries({ ...CONFIGURATION, ...files })) { - mkdirSync(dirname(join(dir, path)), { recursive: true }); - writeFileSync(join(dir, path), text); - } - spawnSync("git", ["init", "--quiet"], { cwd: dir }); - const run = spawnSync(BIOME, ["lint", "--reporter=json", "--no-errors-on-unmatched", "."], { - cwd: dir, - encoding: "utf8", - }); - if (run.stdout === "") { - throw new Error(`biome wrote no report: ${run.stderr}`); - } - const { diagnostics } = JSON.parse(run.stdout) as { diagnostics: Diagnostic[] }; - // One entry per line; when a line also carries a built-in rule's diagnostic (a throw inside finally trips - // noUnsafeFinally too), the plugin's wins, since the plugin is what this test pins. - const byLine: Record = {}; - for (const d of diagnostics) { - const key = `${d.location.path}:${d.location.start.line}`; - if (!(key in byLine) || d.category === "plugin") { - byLine[key] = `${d.category}: ${d.message}`; - } - } - return byLine; -} - describe("the never-throw plugin", () => { test("flags exactly the throws outside the rule, and nothing outside src/ or in the contract file", () => withTempDir("never-throw-", (dir) => { diff --git a/test/lint/rule-gate.test.ts b/test/lint/rule-gate.test.ts new file mode 100644 index 000000000..84dc45f0e --- /dev/null +++ b/test/lint/rule-gate.test.ts @@ -0,0 +1,60 @@ +/** + * The rule-gate plugin's verdict on each refinement form, and its biome.json wiring, pinned by linting a fixture tree + * with the repository's own configuration; a snippet that silently stopped matching would let a bare refinement + * ship, and zod would skip it once a nested value failed. + */ + +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { ROOT } from "../root.js"; +import { withTempDir } from "../temp-dir.js"; +import { lint } from "./fixture-lint.js"; + +const MESSAGE = + "bare refinement: zod skips it once a nested value failed; wrap it in rule() so it runs beside nested failures"; +const EXEMPT_FILE = "src/sections/shared/schema-helpers.ts"; + +/** A line ending in `// bare` is one the plugin must flag; every other refinement here is authored through rule(). */ +const BARE = /\/\/ bare$/; + +const REFINEMENTS = ` +import { z } from "zod"; +import { maxLength, rule } from "./sections/shared/schema-helpers.js"; +const fn = () => true; +export const one = z.string().refine(fn); // bare +export const two = z.string().refine(fn, { error: "x" }); // bare +export const typed = z.string().refine(fn); // bare +export const sup = z.object({ n: z.string() }).superRefine(fn); // bare +export const supParams = z.object({ n: z.string() }).superRefine(fn, { when: () => true }); // bare +export const supTyped = z.object({ n: z.string() }).superRefine<{ n: string }>(fn); // bare +export const composed = z.object({ n: z.string() }).check(z.superRefine(fn)); // bare +export const gated = z.object({ n: z.string() }).check(rule(fn)); +export const bounded = z.array(z.string()).check(maxLength(1, "x")); +`.trimStart(); + +describe("the rule-gate plugin", () => { + test("flags exactly the bare refinements, and nothing in the exempt file or outside src/", () => + withTempDir("rule-gate-", (dir) => { + const expected = Object.fromEntries( + REFINEMENTS.split("\n").flatMap((line, index) => + BARE.test(line) ? [[`src/refinements.ts:${index + 1}`, `plugin: ${MESSAGE}`]] : [], + ), + ); + expect( + lint(dir, { + "src/refinements.ts": REFINEMENTS, + [EXEMPT_FILE]: REFINEMENTS, + "test/src/fixture.ts": REFINEMENTS, + }), + ).toEqual(expected); + })); + + test("the exempt file still holds a bare refinement (rule() itself), so its exemption is not stale", () => + withTempDir("rule-gate-", (dir) => { + const flagged = lint(dir, { + "src/not-exempt.ts": readFileSync(join(ROOT, EXEMPT_FILE), "utf8"), + }); + expect(Object.values(flagged)).toContain(`plugin: ${MESSAGE}`); + })); +}); diff --git a/test/sections/loosen.test.ts b/test/sections/loosen.test.ts index fad6e163e..33e24e873 100644 --- a/test/sections/loosen.test.ts +++ b/test/sections/loosen.test.ts @@ -5,7 +5,7 @@ import { describe, expect, test } from "bun:test"; import { z } from "zod"; -import { checksReportingBesideFailures, loosen } from "../../src/sections/contract/module.js"; +import { loosen } from "../../src/sections/contract/module.js"; describe("loosen", () => { test("strip objects become passthrough, and their superRefines see unknown keys", () => { @@ -87,98 +87,3 @@ describe("loosen", () => { ); }); }); - -describe("every check reports beside a failed nested value", () => { - const pair = z - .object({ mode: z.enum(["a", "b"]).optional(), list: z.array(z.string()).optional() }) - .superRefine((value, ctx) => { - if (value.list !== undefined && value.mode !== "a") { - ctx.addIssue({ code: "custom", path: ["list"], message: "list needs mode a" }); - } - }); - - test("an object's own rule runs when a sibling property failed, and its finding keeps its path", () => { - const issues = loosen(pair).safeParse({ mode: "c", list: ["x"] }).error?.issues; - expect(issues?.map((issue) => [issue.path, issue.message])).toEqual([ - [["mode"], expect.stringMatching(/^Invalid option/)], - [["list"], "list needs mode a"], - ]); - }); - - test("a rule's finding under the failed path is dropped: the shape's issue there is the report", () => { - const sweep = z.object({ list: z.array(z.string()) }).superRefine((value, ctx) => { - for (const key of Object.keys(value.list)) { - ctx.addIssue({ code: "custom", path: ["list", key], message: "swept" }); - } - }); - const issues = loosen(sweep).safeParse({ list: "yes" }).error?.issues; - expect(issues?.map((issue) => [issue.path, issue.message])).toEqual([ - [["list"], expect.stringMatching(/expected array/)], - ]); - }); - - test("a rule that throws on the raw value beside a failure keeps what it found first; without a failure the throw propagates", () => { - const throwing = z - .object({ flag: z.boolean().optional(), list: z.array(z.string()) }) - .superRefine((value, ctx) => { - if (value.flag === true) { - ctx.addIssue({ code: "custom", path: ["flag"], message: "flag found first" }); - } - value.list.map((item) => item.toLowerCase()); - throw new Error("rule bug"); - }); - const issues = loosen(throwing).safeParse({ flag: true, list: [1] }).error?.issues; - expect(issues?.map((issue) => [issue.path, issue.message])).toEqual([ - [["list", 0], expect.stringMatching(/expected string/)], - [["flag"], "flag found first"], - ]); - expect(() => loosen(throwing).safeParse({ list: ["ok"] })).toThrow(new Error("rule bug")); - }); - - test("a node refused as a whole does not run its own rules on the foreign value", () => { - let ran = false; - const watched = z.object({ name: z.string() }).superRefine(() => { - ran = true; - }); - const issues = loosen(watched).safeParse("not a mapping").error?.issues; - expect(issues?.map((issue) => issue.path)).toEqual([[]]); - expect(ran).toBe(false); - }); - - test("a check's own when predicate still decides: one answering false keeps its body uncalled", () => { - let ran = false; - const gated = z.check(() => { - ran = true; - }); - gated._zod.def.when = () => false; - const shape = z.object({ name: z.string() }).check(gated); - expect(loosen(shape).safeParse({ name: "a" }).success).toBe(true); - expect(loosen(shape).safeParse({ name: 1 }).success).toBe(false); - expect(ran).toBe(false); - }); - - test("a check composed onto the loosened shape reports beside a failure through checksReportingBesideFailures", () => { - const composed = loosen(z.array(z.object({ name: z.string() }))).superRefine((value, ctx) => { - if (Array.isArray(value) && value.length > 1) { - ctx.addIssue({ code: "custom", path: [1], message: "second entry" }); - } - }); - expect(composed.safeParse([{ name: 1 }, { name: "b" }]).error?.issues).toHaveLength(1); - const issues = checksReportingBesideFailures(composed).safeParse([{ name: 1 }, { name: "b" }]) - .error?.issues; - expect(issues?.map((issue) => issue.path)).toEqual([[0, "name"], [1]]); - }); - - test("a rule's own finding is not a failure: the list-level rule still runs over an entry with one", () => { - const list = z.array(pair).superRefine((entries, ctx) => { - if (entries.length > 1) { - ctx.addIssue({ code: "custom", message: "at most one entry" }); - } - }); - const issues = loosen(list).safeParse([{ list: ["x"] }, { mode: "a" }]).error?.issues; - expect(issues?.map((issue) => issue.message)).toEqual([ - "list needs mode a", - "at most one entry", - ]); - }); -}); diff --git a/test/sections/raw-sibling.test.ts b/test/sections/raw-sibling.test.ts index 67e5266b3..42e0640bf 100644 --- a/test/sections/raw-sibling.test.ts +++ b/test/sections/raw-sibling.test.ts @@ -1,17 +1,17 @@ /** - * A rule of a registered shape meets the raw value of a sibling that failed its type (reportingBesideFailures in - * src/sections/contract/module.ts), and a throw there is swallowed with the findings the rule had not reached. The - * walk takes the structure from the authored document schema (the loosened shape hides a knobbed list behind its - * routed transform), builds one well-typed value per section plus a variant per other value a field admits (so a - * rule gated on a flag or an option runs), then puts each raw value at every property and list item in turn and runs - * document validation, which parses the registered shape; the seam reports every swallowed throw. + * A rule of a registered shape meets the raw value of a sibling that failed its type (rule() in + * src/sections/shared/schema-helpers.ts), and a throw there is a bug that ends the parse. The walk takes the + * structure from the authored document schema (the loosened shape hides a knobbed list behind its routed transform), + * builds one well-typed value per section plus a variant per other value a field admits (so a rule gated on a flag + * or an option runs), then puts each raw value at every property and list item in turn and runs document + * validation, which parses the registered shape; a throw anywhere is the finding. */ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { z } from "zod"; import { validateSectionShapes } from "../../src/engine/validate.js"; import { SECTION_KEYS, type SectionKey, SettingsFile } from "../../src/schema.js"; -import { loosen, observeSwallowedThrows } from "../../src/sections/contract/module.js"; +import { rule } from "../../src/sections/shared/schema-helpers.js"; /** The zod internals the walk reads (the loosen() idiom). */ interface DefView { @@ -278,18 +278,40 @@ function basesOf(key: SectionKey): Base[] { ]; } +/** One line per throw, under the first base that reached it: the variants repeat a throw at the same path. */ +function throwsAcross(key: SectionKey, parse: (document: unknown) => void): string[] { + const thrown = new Map(); + for (const base of basesOf(key)) { + for (const path of pathsBelow(base.value)) { + for (const [where, document] of placements(base.value, path)) { + try { + parse(document); + } catch (error) { + const site = `${key}${where}: ${String(error)}`; + thrown.set(site, thrown.get(site) ?? `${site}${base.label}`); + } + } + } + } + return [...thrown.values()]; +} + describe("every rule of a registered shape tolerates a raw sibling", () => { - const swallowed: unknown[] = []; - beforeAll(() => observeSwallowedThrows((error) => swallowed.push(error))); - afterAll(() => observeSwallowedThrows(null)); + test("control: a rule that throws on a raw item beside the item's own issue ends the parse with the throw", () => { + const throwing = z.object({ list: z.array(z.string()) }).check( + rule((value) => { + value.list.map((item) => item.toLowerCase()); + }), + ); + expect(() => throwing.safeParse({ list: [1] })).toThrow(TypeError); + }); - test("control: the seam reports a rule that throws on a raw item beside the item's own issue", () => { - const throwing = z.object({ list: z.array(z.string()) }).superRefine((value) => { - value.list.map((item) => item.toLowerCase()); + test("control: the sweep records a throw from the parse it runs, naming the section and the site", () => { + const planted = throwsAcross("labels", () => { + throw new TypeError("planted"); }); - swallowed.length = 0; - expect(loosen(throwing).safeParse({ list: [1] }).success).toBe(false); - expect(swallowed.map((error) => (error as Error).constructor.name)).toEqual(["TypeError"]); + expect(planted.length).toBeGreaterThan(0); + expect(planted.every((line) => /^labels.*: TypeError: planted/.test(line))).toBe(true); }); test("control: the walk reaches a rule gated on a flag and a property left out", () => { @@ -307,20 +329,8 @@ describe("every rule of a registered shape tolerates a raw sibling", () => { }); test.each([...SECTION_KEYS])("%s: no rule throws with a raw value at any path", (key) => { - // One line per throw, under the first base that reached it: the variants repeat a throw at the same path. - const thrown = new Map(); - for (const base of basesOf(key)) { - for (const path of pathsBelow(base.value)) { - for (const [where, document] of placements(base.value, path)) { - swallowed.length = 0; - validateSectionShapes({ [key]: document }, "test"); - for (const error of swallowed) { - const site = `${key}${where}: ${String(error)}`; - thrown.set(site, thrown.get(site) ?? `${site}${base.label}`); - } - } - } - } - expect([...thrown.values()]).toEqual([]); + expect( + throwsAcross(key, (document) => validateSectionShapes({ [key]: document }, "test")), + ).toEqual([]); }); }); diff --git a/test/sections/rule.test.ts b/test/sections/rule.test.ts new file mode 100644 index 000000000..9c181eef2 --- /dev/null +++ b/test/sections/rule.test.ts @@ -0,0 +1,146 @@ +/** + * zod skips a node's own checks once a nested value failed; rule() (src/sections/shared/schema-helpers.ts) runs them + * through zod's public `when` and filters their findings. These pin that contract, which every section rule relies on + * and which a per-section test reaches through one document only; each control shows what zod does bare. + */ + +import { describe, expect, test } from "bun:test"; +import { z } from "zod"; +import { loosen } from "../../src/sections/contract/module.js"; +import { maxLength, minLength, rule } from "../../src/sections/shared/schema-helpers.js"; + +const needsModeA = ( + value: { mode?: "a" | "b"; list?: string[] }, + ctx: z.core.$RefinementCtx, +): void => { + if (value.list !== undefined && value.mode !== "a") { + ctx.addIssue({ code: "custom", path: ["list"], message: "list needs mode a" }); + } +}; + +const fields = { mode: z.enum(["a", "b"]).optional(), list: z.array(z.string()).optional() }; +const pair = z.object(fields).check(rule(needsModeA)); + +const report = (result: z.ZodSafeParseResult) => + result.error?.issues.map((issue) => [issue.path, issue.message]); + +describe("rule() reports beside a failed nested value", () => { + test("an object's own rule runs when a sibling property failed, and its finding keeps its path", () => { + expect(report(pair.safeParse({ mode: "c", list: ["x"] }))).toEqual([ + [["mode"], expect.stringMatching(/^Invalid option/)], + [["list"], "list needs mode a"], + ]); + // Control: the same rule bare is skipped, so a document with a second mistake would hide the first. + const bare = z.object(fields).superRefine(needsModeA); + expect(report(bare.safeParse({ mode: "c", list: ["x"] }))).toEqual([ + [["mode"], expect.stringMatching(/^Invalid option/)], + ]); + }); + + test("a rule's finding under the failed path is dropped: the shape's issue there is the report", () => { + const sweep = z.object({ list: z.array(z.string()) }).check( + rule((value, ctx) => { + for (const key of Object.keys(value.list)) { + ctx.addIssue({ code: "custom", path: ["list", key], message: "swept" }); + } + }), + ); + expect(report(sweep.safeParse({ list: "yes" }))).toEqual([ + [["list"], expect.stringMatching(/expected array/)], + ]); + }); + + test("a node refused as a whole does not run its own rule on the foreign value", () => { + let ran = false; + const watched = z.object({ name: z.string() }).check( + rule(() => { + ran = true; + }), + ); + expect(watched.safeParse("not a mapping").error?.issues.map((issue) => issue.path)).toEqual([ + [], + ]); + expect(ran).toBe(false); + }); + + test("a rule's own when is combined with the gate by AND: false keeps the body uncalled, true does not lift the gate", () => { + const calls: string[] = []; + const shape = z + .object({ name: z.string() }) + .check(rule(() => calls.push("never"), { when: () => false })) + .check(rule(() => calls.push("gated"), { when: () => true })); + expect(shape.safeParse({ name: "a" }).success).toBe(true); + expect(shape.safeParse({ name: 1 }).success).toBe(false); + expect(shape.safeParse("not a mapping").success).toBe(false); + expect(calls).toEqual(["gated", "gated"]); + }); + + test("a rule composed onto the loosened routed list shape reports beside a failed entry, in both container forms", () => { + const entry = z.object({ name: z.string() }); + const knob = z.union([ + z.array(entry), + z.strictObject({ + _undeclared: z.enum(["keep", "delete"]).optional(), + entries: z.array(entry), + }), + ]); + const composed = loosen(knob).check( + rule((value, ctx) => { + const wrapped = !Array.isArray(value); + const entries = wrapped ? (value as { entries: unknown[] }).entries : value; + if (entries.length > 1) { + ctx.addIssue({ + code: "custom", + path: [...(wrapped ? ["entries"] : []), 1], + message: "second entry", + }); + } + }), + ); + const paths = (document: unknown) => + composed.safeParse(document).error?.issues.map((issue) => issue.path); + expect(paths([{ name: 1 }, { name: "b" }])).toEqual([[0, "name"], [1]]); + expect(paths({ entries: [{ name: 1 }, { name: "b" }] })).toEqual([ + ["entries", 0, "name"], + ["entries", 1], + ]); + }); + + test("a rule's own finding is not a failure: the list-level rule still runs over an entry with one", () => { + const list = z.array(pair).check( + rule((entries, ctx) => { + if (entries.length > 1) { + ctx.addIssue({ code: "custom", message: "at most one entry" }); + } + }), + ); + expect( + list.safeParse([{ list: ["x"] }, { mode: "a" }]).error?.issues.map((issue) => issue.message), + ).toEqual(["list needs mode a", "at most one entry"]); + }); +}); + +describe("a gated length bound is skipped when the leaf's type failed", () => { + test("a raw list at a string leaf, and a raw string at a list leaf, each report one issue", () => { + const shape = z.object({ + delimiter: z.string().check(minLength(1, "empty delimiter")).optional(), + reviewers: z.array(z.string()).check(maxLength(1, "too many")).optional(), + }); + expect(report(shape.safeParse({ delimiter: [] }))).toEqual([ + [["delimiter"], expect.stringMatching(/expected string/)], + ]); + expect(report(shape.safeParse({ reviewers: "ab" }))).toEqual([ + [["reviewers"], expect.stringMatching(/expected array/)], + ]); + expect(report(shape.safeParse({ delimiter: "", reviewers: ["a", "b"] }))).toEqual([ + [["delimiter"], "empty delimiter"], + [["reviewers"], "too many"], + ]); + // Control: zod's own .min() runs on any value with a length, so bare it judges the raw list too. + const bare = z.object({ delimiter: z.string().min(1, "empty delimiter") }); + expect(report(bare.safeParse({ delimiter: [] }))).toEqual([ + [["delimiter"], expect.stringMatching(/expected string/)], + [["delimiter"], "empty delimiter"], + ]); + }); +});