diff --git a/TODO.md b/TODO.md index 9ae0204c26..1c30f50c28 100644 --- a/TODO.md +++ b/TODO.md @@ -477,3 +477,73 @@ its test, the `--preload` flag in both runners, and the "Fast Tests" note that documents the override. Confirm the suite's slow-test report (`SLOW_TEST_THRESHOLD_MS`) doesn't regress. Start points: `fast-expect.ts` for what it did and why, and grep `\.toContain(` under `test/` for the call sites. + +## Code-quality detector & test-strengthening follow-ups (from PR #1729) + +*Origin: CodeRabbit review of PR #1729, deferred as out of scope for that +complexity-only refactor (which had to preserve behavior). All of these are +pre-existing behaviors carried over unchanged from `main`, not regressions.* + +### 1. `skipTypeParams` should not treat the `>` in `=>` as a closing angle bracket + +`test/lib/code-quality/detectors.ts` — `skipTypeParams` counts every `>` as a +type-parameter close, so a type alias whose params contain an arrow default, +e.g. `type A void> = { ... }`, is parsed as ending at the arrow and +`parseTypeAliasBody` silently ignores the (valid) alias. The sibling helper +`angleDepthDelta` already handles this token correctly (it ignores a `>` +preceded by `=`). + +Fix direction: reuse `angleDepthDelta` in `skipTypeParams`. Note the naive +rewrite reintroduces an unreachable `return i` fall-through that fails the +repo's 100% line/branch coverage gate — so the fix must be paired with a +covering test that exercises an arrow-in-type-param alias (and keep the +fall-through on the covered path, as the current loop-with-`break` form does). + +### 2. `skipTemplateSubstitution` should skip comment contents + +`test/lib/code-quality/detectors.ts` — the template-substitution scanner tracks +brace depth but does not skip comments, so a `}` inside a comment inside a +`${...}` prematurely closes the substitution; a later nested backtick can then +end the outer template early and leak commas into `parseArgList`. Repro shape: +`` `${/* } */ `x,y`}` ``. + +Fix direction: within the depth loop, skip line/block comments (a `skipComment` +helper) before the brace-depth checks, and add a direct regression test for the +comment-with-`}`-then-nested-template case asserting `parseArgList` doesn't +misinterpret the comma. + +### 3. `foldOutcomeValid` should assert rejected folds preserve the prior quantity + +`test/lib/fold-tree.test.ts` — for the above-cap (rejected) case the validator +checks `recordedQty !== running`, which only proves the quantity wasn't clamped +to the attempted total; it doesn't prove the rejected fold left the *prior* +recorded quantity unchanged. + +Fix direction: capture the recorded quantity before calling `foldChild`, thread +it into `foldOutcomeValid`, and assert exact equality against that pre-fold +value for rejected outcomes (retaining the accepted-case checks). + +### 4. `mutation.ts` CLI value flags should fail fast on a missing value + +`scripts/mutation.ts` — in `applyArg`, a recognized value flag (`--source`, +`--test`, `--timeout`, `--jobs`) with no following token falls through and is +collected as a positional, so it surfaces later as a misleading glob/file error +instead of a clear CLI usage error. (Matches `main`'s original `next !== +undefined` guard behavior — pre-existing.) + +Fix direction: in `applyArg`, when `VALUE_FLAGS[arg]` exists but `next` is +`undefined`, raise a clear "missing value for " usage error rather than +pushing the flag to `positional`; keep consuming/returning true when a value is +present. + +### 5. Seeded PRNG `rand()` can return exactly 1 + +`test/lib/checkout-pricing-consistency.test.ts` — `makeRng`'s `rand` returns +`seed / 0x7fffffff`, which is `1` when `seed === 0x7fffffff`. That lets `pick` +index one past the array and `randInt` return `hi + 1`. Astronomically unlikely +for the fixed seeds in use (and identical to `main`), but incorrect. + +Fix direction: normalize with `seed / 0x80000000` (or clamp below 1). Note this +changes the seeded sequence, so re-baseline any hardcoded expectations and +confirm the property test still passes; best landed on its own so the corpus +shift is reviewed deliberately. diff --git a/biome.json b/biome.json index c4c2262875..a59de64079 100644 --- a/biome.json +++ b/biome.json @@ -76,12 +76,12 @@ "useTemplate": "error" }, "suspicious": { - "noAssignInExpressions": "off", + "noAssignInExpressions": "error", "noConsole": "error", "noDoubleEquals": "error", "noExplicitAny": "off", "noFocusedTests": "error", - "noImplicitAnyLet": "off", + "noImplicitAnyLet": "error", "noSkippedTests": "error", "noVar": "error" } @@ -92,14 +92,6 @@ "includes": ["test/**/*.js", "test/**/*.ts", "test/**/*.tsx"], "linter": { "rules": { - "complexity": { - "noExcessiveCognitiveComplexity": { - "level": "error", - "options": { - "maxAllowedComplexity": 30 - } - } - }, "correctness": { "noUnusedFunctionParameters": "off", "noUnusedVariables": "off" @@ -129,13 +121,8 @@ "includes": ["scripts/**/*.ts"], "linter": { "rules": { - "complexity": { - "noExcessiveCognitiveComplexity": "off" - }, "suspicious": { - "noAssignInExpressions": "off", - "noConsole": "off", - "noImplicitAnyLet": "off" + "noConsole": "off" } } } diff --git a/scripts/compact-test-reporter.ts b/scripts/compact-test-reporter.ts index 27adcb1163..f352fd9661 100644 --- a/scripts/compact-test-reporter.ts +++ b/scripts/compact-test-reporter.ts @@ -124,38 +124,68 @@ const readYamlBlockScalar = ( return stripCommonIndent(block).trimEnd(); }; -const parseYamlTapDiagnostic = (text: string): TapDiagnostic | undefined => { - const lines = text.split(/\r?\n/); - const diagnostic: TapDiagnostic = {}; - +const parseYamlMessage = (lines: string[]): string | undefined => { for (let index = 0; index < lines.length; index++) { const match = lines[index]?.match(/^(\s*)message:\s*(.*)$/); if (!match) continue; const value = match[2]?.trim() ?? ""; const baseIndent = (match[1] ?? "").length; - diagnostic.message = - value.startsWith("|") || value.startsWith(">") - ? readYamlBlockScalar(lines, index, baseIndent) - : parseYamlScalar(value); - break; + return value.startsWith("|") || value.startsWith(">") + ? readYamlBlockScalar(lines, index, baseIndent) + : parseYamlScalar(value); } + return undefined; +}; + +type AtFieldAssign = ( + at: NonNullable, + value: string, +) => void; +const AT_FIELD_ASSIGNERS: Record = { + column: (at, value) => { + at.column = Number(value); + }, + file: (at, value) => { + at.file = value; + }, + line: (at, value) => { + at.line = Number(value); + }, +}; + +const assignAtField = ( + at: NonNullable, + key: string, + value: string, +): void => { + AT_FIELD_ASSIGNERS[key]?.(at, value); +}; + +const parseYamlAt = (lines: string[]): TapDiagnostic["at"] | undefined => { const atIndex = lines.findIndex((line) => /^(\s*)at:\s*$/.test(line)); - if (atIndex !== -1) { - const atIndent = leadingWhitespaceLength(lines[atIndex] ?? ""); - const at: TapDiagnostic["at"] = {}; - for (const line of lines.slice(atIndex + 1)) { - if (line.trim() && leadingWhitespaceLength(line) <= atIndent) break; - const match = line.match(/^\s*(file|line|column):\s*(.*)$/); - if (!match) continue; - const key = match[1]; - const value = parseYamlScalar(match[2] ?? ""); - if (key === "file") at.file = value; - if (key === "line") at.line = Number(value); - if (key === "column") at.column = Number(value); - } - diagnostic.at = at; + if (atIndex === -1) return undefined; + + const atIndent = leadingWhitespaceLength(lines[atIndex] ?? ""); + const at: NonNullable = {}; + for (const line of lines.slice(atIndex + 1)) { + if (line.trim() && leadingWhitespaceLength(line) <= atIndent) break; + const match = line.match(/^\s*(file|line|column):\s*(.*)$/); + if (!match) continue; + assignAtField(at, match[1] ?? "", parseYamlScalar(match[2] ?? "")); } + return at; +}; + +const parseYamlTapDiagnostic = (text: string): TapDiagnostic | undefined => { + const lines = text.split(/\r?\n/); + const diagnostic: TapDiagnostic = {}; + + const message = parseYamlMessage(lines); + if (message !== undefined) diagnostic.message = message; + + const at = parseYamlAt(lines); + if (at !== undefined) diagnostic.at = at; return diagnostic.message || diagnostic.at ? diagnostic : undefined; }; diff --git a/scripts/mutation.ts b/scripts/mutation.ts index 9843066561..8704e808c5 100644 --- a/scripts/mutation.ts +++ b/scripts/mutation.ts @@ -60,40 +60,44 @@ interface ParsedArgs { useHarness: boolean; } -const parseArgs = (args: string[]): ParsedArgs => { - const parsed: ParsedArgs = { - error: null, - exhaustive: false, - help: false, - sources: [], - tests: [], - timeout: DEFAULT_TIMEOUT, - useHarness: false, - }; - const positional: string[] = []; - let index = 0; - while (index < args.length) { - const arg = args[index]; - const next = args[index + 1]; - if (arg === "--exhaustive") parsed.exhaustive = true; - else if (arg === "--harness") parsed.useHarness = true; - else if (arg === "-h" || arg === "--help") parsed.help = true; - else if (arg === "--source" && next !== undefined) { - parsed.sources.push(next); - index += 1; - } else if (arg === "--test" && next !== undefined) { - parsed.tests.push(next); - index += 1; - } else if (arg === "--timeout" && next !== undefined) { - parsed.timeout = Number(next); - index += 1; - } else if (arg === "--jobs" && next !== undefined) { - parsed.batchJobs = Number(next); - index += 1; - } else if (arg !== undefined) positional.push(arg); - index += 1; - } - if (parsed.sources.length > 0 || parsed.tests.length > 0) { +type ValueFlagApply = (parsed: ParsedArgs, value: string) => void; + +/** Options that take a value; maps the flag to how it records `next` on `parsed`. */ +const VALUE_FLAGS: Record = { + "--jobs": (parsed, value) => { + parsed.batchJobs = Number(value); + }, + "--source": (parsed, value) => parsed.sources.push(value), + "--test": (parsed, value) => parsed.tests.push(value), + "--timeout": (parsed, value) => { + parsed.timeout = Number(value); + }, +}; + +/** + * Apply a single argument to `parsed` (or collect it as positional). Returns + * true when it also consumed `next` as the flag's value. + */ +const applyArg = ( + parsed: ParsedArgs, + positional: string[], + arg: string, + next: string | undefined, +): boolean => { + if (arg === "--exhaustive") parsed.exhaustive = true; + else if (arg === "--harness") parsed.useHarness = true; + else if (arg === "-h" || arg === "--help") parsed.help = true; + else if (VALUE_FLAGS[arg] !== undefined && next !== undefined) { + VALUE_FLAGS[arg]?.(parsed, next); + return true; + } else positional.push(arg); + return false; +}; + +/** Fold positional arguments into `parsed`, recording an error on misuse. */ +const applyPositionals = (parsed: ParsedArgs, positional: string[]): void => { + const usedFlagForm = parsed.sources.length > 0 || parsed.tests.length > 0; + if (usedFlagForm) { // Flag-form was used: positionals are not part of the grammar. Any leftover // means a glob expanded past the single value --source/--test consumed // (e.g. `--source src/*.ts` → src/a.ts src/b.ts …), which would silently @@ -105,26 +109,54 @@ const parseArgs = (args: string[]): ParsedArgs => { "A glob likely expanded to multiple files — quote it " + `(e.g. --source 'src/lib/forms/*.ts') or pass repeated --source/--test flags.`; } - } else { - if (positional[0] !== undefined) parsed.sources.push(positional[0]); - if (positional[1] !== undefined) parsed.tests.push(positional[1]); - if (positional.length > 2) { - parsed.error = - `Too many positional arguments (${positional.length}). Quote your globs ` + - `so the shell can't expand them — e.g. 'src/lib/forms/*.ts' ` + - `'test/lib/forms/*.test.ts' — or pass repeated --source/--test flags.`; - } + return; + } + if (positional[0] !== undefined) parsed.sources.push(positional[0]); + if (positional[1] !== undefined) parsed.tests.push(positional[1]); + if (positional.length > 2) { + parsed.error = + `Too many positional arguments (${positional.length}). Quote your globs ` + + `so the shell can't expand them — e.g. 'src/lib/forms/*.ts' ` + + `'test/lib/forms/*.test.ts' — or pass repeated --source/--test flags.`; } +}; + +/** Validate the parsed numeric options, recording the first error found. */ +const validateNumericArgs = (parsed: ParsedArgs): void => { if (!Number.isFinite(parsed.timeout) || parsed.timeout < 0) { parsed.error ??= "Invalid --timeout: expected a non-negative number of milliseconds."; } - if ( + const invalidJobs = parsed.batchJobs !== undefined && - (!Number.isInteger(parsed.batchJobs) || parsed.batchJobs <= 0) - ) { + (!Number.isInteger(parsed.batchJobs) || parsed.batchJobs <= 0); + if (invalidJobs) { parsed.error ??= "Invalid --jobs: expected a positive integer."; } +}; + +const parseArgs = (args: string[]): ParsedArgs => { + const parsed: ParsedArgs = { + error: null, + exhaustive: false, + help: false, + sources: [], + tests: [], + timeout: DEFAULT_TIMEOUT, + useHarness: false, + }; + const positional: string[] = []; + let index = 0; + while (index < args.length) { + const arg = args[index]; + if (arg !== undefined) { + const consumedNext = applyArg(parsed, positional, arg, args[index + 1]); + if (consumedNext) index += 1; + } + index += 1; + } + applyPositionals(parsed, positional); + validateNumericArgs(parsed); return parsed; }; diff --git a/scripts/mutation/isolation.ts b/scripts/mutation/isolation.ts index 16879eeb4d..f28655ffd2 100644 --- a/scripts/mutation/isolation.ts +++ b/scripts/mutation/isolation.ts @@ -149,6 +149,27 @@ const childArgs = ( ...rewriteMutationArgs(root, snapshotRoot, args), ]; +const forceStopChild = (child: Deno.ChildProcess | null): never => { + if (child) stopProcessNow(child); + Deno.exit(130); +}; + +const killChildQuietly = (child: Deno.ChildProcess | null): void => { + if (!child) return; + try { + child.kill(); + } catch { + // It may already have exited. + } +}; + +const settleRecord = ( + record: MutationRunRecord, + interrupted: boolean, + code: number, +): MutationRunRecord => + interrupted ? markInterrupted(record) : markFinished(record, code); + export const runMutationInSnapshot = async ( args: string[], root = projectRoot, @@ -160,18 +181,9 @@ export const runMutationInSnapshot = async ( let child: Deno.ChildProcess | null = null; let interrupted = false; const stopChild = (): void => { - if (interrupted) { - if (child) stopProcessNow(child); - Deno.exit(130); - } + if (interrupted) forceStopChild(child); interrupted = true; - if (child) { - try { - child.kill(); - } catch { - // It may already have exited. - } - } + killChildQuietly(child); }; onTerminationSignals(stopChild); @@ -205,18 +217,14 @@ export const runMutationInSnapshot = async ( if (child !== null) { const status = await child.status; - record = interrupted - ? markInterrupted(record) - : markFinished(record, status.code); + record = settleRecord(record, interrupted, status.code); await writeRunRecord(record); exitCode = interrupted ? 130 : status.code; } } catch (error) { if (child !== null) await stopProcess(child, 250); exitCode = interrupted ? 130 : 1; - record = interrupted - ? markInterrupted(record) - : markFinished(record, exitCode); + record = settleRecord(record, interrupted, exitCode); try { await writeRunRecord(record); } catch { diff --git a/scripts/mutation/runner.ts b/scripts/mutation/runner.ts index 22a51df6f8..f948955297 100644 --- a/scripts/mutation/runner.ts +++ b/scripts/mutation/runner.ts @@ -363,23 +363,15 @@ interface RunMutantsOptions { useHarness: boolean; } -/** Baseline check, then the per-file/per-mutant loop, then the report. */ -const runMutants = async (opts: RunMutantsOptions): Promise => { - const { - abortSignal, - batchJobs, - exhaustive, - ignoreList, - isAborted, - originals, - restoreAll, - results, - sourceFiles, - testFiles, - timeout, - useHarness, - } = opts; - +/** + * Run the baseline (unmutated) tests. Returns `{ code }` when the run should + * stop early (interrupted, or a non-green baseline), or the derived + * `{ perMutantTimeout }` when the baseline passed and mutation can proceed. + */ +const establishBaseline = async ( + opts: RunMutantsOptions, +): Promise<{ code: number } | { perMutantTimeout: number }> => { + const { abortSignal, batchJobs, isAborted, testFiles, timeout } = opts; console.log(dim("Running baseline (unmutated) tests…")); const baseline = await runTests( testFiles, @@ -387,7 +379,7 @@ const runMutants = async (opts: RunMutantsOptions): Promise => { batchJobs, abortSignal, ); - if (isAborted()) return 130; + if (isAborted()) return { code: 130 }; if (baseline.outcome !== "passed") { console.error(red(`\nBaseline tests did not pass (${baseline.outcome}).`)); console.error( @@ -396,7 +388,7 @@ const runMutants = async (opts: RunMutantsOptions): Promise => { console.error( "if these tests import the app / Stripe and need stripe-mock + built assets.", ); - return 1; + return { code: 1 }; } const perMutantTimeout = Math.max( timeout, @@ -408,6 +400,171 @@ const runMutants = async (opts: RunMutantsOptions): Promise => { ), ); console.log(dim(`Using up to ${batchJobs} concurrent test batch(es).`)); + return { perMutantTimeout }; +}; + +/** + * Probe that the *unmutated* target lints clean before its mutants run, and + * report loudly if not. The lint gate can only tell a mutation-introduced + * diagnostic apart from a broken Biome or an already-dirty target if the + * unmutated file lints clean. The file on disk is the original here (restored + * after every mutant), so probe it once per file. A non-zero exit means the + * gate can't be trusted — precommit runs `lint:ci` before mutation, but a + * standalone `deno task mutation` does not — so the caller aborts rather than + * record every mutant as a bogus lint-kill. Probing the target itself (not a + * fixed path) also means a run that mutates this very file never reprobes a + * path that is currently holding a mutant. + */ +const isUnmutatedTargetDirty = async ( + plan: FileMutationPlan, + lint: MutantLinter, +): Promise => { + if (plan.mutants.length === 0) return false; + if ((await lint.exit(plan.file)) === 0) return false; + console.error(red(`\nThe unmutated ${rel(plan.file)} does not lint clean.`)); + console.error( + "The mutation lint gate needs a lint-clean target and a working Biome.", + ); + console.error( + "Run `deno task lint` and fix any errors (precommit runs lint:ci first;", + ); + console.error("a standalone `deno task mutation` does not), then retry."); + return true; +}; + +/** Print the running progress line for a mutant, on the cadence the loop uses. */ +const reportMutantProgress = ( + last: MutantResult, + counts: Record, + completed: number, + total: number, +): void => { + if ( + completed % PROGRESS_INTERVAL !== 0 && + completed !== total && + last.status === "killed" + ) { + return; + } + write("\n"); + console.log( + formatProgressLine({ + completed, + ignored: counts.ignored, + killed: counts.killed, + last, + survived: counts.survived, + timedOut: counts["timed-out"], + total, + }), + ); +}; + +interface MutantLoopContext { + counts: Record; + lint: MutantLinter; + perMutantTimeout: number; + totalMutants: number; +} + +/** Evaluate every mutant for one file plan, recording results and progress. */ +const evaluatePlanMutants = async ( + plan: FileMutationPlan, + opts: RunMutantsOptions, + ctx: MutantLoopContext, +): Promise => { + const { counts, lint, perMutantTimeout, totalMutants } = ctx; + const { + abortSignal, + batchJobs, + ignoreList, + isAborted, + originals, + results, + testFiles, + } = opts; + for (const mutant of plan.mutants) { + if (isAborted()) break; + originals.set(plan.file, plan.original); + const outcome = await evaluateMutant( + plan.file, + plan.original, + mutant, + testFiles, + perMutantTimeout, + batchJobs, + plan.assets, + lint, + abortSignal, + ); + originals.delete(plan.file); + if (isAborted()) break; + // A survivor recorded as known-equivalent is suppressed, not a failure. + const status: Status = + outcome === "survived" && isIgnored(ignoreList, plan.file, mutant) + ? "ignored" + : outcome; + const result = { file: plan.file, mutant, status }; + results.push(result); + counts[status] += 1; + write(statusGlyph(status)); + reportMutantProgress(result, counts, results.length, totalMutants); + } +}; + +/** + * Re-check the ignore-list against the run's results and report any stale + * entries, returning the final exit code. The ignore-list is location-based, so + * it drifts as code moves. Re-check it here — only for the files just mutated — + * and fail if any entry no longer lines up with a real survivor, so it gets + * fixed instead of rotting. Staleness is checked against every mutant + * --exhaustive could produce (regardless of the mode this run used), so an + * entry for an exhaustive-only replacement isn't falsely flagged during a + * non-exhaustive (e.g. precommit) run. + */ +const reportIgnoreListStaleness = ( + opts: RunMutantsOptions, + plans: FileMutationPlan[], + exitCode: number, +): number => { + const possibleKeys = new Set( + plans.flatMap((plan) => + generateMutants(plan.original, plan.file, true).map((mutant) => + mutantKey(plan.file, mutant), + ), + ), + ); + const problems = ignoreListProblems( + opts.ignoreList, + opts.results, + opts.sourceFiles, + possibleKeys, + ); + if (problems.length === 0) return exitCode; + console.error( + yellow("\nIgnore-list issues (scripts/mutation/equivalent-mutants.txt):"), + ); + for (const problem of problems) console.error(red(` ✗ ${problem}`)); + console.error( + dim(" Update or remove these so the list stays in sync with reality."), + ); + return exitCode === 0 ? 1 : exitCode; +}; + +/** Baseline check, then the per-file/per-mutant loop, then the report. */ +const runMutants = async (opts: RunMutantsOptions): Promise => { + const { + exhaustive, + isAborted, + restoreAll, + results, + sourceFiles, + useHarness, + } = opts; + + const baseline = await establishBaseline(opts); + if ("code" in baseline) return baseline.code; + const { perMutantTimeout } = baseline; // Under --harness the client bundles are built once; a mutant on a bundled // source must rebuild the affected bundle(s) or it would falsely survive. @@ -437,74 +594,13 @@ const runMutants = async (opts: RunMutantsOptions): Promise => { for (const plan of plans) { if (isAborted()) break; - // The lint gate can only tell a mutation-introduced diagnostic apart from - // a broken Biome or an already-dirty target if the *unmutated* file lints - // clean. The file on disk is the original here (restored after every - // mutant), so probe it once per file. A non-zero exit means the gate - // can't be trusted — precommit runs `lint:ci` before mutation, but a - // standalone `deno task mutation` does not — so abort loudly rather than - // record every mutant as a bogus lint-kill. Probing the target itself - // (not a fixed path) also means a run that mutates this very file never - // reprobes a path that is currently holding a mutant. - if (plan.mutants.length > 0 && (await lint.exit(plan.file)) !== 0) { - console.error( - red(`\nThe unmutated ${rel(plan.file)} does not lint clean.`), - ); - console.error( - "The mutation lint gate needs a lint-clean target and a working Biome.", - ); - console.error( - "Run `deno task lint` and fix any errors (precommit runs lint:ci first;", - ); - console.error( - "a standalone `deno task mutation` does not), then retry.", - ); - return 1; - } - for (const mutant of plan.mutants) { - if (isAborted()) break; - originals.set(plan.file, plan.original); - const outcome = await evaluateMutant( - plan.file, - plan.original, - mutant, - testFiles, - perMutantTimeout, - batchJobs, - plan.assets, - lint, - abortSignal, - ); - originals.delete(plan.file); - if (isAborted()) break; - // A survivor recorded as known-equivalent is suppressed, not a failure. - const status: Status = - outcome === "survived" && isIgnored(ignoreList, plan.file, mutant) - ? "ignored" - : outcome; - const result = { file: plan.file, mutant, status }; - results.push(result); - counts[status] += 1; - write(statusGlyph(status)); - if ( - results.length % PROGRESS_INTERVAL === 0 || - results.length === totalMutants || - status !== "killed" - ) { - write("\n"); - console.log( - formatProgressLine({ - completed: results.length, - ignored: counts.ignored, - killed: counts.killed, - last: result, - survived: counts.survived, - timedOut: counts["timed-out"], - total: totalMutants, - }), - ); - } - } + if (await isUnmutatedTargetDirty(plan, lint)) return 1; + await evaluatePlanMutants(plan, opts, { + counts, + lint, + perMutantTimeout, + totalMutants, + }); } } finally { restoreAll(); @@ -517,36 +613,7 @@ const runMutants = async (opts: RunMutantsOptions): Promise => { return 130; } - const exitCode = report(results); - // The ignore-list is location-based, so it drifts as code moves. Re-check it - // here — only for the files just mutated — and fail if any entry no longer - // lines up with a real survivor, so it gets fixed instead of rotting. - // Staleness is checked against every mutant --exhaustive could produce - // (regardless of the mode this run used), so an entry for an - // exhaustive-only replacement isn't falsely flagged during a non-exhaustive - // (e.g. precommit) run. - const possibleKeys = new Set( - plans.flatMap((plan) => - generateMutants(plan.original, plan.file, true).map((mutant) => - mutantKey(plan.file, mutant), - ), - ), - ); - const problems = ignoreListProblems( - ignoreList, - results, - sourceFiles, - possibleKeys, - ); - if (problems.length === 0) return exitCode; - console.error( - yellow("\nIgnore-list issues (scripts/mutation/equivalent-mutants.txt):"), - ); - for (const problem of problems) console.error(red(` ✗ ${problem}`)); - console.error( - dim(" Update or remove these so the list stays in sync with reality."), - ); - return exitCode === 0 ? 1 : exitCode; + return reportIgnoreListStaleness(opts, plans, report(results)); }; const mutate = async (options: MutationOptions): Promise => { diff --git a/scripts/safe-upgrade.ts b/scripts/safe-upgrade.ts index a60709c9b2..164baa35df 100644 --- a/scripts/safe-upgrade.ts +++ b/scripts/safe-upgrade.ts @@ -112,6 +112,39 @@ async function fetchJsrVersions( return versions; } +/** + * Split an "npm:"/"jsr:" specifier into its package name and version range. + * Returns an error string when the specifier is malformed or unrecognized. + */ +function parsePackageSpecifier( + specifier: string, +): { pkgName: string; versionRange: string } | { error: string } { + if (!specifier.startsWith("npm:") && !specifier.startsWith("jsr:")) { + return { error: "unknown registry" }; + } + const withoutPrefix = specifier.slice(4); + const atIdx = withoutPrefix.lastIndexOf("@"); + if (atIdx <= 0) { + return { error: "no version specifier found" }; + } + return { + pkgName: withoutPrefix.slice(0, atIdx), + versionRange: withoutPrefix.slice(atIdx + 1), + }; +} + +/** Fetch all stable versions for a package from its registry. */ +function fetchVersionsFor( + registry: "npm" | "jsr", + pkgName: string, +): Promise { + if (registry === "npm") { + return fetchNpmVersions(pkgName); + } + const [scope, name] = pkgName.replace("@", "").split("/"); + return fetchJsrVersions(scope, name); +} + async function checkUpgrade( name: string, specifier: string, @@ -129,24 +162,12 @@ async function checkUpgrade( }; try { - let pkgName: string; - let versionRange: string; - - // npm: and jsr: share the same `@scope/name@version` / `name@version` - // shape after their (equal-length) prefix, so both parse identically. - if (specifier.startsWith("npm:") || specifier.startsWith("jsr:")) { - const withoutPrefix = specifier.slice(4); - const atIdx = withoutPrefix.lastIndexOf("@"); - if (atIdx <= 0) { - result.error = "no version specifier found"; - return result; - } - pkgName = withoutPrefix.slice(0, atIdx); - versionRange = withoutPrefix.slice(atIdx + 1); - } else { - result.error = "unknown registry"; + const parsedSpecifier = parsePackageSpecifier(specifier); + if ("error" in parsedSpecifier) { + result.error = parsedSpecifier.error; return result; } + const { pkgName, versionRange } = parsedSpecifier; const parsed = parseVersionSpec(versionRange); if (!parsed) { @@ -155,13 +176,7 @@ async function checkUpgrade( } result.currentVersion = parsed.version; - let allVersions: VersionInfo[]; - if (result.registry === "npm") { - allVersions = await fetchNpmVersions(pkgName); - } else { - const [scope, name] = pkgName.replace("@", "").split("/"); - allVersions = await fetchJsrVersions(scope, name); - } + const allVersions = await fetchVersionsFor(result.registry, pkgName); // Sort all stable versions descending — no semver range filtering, // we want the latest version overall (like `deno outdated --update --latest`) @@ -232,60 +247,71 @@ async function main() { (r) => r.newVersion === null && r.error === null, ); - // Print results - if (upToDate.length > 0) { - console.log(`Up to date (${upToDate.length}):`); - for (const r of upToDate) { - console.log(` ${r.name} @ ${r.currentVersion}`); - } - console.log(""); + printUpToDate(upToDate); + printUpgrades(upgrades, minAgeDays); + printErrors(errors); + + if (upgrades.length === 0) { + console.log("Everything is up to date!"); + } else if (!dryRun) { + await applyUpgrades(upgrades); } +} - if (upgrades.length > 0) { - console.log(`Upgrades available (${upgrades.length}):`); - for (const r of upgrades) { - const age = Math.floor( - (Date.now() - r.newPublishedAt!.getTime()) / (1000 * 60 * 60 * 24), - ); +function printUpToDate(upToDate: UpgradeResult[]): void { + if (upToDate.length === 0) return; + console.log(`Up to date (${upToDate.length}):`); + for (const r of upToDate) { + console.log(` ${r.name} @ ${r.currentVersion}`); + } + console.log(""); +} + +function printUpgrades(upgrades: UpgradeResult[], minAgeDays: number): void { + if (upgrades.length === 0) return; + console.log(`Upgrades available (${upgrades.length}):`); + for (const r of upgrades) { + // checkUpgrade sets newPublishedAt alongside newVersion, and callers filter + // `upgrades` on newVersion !== null, so newPublishedAt is guaranteed present. + const age = Math.floor( + (Date.now() - r.newPublishedAt!.getTime()) / (1000 * 60 * 60 * 24), + ); + console.log( + ` ${r.name}: ${r.currentVersion} -> ${r.newVersion} (${age} days old)`, + ); + if (r.skippedNewer) { console.log( - ` ${r.name}: ${r.currentVersion} -> ${r.newVersion} (${age} days old)`, + ` ⚠ skipped ${r.skippedNewer} (too recent, < ${minAgeDays} days)`, ); - if (r.skippedNewer) { - console.log( - ` ⚠ skipped ${r.skippedNewer} (too recent, < ${minAgeDays} days)`, - ); - } } - console.log(""); } + console.log(""); +} - if (errors.length > 0) { - console.log(`Errors (${errors.length}):`); - for (const r of errors) { - console.log(` ${r.name}: ${r.error}`); - } - console.log(""); +function printErrors(errors: UpgradeResult[]): void { + if (errors.length === 0) return; + console.log(`Errors (${errors.length}):`); + for (const r of errors) { + console.log(` ${r.name}: ${r.error}`); } + console.log(""); +} - // Apply upgrades - if (upgrades.length > 0 && !dryRun) { - let denoJsonText = await Deno.readTextFile(DENO_JSON_PATH); - for (const r of upgrades) { - // Replace the full specifier, updating to ^newVersion - const oldSpec = r.currentSpec; - const versionPart = oldSpec.slice(oldSpec.lastIndexOf("@") + 1); - const newSpec = oldSpec.replace(versionPart, `^${r.newVersion}`); - denoJsonText = denoJsonText.replace( - JSON.stringify(oldSpec), - JSON.stringify(newSpec), - ); - } - await Deno.writeTextFile(DENO_JSON_PATH, denoJsonText); - console.log(`Updated deno.json with ${upgrades.length} upgrade(s)`); - console.log("Run 'deno task precommit' to verify everything still works"); - } else if (upgrades.length === 0) { - console.log("Everything is up to date!"); +async function applyUpgrades(upgrades: UpgradeResult[]): Promise { + let denoJsonText = await Deno.readTextFile(DENO_JSON_PATH); + for (const r of upgrades) { + // Replace the full specifier, updating to ^newVersion + const oldSpec = r.currentSpec; + const versionPart = oldSpec.slice(oldSpec.lastIndexOf("@") + 1); + const newSpec = oldSpec.replace(versionPart, `^${r.newVersion}`); + denoJsonText = denoJsonText.replace( + JSON.stringify(oldSpec), + JSON.stringify(newSpec), + ); } + await Deno.writeTextFile(DENO_JSON_PATH, denoJsonText); + console.log(`Updated deno.json with ${upgrades.length} upgrade(s)`); + console.log("Run 'deno task precommit' to verify everything still works"); } main(); diff --git a/scripts/stripe-mock.ts b/scripts/stripe-mock.ts index 3209fba139..82330352e2 100644 --- a/scripts/stripe-mock.ts +++ b/scripts/stripe-mock.ts @@ -244,49 +244,86 @@ const withStripeMockStartLock = async ( } }; -const startStripeMockProcess = async ( +const resolveStripeMockPort = ( + options: StartStripeMockOptions, + env: StripeMockEnvSource, +): number => { + const choosePort = options.choosePort ?? chooseStripeMockPort; + return options.port ?? choosePort(env); +}; + +const confirmOwnedStripeMock = ( + options: StartStripeMockOptions, + port: number, + spawned: SpawnedStripeMock, +): Promise => + waitForOwnedStripeMock( + spawned.process, + port, + options.maxAttempts ?? 100, + options.delayMs ?? 100, + options.confirmDelayMs ?? START_CONFIRM_DELAY_MS, + ); + +type StripeMockStartAttempt = + | { readonly kind: "running"; readonly mock: RunningStripeMock } + | { readonly kind: "retry"; readonly error: string }; + +const attemptStartStripeMock = async ( options: StartStripeMockOptions, env: StripeMockEnvSource, paths: StripeMockPaths, configuredPort: boolean, - startAttempts: number, -): Promise => { - let lastStartupError = ""; +): Promise => { + const port = resolveStripeMockPort(options, env); - for (let attempt = 0; attempt < startAttempts; attempt++) { - const choosePort = options.choosePort ?? chooseStripeMockPort; - const port = options.port ?? choosePort(env); - if (await isStripeMockRunning(port)) { - if (configuredPort) return alreadyRunningStripeMock(port); - continue; - } + if (await isStripeMockRunning(port)) { + return configuredPort + ? { kind: "running", mock: alreadyRunningStripeMock(port) } + : { error: "", kind: "retry" }; + } - if (configuredPort) await downloadStripeMock(options); + if (configuredPort) await downloadStripeMock(options); - const spawned = spawnStripeMock(paths, port); + const spawned = spawnStripeMock(paths, port); + const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS; - if ( - await waitForOwnedStripeMock( - spawned.process, - port, - options.maxAttempts ?? 100, - options.delayMs ?? 100, - options.confirmDelayMs ?? START_CONFIRM_DELAY_MS, - ) - ) { - return managedStripeMock( + if (await confirmOwnedStripeMock(options, port, spawned)) { + return { + kind: "running", + mock: managedStripeMock( port, spawned.process, - options.stopTimeoutMs ?? STOP_TIMEOUT_MS, + stopTimeoutMs, spawned.closeStderr, - ); - } + ), + }; + } + + await stopProcess(spawned.process, stopTimeoutMs); + return { error: await spawned.stderr(), kind: "retry" }; +}; + +const startStripeMockProcess = async ( + options: StartStripeMockOptions, + env: StripeMockEnvSource, + paths: StripeMockPaths, + configuredPort: boolean, + startAttempts: number, +): Promise => { + let lastStartupError = ""; - await stopProcess( - spawned.process, - options.stopTimeoutMs ?? STOP_TIMEOUT_MS, + for (let attempt = 0; attempt < startAttempts; attempt++) { + const result = await attemptStartStripeMock( + options, + env, + paths, + configuredPort, ); - lastStartupError = await spawned.stderr(); + if (result.kind === "running") return result.mock; + // Keep the first meaningful stderr: a later retry can return an empty error + // that would otherwise clobber the useful failure context. + if (result.error) lastStartupError = result.error; } throw new Error( diff --git a/src/features/admin/index.ts b/src/features/admin/index.ts index c9fab4814c..44847c8376 100644 --- a/src/features/admin/index.ts +++ b/src/features/admin/index.ts @@ -267,7 +267,9 @@ const buildSegmentRouters = (): Record< const areasBySegment: Record = {}; for (const adminArea of Object.values(ADMIN_AREAS)) { for (const segment of adminArea.segments) { - (areasBySegment[segment] ??= []).push(adminArea); + const list = areasBySegment[segment] ?? []; + list.push(adminArea); + areasBySegment[segment] = list; } } const routers: Record Promise> = {}; diff --git a/src/features/api/payment-processing/index.ts b/src/features/api/payment-processing/index.ts index b81c2158bf..452798d6ef 100644 --- a/src/features/api/payment-processing/index.ts +++ b/src/features/api/payment-processing/index.ts @@ -298,7 +298,7 @@ const processReservedSession: SessionProcessor = async ( // booking at quantity 0 and refunds rather than dropping a paid customer: a // structured sold-out/capacity/encryption result, OR an unexpected throw after // the charge (which would otherwise crash-loop the webhook over paid money). - let honoured; + let honoured: Awaited>; try { honoured = await createAttendeeForSession( session, diff --git a/src/features/public/ticket-form.ts b/src/features/public/ticket-form.ts index c098cdf37e..9fc630b3ad 100644 --- a/src/features/public/ticket-form.ts +++ b/src/features/public/ticket-form.ts @@ -58,7 +58,10 @@ const pushToListings = ( selectedListingIds, )) { if (!selectedListingIds.has(listingId)) continue; - (result[String(listingId)] ??= []).push(value); + const key = String(listingId); + const list = result[key] ?? []; + list.push(value); + result[key] = list; } }; diff --git a/src/ui/client/admin/markdown-preview.ts b/src/ui/client/admin/markdown-preview.ts index d6ebe6b1a7..8cb5ed51d8 100644 --- a/src/ui/client/admin/markdown-preview.ts +++ b/src/ui/client/admin/markdown-preview.ts @@ -79,7 +79,8 @@ export const initMarkdownPreview = (): void => { const requestPreview = async ( textarea: HTMLTextAreaElement, ): Promise => { - const d = (dialog ??= createDialog()); + dialog ??= createDialog(); + const d = dialog; d.setLoading(); d.open(); try { diff --git a/src/ui/client/order.ts b/src/ui/client/order.ts index 2cd279cbfe..c460242631 100644 --- a/src/ui/client/order.ts +++ b/src/ui/client/order.ts @@ -447,7 +447,8 @@ const init = (): void => { string, Record >; - const registry = (global[REGISTRY_KEY] ??= {}); + const registry = global[REGISTRY_KEY] ?? {}; + global[REGISTRY_KEY] = registry; if (registry[CATALOG.origin]) { debugLog("already initialised for", CATALOG.origin); return; diff --git a/test/lib/checkout-pricing-consistency.test.ts b/test/lib/checkout-pricing-consistency.test.ts index 32dd9e0951..4f94e0bfc1 100644 --- a/test/lib/checkout-pricing-consistency.test.ts +++ b/test/lib/checkout-pricing-consistency.test.ts @@ -106,6 +106,79 @@ const expectConsistent = async ( expect(web.modifierApplications).toEqual(pub.modifierApplications); }; +/** A repeatable PRNG bundle so a failing property iteration is reproducible + * from its seed. */ +type Rng = { + rand: () => number; + pick: (xs: readonly T[]) => T; + randInt: (lo: number, hi: number) => number; +}; + +const makeRng = (initialSeed: number): Rng => { + let seed = initialSeed; + const rand = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; + }; + const pick = (xs: readonly T[]): T => xs[Math.floor(rand() * xs.length)]!; + const randInt = (lo: number, hi: number) => + lo + Math.floor(rand() * (hi - lo + 1)); + return { pick, rand, randInt }; +}; + +/** A random 1-3 item cart with distinct listings and per-unit prices. */ +const randomItems = (rng: Rng): CheckoutItem[] => + Array.from({ length: rng.randInt(1, 3) }, (_, i) => + checkoutItem({ + listingId: i + 1, + quantity: rng.randInt(1, 3), + slug: `gen-${i}`, + unitPrice: rng.randInt(10, 60) * 100, + }), + ); + +/** A random calc value in the range appropriate for the given calc kind. */ +const randomCalcValue = ( + kind: "fixed" | "percent" | "multiply", + rng: Rng, +): number => { + if (kind === "multiply") return rng.pick([1.25, 1.5, 2]); + if (kind === "percent") return rng.randInt(5, 25); + return rng.randInt(1, 5); +}; + +/** Insert a random modifier set for one property iteration, returning the + * optional-trigger add-on quantities and any promo code that was assigned. */ +const generateModifiers = async ( + rng: Rng, + iter: number, +): Promise<{ addOns: Map; code: string | undefined }> => { + const addOns = new Map(); + let code: string | undefined; + for (let m = 0; m < rng.randInt(0, 4); m++) { + const kind = rng.pick(["fixed", "percent", "multiply"] as const); + const inserted = await insertModifier({ + calcKind: kind, + calcValue: randomCalcValue(kind, rng), + direction: rng.pick(["charge", "discount"] as const), + name: `gen-${iter}-${m}`, + stock: rng.pick([null, 5]), + }); + const trigger = rng.pick(["automatic", "optional", "code"] as const); + const patch: Record = { + min_visits: rng.pick([0, 0, 1]), + trigger, + }; + if (trigger === "optional") addOns.set(inserted.id, rng.randInt(1, 3)); + if (trigger === "code") { + code = "PROMO"; + patch.code_index = await hmacHash(normalizeCode("PROMO")); + } + await patchModifier(inserted.id, patch); + } + return { addOns, code }; +}; + const parkingFixedSurchargeExpectConsistent = async ( opts: { ctx?: { visits: number }; overrides?: Partial } = {}, ): Promise => { @@ -368,14 +441,7 @@ describeWithEnv( test("property: random modifier mixes re-price identically on both paths", async () => { // A repeatable PRNG so a failure is reproducible from the seed. - let seed = 0x5eed1234; - const rand = () => { - seed = (seed * 1103515245 + 12345) & 0x7fffffff; - return seed / 0x7fffffff; - }; - const pick = (xs: T[]): T => xs[Math.floor(rand() * xs.length)]!; - const randInt = (lo: number, hi: number) => - lo + Math.floor(rand() * (hi - lo + 1)); + const rng = makeRng(0x5eed1234); const db = getDb(); for (let iter = 0; iter < 40; iter++) { @@ -383,45 +449,10 @@ describeWithEnv( await db.execute("DELETE FROM modifier_usages"); await db.execute("DELETE FROM modifiers"); - const items = Array.from({ length: randInt(1, 3) }, (_, i) => - checkoutItem({ - listingId: i + 1, - quantity: randInt(1, 3), - slug: `gen-${i}`, - unitPrice: randInt(10, 60) * 100, - }), - ); - - const addOns = new Map(); - let code: string | undefined; - for (let m = 0; m < randInt(0, 4); m++) { - const kind = pick(["fixed", "percent", "multiply"] as const); - const inserted = await insertModifier({ - calcKind: kind, - calcValue: - kind === "multiply" - ? pick([1.25, 1.5, 2]) - : kind === "percent" - ? randInt(5, 25) - : randInt(1, 5), - direction: pick(["charge", "discount"] as const), - name: `gen-${iter}-${m}`, - stock: pick([null, 5]), - }); - const trigger = pick(["automatic", "optional", "code"] as const); - const patch: Record = { - min_visits: pick([0, 0, 1]), - trigger, - }; - if (trigger === "optional") addOns.set(inserted.id, randInt(1, 3)); - if (trigger === "code") { - code = "PROMO"; - patch.code_index = await hmacHash(normalizeCode("PROMO")); - } - await patchModifier(inserted.id, patch); - } - - const ctx = { visits: randInt(0, 2) }; + const items = randomItems(rng); + const { addOns, code } = await generateModifiers(rng, iter); + + const ctx = { visits: rng.randInt(0, 2) }; const specs = await resolveModifiers(items, { addOns, ...(code !== undefined ? { code } : {}), diff --git a/test/lib/code-quality.test.ts b/test/lib/code-quality.test.ts index 5a0146f92e..ce0ee1cb8f 100644 --- a/test/lib/code-quality.test.ts +++ b/test/lib/code-quality.test.ts @@ -394,6 +394,36 @@ describe("code quality", () => { }); }); + /** + * Scan one file set line by line, collecting violations via a detector. + * Skips code-quality's own files so its rule literals never self-flag. + */ + const collectLineViolations = ( + files: string[], + contents: Map, + detect: ( + relativePath: string, + line: string, + lineNum: number, + ) => string | null, + ): string[] => { + const violations: string[] = []; + for (const file of files) { + const relativePath = repoRelative(file); + if (isCodeQualityFile(relativePath)) continue; + // ensureLoaded() populates `contents` from this same `files` list, so + // every file requested here is guaranteed present. + const lines = contents.get(file)!.split("\n"); + let lineNum = 0; + for (const line of lines) { + lineNum++; + const v = detect(relativePath, line, lineNum); + if (v) violations.push(v); + } + } + return violations; + }; + /** * Scan src and test files line by line, collecting violations via a detector. * Test code is held to the same line-level standards as production code. @@ -407,23 +437,10 @@ describe("code quality", () => { ) => string | null, ): Promise => { await ensureLoaded(); - const violations: string[] = []; - const scan = (files: string[], contents: Map): void => { - for (const file of files) { - const relativePath = repoRelative(file); - if (isCodeQualityFile(relativePath)) continue; - const lines = contents.get(file)!.split("\n"); - let lineNum = 0; - for (const line of lines) { - lineNum++; - const v = detect(relativePath, line, lineNum); - if (v) violations.push(v); - } - } - }; - scan(srcFiles, srcContents); - scan(testFiles, testContents); - return violations; + return [ + ...collectLineViolations(srcFiles, srcContents, detect), + ...collectLineViolations(testFiles, testContents, detect), + ]; }; describe("no aliasing", () => { diff --git a/test/lib/code-quality/detectors.ts b/test/lib/code-quality/detectors.ts index 49491c63b1..f1e3f36868 100644 --- a/test/lib/code-quality/detectors.ts +++ b/test/lib/code-quality/detectors.ts @@ -405,6 +405,12 @@ const NON_CALL_KEYWORDS = new Set([ const isIdentChar = (c: string): boolean => /[\w$]/.test(c); const isIdentStart = (c: string): boolean => /[A-Za-z_$]/.test(c); const isWhitespace = (c: string): boolean => /\s/.test(c); +const isQuote = (c: string | undefined): boolean => + c === '"' || c === "'" || c === "`"; +const isOpenBracket = (c: string | undefined): boolean => + c === "(" || c === "[" || c === "{"; +const isCloseBracket = (c: string | undefined): boolean => + c === ")" || c === "]" || c === "}"; /** * Skip a string or template literal starting at the opening quote `start`. @@ -412,6 +418,27 @@ const isWhitespace = (c: string): boolean => /\s/.test(c); * substitutions are skipped wholesale (including nested strings) so a `)` or * `,` inside them never leaks into argument parsing. */ +/** + * Skip a template `${…}` substitution whose `$` is at `start` (so `content[start]` + * is `$` and `content[start + 1]` is `{`). Returns the index just past the + * matching `}`, skipping nested strings so their braces don't unbalance the count. + */ +const skipTemplateSubstitution = (content: string, start: number): number => { + let depth = 1; + let j = start + 2; + while (j < content.length && depth > 0) { + const d = content[j]; + if (d === "{") depth++; + else if (d === "}") depth--; + else if (d === '"' || d === "'" || d === "`") { + j = skipString(content, j); + continue; + } + j++; + } + return j; +}; + export const skipString = (content: string, start: number): number => { const quote = content[start]; let j = start + 1; @@ -423,18 +450,7 @@ export const skipString = (content: string, start: number): number => { } if (c === quote) return j + 1; if (quote === "`" && c === "$" && content[j + 1] === "{") { - let depth = 1; - j += 2; - while (j < content.length && depth > 0) { - const d = content[j]; - if (d === "{") depth++; - else if (d === "}") depth--; - else if (d === '"' || d === "'" || d === "`") { - j = skipString(content, j); - continue; - } - j++; - } + j = skipTemplateSubstitution(content, j); continue; } j++; @@ -462,6 +478,18 @@ export const skipComment = (content: string, i: number): number => { return i; }; +/** + * If a comment or a string/template literal begins at `i`, return the index just + * past it; otherwise return `i` unchanged. Comments are checked before strings, + * matching the tokenizer order used elsewhere in this file. + */ +const skipCommentOrString = (content: string, i: number): number => { + const pastComment = skipComment(content, i); + if (pastComment !== i) return pastComment; + if (isQuote(content[i])) return skipString(content, i); + return i; +}; + /** * Parse a comma-separated argument list whose opening `(` is at `open`. * Returns the trimmed top-level arguments and the index of the closing `)`. @@ -477,18 +505,14 @@ export const parseArgList = ( let cur = open + 1; let p = open + 1; while (p < content.length && depth > 0) { - const skipped = skipComment(content, p); + const skipped = skipCommentOrString(content, p); if (skipped !== p) { p = skipped; continue; } const d = content[p]; - if (d === '"' || d === "'" || d === "`") { - p = skipString(content, p); - continue; - } - if (d === "(" || d === "[" || d === "{") depth++; - else if (d === ")" || d === "]" || d === "}") { + if (isOpenBracket(d)) depth++; + else if (isCloseBracket(d)) { depth--; if (depth === 0) { args.push(content.slice(cur, p).trim()); @@ -720,24 +744,57 @@ const matchBrace = (code: string, open: number): number => { /** The `{`/`}` offsets of an interface body starting after its name at `pos`, * or null. Skips an optional `<…>` type-parameter/`extends` clause; a `=` or * `;` before the body means this wasn't an interface declaration. */ +/** Change in angle-bracket nesting depth contributed by the char at `i`: + * `+1` for `<`, `-1` for a `>` that is not part of an arrow `=>`, else `0`. */ +const angleDepthDelta = (code: string, i: number): number => { + const c = code[i]; + if (c === "<") return 1; + if (c === ">" && code[i - 1] !== "=") return -1; + return 0; +}; + const parseInterfaceBody = ( code: string, pos: number, ): { open: number; close: number } | null => { let depth = 0; for (let i = pos; i < code.length; i++) { + depth += angleDepthDelta(code, i); + if (depth !== 0) continue; const c = code[i]; - if (c === "<") depth++; - else if (c === ">") { - if (code[i - 1] !== "=") depth--; - } else if (depth === 0 && c === "{") { + if (c === "{") { const close = matchBrace(code, i); return close === -1 ? null : { close, open: i }; - } else if (depth === 0 && (c === ";" || c === "=")) return null; + } + if (c === ";" || c === "=") return null; } return null; }; +/** + * From index `i` — where `code[i]` is `<` — skip a balanced `<…>` type-parameter + * clause and return the index just after its closing `>`. If `code[i]` is not + * `<`, returns `i` unchanged. An unbalanced clause consumes to end of input. + */ +const skipTypeParams = (code: string, i: number): number => { + if (code[i] !== "<") return i; + let depth = 0; + let j = i; + for (; j < code.length; j++) { + if (code[j] === "<") depth++; + else if (code[j] === ">" && --depth === 0) { + j++; + break; + } + } + return j; +}; + +/** Whether the character following a `type X = { … }` body may legitimately + * terminate the alias (end of input, `;`, or a line break). */ +const isTypeAliasBodyEnd = (after: string | undefined): boolean => + !after || after === ";" || after === "\n" || after === "\r"; + /** Advance past whitespace in `code` from `i`. */ const skipSpace = (code: string, i: number): number => { let j = i; @@ -755,20 +812,7 @@ const parseTypeAliasBody = ( code: string, pos: number, ): { open: number; close: number } | null => { - let i = skipSpace(code, pos); - if (code[i] === "<") { - let depth = 0; - for (; i < code.length; i++) { - if (code[i] === "<") depth++; - else if (code[i] === ">") { - depth--; - if (depth === 0) { - i++; - break; - } - } - } - } + let i = skipTypeParams(code, skipSpace(code, pos)); i = skipSpace(code, i); if (code[i] !== "=") return null; i = skipSpace(code, i + 1); @@ -777,8 +821,7 @@ const parseTypeAliasBody = ( if (close === -1) return null; let k = close + 1; while (k < code.length && (code[k] === " " || code[k] === "\t")) k++; - const after = code[k]; - if (after && after !== ";" && after !== "\n" && after !== "\r") return null; + if (!isTypeAliasBodyEnd(code[k])) return null; return { close, open: i }; }; @@ -805,8 +848,8 @@ export const splitTypeMembers = ( }; for (let i = innerStart; i < innerEnd; i++) { const c = code[i]; - if (c === "{" || c === "(" || c === "[" || c === "<") depth++; - else if (c === "}" || c === ")" || c === "]") depth--; + if (isOpenBracket(c) || c === "<") depth++; + else if (isCloseBracket(c)) depth--; else if (c === ">") { if (code[i - 1] !== "=") depth--; } else if (depth === 0 && (c === ";" || c === ",")) push(i); diff --git a/test/lib/db/migration-restore/helpers.ts b/test/lib/db/migration-restore/helpers.ts index c96aadafa4..7fab2c5d5c 100644 --- a/test/lib/db/migration-restore/helpers.ts +++ b/test/lib/db/migration-restore/helpers.ts @@ -319,6 +319,28 @@ export const migrationBoundaries = MIGRATIONS.slice( const shardSlice = (items: T[], shard: number, shardCount: number): T[] => items.filter((_, index) => index % shardCount === shard); +/** + * Spot-check that every object a migration declares it owns is present in the + * live schema again after a drop/restore cycle. + */ +const assertOwnedObjectsPresent = async ( + req: SchemaRequirement, +): Promise => { + for (const table of req.newTables ?? []) { + expect((await tableColumns(table)).size).toBeGreaterThan(0); + } + for (const [table, cols] of Object.entries(req.columns ?? {})) { + const present = await tableColumns(table); + for (const col of cols) expect(present.has(col)).toBe(true); + } + for (const index of req.indexes ?? []) { + expect(await indexExists(index)).toBe(true); + } + for (const trigger of req.triggers ?? []) { + expect(await triggerExists(trigger)).toBe(true); + } +}; + /** * Register one shard of the per-migration restore suite: for each additive * migration in the shard, drop exactly its owned objects, prove verify() @@ -360,19 +382,7 @@ export const defineRestoreCasesSuite = ( expect(await sentinelListingExists()).toBe(true); // Spot-check that each declared object is actually present again. - for (const table of req.newTables ?? []) { - expect((await tableColumns(table)).size).toBeGreaterThan(0); - } - for (const [table, cols] of Object.entries(req.columns ?? {})) { - const present = await tableColumns(table); - for (const col of cols) expect(present.has(col)).toBe(true); - } - for (const index of req.indexes ?? []) { - expect(await indexExists(index)).toBe(true); - } - for (const trigger of req.triggers ?? []) { - expect(await triggerExists(trigger)).toBe(true); - } + await assertOwnedObjectsPresent(req); }); } }, diff --git a/test/lib/fold-tree.test.ts b/test/lib/fold-tree.test.ts index e8d8b86d5a..8d1bff25af 100644 --- a/test/lib/fold-tree.test.ts +++ b/test/lib/fold-tree.test.ts @@ -62,6 +62,19 @@ const freshState = () => ({ selectedListingIds: new Set(), }); +/** Validate a single foldChild outcome against the running total and cap: + * within the cap the fold must be accepted and the quantity recorded; above + * the cap it must be rejected (never clamped) and the quantity left unchanged. */ +const foldOutcomeValid = ( + error: ReturnType, + recordedQty: number | undefined, + running: number, + max: number, +): boolean => + running <= max + ? error === null && recordedQty === running + : error !== null && recordedQty !== running; + /** Mirror the production adapter's steps, purely (no DB; holidays default none): * build the tree, resolve each node's availability, run the walk. */ const foldOf = ( @@ -515,12 +528,12 @@ describe("fold selection algebra (property-based)", () => { for (const q of qtys) { const error = foldChild(state, child, q, 1, PARENT_ID, undefined); running += q; - if (running <= max) { - if (error !== null) return false; - if (state.quantities.get(1) !== running) return false; - } else { - return error !== null && state.quantities.get(1) !== running; + if ( + !foldOutcomeValid(error, state.quantities.get(1), running, max) + ) { + return false; } + if (running > max) return true; } return true; }, diff --git a/test/lib/i18n-coverage.test.ts b/test/lib/i18n-coverage.test.ts index 7f196f73ab..330e10fde7 100644 --- a/test/lib/i18n-coverage.test.ts +++ b/test/lib/i18n-coverage.test.ts @@ -108,25 +108,47 @@ const relFromSrc = (file: string): string => file.slice(SRC_DIR.length + 1); /** Object-property labels are a .ts-module idiom; .tsx uses JSX instead. */ const isTsModule = (file: string): boolean => file.endsWith(".ts"); +/** Wordy matches of `re` on one line, each formatted via `label`. The captured + * user-facing value lives in group `valueGroup` (differs per pattern). */ +const matchesOnLine = ( + line: string, + lineNo: number, + re: RegExp, + valueGroup: number, + label: (m: RegExpMatchArray, value: string, lineNo: number) => string, +): string[] => { + const out: string[] = []; + for (const m of line.matchAll(re)) { + const value = m[valueGroup] ?? ""; + if (wordy(value)) out.push(label(m, value, lineNo)); + } + return out; +}; + +/** Hard-coded strings in JSX attributes and text nodes on one line. */ +const jsxLeftovers = (line: string, lineNo: number): string[] => [ + ...matchesOnLine(line, lineNo, ATTR, 3, (m, v, n) => `L${n} ${m[1]}="${v}"`), + ...matchesOnLine( + line, + lineNo, + TEXT, + 1, + (_m, v, n) => `L${n} text "${v.trim()}"`, + ), +]; + +/** Hard-coded strings in object-property definitions on one line (.ts only). */ +const propLeftovers = (line: string, lineNo: number): string[] => + matchesOnLine(line, lineNo, PROP, 3, (m, v, n) => `L${n} ${m[1]}: "${v}"`); + /** Hard-coded user-facing strings still present in a file's source. */ const leftoverLiterals = (src: string, isTs: boolean): string[] => { const hits: string[] = []; - src.split("\n").forEach((line, i) => { + src.split("\n").forEach((line, idx) => { if (isCommentLine(line)) return; - for (const m of line.matchAll(ATTR)) { - const value = m[3] ?? ""; - if (wordy(value)) hits.push(`L${i + 1} ${m[1]}="${value}"`); - } - if (isTs) { - for (const m of line.matchAll(PROP)) { - const value = m[3] ?? ""; - if (wordy(value)) hits.push(`L${i + 1} ${m[1]}: "${value}"`); - } - } - for (const m of line.matchAll(TEXT)) { - const text = (m[1] ?? "").trim(); - if (wordy(text)) hits.push(`L${i + 1} text "${text}"`); - } + const lineNo = idx + 1; + hits.push(...jsxLeftovers(line, lineNo)); + if (isTs) hits.push(...propLeftovers(line, lineNo)); }); return hits; }; diff --git a/test/lib/square/client.test.ts b/test/lib/square/client.test.ts index 335a0695e2..a5df4c47e9 100644 --- a/test/lib/square/client.test.ts +++ b/test/lib/square/client.test.ts @@ -96,6 +96,11 @@ describeSquare(() => { describe("testSquareConnection", () => { type ConnectionResult = Awaited>; + /** Run an assertion only when the test named a value for it. */ + const when = (value: T | undefined, assert: (value: T) => void) => { + if (value !== undefined) assert(value); + }; + /** Checks only the parts of a connection result a test names. */ const expectConnection = ( result: ConnectionResult, @@ -112,34 +117,24 @@ describeSquare(() => { webhookError?: string; }, ) => { - if (want.ok !== undefined) expect(result.ok).toBe(want.ok); - if (want.tokenValid !== undefined) { - expect(result.accessToken.valid).toBe(want.tokenValid); - } - if (want.tokenError !== undefined) { - expect(result.accessToken.error).toContain(want.tokenError); - } - if (want.mode !== undefined) { - expect(result.accessToken.mode).toBe(want.mode); - } - if (want.locationConfigured !== undefined) { - expect(result.location.configured).toBe(want.locationConfigured); - } - if (want.locationName !== undefined) { - expect(result.location.name).toBe(want.locationName); - } - if (want.locationStatus !== undefined) { - expect(result.location.status).toBe(want.locationStatus); - } - if (want.locationError !== undefined) { - expect(result.location.error).toContain(want.locationError); - } - if (want.webhookConfigured !== undefined) { - expect(result.webhook.configured).toBe(want.webhookConfigured); - } - if (want.webhookError !== undefined) { - expect(result.webhook.error).toContain(want.webhookError); - } + when(want.ok, (ok) => expect(result.ok).toBe(ok)); + when(want.tokenValid, (v) => expect(result.accessToken.valid).toBe(v)); + when(want.tokenError, (e) => + expect(result.accessToken.error).toContain(e), + ); + when(want.mode, (mode) => expect(result.accessToken.mode).toBe(mode)); + when(want.locationConfigured, (c) => + expect(result.location.configured).toBe(c), + ); + when(want.locationName, (n) => expect(result.location.name).toBe(n)); + when(want.locationStatus, (s) => expect(result.location.status).toBe(s)); + when(want.locationError, (e) => + expect(result.location.error).toContain(e), + ); + when(want.webhookConfigured, (c) => + expect(result.webhook.configured).toBe(c), + ); + when(want.webhookError, (e) => expect(result.webhook.error).toContain(e)); }; /** Store settings, stub locations.list, run the checks, assert the result. */ diff --git a/test/shared/bunny-db.test.ts b/test/shared/bunny-db.test.ts index a9e77d5aea..41c01dd2ff 100644 --- a/test/shared/bunny-db.test.ts +++ b/test/shared/bunny-db.test.ts @@ -146,6 +146,26 @@ describeWithEnv("bunny-db", { env: { BUNNY_API_KEY: "test-api-key" } }, () => { test("createDatabase uses AccessKey header", async () => { const headers: string[] = []; + const respondForHeaderTest = (url: string): Response => { + if (url.endsWith("/v2/databases")) { + return new Response(JSON.stringify({ db_id: "db_hdr" }), { + status: 200, + }); + } + if (url.includes("/v2/databases/db_hdr") && !url.includes("/auth")) { + return new Response( + JSON.stringify({ + db: { db_id: "db_hdr", name: "H", url: "libsql://h.net" }, + }), + { status: 200 }, + ); + } + if (url.includes("/auth/generate")) { + return new Response(JSON.stringify({ token: "t" }), { status: 200 }); + } + return new Response("", { status: 500 }); + }; + await withMocks( () => stub( @@ -157,32 +177,7 @@ describeWithEnv("bunny-db", { env: { BUNNY_API_KEY: "test-api-key" } }, () => { ?.AccessKey; if (accessKey) headers.push(accessKey); - if (url.endsWith("/v2/databases")) { - return Promise.resolve( - new Response(JSON.stringify({ db_id: "db_hdr" }), { - status: 200, - }), - ); - } - if ( - url.includes("/v2/databases/db_hdr") && - !url.includes("/auth") - ) { - return Promise.resolve( - new Response( - JSON.stringify({ - db: { db_id: "db_hdr", name: "H", url: "libsql://h.net" }, - }), - { status: 200 }, - ), - ); - } - if (url.includes("/auth/generate")) { - return Promise.resolve( - new Response(JSON.stringify({ token: "t" }), { status: 200 }), - ); - } - return Promise.resolve(new Response("", { status: 500 })); + return Promise.resolve(respondForHeaderTest(url)); }, ), async () => { diff --git a/test/test-utils/fake-dom.ts b/test/test-utils/fake-dom.ts index 1748edfd9d..b91a42c653 100644 --- a/test/test-utils/fake-dom.ts +++ b/test/test-utils/fake-dom.ts @@ -101,22 +101,26 @@ const parseClause = (raw: string): Clause => { return clause; }; +const matchesName = (el: FakeElement, clause: Clause): boolean => { + const name = el.attrs.get("name") ?? ""; + if (clause.namePrefix && !name.startsWith(clause.namePrefix)) return false; + if (clause.nameExact && name !== clause.nameExact) return false; + return true; +}; + +const matchesData = (el: FakeElement, clause: Clause): boolean => { + if (!clause.dataKey) return true; + const dataVal = el.getAttribute(`data-${clause.dataKey}`); + if (dataVal === null) return false; + return clause.dataValue === undefined || dataVal === clause.dataValue; +}; + const matchesClause = (el: FakeElement, clause: Clause): boolean => { if (clause.tag && el.tag !== clause.tag) return false; if (clause.class && !el.classes.has(clause.class)) return false; if (clause.type && el.type !== clause.type) return false; if (clause.checked && !el.checked) return false; - const name = el.attrs.get("name") ?? ""; - if (clause.namePrefix && !name.startsWith(clause.namePrefix)) return false; - if (clause.nameExact && name !== clause.nameExact) return false; - if (clause.dataKey) { - const dataVal = el.getAttribute(`data-${clause.dataKey}`); - if (dataVal === null) return false; - if (clause.dataValue !== undefined && dataVal !== clause.dataValue) { - return false; - } - } - return true; + return matchesName(el, clause) && matchesData(el, clause); }; const matchesSelector = (el: FakeElement, selector: string): boolean => { diff --git a/test/test-utils/test-browser.ts b/test/test-utils/test-browser.ts index a8366976ce..802aaf5c83 100644 --- a/test/test-utils/test-browser.ts +++ b/test/test-utils/test-browser.ts @@ -55,9 +55,10 @@ const regexCollect = ( transform: (m: RegExpExecArray) => T, ): T[] => { const results: T[] = []; - let m: RegExpExecArray | null; - while ((m = re.exec(html)) !== null) { + let m = re.exec(html); + while (m !== null) { results.push(transform(m)); + m = re.exec(html); } return results; };