Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
+2 -1
View File
@@ -14,5 +14,6 @@
"importOrderParserPlugins": [
"typescript",
"decorators-legacy"
]
],
"importOrderSideEffects": false
}
+30 -8
View File
@@ -8,10 +8,15 @@ Scope: the **`@trek/shared`** workspace — the **single source of truth** for A
npm run build # tsdown → dist/ (CJS + ESM + .d.ts). REQUIRED before server/client typecheck or run
npm run build:watch # what the root `npm run dev` runs
npm run typecheck # tsc --noEmit
npm run lint # eslint --fix (rewrites files)
npm run lint # eslint, check-only (lint-prettier.yml)
npm run lint:fix # eslint --fix
npm run lint:format # Prettier outside scripts/format-baseline.json, which only shrinks (lint-prettier.yml)
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 i18n:parity:strict # CI gate, exits 1 on any drift (also runs the untranslated ratchet below)
npm run i18n:untranslated # the untranslated-strings ratchet on its own
npm run i18n:untranslated:update # lower scripts/i18n-untranslated-baseline.json after translating; never raises it
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"`.
@@ -20,7 +25,7 @@ Single test: `npx vitest run src/i18n/i18n-parity.spec.ts`, or `npx vitest run -
## Build & exports
`tsdown.config.ts` emits the root barrel, the i18n metadata barrel, and **one entry per locale** so each locale is its own lazy-loadable chunk (the client dynamic-imports them). `zod` is never bundled. The `exports` map exposes `@trek/shared` (contracts), `@trek/shared/i18n` (metadata/types) and `@trek/shared/i18n/<locale>`.
`tsdown.config.ts` emits the root barrel, the i18n metadata barrel, and **one entry per locale** so each locale is its own lazy-loadable chunk (the client dynamic-imports them). `zod` is never bundled. The `exports` map exposes `@trek/shared` (contracts), `@trek/shared/i18n` (metadata/types), `@trek/shared/i18n/<locale>`, `@trek/shared/roadtrip` and `@trek/shared/sanitize` (the DOMPurify sanitisers, kept out of the root barrel, see below).
## Contracts (`src/<domain>/<domain>.schema.ts`)
@@ -30,12 +35,14 @@ One folder per domain exporting Zod schemas plus inferred types (`export type X
**Schemas mirror the exact wire behavior of existing routes** (`weather/weather.schema.ts` is the example): strings stay strings if the route never coerced them, optional fields reflect partial response subsets, and bespoke 4xx error strings are reproduced in the server controller, not derived from the schema. Don't "tidy up" a schema to be stricter than the contract it documents.
**Response schemas** (`<x>ResponseSchema`, with the row schemas they are built from) describe what a route answers, and the server checks them: a handler declares one with `@ResponseContract(schema)` (`server/src/nest/common/response-contract.ts`), and under `NODE_ENV=test` every response it sends is parsed against it, so the e2e and integration suites fail on drift. They follow the wire exactly as the routes have always sent it, flags as 0/1 and times as stored where that is what goes out, booleans where the service converts. Objects are not strict: an extra key passes, a declared one that is missing or of another type fails. `successResponseSchema` (`{ success: true }`) and `emptyResponseSchema` (a 204) live in `src/common/`. They are exported from the barrel for the client to type its calls with; the client's own copies in `client/src/types.ts` have not moved onto them yet.
## Rules for new contracts
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, because "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, a `z.custom()`/`z.instanceof()`, each counted once per path it sits at) 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). The suffix is only a convention, so the server holds the schemas it really binds to the same count: `npm run contracts:dto-open --workspace=server` walks every `createZodDto` class, whatever its schema is called, against `server/scripts/dto-open-shapes-baseline.json`.
- **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.
@@ -46,9 +53,24 @@ The parity rule governs **existing** routes; it is not a license to mint new deb
- **`languages.ts`** — `SUPPORTED_LANGUAGES` is the canonical registry and the source of `SupportedLanguageCode`. Adding a language starts here.
- **`<locale>/`** — one folder per language, one file per UI domain plus an `index.ts` barrel; each file exports a flat map of dot-namespaced keys typed as `TranslationStrings`. The runtime `t(key)` only resolves these top-level keys.
- **`en/` is canonical.** Every other locale must have the identical file set and top-level keys — `i18n:parity:strict` enforces it in CI. When you add or rename a key, update every locale.
- **Every locale gets a real translation — an English placeholder is not acceptable.** Parity only checks that the key exists, so copying the `en` string passes CI while shipping English to those users. Write native phrasing with the locale's own punctuation and the same `{placeholders}` as `en`; if you genuinely cannot translate one, say so instead of filling it with English.
- **Further i18n specs run in `npm test`** and fail changes that parity lets through: placeholder parity (every `{placeholder}` in an `en` string must appear in each translation), no `en` string may call TREK "self-hosted" (the same build runs on managed installs; exemptions live in the spec), and a wording regression test for plugin permission descriptions (currently one string — add a case there when a permission's real behavior changes). None of these are part of `i18n:parity`, which checks key sets only.
- **Every locale gets a real translation; an English placeholder is not acceptable.** Write native phrasing with the locale's own punctuation and the same `{placeholders}` as `en`; if you genuinely cannot translate one, say so instead of filling it with English. Parity only checks that the key exists, so `i18n:parity:strict` also runs a ratchet (`scripts/i18n-untranslated.mjs`): per locale and file, the `// en-fallback` markers and the unmarked values identical to `en` may not grow past `scripts/i18n-untranslated-baseline.json`. An identical value is excused only when, after dropping placeholders, markup, URLs/e-mail/paths, the product names in `BRAND_NAMES` (Google Maps, Atlas, Immich) and the unit symbols in `UNITS`, no plain word is left (a word with a capital after its first letter, an acronym or a single letter does not count), so "{count} km", "GPX", "OAuth" and "Atlas" pass while "Settings" and "Source code" count. A single ordinary word that really is the locale's own (German "Status", French "Transport") carries `// same-as-en` on its declaration; the marker is honoured only on a value holding one plain word once the excused parts are dropped (on a phrase it is ignored, so it cannot wave a copied sentence through) and only in Latin-script locales (`LATIN_LOCALES`), because a Latin word in Japanese or Arabic is English whatever it says. A plural form en has no key for (Russian `.few`, Arabic `.two`) counts when it equals any form en spells out for that group. Every locale folder must be on `LATIN_LOCALES` or `NON_LATIN_LOCALES`, so a new language is classified there first. Deleting a marker without translating moves the string from one count to the other and still fails. After translating, run `npm run i18n:untranslated:update` to lower the baseline; nothing raises it.
- **Count-bearing strings use plural forms, never `count === 1` in the caller.** The key holds the general form (the CLDR "other" category) and `key.zero|one|two|few|many` hold the forms the language's `Intl.PluralRules` selects for whole numbers (`plural.ts`); `t(key, { count })` (or `{ n }`) picks one. Pass the count as a number. Russian needs `.one`, `.few` and `.many`, Arabic all five, Japanese none. `i18n:parity` checks that every locale has exactly the forms its language reaches with whole numbers and none it never selects. A form may spell the number out (Arabic "ملف واحد") only where its category is that one number; French `one` also covers 0 and Russian `one` covers 21, so they keep `{count}`. A string whose wording changes with the number (the old "Copy to trip" for one place, "Copy {count} to trip" for more) is a plural group whose `one` drops the number where the language allows it, not two keys switched in the caller.
- **An `en` string carrying `{count}` or `{n}` must be a plural group**, even when the forms read the same (a label such as "Notes: {count}"), so every language can inflect. **A quantity is always named `{count}` (or `{n}`)**, the only params `t()` picks a form by: "All {days} days" read "Все 3 дней" in Russian. `i18n:parity` refuses an ungrouped string carrying `{count}`, `{n}` or one of the quantity names in `QUANTITY_PARAMS` (`{days}`, `{minutes}`, `{objects}`, `{max}` …), unless `NOT_PLURAL` in `scripts/i18n-parity.mjs` lists it with a reason: only for a number that is never a quantity (a day number, a step, a multiplier) or one followed by nothing but a unit symbol ("{minutes} min", "{max} MB"). A second number in the same string keeps its own name ("{over} of {count} days"). An entry that stops matching fails too.
- **Further i18n specs run in `npm test`** and fail changes that parity lets through: placeholder parity (every `{placeholder}` in an `en` string must appear in each translation), no `en` string may call TREK "self-hosted" (the same build runs on managed installs; exemptions live in the spec), and a wording regression test for plugin permission descriptions (currently one string; add a case there when a permission's real behavior changes). None of these are part of `i18n:parity`, which checks key sets, plural forms, count strings and the untranslated ratchet.
- **The i18n scripts read the tables as text** through `scripts/i18n-catalog.mjs`: a value must be one string literal on the key's line or the next, and anything else (a concatenation, a template literal) is an error rather than a skipped key. Their specs use the fixtures in `scripts/fixtures/`. That en holds every key the client names is checked on the client side (`npm run lint:i18n-keys` in `client/`).
## Sanitization (`src/sanitize/sanitize.ts`)
## Sanitization (`src/sanitize/sanitize.ts`, `src/sanitize/escape.ts`)
`isomorphic-dompurify` with a minimal inline-only allow-list (a rich-text variant already exists there for when rich text ships). `sanitizeInlineHtml` backs the client's HTML translation path; `escapeHtml` is used wherever the client builds markup from user strings (map popups, account screens). This is meant to be the one home for escaping. No lint rule enforces that yet and a handful of client files still carry a local `escapeHtml` — that is debt to fold in, not a pattern to copy.
`isomorphic-dompurify` with a minimal inline-only allow-list (a rich-text variant already exists there for when rich text ships). The sanitisers are imported from `@trek/shared/sanitize`, never re-exported from the root barrel: on Node, `isomorphic-dompurify` builds a jsdom window as soon as it loads, and the root barrel is what the server and each of its test files import. `sanitizeInlineHtml` backs the client's HTML translation path; `escapeHtml` (DOM-free, in the root barrel) is used wherever the client builds markup from user strings (map popups, account screens). This is meant to be the one home for escaping. No lint rule enforces that yet and a handful of client files still carry a local `escapeHtml` — that is debt to fold in, not a pattern to copy.
## Money (`src/money/money.ts`)
`toMinor`, `sumMinor`, `splitEqualShares` and `currencyDecimals` are the budget arithmetic both sides must agree on to the cent: amounts are netted in whole hundredths, equal splits hand the leftover hundredths out by rotation from `itemId % n`, and the shares always sum back to the total. The server's settlement uses these directly; `money.spec.ts` holds the share table that used to be duplicated between the server and client tests. The client's euro preview (`splitEqualShares` in `client/src/components/Budget/CostsPanel.helpers.ts`) converts the shared cent split; only its `currencyDecimals` (`client/src/utils/formatters.ts`) is still a copy of its own, and folding it onto this one is client work, not a second implementation to copy.
## Permissions (`src/permissions/permissions.ts`)
`PERMISSION_ACTIONS` is the catalog of configurable trip permissions (key, default level, the levels an admin may pick), `PermissionKey` the union of its keys and `evaluatePermission(level, { isAdmin, isOwner, isMember })` the one decision rule. The server's `PermissionsService` and `@RequirePermission(action: PermissionKey)` are built on them, so a new action starts here and a misspelt key fails to compile. The client still evaluates in its own `useCanDo` (with "not configured = allow"); moving it onto `evaluatePermission` is client work.
## Reservation types (`src/reservation/reservation-types.ts`)
`RESERVATION_TYPES` is the catalog of reservation types in picker order, each with its flags (`isTransport`, `isCarrier`, `isRental`, `isStay`, `hasLegs`, `creatableViaMcp`). The named subsets (`TRANSPORT_RESERVATION_TYPES`, `MCP_CREATABLE_TRANSPORT_TYPES`, `BOOKING_RESERVATION_TYPES`, `CARRIER_RESERVATION_TYPES`, `TRAVEL_RESERVATION_TYPES`, …) are derived from it in that order, so an MCP enum built from one lists its values as the UI does. A new type is added here once; the spec pins every subset. The column stays free text: `reservationTypeSchema` and `reservationStatusSchema` accept the catalog values or any stored string, and the request schemas stay as tolerant as before. Inside `reservationSchema` the two fields are strings described by the catalog rather than the union, because Zod 4 types a union field as optional for a consumer compiled without strictNullChecks (the client), which would loosen `Reservation`. The client's own type lists (`TRANSPORT_TYPES` and the `cable_car` lists) have not moved onto it yet.
+4 -5
View File
@@ -2,7 +2,6 @@ import js from '@eslint/js';
import gitignore from 'eslint-config-flat-gitignore';
import eslintConfigPrettier from 'eslint-config-prettier';
import eslintPluginPrettier from 'eslint-plugin-prettier';
import tseslint from 'typescript-eslint';
export default tseslint.config(
@@ -11,11 +10,11 @@ export default tseslint.config(
...tseslint.configs.recommended,
eslintConfigPrettier,
{
plugins: {
prettier: eslintPluginPrettier,
},
// Formatting is Prettier's own check (npm run lint:format, held to
// scripts/format-baseline.json until the one mechanical reformat), not an
// ESLint rule: run through ESLint it could only be enforced with --fix,
// which rewrote the files CI was about to check.
rules: {
'prettier/prettier': 'error',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
+39 -12
View File
@@ -1,6 +1,9 @@
{
"name": "@trek/shared",
"version": "4.3.1",
"version": "5.0.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"private": true,
"description": "Shared API contracts (Zod schemas) — single source of truth for TREK server and client.",
"type": "module",
@@ -47,6 +50,26 @@
"types": "./dist/roadtrip/planning.d.cts",
"default": "./dist/roadtrip/planning.cjs"
}
},
"./stickers": {
"import": {
"types": "./dist/book/stickers/index.d.mts",
"default": "./dist/book/stickers/index.mjs"
},
"require": {
"types": "./dist/book/stickers/index.d.cts",
"default": "./dist/book/stickers/index.cjs"
}
},
"./sanitize": {
"import": {
"types": "./dist/sanitize/sanitize.d.mts",
"default": "./dist/sanitize/sanitize.mjs"
},
"require": {
"types": "./dist/sanitize/sanitize.d.cts",
"default": "./dist/sanitize/sanitize.cjs"
}
}
},
"typesVersions": {
@@ -68,27 +91,31 @@
"typecheck": "tsc --noEmit",
"format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"",
"lint": "eslint --fix \"src/**/*.ts\"",
"lint": "eslint \"src/**/*.ts\"",
"lint:fix": "eslint --fix \"src/**/*.ts\"",
"lint:format": "node scripts/format-lint.mjs",
"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",
"i18n:untranslated": "node scripts/i18n-untranslated.mjs",
"i18n:untranslated:update": "node scripts/i18n-untranslated.mjs --update"
},
"dependencies": {
"isomorphic-dompurify": "^3.15.0",
"zod": "^4.3.6"
"isomorphic-dompurify": "^3.23.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@vitest/coverage-v8": "^4.1.11",
"eslint": "^10.3.0",
"eslint-config-flat-gitignore": "^2.3.0",
"eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"prettier": "3.8.3",
"prettier": "3.9.8",
"prettier-plugin-organize-imports": "^4.3.0",
"tsdown": "^0.22.2",
"typescript": "^6.0.2",
"typescript-eslint": "^8.58.2",
"tsdown": "^0.23.0",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0",
"vitest": "^4.1.11"
}
}
@@ -0,0 +1 @@
{ "de": {
@@ -0,0 +1 @@
{ "de": { "a.ts": { "marked": 1, "identical": "2" } } }
@@ -0,0 +1,14 @@
// Fixture for the i18n script specs: a canonical table.
const a = {
'a.title': 'Trip settings',
'a.count': '{count} places',
'a.count.one': '{count} place',
'a.lone': 'Remove {count} items',
'a.day': 'Day {n}',
'a.brand': 'Google Maps',
'a.code': 'GPX',
'a.quote': "It's here",
'a.multi':
'A long sentence that wraps onto the next line',
};
export default a;
@@ -0,0 +1,5 @@
// Fixture: a locale that lacks en's a.ts.
const b = {
'b.title': 'Titre',
};
export default b;
@@ -0,0 +1,6 @@
// Fixture for the untranslated ratchet's plural rule: en spells out only `one`.
const a = {
'a.pack': '{count} items to pack',
'a.pack.one': '{count} item to pack',
};
export default a;
@@ -0,0 +1,8 @@
// Fixture: the general form, `few` and `many` are English copies; en declares no `few` or `many`.
const a = {
'a.pack': '{count} items to pack',
'a.pack.one': 'Собрать {count} вещь',
'a.pack.few': '{count} items to pack',
'a.pack.many': '{count} item to pack',
};
export default a;
@@ -0,0 +1,5 @@
// Fixture: a canonical table beside a locale on neither script list.
const a = {
'a.title': 'Trip settings',
};
export default a;
@@ -0,0 +1,5 @@
// Fixture: a locale folder the ratchet has not been told the script of.
const a = {
'a.title': 'Trip settings',
};
export default a;
@@ -0,0 +1,11 @@
// Fixture: "Status" is the German word too and says so; the name and the unit need no marker.
// The marker on a copied sentence is not honoured: a.delete still counts.
const a = {
'a.settings': 'Einstellungen',
'a.appearance': 'Erscheinungsbild',
'a.status': 'Status', // same-as-en
'a.addon': 'Atlas',
'a.distance': '{count} km',
'a.delete': 'Delete this trip and all its places permanently', // same-as-en
};
export default a;
@@ -0,0 +1,10 @@
// Fixture for the untranslated ratchet's word rule: single words, names and units.
const a = {
'a.settings': 'Settings',
'a.appearance': 'Appearance',
'a.status': 'Status',
'a.addon': 'Atlas',
'a.distance': '{count} km',
'a.delete': 'Delete this trip and all its places permanently',
};
export default a;
@@ -0,0 +1,10 @@
// Fixture: "Settings" is an English copy; "Status" is one too, with no marker.
const a = {
'a.settings': 'Settings',
'a.appearance': 'Apparence',
'a.status': 'Status',
'a.addon': 'Atlas',
'a.distance': '{count} km',
'a.delete': 'Supprimer définitivement ce voyage et tous ses lieux',
};
export default a;
@@ -0,0 +1,10 @@
// Fixture: a Latin word in Japanese is English, marker or not.
const a = {
'a.settings': '設定',
'a.appearance': 'Appearance',
'a.status': 'Status', // same-as-en
'a.addon': 'Atlas',
'a.distance': '{count} km',
'a.delete': 'この旅行とすべての場所を完全に削除',
};
export default a;
+15
View File
@@ -0,0 +1,15 @@
// Fixture: two unmarked English copies (a.title, a.multi), one marked (a.lone).
const a = {
'a.title': 'Trip settings',
'a.count': '{count} Orte',
'a.count.one': '{count} Ort',
'a.lone': 'Remove {count} items', // en-fallback
'a.day': 'Tag {n}',
'a.brand': 'Google Maps',
'a.code': 'GPX',
'a.quote': 'Es ist hier',
'a.multi':
'A long sentence that wraps onto the next line',
'a.stay': '{days} Tage bleiben',
};
export default a;
+15
View File
@@ -0,0 +1,15 @@
// Fixture for the i18n script specs: a canonical table.
const a = {
'a.title': 'Trip settings',
'a.count': '{count} places',
'a.count.one': '{count} place',
'a.lone': 'Remove {count} items',
'a.day': 'Day {n}',
'a.brand': 'Google Maps',
'a.code': 'GPX',
'a.quote': "It's here",
'a.multi':
'A long sentence that wraps onto the next line',
'a.stay': 'Stay {days} days',
};
export default a;
+1
View File
@@ -0,0 +1 @@
[]
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env node
/*
* lint:format: new shared code is formatted with Prettier.
*
* lint-prettier.yml used to run `npm run lint` with --fix ahead of
* format:check, so the check only ever saw files it had just rewritten, and
* many files differ from what .prettierrc asks for. Formatting all of them
* belongs in one mechanical commit of its own; until it lands, the files that were unformatted when
* this check came in are listed in scripts/format-baseline.json and the list
* only shrinks: every file outside it, a new one in particular, must be
* formatted, and a listed file leaves the list once it has been. After the
* mass reformat, --update empties the list and the check is a plain
* prettier --check over src/.
*
* npm run lint:format check against the baseline (CI)
* npm run lint:format -- --list print every unformatted file
* npm run lint:format -- --update take formatted and deleted files off the list;
* it never adds one
*
* To format a file: npx prettier --write <file>. The comparison lives in
* scripts/lib/format.mjs at the repository root; Prettier and its config come
* from this workspace.
*/
import { fileURLToPath, URL } from 'node:url';
import * as prettier from 'prettier';
import { check } from '../../scripts/lib/format.mjs';
import { runCli } from '../../scripts/lib/ratchet.mjs';
const root = fileURLToPath(new URL('..', import.meta.url));
await runCli('lint:format', (args) =>
check({
prettier,
root,
dirs: ['src'],
accepts: (key) => key.endsWith('.ts'),
update: args.includes('--update'),
list: args.includes('--list'),
}),
);
+68
View File
@@ -0,0 +1,68 @@
// Regenerates src/book/book-icon-names-*.data.ts, the lucide drawings the
// Studio's icon tab offers, from the lucide-react installed at the repo root.
// Run from shared/: `node scripts/gen-book-icon-names.mjs`.
//
// Read from the package's type declarations rather than imported: the shared
// package has no lucide dependency of its own and must not grow one, the
// contract layer stays zod only. The names are taken the way the client's
// iconLibrary.ts takes them from the module: every PascalCase export, less the
// `Lucide*` and `*Icon` aliases of a name that exists bare, and less `Icon`,
// the component every drawing is built on. client/src/components/Studio/
// iconLibrary.test.ts fails when the files and the shipped library drift apart.
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const lucide = join(here, '..', '..', 'node_modules', 'lucide-react');
const { version } = JSON.parse(readFileSync(join(lucide, 'package.json'), 'utf8'));
const declarations = readFileSync(join(lucide, 'dist', 'lucide-react.d.ts'), 'utf8');
/** The last `export { ... };` of the declarations, which names every icon and its aliases. */
const exportLine = declarations
.split('\n')
.filter((line) => line.startsWith('export { '))
.pop();
if (!exportLine) throw new Error('no export list in lucide-react.d.ts');
const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
const exported = exportLine
.replace(/^export \{ /, '')
.replace(/ \};\s*$/, '')
.split(',')
.map((part) =>
part
.trim()
.split(/\s+as\s+/)
.pop(),
)
.filter((name) => PASCAL_CASE.test(name));
const present = new Set(exported);
const names = [...present]
.filter((name) => !(name.startsWith('Lucide') && present.has(name.slice(6))))
.filter((name) => !(name.endsWith('Icon') && present.has(name.slice(0, -4))))
.filter((name) => name !== 'Icon')
.sort();
/** The three files and the initials each holds, so none of them passes a thousand lines. */
const PARTS = [
{ suffix: 'a-e', constant: 'BOOK_ICON_NAMES_A_E', label: 'A to E', test: /^[A-E]/ },
{ suffix: 'f-p', constant: 'BOOK_ICON_NAMES_F_P', label: 'F to P', test: /^[F-P]/ },
{ suffix: 'q-z', constant: 'BOOK_ICON_NAMES_Q_Z', label: 'Q to Z', test: /^[Q-Z]/ },
];
for (const part of PARTS) {
const list = names.filter((name) => part.test.test(name));
const source = `/**
* The lucide drawings the Studio offers, ${part.label}: part of BOOK_ICON_NAMES
* (book-icons.ts). Generated from lucide-react ${version} by
* scripts/gen-book-icon-names.mjs, never edited by hand; the client's
* iconLibrary.test.ts fails when the list and the library it ships drift apart.
*/
export const ${part.constant}: readonly string[] = [
${list.map((name) => ` '${name}',`).join('\n')}
];
`;
writeFileSync(join(here, '..', 'src', 'book', `book-icon-names-${part.suffix}.data.ts`), source);
}
console.log(`wrote ${names.length} icon names from lucide-react ${version}`);
+117
View File
@@ -0,0 +1,117 @@
/**
* Reads the locale tables as text, for the i18n scripts beside this file.
*
* Plain .mjs outside `src/` for the reason i18n-parity.mjs gives: shared's
* typecheck runs without @types/node, and the CI parity job runs these scripts
* with no install at all. The tables are parsed rather than imported so the
* checks stay synchronous and see the `// en-fallback` markers, which an
* import would strip.
*
* A value is one string literal, single or double quoted, on the key's line or
* the next one (the two shapes Prettier writes). Anything else after a key (a
* concatenation, a template literal, a call) is an error rather than a skipped
* key: a check that silently reads less than the file holds passes for the
* wrong reason.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
export const I18N_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'i18n');
export const FALLBACK_MARKER = '// en-fallback';
/**
* The marker a translator leaves on a value that is the locale's own word and
* happens to be spelled as in en (German "Status", French "Transport"). The
* untranslated ratchet honours it only in Latin-script locales.
*/
export const SAME_MARKER = '// same-as-en';
/** A root given as a file URL (what a spec can build without node types) or a path. */
export const asPath = (root) => (root instanceof URL ? fileURLToPath(root) : root);
/** Every locale folder (externalNotifications is a barrel module, not a locale). */
export function listLocales(root = I18N_ROOT) {
const dir = asPath(root);
return readdirSync(dir)
.filter((name) => statSync(join(dir, name)).isDirectory())
.filter((name) => name !== 'externalNotifications');
}
/** The domain files of one locale, sorted. */
export function listDomainFiles(locale, root = I18N_ROOT) {
return readdirSync(join(asPath(root), locale))
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
.sort();
}
const KEY_LINE_RE = /^\s*'([a-z][a-zA-Z0-9.\-_:]*)'\s*:(.*)$/;
const ESCAPES = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0: '\0' };
/** The value of a JS string literal body (between the quotes). */
export function decodeLiteral(body) {
return body.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r?\n|[\s\S])/g, (_, esc) => {
if (esc[0] === 'u' && esc.length > 1) return String.fromCodePoint(parseInt(esc.replace(/[u{}]/g, ''), 16));
if (esc[0] === 'x' && esc.length === 3) return String.fromCharCode(parseInt(esc.slice(1), 16));
if (esc === '\n' || esc === '\r\n') return '';
return ESCAPES[esc] ?? esc;
});
}
/** Reads one quoted literal at the start of `text`; null when `text` does not start with one. */
function readLiteral(text) {
const quote = text[0];
if (quote !== "'" && quote !== '"') return null;
for (let i = 1; i < text.length; i++) {
if (text[i] === '\\') {
i++;
continue;
}
if (text[i] === '\n') return null;
if (text[i] === quote) return { value: decodeLiteral(text.slice(1, i)), rest: text.slice(i + 1) };
}
return null;
}
/**
* Every top-level entry of one table's source: key, value, whether the
* declaration carries the fallback marker (`marked`) or the same-as-en
* marker (`same`), and the line it starts on.
* Throws with file and line on anything it cannot read.
*/
export function parseCatalog(source, label = 'catalogue') {
const lines = source.replace(/\r\n?/g, '\n').split('\n');
const entries = [];
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(KEY_LINE_RE);
if (!match) continue;
const [, key, after] = match;
let text = after.trim();
let end = i;
if (text === '') {
end = i + 1;
text = (lines[end] ?? '').trim();
}
const literal = readLiteral(text);
const tail = literal?.rest.trim() ?? '';
if (!literal || !/^(,|\})?\s*(\/\/.*)?$/.test(tail)) {
throw new Error(`${label}:${i + 1}: '${key}' is not a single string literal`);
}
entries.push({
key,
value: literal.value,
marked: tail.includes(FALLBACK_MARKER),
same: tail.includes(SAME_MARKER),
line: i + 1,
});
i = end;
}
return entries;
}
/** The entries of `locale/file`, read from disk. */
export function readCatalog(locale, file, root = I18N_ROOT) {
return parseCatalog(readFileSync(join(asPath(root), locale, file), 'utf8'), `${locale}/${file}`);
}
+195 -28
View File
@@ -12,39 +12,45 @@
// returns exit-code 1 when any drift is present (intended for CI). Without
// `--strict` the script exits 0 and prints, so it can also run as a non-blocking
// audit during translation work.
// 3. Plural forms: a count-bearing string (`key` or `key.other`, plus at
// least one of `key.zero|one|two|few|many` in en) is a plural group. Its
// category keys are not compared with en's, since Russian needs `.few`
// and `.many` and Japanese needs none. Instead every locale must spell
// out each category whole counts reach in its language, and may not
// carry one its language never selects. The rules come from
// `Intl.PluralRules`, through the same helpers the client resolves with.
// 4. Count strings: an en string carrying {count} or {n} (the two params
// `t()` picks a plural form by) must be a plural group, so every
// language gets the forms it needs. So must one carrying a quantity
// under another name ({days}, {minutes}, {objects}, QUANTITY_PARAMS),
// which no form is picked by: it is renamed to {count}. The exceptions
// are NOT_PLURAL: a number that is never a quantity ("Day {n}", a step,
// a multiplier), or one followed only by a unit symbol.
// 5. Untranslated strings: the marked `// en-fallback` and unmarked English
// copies per locale and file may only shrink (i18n-untranslated.mjs,
// which also lowers the baseline with --update).
//
// Limitations: we only parse *top-level* string keys (those declared as the
// first column of the file, matching the regex below). Nested objects, function
// bodies, and inline comments are ignored. This matches how `t(key)` calls
// resolve at runtime in TranslationContext.
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const i18nRoot = join(here, '..', 'src', 'i18n');
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { getIntlLanguage } from '../src/i18n/languages.ts';
import { allPluralCategories, integerPluralCategories, pluralFormOf, pluralGroups } from '../src/i18n/plural.ts';
import { I18N_ROOT, listDomainFiles, listLocales, readCatalog } from './i18n-catalog.mjs';
import { compare, countUntranslated, formatGrown, readBaseline } from './i18n-untranslated.mjs';
// Match a top-level translation key declaration: leading whitespace, then a
// quoted key (must start with a lowercase letter), then a colon. This is the
// exact pattern every domain file uses.
const TOP_LEVEL_KEY_RE = /^\s*'([a-z][a-zA-Z0-9.\-_]*)'\s*:/gm;
function listLocales() {
return readdirSync(i18nRoot)
.filter((name) => statSync(join(i18nRoot, name)).isDirectory())
// externalNotifications is a barrel module, not a locale.
.filter((name) => name !== 'externalNotifications');
}
function listDomainFiles(locale) {
return readdirSync(join(i18nRoot, locale))
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
.sort();
}
// exact pattern every domain file uses. Keys may hold a colon themselves
// (admin.plugins.perm.db:read:trips); without it in the class those keys were
// never compared, and two locales lacked dozens of them unnoticed.
const TOP_LEVEL_KEY_RE = /^\s*'([a-z][a-zA-Z0-9.\-_:]*)'\s*:/gm;
function extractKeys(locale, file) {
const content = readFileSync(join(i18nRoot, locale, file), 'utf8');
const content = readFileSync(join(I18N_ROOT, locale, file), 'utf8');
const keys = new Set();
for (const match of content.matchAll(TOP_LEVEL_KEY_RE)) {
keys.add(match[1]);
@@ -52,6 +58,105 @@ function extractKeys(locale, file) {
return keys;
}
function withoutVariants(keys, groups) {
return new Set([...keys].filter((k) => !pluralFormOf(k, groups)));
}
/** What one locale owes the plural groups of one file. */
function checkPluralForms(locale, keys, groups) {
const intl = getIntlLanguage(locale);
const required = integerPluralCategories(intl).filter((c) => c !== 'other');
const allowed = new Set(allPluralCategories(intl));
const missing = [];
const invalid = [];
for (const base of groups) {
for (const c of required) if (!keys.has(`${base}.${c}`)) missing.push(`${base}.${c}`);
}
for (const key of keys) {
const form = pluralFormOf(key, groups);
if (form && !allowed.has(form.category)) invalid.push(key);
}
return { missing, invalid };
}
/**
* en strings that carry {count} or {n} without being a quantity of
* something, so no word in any language agrees with the number. Everything
* else with a count is a plural group. An entry that stops matching an
* ungrouped count string fails the check, so the list cannot go stale.
*/
export const NOT_PLURAL = [
{ key: 'assistant.card.tour.days', because: 'the numbers of the days a tour lies on ("Days 2, 4")' },
{ key: 'collab.polls.optionPlaceholder', because: 'the position of a poll option ("Option 3")' },
{ key: 'collections.importOnDay', because: 'the number of the day a place is planned on' },
{ key: 'dashboard.atlas.aroundEquator', because: 'a decimal multiplier ("≈ 1.37×"), not a count of things' },
{ key: 'dayplan.dayN', because: 'the number of a day in the trip' },
{ key: 'planner.dayN', because: 'the number of a day in the trip' },
{ key: 'help.center.step', because: 'the position of a step in a guide' },
{ key: 'help.center.stepOf', because: 'the position of a step in a guide' },
{ key: 'help.center.imageAlt', because: 'the position of a step in a guide' },
{ key: 'system_notice.pager.goto', because: 'the position of a notice in the pager' },
{ key: 'tours.addedToDay', because: 'the number of the day a tour was added to' },
{ key: 'tours.planner.waypointLabel', because: 'the position of a waypoint on the tour' },
{ key: 'dawarich.duration.minutes', because: 'a duration in a unit symbol (min), the same for any number' },
{ key: 'dawarich.duration.hours', because: 'a duration in a unit symbol (h), the same for any number' },
{ key: 'dawarich.duration.hoursMinutes', because: 'a duration in unit symbols (h, min), the same for any number' },
{ key: 'files.uploadErrorSize', because: 'a size limit in a unit symbol (MB), the same for any number' },
];
/**
* Param names that hold a quantity of something but are not the ones `t()`
* picks a plural form by. A string using one keeps a single form in every
* language ("Все {days} дней" for 2 days), so it is held like {count}: rename
* the param to {count} and make the string a plural group.
*/
export const QUANTITY_PARAMS = [
'days',
'nights',
'weeks',
'months',
'years',
'hours',
'minutes',
'seconds',
'items',
'objects',
'max',
];
const COUNT_PARAM_RE = new RegExp(`\\{(?:count|n|${QUANTITY_PARAMS.join('|')})\\}`);
/**
* en strings carrying a count or quantity param outside any plural group,
* and NOT_PLURAL entries that no longer name such a string.
*/
function checkCountStrings(enFiles, notPlural = NOT_PLURAL, root = I18N_ROOT) {
const allowed = new Set(notPlural.map((e) => e.key));
const ungrouped = [];
const seen = new Set();
for (const file of enFiles) {
const entries = readCatalog('en', file, root);
const groups = pluralGroups(entries.map((e) => e.key));
for (const { key, value } of entries) {
if (!COUNT_PARAM_RE.test(value) || groups.has(key) || pluralFormOf(key, groups)) continue;
if (key.endsWith('.other') && groups.has(key.slice(0, -'.other'.length))) continue;
if (allowed.has(key)) seen.add(key);
else ungrouped.push({ file, key });
}
}
return { ungrouped, stale: [...allowed].filter((key) => !seen.has(key)) };
}
/** The untranslated ratchet's verdict, with a reading error reported rather than thrown. */
function checkUntranslated() {
try {
const { grown, lowerable } = compare(countUntranslated(), readBaseline());
return { error: null, grown, lowerable };
} catch (err) {
return { error: err.message, grown: [], lowerable: 0 };
}
}
function diffSets(reference, candidate) {
const missing = [];
const extra = [];
@@ -69,7 +174,14 @@ function checkParity() {
const enKeysByDomain = new Map();
for (const f of enFiles) enKeysByDomain.set(f, extractKeys('en', f));
const report = { fileDrift: [], keyDrift: [] };
const report = { fileDrift: [], keyDrift: [], pluralDrift: [] };
const groupsByDomain = new Map();
for (const f of enFiles) {
const groups = pluralGroups(enKeysByDomain.get(f));
groupsByDomain.set(f, groups);
const { missing, invalid } = checkPluralForms('en', enKeysByDomain.get(f), groups);
if (missing.length || invalid.length) report.pluralDrift.push({ locale: 'en', file: f, missing, invalid });
}
for (const locale of locales) {
if (locale === 'en') continue;
@@ -87,13 +199,23 @@ function checkParity() {
for (const file of enFiles) {
if (!localeFiles.includes(file)) continue;
const localeKeys = extractKeys(locale, file);
const { missing, extra } = diffSets(enKeysByDomain.get(file), localeKeys);
const groups = groupsByDomain.get(file);
const { missing, extra } = diffSets(
withoutVariants(enKeysByDomain.get(file), groups),
withoutVariants(localeKeys, groups),
);
if (missing.length || extra.length) {
report.keyDrift.push({ locale, file, missing, extra });
}
const plural = checkPluralForms(locale, localeKeys, groups);
if (plural.missing.length || plural.invalid.length) {
report.pluralDrift.push({ locale, file, ...plural });
}
}
}
report.countDrift = checkCountStrings(enFiles);
report.untranslated = checkUntranslated();
return report;
}
@@ -122,24 +244,69 @@ function formatReport(report) {
}
}
if (report.pluralDrift.length === 0) {
lines.push('Plural forms: OK');
} else {
lines.push(`Plural forms: ${report.pluralDrift.length} domain file(s) with missing or impossible forms`);
for (const { locale, file, missing, invalid } of report.pluralDrift) {
const parts = [];
if (missing.length) parts.push(`missing ${missing.join(', ')}`);
if (invalid.length) parts.push(`never selected ${invalid.join(', ')}`);
lines.push(` ${locale}/${file}: ${parts.join('; ')}`);
}
}
if (report.countDrift) {
const { ungrouped, stale } = report.countDrift;
if (ungrouped.length === 0 && stale.length === 0) {
lines.push('Count strings: OK');
} else {
lines.push('Count strings: en strings with {count}, {n} or a quantity param that are no plural group');
for (const { file, key } of ungrouped) {
lines.push(
` en/${file}: ${key} (name the quantity {count} and add ${key}.one and the other forms, see shared/CLAUDE.md)`,
);
}
for (const key of stale) lines.push(` NOT_PLURAL lists ${key}, which is no ungrouped count string: remove it`);
}
}
if (report.untranslated) {
const { error, grown, lowerable } = report.untranslated;
if (error) {
lines.push(`Untranslated strings: cannot check, ${error}`);
} else if (grown.length === 0) {
lines.push(
'Untranslated strings: OK' +
(lowerable ? ` (${lowerable} baseline entries can come down: node scripts/i18n-untranslated.mjs --update)` : ''),
);
} else {
lines.push('Untranslated strings: grew past scripts/i18n-untranslated-baseline.json');
lines.push(...formatGrown(grown));
}
}
return lines.join('\n');
}
// Export a structured API for vitest. The CLI entry point only runs when
// executed directly (`node scripts/i18n-parity.mjs`), so importing this file
// from a spec does not produce side effects.
export { checkParity, formatReport };
export { checkCountStrings, checkParity, formatReport };
const isCli = process.argv[1] && process.argv[1].endsWith('i18n-parity.mjs');
if (isCli) {
const strict = process.argv.includes('--strict');
const filesOnly = process.argv.includes('--files-only');
const report = checkParity();
process.stdout.write(formatReport(filesOnly ? { ...report, keyDrift: [] } : report) + '\n');
const shown = filesOnly ? { ...report, keyDrift: [], pluralDrift: [], countDrift: null, untranslated: null } : report;
process.stdout.write(formatReport(shown) + '\n');
if (strict) {
const hasFileDrift = report.fileDrift.length > 0;
const hasKeyDrift = filesOnly ? false : report.keyDrift.length > 0;
if (hasFileDrift || hasKeyDrift) process.exit(1);
const hasKeyDrift = filesOnly ? false : report.keyDrift.length > 0 || report.pluralDrift.length > 0;
const hasCountDrift = !filesOnly && (report.countDrift.ungrouped.length > 0 || report.countDrift.stale.length > 0);
const hasUntranslated = !filesOnly && (report.untranslated.error !== null || report.untranslated.grown.length > 0);
if (hasFileDrift || hasKeyDrift || hasCountDrift || hasUntranslated) process.exit(1);
}
}
-6
View File
@@ -35,12 +35,6 @@ export const ALLOWED = [
'settings.about.descriptionManaged instead, so neither reader is told the ' +
'wrong thing and self-hosters lose nothing.',
},
{
key: 'system_notice.release_notes.feature_dawarich_body',
because:
'it calls Dawarich self-hosted, not TREK, which is what Dawarich is, and the ' +
'release notice carrying it is shown only where the managed condition is false',
},
{
key: 'system_notice.v3_thankyou.body',
because:
@@ -0,0 +1,134 @@
{
"ar": {
"admin.ts": { "marked": 0, "identical": 2 },
"settings.ts": { "marked": 1, "identical": 1 }
},
"az": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 },
"places.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 }
},
"br": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"ca": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 4 },
"settings.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"cs": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 },
"places.ts": { "marked": 0, "identical": 1 }
},
"de": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 2 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"es": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 }
},
"fr": {
"admin.ts": { "marked": 0, "identical": 2 },
"atlas.ts": { "marked": 0, "identical": 1 },
"help.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 10 },
"notif.ts": { "marked": 0, "identical": 1 },
"places.ts": { "marked": 0, "identical": 1 },
"planner.ts": { "marked": 0, "identical": 1 },
"roadtrip.ts": { "marked": 0, "identical": 2 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"gr": {
"admin.ts": { "marked": 0, "identical": 11 },
"common.ts": { "marked": 0, "identical": 1 },
"day.ts": { "marked": 0, "identical": 2 },
"help.ts": { "marked": 0, "identical": 2 },
"journey.ts": { "marked": 0, "identical": 1 },
"places.ts": { "marked": 0, "identical": 1 },
"reservations.ts": { "marked": 0, "identical": 2 },
"roadtrip.ts": { "marked": 0, "identical": 3 },
"settings.ts": { "marked": 0, "identical": 8 },
"storage.ts": { "marked": 0, "identical": 2 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"hu": {
"admin.ts": { "marked": 0, "identical": 1 }
},
"id": {
"admin.ts": { "marked": 0, "identical": 2 },
"journey.ts": { "marked": 0, "identical": 1 }
},
"it": {
"admin.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 },
"storage.ts": { "marked": 0, "identical": 1 }
},
"ja": {
"admin.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 1 }
},
"ko": {
"admin.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"nl": {
"journey.ts": { "marked": 0, "identical": 2 },
"places.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 6 },
"system_notice.ts": { "marked": 0, "identical": 3 }
},
"pl": {
"admin.ts": { "marked": 0, "identical": 1 },
"places.ts": { "marked": 0, "identical": 1 }
},
"ru": {
"admin.ts": { "marked": 0, "identical": 4 },
"settings.ts": { "marked": 0, "identical": 3 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"sk": {
"admin.ts": { "marked": 0, "identical": 1 }
},
"sv": {
"admin.ts": { "marked": 0, "identical": 1 },
"budget.ts": { "marked": 0, "identical": 1 },
"journey.ts": { "marked": 0, "identical": 1 },
"mobileTrip.ts": { "marked": 0, "identical": 1 },
"packing.ts": { "marked": 0, "identical": 1 },
"roadtrip.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 2 }
},
"th": {
"admin.ts": { "marked": 0, "identical": 1 }
},
"tr": {
"system_notice.ts": { "marked": 0, "identical": 1 }
},
"uk": {
"admin.ts": { "marked": 0, "identical": 4 },
"settings.ts": { "marked": 0, "identical": 3 }
},
"vi": {
"admin.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 }
},
"zh": {
"admin.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 }
},
"zh-TW": {
"admin.ts": { "marked": 0, "identical": 1 },
"settings.ts": { "marked": 0, "identical": 1 },
"system_notice.ts": { "marked": 0, "identical": 2 }
}
}
+373
View File
@@ -0,0 +1,373 @@
#!/usr/bin/env node
/**
* i18n:untranslated: English left in the other locales may only shrink.
*
* Parity proves every locale has every key, not that the key holds the
* locale's own language: a copied en string passes it. Two kinds of copy are
* counted per locale and domain file:
*
* marked a declaration carrying `// en-fallback`, the marker a
* translator leaves on a string they could not translate yet
* identical an unmarked value equal to en's, unless the rule in
* `isInvariant` says the text reads the same in every language,
* or a translator confirmed a single word with `// same-as-en`
* in a Latin-script locale (`isExcused`). A plural form en has
* no key for (a Russian `.few` or `.many`) is compared with
* every form en spells out for its group (`enReference`).
*
* Both counts are held at scripts/i18n-untranslated-baseline.json. The check
* fails when either grows past its entry (a file without one may hold none),
* so a feature can no longer ship 26 English copies of a new string. Lowering
* is a separate, explicit step:
*
* node scripts/i18n-untranslated.mjs check against the baseline (CI, via i18n-parity --strict)
* node scripts/i18n-untranslated.mjs --update lower the baseline to today's counts; it never raises an
* entry and drops the ones that reach zero
*
* The two counts are separate on purpose: deleting a marker without
* translating the string moves it from `marked` to `identical`, and the
* identical count refuses it.
*
* Fails closed: a missing or malformed baseline, a locale lacking one of en's
* files, or a value the catalogue reader cannot parse is an error, never a
* pass.
*/
import { pluralFormOf, pluralGroups } from '../src/i18n/plural.ts';
import { asPath, I18N_ROOT, listDomainFiles, listLocales, readCatalog } from './i18n-catalog.mjs';
import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
export const BASELINE = join(dirname(fileURLToPath(import.meta.url)), 'i18n-untranslated-baseline.json');
/**
* Product and service names, which read the same in every language. A value
* is excused for them, never for an ordinary word: German "Status" or French
* "Transport" are the locale's own words only by coincidence, and a one-word
* label copied from en ("Appearance", "Settings") is the commonest untranslated
* string there is. Names with an inner capital (MapLibre, OpenStreetMap) and
* acronyms need no entry, the word rule below already skips them.
*/
export const BRAND_NAMES = [
'Amap',
'Anthropic',
'Apple Maps',
'Atlas',
'ChatGPT',
'Claude',
'Dawarich',
'Discord',
'Docker',
'Gemini',
'Google',
'Google Maps',
'Google Places',
'Home Assistant',
'Immich',
'Mapbox',
'Ntfy',
'Ollama',
'OpenRouter',
'Organic Maps',
'Polaroid',
// The photo book editor's name, like Atlas and Vacay for their add-ons.
'Studio',
'Synology',
'Synology Photos',
'Vacay',
'Webhook',
'wanderer',
];
/** Unit symbols, short codes rather than words: "{count} km", "{minutes} min". */
export const UNITS = ['km', 'mi', 'ft', 'min'];
/**
* Key cap labels, printed on the keyboard in Latin letters whatever the
* language around them ("Ctrl" on a Russian or Japanese keyboard too). A
* locale whose keyboards print another word (German "Strg") translates it.
*/
export const KEY_NAMES = ['Ctrl'];
/**
* Locales written in a script other than Latin. A Latin word left in one of
* them is English whatever the word, so `// same-as-en` is not honoured
* there. Every locale folder must be listed in exactly one of the two lists,
* so a new locale cannot slip past this rule unclassified.
*/
export const NON_LATIN_LOCALES = ['ar', 'gr', 'ja', 'ko', 'ru', 'th', 'uk', 'zh', 'zh-TW'];
export const LATIN_LOCALES = [
'az',
'br',
'ca',
'cs',
'de',
'en',
'es',
'et',
'fr',
'hu',
'id',
'it',
'nl',
'pl',
'sk',
'sv',
'tr',
'vi',
];
const PLACEHOLDER_RE = /\{[a-zA-Z0-9_]+\}/g;
const TAG_RE = /<\/?[a-zA-Z][^>]*>/g;
// A URL, an e-mail address or a path: anything with a slash or an at sign in it.
const ADDRESS_RE = /\S*[/@]\S*/g;
// Hyphens join a word: "Check-in", "Wi-Fi" and "Auto-Backup" are one each.
const WORD_RE = /\p{L}[\p{L}\p{M}'’-]*/gu;
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Longest first, so "Google Maps" goes as one name before "Google" could split it.
const NAME_RE = new RegExp(
`(?<![\\p{L}\\p{N}])(?:${[...BRAND_NAMES, ...UNITS, ...KEY_NAMES]
.sort((a, b) => b.length - a.length)
.map(escapeRe)
.join('|')})(?![\\p{L}\\p{N}])`,
'gu',
);
/**
* A word in the sense of the rule: two letters or more and no capital after
* the first. Single letters (the A and Z of a sort label, the v of
* "v{version}"), acronyms (GPX, URLs, 2FA) and names with an inner capital
* (OAuth, AirTrail) are not words here.
*/
export const isPlainWord = (word) => word.length >= 2 && !/\p{Lu}/u.test(word.slice(1));
/**
* Whether a value equal to en's is legitimately the same text in every
* language. True when, after dropping placeholders, markup, addresses, the
* names in BRAND_NAMES and the UNITS, no plain word is left: "{count} km",
* "OAuth", "GPX", "Google Maps", "Atlas", "PDF · {size}". A single plain word
* is counted like a phrase: "Budget" and "Status" may be the locale's word too,
* and that is for a translator to confirm, not for the rule to assume.
*/
export function isInvariant(value) {
return plainWords(value).length === 0;
}
/** The plain words `value` holds once placeholders, markup, addresses, names and units are dropped. */
export function plainWords(value) {
const text = value.replace(PLACEHOLDER_RE, ' ').replace(TAG_RE, ' ').replace(ADDRESS_RE, ' ').replace(NAME_RE, ' ');
return (text.match(WORD_RE) ?? []).filter(isPlainWord);
}
/** Whether `locale` is written in Latin script. Throws for a locale on neither list. */
export function isLatinLocale(locale) {
if (LATIN_LOCALES.includes(locale)) return true;
if (NON_LATIN_LOCALES.includes(locale)) return false;
throw new Error(
`locale ${locale} is on neither LATIN_LOCALES nor NON_LATIN_LOCALES in scripts/i18n-untranslated.mjs`,
);
}
/**
* Whether an unmarked value equal to en's is excused: it is invariant, or a
* translator marked it `// same-as-en` in a Latin-script locale and it holds
* one plain word. The marker is for a word that really is the locale's own
* (German "Status"); a phrase that reads the same as en's is a copy, and the
* marker on it is ignored rather than trusted.
*/
export const isExcused = (value, same, locale) => {
const words = plainWords(value);
return words.length === 0 || (same && isLatinLocale(locale) && words.length === 1);
};
/**
* Every en value a locale's `key` may not repeat. A key en declares has its
* en value. A form of a plural group that en does not declare (Russian
* `.few`, Arabic `.two`) has every form en spells out for the group, since
* it has no en counterpart of its own and a copy of any of them is English.
* A form en declares keeps the exact comparison: Italian "{count} file" for
* en's general "{count} files" is the Italian plural, not en's `.one`.
*/
export function enReference(en, groups) {
const forms = new Map();
for (const [key, value] of en) {
const base = groupOf(key, groups);
if (base !== null) {
if (!forms.has(base)) forms.set(base, new Set());
forms.get(base).add(value);
}
}
return (key) => {
if (en.has(key)) return new Set([en.get(key)]);
const base = groupOf(key, groups);
return base === null ? new Set() : (forms.get(base) ?? new Set());
};
}
/** The plural group `key` belongs to (its base, `key.other` or a category form), else null. */
function groupOf(key, groups) {
if (groups.has(key)) return key;
if (key.endsWith('.other') && groups.has(key.slice(0, -'.other'.length))) return key.slice(0, -'.other'.length);
return pluralFormOf(key, groups)?.base ?? null;
}
/**
* Today's counts: `{ [locale]: { [file]: { marked, identical } } }`, only
* non-zero entries. Throws on a locale missing one of en's files, a locale
* on neither script list or a value the reader cannot parse.
*/
export function countUntranslated(root = I18N_ROOT) {
const locales = listLocales(root);
if (!locales.includes('en')) throw new Error(`${asPath(root)}/en is required as the reference locale`);
const enFiles = listDomainFiles('en', root);
const enValues = new Map(
enFiles.map((f) => {
const en = new Map(readCatalog('en', f, root).map((e) => [e.key, e.value]));
return [f, enReference(en, pluralGroups(en.keys()))];
}),
);
const counts = {};
for (const locale of locales) {
// Classify every folder first: an unlisted locale is an error, not a pass.
isLatinLocale(locale);
if (locale === 'en') continue;
const files = new Set(listDomainFiles(locale, root));
for (const file of enFiles) {
if (!files.has(file)) throw new Error(`${locale}/${file} is missing; run i18n-parity for the file report`);
const enValuesOf = enValues.get(file);
let marked = 0;
let identical = 0;
for (const { key, value, marked: isMarked, same } of readCatalog(locale, file, root)) {
if (isMarked) marked++;
else if (enValuesOf(key).has(value) && !isExcused(value, same, locale)) identical++;
}
if (marked || identical) (counts[locale] ??= {})[file] = { marked, identical };
}
}
return counts;
}
/** The committed baseline. Throws when it is missing or not the expected shape. */
export function readBaseline(path = BASELINE) {
let parsed;
try {
parsed = JSON.parse(readFileSync(path, 'utf8'));
} catch (err) {
throw new Error(`${path} cannot be read: ${err.message}. Restore it from git before running the check again.`);
}
const isCount = (n) => Number.isInteger(n) && n >= 0;
const valid =
parsed !== null &&
typeof parsed === 'object' &&
!Array.isArray(parsed) &&
Object.values(parsed).every(
(files) =>
files !== null &&
typeof files === 'object' &&
Object.values(files).every(
(entry) => entry !== null && typeof entry === 'object' && isCount(entry.marked) && isCount(entry.identical),
),
);
if (!valid) throw new Error(`${path} is not a { locale: { file: { marked, identical } } } map of whole numbers`);
return parsed;
}
const ZERO = { marked: 0, identical: 0 };
/** Every count above its baseline entry, and how many entries could come down. */
export function compare(counts, baseline) {
const grown = [];
let lowerable = 0;
for (const [locale, files] of Object.entries(counts)) {
for (const [file, now] of Object.entries(files)) {
const allowed = baseline[locale]?.[file] ?? ZERO;
for (const kind of ['marked', 'identical']) {
if (now[kind] > allowed[kind]) grown.push({ locale, file, kind, now: now[kind], allowed: allowed[kind] });
}
}
}
for (const [locale, files] of Object.entries(baseline)) {
for (const [file, allowed] of Object.entries(files)) {
const now = counts[locale]?.[file] ?? ZERO;
if (now.marked < allowed.marked || now.identical < allowed.identical) lowerable++;
}
}
return { grown, lowerable };
}
/** The baseline lowered to `counts`: never raised, zero entries dropped, sorted. */
export function lowered(counts, baseline) {
const out = {};
for (const locale of Object.keys(baseline).sort()) {
for (const file of Object.keys(baseline[locale]).sort()) {
const allowed = baseline[locale][file];
const now = counts[locale]?.[file] ?? ZERO;
const entry = {
marked: Math.min(allowed.marked, now.marked),
identical: Math.min(allowed.identical, now.identical),
};
if (entry.marked || entry.identical) (out[locale] ??= {})[file] = entry;
}
}
return out;
}
/** The baseline as committed: one line per file, so a diff shows which counts came down. */
export function serialize(baseline) {
const locales = Object.keys(baseline).map((locale) => {
const files = Object.entries(baseline[locale]).map(
([file, { marked, identical }]) =>
` ${JSON.stringify(file)}: { "marked": ${marked}, "identical": ${identical} }`,
);
return ` ${JSON.stringify(locale)}: {\n${files.join(',\n')}\n }`;
});
return `{\n${locales.join(',\n')}\n}\n`;
}
export function formatGrown(grown) {
return grown.map(
({ locale, file, kind, now, allowed }) =>
` ${locale}/${file}: ${now} ${kind === 'marked' ? 'marked en-fallback' : 'unmarked English copies'}, ` +
`the baseline allows ${allowed}`,
);
}
const total = (map, kind) =>
Object.values(map)
.flatMap((files) => Object.values(files))
.reduce((sum, e) => sum + e[kind], 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 {
const counts = countUntranslated();
let baseline = readBaseline();
if (process.argv.includes('--update')) {
baseline = lowered(counts, baseline);
writeFileSync(BASELINE, serialize(baseline));
}
const { grown, lowerable } = compare(counts, baseline);
if (grown.length) {
console.error('Untranslated strings grew past scripts/i18n-untranslated-baseline.json:');
for (const line of formatGrown(grown)) console.error(line);
console.error('Translate the new strings (shared/CLAUDE.md: an English placeholder is not acceptable).');
}
if (lowerable && !process.argv.includes('--update')) {
console.log(
`${lowerable} baseline entr${lowerable === 1 ? 'y is' : 'ies are'} above today's count: run with --update to lower.`,
);
}
console.log(
`untranslated: ${total(counts, 'marked')} marked en-fallback, ${total(counts, 'identical')} unmarked English copies`,
);
if (grown.length) process.exit(1);
} catch (err) {
console.error(`FAIL ${err.message}`);
process.exit(1);
}
}
@@ -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
}
+21
View File
@@ -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][] };
+206
View File
@@ -0,0 +1,206 @@
#!/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
* custom a z.custom() or z.instanceof(), a predicate rather than a shape
*
* 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` (src/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.
* An open spot counts once per path it sits at: one z.unknown() instance
* reused across four fields is four open fields. The same `kind@path` is
* listed once, so both sides of an intersection naming one field do not
* count it twice. `ancestors` only stops the walk from looping through a
* recursive z.lazy().
*/
export function openShapes(root) {
const found = new Set();
const ancestors = new Set();
const visit = (schema, path) => {
const def = schema?._zod?.def;
if (!def || ancestors.has(schema)) return;
ancestors.add(schema);
try {
walk(def, schema, path);
} finally {
ancestors.delete(schema);
}
};
const walk = (def, schema, path) => {
switch (def.type) {
case 'unknown':
case 'any':
found.add(`unknown@${path}`);
return;
case 'custom':
// z.custom() and z.instanceof(): a predicate, not a shape, so nothing
// about the value is described.
found.add(`custom@${path}`);
return;
case 'record':
if (isOpenLeaf(def.valueType)) {
found.add(`record@${path}`);
return;
}
visit(def.valueType, `${path}{}`);
return;
case 'map':
visit(def.keyType, `${path}<key>`);
visit(def.valueType, `${path}{}`);
return;
case 'object':
if (isOpenLeaf(def.catchall)) found.add(`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(schema._zod.innerType ?? def.getter(), path);
return;
default:
break;
}
// Wrappers and combinators: optional, nullable, default, catch, pipe,
// array, set, tuple, union, intersection, readonly and the like.
for (const key of ['innerType', 'in', 'out', 'element', 'valueType', '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;
}
}
+9
View File
@@ -1,4 +1,6 @@
import {
asLlmVision,
LLM_VISION_MODES,
adminUserCreateRequestSchema,
adminUserUpdateRequestSchema,
adminPermissionsRequestSchema,
@@ -106,6 +108,13 @@ describe('adminAddonUpdateRequestSchema', () => {
});
});
describe('asLlmVision', () => {
it('keeps the three modes and reads anything else as auto', () => {
for (const mode of LLM_VISION_MODES) expect(asLlmVision(mode)).toBe(mode);
for (const other of [undefined, null, '', 'ON', true, false, 1]) expect(asLlmVision(other)).toBe('auto');
});
});
describe('adminCollabFeaturesRequestSchema', () => {
it('accepts a single computed key', () => {
expect(adminCollabFeaturesRequestSchema.safeParse({ chat: false }).success).toBe(true);
+60
View File
@@ -54,6 +54,28 @@ export const adminFeatureToggleRequestSchema = z.object({
});
export type AdminFeatureToggleRequest = z.infer<typeof adminFeatureToggleRequestSchema>;
/** What a feature toggle answers: the flag as it is stored now. */
export const adminFeatureToggleResponseSchema = z.object({
enabled: z.boolean(),
});
export type AdminFeatureToggleResponse = z.infer<typeof adminFeatureToggleResponseSchema>;
/**
* PUT /api/admin/google-quota (#1582): the most Google API calls TREK may make
* in one UTC day. Null or 0 removes the ceiling.
*/
export const googleQuotaUpdateRequestSchema = z.object({
daily_limit: z.number().int().min(0).max(10_000_000).nullable(),
});
export type GoogleQuotaUpdateRequest = z.infer<typeof googleQuotaUpdateRequestSchema>;
/** The ceiling as stored, today's count, and whether Google is paused until tomorrow. */
export interface GoogleQuotaStatus {
daily_limit: number | null;
used_today: number;
exhausted: boolean;
}
// Shared by all six packing-template create/update routes. `name` is optional so
// the service's 'Name is required' / 'Category name is required' / 'Item name is
// required' 400s stay the contract, and so the update routes keep treating a
@@ -80,6 +102,30 @@ export const adminAddonUpdateRequestSchema = z.object({
});
export type AdminAddonUpdateRequest = z.infer<typeof adminAddonUpdateRequestSchema>;
/**
* Whether the AI Parsing model is handed a photo, stored as `vision` on that
* addon's config. `auto` asks a local Ollama server what the model can do and
* means no for a cloud provider; `on` and `off` are the admin's word.
*/
export const LLM_VISION_MODES = ['auto', 'on', 'off'] as const;
export type LlmVision = (typeof LLM_VISION_MODES)[number];
/**
* The photos handed to a model that reads images. HEIC is not here: no provider
* TREK talks to reads it, and a browser picking from the camera roll hands over
* a JPEG anyway.
*/
export const LLM_PHOTO_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp'] as const;
/** GET /api/llm/capabilities: what the caller's AI model can be handed. */
export const llmCapabilitiesResponseSchema = z.object({ images: z.boolean() });
export type LlmCapabilitiesResponse = z.infer<typeof llmCapabilitiesResponseSchema>;
/** A stored or submitted value as a mode; anything else, a missing value included, is `auto`. */
export function asLlmVision(value: unknown): LlmVision {
return (LLM_VISION_MODES as readonly unknown[]).includes(value) ? (value as LlmVision) : 'auto';
}
// Fully partial — the client PUTs one computed key at a time.
export const adminCollabFeaturesRequestSchema = z.object({
chat: z.boolean().optional(),
@@ -95,6 +141,20 @@ export type AdminCollabFeaturesRequest = z.infer<typeof adminCollabFeaturesReque
export const adminNotificationPreferencesRequestSchema = z.record(z.string(), z.record(z.string(), z.boolean()));
export type AdminNotificationPreferencesRequest = z.infer<typeof adminNotificationPreferencesRequestSchema>;
/**
* What a user's notification cell starts as, set by the admin for the whole
* instance (#1536): `on` (the default), `off` (the user may still turn it on)
* or `blocked` (off for everyone, and the user cannot turn it on).
*/
export const NOTIFICATION_DEFAULTS = ['on', 'off', 'blocked'] as const;
export type NotificationDefault = (typeof NOTIFICATION_DEFAULTS)[number];
/** PUT /api/admin/notification-preferences/defaults: event → channel → default. Cells left out keep theirs. */
export const notificationDefaultsUpdateRequestSchema = z.object({
defaults: z.record(z.string().max(64), z.record(z.string().max(64), z.enum(NOTIFICATION_DEFAULTS))),
});
export type NotificationDefaultsUpdateRequest = z.infer<typeof notificationDefaultsUpdateRequestSchema>;
// Heterogeneous values, and `null` is meaningful — SettingsService treats it as
// "reset to the built-in default". z.record also rejects arrays and null bodies,
// preserving the route's object-only guard.
+168
View File
@@ -0,0 +1,168 @@
import {
aiAdminSettingsSchema,
aiApiKeyConnectRequestSchema,
aiChatgptFinishRequestSchema,
aiInstanceConnectionRequestSchema,
aiModelInfoSchema,
aiOpenrouterStartRequestSchema,
aiPrivacyAckRequestSchema,
aiRetentionSchema,
aiStatusResponseSchema,
} from './ai-connections.schema';
import { describe, expect, it } from 'vitest';
describe('aiRetentionSchema', () => {
it('keeps chats for a number of days, or forever as its own mode', () => {
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 90 }).success).toBe(true);
expect(aiRetentionSchema.safeParse({ mode: 'forever' }).success).toBe(true);
});
it('has no sentinel day count', () => {
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 0 }).success).toBe(false);
expect(aiRetentionSchema.safeParse({ mode: 'days', days: -1 }).success).toBe(false);
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 3651 }).success).toBe(false);
});
});
describe('aiApiKeyConnectRequestSchema', () => {
it('takes a key for a cloud provider', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'anthropic', apiKey: 'sk-ant-api03-abcdef' }).success).toBe(
true,
);
});
it('never lets a user connect ChatGPT by key or a server of their own', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'chatgpt', apiKey: 'abcdefghij' }).success).toBe(false);
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'custom', apiKey: 'abcdefghij' }).success).toBe(false);
expect(
aiApiKeyConnectRequestSchema.safeParse({ kind: 'openai', apiKey: 'sk-abcdefgh', baseUrl: 'http://10.0.0.2' })
.success,
).toBe(false);
});
it('refuses a key too short to be one', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'gemini', apiKey: 'AIza' }).success).toBe(false);
});
});
describe('aiInstanceConnectionRequestSchema', () => {
it('takes an own server with a base URL and a model, the key optional', () => {
expect(
aiInstanceConnectionRequestSchema.safeParse({
kind: 'custom',
baseUrl: 'http://ollama:11434/v1',
model: 'qwen3:8b',
}).success,
).toBe(true);
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'http://ollama:11434' }).success,
).toBe(false);
});
it('refuses a base URL that is not http(s)', () => {
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'javascript:alert(1)', model: 'm' })
.success,
).toBe(false);
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'file:///etc/passwd', model: 'm' })
.success,
).toBe(false);
});
it('gives a cloud key no base URL to redirect it to', () => {
expect(aiInstanceConnectionRequestSchema.safeParse({ kind: 'openrouter', apiKey: 'sk-or-v1-abc' }).success).toBe(
true,
);
expect(
aiInstanceConnectionRequestSchema.safeParse({
kind: 'anthropic',
apiKey: 'sk-ant-api03-abcdef',
baseUrl: 'https://evil.example',
}).success,
).toBe(false);
});
it('never shares a ChatGPT plan as the instance connection', () => {
expect(aiInstanceConnectionRequestSchema.safeParse({ kind: 'chatgpt', apiKey: 'abcdefghij' }).success).toBe(false);
});
});
describe('aiChatgptFinishRequestSchema', () => {
it('needs the flow id it was started with', () => {
const pastedUrl = 'http://127.0.0.1:1455/auth/callback?code=c&state=s';
expect(
aiChatgptFinishRequestSchema.safeParse({ flowId: '0d6c1f0e-2c3b-4a5d-8e9f-1a2b3c4d5e6f', pastedUrl }).success,
).toBe(true);
expect(aiChatgptFinishRequestSchema.safeParse({ flowId: 'flow-1', pastedUrl }).success).toBe(false);
});
});
describe('aiOpenrouterStartRequestSchema', () => {
it('takes only the scope, never a callback address', () => {
expect(aiOpenrouterStartRequestSchema.safeParse({ scope: 'user' }).success).toBe(true);
expect(
aiOpenrouterStartRequestSchema.safeParse({ scope: 'user', callbackUrl: 'https://evil.example' }).success,
).toBe(false);
});
});
describe('aiAdminSettingsSchema', () => {
it('takes the policy, the daily limit and the retention', () => {
expect(
aiAdminSettingsSchema.safeParse({
policy: 'instance_or_user',
dailyTurns: 50,
retention: { mode: 'days', days: 90 },
}).success,
).toBe(true);
expect(
aiAdminSettingsSchema.safeParse({ policy: 'instance', dailyTurns: 0, retention: { mode: 'forever' } }).success,
).toBe(false);
});
});
describe('aiStatusResponseSchema', () => {
it('describes a user on the instance connection with a quota', () => {
expect(
aiStatusResponseSchema.safeParse({
available: true,
policy: 'instance_or_user',
canConnectOwn: true,
effective: {
source: 'instance',
kind: 'anthropic',
model: 'claude-sonnet-4-5',
host: 'api.anthropic.com',
paidBy: 'instance',
},
own: null,
instance: { kind: 'anthropic', model: 'claude-sonnet-4-5', host: 'api.anthropic.com' },
quota: { used: 3, limit: 50 },
privacyAcked: false,
retention: { mode: 'days', days: 90 },
openrouterOAuth: true,
}).success,
).toBe(true);
});
});
describe('the Studio page image', () => {
it('AIVIS-001: a model may say whether it reads images, and a list that cannot say leaves it out', () => {
expect(aiModelInfoSchema.parse({ id: 'm', label: 'm', supportsTools: true, supportsImages: false })).toEqual({
id: 'm',
label: 'm',
supportsTools: true,
supportsImages: false,
});
expect(aiModelInfoSchema.safeParse({ id: 'm', label: 'm', supportsTools: true }).success).toBe(true);
});
it('AIVIS-002: the acknowledgement of page images is its own scope; no other scope exists', () => {
const ack = { kind: 'anthropic', host: 'api.anthropic.com' };
expect(aiPrivacyAckRequestSchema.safeParse(ack).success).toBe(true);
expect(aiPrivacyAckRequestSchema.safeParse({ ...ack, scope: 'studio_images' }).success).toBe(true);
expect(aiPrivacyAckRequestSchema.safeParse({ ...ack, scope: 'everything' }).success).toBe(false);
});
});
+226
View File
@@ -0,0 +1,226 @@
import { z } from 'zod';
/**
* AI connections contract for /api/ai (a user's own provider) and /api/admin/ai
* (the connection the instance provides for everyone, plus the assistant's
* admin settings).
*
* A connection is a provider kind, a model and a sealed credential. The
* credential never leaves the server: every view carries a `hint` (the last
* characters of a key, or the e-mail of a ChatGPT account) instead. Two kinds
* are bound to one side: `chatgpt` is a personal plan and never shared as the
* instance connection, `custom` reaches an arbitrary base URL and is admin-only
* (#1772). The server and the database both refuse the other combination.
*/
export const aiConnectionKindSchema = z.enum(['anthropic', 'openai', 'gemini', 'openrouter', 'chatgpt', 'custom']);
export type AiConnectionKind = z.infer<typeof aiConnectionKindSchema>;
/** The kinds a pasted API key can belong to. */
export const aiApiKeyKindSchema = z.enum(['anthropic', 'openai', 'gemini', 'openrouter']);
export type AiApiKeyKind = z.infer<typeof aiApiKeyKindSchema>;
/**
* Who provides the connection: `instance` only the admin's, `instance_or_user`
* the admin's unless a user connects their own, `user` everyone their own.
*/
export const aiPolicySchema = z.enum(['instance', 'instance_or_user', 'user']);
export type AiPolicy = z.infer<typeof aiPolicySchema>;
/** How long assistant chats are kept. Keeping them forever is its own mode, not a day count. */
export const aiRetentionSchema = z.discriminatedUnion('mode', [
z.object({ mode: z.literal('days'), days: z.number().int().min(1).max(3650) }),
z.object({ mode: z.literal('forever') }),
]);
export type AiRetention = z.infer<typeof aiRetentionSchema>;
export const aiConnectionScopeSchema = z.enum(['instance', 'user']);
export type AiConnectionScope = z.infer<typeof aiConnectionScopeSchema>;
export const aiConnectionStatusSchema = z.enum(['ok', 'needs_reauth', 'signed_out', 'error']);
export type AiConnectionStatus = z.infer<typeof aiConnectionStatusSchema>;
/** One model a connection offers. Only models that can call tools are listed for the assistant. */
export const aiModelInfoSchema = z.object({
id: z.string(),
label: z.string(),
supportsTools: z.boolean(),
free: z.boolean().optional(),
// The one a new connection starts on: the newest stable model of a capable line. Listed first.
recommended: z.boolean().optional(),
// Whether the model reads images (the Studio assistant's page image); left out where the list cannot say.
supportsImages: z.boolean().optional(),
});
export type AiModelInfo = z.infer<typeof aiModelInfoSchema>;
/** A stored connection as the client sees it, without its credential. */
export const aiConnectionViewSchema = z.object({
scope: aiConnectionScopeSchema,
kind: aiConnectionKindSchema,
model: z.string(),
// "…a1b2" for a key, the account e-mail for ChatGPT; never the secret itself.
hint: z.string().nullable(),
status: aiConnectionStatusSchema,
// The provider host the conversation goes to, named in the privacy notice.
host: z.string(),
});
export type AiConnectionView = z.infer<typeof aiConnectionViewSchema>;
// ── User: /api/ai ───────────────────────────────────────────────────────────
/** GET /api/ai/status: whether the assistant can run for this user, and on whose connection. */
export const aiStatusResponseSchema = z.object({
// False whenever no usable connection exists under the policy (fail-closed).
available: z.boolean(),
policy: aiPolicySchema,
// policy !== 'instance' and not the demo user.
canConnectOwn: z.boolean(),
effective: z
.object({
source: aiConnectionScopeSchema,
kind: aiConnectionKindSchema,
model: z.string(),
host: z.string(),
paidBy: aiConnectionScopeSchema,
})
.nullable(),
own: aiConnectionViewSchema.nullable(),
instance: z.object({ kind: aiConnectionKindSchema, model: z.string(), host: z.string() }).nullable(),
// Today's turns against the daily limit, only while the instance pays.
quota: z.object({ used: z.number().int(), limit: z.number().int() }).nullable(),
// Whether the user acknowledged that the effective kind@host receives their data.
privacyAcked: z.boolean(),
// Whether the user also let kind@host receive images of their Studio pages, with their own photos on them.
studioImagesAcked: z.boolean().optional(),
// Whether the model the effective connection runs on reads images (its name says so and no provider refused one for
// it since the server started), so a Studio page can go as a picture.
studioImages: z.boolean().optional(),
retention: aiRetentionSchema,
// OpenRouter's OAuth needs an https callback; without one the client offers the key field instead.
openrouterOAuth: z.boolean(),
});
export type AiStatusResponse = z.infer<typeof aiStatusResponseSchema>;
/** PUT /api/ai/connection: saving tests the key against the provider's model list first. */
export const aiApiKeyConnectRequestSchema = z
.object({
kind: aiApiKeyKindSchema,
apiKey: z.string().min(8).max(400),
model: z.string().max(200).optional(),
})
.strict();
export type AiApiKeyConnectRequest = z.infer<typeof aiApiKeyConnectRequestSchema>;
/** PATCH /api/ai/connection/model */
export const aiModelUpdateRequestSchema = z.object({ model: z.string().min(1).max(200) }).strict();
export type AiModelUpdateRequest = z.infer<typeof aiModelUpdateRequestSchema>;
/** POST /api/ai/connect/chatgpt/finish: the loopback address the browser landed on after sign-in. */
export const aiChatgptFinishRequestSchema = z
.object({
flowId: z.uuid(),
pastedUrl: z.string().max(4096),
})
.strict();
export type AiChatgptFinishRequest = z.infer<typeof aiChatgptFinishRequestSchema>;
/** POST /api/ai/connect/openrouter/start and /api/admin/ai/connect/openrouter/start */
export const aiOpenrouterStartRequestSchema = z.object({ scope: aiConnectionScopeSchema }).strict();
export type AiOpenrouterStartRequest = z.infer<typeof aiOpenrouterStartRequestSchema>;
/** POST /api/ai/connect/openrouter/finish */
export const aiOpenrouterFinishRequestSchema = z
.object({
flowId: z.uuid(),
code: z.string().min(1).max(512),
})
.strict();
export type AiOpenrouterFinishRequest = z.infer<typeof aiOpenrouterFinishRequestSchema>;
/** The answer of every connect/<provider>/start: where to send the browser, and the flow to finish. */
export const aiAuthStartResponseSchema = z.object({
flowId: z.uuid(),
authorizeUrl: z.url(),
expiresAt: z.string(),
});
export type AiAuthStartResponse = z.infer<typeof aiAuthStartResponseSchema>;
/** GET /api/ai/models, GET /api/admin/ai/models */
export const aiModelListResponseSchema = z.object({ models: z.array(aiModelInfoSchema) });
export type AiModelListResponse = z.infer<typeof aiModelListResponseSchema>;
/**
* POST /api/ai/privacy-ack: the user saw that kind@host receives their
* messages, or (`scope: 'studio_images'`) also images of their Studio pages.
*/
export const aiPrivacyAckRequestSchema = z
.object({
kind: aiConnectionKindSchema,
host: z.string().max(253),
scope: z.enum(['studio_images']).optional(),
})
.strict();
export type AiPrivacyAckRequest = z.infer<typeof aiPrivacyAckRequestSchema>;
// ── Admin: /api/admin/ai ────────────────────────────────────────────────────
// z.url() alone would accept javascript: and file:.
const httpUrl = z.url({ protocol: /^https?$/ });
const instanceApiKeyConnection = <K extends AiApiKeyKind>(kind: K) =>
z
.object({
kind: z.literal(kind),
apiKey: z.string().min(8).max(400),
model: z.string().max(200).optional(),
})
.strict();
/** PUT /api/admin/ai/connection: a cloud key, or an OpenAI-compatible server of the admin's own. */
export const aiInstanceConnectionRequestSchema = z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('custom'),
baseUrl: httpUrl.max(500),
apiKey: z.string().max(400).optional(),
model: z.string().min(1).max(200),
})
.strict(),
instanceApiKeyConnection('anthropic'),
instanceApiKeyConnection('openai'),
instanceApiKeyConnection('gemini'),
instanceApiKeyConnection('openrouter'),
]);
export type AiInstanceConnectionRequest = z.infer<typeof aiInstanceConnectionRequestSchema>;
/** What the AI parsing addon is configured with, offered to prefill the instance connection. */
export const aiParsingPrefillSchema = z.object({
kind: aiConnectionKindSchema,
baseUrl: z.string().nullable(),
model: z.string(),
});
export type AiParsingPrefill = z.infer<typeof aiParsingPrefillSchema>;
/** GET /api/admin/ai/connection */
export const aiAdminConnectionResponseSchema = z.object({
connection: aiConnectionViewSchema.extend({ baseUrl: z.string().nullable() }).nullable(),
// Only while no instance connection exists and AI parsing is configured.
prefill: aiParsingPrefillSchema.nullable(),
});
export type AiAdminConnectionResponse = z.infer<typeof aiAdminConnectionResponseSchema>;
/** GET and PUT /api/admin/ai/settings */
export const aiAdminSettingsSchema = z
.object({
policy: aiPolicySchema,
dailyTurns: z.number().int().min(1).max(10000),
retention: aiRetentionSchema,
/**
* Whether the assistant may search the web, through the provider's own
* search (ChatGPT, Anthropic, OpenRouter); left out by older clients, it
* stays on.
*/
webSearch: z.boolean().default(true),
})
.strict();
export type AiAdminSettings = z.infer<typeof aiAdminSettingsSchema>;
@@ -3,11 +3,47 @@ import {
assignmentEndDayRequestSchema,
assignmentMoveRequestSchema,
assignmentParticipantsRequestSchema,
assignmentSchema,
assignmentTransportRequestSchema,
} from './assignment.schema';
import { describe, it, expect } from 'vitest';
describe('assignment Tours read-model merge', () => {
const ordinary = { id: 1, day_id: 2, place_id: 3, order_index: 0, place: { id: 3, name: 'Place' } };
it('keeps ordinary and legacy track places non-Tours without a facet identity', () => {
expect(assignmentSchema.parse(ordinary).tour_place_id).toBeUndefined();
const legacy = assignmentSchema.parse({ ...ordinary, tour_place_id: null, tour_route_geometry: null });
expect(legacy.tour_place_id).toBeNull();
expect(legacy.tour_route_geometry).toBeNull();
});
it('preserves nullable Tour fields, exclusion and incoming/outgoing segment modes', () => {
const fields = {
tour_place_id: 3,
tour_route_geometry: '[[48,11],[49,12]]',
route_excluded: true,
leg_transport_mode: 'walking',
incoming_leg_transport_mode: 'cycling',
};
expect(assignmentSchema.parse({ ...ordinary, ...fields })).toMatchObject(fields);
// MDT-02: the stage of a multi-day tour the day holds, null for the whole tour.
expect(assignmentSchema.parse({ ...ordinary, tour_stage_key: 'stop-1xx' }).tour_stage_key).toBe('stop-1xx');
expect(assignmentSchema.parse({ ...ordinary, tour_stage_key: null }).tour_stage_key).toBeNull();
expect(assignmentSchema.parse({ ...ordinary, tour_place_id: null, tour_route_geometry: null })).toMatchObject({
tour_place_id: null,
tour_route_geometry: null,
});
});
it('does not copy read-only joined Tours fields into create or move requests', () => {
const joined = { tour_place_id: 3, tour_route_geometry: '[[48,11],[49,12]]' };
expect(assignmentCreateRequestSchema.parse({ place_id: 3, ...joined })).toEqual({ place_id: 3 });
expect(assignmentMoveRequestSchema.parse({ new_day_id: 2, ...joined })).toEqual({ new_day_id: 2 });
});
});
it('requires a boolean for an explicit day end', () => {
expect(assignmentEndDayRequestSchema.parse({ end_day: true })).toEqual({ end_day: true });
expect(assignmentEndDayRequestSchema.parse({ end_day: false })).toEqual({ end_day: false });
@@ -22,6 +58,16 @@ describe('assignmentCreateRequestSchema', () => {
expect(assignmentCreateRequestSchema.safeParse({ place_id: '2', notes: null }).success).toBe(true);
expect(assignmentCreateRequestSchema.safeParse({}).success).toBe(false);
});
it('MDT-SH-012: takes the stage of a multi-day tour by the key of the stop it starts at', () => {
expect(assignmentCreateRequestSchema.parse({ place_id: 2, tour_stage_key: 'stop-1xx' })).toEqual({
place_id: 2,
tour_stage_key: 'stop-1xx',
});
for (const tour_stage_key of ['', 'short', 'not a key!', null, 3]) {
expect(assignmentCreateRequestSchema.safeParse({ place_id: 2, tour_stage_key }).success).toBe(false);
}
});
});
describe('assignmentMoveRequestSchema', () => {
@@ -1,4 +1,5 @@
import { assignmentPlaceSchema } from '../place/place.schema';
import { stationKeySchema } from '../tours/tours.schema';
import { z } from 'zod';
@@ -48,11 +49,20 @@ export const assignmentSchema = z.object({
// not a place (booking arrival / morning hotel). null = inherit the day default.
// Inert when the previous timeline element is a place.
incoming_leg_transport_mode: z.string().nullable().optional(),
// Kept on the day and on the map, but not part of the day's route (#2532).
route_excluded: z.boolean().optional(),
// The lodging booking that put this stop on the day, when one did. The day
// planner already shows that booking as its own overnight block, so it hides
// this row and leaves it to road trip mode, which is the view that needs the
// hotel in the driving chain. Null for every stop a traveller placed.
accommodation_id: z.number().nullable().optional(),
tour_place_id: z.number().nullable().optional(),
tour_route_geometry: z.string().nullable().optional(),
/**
* MDT-02: the stage of a multi-day tour this day holds, by the key of the
* stop the stage starts at; null where the day holds the whole tour or a place.
*/
tour_stage_key: z.string().nullable().optional(),
participants: z.array(assignmentParticipantSchema).optional(),
created_at: z.string().optional(),
place: assignmentPlaceSchema,
@@ -62,6 +72,12 @@ export type Assignment = z.infer<typeof assignmentSchema>;
export const assignmentCreateRequestSchema = z.object({
place_id: z.union([z.number(), z.string()]),
notes: z.string().nullable().optional(),
/**
* MDT-02: puts one stage of a multi-day tour on the day instead of the whole
* tour, by the key of the stop the stage starts at (the tour list's
* `stage_stops`). A stage is on one day at most.
*/
tour_stage_key: stationKeySchema.optional(),
});
export type AssignmentCreateRequest = z.infer<typeof assignmentCreateRequestSchema>;
@@ -113,6 +129,12 @@ export const assignmentTransportRequestSchema = z.object({
});
export type AssignmentTransportRequest = z.infer<typeof assignmentTransportRequestSchema>;
/** Take a stop out of the day's route, or put it back (#2532). */
export const assignmentRouteRequestSchema = z.object({
excluded: z.boolean(),
});
export type AssignmentRouteRequest = z.infer<typeof assignmentRouteRequestSchema>;
export const assignmentParticipantsRequestSchema = z.object({
user_ids: z.array(z.number()),
});
@@ -0,0 +1,44 @@
data: {"type":"start","messageId":"msg-12"}
data: {"type":"tool-output-available","toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","output":{"tour":{"place_id":77,"name":"Ridge walk"}}}
data: {"type":"data-trek-applied","data":{"toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","entity":"tour","ids":[77],"dayId":32,"undoUntil":"2026-06-11T09:15:00Z"}}
data: {"type":"data-trek-card","data":{"toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","card":{"kind":"tourRoute"}}}
data: {"type":"start-step"}
data: {"type":"tool-input-start","toolCallId":"toolu_02","toolName":"list_tours"}
data: {"type":"tool-input-available","toolCallId":"toolu_02","toolName":"list_tours","input":{}}
data: {"type":"tool-output-available","toolCallId":"toolu_02","output":{"tours":[{"place_id":77,"name":"Ridge walk"}]}}
data: {"type":"data-trek-card","data":{"toolCallId":"toolu_02","card":{"kind":"tourList"}}}
data: {"type":"finish-step"}
data: {"type":"start-step"}
data: {"type":"text-start","id":"txt-0"}
data: {"type":"text-delta","id":"txt-0","delta":"The ridge walk is on Friday now. "}
data: {"type":"text-delta","id":"txt-0","delta":"A lake loop would fit on Saturday."}
data: {"type":"text-end","id":"txt-0"}
data: {"type":"tool-input-start","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolName":"create_hike"}
data: {"type":"tool-input-available","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolName":"create_hike","input":{"name":"Lake loop","round_trip":true}}
data: {"type":"tool-approval-request","approvalId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"}
data: {"type":"data-trek-change","data":{"toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","verbKey":"addTour","subject":"Lake loop","rows":[{"op":"add","labelKey":"route","before":null,"after":"Car park → Lake → Car park"}],"dayId":null,"placeIds":[],"undoable":true,"card":{"kind":"tourRoute"}}}
data: {"type":"data-trek-quota","data":{"used":4,"limit":50}}
data: {"type":"finish","finishReason":"tool-calls"}
data: [DONE]
@@ -0,0 +1,38 @@
data: {"type":"start","messageId":"msg-12"}
data: {"type":"data-trek-thread","data":{"threadId":7,"title":"Fit the Golden Pavilion into Friday"}}
data: {"type":"start-step"}
data: {"type":"tool-input-start","toolCallId":"toolu_01","toolName":"get_trip_summary"}
data: {"type":"tool-input-available","toolCallId":"toolu_01","toolName":"get_trip_summary","input":{}}
data: {"type":"tool-output-available","toolCallId":"toolu_01","output":{"title":"Kyoto in June","days":[{"id":31,"date":"2026-06-11","places":3},{"id":32,"date":"2026-06-12","places":1}]}}
data: {"type":"finish-step"}
data: {"type":"start-step"}
data: {"type":"text-start","id":"txt-0"}
data: {"type":"text-delta","id":"txt-0","delta":"Friday has room in the afternoon. "}
data: {"type":"text-delta","id":"txt-0","delta":"I would add Kinkaku-ji there."}
data: {"type":"text-end","id":"txt-0"}
data: {"type":"tool-input-start","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolName":"create_and_assign_place"}
data: {"type":"tool-input-available","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolName":"create_and_assign_place","input":{"dayId":32,"name":"Kinkaku-ji","address":"1 Kinkakujicho, Kita Ward, Kyoto","lat":35.0394,"lng":135.7292}}
data: {"type":"tool-approval-request","approvalId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40"}
data: {"type":"data-trek-change","data":{"toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","verbKey":"addPlaceToDay","subject":"Kinkaku-ji","rows":[{"op":"add","labelKey":"day","before":null,"after":"Day 2, Fri 12 Jun"},{"op":"add","labelKey":"address","before":null,"after":"1 Kinkakujicho, Kita Ward, Kyoto"}],"dayId":32,"placeIds":[],"undoable":true}}
data: {"type":"data-trek-quota","data":{"used":3,"limit":50}}
data: {"type":"finish","finishReason":"tool-calls"}
data: [DONE]
@@ -0,0 +1,34 @@
import {
assistantAttachmentIdSchema,
assistantKeepFileArgsSchema,
assistantReadAttachedFileArgsSchema,
} from './assistant-attachments.schema';
import { describe, expect, it } from 'vitest';
const ID = '0b7c2f0e-6f6d-4a8e-9b1a-3d2c1e0f9a87';
describe('assistant attachments contract', () => {
it('takes an attachment only by a uuid, never a path or a number', () => {
expect(assistantAttachmentIdSchema.safeParse(ID).success).toBe(true);
for (const bad of ['../x', '42', '', 42, null]) {
expect(assistantAttachmentIdSchema.safeParse(bad).success).toBe(false);
}
});
it('reads the model arguments of read_attached_file and drops what the server sets itself', () => {
expect(assistantReadAttachedFileArgsSchema.parse({ attachmentId: ID, name: 'x.pdf' })).toEqual({
attachmentId: ID,
});
expect(assistantReadAttachedFileArgsSchema.safeParse({}).success).toBe(false);
});
it('keeps a file with plain ids of the trip, never a string or a negative id, and a short description', () => {
const kept = { attachmentId: ID, reservation_id: 5, budget_item_id: 7, place_id: 9, description: 'Airbnb' };
expect(assistantKeepFileArgsSchema.parse({ ...kept, name: 'x.pdf' })).toEqual(kept);
expect(assistantKeepFileArgsSchema.parse({ attachmentId: ID })).toEqual({ attachmentId: ID });
for (const bad of [{ reservation_id: '5' }, { budget_item_id: -1 }, { description: 'x'.repeat(1001) }]) {
expect(assistantKeepFileArgsSchema.safeParse({ attachmentId: ID, ...bad }).success).toBe(false);
}
});
});
@@ -0,0 +1,40 @@
import { idSchema } from '../common/primitives.schema';
import { fileUpdateRequestSchema } from '../file/file.schema';
import { z } from 'zod';
/**
* A file the user attached in the trip chat, as the conversation knows it.
*
* The server keeps the file with the thread under a random id, which the
* message's `attachment` part carries. The id never reaches anything but the
* thread it was attached in: every read answers an id of another thread or
* another user the way it answers one that does not exist.
*/
export const assistantAttachmentIdSchema = z.uuid();
export type AssistantAttachmentId = z.infer<typeof assistantAttachmentIdSchema>;
/**
* What the model calls `read_attached_file` with: the attachment, by the id
* the user's message names. The server adds the file's name and where its
* text would go to the held call before the user sees it; those are no input.
*/
export const assistantReadAttachedFileArgsSchema = z.object({
attachmentId: assistantAttachmentIdSchema,
});
export type AssistantReadAttachedFileArgs = z.infer<typeof assistantReadAttachedFileArgsSchema>;
/**
* What the model calls `keep_attached_file` with: the attachment, and what
* of the trip the kept file is attached to, the fields a trip file's update
* takes (`fileUpdateRequestSchema`) as plain ids. Every id must name a row of
* the same trip; the server checks that when the user applies the change.
*/
export const assistantKeepFileArgsSchema = z.object({
attachmentId: assistantAttachmentIdSchema,
reservation_id: idSchema.optional(),
budget_item_id: idSchema.optional(),
place_id: idSchema.optional(),
description: fileUpdateRequestSchema.shape.description.unwrap().max(1000).optional(),
});
export type AssistantKeepFileArgs = z.infer<typeof assistantKeepFileArgsSchema>;
@@ -0,0 +1,61 @@
import {
ASSISTANT_JOURNEY_SURFACES,
assistantScopeKey,
assistantScopeSchema,
HOME_ASSISTANT_SCOPE,
} from './assistant-scope.schema';
import { assistantFocusSchema } from './assistant.schema';
import { describe, expect, it } from 'vitest';
describe('assistantScopeSchema', () => {
it('ASTSCOPE-001: is a trip or a journey, each by its own positive id', () => {
expect(assistantScopeSchema.parse({ kind: 'trip', tripId: 5 })).toEqual({ kind: 'trip', tripId: 5 });
expect(assistantScopeSchema.parse({ kind: 'journey', journeyId: 12 })).toEqual({ kind: 'journey', journeyId: 12 });
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 0 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'journey', tripId: 5 }).success).toBe(false);
});
it('ASTSCOPE-002: is never both and never anything else', () => {
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 5, journeyId: 12 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'collection', collectionId: 3 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({}).success).toBe(false);
});
it('ASTSCOPE-003: keys a trip and a journey with the same id apart', () => {
expect(assistantScopeKey({ kind: 'trip', tripId: 7 })).toBe('trip:7');
expect(assistantScopeKey({ kind: 'journey', journeyId: 7 })).toBe('journey:7');
});
it('ASTSCOPE-007: a journey names the page it is asked from, which never changes its key', () => {
const journal = { kind: 'journey', journeyId: 7, surface: 'journal' } as const;
expect(assistantScopeSchema.parse(journal)).toEqual(journal);
expect(assistantScopeSchema.safeParse({ ...journal, surface: 'planner' }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 7, surface: 'journal' }).success).toBe(false);
expect(assistantScopeKey(journal)).toBe(assistantScopeKey({ kind: 'journey', journeyId: 7, surface: 'studio' }));
expect(ASSISTANT_JOURNEY_SURFACES).toEqual(['studio', 'journal']);
});
it('ASTSCOPE-006: has a home scope that names no trip and no journey', () => {
expect(assistantScopeSchema.parse({ kind: 'home' })).toEqual(HOME_ASSISTANT_SCOPE);
expect(assistantScopeSchema.safeParse({ kind: 'home', tripId: 5 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'home', journeyId: 12 }).success).toBe(false);
expect(assistantScopeKey(HOME_ASSISTANT_SCOPE)).toBe('home');
});
});
describe('assistantFocusSchema in the Studio', () => {
it('ASTSCOPE-004: carries the page on screen and up to 30 selected elements, by their document ids', () => {
const focus = { spreadId: 'sp-ab12', elementIds: ['p-1', 'p-2'] };
expect(assistantFocusSchema.parse(focus)).toEqual(focus);
expect(assistantFocusSchema.safeParse({ spreadId: 'sp ab' }).success).toBe(false);
expect(assistantFocusSchema.safeParse({ spreadId: 'x'.repeat(41) }).success).toBe(false);
const many = Array.from({ length: 31 }, (_, i) => `p-${i}`);
expect(assistantFocusSchema.safeParse({ elementIds: many }).success).toBe(false);
});
it('ASTSCOPE-005: leaves the planner focus as it was', () => {
expect(assistantFocusSchema.parse({ dayId: 4, placeIds: [1] })).toEqual({ dayId: 4, placeIds: [1] });
expect(assistantFocusSchema.safeParse({ dayId: 4, page: 2 }).success).toBe(false);
});
});
@@ -0,0 +1,45 @@
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
* What an assistant conversation is about: a trip (the planner's chat), a
* journey (the chat in TREK Studio, which works on the journey's book) or no
* single one (`home`, the chat on the dashboard, Vacay, Atlas, collections and
* settings, which knows all of the user's trips and works on what belongs to
* none of them). A thread belongs to exactly one of them, and the tools a turn
* offers, the context it reads and the routes it is reached under follow from
* it: `/api/trips/:tripId/assistant`, `/api/journeys/:journeyId/assistant` and
* `/api/assistant`.
*/
/**
* The two pages a journey's conversation is held on: the book in TREK Studio,
* and the journal itself (its entries, photos and settings). They share the
* journey's threads; what a turn offers and what it is told follow the page.
*/
export const ASSISTANT_JOURNEY_SURFACES = ['studio', 'journal'] as const;
export const assistantJourneySurfaceSchema = z.enum(ASSISTANT_JOURNEY_SURFACES);
export type AssistantJourneySurface = z.infer<typeof assistantJourneySurfaceSchema>;
export const assistantScopeSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('trip'), tripId: idSchema }).strict(),
z
.object({
kind: z.literal('journey'),
journeyId: idSchema,
/** The page a request comes from; left out, the Studio's. Never part of the key: both pages keep one list. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict(),
z.object({ kind: z.literal('home') }).strict(),
]);
export type AssistantScope = z.infer<typeof assistantScopeSchema>;
/** The scope of the chat outside any one trip or journey. */
export const HOME_ASSISTANT_SCOPE: AssistantScope = { kind: 'home' };
/** The key a scope's conversations are kept under on a client: `trip:5`, `journey:12`, `home`. */
export function assistantScopeKey(scope: AssistantScope): string {
if (scope.kind === 'trip') return `trip:${scope.tripId}`;
return scope.kind === 'journey' ? `journey:${scope.journeyId}` : 'home';
}
@@ -0,0 +1,22 @@
import { assistantShareRequestSchema } from './assistant-share.schema';
import { describe, expect, it } from 'vitest';
describe('assistantShareRequestSchema', () => {
it('takes one to 5000 characters and trims them', () => {
expect(assistantShareRequestSchema.parse({ text: ' Day 2 is set. ' })).toEqual({ text: 'Day 2 is set.' });
expect(assistantShareRequestSchema.safeParse({ text: 'x' }).success).toBe(true);
expect(assistantShareRequestSchema.safeParse({ text: 'x'.repeat(5000) }).success).toBe(true);
});
it('refuses empty or blank text and text past the chat limit', () => {
expect(assistantShareRequestSchema.safeParse({ text: '' }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({ text: ' \n\t ' }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({ text: 'x'.repeat(5001) }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({}).success).toBe(false);
});
it('takes nothing but the text, so the origin is never the client to set', () => {
expect(assistantShareRequestSchema.safeParse({ text: 'hi', origin: 'assistant' }).success).toBe(false);
});
});
@@ -0,0 +1,15 @@
import { z } from 'zod';
/**
* POST /api/trips/:tripId/assistant/threads/:threadId/messages/:messageId/share:
* posts the text of an assistant answer to the trip's chat, marked as shared
* from the assistant. The text is what the user saw in the preview; the
* server checks that the answer is theirs and in this trip, not the words.
* It answers with the chat message (`collabMessageResponseSchema`).
*/
export const assistantShareRequestSchema = z
.object({
text: z.string().trim().min(1).max(5000),
})
.strict();
export type AssistantShareRequest = z.infer<typeof assistantShareRequestSchema>;
@@ -0,0 +1,87 @@
import {
ASSISTANT_PAGE_IMAGE,
assistantPageRenderSchema,
assistantPageViewSchema,
assistantRenderUploadRequestSchema,
drawnPhotoIdsOf,
previewBookPageRequestSchema,
} from './assistant-vision.schema';
import { assistantMessagePartSchema, uiStreamChunkSchema } from './assistant.schema';
import { describe, expect, it } from 'vitest';
const RENDER = {
requestId: '0b6f7c1e-3a52-4d8e-9a7b-2f1e0c9d8a76',
threadId: 4,
spreadId: 'sp-1',
bookVersion: 7,
hiddenPhotoIds: [12],
};
const VIEW = { spreadId: 'sp-1', bookVersion: 7, width: 1280, height: 640, bytes: 182_000, description: 'Page 2' };
describe('the Studio page image', () => {
it('ASTVIS-001: a render request names the page, the version and the photos left out; a proposal its page', () => {
expect(assistantPageRenderSchema.safeParse(RENDER).success).toBe(true);
// A proposal comes as the page the server applied it to, for the Studio to draw as it is.
const spread = { id: 'sp-1', role: 'inner', background: '#ffffff', elements: [], parked: [], entryId: null };
expect(assistantPageRenderSchema.parse({ ...RENDER, spread }).spread).toEqual(spread);
const notAPage = { ...spread, background: 'white' };
expect(assistantPageRenderSchema.safeParse({ ...RENDER, spread: notAPage }).success).toBe(false);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, requestId: 'r1' }).success).toBe(false);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, spreadId: '../x' }).success).toBe(false);
});
it('ASTVIS-002: a page view keeps the size of the image and the description, never the image', () => {
expect(assistantPageViewSchema.parse({ ...VIEW, data: 'aGVsbG8=' })).toEqual(VIEW);
const textOnly = { ...VIEW, width: null, height: null, bytes: null };
expect(assistantPageViewSchema.safeParse(textOnly).success).toBe(true);
});
it('ASTVIS-003: the page view is a stored part; the render request and the page view are stream chunks', () => {
expect(assistantMessagePartSchema.safeParse({ type: 'data-trek-page-view', data: VIEW }).success).toBe(true);
const request = { type: 'data-trek-render-request', data: RENDER, transient: true };
expect(uiStreamChunkSchema.safeParse(request).success).toBe(true);
expect(uiStreamChunkSchema.safeParse({ type: 'data-trek-page-view', data: VIEW }).success).toBe(true);
});
it('ASTVIS-004: an upload reads its text fields as multipart sends them, and its photo ids as a list', () => {
const fields = { bookVersion: '7', spreadId: 'sp-1', drawnPhotoIds: '12,30' };
expect(assistantRenderUploadRequestSchema.parse(fields)).toEqual({ ...fields, bookVersion: 7 });
expect(drawnPhotoIdsOf('12,30')).toEqual([12, 30]);
expect(drawnPhotoIdsOf('')).toEqual([]);
expect(drawnPhotoIdsOf(undefined)).toEqual([]);
});
it('ASTVIS-006: a preview names a page and may carry the ops of a proposed edit, nothing else', () => {
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1' }).success).toBe(true);
const ops = [{ op: 'background', color: '#ffffff' }];
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', ops }).success).toBe(true);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', ops: [] }).success).toBe(false);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', journeyId: 3 }).success).toBe(false);
});
it('ASTVIS-005: an upload refuses ids that are no list of numbers, and fields it does not know', () => {
const base = { bookVersion: '7', spreadId: 'sp-1' };
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, drawnPhotoIds: '12,,3' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, drawnPhotoIds: '1;2' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, data: 'x' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, bookVersion: '-1' }).success).toBe(false);
});
it('ASTVIS-007: a page may name as many photos as its frames and map stops hold, up to the cap', () => {
const many = Array.from({ length: ASSISTANT_PAGE_IMAGE.maxPagePhotos }, (_, i) => i + 1);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, hiddenPhotoIds: many }).success).toBe(true);
const tooMany = [...many, ASSISTANT_PAGE_IMAGE.maxPagePhotos + 1];
expect(assistantPageRenderSchema.safeParse({ ...RENDER, hiddenPhotoIds: tooMany }).success).toBe(false);
const fields = { bookVersion: '7', spreadId: 'sp-1', drawnPhotoIds: many.join(',') };
expect(assistantRenderUploadRequestSchema.safeParse(fields).success).toBe(true);
});
it('ASTVIS-008: a preview and a render request may name a design draft, by an id that is no path', () => {
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', designId: 'd-1a2b' }).success).toBe(true);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', designId: '../d' }).success).toBe(false);
expect(assistantPageRenderSchema.parse({ ...RENDER, designId: 'd-1a2b' }).designId).toBe('d-1a2b');
expect(assistantPageRenderSchema.safeParse({ ...RENDER, designId: 'd/1' }).success).toBe(false);
});
});
@@ -0,0 +1,123 @@
import { bookSpreadIdSchema } from '../book/book-op-ids';
import { bookDesignIdSchema, editBookPageArgs } from '../book/book-ops.schema';
import { bookSpreadSchema } from '../book/book.schema';
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
* The Studio assistant looking at a page (journey-studio.md section 3). The
* server cannot draw a page, so it asks the Studio tab that holds the turn's
* stream for one: a `data-trek-render-request` chunk names the page, the book
* version and the photos to leave out, the tab draws that one page and
* uploads it as an image, and the turn hands it to a model that reads images,
* beside the page's description. Nothing of the image is kept: the message
* stores what was looked at (`data-trek-page-view`), never the bytes.
*/
export const ASSISTANT_PAGE_IMAGE = {
/** The long edge a page is drawn at, in pixels, and the JPEG quality the Studio sends it with. */
longEdge: 1280,
jpegQuality: 0.82,
/** What the server takes at most: the bytes, the long edge and the pixels of one image. */
maxBytes: 1024 * 1024,
maxEdge: 2048,
maxPixels: 4_000_000,
/** Photos one page may name as hidden or drawn: its frames and the pictures its maps mark stops with. */
maxPagePhotos: 1000,
/** How long a turn waits for a page image before it goes on with the description alone. */
timeoutMs: 15_000,
/** Images one model request carries at most, one per tool answer; earlier ones go as their text. */
perRequest: 3,
/** Previews of a proposed change one step and one turn may ask for. */
previewsPerStep: 3,
previewsPerTurn: 8,
/**
* Previews a turn may ask for once a whole-book design is in play (it
* called design_book or revise_book_design, or looks at a draft): a design
* is judged on many pages, the cover twice. Still three images a request.
*/
previewsPerDesignTurn: 16,
} as const;
/**
* A page the server asks the Studio to draw, streamed while the turn waits.
* `spread` is a proposal's page as the server applied it (a preview): the
* Studio draws that one in place of the stored page; without it the page is
* drawn as the book stands at `bookVersion`. The photos in `hiddenPhotoIds`
* are drawn as empty frames, and a map stop showing one as a plain dot: only
* the asking user's own photos leave the browser.
*/
export const assistantPageRenderSchema = z.object({
requestId: z.uuid(),
threadId: idSchema,
spreadId: bookSpreadIdSchema,
bookVersion: z.number().int().nonnegative(),
/**
* A proposal's page as the server applied it, with the journey's photos,
* words and figures: the Studio draws this one in place of the stored page,
* nothing saved.
*/
spread: bookSpreadSchema.optional(),
/** A page of a design draft (design_book) rather than of the book: the Studio draws it from the draft. */
designId: bookDesignIdSchema.optional(),
hiddenPhotoIds: z.array(idSchema).max(ASSISTANT_PAGE_IMAGE.maxPagePhotos),
});
export type AssistantPageRender = z.infer<typeof assistantPageRenderSchema>;
/**
* What a turn looked at, as the message keeps it: the page, the version, the
* image's size when one reached the model (null when the model read the
* description alone), and the description itself. Never the image.
*/
export const assistantPageViewSchema = z.object({
spreadId: bookSpreadIdSchema,
bookVersion: z.number().int().nonnegative(),
width: z.number().int().positive().nullable(),
height: z.number().int().positive().nullable(),
bytes: z.number().int().positive().nullable(),
description: z.string().max(20_000),
});
export type AssistantPageView = z.infer<typeof assistantPageViewSchema>;
/**
* `preview_book_page`, a read of the Studio turn's own (no MCP tool): one page
* as it stands, or with `ops` as an `edit_book_page` with them would leave it,
* nothing saved. It answers the page's description and findings, and a model
* that reads images also gets the page as the Studio draws it.
*/
export const previewBookPageRequestSchema = z.strictObject({
spreadId: bookSpreadIdSchema,
ops: editBookPageArgs.ops.optional(),
/** Look at the page of a design draft instead of the book's (design_book's design_id). */
designId: bookDesignIdSchema.optional(),
});
export type PreviewBookPageRequest = z.infer<typeof previewBookPageRequestSchema>;
/**
* POST /api/journeys/:journeyId/assistant/threads/:threadId/renders/:requestId,
* multipart: the image in the field `image`, these as text fields beside it.
* `drawnPhotoIds` lists the photos the image shows, comma-separated; the
* server refuses the image when one of them is not the user's to show.
*/
export const assistantRenderUploadRequestSchema = z
.object({
bookVersion: z.coerce.number().int().nonnegative(),
spreadId: bookSpreadIdSchema,
drawnPhotoIds: z
.string()
.max(ASSISTANT_PAGE_IMAGE.maxPagePhotos * 13)
.regex(/^(?:\d{1,12}(?:,\d{1,12})*)?$/)
.optional(),
})
.strict();
export type AssistantRenderUploadRequest = z.infer<typeof assistantRenderUploadRequestSchema>;
/** The answer to an image the turn took; anything it did not take is refused with an error instead. */
export const assistantRenderUploadResponseSchema = z.object({ accepted: z.literal(true) });
export type AssistantRenderUploadResponse = z.infer<typeof assistantRenderUploadResponseSchema>;
/** The photo ids of an upload's `drawnPhotoIds` field. */
export function drawnPhotoIdsOf(field: string | undefined): number[] {
return field ? field.split(',').map(Number) : [];
}
@@ -0,0 +1,496 @@
/// <reference types="node" />
import {
ASSISTANT_CHANGE_LABEL_KEYS,
assistantAddFoundPlaceRequestSchema,
assistantAddFoundPlaceResponseSchema,
assistantAttachmentRequestSchema,
assistantChangePreviewSchema,
assistantChangePreviewWriteSchema,
assistantChatRequestSchema,
assistantDecisionsRequestSchema,
assistantFoundPlaceSchema,
assistantInsertFoundPlaceRequestSchema,
assistantMessageSchema,
assistantPlacesSchema,
assistantStopRequestSchema,
assistantWeatherSchema,
isAssistantTourFile,
UI_STREAM_DONE,
uiStreamChunkSchema,
type UiStreamChunk,
} from './assistant.schema';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
const ctx = { locale: 'de', timeZone: 'Europe/Berlin' };
/** The `data:` payloads of an SSE body, in order. */
const dataEvents = (body: string) =>
body
.split('\n\n')
.filter((event) => event.startsWith('data: '))
.map((event) => event.slice('data: '.length));
const fixture = readFileSync(fileURLToPath(new URL('./__fixtures__/ui-stream.v1.txt', import.meta.url)), 'utf8');
describe('assistantChatRequestSchema', () => {
it('takes a first message without a thread and trims the text', () => {
const parsed = assistantChatRequestSchema.parse({ ...ctx, threadId: null, text: ' Plan day 2 ' });
expect(parsed.text).toBe('Plan day 2');
});
it('refuses blank or overlong text, a bad thread id and unknown keys', () => {
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: ' ' }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: 'x'.repeat(32_001) }).success).toBe(
false,
);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: 0, text: 'hi' }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: 'hi', tripId: 9 }).success).toBe(false);
});
it('carries a focus of at most 20 places', () => {
const many = Array.from({ length: 21 }, (_, i) => i + 1);
expect(
assistantChatRequestSchema.safeParse({ ...ctx, threadId: 3, text: 'hi', focus: { dayId: 4, placeIds: [1] } })
.success,
).toBe(true);
expect(
assistantChatRequestSchema.safeParse({ ...ctx, threadId: 3, text: 'hi', focus: { placeIds: many } }).success,
).toBe(false);
});
it('needs the locale and time zone', () => {
expect(assistantChatRequestSchema.safeParse({ threadId: null, text: 'hi' }).success).toBe(false);
});
it('names the page of a journey it is asked from, the Studio or the journal, and nothing else', () => {
const base = { ...ctx, threadId: null, text: 'hi' };
expect(assistantChatRequestSchema.parse({ ...base, surface: 'journal' }).surface).toBe('journal');
expect(assistantChatRequestSchema.parse({ ...base, surface: 'studio' }).surface).toBe('studio');
expect(assistantChatRequestSchema.parse(base).surface).toBeUndefined();
expect(assistantChatRequestSchema.safeParse({ ...base, surface: 'planner' }).success).toBe(false);
const decision = { toolCallId: 'a', approved: true };
expect(assistantDecisionsRequestSchema.parse({ ...ctx, decisions: [decision], surface: 'journal' }).surface).toBe(
'journal',
);
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [decision], surface: 'x' }).success).toBe(
false,
);
});
});
describe('assistantAttachmentRequestSchema', () => {
it('reads the multipart text fields, the thread id from its text', () => {
expect(assistantAttachmentRequestSchema.parse({ ...ctx })).toEqual(ctx);
expect(assistantAttachmentRequestSchema.parse({ ...ctx, threadId: '12' })).toEqual({ ...ctx, threadId: 12 });
});
it('refuses a bad thread id, unknown fields and a missing context', () => {
for (const threadId of ['0', '-1', 'abc', '1.5']) {
expect(assistantAttachmentRequestSchema.safeParse({ ...ctx, threadId }).success, threadId).toBe(false);
}
expect(assistantAttachmentRequestSchema.safeParse({ ...ctx, text: 'hi' }).success).toBe(false);
expect(assistantAttachmentRequestSchema.safeParse({ threadId: '3' }).success).toBe(false);
});
});
describe('assistantDecisionsRequestSchema', () => {
it('takes one to twelve decisions', () => {
const decision = { toolCallId: 'a', approved: true };
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [decision] }).success).toBe(true);
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [] }).success).toBe(false);
expect(
assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: Array.from({ length: 51 }, () => decision) })
.success,
).toBe(false);
});
it('never takes arguments for a call, only the decision', () => {
expect(
assistantDecisionsRequestSchema.safeParse({
...ctx,
decisions: [{ toolCallId: 'a', approved: true, args: { name: 'x' } }],
}).success,
).toBe(false);
});
});
describe('assistantStopRequestSchema', () => {
it('is an empty JSON object', () => {
expect(assistantStopRequestSchema.safeParse({}).success).toBe(true);
expect(assistantStopRequestSchema.safeParse({ force: true }).success).toBe(false);
});
});
describe('assistantChangePreviewSchema', () => {
const preview = {
toolCallId: 'c1',
verbKey: 'addPlace',
subject: 'Kinkaku-ji',
rows: [{ op: 'add', labelKey: 'address', before: null, after: 'Kyoto' }],
dayId: null,
placeIds: [],
undoable: true,
};
it('labels rows from the closed key list only', () => {
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
expect(
assistantChangePreviewSchema.safeParse({ ...preview, rows: [{ ...preview.rows[0], labelKey: 'evil' }] }).success,
).toBe(false);
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, verbKey: 'deleteTrip' }).success).toBe(false);
});
it('reads a verb a later build added as a plain update, and writes none it does not know', () => {
expect(assistantChangePreviewSchema.parse({ ...preview, verbKey: 'laterVerb' }).verbKey).toBe('genericUpdate');
expect(assistantChangePreviewWriteSchema.parse(preview).verbKey).toBe('addPlace');
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, card: { kind: 'nope' } }).success).toBe(false);
});
it('names the proposal a taken change came from by its call id, bounded like the take request', () => {
expect(assistantChangePreviewWriteSchema.parse({ ...preview, takenFrom: 'call_hike' }).takenFrom).toBe('call_hike');
expect(assistantChangePreviewSchema.parse(preview).takenFrom).toBeUndefined();
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: '' }).success).toBe(false);
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: 'c'.repeat(65) }).success).toBe(false);
});
it('holds at most twelve rows', () => {
const rows = ASSISTANT_CHANGE_LABEL_KEYS.slice(0, 13).map((labelKey) => ({
op: 'add',
labelKey,
before: null,
after: 'x',
}));
expect(assistantChangePreviewSchema.safeParse({ ...preview, rows }).success).toBe(false);
});
});
describe('assistantMessageSchema', () => {
it('reads a stored message with an expired approval', () => {
const parsed = assistantMessageSchema.safeParse({
id: '12',
role: 'assistant',
status: 'awaiting_approval',
createdAt: '2026-10-21T08:00:00.000Z',
parts: [
{ type: 'text', text: 'Adding it.' },
{
type: 'tool-call',
toolCallId: 'c1',
toolName: 'create_place',
args: { name: 'Kinkaku-ji' },
approval: { id: 'c1', resolution: 'expired' },
},
],
});
expect(parsed.success).toBe(true);
});
it('reads a user message that attached a file, by its name, type and size only', () => {
const message = { id: '13', role: 'user', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const attachment = { type: 'attachment', name: 'ticket.pdf', mime: 'application/pdf', size: 2048 };
expect(assistantMessageSchema.safeParse({ ...message, parts: [attachment] }).success).toBe(true);
const negative = { ...attachment, size: -1 };
expect(assistantMessageSchema.safeParse({ ...message, parts: [negative] }).success).toBe(false);
});
it('reads the id a kept attachment goes by, and only a uuid as one', () => {
const message = { id: '14', role: 'user', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const attachment = { type: 'attachment', name: 'ticket.pdf', mime: 'application/pdf', size: 2048 };
const kept = { ...attachment, attachmentId: '0b7c2f0e-6f6d-4a8e-9b1a-3d2c1e0f9a87' };
expect(assistantMessageSchema.parse({ ...message, parts: [kept] }).parts[0]).toEqual(kept);
const forged = { ...attachment, attachmentId: '../other-thread' };
expect(assistantMessageSchema.safeParse({ ...message, parts: [forged] }).success).toBe(false);
});
});
describe('uiStreamChunkSchema', () => {
it('reads an unknown error code as generic', () => {
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'something_new' })).toEqual({
type: 'error',
errorText: 'generic',
});
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'daily_limit' })).toEqual({
type: 'error',
errorText: 'daily_limit',
});
});
it('refuses a chunk type it does not know', () => {
expect(uiStreamChunkSchema.safeParse({ type: 'reasoning-delta', id: 'r', delta: 'x' }).success).toBe(false);
});
});
describe('ui-stream.v1 fixture', () => {
const events = dataEvents(fixture);
const chunks = events.slice(0, -1).map((event) => uiStreamChunkSchema.parse(JSON.parse(event)));
const ofType = <T extends UiStreamChunk['type']>(type: T) =>
chunks.filter((c): c is Extract<UiStreamChunk, { type: T }> => c.type === type);
it('is a stream of valid chunks closed by [DONE]', () => {
expect(events.at(-1)).toBe(UI_STREAM_DONE);
expect(chunks[0]?.type).toBe('start');
expect(chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' });
});
it('names the new thread before anything else is said', () => {
expect(chunks[1]?.type).toBe('data-trek-thread');
});
it('asks for approval with the call id and previews that same call', () => {
const [request] = ofType('tool-approval-request');
const [change] = ofType('data-trek-change');
expect(request).toBeDefined();
expect(request?.approvalId).toBe(request?.toolCallId);
expect(change?.data.toolCallId).toBe(request?.toolCallId);
expect(ofType('tool-input-available').map((c) => c.toolCallId)).toContain(request?.toolCallId);
});
it('closes every text block it opens', () => {
const opened = ofType('text-start').map((c) => c.id);
expect(opened.length).toBeGreaterThan(0);
expect(ofType('text-end').map((c) => c.id)).toEqual(opened);
});
});
describe('mentions in a chat request', () => {
const base = { ...ctx, threadId: 3, text: 'Move @Louvre to @Friday' };
it('names up to ten days, places or bookings by id, never by label', () => {
const mentions = [
{ kind: 'place', id: 4 },
{ kind: 'day', id: 9 },
{ kind: 'reservation', id: 2 },
];
expect(assistantChatRequestSchema.safeParse({ ...base, mentions }).success).toBe(true);
const tooMany = Array.from({ length: 51 }, () => ({ kind: 'place', id: 4 }));
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: tooMany }).success).toBe(false);
const labelled = [{ kind: 'place', id: 4, label: 'Louvre' }];
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: labelled }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: [{ kind: 'trip', id: 4 }] }).success).toBe(false);
});
});
describe('assistantAddFoundPlaceRequestSchema', () => {
const parse = (body: Record<string, unknown>) => assistantAddFoundPlaceRequestSchema.safeParse({ ...ctx, ...body });
it('names a found place by its ref and the day it goes on', () => {
expect(parse({ ref: 'toolu_01:2', dayId: 32 }).success).toBe(true);
});
it('refuses an empty or overlong ref, a bad day and anything about the place itself', () => {
expect(parse({ ref: '', dayId: 32 }).success).toBe(false);
expect(parse({ ref: 'x'.repeat(81), dayId: 32 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 0 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 3, name: 'Elsewhere' }).success).toBe(false);
expect(assistantAddFoundPlaceRequestSchema.safeParse({ ref: 'a:1', dayId: 3 }).success).toBe(false);
});
});
describe('assistantInsertFoundPlaceRequestSchema', () => {
const parse = (body: Record<string, unknown>) =>
assistantInsertFoundPlaceRequestSchema.safeParse({ ...ctx, ...body });
it('names a found place by its ref and the saved tour it goes into', () => {
expect(parse({ ref: 'toolu_01:2', tourId: 64 }).success).toBe(true);
});
it('refuses a bad tour, a day instead of a tour and anything about the stop itself', () => {
expect(parse({ ref: 'a:1', tourId: 0 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 3 }).success).toBe(false);
expect(parse({ ref: 'a:1', tourId: 64, after_key: 'abc123' }).success).toBe(false);
expect(assistantInsertFoundPlaceRequestSchema.safeParse({ ref: 'a:1', tourId: 64 }).success).toBe(false);
});
});
describe('route files attached in the chat', () => {
it('tells a GPX, KML or KMZ file by its name, whatever its case', () => {
expect(isAssistantTourFile('Herzogstand.GPX')).toBe(true);
expect(isAssistantTourFile('map.kml')).toBe(true);
expect(isAssistantTourFile('map.kmz')).toBe(true);
expect(isAssistantTourFile('ticket.pdf')).toBe(false);
expect(isAssistantTourFile('gpx')).toBe(false);
});
});
describe('the effect of a change', () => {
const preview = {
toolCallId: 'c1',
verbKey: 'addPlaceToDay',
subject: 'Kinkaku-ji',
rows: [],
dayId: 32,
placeIds: [],
undoable: true,
};
const ghost = { name: 'Kinkaku-ji', lat: 35.0394, lng: 135.7292, categoryId: null };
const add = { kind: 'add', dayId: 32, fromDayId: null, placeId: null, assignmentId: null, place: ghost };
const withEffect = (effect: unknown) => assistantChangePreviewSchema.safeParse({ ...preview, effect }).success;
it('is optional, so previews stored before it still read', () => {
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
expect(withEffect(null)).toBe(true);
});
it('places a new place on its day, or moves an existing one between days', () => {
expect(withEffect(add)).toBe(true);
const existing = { placeId: 7, assignmentId: 12, place: null };
expect(withEffect({ kind: 'move', dayId: 32, fromDayId: 31, ...existing })).toBe(true);
expect(withEffect({ kind: 'remove', dayId: 31, fromDayId: null, ...existing })).toBe(true);
});
it('refuses a position off the globe, an overlong name and an unknown kind', () => {
expect(withEffect({ ...add, place: { ...ghost, lat: 91 } })).toBe(false);
expect(withEffect({ ...add, place: { ...ghost, lng: -181 } })).toBe(false);
expect(withEffect({ ...add, place: { ...ghost, name: 'x'.repeat(201) } })).toBe(false);
expect(withEffect({ ...add, kind: 'swap' })).toBe(false);
});
});
describe('assistantFoundPlaceSchema', () => {
const place = {
ref: 'toolu_01:0',
name: 'Trattoria da Enzo',
address: 'Via dei Vascellari 29, Roma',
lat: 41.8885,
lng: 12.4771,
kind: 'food',
rating: 4.6,
openNow: null,
googlePlaceId: 'ChIJ-abc_123',
osmId: null,
photoKey: 'ChIJ-abc_123',
inTripPlaceId: null,
};
const withPlace = (patch: Record<string, unknown>) => assistantFoundPlaceSchema.safeParse({ ...place, ...patch });
it('reads a place with a source id as its photo key, or coordinates', () => {
expect(withPlace({}).success).toBe(true);
expect(withPlace({ photoKey: 'coords:41.8885,12.4771' }).success).toBe(true);
expect(withPlace({ photoKey: 'coords:-33.9,-70.6' }).success).toBe(true);
expect(withPlace({ photoKey: null }).success).toBe(true);
});
it('never takes a URL or anything with a path as the photo key', () => {
const notKeys = [
'https://evil.example/p.jpg',
'//evil.example/p.jpg',
'/api/maps/place-photo/x/bytes',
'a/b',
'coords:1,2;x',
'',
];
for (const photoKey of notKeys) expect(withPlace({ photoKey }).success, photoKey).toBe(false);
});
it('refuses a Google id that is not one, a rating past five and an unknown kind', () => {
expect(withPlace({ googlePlaceId: 'a b' }).success).toBe(false);
expect(withPlace({ rating: 5.1 }).success).toBe(false);
expect(withPlace({ kind: 'casino' }).success).toBe(false);
});
it('holds at most twenty places to a step and counts the rest', () => {
const places = Array.from({ length: 21 }, (_, i) => ({ ...place, ref: `toolu_01:${i}` }));
const step = (body: Record<string, unknown>) =>
assistantPlacesSchema.safeParse({ toolCallId: 'toolu_01', ...body });
expect(step({ places: places.slice(0, 20), more: 1 }).success).toBe(true);
expect(step({ places, more: 0 }).success).toBe(false);
expect(step({ places: [], more: -1 }).success).toBe(false);
});
});
describe('assistantWeatherSchema', () => {
const day = {
dayId: 32,
date: '2026-06-12',
main: 'Clear',
tempMax: 24.5,
tempMin: 16,
rainPct: 10,
kind: 'forecast',
};
it('reads one to sixteen days, a climate day without a low or a rain chance', () => {
expect(assistantWeatherSchema.safeParse({ days: [day] }).success).toBe(true);
const climate = { ...day, dayId: null, tempMin: null, rainPct: null, kind: 'climate' };
expect(assistantWeatherSchema.safeParse({ days: [climate] }).success).toBe(true);
expect(assistantWeatherSchema.safeParse({ days: [] }).success).toBe(false);
expect(assistantWeatherSchema.safeParse({ days: Array.from({ length: 17 }, () => day) }).success).toBe(false);
});
it('refuses a date that is not a calendar date and a rain chance past 100', () => {
expect(assistantWeatherSchema.safeParse({ days: [{ ...day, date: '12.06.2026' }] }).success).toBe(false);
expect(assistantWeatherSchema.safeParse({ days: [{ ...day, rainPct: 101 }] }).success).toBe(false);
});
});
describe('the new message parts', () => {
const message = { id: '14', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const rainyDay = { dayId: 32, date: '2026-06-12', main: 'Rain', tempMax: 18, tempMin: 12, rainPct: 80 };
it('keeps found places and the weather on an answer', () => {
const parts = [
{ type: 'data-trek-places', data: { toolCallId: 'toolu_01', places: [], more: 0 } },
{ type: 'data-trek-weather', data: { days: [{ ...rainyDay, kind: 'forecast' }] } },
];
expect(assistantMessageSchema.safeParse({ ...message, role: 'assistant', parts }).success).toBe(true);
});
it('keeps the checked mentions of a question with their labels', () => {
const item = { kind: 'place', id: 4, label: 'Louvre' };
const parts = [
{ type: 'text', text: 'Is @Louvre open on Monday?' },
{ type: 'data-trek-mentions', data: { items: [item] } },
];
expect(assistantMessageSchema.safeParse({ ...message, role: 'user', parts }).success).toBe(true);
const tooLong = [{ type: 'data-trek-mentions', data: { items: [{ ...item, label: 'x'.repeat(121) }] } }];
expect(assistantMessageSchema.safeParse({ ...message, role: 'user', parts: tooLong }).success).toBe(false);
});
it('never stores the live activity of a step', () => {
const activity = { type: 'data-trek-activity', data: { toolCallId: 'toolu_01', label: null, area: null } };
expect(assistantMessageSchema.safeParse({ ...message, role: 'assistant', parts: [activity] }).success).toBe(false);
});
it('answers a suggested found place with the message that holds it', () => {
const answer = { ...message, role: 'assistant', status: 'awaiting_approval', parts: [] };
expect(assistantAddFoundPlaceResponseSchema.safeParse({ message: answer }).success).toBe(true);
expect(assistantAddFoundPlaceResponseSchema.safeParse({}).success).toBe(false);
});
});
describe('the new stream chunks', () => {
const activity = (data: Record<string, unknown>) =>
uiStreamChunkSchema.safeParse({ type: 'data-trek-activity', data: { toolCallId: 'toolu_01', ...data } }).success;
it('streams the live activity of a step, marked transient, with a point or a box', () => {
const point = { type: 'point', lat: 41.89, lng: 12.47, radiusM: 1500 };
const bbox = { type: 'bbox', south: 41.8, west: 12.4, north: 41.95, east: 12.6 };
for (const area of [point, bbox, null]) expect(activity({ label: 'Trastevere', area })).toBe(true);
const chunk = { type: 'data-trek-activity', transient: true, data: { toolCallId: 't', label: null, area: null } };
expect(uiStreamChunkSchema.safeParse(chunk).success).toBe(true);
});
it('refuses an activity with a radius past 50 km or a label past 80 characters', () => {
const area = { type: 'point', lat: 41.89, lng: 12.47, radiusM: 50_001 };
expect(activity({ label: null, area })).toBe(false);
expect(activity({ label: 'x'.repeat(81), area: null })).toBe(false);
});
it('streams found places and the weather as they are stored', () => {
const places = { type: 'data-trek-places', data: { toolCallId: 'toolu_01', places: [], more: 3 } };
const day = { dayId: null, date: '2026-06-12', main: 'Clouds', tempMax: 21, tempMin: null, rainPct: null };
const weather = { type: 'data-trek-weather', data: { days: [{ ...day, kind: 'current' }] } };
expect(uiStreamChunkSchema.safeParse(places).success).toBe(true);
expect(uiStreamChunkSchema.safeParse(weather).success).toBe(true);
});
it('names the found-place refusal by its code', () => {
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'decide_first' })).toEqual({
type: 'error',
errorText: 'decide_first',
});
});
});
+817
View File
@@ -0,0 +1,817 @@
import { bookElementIdSchema, bookSpreadIdSchema } from '../book/book-ops.schema';
import { idParamSchema, idSchema } from '../common/primitives.schema';
import { assistantAttachmentIdSchema } from './assistant-attachments.schema';
import { assistantJourneySurfaceSchema } from './assistant-scope.schema';
import { assistantPageRenderSchema, assistantPageViewSchema } from './assistant-vision.schema';
import {
assistantCardSchema,
assistantCardWriteSchema,
ATLAS_APPLIED_ENTITIES,
ATLAS_VERB_KEYS,
BOOK_APPLIED_ENTITIES,
BOOK_DESIGN_VERB_KEYS,
BOOK_VERB_KEYS,
BOOKING_APPLIED_ENTITIES,
BOOKING_VERB_KEYS,
BUDGET_APPLIED_ENTITIES,
BUDGET_VERB_KEYS,
COLLAB_APPLIED_ENTITIES,
COLLAB_VERB_KEYS,
COLLECTION_APPLIED_ENTITIES,
COLLECTION_VERB_KEYS,
JOURNEY_APPLIED_ENTITIES,
JOURNEY_VERB_KEYS,
PACKING_APPLIED_ENTITIES,
PACKING_VERB_KEYS,
ROADTRIP_APPLIED_ENTITIES,
ROADTRIP_VERB_KEYS,
storedTrekCardSchema,
TOUR_APPLIED_ENTITIES,
TOUR_VERB_KEYS,
trekCardSchema,
VACAY_APPLIED_ENTITIES,
VACAY_VERB_KEYS,
type AssistantCard,
} from './cards';
import { z } from 'zod';
/**
* Trip assistant contract for /api/trips/:tripId/assistant.
*
* The assistant works the trip through the same MCP tools any client uses.
* Reading tools run at once; every writing call is held as a change preview
* the user applies or discards, and only then runs, with the arguments the
* server stored, never ones the client sends back. A file attached in the
* chat (`attachments`) is read by the server itself: the step is the call
* `read_booking_file`, and each booking it finds is held as an
* `import_booking` change like any other. Neither is a tool the model knows.
*
* `chat`, `attachments` and `threads/:threadId/decisions` answer with a stream of UI message
* chunks (`uiStreamChunkSchema`, a subset of the UI Message Stream v1 plus the
* `data-trek-*` parts), one `data: <json>` event each, closed by
* `data: [DONE]`. `__fixtures__/ui-stream.v1.txt` is one such stream; the
* server's writer and the client's parser are both tested against it.
*/
/** Why a turn could not run or stopped, as the `error` chunk and the JSON errors name it. */
export const ASSISTANT_ERROR_CODES = [
'not_connected',
'busy',
'daily_limit',
'rate_limited',
'needs_reauth',
'usage_limit',
'not_eligible',
'invalid_key',
'provider_unavailable',
'max_steps',
// The model answered with nothing, not even after it was asked to go on.
'empty_answer',
'offline',
'no_bookings_found',
// An attached GPX, KML or KMZ file without a single track or route to take in as a tour.
'no_tracks_found',
'import_unavailable',
// A found place was suggested while the thread still holds changes nobody decided on.
'decide_first',
// TREK's own per-user limit on turns and changes, apart from the provider's `rate_limited`.
'too_many_requests',
'generic',
] as const;
export const assistantErrorCodeSchema = z.enum(ASSISTANT_ERROR_CODES);
export type AssistantErrorCode = z.infer<typeof assistantErrorCodeSchema>;
/**
* What a change does, one per writing tool. The client labels the card with
* `assistant.change.verb.<key>`. These are the core verbs; each part of TREK
* adds its own in its cards contract (`cards/<pkg>.contract.ts`).
*/
export const CORE_VERB_KEYS = [
'addPlace',
'addPlaceToDay',
'updatePlace',
'assignPlace',
'moveAssignment',
'removeFromDay',
'addDayNote',
'updateDayNote',
'addPackingItem',
'updatePackingItem',
'addTodo',
'addBudgetItem',
'updateBudgetItem',
'addReservation',
'importBooking',
'rememberNote',
// The text of a file attached in the chat, sent to the AI provider once the user agrees.
'readAttachment',
// A file attached in the chat, kept in the trip's Files, on its own or with a booking, an expense or a place.
'keepFile',
// A tour: a hike or a city walk created, a hike changed, tours taken in from a GPX file.
'addTour',
'updateTour',
'importTour',
// Any other tool: by what its annotations say it does.
'genericCreate',
'genericUpdate',
'genericRemove',
] as const;
export const ASSISTANT_CHANGE_VERB_KEYS = [
...CORE_VERB_KEYS,
...TOUR_VERB_KEYS,
...ROADTRIP_VERB_KEYS,
...BUDGET_VERB_KEYS,
...BOOKING_VERB_KEYS,
...COLLAB_VERB_KEYS,
...COLLECTION_VERB_KEYS,
...ATLAS_VERB_KEYS,
...VACAY_VERB_KEYS,
...JOURNEY_VERB_KEYS,
...PACKING_VERB_KEYS,
...BOOK_VERB_KEYS,
...BOOK_DESIGN_VERB_KEYS,
] as const;
export const assistantChangeVerbKeySchema = z.enum(ASSISTANT_CHANGE_VERB_KEYS);
export type AssistantChangeVerbKey = z.infer<typeof assistantChangeVerbKeySchema>;
/** The field a change row shows, labelled `assistant.change.label.<key>`. */
export const ASSISTANT_CHANGE_LABEL_KEYS = [
'name',
'description',
'address',
'coordinates',
'category',
'day',
'time',
'endTime',
'notes',
'website',
'phone',
'email',
'openingHours',
'price',
'currency',
'stopType',
'text',
'icon',
'color',
'position',
'quantity',
'weight',
'bag',
'packed',
'dueDate',
'priority',
'assignee',
'type',
'location',
'link',
'confirmation',
'checkIn',
'checkOut',
'stay',
'members',
'route',
// The hardest SAC grade a hike's way may take, T1 to T6.
'difficulty',
// The recorded track a tour was done on; the part of the packing list a tour points at.
'track',
'packing',
// The minutes of breaks a tour plans on top of its moving time.
'breaks',
// A new order of a day's places or of the days, as the names in that order.
'order',
// An argument of a tool without a card of its own; the row names it in `field`.
'field',
// Where the text of an attached file goes once the user agrees: the model and its host.
'sentTo',
// The booking, expense or place a kept file is attached to.
'attachedTo',
] as const;
export const assistantChangeLabelKeySchema = z.enum(ASSISTANT_CHANGE_LABEL_KEYS);
export type AssistantChangeLabelKey = z.infer<typeof assistantChangeLabelKeySchema>;
const latSchema = z.number().min(-90).max(90);
const lngSchema = z.number().min(-180).max(180);
// ── Requests ────────────────────────────────────────────────────────────────
/**
* A day, place or booking the user named with `@` in the message. The server
* checks each against the trip and takes the label from its own data, never
* from the request; one that is not in the trip is dropped without a word.
*/
export const ASSISTANT_MENTION_KINDS = ['day', 'place', 'reservation'] as const;
export const assistantMentionSchema = z
.object({
kind: z.enum(ASSISTANT_MENTION_KINDS),
id: idSchema,
})
.strict();
export type AssistantMention = z.infer<typeof assistantMentionSchema>;
/** The part of the map the planner shows, so "here" and "nearby" mean what is on screen. */
export const assistantMapViewSchema = z
.object({ south: latSchema, west: lngSchema, north: latSchema, east: lngSchema })
.strict();
export type AssistantMapView = z.infer<typeof assistantMapViewSchema>;
/**
* What the user is looking at when they ask: the selected day, or the places
* they asked about, and the part of the map on screen.
*/
export const assistantFocusSchema = z
.object({
dayId: idSchema.optional(),
placeIds: z.array(idSchema).max(20).optional(),
view: assistantMapViewSchema.optional(),
/** In the Studio: the page (spread) on screen, and the elements selected on it. */
spreadId: bookSpreadIdSchema.optional(),
elementIds: z.array(bookElementIdSchema).max(30).optional(),
})
.strict();
export type AssistantFocus = z.infer<typeof assistantFocusSchema>;
/** The language to answer in and the zone "today" is read in, sent with every turn. */
export const assistantClientCtxSchema = z.object({
locale: z.string().min(2).max(10),
timeZone: z.string().min(1).max(64),
});
export type AssistantClientCtx = z.infer<typeof assistantClientCtxSchema>;
/** POST /chat: a new message, in an existing thread or (threadId null) a new one. */
export const assistantChatRequestSchema = assistantClientCtxSchema
.extend({
threadId: idSchema.nullable(),
text: z.string().trim().min(1).max(32_000),
focus: assistantFocusSchema.optional(),
mentions: z.array(assistantMentionSchema).max(50).optional(),
/** The client draws a Studio page when the turn asks for one (the Studio's chat, assistant-vision.schema.ts). */
renders: z.boolean().optional(),
/** A journey's chat only: the page the user asks from, the Studio's when left out. A trip's chat ignores it. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict();
export type AssistantChatRequest = z.infer<typeof assistantChatRequestSchema>;
/**
* POST /attachments, multipart: the file in the field `file`, these as text
* fields beside it. A new thread when threadId is left out. Multipart sends
* every field as a string, so the id is read from its text.
*/
export const assistantAttachmentRequestSchema = assistantClientCtxSchema
.extend({
threadId: idParamSchema.optional(),
})
.strict();
export type AssistantAttachmentRequest = z.infer<typeof assistantAttachmentRequestSchema>;
/** One decision on a held change. */
export const assistantDecisionSchema = z
.object({
toolCallId: z.string().min(1).max(64),
approved: z.boolean(),
})
.strict();
export type AssistantDecision = z.infer<typeof assistantDecisionSchema>;
/** POST /threads/:threadId/decisions: every change the step holds, applied or discarded. */
export const assistantDecisionsRequestSchema = assistantClientCtxSchema
.extend({
decisions: z.array(assistantDecisionSchema).min(1).max(50),
/** As on a chat turn: the client draws a Studio page when the turn asks for one. */
renders: z.boolean().optional(),
/** As on a chat turn: the page of a journey the decision is made on, which picks the tools the turn goes on with. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict();
export type AssistantDecisionsRequest = z.infer<typeof assistantDecisionsRequestSchema>;
/** POST /stop. No fields: the body is JSON only so the request cannot be sent cross-site as a form. */
export const assistantStopRequestSchema = z.object({}).strict();
export type AssistantStopRequest = z.infer<typeof assistantStopRequestSchema>;
/** POST /tool-calls/:toolCallId/undo. No fields, for the same reason as stop. */
export const assistantUndoRequestSchema = z.object({}).strict();
export type AssistantUndoRequest = z.infer<typeof assistantUndoRequestSchema>;
/**
* POST /threads/:threadId/found-places: suggest a place from a search result
* for a day. `ref` names the place in the thread's stored places part; the
* server holds the change like any other and runs no model turn for it.
*/
export const assistantAddFoundPlaceRequestSchema = assistantClientCtxSchema
.extend({
ref: z.string().min(1).max(80),
dayId: idSchema,
})
.strict();
export type AssistantAddFoundPlaceRequest = z.infer<typeof assistantAddFoundPlaceRequestSchema>;
/**
* POST /threads/:threadId/found-places/tour: "+ Tour" on a place a search
* found, while a saved tour is open in the planner. Held like "+ Day 3": the
* place comes from the stored search results, the tour must be one of this
* trip's, and the server picks where along it the stop goes.
*/
export const assistantInsertFoundPlaceRequestSchema = assistantClientCtxSchema
.extend({
ref: z.string().min(1).max(80),
tourId: idSchema,
})
.strict();
export type AssistantInsertFoundPlaceRequest = z.infer<typeof assistantInsertFoundPlaceRequestSchema>;
/** The route files the chat takes in as tours (P7), beside the booking files. */
export const ASSISTANT_TOUR_FILE_EXTENSIONS = ['.gpx', '.kml', '.kmz'] as const;
/** Whether a file the user attached is a route file, by its name. */
export function isAssistantTourFile(fileName: string): boolean {
const dot = fileName.lastIndexOf('.');
const ext = dot < 0 ? '' : fileName.slice(dot).toLowerCase();
return (ASSISTANT_TOUR_FILE_EXTENSIONS as readonly string[]).includes(ext);
}
/**
* POST /threads/:threadId/proposals: take a proposal an answer showed as a
* card ("Plan this"). `toolCallId` names the read whose card it was; the
* server holds the matching change like a found place, from what it stored,
* and answers like the found places route.
*/
export const assistantTakeProposalRequestSchema = assistantClientCtxSchema
.extend({
toolCallId: z.string().min(1).max(64),
})
.strict();
export type AssistantTakeProposalRequest = z.infer<typeof assistantTakeProposalRequestSchema>;
// ── Change previews ─────────────────────────────────────────────────────────
/**
* What a change does to the day plan, so the map can show it before it is
* applied: the day it lands on (for a removal, the day it leaves), the day a
* move comes from, and for a place that does not exist yet its name and
* position. Null for a change that does not touch the plan.
*/
export const assistantChangeEffectSchema = z.object({
kind: z.enum(['add', 'remove', 'move']),
dayId: idSchema,
fromDayId: idSchema.nullable(),
placeId: idSchema.nullable(),
assignmentId: idSchema.nullable(),
place: z
.object({
name: z.string().max(200),
lat: latSchema,
lng: lngSchema,
categoryId: idSchema.nullable(),
})
.nullable(),
});
export type AssistantChangeEffect = z.infer<typeof assistantChangeEffectSchema>;
/** One line of a change card, in plain words: names, dates and times, never ids. */
export const assistantChangeRowSchema = z.object({
op: z.enum(['add', 'change', 'move']),
labelKey: assistantChangeLabelKeySchema,
before: z.string().nullable(),
after: z.string(),
// The argument a `field` row shows, as the tool names it.
field: z.string().max(60).optional(),
});
export type AssistantChangeRow = z.infer<typeof assistantChangeRowSchema>;
/** A held writing call as the server writes it: every verb and card one this build knows. */
export const assistantChangePreviewWriteSchema = z.object({
toolCallId: z.string(),
verbKey: assistantChangeVerbKeySchema,
// What the change is about: the place, note or item name.
subject: z.string(),
rows: z.array(assistantChangeRowSchema).max(12),
// Where "Show on map" goes after the change was applied.
dayId: idSchema.nullable(),
placeIds: z.array(idSchema),
// Whether applying it can be undone for a while (a create with a matching delete).
undoable: z.boolean(),
// Left out by servers and stored previews from before the map showed changes.
effect: assistantChangeEffectSchema.nullable().optional(),
// The tool behind a card without one of its own, and the part of TREK it works in.
tool: z.string().max(80).optional(),
domain: z.string().max(40).optional(),
// What the change will do, drawn as a card; absent on older rows and on cards without one.
card: trekCardSchema.nullable().optional(),
// The proposal a change held by "Plan this" was taken from (its call id); absent on every other change.
takenFrom: assistantTakeProposalRequestSchema.shape.toolCallId.optional(),
});
/**
* A held writing call as the user sees it before deciding, and as it is read
* back: a verb a later build added reads as a plain update and a card this
* build cannot draw as none, so an older client or a rolled back server still
* shows the change instead of dropping it.
*/
export const assistantChangePreviewSchema = assistantChangePreviewWriteSchema.extend({
verbKey: assistantChangeVerbKeySchema.catch('genericUpdate'),
card: storedTrekCardSchema.optional(),
});
export type AssistantChangePreview = z.infer<typeof assistantChangePreviewSchema>;
/** What an applied change can touch in the core; each part of TREK adds its own in its cards contract. */
export const CORE_APPLIED_ENTITIES = [
'place',
'assignment',
'day_note',
'packing',
'todo',
'budget',
'reservation',
'memory',
'tour',
// A file kept in the trip's Files.
'file',
'other',
] as const;
const assistantAppliedEntitySchema = z.enum([
...CORE_APPLIED_ENTITIES,
...TOUR_APPLIED_ENTITIES,
...ROADTRIP_APPLIED_ENTITIES,
...BUDGET_APPLIED_ENTITIES,
...BOOKING_APPLIED_ENTITIES,
...COLLAB_APPLIED_ENTITIES,
...COLLECTION_APPLIED_ENTITIES,
...ATLAS_APPLIED_ENTITIES,
...VACAY_APPLIED_ENTITIES,
...JOURNEY_APPLIED_ENTITIES,
...PACKING_APPLIED_ENTITIES,
...BOOK_APPLIED_ENTITIES,
]);
/** An applied change as the server writes it: what it touched, and until when it can be undone. */
const assistantAppliedWriteSchema = z.object({
toolCallId: z.string(),
entity: assistantAppliedEntitySchema,
ids: z.array(idSchema),
dayId: idSchema.nullable(),
undoUntil: z.string().nullable(),
});
/** An applied change as it is read back: an entity a later build added reads as `other`, with nothing to open. */
export const assistantAppliedSchema = assistantAppliedWriteSchema.extend({
entity: assistantAppliedEntitySchema.catch('other'),
});
export type AssistantApplied = z.infer<typeof assistantAppliedSchema>;
// ── Cards in an answer ──────────────────────────────────────────────────────
/** The kind a found place is drawn as, read from whatever its source calls it. */
export const ASSISTANT_FOUND_PLACE_KINDS = [
'lodging',
'food',
'drinks',
'sight',
'shopping',
'transport',
'beach',
'nature',
'activity',
] as const;
/**
* One place a search step found, normalized by the server from the tool's
* result. It never carries a URL: the client asks TREK's photo proxy with
* `photoKey` (a source id or `coords:lat,lng`) and shows only a same-origin
* answer. `openNow` is set only from the source's own flag and only while
* the trip is running; `inTripPlaceId` names the trip's place when it is the
* same one.
*/
export const assistantFoundPlaceSchema = z.object({
// `${toolCallId}:${index}`, the handle a suggestion for a day names it by.
ref: z.string().max(80),
name: z.string().max(120),
address: z.string().max(200).nullable(),
lat: latSchema,
lng: lngSchema,
kind: z.enum(ASSISTANT_FOUND_PLACE_KINDS).nullable(),
rating: z.number().min(0).max(5).nullable(),
openNow: z.boolean().nullable(),
googlePlaceId: z
.string()
.regex(/^[\w-]{1,200}$/)
.nullable(),
osmId: z.string().max(40).nullable(),
photoKey: z
.string()
.regex(/^([\w-]{1,200}|coords:-?\d{1,3}(\.\d{1,12})?,-?\d{1,3}(\.\d{1,12})?)$/)
.nullable(),
inTripPlaceId: idSchema.nullable(),
});
export type AssistantFoundPlace = z.infer<typeof assistantFoundPlaceSchema>;
/** The places one search step found: at most eight, `more` counts the rest. */
export const assistantPlacesSchema = z.object({
toolCallId: z.string().max(64),
places: z.array(assistantFoundPlaceSchema).max(20),
more: z.number().int().nonnegative(),
});
export type AssistantPlaces = z.infer<typeof assistantPlacesSchema>;
/**
* The weather the steps of an answer looked up, one entry per date.
* Temperatures are °C; the client converts them to the user's unit. `main`
* is the condition the weather icon is chosen by.
*/
export const assistantWeatherDaySchema = z.object({
dayId: idSchema.nullable(),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
main: z.string().max(20),
tempMax: z.number(),
tempMin: z.number().nullable(),
rainPct: z.number().int().min(0).max(100).nullable(),
kind: z.enum(['forecast', 'climate', 'current']),
});
export type AssistantWeatherDay = z.infer<typeof assistantWeatherDaySchema>;
export const assistantWeatherSchema = z.object({
days: z.array(assistantWeatherDaySchema).min(1).max(16),
});
export type AssistantWeather = z.infer<typeof assistantWeatherSchema>;
/**
* The tool the model ends an answer with to offer what the user may ask
* next. The server answers it itself and never shows it as a step.
*/
export const ASSISTANT_FOLLOW_UPS_TOOL = 'suggest_follow_ups';
/** The longest follow-up question the chat shows on one chip. */
export const MAX_FOLLOW_UP_CHARS = 80;
/** How many follow-up questions an answer offers at most. */
export const MAX_FOLLOW_UPS = 3;
/** The questions the model offers to ask next, fitting the conversation, in the user's language. */
export const assistantFollowUpsSchema = z.object({
questions: z.array(z.string().min(1).max(MAX_FOLLOW_UP_CHARS)).min(1).max(MAX_FOLLOW_UPS),
});
export type AssistantFollowUps = z.infer<typeof assistantFollowUpsSchema>;
/**
* The step a provider's own web search shows as in the chat: a tool call the
* server records for the step list, never sent back to the model as one.
*/
export const ASSISTANT_WEB_SEARCH_STEP = 'web_search';
/** How many pages one answer names as its sources at most. */
export const MAX_ASSISTANT_SOURCES = 12;
/**
* The pages an answer drew on from the provider's web search, in the order
* they were cited, each once: a link to open and its title.
*/
export const assistantSourcesSchema = z.object({
sources: z
.array(
z.object({
url: z
.string()
.max(2000)
.regex(/^https?:\/\//),
title: z.string().max(200),
}),
)
.min(1)
.max(MAX_ASSISTANT_SOURCES),
});
export type AssistantSources = z.infer<typeof assistantSourcesSchema>;
/** Where a running step looks: a point with a radius, or a box. */
export const assistantActivityAreaSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('point'),
lat: latSchema,
lng: lngSchema,
radiusM: z.number().int().min(50).max(50_000),
}),
z.object({
type: z.literal('bbox'),
south: latSchema,
west: lngSchema,
north: latSchema,
east: lngSchema,
}),
]);
export type AssistantActivityArea = z.infer<typeof assistantActivityAreaSchema>;
/**
* What a running step is doing, for the live line and the map: the place or
* query it names (shortened), and the area it searches when that is small
* enough to show. Only streamed, never stored.
*/
export const assistantActivitySchema = z.object({
toolCallId: z.string().max(64),
label: z.string().max(80).nullable(),
area: assistantActivityAreaSchema.nullable(),
});
export type AssistantActivity = z.infer<typeof assistantActivitySchema>;
/** The mentions of a user message as the server checked them, with the labels it took from the trip. */
export const assistantMentionsSchema = z.object({
items: z
.array(
z.object({
kind: z.enum(ASSISTANT_MENTION_KINDS),
id: idSchema,
label: z.string().max(120),
}),
)
.max(50),
});
export type AssistantMentions = z.infer<typeof assistantMentionsSchema>;
// ── Threads and messages ────────────────────────────────────────────────────
export const assistantThreadSummarySchema = z.object({
id: idSchema,
title: z.string(),
lastMessageAt: z.string(),
});
export type AssistantThreadSummary = z.infer<typeof assistantThreadSummarySchema>;
/** GET /threads: the user's latest threads in this trip. */
export const assistantThreadListResponseSchema = z.object({ threads: z.array(assistantThreadSummarySchema) });
export type AssistantThreadListResponse = z.infer<typeof assistantThreadListResponseSchema>;
/**
* A server-side approval gate on a tool call. `resolution` closes a request
* nobody decided: it expired after 24 hours, or the turn was cancelled.
*/
export const assistantToolApprovalSchema = z.object({
id: z.string(),
approved: z.boolean().optional(),
resolution: z.enum(['cancelled', 'expired']).optional(),
});
export type AssistantToolApproval = z.infer<typeof assistantToolApprovalSchema>;
/**
* The parts of a message, with the change, receipt and card parts read or
* written as given. Generic over the three schemas so the emitted declaration
* keeps each one's own Zod type instead of a precomputed object type, which a
* consumer without strictNullChecks would read differently from its own infer.
*/
function messagePartSchema<
Change extends z.ZodType<AssistantChangePreview>,
Applied extends z.ZodType<AssistantApplied>,
Card extends z.ZodType<AssistantCard>,
>(change: Change, applied: Applied, card: Card) {
return z.discriminatedUnion('type', [
z.object({ type: z.literal('text'), text: z.string() }),
// A file the user handed the assistant. Only its description is kept here, never its content; the
// server keeps the file under `attachmentId` (left out on messages from before it kept files).
z.object({
type: z.literal('attachment'),
name: z.string(),
mime: z.string(),
size: z.number().int().nonnegative(),
attachmentId: assistantAttachmentIdSchema.optional(),
}),
z.object({
type: z.literal('tool-call'),
toolCallId: z.string(),
toolName: z.string(),
args: z.record(z.string(), z.unknown()),
result: z.unknown().optional(),
isError: z.boolean().optional(),
approval: assistantToolApprovalSchema.optional(),
}),
z.object({ type: z.literal('data-trek-change'), data: change }),
z.object({ type: z.literal('data-trek-applied'), data: applied }),
z.object({ type: z.literal('data-trek-places'), data: assistantPlacesSchema }),
z.object({ type: z.literal('data-trek-weather'), data: assistantWeatherSchema }),
// What the model offers to ask next, at the end of an answer.
z.object({ type: z.literal('data-trek-follow-ups'), data: assistantFollowUpsSchema }),
// The pages the answer cites from the provider's web search.
z.object({ type: z.literal('data-trek-sources'), data: assistantSourcesSchema }),
// The card of one tool call: a read's beside the answer, an applied write's on the message that proposed it.
z.object({ type: z.literal('data-trek-card'), data: card }),
// Only on a user message.
z.object({ type: z.literal('data-trek-mentions'), data: assistantMentionsSchema }),
// A Studio page the turn looked at: what it was and its description, never the image.
z.object({ type: z.literal('data-trek-page-view'), data: assistantPageViewSchema }),
]);
}
/** One stored part of a message, in the order the model produced it, as a reader takes it. */
export const assistantMessagePartSchema = messagePartSchema(
assistantChangePreviewSchema,
assistantAppliedSchema,
assistantCardSchema,
);
export type AssistantMessagePart = z.infer<typeof assistantMessagePartSchema>;
/** The parts as the server writes them: a verb, entity or card this build cannot name is a bug in the writer. */
export const assistantMessagePartWriteSchema = messagePartSchema(
assistantChangePreviewWriteSchema,
assistantAppliedWriteSchema,
assistantCardWriteSchema,
);
/**
* A message's parts as they are read back: a `data-trek-*` part this build
* does not know, or one that no longer reads, is dropped, so a part a later
* build added never blanks the message around it. Any other broken part
* still fails the whole list. A known part reads through its tolerant fields
* (a later verb, entity or card kind); parts are written strictly, with
* `assistantMessagePartWriteSchema`.
*/
export const assistantStoredPartsSchema = z
.array(
z.union([
assistantMessagePartSchema,
z.object({ type: z.string().startsWith('data-trek-') }).transform(() => null),
]),
)
.transform((parts) => parts.filter((part): part is AssistantMessagePart => part !== null));
export const assistantMessageSchema = z.object({
id: z.string(),
role: z.enum(['user', 'assistant']),
parts: z.array(assistantMessagePartSchema),
status: z.enum(['complete', 'awaiting_approval', 'aborted', 'error']),
createdAt: z.string(),
});
export type AssistantMessage = z.infer<typeof assistantMessageSchema>;
/** GET /threads/:threadId: the thread with its latest 50 messages, oldest first. */
export const assistantThreadResponseSchema = z.object({
thread: assistantThreadSummarySchema,
messages: z.array(assistantMessageSchema),
});
export type AssistantThreadResponse = z.infer<typeof assistantThreadResponseSchema>;
/** POST /threads/:threadId/found-places: the new assistant message holding the suggested change. */
export const assistantAddFoundPlaceResponseSchema = z.object({ message: assistantMessageSchema });
export type AssistantAddFoundPlaceResponse = z.infer<typeof assistantAddFoundPlaceResponseSchema>;
/** POST /tool-calls/:toolCallId/undo */
export const assistantUndoResponseSchema = z.object({ undone: z.literal(true) });
export type AssistantUndoResponse = z.infer<typeof assistantUndoResponseSchema>;
// ── Stream ──────────────────────────────────────────────────────────────────
/** The marker the last `data:` event of a stream carries instead of a chunk. */
export const UI_STREAM_DONE = '[DONE]';
/**
* The chunks of an assistant stream. A client ignores a chunk whose type it
* does not know, so new types can be added without breaking older clients.
* An error names an `AssistantErrorCode`; one this client does not know reads
* as `generic`.
*/
export const uiStreamChunkSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('start'), messageId: z.string() }),
z.object({ type: z.literal('start-step') }),
z.object({ type: z.literal('text-start'), id: z.string() }),
z.object({ type: z.literal('text-delta'), id: z.string(), delta: z.string() }),
z.object({ type: z.literal('text-end'), id: z.string() }),
z.object({ type: z.literal('tool-input-start'), toolCallId: z.string(), toolName: z.string() }),
z.object({
type: z.literal('tool-input-available'),
toolCallId: z.string(),
toolName: z.string(),
input: z.record(z.string(), z.unknown()),
}),
// approvalId is the toolCallId: one id addresses the call and its decision.
z.object({ type: z.literal('tool-approval-request'), approvalId: z.string(), toolCallId: z.string() }),
z.object({ type: z.literal('tool-output-available'), toolCallId: z.string(), output: z.unknown() }),
z.object({ type: z.literal('tool-output-error'), toolCallId: z.string(), errorText: z.string() }),
z.object({ type: z.literal('tool-output-denied'), toolCallId: z.string() }),
z.object({ type: z.literal('data-trek-thread'), data: z.object({ threadId: idSchema, title: z.string() }) }),
z.object({ type: z.literal('data-trek-change'), data: assistantChangePreviewSchema }),
z.object({ type: z.literal('data-trek-applied'), data: assistantAppliedSchema }),
z.object({ type: z.literal('data-trek-places'), data: assistantPlacesSchema }),
z.object({ type: z.literal('data-trek-weather'), data: assistantWeatherSchema }),
z.object({ type: z.literal('data-trek-follow-ups'), data: assistantFollowUpsSchema }),
z.object({ type: z.literal('data-trek-sources'), data: assistantSourcesSchema }),
z.object({ type: z.literal('data-trek-card'), data: assistantCardSchema }),
// Live progress of a running step; the message never keeps it.
z.object({
type: z.literal('data-trek-activity'),
data: assistantActivitySchema,
transient: z.literal(true).optional(),
}),
// A Studio page the turn asks the Studio tab to draw and upload; the message never keeps it.
z.object({
type: z.literal('data-trek-render-request'),
data: assistantPageRenderSchema,
transient: z.literal(true).optional(),
}),
z.object({ type: z.literal('data-trek-page-view'), data: assistantPageViewSchema }),
z.object({
type: z.literal('data-trek-quota'),
data: z.object({ used: z.number().int().nonnegative(), limit: z.number().int().nonnegative() }),
}),
z.object({ type: z.literal('finish-step') }),
z.object({ type: z.literal('finish'), finishReason: z.enum(['stop', 'tool-calls', 'error']).optional() }),
z.object({ type: z.literal('error'), errorText: assistantErrorCodeSchema.catch('generic') }),
z.object({ type: z.literal('abort') }),
]);
export type UiStreamChunk = z.infer<typeof uiStreamChunkSchema>;
@@ -0,0 +1,49 @@
import { idSchema } from '../../common/primitives.schema';
import { atlasCountryCodeSchema, atlasRegionCodeSchema, atlasTallySchema } from './atlas-country.card';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** When a wish is planned for: a year, a month or a day ("2027", "2027-05", "2027-05-14"). */
export const atlasTargetDateSchema = z.string().regex(/^\d{4}(-\d{2}(-\d{2})?)?$/);
/** One wish of the bucket list. Never its coordinates: the card names it, the Atlas places it. */
export const atlasBucketEntrySchema = z.object({
/** Null on a wish that is still to be added. */
id: idSchema.nullable(),
name: cardText(120),
/** Null without a country, and for a legacy alpha-3 code (the card shows a star then). */
countryCode: atlasCountryCodeSchema.nullable(),
regionCode: atlasRegionCodeSchema.nullable(),
targetDate: atlasTargetDateSchema.nullable(),
notes: cardText(200).nullable(),
/** The day the wish came true. */
reachedOn: cardDateSchema.nullable(),
reachedFrom: z.enum(['manual', 'dawarich']).nullable(),
});
/** What an add, a change or a removal does to the bucket list. */
export const atlasBucketChangeSchema = z.object({
op: z.enum(['add', 'update', 'remove']),
/** The wish as it is: set on a change and a removal. */
before: atlasBucketEntrySchema.nullable(),
/** The same wish is on the list already, so the add will be refused. */
duplicate: z.boolean(),
/** How many wishes the list holds. */
wishes: atlasTallySchema.nullable(),
});
/**
* Wishes of the bucket list: the open ones first, soonest first, then the ones
* that came true. An answer shows the list; a change card shows the one wish
* it adds, changes or removes (`items[0]`).
*/
export const atlasBucketCardSchema = z.object({
kind: z.literal('atlasBucket'),
items: z.array(atlasBucketEntrySchema).min(1).max(12),
more: cardCountSchema,
change: atlasBucketChangeSchema.nullable(),
});
export type AtlasBucketCard = z.infer<typeof atlasBucketCardSchema>;
export type AtlasBucketEntry = z.infer<typeof atlasBucketEntrySchema>;
export type AtlasBucketChange = z.infer<typeof atlasBucketChangeSchema>;
@@ -0,0 +1,107 @@
import { atlasBucketCardSchema, type AtlasBucketCard, type AtlasBucketEntry } from './atlas-bucket.card';
import { atlasCountryCardSchema, type AtlasCountryCard } from './atlas-country.card';
import { atlasPassportCardSchema, type AtlasPassportCard } from './atlas-passport.card';
import { ATLAS_APPLIED_ENTITIES, ATLAS_CARD_SCHEMAS } from './atlas.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const passport: AtlasPassportCard = {
kind: 'atlasPassport',
countries: { visited: 23, planned: 4, idea: 1 },
totals: { trips: 48, days: 410, places: 990, cities: 312, flownKm: 182_300 },
flags: [
{ code: 'JP', status: 'visited' },
{ code: 'PT', status: 'planned' },
],
moreFlags: 21,
continents: [{ name: 'Europe', visited: 14, planned: 2 }],
nextTrip: { title: 'Lisbon', startDate: '2026-11-03', daysUntil: 12 },
streakYears: 3,
};
const kyoto = { code: 'JP-26', name: 'Kyoto', before: null, after: 'visited' as const };
const markJapan: NonNullable<AtlasCountryCard['change']> = {
op: 'mark',
region: kyoto,
after: 'visited',
countries: { before: 23, after: 24 },
regions: { before: 0, after: 1 },
};
const kyotoTrip = { id: 7, title: 'Kyoto in spring', startDate: '2024-04-03', endDate: '2024-04-14' };
const country: AtlasCountryCard = {
kind: 'atlasCountry',
code: 'JP',
status: 'planned',
markedBy: null,
placeCount: 14,
tripCount: 2,
trips: [kyotoTrip],
moreTrips: 1,
places: ['Fushimi Inari'],
morePlaces: 13,
change: markJapan,
};
const lights: AtlasBucketEntry = {
id: null,
name: 'Northern lights',
countryCode: 'IS',
regionCode: null,
targetDate: '2027-02',
notes: 'Glacier hike and hot springs',
reachedOn: null,
reachedFrom: null,
};
const bucket: AtlasBucketCard = {
kind: 'atlasBucket',
items: [lights],
more: 0,
change: { op: 'add', before: null, duplicate: false, wishes: { before: 7, after: 8 } },
};
describe('the atlas cards', () => {
it('CARDS-ATLAS-001: the passport, a country change and a bucket wish parse as themselves and in the union', () => {
expect(atlasPassportCardSchema.parse(passport)).toEqual(passport);
expect(atlasCountryCardSchema.parse(country)).toEqual(country);
expect(atlasBucketCardSchema.parse(bucket)).toEqual(bucket);
for (const card of [passport, country, bucket]) {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(JSON.stringify(card)).not.toMatch(/https?:/);
}
expect(ATLAS_CARD_SCHEMAS).toHaveLength(3);
expect(ATLAS_APPLIED_ENTITIES).toEqual(['atlas']);
});
it('CARDS-ATLAS-002: a lower case or alpha-3 country code and a region outside the ISO form are refused', () => {
expect(atlasCountryCardSchema.safeParse({ ...country, code: 'jp' }).success).toBe(false);
expect(atlasCountryCardSchema.safeParse({ ...country, code: 'JPN' }).success).toBe(false);
const region = { ...kyoto, code: 'Kyoto' };
expect(atlasCountryCardSchema.safeParse({ ...country, change: { ...markJapan, region } }).success).toBe(false);
const wish = { ...lights, countryCode: 'isl' };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(false);
});
it('CARDS-ATLAS-003: lists past their bounds and an empty bucket card do not parse, and read as null', () => {
const flags = Array.from({ length: 41 }, () => ({ code: 'FR', status: 'visited' as const }));
expect(atlasPassportCardSchema.safeParse({ ...passport, flags }).success).toBe(false);
const trips = Array.from({ length: 5 }, () => kyotoTrip);
expect(atlasCountryCardSchema.safeParse({ ...country, trips }).success).toBe(false);
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [] }).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...bucket, items: [] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...passport, countries: { visited: -1, planned: 0, idea: 0 } })).toBeNull();
});
it('CARDS-ATLAS-004: a target date is a year, a month or a day, and a counter after a change may be unknown', () => {
for (const targetDate of ['2027', '2027-05', '2027-05-14']) {
const wish = { ...lights, targetDate };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(true);
}
const wish = { ...lights, targetDate: 'May 2027' };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(false);
const unknown = { ...markJapan, after: 'unknown' as const, countries: { before: 23, after: null } };
expect(atlasCountryCardSchema.parse({ ...country, change: unknown }).change?.countries?.after).toBeNull();
});
});
@@ -0,0 +1,70 @@
import { visitStatusSchema } from '../../atlas/atlas.schema';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** ISO 3166-1 alpha-2 in upper case: the only code a flag and a country name are drawn from. */
export const atlasCountryCodeSchema = z.string().regex(/^[A-Z]{2}$/);
/** ISO 3166-2 as the atlas stores a region ("DE-BY", "US-CA"). */
export const atlasRegionCodeSchema = z.string().regex(/^[A-Z]{2}-[A-Z0-9]{1,8}$/);
/** A counter a change moves. `after` is null when the user's trips decide it, known once the change is applied. */
export const atlasTallySchema = z.object({ before: cardCountSchema, after: cardCountSchema.nullable() });
/** Where a country or a region stands after a change: `none` is off the map, `unknown` is up to the trips. */
export const atlasStatusAfterSchema = z.enum(['visited', 'planned', 'idea', 'none', 'unknown']);
/** A trip that went to the country, as a line of the card. */
const atlasTripLineSchema = z.object({
id: idSchema,
title: cardText(80),
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
});
/** What a mark or an unmark does to the country, or to one of its regions. */
export const atlasCountryChangeSchema = z.object({
op: z.enum(['mark', 'unmark']),
/** Set when the change is about one region of the country. */
region: z
.object({
code: atlasRegionCodeSchema,
name: cardText(80),
before: visitStatusSchema.nullable(),
after: atlasStatusAfterSchema,
})
.nullable(),
/** The country's own status once the change is applied. */
after: atlasStatusAfterSchema,
/** Visited countries of the whole atlas; null when the atlas could not be read. */
countries: atlasTallySchema.nullable(),
/** Visited regions of this country, on region changes only. */
regions: atlasTallySchema.nullable(),
});
/**
* One country of the atlas: its status, who marked it, the trips and places
* that put it there. An answer (`change` null) shows it as it is now; a change
* card shows it as it was, with what the mark or unmark does to it and to the
* visited counters.
*/
export const atlasCountryCardSchema = z.object({
kind: z.literal('atlasCountry'),
code: atlasCountryCodeSchema,
/** Now on an answer, before the change on a change card; null when the country is not on the map. */
status: visitStatusSchema.nullable(),
markedBy: z.enum(['manual', 'dawarich', 'region']).nullable(),
placeCount: cardCountSchema.nullable(),
tripCount: cardCountSchema.nullable(),
trips: z.array(atlasTripLineSchema).max(4),
moreTrips: cardCountSchema,
places: z.array(cardText(80)).max(8),
morePlaces: cardCountSchema,
change: atlasCountryChangeSchema.nullable(),
});
export type AtlasCountryCard = z.infer<typeof atlasCountryCardSchema>;
export type AtlasCountryChange = z.infer<typeof atlasCountryChangeSchema>;
export type AtlasTally = z.infer<typeof atlasTallySchema>;
export type AtlasStatusAfter = z.infer<typeof atlasStatusAfterSchema>;
@@ -0,0 +1,52 @@
import { visitStatusSchema } from '../../atlas/atlas.schema';
import { atlasCountryCodeSchema } from './atlas-country.card';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** The continents of CONTINENT_MAP and its fallback; the client names them with the Atlas page's own words. */
export const ATLAS_CARD_CONTINENTS = [
'Europe',
'Asia',
'North America',
'South America',
'Africa',
'Oceania',
'Antarctica',
'Other',
] as const;
export const atlasCardContinentSchema = z.enum(ATLAS_CARD_CONTINENTS);
export type AtlasCardContinent = z.infer<typeof atlasCardContinentSchema>;
/**
* The user's travel picture as the Atlas page shows it: visited, planned and
* wished-for countries, the trips, days, places and cities behind them, the
* distance flown, the flags, the continents, the next trip and the streak.
*/
export const atlasPassportCardSchema = z.object({
kind: z.literal('atlasPassport'),
countries: z.object({ visited: cardCountSchema, planned: cardCountSchema, idea: cardCountSchema }),
totals: z.object({
trips: cardCountSchema,
days: cardCountSchema,
places: cardCountSchema,
cities: cardCountSchema,
/** Rounded kilometres; null when nothing was flown. */
flownKm: cardCountSchema.nullable(),
}),
/** Visited countries, latest first, then planned ones, soonest first. */
flags: z.array(z.object({ code: atlasCountryCodeSchema, status: visitStatusSchema })).max(40),
moreFlags: cardCountSchema,
continents: z
.array(z.object({ name: atlasCardContinentSchema, visited: cardCountSchema, planned: cardCountSchema }))
.max(8),
nextTrip: z
.object({
title: cardText(80),
startDate: cardDateSchema.nullable(),
daysUntil: z.number().int().min(0).max(36_500).nullable(),
})
.nullable(),
streakYears: z.number().int().min(0).max(200).nullable(),
});
export type AtlasPassportCard = z.infer<typeof atlasPassportCardSchema>;
@@ -0,0 +1,19 @@
import { atlasBucketCardSchema } from './atlas-bucket.card';
import { atlasCountryCardSchema } from './atlas-country.card';
import { atlasPassportCardSchema } from './atlas-passport.card';
export * from './atlas-bucket.card';
export * from './atlas-country.card';
export * from './atlas-passport.card';
/**
* What the atlas brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const ATLAS_CARD_SCHEMAS = [atlasPassportCardSchema, atlasCountryCardSchema, atlasBucketCardSchema] as const;
export const ATLAS_VERB_KEYS = [] as const;
/** A country, a region or a wish of the bucket list: the receipt opens the Atlas. */
export const ATLAS_APPLIED_ENTITIES = ['atlas'] as const;
@@ -0,0 +1,90 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantChangePreviewSchema } from '../assistant.schema';
import { BOOK_DESIGN_CARD_LIMITS, bookDesignCardSchema } from './book-design.card';
import { BOOK_DESIGN_VERB_KEYS } from './book-design.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
// BKDCARD-001 to BKDCARD-004
function card(over: Record<string, unknown> = {}) {
return {
kind: 'bookDesign',
change: 'proposed',
journeyId: 4,
designId: 'd-1',
baseVersion: 7,
style: 'editorial',
paper: '#faf8f4',
ink: '#1a1a1a',
accent: '#b45309',
heading: 'playfair',
body: 'garamond',
spreads: [
{
spreadId: 'sp-1',
index: 0,
action: 'replace',
beat: 'cover',
chapter: null,
entryId: null,
photoCount: 1,
severe: 0,
warn: 0,
},
{
spreadId: 'sp-9',
index: 3,
action: 'insert',
beat: 'hero',
chapter: 'Alfama',
entryId: 12,
photoCount: 1,
severe: 0,
warn: 1,
},
],
more: 0,
leftOut: 3,
revisionId: null,
skipped: [],
...over,
};
}
describe('the book design card', () => {
it('BKDCARD-001: reads a design card through the union, as itself', () => {
const parsed = trekCardSchema.parse(card());
expect(parsed.kind).toBe('bookDesign');
expect(bookDesignCardSchema.parse(parsed).spreads).toHaveLength(2);
expect(storedTrekCardSchema.parse(card({ change: 'applied', revisionId: 5 }))).toMatchObject({ revisionId: 5 });
});
it('BKDCARD-002: a field past its bound, an unknown style or reason, reads as no card', () => {
const page = card().spreads[1];
const longChapter = [{ ...page, chapter: 'x'.repeat(BOOK_DESIGN_CARD_LIMITS.chapter + 1) }];
expect(storedTrekCardSchema.parse(card({ spreads: longChapter }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ style: 'baroque' }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ skipped: [{ spreadId: 'sp-1', reason: 'tired' }] }))).toBeNull();
const many = Array.from({ length: BOOK_DESIGN_CARD_LIMITS.spreads + 1 }, () => page);
expect(storedTrekCardSchema.parse(card({ spreads: many }))).toBeNull();
});
it('BKDCARD-003: rides on a change preview with its own verb', () => {
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'designBook',
subject: '',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card(),
});
expect([preview.verbKey, preview.card?.kind]).toEqual(['designBook', 'bookDesign']);
});
it('BKDCARD-004: names the verbs of the book-level changes in the shared enum', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining([...BOOK_DESIGN_VERB_KEYS]));
});
});
@@ -0,0 +1,66 @@
import { BOOK_DESIGN_SKIP_REASONS } from '../../book/book-design-tools.schema';
import { bookDesignIdSchema, bookSpreadIdSchema } from '../../book/book-ops.schema';
import { BOOK_FONTS_IDS } from '../../book/book.schema';
import { BOOK_DESIGN_STYLES } from '../../book/design/design-directives.schema';
import { BOOK_DESIGN_ACTIONS } from '../../book/design/design-merge';
import { BOOK_DESIGN_BEATS } from '../../book/design/design-pacing';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardHexColorSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A whole-book design as the Studio's chat shows it: the book's look (style,
* paper, ink, accent, the two typefaces) and the plan page by page, what
* each page becomes and how many findings the server's check left on it.
* `none` is the answer of `design_book` (a draft, nothing proposed yet),
* `proposed` the held `apply_book_design`, `applied` its receipt with the
* revision that takes it back and the pages it left as they were. The pages
* themselves are drawn from the draft (GET /api/journeys/:id/book-designs/:designId),
* never carried in the card.
*/
export const BOOK_DESIGN_CARD_LIMITS = { spreads: 120, chapter: 40 } as const;
export const BOOK_DESIGN_CARD_CHANGES = ['none', 'proposed', 'applied'] as const;
/** One page of the plan as a card names it. */
export const bookDesignCardSpreadSchema = z.object({
spreadId: bookSpreadIdSchema,
index: cardCountSchema,
action: z.enum(BOOK_DESIGN_ACTIONS),
beat: z.enum(BOOK_DESIGN_BEATS),
chapter: cardText(BOOK_DESIGN_CARD_LIMITS.chapter).nullable(),
entryId: idSchema.nullable(),
photoCount: cardCountSchema,
severe: cardCountSchema,
warn: cardCountSchema,
});
export type BookDesignCardSpread = z.infer<typeof bookDesignCardSpreadSchema>;
export const bookDesignCardSchema = z.object({
kind: z.literal('bookDesign'),
change: z.enum(BOOK_DESIGN_CARD_CHANGES),
journeyId: idSchema,
designId: bookDesignIdSchema,
/** The book's version the draft was made against; null for a journey without a book. */
baseVersion: cardCountSchema.nullable(),
style: z.enum(BOOK_DESIGN_STYLES),
paper: cardHexColorSchema,
ink: cardHexColorSchema,
accent: cardHexColorSchema,
heading: z.enum(BOOK_FONTS_IDS),
body: z.enum(BOOK_FONTS_IDS),
spreads: z.array(bookDesignCardSpreadSchema).max(BOOK_DESIGN_CARD_LIMITS.spreads),
/** Plan pages past the ones listed. */
more: cardCountSchema,
/** Photos of the journey the design left out. */
leftOut: cardCountSchema,
/** Once applied: the revision the undo restores. */
revisionId: idSchema.nullable(),
/** Once applied: the pages the apply left as they were, and why. */
skipped: z
.array(z.object({ spreadId: bookSpreadIdSchema, reason: z.enum(BOOK_DESIGN_SKIP_REASONS) }))
.max(BOOK_DESIGN_CARD_LIMITS.spreads),
});
export type BookDesignCard = z.infer<typeof bookDesignCardSchema>;
@@ -0,0 +1,20 @@
import { bookDesignCardSchema } from './book-design.card';
export * from './book-design.card';
/**
* What the assistant's whole-book design brings to the chat: the card of a
* design and its proposal, and the verbs of the book-level changes (the
* design applied, the page format and numbers, a page copied, a layout kept
* or taken away). They touch pages of the book, so they name the photo
* book's own entity (`book_page`, book.contract.ts) and add none.
*/
export const BOOK_DESIGN_CARD_SCHEMAS = [bookDesignCardSchema] as const;
export const BOOK_DESIGN_VERB_KEYS = [
'designBook',
'setBookSetup',
'setBookTheme',
'duplicateBookPage',
'saveBookLayout',
'removeBookLayout',
] as const;
@@ -0,0 +1,119 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema, assistantChangePreviewSchema } from '../assistant.schema';
import { BOOK_PAGE_CARD_LIMITS, bookPageCardSchema, type BookCardPage } from './book-page.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
// BOOKCARD-001 to BOOKCARD-007
function page(over: Partial<BookCardPage> = {}): BookCardPage {
return { spreadId: 'sp-lisbon', index: 2, role: 'inner', number: 1, photos: 3, ...over };
}
function card(over: Record<string, unknown> = {}) {
return {
kind: 'bookPage',
journeyId: 4,
change: 'changed',
baseVersion: 7,
pages: [page()],
count: 0,
movedTo: null,
ops: [
{ op: 'layout', template: 'two-up' },
{ op: 'background', color: '#f4efe6' },
],
cover: null,
layout: { kind: 'template', id: 'two-up', name: null },
photosAdded: 2,
findings: [{ code: 'overlap', severity: 'severe' }],
moreFindings: 0,
...over,
};
}
describe('the book page card', () => {
it('BOOKCARD-001: reads a full card through the union, as itself, its operations parsed by the book engine', () => {
const parsed = trekCardSchema.parse(card());
expect(parsed.kind).toBe('bookPage');
const own = bookPageCardSchema.parse(parsed);
expect(own.ops).toHaveLength(2);
expect(own.ops[0]).toMatchObject({ op: 'layout', template: 'two-up' });
});
it('BOOKCARD-002: a cover change carries its arguments, a new book no page and no version', () => {
const cover = { template: 'cover-full', photoId: 81, title: 'Portugal', subtitle: null };
expect(bookPageCardSchema.safeParse(card({ ops: [], cover, layout: null })).success).toBe(true);
const fresh = card({ change: 'new', baseVersion: null, pages: [], count: 5, ops: [], layout: null, findings: [] });
expect(bookPageCardSchema.safeParse(fresh).success).toBe(true);
});
it('BOOKCARD-003: an operation the engine refuses, an unknown template or a page past the cap reads as no card', () => {
expect(storedTrekCardSchema.parse(card({ ops: [{ op: 'explode' }] }))).toBeNull();
const cover = { template: 'nope', photoId: null, title: null, subtitle: null };
expect(storedTrekCardSchema.parse(card({ cover }))).toBeNull();
const eleven = Array.from({ length: 11 }, (_, i) => page({ spreadId: `sp-${i}`, index: i }));
expect(storedTrekCardSchema.parse(card({ pages: eleven }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ pages: [page({ spreadId: 'not a page id' })] }))).toBeNull();
});
it('BOOKCARD-004: holds at most six findings, each a known code and severity', () => {
const findings = Array.from({ length: BOOK_PAGE_CARD_LIMITS.findings + 1 }, () => ({
code: 'empty_frame',
severity: 'warn',
}));
expect(bookPageCardSchema.safeParse(card({ findings })).success).toBe(false);
expect(bookPageCardSchema.safeParse(card({ findings: [{ code: 'ugly', severity: 'warn' }] })).success).toBe(false);
expect(bookPageCardSchema.safeParse(card({ findings: findings.slice(1), moreFindings: 3 })).success).toBe(true);
});
it('BOOKCARD-005: rides on a change preview', () => {
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'editBookPage',
subject: 'Lisbon',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card(),
});
expect(preview.verbKey).toBe('editBookPage');
expect(preview.card?.kind).toBe('bookPage');
});
it('BOOKCARD-006: names its verbs and its entity in the shared enums', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(
expect.arrayContaining([
'createBook',
'addBookPages',
'editBookPage',
'moveBookPage',
'removeBookPages',
'setBookCover',
]),
);
const applied = assistantAppliedSchema.parse({
toolCallId: 'call_1',
entity: 'book_page',
ids: [],
dayId: null,
undoUntil: null,
});
expect(applied.entity).toBe('book_page');
});
it('BOOKCARD-007: carries the page after as the server made it; without one it reads, an unreadable one drops itself', () => {
const after = { id: 'sp-lisbon', role: 'inner', background: '#ffffff', elements: [], parked: [], entryId: null };
expect(bookPageCardSchema.parse(card({ after })).after).toEqual(after);
// A card from before the page rode on it, as the thread keeps it, reads as it was.
expect(bookPageCardSchema.parse(card()).after).toBeUndefined();
expect(storedTrekCardSchema.parse(card())).toMatchObject({ kind: 'bookPage', journeyId: 4 });
// A page a later build cannot read drops itself, never the card: the Studio then runs the operations.
const unread = { ...after, background: 'white' };
const kept = bookPageCardSchema.parse(card({ after: unread }));
expect(kept.after).toBeUndefined();
expect(kept.ops).toHaveLength(2);
expect(storedTrekCardSchema.parse(card({ after: unread }))).toMatchObject({ kind: 'bookPage', journeyId: 4 });
});
});
@@ -0,0 +1,116 @@
import {
BOOK_FINDING_CODES,
BOOK_OP_LIMITS,
bookAnyTemplateIdSchema,
bookPageOpSchema,
bookSpreadIdSchema,
} from '../../book/book-ops.schema';
import { bookSpreadSchema, MAX_BOOK_TITLE, MAX_SPREADS } from '../../book/book.schema';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A change to a journey's photo book as the Studio's chat shows it: the pages
* a held book write works on, what it lays them out on and brings onto them,
* and what the server's check of the result found. For an edit or the cover
* it carries the page after as the server's trial of the change made it, so
* the Studio draws the page before and after with the view the editor uses,
* never from an image, and the page after as the server would write it. The
* page operations ride along for a card without that page and for a book
* that moved on since the trial: the Studio runs them on its own book with
* the same engine. Once applied it names the pages as the change left them.
*/
/** How much of a change a card carries; the server cuts to the same numbers. */
export const BOOK_PAGE_CARD_LIMITS = { findings: 6, layout: 60 } as const;
/** What the change does to its pages: makes them, changes them, moves one, or deletes them. */
export const BOOK_PAGE_CARD_CHANGES = ['new', 'changed', 'moved', 'willDelete'] as const;
/** One page as a card names it. */
export const bookCardPageSchema = z.object({
spreadId: bookSpreadIdSchema,
/** Where it stands in the book, the cover at 0. */
index: z
.number()
.int()
.min(0)
.max(MAX_SPREADS - 1),
role: bookSpreadSchema.shape.role.unwrap(),
/** Its place among the double pages, from 1; null for a single page (the covers, the first and the last). */
number: z.number().int().min(1).max(MAX_SPREADS).nullable(),
/** Photos placed on it. */
photos: cardCountSchema,
});
export type BookCardPage = z.infer<typeof bookCardPageSchema>;
/** A finding of the server's check, by its code: the client names it in the user's language. */
export const bookCardFindingSchema = z.object({
code: z.enum(BOOK_FINDING_CODES),
severity: z.enum(['severe', 'warn', 'info']),
});
export type BookCardFinding = z.infer<typeof bookCardFindingSchema>;
/** The layout a change lays a page out on. A saved layout carries its own name; the built-in ones the client names. */
export const bookCardLayoutSchema = z.object({
kind: z.enum(['template', 'grid', 'saved', 'auto']),
id: cardText(BOOK_PAGE_CARD_LIMITS.layout),
name: cardText(BOOK_PAGE_CARD_LIMITS.layout).nullable(),
});
export type BookCardLayout = z.infer<typeof bookCardLayoutSchema>;
/** `set_book_cover`'s arguments, null where the call leaves a part of the cover as it is. */
export const bookCardCoverSchema = z.object({
template: bookAnyTemplateIdSchema.nullable(),
photoId: idSchema.nullable(),
title: z.string().max(MAX_BOOK_TITLE).nullable(),
subtitle: z.string().max(MAX_BOOK_TITLE).nullable(),
});
export type BookCardCover = z.infer<typeof bookCardCoverSchema>;
export const bookPageCardSchema = z.object({
kind: z.literal('bookPage'),
journeyId: idSchema,
change: z.enum(BOOK_PAGE_CARD_CHANGES),
/** The book's version the change was checked against; null for a journey without a book. */
baseVersion: cardCountSchema.nullable(),
/**
* The pages the change works on, as they stand before it: the page edited,
* the cover, the page moved, the pages deleted, the page new ones follow.
* Once applied, the pages as the change left them, new ones included.
*/
pages: z.array(bookCardPageSchema).max(BOOK_OP_LIMITS.pagesPerCall),
/** How many pages the change adds or deletes; for a new book, its pages. */
count: cardCountSchema,
/** Where a moved page lands among the double pages, from 1. */
movedTo: z.number().int().min(1).max(MAX_SPREADS).nullable(),
/**
* `edit_book_page`'s operations, to draw the page after where the card has
* no `after` or the Studio's book moved on from `baseVersion`; empty for
* another tool, when too long to carry, or when the page after needs their
* room.
*/
ops: z.array(bookPageOpSchema).max(BOOK_OP_LIMITS.opsPerCall),
cover: bookCardCoverSchema.nullable(),
/**
* The page an edit or the cover leaves, as the server's trial of the change
* made it with the journey's photos, words and figures: a caption from its
* photo's caption, a text from its entry, a map from the route. The Studio
* draws the page after from it while its book is at `baseVersion`. Absent
* on a card from before it, on a page too heavy to carry and on another
* tool's card, where the Studio runs `ops` or `cover` on its own book, as
* it does once its book moved on; absent once applied, where it draws the
* page as it is. One a later build cannot read drops itself, never the card.
*/
after: bookSpreadSchema.optional().catch(undefined),
layout: bookCardLayoutSchema.nullable(),
/** Photos the change brings onto its pages that were not on them. */
photosAdded: cardCountSchema,
/** The check's findings on the pages after the change, the most severe first. */
findings: z.array(bookCardFindingSchema).max(BOOK_PAGE_CARD_LIMITS.findings),
/** Severe findings and warnings past those; the info ones past them are not counted. */
moreFindings: cardCountSchema,
});
export type BookPageCard = z.infer<typeof bookPageCardSchema>;
@@ -0,0 +1,23 @@
import { bookPageCardSchema } from './book-page.card';
export * from './book-page.card';
/**
* What the Studio's photo book brings to the assistant chat: the kind of card
* a held book write draws, the verbs of its change cards and what an applied
* one touches. cards/index.ts and assistant.schema.ts spread these into the
* card union and the shared enums, so a new kind, verb or entity is added
* here and nowhere else.
*/
export const BOOK_CARD_SCHEMAS = [bookPageCardSchema] as const;
/** A book laid down, pages added, changed, moved or deleted, the cover set. */
export const BOOK_VERB_KEYS = [
'createBook',
'addBookPages',
'editBookPage',
'moveBookPage',
'removeBookPages',
'setBookCover',
] as const;
/** A page of a journey's book; the receipt opens the Studio on it. Pages have string ids, so the card names them. */
export const BOOK_APPLIED_ENTITIES = ['book_page'] as const;
@@ -0,0 +1,125 @@
import {
BOOKING_CHANGED_FIELDS,
bookingCardSchema,
type BookingItem,
type BookingLeg,
type BookingStay,
type BookingTicket,
} from './booking.card';
import { BOOKING_APPLIED_ENTITIES, BOOKING_VERB_KEYS } from './booking.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const day = { id: 31, number: 1, date: '2026-06-03' };
const LEG: BookingLeg = {
carrier: 'Lufthansa',
number: 'LH 400',
departs: '08:15',
departsDay: day,
arrives: '11:05',
arrivesDay: day,
minutes: 530,
seat: '12A',
platform: null,
};
const TICKET: BookingTicket = {
shape: 'ticket',
stops: [
{ name: 'Frankfurt', code: 'FRA', lat: 50.03, lng: 8.57 },
{ name: 'New York', code: 'JFK', lat: 40.64, lng: -73.78 },
],
legs: [LEG],
minutes: 530,
mappable: true,
};
const STAY: BookingStay = {
shape: 'stay',
accommodationId: 601,
placeId: 12,
address: 'Invalidenstraße 38',
lat: 52.53,
lng: 13.38,
photoKey: 'ChIJmercure',
checkIn: { day, from: '15:00', until: '20:00' },
checkOut: { day: { id: 33, number: 3, date: '2026-06-05' }, by: '11:00' },
nights: 2,
};
const ticket: BookingItem = {
tripId: 4,
tripTitle: null,
reservationId: 501,
type: 'flight',
title: 'Frankfurt to New York',
status: 'confirmed',
needsReview: false,
hasReference: true,
price: { amount: 420, currency: 'EUR' },
travelers: [{ id: 7, name: 'mia', avatarKey: 'mia.png' }],
moreTravelers: 0,
changed: [],
body: TICKET,
};
const stay: BookingItem = {
...ticket,
reservationId: null,
type: 'hotel',
status: null,
body: STAY,
};
const card = (items: unknown[], extra: Record<string, unknown> = {}) => ({
kind: 'booking',
change: 'none',
items,
more: 0,
...extra,
});
describe('bookingCardSchema', () => {
it('CARDBOOK-001: takes a ticket, a stay and a venue in one card, and the union reads it', () => {
const body = { shape: 'venue', day, starts: '19:00', ends: null, location: 'Borchardt', placeId: 13 };
const venue = { ...ticket, body: { ...body, lat: null, lng: null } };
expect(bookingCardSchema.safeParse(card([ticket, stay, venue])).success).toBe(true);
expect(trekCardSchema.safeParse(card([ticket], { change: 'update' })).success).toBe(true);
});
it('CARDBOOK-002: holds one to eight bookings and counts the rest', () => {
expect(bookingCardSchema.safeParse(card([])).success).toBe(false);
expect(bookingCardSchema.safeParse(card(Array.from({ length: 9 }, () => ticket))).success).toBe(false);
expect(bookingCardSchema.safeParse(card([ticket], { more: -1 })).success).toBe(false);
});
it('CARDBOOK-003: refuses a picture address or a coordinate key as photo key, and a clock past 23:59', () => {
const photo = (photoKey: string) => card([{ ...stay, body: { ...STAY, photoKey } }]);
expect(bookingCardSchema.safeParse(photo('https://maps.example/x.jpg')).success).toBe(false);
expect(bookingCardSchema.safeParse(photo('coords:52.5,13.4')).success).toBe(false);
const late = { ...ticket, body: { ...TICKET, legs: [{ ...LEG, departs: '24:00' }] } };
expect(bookingCardSchema.safeParse(card([late])).success).toBe(false);
});
it('CARDBOOK-004: refuses a ticket without a leg, an unknown shape, a lowercase code and a currency in words', () => {
expect(bookingCardSchema.safeParse(card([{ ...ticket, body: { ...TICKET, legs: [] } }])).success).toBe(false);
expect(bookingCardSchema.safeParse(card([{ ...ticket, body: { shape: 'cruise' } }])).success).toBe(false);
const code = { ...ticket, body: { ...TICKET, stops: [{ name: 'Frankfurt', code: 'fra', lat: null, lng: null }] } };
expect(bookingCardSchema.safeParse(card([code])).success).toBe(false);
const words = { ...ticket, price: { amount: 5, currency: 'euro' } };
expect(bookingCardSchema.safeParse(card([words])).success).toBe(false);
});
it('CARDBOOK-005: a changed field must be one the card knows; a broken card reads as none, never the message', () => {
expect(bookingCardSchema.safeParse(card([{ ...ticket, changed: [...BOOKING_CHANGED_FIELDS] }])).success).toBe(true);
expect(bookingCardSchema.safeParse(card([{ ...ticket, changed: ['seat'] }])).success).toBe(false);
expect(storedTrekCardSchema.parse(card([{ ...ticket, title: '' }]))).toBeNull();
});
it('CARDBOOK-006: the bookings add their verbs and the stay as an applied entity', () => {
expect(BOOKING_VERB_KEYS).toEqual(['addStay', 'updateStay', 'updateReservation']);
expect(BOOKING_APPLIED_ENTITIES).toEqual(['accommodation']);
});
});
+153
View File
@@ -0,0 +1,153 @@
import { idSchema } from '../../common/primitives.schema';
import { RESERVATION_STATUSES } from '../../reservation/reservation-types';
import {
cardClockSchema,
cardCountSchema,
cardDaySchema,
cardLatSchema,
cardLngSchema,
cardMoneySchema,
cardPersonSchema,
cardPhotoKeySchema,
cardText,
} from './card-parts';
import { z } from 'zod';
/**
* Bookings in the assistant chat: a flight, a train, a hire car (a ticket), a
* hotel or any stay (a stay), a table, a show, a tour or a car park (a
* venue). One card per tool call holds the bookings it is about, at most
* eight, with the rest counted; an e-ticket file with a flight, a hotel and a
* flight back stays one itinerary. A booking's reference never travels, only
* that it has one: the chat is stored and can be shared, and the planner
* blurs it too.
*/
/** The type column is free text: any short key passes, the client draws an unknown one as `other`. */
const bookingTypeSchema = z.string().regex(/^[a-z_]{1,30}$/);
const lat = cardLatSchema.nullable();
const lng = cardLngSchema.nullable();
/** One end or stop of a route: the airport or station, its code where it has one. */
const bookingStopSchema = z.object({
name: cardText(80),
code: z
.string()
.regex(/^[A-Z0-9]{2,5}$/)
.nullable(),
lat,
lng,
});
/** One segment; a stopover's arrival lives only here (a stop's endpoint carries the onward departure). */
const bookingLegSchema = z.object({
carrier: cardText(60).nullable(),
number: cardText(20).nullable(),
departs: cardClockSchema.nullable(),
departsDay: cardDaySchema.nullable(),
arrives: cardClockSchema.nullable(),
arrivesDay: cardDaySchema.nullable(),
/** Only when both ends know their zone. */
minutes: z.number().int().min(1).max(10_080).nullable(),
seat: cardText(20).nullable(),
platform: cardText(20).nullable(),
});
const ticketBodySchema = z.object({
shape: z.literal('ticket'),
/** From, the stops, to; empty when no route is known (a hire car, a taxi). */
stops: z.array(bookingStopSchema).max(9),
/** One per segment between the stops, else exactly one. */
legs: z.array(bookingLegSchema).min(1).max(8),
/** First departure to last arrival. */
minutes: z.number().int().min(1).max(20_160).nullable(),
/** A saved booking with two stops that have coordinates: the plan can draw it. */
mappable: z.boolean(),
});
const stayBodySchema = z.object({
shape: z.literal('stay'),
/** Null while a create or a new place waits. */
accommodationId: idSchema.nullable(),
placeId: idSchema.nullable(),
address: cardText(200).nullable(),
lat,
lng,
/** A Google place id for TREK's photo proxy; never a picture address. */
photoKey: cardPhotoKeySchema.nullable(),
checkIn: z
.object({ day: cardDaySchema, from: cardClockSchema.nullable(), until: cardClockSchema.nullable() })
.nullable(),
checkOut: z.object({ day: cardDaySchema, by: cardClockSchema.nullable() }).nullable(),
nights: z.number().int().min(0).max(366).nullable(),
});
const venueBodySchema = z.object({
shape: z.literal('venue'),
day: cardDaySchema.nullable(),
starts: cardClockSchema.nullable(),
ends: cardClockSchema.nullable(),
/** The location text, else the linked place's name. */
location: cardText(200).nullable(),
placeId: idSchema.nullable(),
lat,
lng,
});
/** What an update changes, as the card shows it (its derived values, not the raw arguments). */
export const BOOKING_CHANGED_FIELDS = [
'title',
'type',
'status',
'day',
'time',
'route',
'stay',
'checkIn',
'checkOut',
'location',
'price',
'travelers',
'reference',
] as const;
export type BookingChangedField = (typeof BOOKING_CHANGED_FIELDS)[number];
export const bookingItemSchema = z.object({
tripId: idSchema,
/** Only on a row of another trip (the upcoming bookings across every trip). */
tripTitle: cardText(120).nullable(),
reservationId: idSchema.nullable(),
type: bookingTypeSchema,
title: cardText(200),
/** Null for a transit journey, a bare stay, or a status not known. */
status: z.enum(RESERVATION_STATUSES).nullable(),
needsReview: z.boolean(),
/** A confirmation number exists; the number itself never travels. */
hasReference: z.boolean(),
price: cardMoneySchema.nullable(),
travelers: z.array(cardPersonSchema).max(8),
moreTravelers: z.number().int().min(0).max(500),
changed: z.array(z.enum(BOOKING_CHANGED_FIELDS)).max(BOOKING_CHANGED_FIELDS.length),
body: z.discriminatedUnion('shape', [ticketBodySchema, stayBodySchema, venueBodySchema]),
});
export type BookingItem = z.infer<typeof bookingItemSchema>;
export type BookingBody = BookingItem['body'];
export type BookingTicket = Extract<BookingBody, { shape: 'ticket' }>;
export type BookingStay = Extract<BookingBody, { shape: 'stay' }>;
export type BookingVenue = Extract<BookingBody, { shape: 'venue' }>;
export type BookingLeg = BookingTicket['legs'][number];
export type BookingStop = BookingTicket['stops'][number];
/** What a held write does to its bookings; `none` on an answer and on an applied change. */
export const BOOKING_CHANGES = ['none', 'create', 'update', 'remove'] as const;
export const bookingCardSchema = z.object({
kind: z.literal('booking'),
change: z.enum(BOOKING_CHANGES),
items: z.array(bookingItemSchema).min(1).max(8),
/** Bookings the answer held past the eight shown. */
more: cardCountSchema,
});
export type BookingCard = z.infer<typeof bookingCardSchema>;
@@ -0,0 +1,16 @@
import { bookingCardSchema } from './booking.card';
export * from './booking.card';
/**
* What the bookings bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const BOOKING_CARD_SCHEMAS = [bookingCardSchema] as const;
/** addReservation and importBooking sit in the core list already. */
export const BOOKING_VERB_KEYS = ['addStay', 'updateStay', 'updateReservation'] as const;
/** 'reservation' is a core entity already; a stay is its own row. */
export const BOOKING_APPLIED_ENTITIES = ['accommodation'] as const;
@@ -0,0 +1,154 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema, assistantChangePreviewSchema } from '../assistant.schema';
import { BUDGET_APPLIED_ENTITIES, BUDGET_CARD_SCHEMAS, BUDGET_VERB_KEYS } from './budget.contract';
import { costPerPersonCardSchema, type CostPerPersonCard } from './cost-per-person.card';
import { EXPENSE_PEOPLE_MAX, expensesCardSchema, type CardExpense, type ExpensesCard } from './expenses.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { paymentsCardSchema, type PaymentsCard } from './payments.card';
import { settlementCardSchema, type SettlementCard } from './settlement.card';
import { describe, expect, it } from 'vitest';
const ana = { id: 7, name: 'Ana', avatarKey: 'ana.png' };
const ben = { id: 8, name: 'Ben', avatarKey: null };
const dinner: CardExpense = {
id: 31,
name: 'Dinner at Lokanta',
category: 'food',
amount: { amount: 84, currency: 'EUR' },
tripAmount: null,
date: '2026-06-03',
place: { id: 12, name: 'Lokanta' },
payers: [{ person: ana, amount: 84 }],
split: 'equal',
shares: [
{ person: ana, amount: 42, paid: true },
{ person: ben, amount: 42, paid: false },
],
moreShares: 0,
note: null,
receipts: 2,
before: null,
highlight: [],
change: 'none',
};
const expenses: ExpensesCard = {
kind: 'expenses',
rows: [dinner],
offset: 0,
more: 13,
total: { amount: 1204.5, currency: 'EUR' },
unconverted: 1,
};
const payments: PaymentsCard = {
kind: 'payments',
rows: [
{
id: null,
from: ben,
to: ana,
amount: { amount: 42.5, currency: 'EUR' },
date: '2026-06-07',
note: 'Bank transfer',
before: { from: ana, to: null, amount: { amount: 40, currency: 'EUR' } },
change: 'changed',
},
],
more: 0,
};
const settlement: SettlementCard = {
kind: 'settlement',
currency: 'EUR',
flows: [{ from: ben, to: ana, amount: 42.5 }],
moreFlows: 0,
balances: [
{ person: ana, balance: 42.5 },
{ person: ben, balance: -42.5 },
],
moreBalances: 0,
recorded: 3,
unconverted: { entries: 2, currencies: ['USD'] },
};
const perPerson: CostPerPersonCard = {
kind: 'costPerPerson',
currency: 'EUR',
rows: [{ person: ana, share: 69, paid: 45, count: 2 }],
more: 0,
};
describe('budget cards', () => {
it('CARDS-BUD-001: the four kinds join the card union and read back as built', () => {
expect(BUDGET_CARD_SCHEMAS).toEqual([
expensesCardSchema,
paymentsCardSchema,
settlementCardSchema,
costPerPersonCardSchema,
]);
for (const card of [expenses, payments, settlement, perPerson]) {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
}
});
it('CARDS-BUD-002: a waiting change states what it replaces and whom it is about', () => {
const update: CardExpense = {
...dinner,
amount: { amount: 96, currency: 'EUR' },
before: { name: null, amount: { amount: 84, currency: 'EUR' }, category: null, date: null, split: 'custom' },
highlight: [8],
change: 'changed',
};
expect(expensesCardSchema.parse({ ...expenses, rows: [update], total: null }).rows[0]).toEqual(update);
expect(expensesCardSchema.safeParse({ ...expenses, rows: [{ ...update, change: 'moved' }] }).success).toBe(false);
// A refund is a negative amount; nothing past a billion is.
const refund = { ...dinner, amount: { amount: -20, currency: 'EUR' } };
expect(expensesCardSchema.safeParse({ ...expenses, rows: [refund] }).success).toBe(true);
expect(expensesCardSchema.safeParse({ ...expenses, total: { amount: 2e9, currency: 'EUR' } }).success).toBe(false);
});
it('CARDS-BUD-003: lists and splits are bounded, and a card past a bound reads as no card', () => {
const many = Array.from({ length: EXPENSE_PEOPLE_MAX + 1 }, (_, i) => ({
person: { ...ben, id: 100 + i },
amount: 1,
paid: false,
}));
expect(storedTrekCardSchema.parse({ ...expenses, rows: [{ ...dinner, shares: many }] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, rows: Array.from({ length: 13 }, () => dinner) })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, rows: [] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, offset: -1 })).toBeNull();
const free = { ...payments.rows[0], amount: { amount: 0, currency: 'EUR' } };
expect(storedTrekCardSchema.parse({ ...payments, rows: [free] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...settlement, currency: 'euro' })).toBeNull();
expect(storedTrekCardSchema.parse({ ...perPerson, rows: [] })).toBeNull();
});
it('CARDS-BUD-004: people carry a stored file name only, never an address', () => {
const linked = { ...ana, avatarKey: 'https://sso.example/ana.png' };
expect(storedTrekCardSchema.parse({ ...perPerson, rows: [{ ...perPerson.rows[0], person: linked }] })).toBeNull();
const upward = { from: ana, to: { ...ben, avatarKey: '../x' }, amount: 1 };
expect(storedTrekCardSchema.parse({ ...settlement, flows: [upward] })).toBeNull();
});
it('CARDS-BUD-005: a payment change reads its verb, and a payment receipt its own entity', () => {
expect(BUDGET_VERB_KEYS).toEqual(['addPayment', 'updatePayment']);
for (const verb of BUDGET_VERB_KEYS) expect(ASSISTANT_CHANGE_VERB_KEYS).toContain(verb);
const preview = {
toolCallId: 'c1',
verbKey: 'addPayment',
subject: 'Ben → Ana',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: payments,
};
expect(assistantChangePreviewSchema.parse(preview)).toMatchObject({ verbKey: 'addPayment', card: payments });
expect(BUDGET_APPLIED_ENTITIES).toEqual(['settlement']);
const receipt = { toolCallId: 'c1', entity: 'settlement', ids: [5], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe('settlement');
});
});
@@ -0,0 +1,27 @@
import { costPerPersonCardSchema } from './cost-per-person.card';
import { expensesCardSchema } from './expenses.card';
import { paymentsCardSchema } from './payments.card';
import { settlementCardSchema } from './settlement.card';
export * from './cost-per-person.card';
export * from './expenses.card';
export * from './payments.card';
export * from './settlement.card';
/**
* What the budget brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const BUDGET_CARD_SCHEMAS = [
expensesCardSchema,
paymentsCardSchema,
settlementCardSchema,
costPerPersonCardSchema,
] as const;
/** A settle-up payment recorded or changed; removing one is a plain removal. */
export const BUDGET_VERB_KEYS = ['addPayment', 'updatePayment'] as const;
/** A settle-up payment: the receipt opens the Costs tab, where the payments are listed. */
export const BUDGET_APPLIED_ENTITIES = ['settlement'] as const;
+60
View File
@@ -0,0 +1,60 @@
import { idSchema } from '../../common/primitives.schema';
import { z } from 'zod';
/**
* The pieces every card of the assistant chat is built from. A kind uses
* these, `idSchema` and its domain's own enums, nothing else, so every card
* bounds its text the same way and none of them carries a URL or a path: a
* picture travels as a key the client turns into TREK's own address.
*/
/** One line of text, clipped and masked by the server before it is sent. */
export const cardText = (max: number) => z.string().min(1).max(max);
export const cardLatSchema = z.number().min(-90).max(90);
export const cardLngSchema = z.number().min(-180).max(180);
/** A point of a line to draw, `[lat, lng]` at five decimals; single points are `{ lat, lng }` objects. */
export type CardPoint = [number, number];
// Re-typed on the way out: server and client compile without strictNullChecks, where an inferred tuple
// makes every item optional and no longer fits a `[number, number]`.
export const cardPointSchema = z.tuple([cardLatSchema, cardLngSchema]).transform(([lat, lng]): CardPoint => [lat, lng]);
export const cardDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
export const cardClockSchema = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/);
export const cardInstantSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
/** A colour the data carries (a member's, a category's); the client draws it through safeHexColor. */
export const cardHexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
export const cardCurrencySchema = z.string().regex(/^[A-Z]{3}$/);
export const cardMoneySchema = z.object({ amount: z.number().min(-1e9).max(1e9), currency: cardCurrencySchema });
export const cardCountSchema = z.number().int().min(0).max(1_000_000);
/** A stored file name (an avatar, a place image): the client builds TREK's own path. Never a URL, never a path. */
export const cardFileKeySchema = z.string().regex(/^(?!.*\.\.)[A-Za-z0-9][\w.-]{0,199}$/);
/** A Google place id for TREK's photo proxy, like a found place's photo key without `coords:`. */
export const cardPhotoKeySchema = z.string().regex(/^[\w-]{1,200}$/);
/** A traveller as a card shows them: the client compares `id` with the signed-in user, so no card says "me". */
export const cardPersonSchema = z.object({
id: idSchema,
name: cardText(80),
avatarKey: cardFileKeySchema.nullable(),
});
/** A trip day: its id for links, its number or date for words. */
export const cardDaySchema = z.object({
id: idSchema.nullable(),
number: z.number().int().min(1).max(999).nullable(),
date: cardDateSchema.nullable(),
});
/** The most one card may weigh, as JSON text; a heavier one is not sent at all. */
export const MAX_CARD_CHARS = 24_000;
export type CardMoney = z.infer<typeof cardMoneySchema>;
export type CardPerson = z.infer<typeof cardPersonSchema>;
export type CardDay = z.infer<typeof cardDaySchema>;
@@ -0,0 +1,33 @@
import { idSchema } from '../../common/primitives.schema';
import { cardInstantSchema, cardLatSchema, cardLngSchema, cardMoneySchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A charger as one look at it found it: how many points were free when it
* was checked, the cheapest published price per kWh, and where the figures
* come from. A snapshot with its time, never refreshed in the chat, and
* never the source's address: the attribution is its name and licence.
*/
export const chargingCardSchema = z.object({
kind: z.literal('charging'),
// The stop of the trip it is, or null for a charger found by its position.
placeId: idSchema.nullable(),
name: cardText(80).nullable(),
station: cardText(120).nullable(),
lat: cardLatSchema.nullable(),
lng: cardLngSchema.nullable(),
status: z.enum(['ok', 'unknown', 'ambiguous', 'unavailable']),
stale: z.boolean(),
available: z.number().int().min(0).max(999).nullable(),
total: z.number().int().min(0).max(999),
checkedAt: cardInstantSchema.nullable(),
updatedAt: cardInstantSchema.nullable(),
// The cheapest unconditional energy price with tax, per kWh; null when the prices are in several currencies.
energy: cardMoneySchema.nullable(),
// The other price components the tariffs name besides that one.
otherPrices: z.number().int().min(0).max(99),
source: cardText(80).nullable(),
license: cardText(120).nullable(),
});
export type ChargingCard = z.infer<typeof chargingCardSchema>;
@@ -0,0 +1,67 @@
import { idSchema } from '../../common/primitives.schema';
import { cardInstantSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Messages of the trip chat, drawn the way the chat draws them: a bubble per
* message, the others on one side with their face and name, the user's own on
* the other in the accent. An answer shows the last few messages a read
* returned and counts the older ones; a held write shows the one message it
* sends, removes or reacts to, as it will look afterwards. A file travels as
* its id only, which the client turns into TREK's own download path.
*/
/** One emoji of a message's reactions; `mine` says the signed-in user is among them, which only the server knows. */
const chatReactionSchema = z.object({
emoji: z.string().min(1).max(16),
count: z.number().int().min(1).max(999),
mine: z.boolean(),
/** The first names behind it, for the tooltip the chat shows. */
names: z.array(cardText(80)).max(6),
});
/** A file sent with a message: an image is drawn in the bubble, any other file named. */
const chatFileSchema = z.object({
fileId: idSchema,
image: z.boolean(),
name: cardText(120).nullable(),
});
/** The message a bubble answers, quoted on top of it. */
const chatReplySchema = z.object({
name: cardText(80),
text: cardText(120),
});
export const COLLAB_BUBBLE_CHANGES = ['none', 'send', 'remove', 'react'] as const;
export const collabBubbleCardSchema = z.object({
/** Null while a send waits for its decision. */
id: idSchema.nullable(),
author: cardPersonSchema,
/** Line breaks kept; empty only for a message that is an image alone. */
text: z.string().max(4000),
/** The text was cut: an excerpt of a long message, or a send longer than the bubble holds. */
cut: z.boolean(),
/** Null while a send waits for its decision. */
at: cardInstantSchema.nullable(),
reply: chatReplySchema.nullable(),
reactions: z.array(chatReactionSchema).max(8),
files: z.array(chatFileSchema).max(4),
/** Shared from an assistant answer: the chat marks it so. */
fromAssistant: z.boolean(),
change: z.enum(COLLAB_BUBBLE_CHANGES),
/** The emoji a held reaction toggles. */
reactEmoji: z.string().min(1).max(16).nullable(),
});
export type CollabBubbleCard = z.infer<typeof collabBubbleCardSchema>;
export const collabChatCardSchema = z.object({
kind: z.literal('collabChat'),
/** Oldest first, as the chat lists them. */
messages: z.array(collabBubbleCardSchema).min(1).max(6),
/** Older messages of the read that are not shown. */
earlier: z.number().int().min(0).max(10_000),
});
export type CollabChatCard = z.infer<typeof collabChatCardSchema>;
@@ -0,0 +1,44 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Shared notes of the trip, drawn like the note cards of the Collab tab: a
* head band tinted by the category's colour with its title, and the start of
* its text under it. An answer holds up to four notes of a read (pinned
* first) and counts the rest; a held write holds the one note it adds,
* changes or deletes, as it will look afterwards. A note's link travels as
* its host only, never as an address the chat could open.
*/
export const COLLAB_NOTE_CHANGES = ['none', 'create', 'update', 'remove'] as const;
/** The parts of a note a held change sets to something new. */
export const COLLAB_NOTE_FIELDS = ['title', 'body', 'category', 'color', 'website', 'pinned'] as const;
export const collabNoteCardSchema = z.object({
/** Null while a new note waits for its decision. */
noteId: idSchema.nullable(),
title: cardText(200),
/** Markdown with its line breaks, shown in three lines as the note card does. */
body: z.string().min(1).max(600).nullable(),
category: cardText(100).nullable(),
color: cardHexColorSchema.nullable(),
pinned: z.boolean(),
/** "example.org": the host of the note's link. */
websiteHost: z.string().min(1).max(253).nullable(),
files: z.number().int().min(0).max(999),
author: cardPersonSchema.nullable(),
change: z.enum(COLLAB_NOTE_CHANGES),
changed: z.array(z.enum(COLLAB_NOTE_FIELDS)).max(6),
});
export type CollabNoteCard = z.infer<typeof collabNoteCardSchema>;
export const collabNotesCardSchema = z.object({
kind: z.literal('collabNotes'),
notes: z.array(collabNoteCardSchema).min(1).max(4),
/** Notes of the read that are not shown. */
more: cardCountSchema,
});
export type CollabNotesCard = z.infer<typeof collabNotesCardSchema>;
@@ -0,0 +1,54 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardInstantSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Polls of the trip, drawn like the poll cards of the Collab tab: the
* question, what kind of poll it is, and its options with their bars. An
* answer holds up to four polls of a read (open ones first) and counts the
* rest; a held write holds the one poll it starts, votes in, closes or
* deletes, as it will look afterwards. Whether the signed-in user voted for
* an option is something only the server knows, so it travels as `mine`.
*/
const pollOptionCardSchema = z.object({
text: cardText(160),
votes: z.number().int().min(0).max(9999),
mine: z.boolean(),
/** The first three voters, as the poll card shows them. */
voters: z.array(cardPersonSchema).max(3),
});
export const COLLAB_POLL_CHANGES = ['none', 'create', 'vote', 'close', 'remove'] as const;
/** Why the server would refuse a held vote: the poll is closed, or it has no such option. */
export const COLLAB_POLL_WARNINGS = ['closed', 'unknownOption'] as const;
export const collabPollCardSchema = z.object({
/** Null while a new poll waits for its decision. */
pollId: idSchema.nullable(),
question: cardText(300),
options: z.array(pollOptionCardSchema).min(1).max(12),
moreOptions: z.number().int().min(0).max(500),
multiple: z.boolean(),
/** Closed by hand; the client adds the deadline, as the Collab tab does. */
closed: z.boolean(),
deadline: cardInstantSchema.nullable(),
author: cardPersonSchema.nullable(),
change: z.enum(COLLAB_POLL_CHANGES),
/** The option a held vote toggles. */
votedIndex: z.number().int().min(0).max(499).nullable(),
/** True when the held vote is cast, false when it is taken back. */
votedAdds: z.boolean(),
warning: z.enum(COLLAB_POLL_WARNINGS).nullable(),
});
export type CollabPollCard = z.infer<typeof collabPollCardSchema>;
export const collabPollsCardSchema = z.object({
kind: z.literal('collabPolls'),
polls: z.array(collabPollCardSchema).min(1).max(4),
/** Polls of the read that are not shown. */
more: cardCountSchema,
});
export type CollabPollsCard = z.infer<typeof collabPollsCardSchema>;
@@ -0,0 +1,130 @@
import { assistantAppliedSchema } from '../assistant.schema';
import {
COLLAB_APPLIED_ENTITIES,
COLLAB_VERB_KEYS,
type CollabChatCard,
type CollabNotesCard,
type CollabPollsCard,
} from './collab.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const ANNA = { id: 7, name: 'Anna', avatarKey: 'anna.png' };
/** A message as the trip chat shows it. */
const bubble = (over: Partial<CollabChatCard['messages'][number]> = {}): CollabChatCard['messages'][number] => ({
id: 11,
author: ANNA,
text: 'Shall we take\nthe early train?',
cut: false,
at: '2026-10-21T09:12:00Z',
reply: null,
reactions: [{ emoji: '❤️', count: 2, mine: true, names: ['Anna', 'Jon'] }],
files: [{ fileId: 4, image: true, name: 'ticket.jpg' }],
fromAssistant: false,
change: 'none',
reactEmoji: null,
...over,
});
const chat = (over: Partial<CollabChatCard> = {}): CollabChatCard => ({
kind: 'collabChat',
messages: [bubble()],
earlier: 3,
...over,
});
const poll = (over: Partial<CollabPollsCard['polls'][number]> = {}): CollabPollsCard['polls'][number] => ({
pollId: 5,
question: 'Where do we eat on Friday?',
options: [
{ text: 'Trattoria Roma', votes: 2, mine: true, voters: [ANNA] },
{ text: 'Night market', votes: 0, mine: false, voters: [] },
],
moreOptions: 0,
multiple: false,
closed: false,
deadline: '2026-10-24T18:00:00Z',
author: ANNA,
change: 'none',
votedIndex: null,
votedAdds: false,
warning: null,
...over,
});
const note = (over: Partial<CollabNotesCard['notes'][number]> = {}): CollabNotesCard['notes'][number] => ({
noteId: 9,
title: 'Restaurants to try',
body: 'Pasta at **Luigi**\nthe rooftop bar',
category: 'Ideas',
color: '#10b981',
pinned: true,
websiteHost: 'luigis.it',
files: 2,
author: ANNA,
change: 'none',
changed: [],
...over,
});
describe('the trip chat cards', () => {
it('CARDS-COLLAB-001: a chat, a poll and a note card read as themselves in the union', () => {
for (const card of [
chat(),
{ kind: 'collabPolls', polls: [poll()], more: 2 },
{ kind: 'collabNotes', notes: [note()], more: 0 },
]) {
expect(trekCardSchema.parse(card)).toEqual(card);
}
});
it('CARDS-COLLAB-002: a held send has no id and no time yet, and an image alone has no text', () => {
const held = chat({ messages: [bubble({ id: null, at: null, change: 'send', reactions: [], files: [] })] });
expect(trekCardSchema.parse(held)).toEqual(held);
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ text: '' })] })).success).toBe(true);
});
it('CARDS-COLLAB-003: an avatar is a stored file name, never an address or a way up', () => {
for (const avatarKey of ['https://idp.test/me.png', '../secret.png', '/uploads/avatars/a.png']) {
const card = chat({ messages: [bubble({ author: { ...ANNA, avatarKey } })] });
expect(trekCardSchema.safeParse(card).success).toBe(false);
expect(storedTrekCardSchema.parse(card)).toBeNull();
}
});
it('CARDS-COLLAB-004: a time is a UTC moment to the second, as the server normalises it', () => {
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ at: '2026-10-21 09:12:00' })] })).success).toBe(false);
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ at: '2026-10-21T09:12Z' })] })).success).toBe(false);
const late = { kind: 'collabPolls', polls: [poll({ deadline: '2026-10-24' })], more: 0 };
expect(trekCardSchema.safeParse(late).success).toBe(false);
});
it('CARDS-COLLAB-005: lists past their bounds read as null', () => {
const seven = Array.from({ length: 7 }, (_, index) => bubble({ id: index + 1 }));
expect(storedTrekCardSchema.parse(chat({ messages: seven }))).toBeNull();
expect(storedTrekCardSchema.parse(chat({ messages: [] }))).toBeNull();
const five = [1, 2, 3, 4, 5].map((pollId) => poll({ pollId }));
expect(storedTrekCardSchema.parse({ kind: 'collabPolls', polls: five, more: 0 })).toBeNull();
expect(storedTrekCardSchema.parse({ kind: 'collabNotes', notes: [], more: 0 })).toBeNull();
const many = Array.from({ length: 13 }, (_, index) => ({ text: `#${index}`, votes: 0, mine: false, voters: [] }));
expect(storedTrekCardSchema.parse({ kind: 'collabPolls', polls: [poll({ options: many })], more: 0 })).toBeNull();
expect(storedTrekCardSchema.parse(chat({ messages: [bubble({ text: 'x'.repeat(4001) })] }))).toBeNull();
});
it('CARDS-COLLAB-006: a note colour is a hex colour and its link only a host', () => {
const tinted = { kind: 'collabNotes', notes: [note({ color: 'url(https://x.test/p)' })], more: 0 };
expect(trekCardSchema.safeParse(tinted).success).toBe(false);
const linked = { kind: 'collabNotes', notes: [{ ...note(), website: 'https://x.test' }], more: 0 };
expect(trekCardSchema.parse(linked)).toEqual({ kind: 'collabNotes', notes: [note()], more: 0 });
});
it('CARDS-COLLAB-007: the trip chat adds three applied entities and no verb', () => {
expect(COLLAB_VERB_KEYS).toEqual([]);
for (const entity of COLLAB_APPLIED_ENTITIES) {
const receipt = { toolCallId: 'call_1', entity, ids: [3], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe(entity);
}
});
});
@@ -0,0 +1,19 @@
import { collabChatCardSchema } from './collab-chat.card';
import { collabNotesCardSchema } from './collab-notes.card';
import { collabPollsCardSchema } from './collab-polls.card';
export * from './collab-chat.card';
export * from './collab-notes.card';
export * from './collab-polls.card';
/**
* What the trip chat brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and the entities its applied changes touch,
* beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else. Its changes keep the generic
* verbs (add, change, remove) and name their tool instead.
*/
export const COLLAB_CARD_SCHEMAS = [collabChatCardSchema, collabPollsCardSchema, collabNotesCardSchema] as const;
export const COLLAB_VERB_KEYS = [] as const;
export const COLLAB_APPLIED_ENTITIES = ['collab_message', 'collab_poll', 'collab_note'] as const;
@@ -0,0 +1,44 @@
import { COLLECTION_STATUSES } from '../../collection/collection.schema';
import { cardCountSchema, cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { collectionCardListSchema } from './collection-places.card';
import { z } from 'zod';
/**
* The lists a user keeps, as the chat shows them: each with its colour, size
* and people, an incoming invite with whom it came from, the lists a place is
* saved in with its status in each, and what a held change does to a list.
*/
/** What a change does to a list; `none` on an answer. */
export const COLLECTION_LIST_CHANGES = [
'none',
'add',
'update',
'remove',
'join',
'decline',
'withdraw',
'order',
] as const;
export const collectionListRowSchema = collectionCardListSchema.extend({
/** The place's status in this list (a lookup of where a place is saved). */
status: z.enum(COLLECTION_STATUSES).nullable(),
/** Who sent an incoming invite, or whom a withdrawn one was for. */
person: cardPersonSchema.nullable(),
/** An invite the user has not answered yet. */
invite: z.boolean(),
change: z.enum(COLLECTION_LIST_CHANGES),
before: z.object({ name: cardText(120), color: cardHexColorSchema.nullable() }).nullable(),
});
export type CollectionListRow = z.infer<typeof collectionListRowSchema>;
export const collectionListsCardSchema = z.object({
kind: z.literal('collectionLists'),
lists: z.array(collectionListRowSchema).max(12),
more: cardCountSchema,
/** The place a lookup asked about, as it was asked. */
place: cardText(120).nullable(),
});
export type CollectionListsCard = z.infer<typeof collectionListsCardSchema>;
@@ -0,0 +1,132 @@
import { COLLECTION_STATUSES } from '../../collection/collection.schema';
import { idSchema } from '../../common/primitives.schema';
import {
cardCountSchema,
cardFileKeySchema,
cardHexColorSchema,
cardLatSchema,
cardLngSchema,
cardPhotoKeySchema,
cardText,
} from './card-parts';
import { z } from 'zod';
/**
* Saved places of the collections as the chat shows them: a list's head with
* its colour, size and people, its places as its rows (status, labels, rating,
* whether the trip has the place already), and what a held change does to
* them. A saved place's id is its own and never a trip place's: the one link
* to the trip is `inTripPlaceId`.
*/
const statusSchema = z.enum(COLLECTION_STATUSES);
/** The fields of a saved place a change can touch, each named on the card by its label. */
export const COLLECTION_CARD_FIELDS = [
'name',
'address',
'coordinates',
'description',
'notes',
'category',
'link',
'photo',
] as const;
/** What a change does to a label of a list; `none` on an answer. */
export const COLLECTION_LABEL_CHANGES = ['none', 'add', 'rename', 'remove'] as const;
/** A list as a card names it: its colour dot, its size and how many share it. `id` null: the list a change creates. */
export const collectionCardListSchema = z.object({
id: idSchema.nullable(),
name: cardText(120),
color: cardHexColorSchema.nullable(),
placeCount: cardCountSchema.nullable(),
/** Accepted members besides the owner. */
memberCount: cardCountSchema,
/** Places per status, only where the whole list was read. */
counts: z.object({ idea: cardCountSchema, want: cardCountSchema, visited: cardCountSchema }).nullable(),
});
export type CollectionCardList = z.infer<typeof collectionCardListSchema>;
export const collectionCardLabelSchema = z.object({
id: idSchema.nullable(),
name: cardText(60),
color: cardHexColorSchema.nullable(),
/** How many places of its list carry it, where the whole list was read. */
places: cardCountSchema.nullable(),
change: z.enum(COLLECTION_LABEL_CHANGES),
before: z.object({ name: cardText(60), color: cardHexColorSchema.nullable() }).nullable(),
});
export type CollectionCardLabel = z.infer<typeof collectionCardLabelSchema>;
/** What a held change does to one saved place. */
export const collectionCardDeltaSchema = z.object({
status: z.object({ from: statusSchema.nullable(), to: statusSchema }).nullable(),
/** The user's own vote; `to: null` takes it away. */
rating: z.object({ to: z.number().int().min(1).max(5).nullable() }).nullable(),
labelsAdded: z.array(idSchema).max(10),
labelsRemoved: z.array(idSchema).max(10),
fields: z.array(z.enum(COLLECTION_CARD_FIELDS)).max(8),
movedTo: collectionCardListSchema.nullable(),
removed: z.boolean(),
});
export type CollectionCardDelta = z.infer<typeof collectionCardDeltaSchema>;
export const collectionCardPlaceSchema = z.object({
/** The saved place's own id; null before a save is applied. */
id: idSchema.nullable(),
listId: idSchema.nullable(),
name: cardText(120),
address: cardText(200).nullable(),
lat: cardLatSchema.nullable(),
lng: cardLngSchema.nullable(),
category: z
.object({ name: cardText(60), icon: cardText(40).nullable(), color: cardHexColorSchema.nullable() })
.nullable(),
status: statusSchema,
labelIds: z.array(idSchema).max(10),
rating: z.number().min(1).max(5).nullable(),
ratingCount: cardCountSchema,
/** The Google place id the photo proxy finds its picture by. */
googlePlaceId: cardPhotoKeySchema.nullable(),
osmId: cardText(40).nullable(),
/** The file name of its own uploaded photo; the client builds `/uploads/places/<key>`. */
imageKey: cardFileKeySchema.nullable(),
/** The same place in the chat's trip, by its provider id or the trip place it was saved from. */
inTripPlaceId: idSchema.nullable(),
/** The lists that hold the place already (a save's warning). */
savedIn: z.array(z.object({ listId: idSchema, name: cardText(120), status: statusSchema })).max(3),
delta: collectionCardDeltaSchema.nullable(),
});
export type CollectionCardPlace = z.infer<typeof collectionCardPlaceSchema>;
/** What an applied change of several places did, from the tool's answer. */
export const collectionCardOutcomeSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('duplicate'), name: cardText(120) }),
z.object({
type: z.literal('copied'),
copied: cardCountSchema,
skipped: cardCountSchema,
skippedNames: z.array(cardText(120)).max(5),
}),
z.object({ type: z.literal('statusSet'), updated: cardCountSchema, found: cardCountSchema }),
]);
export type CollectionCardOutcome = z.infer<typeof collectionCardOutcomeSchema>;
export const collectionPlacesCardSchema = z.object({
kind: z.literal('collectionPlaces'),
/** Null when the places sit in several lists. */
list: collectionCardListSchema.nullable(),
places: z.array(collectionCardPlaceSchema).max(8),
more: cardCountSchema,
/** Only the labels the shown places carry or the change names. */
labels: z.array(collectionCardLabelSchema).max(24),
outcome: collectionCardOutcomeSchema.nullable(),
/** A status set on a trip place in every list that holds it. */
everyList: z.boolean(),
/** A copy into a trip other than the chat's. */
otherTrip: z.boolean(),
});
export type CollectionPlacesCard = z.infer<typeof collectionPlacesCardSchema>;
@@ -0,0 +1,138 @@
import { assistantAppliedSchema } from '../assistant.schema';
import { MAX_CARD_CHARS } from './card-parts';
import { collectionListsCardSchema } from './collection-lists.card';
import { collectionPlacesCardSchema } from './collection-places.card';
import { COLLECTION_APPLIED_ENTITIES } from './collection.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const list = { id: 12, name: 'Paris food', color: '#e11d48', placeCount: 12, memberCount: 2, counts: null };
const place = {
id: 34,
listId: 12,
name: 'Septime',
address: '80 Rue de Charonne',
lat: 48.853,
lng: 2.381,
category: { name: 'Restaurant', icon: 'Utensils', color: '#f97316' },
status: 'want',
labelIds: [5],
rating: 4.5,
ratingCount: 2,
googlePlaceId: 'ChIJseptime',
osmId: null,
imageKey: 'septime.jpg',
inTripPlaceId: null,
savedIn: [],
delta: null,
};
const placesCard = {
kind: 'collectionPlaces',
list,
places: [place],
more: 0,
labels: [{ id: 5, name: 'Dinner', color: '#2563eb', places: 3, change: 'none', before: null }],
outcome: null,
everyList: false,
otherTrip: false,
};
const row = {
...list,
status: null,
person: null,
invite: false,
change: 'none',
before: null,
};
describe('collection cards', () => {
it('CARDS-COLL-001: a list with its saved places and labels reads as itself through the union', () => {
expect(trekCardSchema.parse(placesCard)).toEqual(placesCard);
expect(storedTrekCardSchema.parse(placesCard)).toEqual(placesCard);
expect(JSON.stringify(placesCard).length).toBeLessThan(MAX_CARD_CHARS);
});
it('CARDS-COLL-002: a place a change has not saved yet and the list a change creates carry no id', () => {
const pending = {
...placesCard,
list: { ...list, id: null, placeCount: 0, memberCount: 0 },
places: [{ ...place, id: null, listId: null, imageKey: null, delta: deltaOf({ removed: false }) }],
};
expect(collectionPlacesCardSchema.safeParse(pending).success).toBe(true);
});
it('CARDS-COLL-003: a photo is a stored file name, never an address or a path', () => {
const refused = ['https://example.com/a.jpg', '/uploads/places/a.jpg', '../a.jpg', 'data:image/png;base64,x'];
for (const imageKey of refused) {
const card = { ...placesCard, places: [{ ...place, imageKey }] };
expect(collectionPlacesCardSchema.safeParse(card).success, imageKey).toBe(false);
}
});
it('CARDS-COLL-004: rows, labels and names stay inside their bounds; a card past them reads as null', () => {
const nine = Array.from({ length: 9 }, (_, i) => ({ ...place, id: i + 1 }));
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, places: nine }).success).toBe(false);
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, list: { ...list, name: '' } }).success).toBe(false);
const tooHigh = { ...placesCard, places: [{ ...place, rating: 6 }] };
expect(collectionPlacesCardSchema.safeParse(tooHigh).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...placesCard, places: nine })).toBeNull();
});
it('CARDS-COLL-005: a change names the status it leaves, the vote it casts and the fields it touches', () => {
const delta = deltaOf({ status: { from: 'idea', to: 'visited' }, rating: { to: null }, fields: ['photo'] });
const card = { ...placesCard, places: [{ ...place, delta }] };
expect(collectionPlacesCardSchema.parse(card).places[0]?.delta).toEqual(delta);
const unknownField = { ...placesCard, places: [{ ...place, delta: deltaOf({ fields: ['phone'] }) }] };
expect(collectionPlacesCardSchema.safeParse(unknownField).success).toBe(false);
});
it('CARDS-COLL-006: an applied copy, a duplicate and a status set across lists each say what happened', () => {
for (const outcome of [
{ type: 'duplicate', name: 'Septime' },
{ type: 'copied', copied: 2, skipped: 1, skippedNames: ['Le Comptoir'] },
{ type: 'statusSet', updated: 3, found: 2 },
]) {
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, outcome }).success, outcome.type).toBe(true);
}
});
it('CARDS-COLL-007: the lists card holds lists, invites and a lookup of where a place is saved', () => {
const card = {
kind: 'collectionLists',
lists: [
{ ...row, status: 'visited' },
{ ...row, id: 13, invite: true, person: { id: 4, name: 'Maya', avatarKey: null }, placeCount: null },
],
more: 0,
place: 'Septime',
};
expect(trekCardSchema.parse(card)).toEqual(card);
const thirteen = Array.from({ length: 13 }, (_, i) => ({ ...row, id: i + 1 }));
expect(collectionListsCardSchema.safeParse({ ...card, lists: thirteen }).success).toBe(false);
expect(collectionListsCardSchema.safeParse({ ...card, lists: [{ ...row, change: 'rename' }] }).success).toBe(false);
});
it('CARDS-COLL-008: an applied change names a list or a saved place as what it touched', () => {
for (const entity of COLLECTION_APPLIED_ENTITIES) {
const applied = { toolCallId: 'c1', entity, ids: [12], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(applied).entity).toBe(entity);
}
});
});
function deltaOf(over: Record<string, unknown>) {
return {
status: null,
rating: null,
labelsAdded: [],
labelsRemoved: [],
fields: [],
movedTo: null,
removed: false,
...over,
};
}
@@ -0,0 +1,18 @@
import { collectionListsCardSchema } from './collection-lists.card';
import { collectionPlacesCardSchema } from './collection-places.card';
export * from './collection-lists.card';
export * from './collection-places.card';
/**
* What the collections bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const COLLECTION_CARD_SCHEMAS = [collectionPlacesCardSchema, collectionListsCardSchema] as const;
/** Their changes read as the plain add, change and remove, named by each tool's own label. */
export const COLLECTION_VERB_KEYS = [] as const;
/** A list (`collection`) and a saved place of one (`collection_place`), both opened in Collections. */
export const COLLECTION_APPLIED_ENTITIES = ['collection', 'collection_place'] as const;
@@ -0,0 +1,55 @@
import { idSchema } from '../../common/primitives.schema';
import { roadtripCorridorRequestSchema } from '../../roadtrip/planning.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardLatSchema, cardLngSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* What search_roadtrip_corridor found along one day's drive, in the order
* the drive passes it: how far into the drive and how far off the road each
* hit lies, between which stops, and for a charger its sockets. A search
* that is not done yet says how much of the road it has searched.
*/
/** The hits a card lists; the rest are counted in `more`. */
export const CORRIDOR_CARD_HITS_MAX = 12;
export const corridorCardSchema = z.object({
kind: z.literal('corridor'),
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS),
category: roadtripCorridorRequestSchema.shape.category,
widthKm: z.number().positive().max(10),
hits: z
.array(
z.object({
// `<toolCallId>:<index>`, the way a found place is named.
ref: z.string().min(1).max(80),
name: cardText(80).nullable(),
brand: cardText(40).nullable(),
lat: cardLatSchema,
lng: cardLngSchema,
alongKm: z.number().min(0).max(40_000),
offKm: z.number().min(0).max(10),
// The names of the stops the hit lies between, in driving order.
between: z.tuple([cardText(80), cardText(80)]).nullable(),
sockets: z
.array(
z.object({
type: cardText(20),
kw: z.number().min(0).max(2000).nullable(),
count: z.number().int().min(0).max(99).nullable(),
}),
)
.max(4),
}),
)
.max(CORRIDOR_CARD_HITS_MAX),
more: z.number().int().min(0).max(10_000),
searched: z.object({ done: z.number().int().min(0).max(1000), total: z.number().int().min(0).max(1000) }),
// Areas that failed, came back cut short, or are still to be searched.
partial: z.boolean(),
});
export type CorridorCard = z.infer<typeof corridorCardSchema>;
export type CorridorCardHit = CorridorCard['hits'][number];
@@ -0,0 +1,30 @@
import { cardCurrencySchema, cardPersonSchema } from './card-parts';
import { z } from 'zod';
/**
* What the trip's expenses come to for each traveller, in the trip
* currency: the sum of their shares, how much of that is marked paid, and in
* how many expenses they take part. Largest share first.
*/
/** Travellers one card names; the rest are counted in `more`. */
export const COST_PER_PERSON_ROWS_MAX = 20;
export const costPerPersonCardSchema = z.object({
kind: z.literal('costPerPerson'),
currency: cardCurrencySchema,
rows: z
.array(
z.object({
person: cardPersonSchema,
share: z.number().min(-1e9).max(1e9),
paid: z.number().min(-1e9).max(1e9),
count: z.number().int().min(0).max(100_000),
}),
)
.min(1)
.max(COST_PER_PERSON_ROWS_MAX),
more: z.number().int().min(0).max(1000),
});
export type CostPerPersonCard = z.infer<typeof costPerPersonCardSchema>;
@@ -0,0 +1,55 @@
import { idSchema } from '../../common/primitives.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardLatSchema, cardLngSchema, cardPointSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* One day's route drawn straight from stop to stop, with the via points a
* change sends the drive through: the card of every change that bends a
* day's drive, and of a Google Maps route read or imported. Straight lines on
* purpose: TREK routes the road once the change is applied.
*/
/** The stops of a day a card draws. */
export const DAY_ROUTE_CARD_STOPS_MAX = 40;
/** The via points a card draws. */
export const DAY_ROUTE_CARD_VIAS_MAX = 100;
export const dayRouteCardSchema = z.object({
kind: z.literal('dayRoute'),
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS).nullable(),
stops: z
.array(
z.object({
placeId: idSchema.nullable(),
name: cardText(80),
lat: cardLatSchema,
lng: cardLngSchema,
// A stop the change adds to the day.
added: z.boolean(),
}),
)
.max(DAY_ROUTE_CARD_STOPS_MAX),
vias: z
.array(
z.object({
lat: cardLatSchema,
lng: cardLngSchema,
// The stop of the day the via follows, counting from 0.
after: z.number().int().min(0).max(500),
state: z.enum(['added', 'moved', 'removed', 'repinned']),
// Where a moved via was before.
from: cardPointSchema.nullable(),
}),
)
.max(DAY_ROUTE_CARD_VIAS_MAX),
// The stop every new via follows, and the imported track the chain was fitted to.
afterName: cardText(80).nullable(),
track: cardText(80).nullable(),
// Stops of a read Google Maps route that have no position.
unresolved: z.array(cardText(80)).max(10),
});
export type DayRouteCard = z.infer<typeof dayRouteCardSchema>;
export type DayRouteCardVia = DayRouteCard['vias'][number];
+102
View File
@@ -0,0 +1,102 @@
import { idSchema } from '../../common/primitives.schema';
import { cardDateSchema, cardMoneySchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Expenses of the trip as the Costs page shows them: the name, the amount in
* the currency it was paid in (and in the trip currency when that differs and
* a rate is known), the day, the place it belongs to, who paid how much and
* who shares it. One card serves the expense list (`list_budget_items`) and
* every change to a single expense: the row of a change carries what it
* replaces (`before`), the people it is about (`highlight`) and what happens
* to it (`change`). Amounts are numbers with a currency code; the client
* writes them the way the Costs page does.
*/
/** Rows one expenses card lists; the rest are counted in `more`. */
export const EXPENSE_ROWS_MAX = 12;
/** Payers or shares one row names; the rest of a split are counted in `moreShares`. */
export const EXPENSE_PEOPLE_MAX = 20;
/** A signed amount: a refund is negative (#2176). */
const cardAmountSchema = z.number().min(-1e9).max(1e9);
/** How an expense is shared: evenly, in amounts of its own per person, or by nobody (planning only). */
export const expenseSplitSchema = z.enum(['equal', 'custom', 'none']);
/** What a change does to a row; an answer's rows are `none`. */
export const expenseChangeSchema = z.enum(['none', 'new', 'changed', 'willDelete']);
/** One person's part of an expense, and whether they have paid it. */
export const cardExpenseShareSchema = z.object({
person: cardPersonSchema,
amount: cardAmountSchema,
paid: z.boolean(),
});
/** Someone who paid for the expense, and how much. */
export const cardExpensePayerSchema = z.object({ person: cardPersonSchema, amount: cardAmountSchema });
/**
* The values a waiting update replaces, each null where the update leaves it
* alone: a category or a date that was empty before reads as unchanged.
*/
export const cardExpenseBeforeSchema = z.object({
name: cardText(120).nullable(),
amount: cardMoneySchema.nullable(),
category: z.string().max(60).nullable(),
date: cardDateSchema.nullable(),
split: expenseSplitSchema.nullable(),
});
export const cardExpenseSchema = z.object({
/** Null while a new expense waits for its decision. */
id: idSchema.nullable(),
name: cardText(120),
/** As stored; the client maps it to a Costs category, legacy free text included. */
category: z.string().max(60).nullable(),
/** The total in the currency it was entered in (the trip's when it names none). */
amount: cardMoneySchema,
/** The total in the trip currency, only when that differs and a rate converts it. */
tripAmount: cardMoneySchema.nullable(),
date: cardDateSchema.nullable(),
place: z.object({ id: idSchema, name: cardText(120) }).nullable(),
payers: z.array(cardExpensePayerSchema).max(EXPENSE_PEOPLE_MAX),
split: expenseSplitSchema,
shares: z.array(cardExpenseShareSchema).max(EXPENSE_PEOPLE_MAX),
/** Shares of the split past the ones named. */
moreShares: z.number().int().min(0).max(1000),
/** A change row's note; list rows leave it out. */
note: cardText(160).nullable(),
/** How many receipts are attached; never the files themselves. */
receipts: z.number().int().min(0).max(999),
before: cardExpenseBeforeSchema.nullable(),
/** The people the change is about: a paid tick set, someone joining the split. */
highlight: z.array(idSchema).max(EXPENSE_PEOPLE_MAX),
change: expenseChangeSchema,
});
export const expensesCardSchema = z.object({
kind: z.literal('expenses'),
rows: z.array(cardExpenseSchema).min(1).max(EXPENSE_ROWS_MAX),
/**
* Where in the trip's list the rows start: a later page of the list starts
* past 0, so two pages read as one list only where they meet. 0 on a change.
*/
offset: z.number().int().min(0).max(100_000),
/** Expenses of the trip the card leaves out. */
more: z.number().int().min(0).max(100_000),
/** The list's total over every expense, in the trip currency; null on a change. */
total: cardMoneySchema.nullable(),
/** Expenses the total leaves out: foreign ones no rate converts yet. */
unconverted: z.number().int().min(0).max(100_000),
});
export type ExpensesCard = z.infer<typeof expensesCardSchema>;
export type CardExpense = z.infer<typeof cardExpenseSchema>;
export type CardExpenseShare = z.infer<typeof cardExpenseShareSchema>;
export type CardExpensePayer = z.infer<typeof cardExpensePayerSchema>;
export type CardExpenseBefore = z.infer<typeof cardExpenseBeforeSchema>;
export type ExpenseSplit = z.infer<typeof expenseSplitSchema>;
export type ExpenseChange = z.infer<typeof expenseChangeSchema>;
@@ -0,0 +1,14 @@
import { journalChatCardSchema } from './journal-chat.card';
import { tripChatCardSchema } from './trip-chat.card';
export * from './journal-chat.card';
export * from './trip-chat.card';
/**
* What the chat outside any one trip (the `home` scope) brings to the
* assistant chat: the cards that offer to go on in a trip's own chat or on a
* journal's page. It has no change cards of its own; the writes it proposes
* are the atlas', the vacation planner's, the collections' and a new
* journal's. cards/index.ts spreads the kinds into the card union.
*/
export const HOME_CARD_SCHEMAS = [tripChatCardSchema, journalChatCardSchema] as const;
+209
View File
@@ -0,0 +1,209 @@
import {
ASSISTANT_CHANGE_VERB_KEYS,
assistantAppliedSchema,
assistantChangePreviewSchema,
assistantMessagePartSchema,
assistantMessagePartWriteSchema,
assistantStoredPartsSchema,
assistantTakeProposalRequestSchema,
CORE_APPLIED_ENTITIES,
CORE_VERB_KEYS,
uiStreamChunkSchema,
UI_STREAM_DONE,
} from '../assistant.schema';
import { cardFileKeySchema, cardPersonSchema, cardText, MAX_CARD_CHARS } from './card-parts';
import { assistantCardSchema, storedTrekCardSchema, trekCardSchema } from './index';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
const CALL = 'call_1';
const preview = {
toolCallId: CALL,
verbKey: 'addTour',
subject: 'Lake loop',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
};
/** Every kind as its package declares it today, built from its own literal. */
const KINDS = trekCardSchema.options.map((option) => option.shape.kind.value);
/**
* A kind as the packages build theirs, from the card parts, with bounds to
* cross: the read tolerance is the same for every kind, so these cases hold
* whatever fields the packages give their own.
*/
const probeSchema = z
.discriminatedUnion('kind', [
z.object({ kind: z.literal('probe'), title: cardText(8), people: z.array(cardPersonSchema).max(2) }),
])
.nullable()
.catch(null);
describe('the card union', () => {
it('CARDS-001: holds every kind once, each read as itself', () => {
expect(new Set(KINDS).size).toBe(KINDS.length);
expect(KINDS).toEqual(expect.arrayContaining(['tourRoute', 'tourList', 'packingList', 'todoList']));
for (const kind of KINDS) {
const read = storedTrekCardSchema.parse({ kind });
if (read !== null) expect(read.kind).toBe(kind);
}
});
it('CARDS-002: reads an unknown kind, a missing kind or no card at all as null', () => {
for (const card of [{ kind: 'bookPage' }, {}, null, undefined, 'tourRoute', 7]) {
expect(storedTrekCardSchema.parse(card)).toBeNull();
}
});
it('CARDS-003: reads a field past its bound as null, and drops keys a kind does not declare', () => {
expect(probeSchema.parse({ kind: 'probe', title: 'Far too long a title', people: [] })).toBeNull();
const four = [1, 2, 3, 4].map((id) => ({ id, name: `P${id}`, avatarKey: null }));
expect(probeSchema.parse({ kind: 'probe', title: 'Walk', people: four })).toBeNull();
expect(probeSchema.parse({ kind: 'probe', title: 'Walk', people: [], url: 'https://x.test' })).toEqual({
kind: 'probe',
title: 'Walk',
people: [],
});
});
it('CARDS-004: a stored file key is a file name, never a path, a URL or a way up', () => {
expect(cardFileKeySchema.safeParse('a1b2c3.jpg').success).toBe(true);
for (const key of ['../secret', 'avatars/a.jpg', 'https://x.test/a.jpg', '.hidden', 'a..b', '']) {
expect(cardFileKeySchema.safeParse(key).success).toBe(false);
}
expect(MAX_CARD_CHARS).toBe(24_000);
});
});
describe('cards in parts, chunks and previews', () => {
it('CARDS-010: a card part reads an unknown, a kindless or a broken card as null and keeps the part', () => {
for (const card of [{ kind: 'bookPage', page: 3 }, { title: 'x' }, 'nope']) {
const part = assistantMessagePartSchema.parse({ type: 'data-trek-card', data: { toolCallId: CALL, card } });
expect(part).toEqual({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } });
}
});
it('CARDS-011: a card chunk reads the same way, and a known card comes through with extra keys dropped', () => {
const unknown = uiStreamChunkSchema.parse({
type: 'data-trek-card',
data: { toolCallId: CALL, card: { kind: 'x' } },
});
expect(unknown).toEqual({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } });
const known = assistantCardSchema.parse({ toolCallId: CALL, card: { kind: KINDS[0], later: 1 }, extra: true });
expect(known).not.toHaveProperty('extra');
if (known.card !== null) expect(known.card).not.toHaveProperty('later');
});
it('CARDS-012: a change preview reads without a card, and with a broken one as null', () => {
expect(assistantChangePreviewSchema.parse(preview)).not.toHaveProperty('card');
expect(assistantChangePreviewSchema.parse({ ...preview, card: { kind: 'nope' } }).card).toBeNull();
expect(assistantChangePreviewSchema.parse({ ...preview, card: { title: 'no kind' } }).card).toBeNull();
});
it('CARDS-014: a verb or an entity a later build added reads as a plain update and as other', () => {
const later = { ...preview, verbKey: 'laterVerb' };
expect(assistantChangePreviewSchema.parse(later).verbKey).toBe('genericUpdate');
const receipt = { toolCallId: CALL, entity: 'later_entity', ids: [4], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe('other');
const parts = assistantStoredPartsSchema.parse([
{ type: 'data-trek-change', data: later },
{ type: 'data-trek-applied', data: receipt },
]);
expect(parts.map((part) => part.type)).toEqual(['data-trek-change', 'data-trek-applied']);
});
it('CARDS-013: a card is always under its call, whose id is 1 to 64 characters', () => {
expect(assistantCardSchema.safeParse({ toolCallId: '', card: null }).success).toBe(false);
expect(assistantCardSchema.safeParse({ toolCallId: 'x'.repeat(65), card: null }).success).toBe(false);
});
});
describe('stored parts', () => {
it('CARDS-020: drop a data part this build does not know, or one that no longer reads, and keep the rest', () => {
const parts = assistantStoredPartsSchema.parse([
{ type: 'text', text: 'Here is the walk.' },
{ type: 'data-trek-book-page', data: { page: 3 } },
{ type: 'data-trek-places', data: { toolCallId: CALL } },
{ type: 'data-trek-card', data: { toolCallId: CALL, card: { kind: 'future' } } },
{ type: 'data-trek-change', data: preview },
]);
expect(parts.map((part) => part.type)).toEqual(['text', 'data-trek-card', 'data-trek-change']);
});
it('CARDS-021: still refuse a broken part that is not a data part', () => {
expect(assistantStoredPartsSchema.safeParse([{ type: 'text', text: 5 }]).success).toBe(false);
expect(assistantStoredPartsSchema.safeParse([{ type: 'tool-call' }]).success).toBe(false);
});
it('CARDS-022: are written strictly: an unknown part is no part', () => {
expect(assistantMessagePartSchema.safeParse({ type: 'data-trek-book-page', data: {} }).success).toBe(false);
expect(assistantMessagePartWriteSchema.safeParse({ type: 'data-trek-book-page', data: {} }).success).toBe(false);
});
it('CARDS-023: are written strictly: no verb, entity or card kind this build does not know', () => {
const write = (part: unknown) => assistantMessagePartWriteSchema.safeParse(part).success;
expect(write({ type: 'data-trek-change', data: preview })).toBe(true);
expect(write({ type: 'data-trek-change', data: { ...preview, verbKey: 'laterVerb' } })).toBe(false);
expect(write({ type: 'data-trek-change', data: { ...preview, card: { kind: 'nope' } } })).toBe(false);
const receipt = { toolCallId: CALL, entity: 'later_entity', ids: [4], dayId: null, undoUntil: null };
expect(write({ type: 'data-trek-applied', data: receipt })).toBe(false);
expect(write({ type: 'data-trek-card', data: { toolCallId: CALL, card: { kind: 'nope' } } })).toBe(false);
expect(write({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } })).toBe(true);
});
});
describe('the enums the packages extend', () => {
it('CARDS-030: keep every core verb and entity, the hike verbs among them', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining([...CORE_VERB_KEYS]));
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining(['addTour', 'updateTour', 'importTour']));
expect(new Set(ASSISTANT_CHANGE_VERB_KEYS).size).toBe(ASSISTANT_CHANGE_VERB_KEYS.length);
for (const entity of CORE_APPLIED_ENTITIES) {
expect(assistantAppliedSchema.shape.entity.safeParse(entity).success).toBe(true);
}
});
});
describe('assistantTakeProposalRequestSchema', () => {
it('CARDS-040: names the read whose proposal is taken, with the turn context and nothing else', () => {
const ctx = { locale: 'en', timeZone: 'Europe/Berlin' };
expect(assistantTakeProposalRequestSchema.parse({ ...ctx, toolCallId: CALL })).toEqual({
...ctx,
toolCallId: CALL,
});
expect(assistantTakeProposalRequestSchema.safeParse({ ...ctx, toolCallId: '' }).success).toBe(false);
expect(assistantTakeProposalRequestSchema.safeParse({ ...ctx, toolCallId: CALL, args: {} }).success).toBe(false);
expect(assistantTakeProposalRequestSchema.safeParse({ toolCallId: CALL }).success).toBe(false);
});
});
describe('ui-stream.cards.v1 fixture', () => {
const text = readFileSync(resolve(__dirname, '../__fixtures__/ui-stream.cards.v1.txt'), 'utf8');
const events = text
.split('\n\n')
.filter(Boolean)
.map((event) => event.slice('data: '.length));
const chunks = events.slice(0, -1).map((event) => uiStreamChunkSchema.parse(JSON.parse(event)));
it('CARDS-050: is a stream of valid chunks closed by [DONE]', () => {
expect(events.at(-1)).toBe(UI_STREAM_DONE);
expect(chunks.length).toBeGreaterThan(10);
});
it('CARDS-051: carries an applied write card after its receipt, a read card after its answer, a held one in its preview', () => {
const types = chunks.map((chunk) => chunk.type);
const cards = chunks.flatMap((chunk) => (chunk.type === 'data-trek-card' ? [chunk.data.toolCallId] : []));
const applied = chunks.find((chunk) => chunk.type === 'data-trek-applied');
const read = chunks.find((chunk) => chunk.type === 'tool-input-start' && chunk.toolName === 'list_tours');
expect(applied?.type === 'data-trek-applied' && applied.data.toolCallId).toBe(cards[0]);
expect(read?.type === 'tool-input-start' && read.toolCallId).toBe(cards[1]);
expect(types.indexOf('data-trek-applied')).toBeLessThan(types.indexOf('data-trek-card'));
const change = chunks.find((chunk) => chunk.type === 'data-trek-change');
expect(change?.type === 'data-trek-change' && 'card' in change.data).toBe(true);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { ATLAS_CARD_SCHEMAS } from './atlas.contract';
import { BOOK_DESIGN_CARD_SCHEMAS } from './book-design.contract';
import { BOOK_CARD_SCHEMAS } from './book.contract';
import { BOOKING_CARD_SCHEMAS } from './booking.contract';
import { BUDGET_CARD_SCHEMAS } from './budget.contract';
import { COLLAB_CARD_SCHEMAS } from './collab.contract';
import { COLLECTION_CARD_SCHEMAS } from './collection.contract';
import { HOME_CARD_SCHEMAS } from './home.contract';
import { JOURNEY_CARD_SCHEMAS } from './journey.contract';
import { PACKING_CARD_SCHEMAS } from './packing.contract';
import { ROADTRIP_CARD_SCHEMAS } from './roadtrip.contract';
import { TOUR_CARD_SCHEMAS } from './tour.contract';
import { VACAY_CARD_SCHEMAS } from './vacay.contract';
import { z } from 'zod';
export * from './card-parts';
export * from './atlas.contract';
export * from './book.contract';
export * from './book-design.contract';
export * from './booking.contract';
export * from './budget.contract';
export * from './collab.contract';
export * from './collection.contract';
export * from './home.contract';
export * from './journey.contract';
export * from './packing.contract';
export * from './roadtrip.contract';
export * from './tour.contract';
export * from './vacay.contract';
/**
* The cards of the assistant chat: one per tool call, drawn beside an answer
* (a read's result) or inside a change card (what a held write will do, and
* what it did once applied). Each part of TREK owns its kinds in its
* `<pkg>.contract.ts`; the server builds every card from the tool's own
* answer and checks it against this union before it is sent.
*/
const trekCardUnion = z.discriminatedUnion('kind', [
...TOUR_CARD_SCHEMAS,
...ROADTRIP_CARD_SCHEMAS,
...BUDGET_CARD_SCHEMAS,
...BOOKING_CARD_SCHEMAS,
...COLLAB_CARD_SCHEMAS,
...COLLECTION_CARD_SCHEMAS,
...ATLAS_CARD_SCHEMAS,
...VACAY_CARD_SCHEMAS,
...JOURNEY_CARD_SCHEMAS,
...PACKING_CARD_SCHEMAS,
...BOOK_CARD_SCHEMAS,
...BOOK_DESIGN_CARD_SCHEMAS,
...HOME_CARD_SCHEMAS,
]);
type TrekCardUnion = typeof trekCardUnion;
/**
* The card union under a name of its own: the message, part and thread
* schemas that hold cards then refer to it instead of spelling out every kind
* again, which made the server's typecheck run out of memory. The one member
* keeps the interface from being empty; it is the union's own.
*/
export interface TrekCardSchema extends TrekCardUnion {
readonly options: TrekCardUnion['options'];
}
export const trekCardSchema: TrekCardSchema = trekCardUnion;
export type TrekCard = z.infer<typeof trekCardSchema>;
export type TrekCardKind = TrekCard['kind'];
export type TrekCardOf<K extends TrekCardKind> = Extract<TrekCard, { kind: K }>;
/**
* How a stored or streamed card is read. A kind this build does not know, a
* missing field or a value past a bound reads as null and the card is left
* out, never the message around it: a newer server may write kinds an older
* client or a rolled back server has not heard of (verified with zod 4.6.5).
* Keys a kind does not declare are dropped, so a field added later reads too.
*/
export const storedTrekCardSchema = trekCardSchema.nullable().catch(null);
/** The card of one tool call, under that call's id: a read's, or a held or applied write's. */
export const assistantCardSchema = z.object({
toolCallId: z.string().min(1).max(64),
card: storedTrekCardSchema,
});
export type AssistantCard = z.infer<typeof assistantCardSchema>;
/** The same as the server writes it: a card the union refuses is a bug in its builder, never a silent null. */
export const assistantCardWriteSchema = assistantCardSchema.extend({ card: trekCardSchema.nullable() });
@@ -0,0 +1,46 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { journalChatCardSchema } from './journal-chat.card';
import { describe, expect, it } from 'vitest';
const card = {
kind: 'journalChat',
journey: {
id: 12,
title: 'Japan 2026',
subtitle: 'Two weeks in autumn',
startDate: '2026-11-02',
endDate: '2026-11-16',
entryCount: 4,
photoCount: 120,
},
question: 'Make a new entry for Berlin Hauptbahnhof',
} as const;
describe('journalChatCardSchema', () => {
it('JOURNALCHAT-001: is part of the card union and reads as itself', () => {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
});
it('JOURNALCHAT-002: takes a journal without dates, a subtitle or a question', () => {
const bare = {
kind: 'journalChat',
journey: { id: 3, title: 'Notes', subtitle: null, startDate: null, endDate: null, entryCount: 0, photoCount: 0 },
question: null,
};
expect(journalChatCardSchema.parse(bare)).toEqual(bare);
});
it('JOURNALCHAT-003: refuses a bad id, a bad date, an empty title, a negative count or an overlong question', () => {
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, id: 0 } }).success).toBe(false);
expect(
journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, startDate: '2.11.2026' } }).success,
).toBe(false);
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, title: '' } }).success).toBe(false);
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, entryCount: -1 } }).success).toBe(
false,
);
expect(journalChatCardSchema.safeParse({ ...card, question: 'x'.repeat(501) }).success).toBe(false);
});
});
@@ -0,0 +1,28 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A journal the chat outside any one trip offers to go on with on the
* journal's own page: the conversation there knows the journal's entries and
* photos and can change them, which the chat on the dashboard does not. The
* question is what the user asked about the journal, handed over so it waits
* there ready to send.
*/
export const journalChatCardSchema = z.object({
kind: z.literal('journalChat'),
journey: z.object({
id: idSchema,
title: cardText(200),
subtitle: cardText(300).nullable(),
/** The days of the trips it holds, when it holds any. */
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
entryCount: cardCountSchema,
photoCount: cardCountSchema,
}),
/** The question to ask on the journal's page, in the user's words; null when there is none to hand over. */
question: cardText(500).nullable(),
});
export type JournalChatCard = z.infer<typeof journalChatCardSchema>;
@@ -0,0 +1,126 @@
import {
ASSISTANT_CHANGE_VERB_KEYS,
assistantAppliedSchema,
assistantChangePreviewSchema,
assistantMessagePartSchema,
uiStreamChunkSchema,
} from '../assistant.schema';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { JOURNEY_CARD_LIMITS, journeyEntriesCardSchema, type JourneyEntryLook } from './journey-entries.card';
import { describe, expect, it } from 'vitest';
// JRNCARD-001 to JRNCARD-006
function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
return {
entryId: 12,
type: 'entry',
title: 'Sunset at the Spree',
date: '2026-10-21',
time: '14:30',
place: 'Berlin',
point: { lat: 52.52, lng: 13.405 },
countryCode: 'DE',
story: 'The light over the river was unreal.',
mood: 'amazing',
weather: 'sunny',
photoId: 7,
video: false,
photoCount: 4,
visibility: 'public',
draft: false,
fromTripPlace: false,
dayIndex: 0,
...over,
};
}
function card(entries: JourneyEntryLook[], over: Record<string, unknown> = {}) {
return {
kind: 'journeyEntries',
journeyId: 3,
journalTitle: 'Berlin 2026',
tripJournal: true,
change: 'none',
entries,
more: 0,
...over,
};
}
describe('the journal entries card', () => {
it('JRNCARD-001: reads a full card through the union, as itself', () => {
const parsed = trekCardSchema.parse(card([look(), look({ entryId: 13, photoId: null, dayIndex: 1 })]));
expect(parsed.kind).toBe('journeyEntries');
expect(journeyEntriesCardSchema.parse(parsed).entries).toHaveLength(2);
});
it('JRNCARD-002: holds one to eight entries, a pending entry without an id among them', () => {
expect(journeyEntriesCardSchema.safeParse(card([])).success).toBe(false);
const eight = Array.from({ length: JOURNEY_CARD_LIMITS.entries }, (_, i) => look({ entryId: i + 1 }));
expect(journeyEntriesCardSchema.safeParse(card(eight)).success).toBe(true);
expect(journeyEntriesCardSchema.safeParse(card([...eight, look({ entryId: 99 })])).success).toBe(false);
expect(journeyEntriesCardSchema.safeParse(card([look({ entryId: null })], { change: 'new' })).success).toBe(true);
});
it('JRNCARD-003: a story past its bound, a bad date, time or country reads as no card at all', () => {
const bad = [
look({ story: 'x'.repeat(JOURNEY_CARD_LIMITS.story + 1) }),
look({ date: '21.10.2026' }),
look({ time: '9:05' }),
look({ countryCode: 'de' }),
look({ mood: 'Very Happy' }),
look({ point: { lat: 91, lng: 0 } }),
look({ title: '' }),
];
for (const entry of bad) {
expect(journeyEntriesCardSchema.safeParse(card([entry])).success).toBe(false);
expect(storedTrekCardSchema.parse(card([entry]))).toBeNull();
}
});
it('JRNCARD-004: carries no address of a picture, only the photo id', () => {
const parsed = journeyEntriesCardSchema.parse(
card([{ ...look(), thumbnail_path: '/uploads/x.jpg', file_path: 'secret' } as JourneyEntryLook]),
);
const text = JSON.stringify(parsed);
expect(text).not.toContain('thumbnail_path');
expect(text).not.toContain('/uploads/');
expect(parsed.entries[0]?.photoId).toBe(7);
});
it('JRNCARD-005: rides a data-trek-card part and chunk, and a change preview', () => {
const data = { toolCallId: 'call_1', card: card([look()]) };
const part = assistantMessagePartSchema.parse({ type: 'data-trek-card', data });
expect(part.type === 'data-trek-card' && part.data.card?.kind).toBe('journeyEntries');
const chunk = uiStreamChunkSchema.parse({ type: 'data-trek-card', data });
expect(chunk.type === 'data-trek-card' && chunk.data.card?.kind).toBe('journeyEntries');
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'addJournalEntry',
subject: 'Sunset at the Spree',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card([look({ entryId: null })], { change: 'new' }),
});
expect(preview.verbKey).toBe('addJournalEntry');
expect(preview.card?.kind).toBe('journeyEntries');
});
it('JRNCARD-006: names its verbs and its entity in the shared enums', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(
expect.arrayContaining(['addJournalEntry', 'updateJournalEntry', 'removeJournalEntry']),
);
const applied = assistantAppliedSchema.parse({
toolCallId: 'call_1',
entity: 'journey_entry',
ids: [12],
dayId: null,
undoUntil: null,
});
expect(applied.entity).toBe('journey_entry');
});
});
@@ -0,0 +1,97 @@
import { idSchema } from '../../common/primitives.schema';
import { journeyEntryTypeSchema, journeyEntryVisibilitySchema } from '../../journey/journey.schema';
import { cardClockSchema, cardCountSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Entries of one travel journal as the assistant chat shows them: what a
* read of the journal found (one entry or several), what a held change will
* write, and what it wrote once applied. One kind for all three, so the
* answer, the change row and the receipt read one shape.
*/
/** How much of a journal a card carries; the server clips to the same numbers. */
export const JOURNEY_CARD_LIMITS = {
entries: 8,
title: 100,
place: 80,
story: 240,
journal: 80,
weather: 40,
tags: 6,
tag: 40,
points: 3,
point: 80,
} as const;
/** The verdict on a place as a card shows it: the first points on each side, and how many each side holds. */
export const journeyEntryVerdictSchema = z.object({
pros: z.array(cardText(JOURNEY_CARD_LIMITS.point)).max(JOURNEY_CARD_LIMITS.points),
cons: z.array(cardText(JOURNEY_CARD_LIMITS.point)).max(JOURNEY_CARD_LIMITS.points),
prosCount: cardCountSchema,
consCount: cardCountSchema,
});
export type JourneyEntryVerdict = z.infer<typeof journeyEntryVerdictSchema>;
/**
* One entry as a card shows it. Its texts are plain and on one line (the story
* without its markdown, cut to its start), masked like a provider answer when
* they come from a result; a photo travels as its id, never as a path.
*/
export const journeyEntryLookSchema = z.object({
/** Null for an entry a held change has not written yet. */
entryId: idSchema.nullable(),
type: journeyEntryTypeSchema,
title: cardText(JOURNEY_CARD_LIMITS.title).nullable(),
date: cardDateSchema,
time: cardClockSchema.nullable(),
/** The place as the entry names it; the client shortens it as the journal does. */
place: cardText(JOURNEY_CARD_LIMITS.place).nullable(),
point: z.object({ lat: cardLatSchema, lng: cardLngSchema }).nullable(),
countryCode: z
.string()
.regex(/^[A-Z]{2}$/)
.nullable(),
story: cardText(JOURNEY_CARD_LIMITS.story).nullable(),
/** A mood id; the client draws the ones it knows and leaves the rest out. */
mood: z
.string()
.regex(/^[a-z]{1,20}$/)
.nullable(),
/** A weather id the journal knows, or the words the traveller wrote. */
weather: cardText(JOURNEY_CARD_LIMITS.weather).nullable(),
/** The TREK photo the entry opens with (its thumbnail), the first one that has a picture. */
photoId: idSchema.nullable(),
/** That photo is the poster of a clip. */
video: z.boolean(),
photoCount: cardCountSchema,
visibility: journeyEntryVisibilitySchema,
draft: z.boolean(),
/** Made from a place of a trip: deleting it turns it back into a suggestion. */
fromTripPlace: z.boolean(),
/** Which day of the journal it falls on, counted from 0, for the day's colour; null when unknown. */
dayIndex: z.number().int().min(0).max(9_999).nullable(),
/** Its first tags. Optional, like the two below: cards stored before they existed leave them out. */
tags: z.array(cardText(JOURNEY_CARD_LIMITS.tag)).max(JOURNEY_CARD_LIMITS.tags).optional(),
verdict: journeyEntryVerdictSchema.nullable().optional(),
/** In a new order of the journal's entries, this one changed its place. */
moved: z.boolean().optional(),
});
export type JourneyEntryLook = z.infer<typeof journeyEntryLookSchema>;
/** What a change card's entries go through: nothing on an answer, else what the change does to them. */
export const JOURNEY_CARD_CHANGES = ['none', 'new', 'changed', 'willDelete', 'reordered'] as const;
export const journeyEntriesCardSchema = z.object({
kind: z.literal('journeyEntries'),
journeyId: idSchema,
journalTitle: cardText(JOURNEY_CARD_LIMITS.journal).nullable(),
/** The journal is the one the open trip shows in its Journal tab, as read when the card was made. */
tripJournal: z.boolean(),
change: z.enum(JOURNEY_CARD_CHANGES),
entries: z.array(journeyEntryLookSchema).min(1).max(JOURNEY_CARD_LIMITS.entries),
/** Entries the read found that the card does not carry. */
more: cardCountSchema,
});
export type JourneyEntriesCard = z.infer<typeof journeyEntriesCardSchema>;
@@ -0,0 +1,39 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { JOURNEY_HEADER_LIMITS, journeyHeaderCardSchema } from './journey-header.card';
import { describe, expect, it } from 'vitest';
const card = {
kind: 'journeyHeader',
journeyId: 12,
title: 'Japan 2026',
subtitle: null,
change: 'changed',
trips: [{ id: 5, title: 'Tokyo days', startDate: '2026-11-02', endDate: null, change: 'link' }],
entries: 3,
photos: null,
suggestions: 9,
} as const;
describe('journeyHeaderCardSchema', () => {
it('JOURNEYHEADER-001: is part of the card union and reads as itself', () => {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
});
it('JOURNEYHEADER-002: takes a new journal without an id, and a trip the user trips do not list', () => {
const fresh = { ...card, journeyId: null, change: 'new', trips: [{ ...card.trips[0], id: null }] };
expect(journeyHeaderCardSchema.parse(fresh)).toEqual(fresh);
});
it('JOURNEYHEADER-003: refuses an unknown change, too many trips, an empty title or a negative count', () => {
expect(journeyHeaderCardSchema.safeParse({ ...card, change: 'renamed' }).success).toBe(false);
const many = Array.from({ length: JOURNEY_HEADER_LIMITS.trips + 1 }, () => card.trips[0]);
expect(journeyHeaderCardSchema.safeParse({ ...card, trips: many }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, title: '' }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, entries: -1 }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, trips: [{ ...card.trips[0], change: 'moved' }] }).success).toBe(
false,
);
});
});
@@ -0,0 +1,47 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A journal itself as the assistant chat shows a change of it: a new one,
* its settings changed, a trip linked or unlinked, its suggestions brought
* back, or the whole journal deleted. The rows of the change card say what
* changes field by field; this card is the journal under them, its trips and
* what a change takes with it.
*/
/** How much of a journal the card carries; the server clips to the same numbers. */
export const JOURNEY_HEADER_LIMITS = { title: 200, subtitle: 300, trips: 12, tripTitle: 120 } as const;
/** What the change does to the journal: makes it, changes it, deletes it. */
export const JOURNEY_HEADER_CHANGES = ['new', 'changed', 'willDelete'] as const;
/** What the change does to one of its trips. */
export const JOURNEY_HEADER_TRIP_CHANGES = ['kept', 'link', 'unlink'] as const;
export const journeyHeaderTripSchema = z.object({
/** Null for a trip a new journal names that the user's trips do not list. */
id: idSchema.nullable(),
title: cardText(JOURNEY_HEADER_LIMITS.tripTitle),
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
change: z.enum(JOURNEY_HEADER_TRIP_CHANGES),
});
export type JourneyHeaderTrip = z.infer<typeof journeyHeaderTripSchema>;
export const journeyHeaderCardSchema = z.object({
kind: z.literal('journeyHeader'),
/** Null for a journal a held change has not made yet. */
journeyId: idSchema.nullable(),
title: cardText(JOURNEY_HEADER_LIMITS.title),
subtitle: cardText(JOURNEY_HEADER_LIMITS.subtitle).nullable(),
change: z.enum(JOURNEY_HEADER_CHANGES),
trips: z.array(journeyHeaderTripSchema).max(JOURNEY_HEADER_LIMITS.trips),
/** What the journal holds: what a deletion takes with it, what an unlinked trip leaves behind. */
entries: cardCountSchema.nullable(),
photos: cardCountSchema.nullable(),
/** Places of the linked trips that come in as suggestions; null when unknown. */
suggestions: cardCountSchema.nullable(),
});
export type JourneyHeaderCard = z.infer<typeof journeyHeaderCardSchema>;
@@ -0,0 +1,57 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Photos of a journal as the assistant chat shows a change of them: one put
* on an entry or taken off it, photos moved from one entry to another, an
* entry's photos in a new order (the first is its cover), a caption changed,
* photos added from a library. A photo travels as its TREK photo id, which
* the client turns into TREK's own thumbnail address.
*/
/** How much a card carries; the server clips to the same numbers. */
export const JOURNEY_PHOTOS_LIMITS = { photos: 8, caption: 160, title: 100 } as const;
export const JOURNEY_PHOTOS_MODES = ['link', 'unlink', 'move', 'order', 'caption', 'add'] as const;
/** An entry the photos leave or reach. */
export const journeyPhotosEntrySchema = z.object({
entryId: idSchema.nullable(),
title: cardText(JOURNEY_PHOTOS_LIMITS.title).nullable(),
date: cardDateSchema.nullable(),
});
export type JourneyPhotosEntry = z.infer<typeof journeyPhotosEntrySchema>;
export const journeyPhotoLookSchema = z.object({
/** The TREK photo, for its thumbnail. */
photoId: idSchema,
video: z.boolean(),
caption: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
});
export type JourneyPhotoLook = z.infer<typeof journeyPhotoLookSchema>;
export const journeyPhotosCardSchema = z.object({
kind: z.literal('journeyPhotos'),
journeyId: idSchema,
mode: z.enum(JOURNEY_PHOTOS_MODES),
/** The entry the photos leave (a move, an unlink). */
from: journeyPhotosEntrySchema.nullable(),
/** The entry the photos reach or whose photos change (a link, a move, a new order, an add). */
to: journeyPhotosEntrySchema.nullable(),
/** In the order the change leaves them; for a new order, the first is the entry's cover. */
photos: z.array(journeyPhotoLookSchema).max(JOURNEY_PHOTOS_LIMITS.photos),
/** Photos the change concerns that the card does not carry. */
more: cardCountSchema,
/** A move that leaves the photos on the first entry as well. */
kept: z.boolean(),
/** A caption change, old to new; null on every other change. */
caption: z
.object({
before: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
after: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
})
.nullable(),
});
export type JourneyPhotosCard = z.infer<typeof journeyPhotosCardSchema>;
@@ -0,0 +1,49 @@
import { journeyEntriesCardSchema } from './journey-entries.card';
import { journeyHeaderCardSchema } from './journey-header.card';
import { journeyPhotosCardSchema } from './journey-photos.card';
export * from './journey-entries.card';
export * from './journey-header.card';
export * from './journey-photos.card';
/**
* What the travel journal brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const JOURNEY_CARD_SCHEMAS = [
journeyEntriesCardSchema,
journeyHeaderCardSchema,
journeyPhotosCardSchema,
] as const;
/**
* An entry written, changed or deleted, the entries put in a new order; a journal started, renamed, given
* another status or other settings, deleted; a trip linked or unlinked; its
* suggestions brought back; the user's own view of it changed; a photo put on
* an entry, taken off, moved, put in order, captioned or added.
*/
export const JOURNEY_VERB_KEYS = [
'addJournalEntry',
'updateJournalEntry',
'removeJournalEntry',
'reorderJournalEntries',
'createJournal',
'renameJournal',
'setJournalStatus',
'updateJournalSettings',
'deleteJournal',
'linkJournalTrip',
'unlinkJournalTrip',
'restoreJournalSuggestions',
'setJournalPreferences',
'linkJournalPhoto',
'unlinkJournalPhoto',
'moveJournalPhotos',
'orderJournalPhotos',
'captionJournalPhoto',
'addJournalPhotos',
] as const;
/** An entry of a journal, or the journal itself; the receipt opens it there. */
export const JOURNEY_APPLIED_ENTITIES = ['journey_entry', 'journey'] as const;
@@ -0,0 +1,121 @@
import { idSchema } from '../../common/primitives.schema';
import { cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A packing list in the assistant chat: the trip's, the part a tour points
* at, or a template about to be added. It is grouped the way the packing
* list shows it, by category or by bag; a bag overview is the same card with
* the bags as groups and no item rows. On a change card the rows carry what
* the change does to them (`change`, and the old value of every field it
* touches), on an answer `change` is `none`.
*/
const gramsSchema = z.number().int().min(0).max(1_000_000);
const checklistCountSchema = z.number().int().min(0).max(5_000);
/**
* The index of a category in the order its list first shows it; the client
* maps it onto the list's own colours, so the chat's dot matches the panel's.
* Null where the card does not know the category yet (the hash colour then).
*/
export const checklistColorSlotSchema = z.number().int().min(0).max(999);
/** The value a field held before a change, as stored (an ISO date, a colour, grams, a name). */
export const checklistBeforeSchema = z.string().max(120).nullable();
export const PACKING_ROW_CHANGES = ['none', 'add', 'update', 'check', 'uncheck', 'remove', 'share'] as const;
export const PACKING_ITEM_FIELDS = ['name', 'category', 'quantity', 'packed', 'weight', 'bag', 'tier'] as const;
export const PACKING_BAG_FIELDS = ['name', 'color', 'limit', 'owner'] as const;
export const PACKING_TIERS = ['common', 'personal', 'shared'] as const;
/** A bag on the list (`id:12`) or one a pending import creates (`new:0`). */
export const packingBagKeySchema = z.string().regex(/^(id:\d{1,12}|new:\d{1,2})$/);
export const packingCardBagSchema = z.object({
key: packingBagKeySchema,
id: idSchema.nullable(),
name: cardText(100),
/** Null while a create waits for the server to pick it. */
color: cardHexColorSchema.nullable(),
/** What the bag weighs with every member's items in it (#2191). */
weightGrams: gramsSchema.nullable(),
limitGrams: gramsSchema.nullable(),
owner: cardPersonSchema.nullable(),
members: z.array(cardPersonSchema).max(6),
membersRemoved: z.array(cardPersonSchema).max(6),
change: z.enum(['none', 'add', 'update', 'remove', 'members']),
changed: z.array(z.object({ field: z.enum(PACKING_BAG_FIELDS), before: checklistBeforeSchema })).max(4),
/** For a bag about to be deleted: the items that land in "Unassigned". */
movesOut: checklistCountSchema,
});
export type PackingCardBag = z.infer<typeof packingCardBagSchema>;
export const packingCardItemSchema = z.object({
/** Null while a create waits. */
id: idSchema.nullable(),
name: cardText(200),
quantity: z.number().int().min(1).max(999),
/** All of it once ticked, the partial count before that (#2296). */
packed: z.number().int().min(0).max(999),
checked: z.boolean(),
/** Unit weight times quantity; null where none is recorded. */
weightGrams: gramsSchema.nullable(),
/** One of the card's `bags`; null for an item in no bag. */
bagKey: packingBagKeySchema.nullable(),
tier: z.enum(PACKING_TIERS),
sharedWith: z.array(cardPersonSchema).max(4),
change: z.enum(PACKING_ROW_CHANGES),
changed: z.array(z.object({ field: z.enum(PACKING_ITEM_FIELDS), before: checklistBeforeSchema })).max(7),
});
export type PackingCardItem = z.infer<typeof packingCardItemSchema>;
export const packingCardGroupSchema = z.object({
key: z.discriminatedUnion('by', [
z.object({
by: z.literal('category'),
/** Null: the items without a category, which the list files under its default one. */
name: cardText(100).nullable(),
slot: checklistColorSlotSchema.nullable(),
}),
/** Null: the pile in no bag. */
z.object({ by: z.literal('bag'), bagKey: packingBagKeySchema.nullable() }),
]),
/** Who looks after the category. */
assignees: z.array(cardPersonSchema).max(6),
/** Who a change of the category's people takes off it. */
assigneesRemoved: z.array(cardPersonSchema).max(6),
items: z.array(packingCardItemSchema).max(40),
/** The group's items on the list, shown or not. */
count: checklistCountSchema,
packed: checklistCountSchema,
});
export type PackingCardGroup = z.infer<typeof packingCardGroupSchema>;
export const packingListCardSchema = z.object({
kind: z.literal('packingList'),
source: z.discriminatedUnion('type', [
z.object({ type: z.literal('trip') }),
z.object({
type: z.literal('tour'),
placeId: idSchema,
name: cardText(200),
category: cardText(200).nullable(),
}),
z.object({
type: z.literal('template'),
templateId: idSchema,
name: cardText(100),
itemCount: checklistCountSchema,
}),
]),
groupBy: z.enum(['category', 'bag']),
/** How much of the list is packed; answers only. */
progress: z.object({ packed: checklistCountSchema, total: checklistCountSchema }).nullable(),
bags: z.array(packingCardBagSchema).max(20),
groups: z.array(packingCardGroupSchema).max(12),
/** Groups past the twelve shown. */
moreGroups: checklistCountSchema,
});
export type PackingListCard = z.infer<typeof packingListCardSchema>;
@@ -0,0 +1,161 @@
import { packingListItemsRequestSchema } from '../../packing/packing.schema';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { packingListCardSchema } from './packing-list.card';
import { todoListCardSchema } from './todo-list.card';
import { describe, expect, it } from 'vitest';
/**
* PKCARD-001 to PKCARD-008: the packing and to-do cards of the assistant
* chat. Both kinds join the card union; every field is bounded; a bag is
* named by a key, a colour only as `#rrggbb`, a person never with an address,
* a date only as `YYYY-MM-DD`; and the list read they come from takes its
* filters in a closed shape.
*/
const ANA = { id: 2, name: 'Ana', avatarKey: 'ana.png' };
const item = (over: Record<string, unknown> = {}) => ({
id: 7,
name: 'Rain jacket',
quantity: 1,
packed: 0,
checked: false,
weightGrams: 480,
bagKey: 'id:3',
tier: 'common',
sharedWith: [],
change: 'none',
changed: [],
...over,
});
const bag = (over: Record<string, unknown> = {}) => ({
key: 'id:3',
id: 3,
name: 'Carry-on',
color: '#6366f1',
weightGrams: 6200,
limitGrams: 8000,
owner: ANA,
members: [ANA],
membersRemoved: [],
change: 'none',
changed: [],
movesOut: 0,
...over,
});
const packing = (over: Record<string, unknown> = {}) => ({
kind: 'packingList',
source: { type: 'trip' },
groupBy: 'category',
progress: { packed: 1, total: 3 },
bags: [bag()],
groups: [
{
key: { by: 'category', name: 'Clothes', slot: 0 },
assignees: [ANA],
assigneesRemoved: [],
items: [item()],
count: 3,
packed: 1,
},
],
moreGroups: 0,
...over,
});
/** The packing card with one row in its one group. */
const withRow = (row: unknown) => packing({ groups: [{ ...packing().groups[0], items: [row] }] });
const todo = (over: Record<string, unknown> = {}) => ({
id: 9,
name: 'Book the ferry',
note: 'Check the early sailing first',
checked: false,
dueDate: '2026-06-12',
dueDayId: 31,
priority: 1,
assignee: ANA,
change: 'none',
changed: [],
...over,
});
const todos = (items: unknown[] = [todo()]) => ({
kind: 'todoList',
progress: { open: 2, done: 1, overdue: 1 },
groups: [{ category: 'Bookings', slot: 0, assignees: [], assigneesRemoved: [], items, count: 2, open: 2 }],
moreGroups: 0,
});
describe('packing and to-do cards', () => {
it('PKCARD-001: a packing list, a bag overview, a tour and a template source all read as cards of the union', () => {
expect(trekCardSchema.parse(packing()).kind).toBe('packingList');
const bags = packing({ groupBy: 'bag', progress: null, groups: [] });
expect(packingListCardSchema.safeParse(bags).success).toBe(true);
const tour = { type: 'tour', placeId: 11, name: 'Ridge', category: 'Hiking gear' };
expect(packingListCardSchema.safeParse(packing({ source: tour })).success).toBe(true);
const template = { type: 'template', templateId: 4, name: 'Beach week', itemCount: 24 };
expect(packingListCardSchema.safeParse(packing({ source: template, groups: [] })).success).toBe(true);
const pile = { key: { by: 'bag', bagKey: null }, assignees: [], assigneesRemoved: [], items: [], count: 2 };
expect(packingListCardSchema.safeParse(packing({ groups: [{ ...pile, packed: 0 }] })).success).toBe(true);
});
it('PKCARD-002: bags are named by key, a waiting one as new:N; any other key is refused', () => {
const waiting = bag({ key: 'new:0', id: null, color: null });
expect(packingListCardSchema.safeParse(packing({ bags: [waiting] })).success).toBe(true);
for (const key of ['3', 'id:', 'new:123', 'bag:3']) {
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ key })] })).success, key).toBe(false);
}
});
it('PKCARD-003: a colour is only #rrggbb and a person never carries an address', () => {
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ color: '#abc' })] })).success).toBe(false);
const url = { ...ANA, avatarKey: 'https://example.com/a.png' };
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ owner: url })] })).success).toBe(false);
expect(todoListCardSchema.safeParse(todos([todo({ assignee: url })])).success).toBe(false);
});
it('PKCARD-004: counts stay in bounds: no more than 999 packed, no item without a name', () => {
for (const row of [item({ packed: 1000 }), item({ name: '' }), item({ quantity: 0 })]) {
expect(packingListCardSchema.safeParse(withRow(row)).success).toBe(false);
}
const many = packing({ groups: Array(13).fill(packing().groups[0]) });
expect(packingListCardSchema.safeParse(many).success).toBe(false);
});
it('PKCARD-005: a change row says what it does and what each touched field held before', () => {
const changed = item({ change: 'update', changed: [{ field: 'bag', before: 'Daypack' }] });
expect(packingListCardSchema.safeParse(withRow(changed)).success).toBe(true);
const odd = item({ change: 'update', changed: [{ field: 'colour', before: null }] });
expect(packingListCardSchema.safeParse(withRow(odd)).success).toBe(false);
});
it('PKCARD-006: a to-do list reads as a card, a tick keeping whether it was done; a local date is refused', () => {
expect(trekCardSchema.parse(todos()).kind).toBe('todoList');
expect(todoListCardSchema.safeParse(todos([todo({ dueDate: '12.06.2026' })])).success).toBe(false);
expect(todoListCardSchema.safeParse(todos([todo({ priority: 4 })])).success).toBe(false);
const plain = todo({ dueDate: null, dueDayId: null, note: null });
expect(todoListCardSchema.safeParse(todos([plain])).success).toBe(true);
const ticked = todo({ change: 'check', checked: true, changed: [{ field: 'done', before: '0' }] });
expect(todoListCardSchema.safeParse(todos([ticked])).success).toBe(true);
});
it('PKCARD-007: a broken stored card reads as null instead of breaking the message', () => {
expect(storedTrekCardSchema.parse(packing({ groupBy: 'weight' }))).toBeNull();
expect(storedTrekCardSchema.parse(todos([todo({ change: 'archive' })]))).toBeNull();
});
it('PKCARD-008: the list read takes a category, a bag or none, a packed state and a grouping, nothing else', () => {
expect(packingListItemsRequestSchema.parse({ bag_id: null, status: 'open', group_by: 'bag' })).toEqual({
bag_id: null,
status: 'open',
group_by: 'bag',
});
expect(packingListItemsRequestSchema.safeParse({ status: 'done' }).success).toBe(false);
expect(packingListItemsRequestSchema.safeParse({ bag_id: 0 }).success).toBe(false);
expect(packingListItemsRequestSchema.safeParse({ category: '' }).success).toBe(false);
});
});
@@ -0,0 +1,18 @@
import { packingListCardSchema } from './packing-list.card';
import { todoListCardSchema } from './todo-list.card';
export * from './packing-list.card';
export * from './todo-list.card';
/**
* What the packing and to-do lists bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else. Their changes name the generic
* verbs with the tool's own label; a bag is the one thing they touch that the
* core has no name for.
*/
export const PACKING_CARD_SCHEMAS = [packingListCardSchema, todoListCardSchema] as const;
export const PACKING_VERB_KEYS = [] as const;
export const PACKING_APPLIED_ENTITIES = ['packing_bag'] as const;
@@ -0,0 +1,51 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCurrencySchema, cardDateSchema, cardPersonSchema, cardText } from './card-parts';
import { expenseChangeSchema } from './expenses.card';
import { z } from 'zod';
/**
* Settle-up payments between the travellers, as the Costs page lists them
* under its payment history: who paid whom, how much, on which day, with the
* note it carries. One card serves the list (`list_settlements`) and every
* change to one payment; a waiting change names what it replaces in `before`.
*/
/** Payments one card lists; the rest are counted in `more`. */
export const PAYMENT_ROWS_MAX = 12;
/** What one payment moved: always more than nothing. */
export const cardPaymentMoneySchema = z.object({
amount: z.number().positive().max(1e9),
currency: cardCurrencySchema,
});
/** The values a waiting update of a payment replaces, each null where it stays. */
export const cardPaymentBeforeSchema = z.object({
from: cardPersonSchema.nullable(),
to: cardPersonSchema.nullable(),
amount: cardPaymentMoneySchema.nullable(),
});
export const cardPaymentSchema = z.object({
/** Null while a new payment waits for its decision. */
id: idSchema.nullable(),
from: cardPersonSchema,
to: cardPersonSchema,
amount: cardPaymentMoneySchema,
/** The day it was paid, else the day it was recorded. */
date: cardDateSchema.nullable(),
note: cardText(120).nullable(),
before: cardPaymentBeforeSchema.nullable(),
change: expenseChangeSchema,
});
export const paymentsCardSchema = z.object({
kind: z.literal('payments'),
rows: z.array(cardPaymentSchema).min(1).max(PAYMENT_ROWS_MAX),
more: z.number().int().min(0).max(100_000),
});
export type PaymentsCard = z.infer<typeof paymentsCardSchema>;
export type CardPayment = z.infer<typeof cardPaymentSchema>;
export type CardPaymentMoney = z.infer<typeof cardPaymentMoneySchema>;
@@ -0,0 +1,42 @@
import { idSchema } from '../../common/primitives.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardText } from './card-parts';
import { z } from 'zod';
/**
* The rules a road trip drives by, as a held change sets them: the driving
* settings it changes, each from its old value to its new one, or where it
* makes a day end (at a stop, part way along a drive, or back to the
* automatic end). The client names each setting the way the planner's
* settings name it, so a setting this build does not know reads by its key.
*/
/** A setting's value as the planner stores it: a clock, a number, a switch, a choice; null when it is not set. */
const settingValueSchema = z.union([z.string().max(40), z.number().min(0).max(100_000), z.boolean()]).nullable();
export const roadtripRulesCardSchema = z.object({
kind: z.literal('roadtripRules'),
settings: z
.array(
z.object({
key: z.string().regex(/^roadtrip_[a-z0-9_]{1,40}$/),
before: settingValueSchema,
after: settingValueSchema,
}),
)
.max(24),
dayEnd: z
.object({
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS),
// At the stop `from`; `percent` along the drive from `from` to `to`; or the automatic end again.
mode: z.enum(['stop', 'along', 'auto']),
from: cardText(80).nullable(),
to: cardText(80).nullable(),
percent: z.number().int().min(0).max(100).nullable(),
})
.nullable(),
});
export type RoadtripRulesCard = z.infer<typeof roadtripRulesCardSchema>;
export type RoadtripSettingChange = RoadtripRulesCard['settings'][number];
+138
View File
@@ -0,0 +1,138 @@
import { idSchema } from '../../common/primitives.schema';
import { roadtripStopTypeSchema } from '../../place/place.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardClockSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardPointSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A road trip's drive as calculate_roadtrip worked it out: the totals, a
* strip of its days and, for each day, the stops the planner's rail lists, in
* the shape the rail reads them, so the chat draws the very rows the planner
* draws. The server builds it from the tool's raw answer and fits it under
* MAX_CARD_CHARS: a long trip keeps its first days and counts the rest
* (`moreDays`), a long day its first stops (`moreStops`), and the lines of
* the drive are thinned until the card fits.
*/
/** The days a card holds in full; the rest are counted in `moreDays`. */
export const ROADTRIP_CARD_DAYS_MAX = 14;
/** The stops of one day a card holds; the rest are counted in `moreStops`. */
export const ROADTRIP_CARD_STOPS_MAX = 16;
/** The driven pieces of one day; a ride between two terminals splits a day's line. */
export const ROADTRIP_CARD_DAY_LINES_MAX = 4;
/** The points of one driven piece. */
export const ROADTRIP_CARD_LINE_POINTS_MAX = 64;
/** The points of every line of the card together. */
export const ROADTRIP_CARD_POINTS_MAX = 400;
const metres = z.number().min(0).max(5e7);
const seconds = z.number().min(0).max(1e7);
const minutes = z.number().int().min(0).max(100_000);
const dayNumber = z.number().int().min(1).max(MAX_TRIP_DAYS);
/** A driven piece of a day, `[lat, lng]` points at five decimals. */
export const roadtripCardLineSchema = z.array(cardPointSchema).min(2).max(ROADTRIP_CARD_LINE_POINTS_MAX);
/** One stop of a day as the planner's rail reads it, with its schedule entry and what is wrong about it. */
export const roadtripCardStopSchema = z.object({
// Null for a ride's terminal or a hire car's desk, which are no places of the trip.
placeId: idSchema.nullable(),
// Null for a booked night at a day's edge and for a terminal: neither is an assignment.
assignmentId: idSchema.nullable(),
name: cardText(80),
lat: cardLatSchema,
lng: cardLngSchema,
stopType: roadtripStopTypeSchema.nullable(),
// A time pinned on the stop, and the time the drive leaves it at.
time: cardClockSchema.nullable(),
leaveAt: cardClockSchema.nullable(),
dwellMinutes: z.number().int().min(0).max(10_080).nullable(),
offRoadM: z.number().int().min(0).max(100_000).nullable(),
// The stop's own fill figure; null follows the trip's setting.
fillPercent: z.number().int().min(0).max(100).nullable(),
// The booked night's stop on its check-in day.
night: z.object({ checkIn: cardClockSchema.nullable() }).nullable(),
// A marker the daily travel times put where a day ends or resumes.
autoNight: z.object({ phase: z.enum(['start', 'end']), fromDayNumber: dayNumber }).nullable(),
bookend: z
.object({
phase: z.enum(['morning', 'evening']),
reservationId: idSchema.nullable(),
checkingIn: z.boolean(),
checkingOut: z.boolean(),
checkIn: cardClockSchema.nullable(),
checkOut: cardClockSchema.nullable(),
})
.nullable(),
carrier: z
.object({
reservationId: idSchema,
type: z.string().min(1).max(20),
role: z.enum(['departure', 'arrival', 'pickup', 'return']),
title: cardText(80),
code: z.string().min(1).max(8).nullable(),
at: cardClockSchema.nullable(),
})
.nullable(),
// The schedule's entry for the stop.
arrival: cardClockSchema.nullable(),
departure: cardClockSchema.nullable(),
anchored: z.boolean(),
dayOffset: z.number().int().min(0).max(60),
late: z.array(z.object({ code: z.enum(['late', 'missedLeave']), minutes })).max(2),
// About the drive LEAVING this stop.
findings: z
.array(
z.object({
code: z.enum(['leg', 'range']),
overMinutes: minutes.nullable(),
sinceKm: z.number().min(0).max(40_000).nullable(),
}),
)
.max(2),
});
/** One day of the drive. `legs[i]` runs from `stops[i]` to `stops[i + 1]`; null where it is not routed. */
export const roadtripCardDaySchema = z.object({
dayId: idSchema,
dayNumber,
date: cardDateSchema.nullable(),
title: cardText(80).nullable(),
distanceM: metres,
durationS: seconds,
stops: z.array(roadtripCardStopSchema).max(ROADTRIP_CARD_STOPS_MAX),
moreStops: z.number().int().min(0).max(1000),
legs: z
.array(z.object({ distanceM: metres, durationS: seconds, mode: z.string().min(1).max(40) }).nullable())
.max(ROADTRIP_CARD_STOPS_MAX - 1),
dayOver: z.object({ minutes, limitMinutes: z.number().int().min(1).max(1440) }).nullable(),
avoidMissed: z.array(z.enum(['motorway', 'toll', 'ferry'])).max(3),
// Where the range runs out, counted from the last fill.
dryKm: z.number().min(0).max(40_000).nullable(),
// The driven pieces only: a ride's straight jump between its terminals is left out.
lines: z.array(roadtripCardLineSchema).max(ROADTRIP_CARD_DAY_LINES_MAX),
});
export const roadtripCardSchema = z.object({
kind: z.literal('roadtrip'),
complete: z.boolean(),
problem: z.enum(['routing', 'coordinates', 'dayWindow']).nullable(),
// The settings a preview tried without saving them; empty for the saved drive.
previewKeys: z.array(z.string().regex(/^roadtrip_[a-z0-9_]{1,40}$/)).max(12),
vehicle: z.enum(['combustion', 'electric']).nullable(),
defaultFill: z.number().int().min(1).max(100).nullable(),
// The trip's own setting, so the sketch colours its days the way the map does.
dayColors: z.boolean(),
distanceM: metres,
durationS: seconds,
stopCount: z.number().int().min(0).max(10_000),
chargingCount: z.number().int().min(0).max(10_000),
days: z.array(roadtripCardDaySchema).min(1).max(ROADTRIP_CARD_DAYS_MAX),
moreDays: z.number().int().min(0).max(1000),
quietDays: z.number().int().min(0).max(1000),
undatedRides: z.number().int().min(0).max(100),
});
export type RoadtripCard = z.infer<typeof roadtripCardSchema>;
export type RoadtripCardDay = z.infer<typeof roadtripCardDaySchema>;
export type RoadtripCardStop = z.infer<typeof roadtripCardStopSchema>;
@@ -0,0 +1,241 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema } from '../assistant.schema';
import { MAX_CARD_CHARS } from './card-parts';
import { chargingCardSchema } from './charging.card';
import { corridorCardSchema } from './corridor.card';
import { dayRouteCardSchema } from './day-route.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { roadtripRulesCardSchema } from './roadtrip-rules.card';
import { ROADTRIP_CARD_DAYS_MAX, roadtripCardSchema, type RoadtripCardStop } from './roadtrip.card';
import { ROADTRIP_VERB_KEYS } from './roadtrip.contract';
import { transitCardSchema } from './transit.card';
import { describe, expect, it } from 'vitest';
const stop = (name: string, extra: Partial<RoadtripCardStop> = {}): RoadtripCardStop => ({
placeId: 7,
assignmentId: 70,
name,
lat: 48.13743,
lng: 11.57549,
stopType: null,
time: null,
leaveAt: null,
dwellMinutes: 30,
offRoadM: null,
fillPercent: null,
night: null,
autoNight: null,
bookend: null,
carrier: null,
arrival: '08:00',
departure: '08:30',
anchored: false,
dayOffset: 0,
late: [],
findings: [],
...extra,
});
const day = (dayId: number) => ({
dayId,
dayNumber: dayId,
date: '2026-10-01',
title: null,
distanceM: 152_000,
durationS: 5880,
stops: [stop('Munich'), stop('Verona', { placeId: 8, assignmentId: 80, arrival: '15:20', departure: null })],
moreStops: 0,
legs: [{ distanceM: 152_000, durationS: 5880, mode: 'driving' }],
dayOver: null,
avoidMissed: [],
dryKm: null,
lines: [
[
[48.13743, 11.57549],
[45.43839, 10.99162],
],
],
});
const drive = {
kind: 'roadtrip',
complete: true,
problem: null,
previewKeys: [],
vehicle: 'electric',
defaultFill: 80,
dayColors: true,
distanceM: 152_000,
durationS: 5880,
stopCount: 2,
chargingCount: 0,
days: [day(1)],
moreDays: 0,
quietDays: 0,
undatedRides: 0,
};
describe('road trip cards', () => {
it('RTCARD-010: a drive with its days, stops and lines reads, and is one of the union', () => {
expect(roadtripCardSchema.safeParse(drive).success).toBe(true);
expect(trekCardSchema.safeParse(drive).success).toBe(true);
});
it('RTCARD-011: a drive past its bounds reads as no card instead of breaking the message', () => {
const days = Array.from({ length: ROADTRIP_CARD_DAYS_MAX + 1 }, (_, index) => day(index + 1));
expect(roadtripCardSchema.safeParse({ ...drive, days }).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...drive, days })).toBeNull();
expect(storedTrekCardSchema.parse({ ...drive, days: [] })).toBeNull();
const badClock = { ...drive, days: [{ ...day(1), stops: [stop('Munich', { arrival: '25:00' })] }] };
expect(roadtripCardSchema.safeParse(badClock).success).toBe(false);
const oneLinePoint = { ...drive, days: [{ ...day(1), lines: [[[48, 11]]] }] };
expect(roadtripCardSchema.safeParse(oneLinePoint).success).toBe(false);
});
it('RTCARD-012: a terminal, a booked night and a day marker are stops of their own shape', () => {
const terminal = stop('Munich Airport', {
placeId: null,
assignmentId: null,
carrier: { reservationId: 4, type: 'flight', role: 'departure', title: 'LH 1840', code: 'MUC', at: '11:05' },
});
const night = stop('Hotel Adler', {
assignmentId: null,
stopType: 'hotel',
bookend: {
phase: 'evening',
reservationId: null,
checkingIn: true,
checkingOut: false,
checkIn: '15:00',
checkOut: null,
},
});
const marker = stop('Brenner', { autoNight: { phase: 'end', fromDayNumber: 1 } });
const card = { ...drive, days: [{ ...day(1), stops: [terminal, night, marker], legs: [null, null] }] };
expect(roadtripCardSchema.safeParse(card).success).toBe(true);
const typeless = { ...terminal, carrier: { ...terminal.carrier, type: '' } };
expect(roadtripCardSchema.safeParse({ ...drive, days: [{ ...day(1), stops: [typeless] }] }).success).toBe(false);
});
it('RTCARD-013: a corridor search, a charger, connections and a day route read, each within its bounds', () => {
const corridor = {
kind: 'corridor',
dayId: 3,
dayNumber: 2,
category: 'charging',
widthKm: 5,
hits: [
{
ref: 'call_1:0',
name: 'Ionity Holzkirchen',
brand: 'Ionity',
lat: 47.88,
lng: 11.7,
alongKm: 31.4,
offKm: 0.42,
between: ['Munich', 'Verona'],
sockets: [{ type: 'ccs', kw: 350, count: 6 }],
},
],
more: 0,
searched: { done: 6, total: 9 },
partial: true,
};
expect(corridorCardSchema.safeParse(corridor).success).toBe(true);
expect(corridorCardSchema.safeParse({ ...corridor, category: 'museum' }).success).toBe(false);
const charging = {
kind: 'charging',
placeId: 7,
name: 'Ionity Holzkirchen',
station: null,
lat: 47.88,
lng: 11.7,
status: 'ok',
stale: false,
available: 4,
total: 6,
checkedAt: '2026-10-01T09:38:00Z',
updatedAt: null,
energy: { amount: 0.59, currency: 'EUR' },
otherPrices: 1,
source: 'MobiData BW',
license: 'CC BY 4.0',
};
expect(chargingCardSchema.safeParse(charging).success).toBe(true);
expect(chargingCardSchema.safeParse({ ...charging, checkedAt: '2026-10-01 09:38' }).success).toBe(false);
const leg = {
mode: 'RAIL',
line: 'RE 4',
lineColor: '#ff0000',
lineTextColor: null,
from: { name: 'Munich Hbf', time: '08:04', track: '12' },
to: { name: 'Rosenheim', time: '08:41', track: null },
durationS: 2220,
stops: 3,
headsign: 'Salzburg',
agency: null,
};
const itinerary = {
date: '2026-10-01',
start: '08:04',
end: '08:41',
endDayOffset: 0,
durationS: 2220,
transfers: 0,
walkS: 0,
legs: [leg],
};
const transit = { kind: 'transit', from: 'Munich', to: 'Rosenheim', dayId: null, more: 0, dropped: 0 };
expect(transitCardSchema.safeParse({ ...transit, itineraries: [itinerary] }).success).toBe(true);
const shortColour = { ...itinerary, legs: [{ ...leg, lineColor: '#f00' }] };
expect(transitCardSchema.safeParse({ ...transit, itineraries: [shortColour] }).success).toBe(false);
const route = {
kind: 'dayRoute',
dayId: 3,
dayNumber: 2,
stops: [{ placeId: 7, name: 'Munich', lat: 48.1, lng: 11.6, added: false }],
vias: [{ lat: 47.5, lng: 11.2, after: 0, state: 'moved', from: [47.4, 11.1] }],
afterName: 'Munich',
track: null,
unresolved: [],
};
expect(dayRouteCardSchema.safeParse(route).success).toBe(true);
const lostVia = { ...route, vias: [{ ...route.vias[0], state: 'lost' }] };
expect(dayRouteCardSchema.safeParse(lostVia).success).toBe(false);
});
it('RTCARD-014: the road trip adds its verbs and its applied entity to the shared enums', () => {
for (const verb of ROADTRIP_VERB_KEYS) expect(ASSISTANT_CHANGE_VERB_KEYS).toContain(verb);
const applied = { toolCallId: 'call_1', entity: 'roadtrip', ids: [5], dayId: 3, undoUntil: null };
expect(assistantAppliedSchema.parse(applied).entity).toBe('roadtrip');
});
it('RTCARD-016: the rules a change sets read with their values as stored, and a key that is no setting does not', () => {
const rules = {
kind: 'roadtripRules',
settings: [
{ key: 'roadtrip_day_start', before: '08:00', after: '09:30' },
{ key: 'roadtrip_hotel_bookends', before: null, after: true },
{ key: 'roadtrip_leg_minutes', before: 120, after: 0 },
],
dayEnd: { dayId: 3, dayNumber: 2, mode: 'along', from: 'Garmisch', to: 'Innsbruck', percent: 40 },
};
expect(roadtripRulesCardSchema.safeParse(rules).success).toBe(true);
expect(trekCardSchema.safeParse({ ...rules, dayEnd: null }).success).toBe(true);
const foreign = { ...rules, settings: [{ key: 'endpoint_url', before: null, after: 'x' }] };
expect(roadtripRulesCardSchema.safeParse(foreign).success).toBe(false);
const auto = { ...rules, dayEnd: { ...rules.dayEnd, mode: 'never' } };
expect(roadtripRulesCardSchema.safeParse(auto).success).toBe(false);
});
it('RTCARD-015: the fullest drive the bounds allow is a card the server can still check under the size cap', () => {
// The bounds alone do not hold a drive under MAX_CARD_CHARS; the server's builder fits it.
const days = Array.from({ length: ROADTRIP_CARD_DAYS_MAX }, (_, index) => day(index + 1));
const full = { ...drive, days };
expect(roadtripCardSchema.safeParse(full).success).toBe(true);
expect(JSON.stringify(full).length).toBeLessThan(MAX_CARD_CHARS);
});
});
@@ -0,0 +1,48 @@
import { chargingCardSchema } from './charging.card';
import { corridorCardSchema } from './corridor.card';
import { dayRouteCardSchema } from './day-route.card';
import { roadtripRulesCardSchema } from './roadtrip-rules.card';
import { roadtripCardSchema } from './roadtrip.card';
import { transitCardSchema } from './transit.card';
export * from './charging.card';
export * from './corridor.card';
export * from './day-route.card';
export * from './roadtrip-rules.card';
export * from './roadtrip.card';
export * from './transit.card';
/**
* What the road trip brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const ROADTRIP_CARD_SCHEMAS = [
roadtripCardSchema,
corridorCardSchema,
chargingCardSchema,
transitCardSchema,
dayRouteCardSchema,
roadtripRulesCardSchema,
] as const;
/**
* A via point sent into a day's drive, a chain of them laid at once, one
* moved, one taken out, the vias of a day pinned again to its stops; the
* driving settings changed; where a day ends set; a Google Maps route taken
* in as stops; a transit connection added.
*/
export const ROADTRIP_VERB_KEYS = [
'addRouteVia',
'shapeRoute',
'moveRouteVia',
'removeRouteVia',
'repinRouteVias',
'updateDriveSettings',
'setDayBoundary',
'importRoute',
'addTransit',
] as const;
/** The road trip of a trip: its vias, its settings and its day endings, shown on the plan by their day. */
export const ROADTRIP_APPLIED_ENTITIES = ['roadtrip'] as const;
@@ -0,0 +1,36 @@
import { cardCurrencySchema, cardPersonSchema } from './card-parts';
import { z } from 'zod';
/**
* Settle up as the Costs page shows it: the payments that would square the
* trip (who pays whom), each traveller's balance (positive is owed money,
* negative owes it), how many payments were already recorded, and the
* entries no exchange rate converts yet, which count in no figure. Every
* amount is in `currency`.
*/
/** Suggested payments one card names; the rest are counted in `moreFlows`. */
export const SETTLEMENT_FLOWS_MAX = 12;
/** Balances one card names; the rest are counted in `moreBalances`. */
export const SETTLEMENT_BALANCES_MAX = 20;
export const settlementCardSchema = z.object({
kind: z.literal('settlement'),
currency: cardCurrencySchema,
flows: z
.array(z.object({ from: cardPersonSchema, to: cardPersonSchema, amount: z.number().positive().max(1e9) }))
.max(SETTLEMENT_FLOWS_MAX),
moreFlows: z.number().int().min(0).max(1000),
balances: z
.array(z.object({ person: cardPersonSchema, balance: z.number().min(-1e9).max(1e9) }))
.max(SETTLEMENT_BALANCES_MAX),
moreBalances: z.number().int().min(0).max(1000),
/** Payments already recorded. */
recorded: z.number().int().min(0).max(100_000),
unconverted: z.object({
entries: z.number().int().min(0).max(100_000),
currencies: z.array(cardCurrencySchema).max(6),
}),
});
export type SettlementCard = z.infer<typeof settlementCardSchema>;
@@ -0,0 +1,59 @@
import { idSchema } from '../../common/primitives.schema';
import { cardDateSchema, cardPersonSchema, cardText } from './card-parts';
import { checklistBeforeSchema, checklistColorSlotSchema } from './packing-list.card';
import { z } from 'zod';
/**
* The trip's to-dos in the assistant chat, grouped by their list (category)
* the way the to-do panel shows them. On a change card the rows carry what
* the change does to them and the old value of every field it touches; on an
* answer `change` is `none`.
*/
const todoCountSchema = z.number().int().min(0).max(5_000);
export const TODO_ROW_CHANGES = ['none', 'add', 'update', 'check', 'uncheck', 'remove'] as const;
/** `done` is kept by a tick only (`'1'` or `'0'`), for the way back; it is never drawn as a fact. */
export const TODO_FIELDS = ['name', 'note', 'category', 'dueDate', 'priority', 'assignee', 'done'] as const;
export const todoCardItemSchema = z.object({
/** Null while a create waits. */
id: idSchema.nullable(),
name: cardText(300),
/** The first line of the description. */
note: cardText(160).nullable(),
checked: z.boolean(),
dueDate: cardDateSchema.nullable(),
/** The trip day on the due date, so the date can show that day in the plan. */
dueDayId: idSchema.nullable(),
/** 0 for none, 1 the highest. */
priority: z.number().int().min(0).max(3),
assignee: cardPersonSchema.nullable(),
change: z.enum(TODO_ROW_CHANGES),
changed: z.array(z.object({ field: z.enum(TODO_FIELDS), before: checklistBeforeSchema })).max(7),
});
export type TodoCardItem = z.infer<typeof todoCardItemSchema>;
export const todoCardGroupSchema = z.object({
/** Null: the to-dos on no list. */
category: cardText(100).nullable(),
slot: checklistColorSlotSchema.nullable(),
/** Who a list's new to-dos go to by default. */
assignees: z.array(cardPersonSchema).max(6),
assigneesRemoved: z.array(cardPersonSchema).max(6),
items: z.array(todoCardItemSchema).max(40),
/** The group's to-dos, shown or not. */
count: todoCountSchema,
open: todoCountSchema,
});
export type TodoCardGroup = z.infer<typeof todoCardGroupSchema>;
export const todoListCardSchema = z.object({
kind: z.literal('todoList'),
/** Overdue against the day of the read; answers only. */
progress: z.object({ open: todoCountSchema, done: todoCountSchema, overdue: todoCountSchema }).nullable(),
groups: z.array(todoCardGroupSchema).max(12),
moreGroups: todoCountSchema,
});
export type TodoListCard = z.infer<typeof todoListCardSchema>;
@@ -0,0 +1,37 @@
import { idSchema } from '../../common/primitives.schema';
import { tourMaxHikingDifficultySchema, tourTypeKeySchema } from '../../tours/tours.schema';
import { cardText } from './card-parts';
import { z } from 'zod';
/**
* The saved tours of a trip, or of one of its days, as rows like the Tours
* sidebar shows them: the activity, the name, time, distance and climb, the
* stages of a tour over several days, and the days it is on.
*/
/** The most rows one card lists; `more` counts the rest. */
export const TOUR_LIST_ROWS = 12;
export const tourListRowSchema = z.object({
placeId: idSchema,
name: cardText(120),
activity: tourTypeKeySchema,
limit: tourMaxHikingDifficultySchema.nullable(),
distanceM: z.number().int().min(0).max(5_000_000).nullable(),
ascentM: z.number().int().min(0).max(100_000).nullable(),
minutes: z.number().int().min(0).max(86_400).nullable(),
stages: z.number().int().min(2).max(60).nullable(),
/** The numbers of the trip days it is on, in day order. */
days: z.array(z.number().int().min(1).max(999)).max(10),
});
export type TourListRow = z.infer<typeof tourListRowSchema>;
export const tourListCardSchema = z.object({
kind: z.literal('tourList'),
/** The day the list was asked for; null for the whole trip. */
dayId: idSchema.nullable(),
more: z.number().int().min(0).max(10_000),
rows: z.array(tourListRowSchema).min(1).max(TOUR_LIST_ROWS),
});
export type TourListCard = z.infer<typeof tourListCardSchema>;

Some files were not shown because too many files have changed in this diff Show More