Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

ci(shared): ratchet the open shapes in request schemas

Maurice0b4000af8174
diff --git a/shared/CLAUDE.md b/shared/CLAUDE.md
index 36d2d5716..8d06013ad 100644
--- a/shared/CLAUDE.md
+++ b/shared/CLAUDE.md
@@ -12,6 +12,7 @@ npm run lint # eslint --fix (rewrites files)
npm run test # vitest run — co-located *.spec.ts files
npm run i18n:parity # audit locale drift, exits 0
npm run i18n:parity:strict # CI gate — exits 1 on any drift
+npm run contracts:open # CI gate (after build): open shapes in request schemas may only shrink
```
Single test: `npx vitest run src/i18n/i18n-parity.spec.ts`, or `npx vitest run -t "rejects extra keys"`.
@@ -35,7 +36,7 @@ One folder per domain exporting Zod schemas plus inferred types (`export type X
The parity rule governs **existing** routes; it is not a license to mint new debt:
- **The contract describes the wire, not the storage engine.** New booleans are `z.boolean()` — convert SQLite 0/1 at the service boundary, never add a `z.union([z.boolean(), z.number()])`. New ids use `idSchema`/`idParamSchema`, never `number | string`. Request and response types for a field must agree.
-- **Use the shared primitives** instead of re-declaring bare `z.number()`/`z.string()` per domain. Narrow an existing open object rather than adding a new `z.record(...)`/passthrough body — "any object" gives zero drift protection.
+- **Use the shared primitives** instead of re-declaring bare `z.number()`/`z.string()` per domain. Narrow an existing open object rather than adding a new `z.record(...)`/passthrough body — "any object" gives zero drift protection. `contracts:open` (`scripts/open-request-schemas.mjs`) counts the open shapes in every exported `*RequestSchema` (a loose object, a record of unknown, a `z.unknown()`/`z.any()` field or body) against `scripts/open-request-schemas-baseline.json`: a new request schema may hold none, an existing one no more than its entry. It reads the built `dist/`; `src/open-request-schemas.spec.ts` runs the same check over `src/` in `npm test`. After narrowing a schema, `npm run contracts:open -- --update` lowers the baseline (it never raises or adds an entry).
- **Add a schema, add a spec** — especially for lenient parsers fed by untrusted or LLM input.
- **Stay lean and isomorphic**: zero imports from client/server, no `node:` APIs, effectively no new runtime dependencies (the contract layer approaches `zod`-only; i18n is a separable concern — don't couple new contract code to it).
- **Never hand-copy a locale list.** `SUPPORTED_LANGUAGES` in `src/i18n/languages.ts` is the one registry — derive barrels, loaders and spec maps from it.
diff --git a/shared/package.json b/shared/package.json
index b6843e07f..605c9fa70 100644
--- a/shared/package.json
+++ b/shared/package.json
@@ -70,7 +70,8 @@
"format:check": "prettier --check \"src/**/*.ts\"",
"lint": "eslint --fix \"src/**/*.ts\"",
"i18n:parity": "node scripts/i18n-parity.mjs",
- "i18n:parity:strict": "node scripts/i18n-parity.mjs --strict"
+ "i18n:parity:strict": "node scripts/i18n-parity.mjs --strict",
+ "contracts:open": "node scripts/open-request-schemas.mjs"
},
"dependencies": {
"isomorphic-dompurify": "^3.23.0",
diff --git a/shared/scripts/open-request-schemas-baseline.json b/shared/scripts/open-request-schemas-baseline.json
new file mode 100644
index 000000000..cb9f6fe1f
--- /dev/null
+++ b/shared/scripts/open-request-schemas-baseline.json
@@ -0,0 +1,49 @@
+{
+ "accommodationUpdateRequestSchema": 1,
+ "adminAddonUpdateRequestSchema": 1,
+ "adminDefaultUserSettingsRequestSchema": 1,
+ "adminPermissionsRequestSchema": 1,
+ "adminTestNotificationRequestSchema": 2,
+ "appSettingsUpdateRequestSchema": 1,
+ "autoBackupSettingsRequestSchema": 1,
+ "bookingImportConfirmRequestSchema": 1,
+ "collabPollCreateRequestSchema": 1,
+ "collectionImportIntoRequestSchema": 1,
+ "collectionImportRequestSchema": 1,
+ "journeyAddTripRequestSchema": 2,
+ "journeyContributorRequestSchema": 3,
+ "journeyContributorUpdateRequestSchema": 2,
+ "journeyCreateRequestSchema": 4,
+ "journeyEntryCreateRequestSchema": 2,
+ "journeyEntryPhotoUploadRequestSchema": 2,
+ "journeyEntryUpdateRequestSchema": 1,
+ "journeyGalleryVideoRequestSchema": 2,
+ "journeyLinkPhotoRequestSchema": 3,
+ "journeyPhotoUpdateRequestSchema": 1,
+ "journeyPreferencesRequestSchema": 1,
+ "journeyProviderPhotosRequestSchema": 8,
+ "journeyReorderEntriesRequestSchema": 2,
+ "journeyShareLinkRequestSchema": 5,
+ "journeyUpdateRequestSchema": 1,
+ "mapsPlaceEnrichmentRequestSchema": 1,
+ "oauthTokenRequestSchema": 1,
+ "packingImportRequestSchema": 1,
+ "passkeyLoginVerifyRequestSchema": 1,
+ "passkeyRegisterVerifyRequestSchema": 2,
+ "passkeyRenameRequestSchema": 1,
+ "placeCreateRequestSchema": 1,
+ "placeUpdateRequestSchema": 1,
+ "pluginActivateRequestSchema": 1,
+ "pluginEgressHostsRequestSchema": 2,
+ "pluginInstallRequestSchema": 1,
+ "pluginLinkRequestSchema": 1,
+ "pluginRetrustRequestSchema": 1,
+ "pluginRouteRequestSchema": 1,
+ "pluginUninstallRequestSchema": 1,
+ "pluginUpdateRequestSchema": 1,
+ "pluginUserSettingsUpdateRequestSchema": 2,
+ "reservationCreateRequestSchema": 1,
+ "reservationUpdateRequestSchema": 1,
+ "settingUpsertRequestSchema": 1,
+ "settingsBulkRequestSchema": 1
+}
diff --git a/shared/scripts/open-request-schemas.d.mts b/shared/scripts/open-request-schemas.d.mts
new file mode 100644
index 000000000..092300306
--- /dev/null
+++ b/shared/scripts/open-request-schemas.d.mts
@@ -0,0 +1,21 @@
+// Types for open-request-schemas.mjs, so the spec imports it without a suppression.
+
+export declare const BASELINE: string;
+export declare const REQUEST_SCHEMA: RegExp;
+
+export declare function openShapes(root: unknown): string[];
+export declare function countOpenShapes(namespace: Record<string, unknown>): Record<string, number>;
+export declare function readBaseline(path?: string): Record<string, number>;
+export declare function compare(
+ baseline: Record<string, number>,
+ counts: Record<string, number>,
+): { grown: [string, number][]; lowerable: [string, number][] };
+export declare function lowerBaseline(
+ baseline: Record<string, number>,
+ counts: Record<string, number>,
+): Record<string, number>;
+export declare function report(
+ baseline: Record<string, number>,
+ counts: Record<string, number>,
+ log?: Pick<Console, 'error'>,
+): { grown: [string, number][]; lowerable: [string, number][] };
diff --git a/shared/scripts/open-request-schemas.mjs b/shared/scripts/open-request-schemas.mjs
new file mode 100644
index 000000000..2f7fa5a31
--- /dev/null
+++ b/shared/scripts/open-request-schemas.mjs
@@ -0,0 +1,186 @@
+#!/usr/bin/env node
+/*
+ * contracts:open: the request contracts may only get tighter.
+ *
+ * A write route's body is validated against its *RequestSchema, and the boot
+ * gate on the server only checks that one exists. An open shape inside it
+ * accepts anything at that spot, so the route is covered on paper while the
+ * real shape lives in service code and casts (see CLAUDE.md, "Narrow an
+ * existing open object rather than adding a new z.record(...)/passthrough
+ * body"). This counts the open shapes in every exported *RequestSchema:
+ *
+ * loose an object that keeps unknown keys (z.looseObject, .passthrough(),
+ * a catchall of unknown or any)
+ * record a z.record whose values are unknown or any
+ * unknown a z.unknown() or z.any() anywhere else, a field or the whole body
+ *
+ * and compares the count per schema with scripts/open-request-schemas-baseline.json.
+ * A schema over its entry fails, so does a new schema with any open shape;
+ * narrowing one is reported so the baseline can follow.
+ *
+ * npm run contracts:open check the built package against the baseline (CI)
+ * npm run contracts:open -- --update lower the baseline to today's counts; it never
+ * raises or adds an entry
+ *
+ * It reads the built dist/, so run `npm run build` first. The same check runs
+ * against src/ in `npm test` (scripts/open-request-schemas.spec.ts).
+ */
+import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+export const BASELINE = fileURLToPath(new URL('./open-request-schemas-baseline.json', import.meta.url));
+const DIST = fileURLToPath(new URL('../dist/index.cjs', import.meta.url));
+
+/** The exports this ratchet looks at. */
+export const REQUEST_SCHEMA = /RequestSchema$/;
+
+const isOpenLeaf = (schema) => {
+ const type = schema?._zod?.def?.type;
+ return type === 'unknown' || type === 'any';
+};
+
+/**
+ * The open shapes inside one Zod schema, as a list of `kind@path` strings.
+ * Each schema node is visited once, so a shared fragment reused through
+ * `.and()` counts once per request schema.
+ */
+export function openShapes(root) {
+ const found = [];
+ const seen = new Set();
+ const visit = (schema, path) => {
+ const def = schema?._zod?.def;
+ if (!def || seen.has(schema)) return;
+ seen.add(schema);
+ switch (def.type) {
+ case 'unknown':
+ case 'any':
+ found.push(`unknown@${path}`);
+ return;
+ case 'record':
+ if (isOpenLeaf(def.valueType)) {
+ found.push(`record@${path}`);
+ return;
+ }
+ visit(def.valueType, `${path}{}`);
+ return;
+ case 'object':
+ if (isOpenLeaf(def.catchall)) found.push(`loose@${path}`);
+ else if (def.catchall && def.catchall._zod.def.type !== 'never') visit(def.catchall, `${path}.*`);
+ for (const [key, value] of Object.entries(def.shape ?? {})) visit(value, `${path}.${key}`);
+ return;
+ case 'lazy':
+ visit(def.getter(), path);
+ return;
+ default:
+ break;
+ }
+ // Wrappers and combinators: optional, nullable, default, catch, pipe,
+ // array, tuple, union, intersection, readonly and the like.
+ for (const key of ['innerType', 'in', 'out', 'element', 'left', 'right', 'rest']) {
+ if (def[key]?._zod) visit(def[key], path);
+ }
+ for (const key of ['options', 'items']) {
+ if (Array.isArray(def[key])) def[key].forEach((option, i) => visit(option, `${path}|${i}`));
+ }
+ };
+ visit(root, '$');
+ return found;
+}
+
+/** Open-shape counts for every exported *RequestSchema of a module namespace, sorted by name. */
+export function countOpenShapes(namespace) {
+ const counts = {};
+ for (const name of Object.keys(namespace).sort()) {
+ if (!REQUEST_SCHEMA.test(name) || !namespace[name]?._zod) continue;
+ counts[name] = openShapes(namespace[name]).length;
+ }
+ return counts;
+}
+
+/** The baseline as committed. Missing, unreadable or malformed is an error, never an empty baseline. */
+export function readBaseline(path = BASELINE) {
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
+ } catch (err) {
+ throw new Error(`scripts/open-request-schemas-baseline.json cannot be read: ${err.message}`);
+ }
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('scripts/open-request-schemas-baseline.json must be an object of schema names to counts');
+ }
+ for (const [name, n] of Object.entries(parsed)) {
+ if (!Number.isInteger(n) || n < 1) {
+ throw new Error(`scripts/open-request-schemas-baseline.json: ${name} holds ${JSON.stringify(n)}, expected a whole number above 0`);
+ }
+ }
+ return parsed;
+}
+
+/** Schemas over their allowance, and entries the schemas have narrowed below. */
+export function compare(baseline, counts) {
+ const grown = Object.entries(counts).filter(([name, n]) => n > (baseline[name] ?? 0));
+ const lowerable = Object.entries(baseline).filter(([name, n]) => (counts[name] ?? 0) < n);
+ return { grown, lowerable };
+}
+
+/** The baseline lowered to today's counts. Never raises an entry, never adds one, drops the ones at zero. */
+export function lowerBaseline(baseline, counts) {
+ const lowered = {};
+ for (const [name, allowed] of Object.entries(baseline)) {
+ const now = Math.min(allowed, counts[name] ?? 0);
+ if (now > 0) lowered[name] = now;
+ }
+ return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b)));
+}
+
+export function report(baseline, counts, log = console) {
+ const { grown, lowerable } = compare(baseline, counts);
+ for (const [name, n] of grown) {
+ const entry = baseline[name];
+ log.error(
+ `FAIL ${name}: ${n} open shape(s), ` +
+ (entry ? `its baseline is ${entry}. ` : 'a new schema may hold none. ') +
+ 'Type the fields instead of accepting any object (shared/CLAUDE.md, "Rules for new contracts").',
+ );
+ }
+ return { grown, lowerable };
+}
+
+function main(argv) {
+ if (!existsSync(DIST)) {
+ throw new Error('dist/index.cjs is missing: run "npm run build" in shared/ first');
+ }
+ const namespace = createRequire(import.meta.url)(DIST);
+ const counts = countOpenShapes(namespace);
+ if (Object.keys(counts).length === 0) {
+ throw new Error('no *RequestSchema export found in dist/: the check would pass without looking at anything');
+ }
+ let baseline = readBaseline();
+ const update = argv.includes('--update');
+ if (update) {
+ baseline = lowerBaseline(baseline, counts);
+ writeFileSync(BASELINE, JSON.stringify(baseline, null, 2) + '\n');
+ }
+ const { grown, lowerable } = report(baseline, counts);
+ if (lowerable.length && !update) {
+ console.log(`${lowerable.length} schema(s) hold fewer open shapes than their baseline now: run with --update to lower it.`);
+ }
+ const total = Object.values(baseline).reduce((a, b) => a + b, 0);
+ console.log(
+ `open shapes: ${Object.keys(counts).length} request schema(s), ${Object.keys(baseline).length} still open, ${total} open shape(s) held at their baseline`,
+ );
+ return grown.length ? 1 : 0;
+}
+
+// Compared by real path, so the check still runs when the script is started through a symlink.
+const isCli =
+ Boolean(process.argv[1]) && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
+if (isCli) {
+ try {
+ process.exitCode = main(process.argv.slice(2));
+ } catch (err) {
+ console.error(`FAIL ${err.message}`);
+ process.exitCode = 1;
+ }
+}
diff --git a/shared/src/open-request-schemas.spec.ts b/shared/src/open-request-schemas.spec.ts
new file mode 100644
index 000000000..d78e3f46c
--- /dev/null
+++ b/shared/src/open-request-schemas.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * The open-shape ratchet over the request contracts (scripts/open-request-schemas.mjs).
+ * The CLI checks the built dist/ in CI; this spec runs the same walk over src/
+ * so `npm test` fails too, and proves the walker sees every kind of open shape
+ * and fails on one a schema did not have before.
+ */
+import { compare, countOpenShapes, lowerBaseline, openShapes, readBaseline } from '../scripts/open-request-schemas.mjs';
+import * as contracts from './index';
+
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { z } from 'zod';
+
+describe('open request schemas', () => {
+ it('OPEN-001: no request schema holds more open shapes than the baseline allows', () => {
+ const counts = countOpenShapes(contracts);
+ const { grown } = compare(readBaseline(), counts);
+ expect(grown, 'type the fields instead of accepting any object, see shared/CLAUDE.md').toEqual([]);
+ });
+
+ it('OPEN-002: the baseline names only schemas that exist and are still open', () => {
+ const counts = countOpenShapes(contracts);
+ const { lowerable } = compare(readBaseline(), counts);
+ expect(lowerable, 'run `npm run contracts:open -- --update` after narrowing a schema').toEqual([]);
+ });
+
+ it('OPEN-003: finds every kind of open shape, wherever it sits', () => {
+ expect(openShapes(z.record(z.string(), z.unknown()))).toEqual(['record@$']);
+ expect(openShapes(z.looseObject({ a: z.string() }))).toEqual(['loose@$']);
+ expect(openShapes(z.object({ a: z.string() }).passthrough())).toEqual(['loose@$']);
+ expect(openShapes(z.object({ a: z.unknown().optional(), b: z.any() }))).toEqual(['unknown@$.a', 'unknown@$.b']);
+ expect(openShapes(z.unknown())).toEqual(['unknown@$']);
+ const open = z.record(z.string(), z.unknown());
+ expect(openShapes(open.and(z.object({ name: z.string() })))).toEqual(['record@$']);
+ expect(openShapes(z.array(z.object({ meta: z.record(z.string(), z.any()) })))).toEqual(['record@$.meta']);
+ expect(openShapes(z.union([z.string(), z.object({ x: z.unknown() })]))).toEqual(['unknown@$|1.x']);
+ expect(openShapes(z.object({ x: z.unknown() }).nullable().default(null))).toEqual(['unknown@$.x']);
+ });
+
+ it('OPEN-004: a closed schema counts nothing', () => {
+ expect(openShapes(z.object({ a: z.string(), b: z.array(z.number()) }))).toEqual([]);
+ expect(openShapes(z.strictObject({ a: z.string() }))).toEqual([]);
+ expect(openShapes(z.record(z.string(), z.number()))).toEqual([]);
+ });
+
+ it('OPEN-005: fails on a new open schema and on an existing one that opens further', () => {
+ const namespace = {
+ fooRequestSchema: z.object({ a: z.string() }),
+ barRequestSchema: z.looseObject({ b: z.unknown() }),
+ notARequest: z.unknown(),
+ };
+ const counts = countOpenShapes(namespace);
+ expect(counts).toEqual({ barRequestSchema: 2, fooRequestSchema: 0 });
+
+ const grownNew = compare({}, counts);
+ expect(grownNew.grown).toEqual([['barRequestSchema', 2]]);
+ const grownMore = compare({ barRequestSchema: 1 }, counts);
+ expect(grownMore.grown).toEqual([['barRequestSchema', 2]]);
+ expect(compare({ barRequestSchema: 2 }, counts).grown).toEqual([]);
+ });
+
+ it('OPEN-006: lowering never raises or adds an entry and drops the ones that closed', () => {
+ expect(lowerBaseline({ a: 3, b: 2, c: 1 }, { a: 1, b: 5, c: 0, d: 4 })).toEqual({ a: 1, b: 2 });
+ });
+
+ it('OPEN-007: a missing or malformed baseline is an error, never an empty baseline', () => {
+ expect(() => readBaseline('/definitely/not/here.json')).toThrow(/cannot be read/);
+ // Valid JSON, but not a map of schema names to counts.
+ expect(() => readBaseline(fileURLToPath(new URL('../package.json', import.meta.url)))).toThrow(
+ /expected a whole number/,
+ );
+ });
+});