ezship 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/commands.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  //
6
6
  // A Builder works on a *working copy* -- a directory for the CLI, IndexedDB for the browser. `pull` mirrors the
7
7
  // Site's shared files into it, `push` publishes it, `deploy` ships the shared files. ls/cat/put/edit/delete/mv act
8
- // on the working copy only. See CONTEXT.md and docs/adr/0004.
8
+ // on the working copy only. See CONTEXT.md and docs/adr/0204.
9
9
 
10
10
  import { extractTarget, usesWorkingCopy } from "./connections.mjs";
11
11
  import { parseCron } from "./cron.mjs";
@@ -22,10 +22,29 @@ import {
22
22
  } from "./schema.mjs";
23
23
  import { parseSessionDeclaration, SESSION_FILE } from "./session.mjs";
24
24
  import { ACCESS_FILE, checkAccess, parseGate } from "./access.mjs";
25
- import { readWorkflow, workflowShapes } from "./workflow.mjs";
25
+ import { checkWorkflowNames, readWorkflow, workflowShapes } from "./workflow.mjs";
26
+
27
+ import { ASSET_TYPES, ATTACHMENT_TYPES } from "./paths.mjs";
26
28
 
27
29
  export { MAX_MESSAGE_CHARS, messageText } from "./schema.mjs";
28
30
 
31
+ // The page's side of the wire lives in paths.mjs, the one module the Framework bundles (docs/adr/0216).
32
+ export {
33
+ ACCESS_RULES_PATH,
34
+ ASSET_PATH,
35
+ ASSET_TYPES,
36
+ ATTACHMENT_PATH,
37
+ ATTACHMENT_TYPES,
38
+ attachmentContentType,
39
+ DOCUMENT_BASE_PATH,
40
+ FIRST_SCREEN_EVENT,
41
+ FUNCTION_BASE_PATH,
42
+ LIVE_STREAM_PATH,
43
+ LIVE_VERSIONS_PATH,
44
+ SCOPE_PATH,
45
+ VERSIONS_HEADER,
46
+ } from "./paths.mjs";
47
+
29
48
  export {
30
49
  parseSessionDeclaration,
31
50
  sessionValueError,
@@ -54,7 +73,7 @@ export {
54
73
 
55
74
  /** @typedef {import("./commands.d.mts").Workspace} Workspace */
56
75
 
57
- // ---- what a Site is (docs/adr/0012) -------------------------------------------------------------------
76
+ // ---- what a Site is (docs/adr/0209) -------------------------------------------------------------------
58
77
  // Also re-exported by the platform's src/shared.ts.
59
78
 
60
79
  /**
@@ -68,7 +87,7 @@ export const MAIN_FILE = "App.tsx";
68
87
  */
69
88
  export const CONTEXT_FILE = "CONTEXT.md";
70
89
  /**
71
- * docs/<name>.md in a Site or the Global Workspace (ADR 0144): plain Markdown for Builders, pushed and
90
+ * docs/<name>.md in a Site or the Global Workspace (ADR 0209): plain Markdown for Builders, pushed and
72
91
  * versioned like code, never built or served. CONTEXT.md's inventory lists each one.
73
92
  * @type {typeof import("./commands.d.mts").DOCS_DIR}
74
93
  */
@@ -78,7 +97,7 @@ export function docName(path) {
78
97
  const match = /^docs\/([a-z0-9][a-z0-9-]{0,63})\.md$/.exec(path);
79
98
  return match ? match[1] : null;
80
99
  }
81
- /** Why a docs/ path is malformed (ADR 0144); `shape` ends the message. */
100
+ /** Why a docs/ path is malformed (ADR 0209); `shape` ends the message. */
82
101
  const docPathError = (/** @type {string} */ path, /** @type {string} */ shape) =>
83
102
  path.slice(DOCS_DIR.length).includes("/")
84
103
  ? `${path}: docs/ has no subfolders. ${shape}`
@@ -91,7 +110,7 @@ export const PAGES_DIR = "pages/";
91
110
  /** @type {typeof import("./commands.d.mts").COMPONENTS_DIR} */
92
111
  export const COMPONENTS_DIR = "components/";
93
112
  /**
94
- * hooks/use<Name>.ts (ADR 0091): one custom hook per file, default-exported under the file's name, in a Site or
113
+ * hooks/use<Name>.ts (ADR 0209): one custom hook per file, default-exported under the file's name, in a Site or
95
114
  * the Global Workspace (imported as `global/hooks/use<Name>`). Browser code with a component's imports and Rules.
96
115
  * @type {typeof import("./commands.d.mts").HOOKS_DIR}
97
116
  */
@@ -106,65 +125,33 @@ export const FUNCTIONS_DIR = "functions/";
106
125
  /** @type {typeof import("./commands.d.mts").FUNCTION_ARTIFACT} */
107
126
  export const FUNCTION_ARTIFACT = "_server/functions.json";
108
127
  /**
109
- * The Instance's Table rules (docs/adr/0099), compiled at Global Push: private like FUNCTION_ARTIFACT, and
128
+ * The Instance's Table rules (docs/adr/0226), compiled at Global Push: private like FUNCTION_ARTIFACT, and
110
129
  * never part of a Site's build.
111
130
  * @type {typeof import("./commands.d.mts").RULES_ARTIFACT}
112
131
  */
113
132
  export const RULES_ARTIFACT = "_server/rules.json";
114
133
  /**
115
- * The Instance's scheduled jobs (ADR 0136), compiled at Global Push beside the rules: private, and never part
134
+ * The Instance's scheduled jobs (ADR 0230), compiled at Global Push beside the rules: private, and never part
116
135
  * of a Site's build.
117
136
  * @type {typeof import("./commands.d.mts").JOBS_ARTIFACT}
118
137
  */
119
138
  export const JOBS_ARTIFACT = "_server/jobs.json";
120
- /** @type {typeof import("./commands.d.mts").FUNCTION_BASE_PATH} */
121
- export const FUNCTION_BASE_PATH = "/_ez/functions";
122
139
  /** @type {typeof import("./commands.d.mts").DOCUMENTS_DIR} */
123
140
  export const DOCUMENTS_DIR = "documents/";
124
141
  /** @type {typeof import("./commands.d.mts").DOCUMENT_ARTIFACT} */
125
142
  export const DOCUMENT_ARTIFACT = "_server/documents.json";
126
- /** @type {typeof import("./commands.d.mts").DOCUMENT_BASE_PATH} */
127
- export const DOCUMENT_BASE_PATH = "/_ez/documents";
128
143
  /** @type {typeof import("./commands.d.mts").DOCUMENT_RE} */
129
144
  export const DOCUMENT_RE = /^documents\/([A-Z][A-Za-z0-9]*)\.tsx$/;
130
145
  /** @type {typeof import("./commands.d.mts").MAX_RENDER_INPUT_BYTES} */
131
146
  export const MAX_RENDER_INPUT_BYTES = 1_000_000;
132
147
  /**
133
- * The Document a Global `documents/<Name>.tsx` file holds, or null for any other path (docs/adr/0105).
148
+ * The Document a Global `documents/<Name>.tsx` file holds, or null for any other path (docs/adr/0233).
134
149
  * @type {typeof import("./commands.d.mts").documentName}
135
150
  */
136
151
  export function documentName(path) {
137
152
  const m = DOCUMENT_RE.exec(path);
138
153
  return m ? m[1] : null;
139
154
  }
140
- /**
141
- * A page's live Table versions (docs/adr/0053): `GET <prefix>/_ez/db/stream` answers `text/event-stream`, each
142
- * `versions` event the complete map the viewer may read; `GET <prefix>/_ez/db/versions` is the same map once.
143
- * @type {typeof import("./commands.d.mts").LIVE_STREAM_PATH}
144
- */
145
- export const LIVE_STREAM_PATH = "/_ez/db/stream";
146
- /** @type {typeof import("./commands.d.mts").LIVE_VERSIONS_PATH} */
147
- export const LIVE_VERSIONS_PATH = "/_ez/db/versions";
148
- /**
149
- * The rules of the Tables this artifact declares (docs/adr/0098): `GET <prefix>/_ez/access` answers
150
- * `{ rules: { [table]: { read, write } }, workflows: { [table]: WorkflowMeta } }`, what `useCan` evaluates
151
- * and `useWorkflow` shows (docs/adr/0103). The Host's answer to a write is the authority; these only let a
152
- * page hide what it would refuse.
153
- * @type {typeof import("./commands.d.mts").ACCESS_RULES_PATH}
154
- */
155
- export const ACCESS_RULES_PATH = "/_ez/access";
156
- /**
157
- * The active scope for the Framework's switcher (docs/adr/0098): `GET <prefix>/_ez/scope` answers
158
- * `{ scope: { column, key, values: [{ value, label }], active } | null }`.
159
- * @type {typeof import("./commands.d.mts").SCOPE_PATH}
160
- */
161
- export const SCOPE_PATH = "/_ez/scope";
162
- /**
163
- * The response header on a page's writes and function calls: the viewer's version map read after the commit,
164
- * as JSON, so the page can wait until its live queries show the write.
165
- * @type {typeof import("./commands.d.mts").VERSIONS_HEADER}
166
- */
167
- export const VERSIONS_HEADER = "ez-versions";
168
155
  /** @type {typeof import("./commands.d.mts").FUNCTION_NAME_RE} */
169
156
  export const FUNCTION_NAME_RE = /^[a-z][A-Za-z0-9]{0,63}$/;
170
157
  /** @type {typeof import("./commands.d.mts").functionName} */
@@ -173,7 +160,7 @@ export function functionName(path) {
173
160
  return match ? match[1] : null;
174
161
  }
175
162
  /**
176
- * local/<name>.ts: a Site's local functions, Node code the Desktop runs on the Member's computer (ADR 0048).
163
+ * local/<name>.ts: a Site's local functions, Node code the Desktop runs on the Member's computer (ADR 0235).
177
164
  * @type {typeof import("./commands.d.mts").LOCAL_DIR}
178
165
  */
179
166
  export const LOCAL_DIR = "local/";
@@ -187,7 +174,7 @@ export function localFunctionName(path) {
187
174
  return match ? match[1] : null;
188
175
  }
189
176
  /**
190
- * jobs/<name>.ts in the Global Workspace: the Instance's scheduled jobs (ADRs 0076, 0136), server code no browser
177
+ * jobs/<name>.ts in the Global Workspace: the Instance's scheduled jobs (ADR 0230), server code no browser
191
178
  * can call; schedules.json runs them.
192
179
  * @type {typeof import("./commands.d.mts").JOBS_DIR}
193
180
  */
@@ -198,7 +185,7 @@ export function jobName(path) {
198
185
  return match ? match[1] : null;
199
186
  }
200
187
  /**
201
- * listeners/<name>.ts: a Site's Listeners (ADR 0092), server code run once for each event that reaches it;
188
+ * listeners/<name>.ts: a Site's Listeners (ADR 0231), server code run once for each event that reaches it;
202
189
  * listeners.json names them and how their events arrive.
203
190
  * @type {typeof import("./commands.d.mts").LISTENERS_DIR}
204
191
  */
@@ -215,7 +202,7 @@ export const LISTENER_MAX = 20;
215
202
  /** Where a deployed Listener receives on the app origin: `<prefix>/_ez/listeners/<name>`. */
216
203
  /** @type {typeof import("./commands.d.mts").LISTENER_BASE_PATH} */
217
204
  export const LISTENER_BASE_PATH = "/_ez/listeners/";
218
- /** How a sending service proves a delivery (ADR 0092); data, grown by platform release. */
205
+ /** How a sending service proves a delivery (ADR 0231); data, grown by platform release. */
219
206
  /** @type {typeof import("./commands.d.mts").WEBHOOK_SCHEMES} */
220
207
  export const WEBHOOK_SCHEMES = Object.freeze(
221
208
  /** @type {const} */ (["standard", "stripe", "github", "token"]),
@@ -227,7 +214,7 @@ export const LISTENER_OVERLAP_HOURS = Object.freeze({ default: 24, max: 168 });
227
214
  /** @type {typeof import("./commands.d.mts").LISTENER_BODY_MAX} */
228
215
  export const LISTENER_BODY_MAX = 256_000;
229
216
  /**
230
- * The Data API (docs/adr/0119, docs/adr/0151): other systems reach an Instance's data under `/_ez/api/` on its
217
+ * The Data API (docs/adr/0232): other systems reach an Instance's data under `/_ez/api/` on its
231
218
  * app origin with an API Key, `Authorization: Bearer ezk_...`.
232
219
  * @type {typeof import("./commands.d.mts").API_BASE_PATH}
233
220
  */
@@ -343,7 +330,7 @@ export function parseListeners(source, files) {
343
330
  }
344
331
 
345
332
  /**
346
- * The optional Global file that schedules jobs on a UTC cron (ADRs 0076, 0136); a Global Push activates it.
333
+ * The optional Global file that schedules jobs on a UTC cron (ADR 0230); a Global Push activates it.
347
334
  * @type {typeof import("./commands.d.mts").SCHEDULES_FILE}
348
335
  */
349
336
  export const SCHEDULES_FILE = "schedules.json";
@@ -428,7 +415,7 @@ export function parseSchedules(source, files) {
428
415
  }
429
416
 
430
417
  /**
431
- * The optional page.json of a Site and of the Global Workspace (ADR 0148): the deployed page's settings. The
418
+ * The optional page.json of a Site and of the Global Workspace (ADR 0209): the deployed page's settings. The
432
419
  * Global one sets every Site's, a Site's own overrides it key by key, and the Pipeline writes the result
433
420
  * into the page's head.
434
421
  * @type {typeof import("./commands.d.mts").PAGE_FILE}
@@ -503,8 +490,9 @@ export function pageIcon(files, global) {
503
490
  }
504
491
 
505
492
  /**
506
- * lib/<name>.ts in the Global Workspace (ADR 0077): pure TypeScript every Site's pages, components and server
493
+ * lib/<name>.ts in the Global Workspace (ADR 0210): pure TypeScript every Site's pages, components and server
507
494
  * functions import as `global/lib/<name>`. Named exports; whatever reads or writes takes the database as an argument.
495
+ * A Site has the same folder for helpers only it uses (ADR 0209), imported by path (`./lib/<name>`).
508
496
  * @type {typeof import("./commands.d.mts").LIB_DIR}
509
497
  */
510
498
  export const LIB_DIR = "lib/";
@@ -514,7 +502,7 @@ export function libModuleName(path) {
514
502
  return match ? match[1] : null;
515
503
  }
516
504
  /**
517
- * Table rules (docs/adr/0099): `rules/<table>.ts` in the Global Workspace, named after a published Table.
505
+ * Table rules (docs/adr/0226): `rules/<table>.ts` in the Global Workspace, named after a published Table.
518
506
  * @type {typeof import("./commands.d.mts").RULES_DIR}
519
507
  */
520
508
  export const RULES_DIR = "rules/";
@@ -524,7 +512,7 @@ export function ruleTableName(path) {
524
512
  return match ? match[1] : null;
525
513
  }
526
514
  /**
527
- * Workflows (docs/adr/0103): `workflows/<table>.ts` in the Global Workspace, named after a published Table.
515
+ * Workflows (docs/adr/0227): `workflows/<table>.ts` in the Global Workspace, named after a published Table.
528
516
  * @type {typeof import("./commands.d.mts").WORKFLOWS_DIR}
529
517
  */
530
518
  export const WORKFLOWS_DIR = "workflows/";
@@ -534,13 +522,13 @@ export function workflowTableName(path) {
534
522
  return match ? match[1] : null;
535
523
  }
536
524
  /**
537
- * Live server code of the Global Workspace (docs/adr/0099, 0103): a rules or a workflow file, compiled at
525
+ * Live server code of the Global Workspace (docs/adr/0226, 0227): a rules or a workflow file, compiled at
538
526
  * Push into the Instance's rules artifact. Both import what server code may.
539
527
  * @param {string} path
540
528
  */
541
529
  const liveCodeTable = (path) => ruleTableName(path) ?? workflowTableName(path);
542
530
  /**
543
- * Desktop release files (ADR 0048): where every Instance app origin serves the installer and its update feed,
531
+ * Desktop release files (ADR 0235): where every Instance app origin serves the installer and its update feed,
544
532
  * what a release file may be called, and how large one may be.
545
533
  * @type {typeof import("./commands.d.mts").DESKTOP_PATH}
546
534
  */
@@ -550,7 +538,7 @@ export const DESKTOP_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
550
538
  /** @type {typeof import("./commands.d.mts").MAX_DESKTOP_FILE_BYTES} */
551
539
  export const MAX_DESKTOP_FILE_BYTES = 100_000_000;
552
540
  /**
553
- * The packages Site UI and Global components and hooks may import by name (docs/adr/0114): declarative React,
541
+ * The packages Site UI and Global components and hooks may import by name (docs/adr/0209): declarative React,
554
542
  * pinned by the Pipeline, added only by a platform release.
555
543
  * @type {typeof import("./commands.d.mts").SITE_PACKAGES}
556
544
  */
@@ -611,11 +599,17 @@ export const TYPES_FILE = "db/types.d.ts";
611
599
  export const BUILD_ENTRY = "index.html";
612
600
  /** @type {typeof import("./commands.d.mts").BUILD_CONFIG_MARKER} */
613
601
  export const BUILD_CONFIG_MARKER = "<!--ez:config-->";
602
+ /**
603
+ * The attribute on the page's `modulepreload` link for the vendor chunk (docs/adr/0216): how the app host
604
+ * finds the chunk of React and the Framework, which it may serve once for all of an Instance's Sites.
605
+ * @type {typeof import("./commands.d.mts").BUILD_VENDOR_ATTR}
606
+ */
607
+ export const BUILD_VENDOR_ATTR = "data-ez-vendor";
614
608
 
615
609
  /**
616
610
  * The compiler options every type check of Site code uses: the Pipeline's and the editor's tsconfig.json both
617
- * spread these, so local \`tsc\` and \`ez check\` agree (docs/adr/0078). \`noUncheckedIndexedAccess\` is
618
- * left off (docs/adr/0086).
611
+ * spread these, so local \`tsc\` and \`ez check\` agree (docs/adr/0236). \`noUncheckedIndexedAccess\` is
612
+ * left off (docs/adr/0236).
619
613
  * @type {typeof import("./commands.d.mts").COMPILER_OPTIONS}
620
614
  */
621
615
  export const COMPILER_OPTIONS = Object.freeze({
@@ -654,48 +648,17 @@ export const GLOBAL_ID = "global";
654
648
  */
655
649
  export const SHELL_FILE = "Shell.tsx";
656
650
 
657
- // ---- Instance assets (docs/adr/0014): a name, an immutable object, a frozen URL; Site code says asset("logo").
651
+ // ---- Instance assets (docs/adr/0213): a name, an immutable object, a frozen URL; Site code says asset("logo").
658
652
 
659
653
  /**
660
654
  * An asset's name: the API Site code uses (`asset("logo")`), unique within the Instance, never renamed.
661
655
  * @type {typeof import("./commands.d.mts").ASSET_NAME_RE}
662
656
  */
663
657
  export const ASSET_NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
664
- /**
665
- * Allowed asset types by extension. Limits are data: loosened by platform release, never per Instance.
666
- * @type {typeof import("./commands.d.mts").ASSET_TYPES}
667
- */
668
- export const ASSET_TYPES = Object.freeze({
669
- png: "image/png",
670
- jpg: "image/jpeg",
671
- jpeg: "image/jpeg",
672
- gif: "image/gif",
673
- webp: "image/webp",
674
- avif: "image/avif",
675
- svg: "image/svg+xml",
676
- mp4: "video/mp4",
677
- webm: "video/webm",
678
- mp3: "audio/mpeg",
679
- m4a: "audio/mp4",
680
- wav: "audio/wav",
681
- pdf: "application/pdf",
682
- txt: "text/plain",
683
- csv: "text/csv",
684
- json: "application/json",
685
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
686
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
687
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
688
- zip: "application/zip",
689
- });
690
658
  /** @type {typeof import("./commands.d.mts").MAX_ASSET_BYTES} */
691
659
  export const MAX_ASSET_BYTES = 100_000_000;
692
660
  /** @type {typeof import("./commands.d.mts").MAX_INSTANCE_ASSET_BYTES} */
693
661
  export const MAX_INSTANCE_ASSET_BYTES = 2_000_000_000;
694
- /**
695
- * Where a Site's app serves the Instance's assets: `<prefix>/_ez/files/<name>`.
696
- * @type {typeof import("./commands.d.mts").ASSET_PATH}
697
- */
698
- export const ASSET_PATH = "/_ez/files";
699
662
 
700
663
  /**
701
664
  * The content type an asset file gets from its extension, or null when the type is not allowed.
@@ -706,12 +669,7 @@ export function assetContentType(filename) {
706
669
  return m ? (ASSET_TYPES[m[1].toLowerCase()] ?? null) : null;
707
670
  }
708
671
 
709
- // ---- App Attachments (docs/adr/0047): a file on one FILE column of one row; pages upload with db.upload.
710
- /**
711
- * Allowed attachment types by extension: the asset table. Limits are data, loosened by release.
712
- * @type {typeof import("./commands.d.mts").ATTACHMENT_TYPES}
713
- */
714
- export const ATTACHMENT_TYPES = Object.freeze({ ...ASSET_TYPES });
672
+ // ---- App Attachments (docs/adr/0221): a file on one FILE column of one row; pages upload with db.upload.
715
673
  /** @type {typeof import("./commands.d.mts").MAX_ATTACHMENT_BYTES} */
716
674
  export const MAX_ATTACHMENT_BYTES = 25_000_000;
717
675
  /** The Instance's attachment pool, separate from its assets. @type {typeof import("./commands.d.mts").MAX_INSTANCE_ATTACHMENT_BYTES} */
@@ -722,20 +680,6 @@ export const MAX_UNBOUND_ATTACHMENTS = 20;
722
680
  export const MAX_UNBOUND_ATTACHMENT_BYTES = 250_000_000;
723
681
  /** An upload no row has bound within this time is swept. @type {typeof import("./commands.d.mts").UNBOUND_ATTACHMENT_TTL_MS} */
724
682
  export const UNBOUND_ATTACHMENT_TTL_MS = 86_400_000;
725
- /**
726
- * Where a Site's app takes and serves attachments: `POST <prefix>/_ez/attachments/<table>/<column>?name=<file>`
727
- * and `GET <prefix>/_ez/attachments/<id>`.
728
- * @type {typeof import("./commands.d.mts").ATTACHMENT_PATH}
729
- */
730
- export const ATTACHMENT_PATH = "/_ez/attachments";
731
- /**
732
- * The content type an attachment gets from its filename's extension, or null when the type is not allowed.
733
- * @type {typeof import("./commands.d.mts").attachmentContentType}
734
- */
735
- export function attachmentContentType(filename) {
736
- const m = /\.([A-Za-z0-9]+)$/.exec(filename);
737
- return m ? (ATTACHMENT_TYPES[m[1].toLowerCase()] ?? null) : null;
738
- }
739
683
  /**
740
684
  * pages/index.tsx, or lowercase segments joined by dots, `$name` for a parameter: pages/orders.$id.tsx.
741
685
  * @type {typeof import("./commands.d.mts").PAGE_RE}
@@ -759,7 +703,7 @@ export function isValidFilePath(path) {
759
703
  const INVALID_PATH = (p) =>
760
704
  `Invalid path: ${p}. Use relative paths like components/Hello.tsx (no leading slash, no ..).`;
761
705
 
762
- const SITE_SHAPE = `A Site is ${MAIN_FILE}, required ${CONTEXT_FILE}, ${PAGES_DIR}<route>.tsx, ${COMPONENTS_DIR}<Name>.tsx, ${HOOKS_DIR}use<Name>.ts, ${FUNCTIONS_DIR}<name>.ts, ${LOCAL_DIR}<name>.ts, ${LISTENERS_DIR}<name>.ts, ${CONSTANTS_FILE}, ${DOCS_DIR}<name>.md (Markdown docs), optional ${LISTENERS_FILE}, optional ${PAGE_FILE} (the browser icon) and optional ${STYLE_FILE}. Schema, generated types and scheduled jobs belong to the Global Workspace.`;
706
+ const SITE_SHAPE = `A Site is ${MAIN_FILE}, required ${CONTEXT_FILE}, ${PAGES_DIR}<route>.tsx, ${COMPONENTS_DIR}<Name>.tsx, ${HOOKS_DIR}use<Name>.ts, ${LIB_DIR}<name>.ts (helpers), ${FUNCTIONS_DIR}<name>.ts, ${LOCAL_DIR}<name>.ts, ${LISTENERS_DIR}<name>.ts, ${CONSTANTS_FILE}, ${DOCS_DIR}<name>.md (Markdown docs), optional ${LISTENERS_FILE}, optional ${PAGE_FILE} (the browser icon) and optional ${STYLE_FILE}. Schema, generated types and scheduled jobs belong to the Global Workspace.`;
763
707
 
764
708
  /**
765
709
  * Why required context is invalid, or null. Content quality is guided by the instructions, not parsed.
@@ -771,7 +715,7 @@ export function contextError(content) {
771
715
  : `${CONTEXT_FILE} is required and must contain text. Create or populate it with this Site's or Instance's purpose, workflows and constraints using ez put ${CONTEXT_FILE} (ez global put ${CONTEXT_FILE} for Global).`;
772
716
  }
773
717
 
774
- // ---- the generated file inventory in CONTEXT.md (docs/adr/0108) ------------------------------------------
718
+ // ---- the generated file inventory in CONTEXT.md (docs/adr/0215) ------------------------------------------
775
719
 
776
720
  /** @type {typeof import("./commands.d.mts").INVENTORY_START} */
777
721
  export const INVENTORY_START =
@@ -797,7 +741,7 @@ function docSummary(source) {
797
741
  return sentence.length > SUMMARY_MAX ? `${sentence.slice(0, SUMMARY_MAX - 1)}…` : sentence;
798
742
  }
799
743
 
800
- /** A doc's first Markdown heading (ADR 0144), or null when it has none. @param {string} source */
744
+ /** A doc's first Markdown heading (ADR 0209), or null when it has none. @param {string} source */
801
745
  function headingSummary(source) {
802
746
  const heading = /^#{1,6}[ \t]+(.+?)[ \t#]*$/m.exec(source)?.[1]?.trim();
803
747
  if (!heading) return null;
@@ -806,7 +750,7 @@ function headingSummary(source) {
806
750
 
807
751
  /**
808
752
  * The inventory block for a Working Copy: one line per .ts/.tsx file but generated ones, with the first
809
- * sentence of its first doc comment, and one per docs/<name>.md with its first heading (ADR 0144), sorted by
753
+ * sentence of its first doc comment, and one per docs/<name>.md with its first heading (ADR 0209), sorted by
810
754
  * path, between INVENTORY_START and INVENTORY_END.
811
755
  * @type {typeof import("./commands.d.mts").contextInventory}
812
756
  */
@@ -862,7 +806,7 @@ export function pageRoute(path) {
862
806
  );
863
807
  }
864
808
 
865
- /** Why a hooks/ path is malformed (ADR 0091); `shape` ends the message. */
809
+ /** Why a hooks/ path is malformed (ADR 0209); `shape` ends the message. */
866
810
  const hookPathError = (/** @type {string} */ path, /** @type {string} */ shape) => {
867
811
  const rest = path.slice(HOOKS_DIR.length);
868
812
  if (rest.includes("/")) return `${path}: hooks/ has no subfolders. ${shape}`;
@@ -879,9 +823,6 @@ export function siteFileError(path) {
879
823
  if (!isValidFilePath(path)) return INVALID_PATH(path);
880
824
  if (functionName(path) || localFunctionName(path) || listenerName(path)) return null;
881
825
  if (path === LISTENERS_FILE || path === PAGE_FILE) return null;
882
- // ADR 0136: schedules belong to the Instance.
883
- if (path === SCHEDULES_FILE || path.startsWith(JOBS_DIR))
884
- return `${path}: scheduled jobs belong to the Global Workspace now: global/${SCHEDULES_FILE} and global/${JOBS_DIR}<name>.ts (ez global put). Move what a job shares with this Site to global/lib/<name>.ts and global/constants.ts, then delete the Site's copy.`;
885
826
  if (path.startsWith(LISTENERS_DIR)) {
886
827
  if (path.slice(LISTENERS_DIR.length).includes("/"))
887
828
  return `${path}: listeners/ has no subfolders. ${SITE_SHAPE}`;
@@ -894,8 +835,6 @@ export function siteFileError(path) {
894
835
  }
895
836
  if (path === MAIN_FILE || path === CONTEXT_FILE || path === CONSTANTS_FILE || path === STYLE_FILE)
896
837
  return null;
897
- if (path === SCHEMA_FILE || path === TYPES_FILE)
898
- return `${path} now belongs to the Global Workspace. Move the schema to global/db/schema.sql, remove NOT NULL, push global, and delete the Site copies. Import types from "global/db/types".`;
899
838
  if (path.startsWith(PAGES_DIR)) {
900
839
  if (pageRoute(path) !== null) return null;
901
840
  if (path.slice(PAGES_DIR.length).includes("/"))
@@ -911,6 +850,12 @@ export function siteFileError(path) {
911
850
  return `${path}: <Name> is PascalCase (components/OrderRow.tsx). ${SITE_SHAPE}`;
912
851
  }
913
852
  if (path.startsWith(HOOKS_DIR)) return hookName(path) ? null : hookPathError(path, SITE_SHAPE);
853
+ if (path.startsWith(LIB_DIR)) {
854
+ if (libModuleName(path)) return null;
855
+ if (path.slice(LIB_DIR.length).includes("/"))
856
+ return `${path}: lib/ has no subfolders. ${SITE_SHAPE}`;
857
+ return `${path}: a lib module is lib/<name>.ts, a lowercase-first name (lib/pricing.ts). ${SITE_SHAPE}`;
858
+ }
914
859
  if (path.startsWith(DOCS_DIR)) return docName(path) ? null : docPathError(path, SITE_SHAPE);
915
860
  return `${path} is not a Site file. ${SITE_SHAPE}`;
916
861
  }
@@ -1012,7 +957,6 @@ export default function App() {
1012
957
  <>
1013
958
  <Nav>
1014
959
  <Link to="/">Home</Link>
1015
- <Link to="/about">About</Link>
1016
960
  </Nav>
1017
961
  <Outlet />
1018
962
  </>
@@ -1033,13 +977,6 @@ export default function Home() {
1033
977
  </>
1034
978
  );
1035
979
  }
1036
- `,
1037
- "pages/about.tsx": `import { APP } from "../constants";
1038
-
1039
- /** What this app is. */
1040
- export default function About() {
1041
- return <p>About {APP.name}.</p>;
1042
- }
1043
980
  `,
1044
981
  "components/Hello.tsx": `/** A greeting with the app's name. */
1045
982
  export default function Hello({ name }: { name: string }) {
@@ -1049,7 +986,9 @@ export default function Hello({ name }: { name: string }) {
1049
986
  [CONSTANTS_FILE]: `/** The app's name and other plain values its pages share. */
1050
987
  export const APP = { name: "My app" } as const;
1051
988
  `,
1052
- [STYLE_FILE]: `body { font-family: system-ui, sans-serif; margin: 2rem; }
989
+ [STYLE_FILE]: `/* This Site's own classes, loaded after the Theme (global/style.css). The Theme owns the look: take every
990
+ colour, radius and shadow from its tokens (background: var(--surface); border: 1px solid var(--line)), and
991
+ change the look itself there, for every Site at once. */
1053
992
  `,
1054
993
  });
1055
994
 
@@ -1080,9 +1019,10 @@ Generated db/types.d.ts is the reference for row types; do not copy it here.
1080
1019
  ## Shared UI
1081
1020
  Map components, constants, Shell.tsx and the theme to their responsibilities and usage.
1082
1021
  The Instance started with a theme (style.css: tokens in :root, then the classes), a Shell (the top bar;
1083
- BRAND in constants.ts) and the components Button, PageHeader, Panel, Stat, Badge, StateBadge, Notice,
1084
- Dialog, ConfirmDialog, Tabs, FilterChips, SearchBox, DataTable, Pager, DetailList, Field, Empty, Money,
1085
- When and Yes; edit, replace or delete them, and record here what you decide about them.
1022
+ BRAND in constants.ts) and the components Button, PageHeader, Panel, Stat, Stats, Badge, StateBadge, Notice,
1023
+ Dialog, ConfirmDialog, Tabs, Toolbar, FilterChips, SearchBox, DataTable, Pager, DetailList, Board, BoardColumn,
1024
+ Card, Form, Field, TextInput, NumberInput, SelectInput, DateInput, TextArea, Checkbox, Empty, Money, When and
1025
+ Yes; edit, replace or delete them, and record here what you decide about them.
1086
1026
 
1087
1027
  ## Decisions and constraints
1088
1028
  Record shared decisions, their reasons, known limitations and open questions.
@@ -1094,7 +1034,7 @@ Record shared decisions, their reasons, known limitations and open questions.
1094
1034
 
1095
1035
  /**
1096
1036
  * What a new Instance's Global Workspace starts with, on top of DEFAULT_GLOBAL_FILES: a theme, a Shell with a
1097
- * nav slot and the menu, and the components every suite so far has rebuilt (docs/adr/0108, 0147). Written once at
1037
+ * nav slot and the menu, and the components every suite so far has rebuilt (docs/adr/0215). Written once at
1098
1038
  * Instance creation as Version 0; a customer edits, replaces or deletes them like any global file. Not a
1099
1039
  * Framework Kit (`planning/react-sites/issues/01`): nothing here is imported unless a Site imports it.
1100
1040
  * @type {typeof import("./commands.d.mts").STARTER_GLOBAL_FILES}
@@ -1134,8 +1074,6 @@ export const STARTER_GLOBAL_FILES = Object.freeze({
1134
1074
  --control: 2.25rem;
1135
1075
  --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
1136
1076
  --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1137
- /* Kept for Site styles written against the first starter theme. */
1138
- --accent: var(--primary-soft);
1139
1077
  }
1140
1078
  /* Fingers need bigger targets than a mouse: every control grows on a touch screen. */
1141
1079
  @media (pointer: coarse) {
@@ -1343,6 +1281,38 @@ table.data th.num .sort { flex-direction: row-reverse; }
1343
1281
  .stat.info .value { color: var(--info); }
1344
1282
  .stat.warn .value { color: var(--warn); }
1345
1283
  .stat.danger .value { color: var(--danger); }
1284
+ /* Stats: Stat tiles in one row, all one width, wrapping as the page narrows. */
1285
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
1286
+
1287
+ /* ---- Toolbar: the controls above a list, its aside at the far end ---- */
1288
+ .toolbar > .toolbar-aside { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-left: auto; }
1289
+ .panel > .toolbar,
1290
+ .panel > .panel-body > .toolbar:first-child { padding: 12px 16px; border-bottom: 1px solid var(--line); }
1291
+ .panel > .panel-body:not(.flush) > .toolbar:first-child { margin: -16px -16px 16px; }
1292
+
1293
+ /* ---- Board, BoardColumn, Card: columns of cards side by side ---- */
1294
+ .board { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; align-items: start; }
1295
+ .board-column { display: flex; flex-direction: column; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-lg); box-shadow: var(--shadow); min-width: 0; }
1296
+ .board-column > .board-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--line); }
1297
+ .board-column > .board-head .board-title { display: flex; align-items: center; gap: 8px; margin-right: auto; min-width: 0; }
1298
+ .board-column > .board-head h3 { font-size: 0.9375rem; }
1299
+ .board-column > .board-head .board-count { padding: 0 8px; border-radius: 999px; background: var(--surface-2); color: var(--muted); font-size: 0.8125rem; font-variant-numeric: tabular-nums; }
1300
+ .board-column > .board-hint { padding: 8px 14px 0; color: var(--muted); font-size: 0.8125rem; }
1301
+ .board-column > .board-cards { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; }
1302
+ .board-column .board-empty { color: var(--muted); font-size: 0.8125rem; text-align: center; padding: 12px 0; }
1303
+ .card { display: flex; flex-direction: column; gap: 4px; padding: 10px 12px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); color: var(--text); text-decoration: none; min-width: 0; }
1304
+ a.card:hover { background: var(--hover); border-color: var(--line-strong); }
1305
+ .card > .card-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 6px 8px; }
1306
+ .card > .card-head .card-title { font-weight: 600; overflow-wrap: anywhere; }
1307
+ .card > .card-meta { color: var(--muted); font-size: 0.8125rem; }
1308
+
1309
+ /* ---- Form: fields in one column or two, its buttons at the end ---- */
1310
+ .form { display: flex; flex-direction: column; gap: 16px; }
1311
+ .form > .form-fields { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px 16px; align-items: start; }
1312
+ @media (min-width: 640px) { .form > .form-fields.two { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
1313
+ .form > .form-fields.two > .field:has(textarea) { grid-column: 1 / -1; }
1314
+ .form > .form-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
1315
+ .field.check { flex-direction: row; align-items: center; gap: 8px; }
1346
1316
 
1347
1317
  /* ---- Notice ---- */
1348
1318
  .notice { display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border-radius: var(--radius); border: 1px solid transparent; background: var(--info-bg); color: var(--text); border-left: 3px solid var(--info); }
@@ -1360,9 +1330,9 @@ table.data th.num .sort { flex-direction: row-reverse; }
1360
1330
  .tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); overflow-x: auto; scrollbar-width: none; }
1361
1331
  .tabs .tab { position: relative; display: inline-flex; align-items: center; gap: 6px; min-height: 38px; padding: 0 12px; margin-bottom: -1px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--muted); font-weight: 500; text-decoration: none; white-space: nowrap; cursor: pointer; }
1362
1332
  .tabs .tab:hover { color: var(--text); }
1363
- .tabs .tab[aria-current] { color: var(--text); border-bottom-color: var(--primary); }
1333
+ .tabs .tab:is(button[aria-current], [aria-current="page"]) { color: var(--text); border-bottom-color: var(--primary); }
1364
1334
  .tabs .count { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--surface-2); color: var(--muted); font-size: 0.75rem; line-height: 18px; text-align: center; font-variant-numeric: tabular-nums; }
1365
- .tabs .tab[aria-current] .count { background: var(--primary-soft); color: var(--primary); }
1335
+ .tabs .tab:is(button[aria-current], [aria-current="page"]) .count { background: var(--primary-soft); color: var(--primary); }
1366
1336
 
1367
1337
  /* ---- FilterChips ---- */
1368
1338
  .chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
@@ -1434,19 +1404,21 @@ export default function Badge({
1434
1404
  import { Link, run, useFormStatus } from "@ezship/react";
1435
1405
 
1436
1406
  /**
1437
- * A button. \`action\` may be async: the button shows a spinner and ignores clicks until it settles, and a
1407
+ * A button. \`action\` (or \`onClick\`, the same thing) may be async: the button shows a spinner and ignores clicks until it settles, and a
1438
1408
  * failure shows the standard notice. \`confirm\` asks first. \`to\` draws a link that looks like a button.
1439
- * A \`type="submit"\` button inside a <form action> shows the form's pending state.
1409
+ * A \`type="submit"\` button inside a <form action> shows the form's pending state; \`busy\` shows any other.
1440
1410
  */
1441
1411
  export default function Button({
1442
1412
  children,
1443
1413
  variant = "secondary",
1444
1414
  size,
1445
- action,
1415
+ action: given,
1416
+ onClick,
1446
1417
  confirm: question,
1447
1418
  to,
1448
1419
  type = "button",
1449
1420
  disabled,
1421
+ busy: pending,
1450
1422
  label,
1451
1423
  title,
1452
1424
  }: {
@@ -1455,19 +1427,24 @@ export default function Button({
1455
1427
  size?: "sm";
1456
1428
  /** What a click does; a returned promise keeps the button busy until it settles. */
1457
1429
  action?: () => unknown;
1430
+ /** The same as action, under the name a button's handler usually has. */
1431
+ onClick?: () => unknown;
1458
1432
  /** A question the person confirms before \`action\` runs, such as "Delete this order?". */
1459
1433
  confirm?: string;
1460
1434
  /** A route of this Site: the button is a link. */
1461
1435
  to?: string;
1462
1436
  type?: "button" | "submit";
1463
1437
  disabled?: boolean;
1438
+ /** Busy, as while its own action runs: a Form's submit button while the form's action does. */
1439
+ busy?: boolean;
1464
1440
  /** The accessible name, for a button whose children are only a symbol. */
1465
1441
  label?: string;
1466
1442
  title?: string;
1467
1443
  }) {
1444
+ const action = given ?? onClick;
1468
1445
  const [running, start] = useTransition();
1469
1446
  const form = useFormStatus();
1470
- const busy = running || (type === "submit" && form.pending);
1447
+ const busy = running || pending === true || (type === "submit" && form.pending);
1471
1448
  const className = ["btn", variant === "secondary" ? "" : variant, size ?? ""].join(" ").trim();
1472
1449
  if (to)
1473
1450
  return (
@@ -2098,7 +2075,7 @@ export default function Panel({
2098
2075
  `,
2099
2076
  "components/SearchBox.tsx": `/**
2100
2077
  * A labelled search input with a clear button; Escape clears it too. Filter in the query with
2101
- * { col: { like: \`%\${q}%\` } }, and debounce the value (useDebounced) when every keystroke would query.
2078
+ * { col: { contains: q } }, and debounce the value (useDebounced) when every keystroke would query.
2102
2079
  */
2103
2080
  export default function SearchBox({
2104
2081
  value,
@@ -2189,8 +2166,9 @@ export default function StateBadge({
2189
2166
  "components/Tabs.tsx": `import { Link } from "@ezship/react";
2190
2167
 
2191
2168
  /**
2192
- * A row of tabs. A tab with \`to\` is a link to that route and is current when the route is; the others are
2193
- * buttons, current when their \`value\` is \`value\`, and call \`onChange\`. \`count\` draws a number beside it.
2169
+ * A row of tabs. A tab with \`to\` is a link, current on exactly its route and query (\`/?status=open\`; \`/\` is
2170
+ * the unfiltered one); the others are buttons, current when their \`value\` is \`value\`, and call \`onChange\`.
2171
+ * \`count\` draws a number beside it.
2194
2172
  */
2195
2173
  export default function Tabs({
2196
2174
  tabs,
@@ -2253,6 +2231,429 @@ export default function Yes({ value }: { value: boolean | null | undefined }) {
2253
2231
  if (value === null || value === undefined) return <span className="muted">—</span>;
2254
2232
  return <span>{value ? "Yes" : "No"}</span>;
2255
2233
  }
2234
+ `,
2235
+ "components/Board.tsx": `import type { ReactNode } from "react";
2236
+
2237
+ /**
2238
+ * Columns of cards side by side, one per team, stage or status, wrapping as the page narrows: put BoardColumn
2239
+ * inside, and Card inside each. For a table of rows use DataTable.
2240
+ */
2241
+ export default function Board({ children }: { children: ReactNode }) {
2242
+ return <div className="board">{children}</div>;
2243
+ }
2244
+ `,
2245
+ "components/BoardColumn.tsx": `import type { ReactNode } from "react";
2246
+
2247
+ /**
2248
+ * One column of a Board: a title, how many it holds, an optional line under the title and a control at its
2249
+ * end (aside), then its Cards. With count 0 it shows empty instead of its children.
2250
+ */
2251
+ export default function BoardColumn({
2252
+ title,
2253
+ count,
2254
+ hint,
2255
+ aside,
2256
+ empty = "Nothing here.",
2257
+ children,
2258
+ }: {
2259
+ title: string;
2260
+ count?: number;
2261
+ hint?: ReactNode;
2262
+ aside?: ReactNode;
2263
+ empty?: string;
2264
+ children?: ReactNode;
2265
+ }) {
2266
+ return (
2267
+ <section className="board-column">
2268
+ <header className="board-head">
2269
+ <div className="board-title">
2270
+ <h3>{title}</h3>
2271
+ {count === undefined ? null : <span className="board-count">{count}</span>}
2272
+ </div>
2273
+ {aside}
2274
+ </header>
2275
+ {hint ? <p className="board-hint">{hint}</p> : null}
2276
+ <div className="board-cards">
2277
+ {count === 0 ? <p className="board-empty">{empty}</p> : children}
2278
+ </div>
2279
+ </section>
2280
+ );
2281
+ }
2282
+ `,
2283
+ "components/Card.tsx": `import type { ReactNode } from "react";
2284
+ import { Link } from "@ezship/react";
2285
+
2286
+ /**
2287
+ * One item of a BoardColumn or a list of cards: a title, a Badge beside it (aside), a muted line (meta) and
2288
+ * anything else under them. With to, the whole card is a link to that route, so it holds no button or input.
2289
+ */
2290
+ export default function Card({
2291
+ title,
2292
+ meta,
2293
+ aside,
2294
+ to,
2295
+ children,
2296
+ }: {
2297
+ title: ReactNode;
2298
+ meta?: ReactNode;
2299
+ aside?: ReactNode;
2300
+ to?: string;
2301
+ children?: ReactNode;
2302
+ }) {
2303
+ const body = (
2304
+ <>
2305
+ <div className="card-head">
2306
+ <span className="card-title">{title}</span>
2307
+ {aside}
2308
+ </div>
2309
+ {meta ? <div className="card-meta">{meta}</div> : null}
2310
+ {children}
2311
+ </>
2312
+ );
2313
+ return to ? (
2314
+ <Link to={to} className="card">
2315
+ {body}
2316
+ </Link>
2317
+ ) : (
2318
+ <div className="card">{body}</div>
2319
+ );
2320
+ }
2321
+ `,
2322
+ "components/Checkbox.tsx": `import type { ReactNode } from "react";
2323
+
2324
+ /** A labelled checkbox: checked is its value, and onChange answers the new one. */
2325
+ export default function Checkbox({
2326
+ label,
2327
+ checked,
2328
+ onChange,
2329
+ disabled,
2330
+ }: {
2331
+ label: ReactNode;
2332
+ checked: boolean;
2333
+ onChange: (checked: boolean) => void;
2334
+ disabled?: boolean;
2335
+ }) {
2336
+ return (
2337
+ <label className="field check">
2338
+ <input
2339
+ type="checkbox"
2340
+ checked={checked}
2341
+ disabled={disabled}
2342
+ onChange={(e) => onChange(e.target.checked)}
2343
+ />
2344
+ <span>{label}</span>
2345
+ </label>
2346
+ );
2347
+ }
2348
+ `,
2349
+ "components/DateInput.tsx": `import type { ReactNode } from "react";
2350
+ import type { DateString } from "@ezship/react";
2351
+ import Field from "./Field";
2352
+
2353
+ /** A labelled date input for a DATE column: value is a DateString or null, and onChange answers the same. */
2354
+ export default function DateInput({
2355
+ label,
2356
+ value,
2357
+ onChange,
2358
+ hint,
2359
+ error,
2360
+ required,
2361
+ disabled,
2362
+ min,
2363
+ max,
2364
+ }: {
2365
+ label: string;
2366
+ value: DateString | null;
2367
+ onChange: (value: DateString | null) => void;
2368
+ hint?: ReactNode;
2369
+ error?: string | null;
2370
+ required?: boolean;
2371
+ disabled?: boolean;
2372
+ min?: DateString;
2373
+ max?: DateString;
2374
+ }) {
2375
+ return (
2376
+ <Field label={label} hint={hint} error={error} required={required}>
2377
+ <input
2378
+ type="date"
2379
+ value={value ?? ""}
2380
+ min={min}
2381
+ max={max}
2382
+ disabled={disabled}
2383
+ aria-invalid={error ? true : undefined}
2384
+ aria-required={required ? true : undefined}
2385
+ onChange={(e) => onChange(e.target.value === "" ? null : e.target.value)}
2386
+ />
2387
+ </Field>
2388
+ );
2389
+ }
2390
+ `,
2391
+ "components/Form.tsx": `import { startTransition, useActionState, type ReactNode } from "react";
2392
+ import { attempt } from "@ezship/react";
2393
+ import Button from "./Button";
2394
+ import Notice from "./Notice";
2395
+
2396
+ /**
2397
+ * A form that runs action when it is submitted: a server function call, or a db write. Put the inputs inside
2398
+ * (TextInput, NumberInput, SelectInput, DateInput, TextArea, Checkbox, a Field). While action runs the submit
2399
+ * button is busy; what it throws (a failed check, a refused write, a function's error) shows above the fields
2400
+ * and the form stays as it was. columns 2 lays the fields in two columns on a wide screen, a TextArea across
2401
+ * both. onCancel adds a Cancel button. Inside a Dialog, give the Dialog no footer.
2402
+ */
2403
+ export default function Form({
2404
+ action,
2405
+ submit = "Save",
2406
+ onCancel,
2407
+ columns = 1,
2408
+ children,
2409
+ }: {
2410
+ /** What Submit does; throw an Error to refuse, with the message to show. */
2411
+ action: () => unknown;
2412
+ /** The submit button's words. */
2413
+ submit?: string;
2414
+ onCancel?: () => void;
2415
+ columns?: 1 | 2;
2416
+ children: ReactNode;
2417
+ }) {
2418
+ const [error, save, pending] = useActionState(
2419
+ attempt(async () => {
2420
+ await action();
2421
+ }),
2422
+ null,
2423
+ );
2424
+ // Submitted from onSubmit, not <form action>: React resets a form after its action, which would show a
2425
+ // controlled select or checkbox at its first value while its state keeps the chosen one.
2426
+ return (
2427
+ <form
2428
+ className="form"
2429
+ noValidate
2430
+ onSubmit={(e) => {
2431
+ e.preventDefault();
2432
+ if (!pending) startTransition(save);
2433
+ }}
2434
+ >
2435
+ {error ? <Notice tone="danger">{error}</Notice> : null}
2436
+ <div className={columns === 2 ? "form-fields two" : "form-fields"}>{children}</div>
2437
+ <div className="form-actions">
2438
+ {onCancel ? <Button action={onCancel}>Cancel</Button> : null}
2439
+ <Button type="submit" variant="primary" busy={pending}>
2440
+ {submit}
2441
+ </Button>
2442
+ </div>
2443
+ </form>
2444
+ );
2445
+ }
2446
+ `,
2447
+ "components/NumberInput.tsx": `import type { ReactNode } from "react";
2448
+ import Field from "./Field";
2449
+
2450
+ /**
2451
+ * A labelled number input for an INTEGER or REAL column: value is a number or null (empty), and onChange
2452
+ * answers the same, never text. For MONEY keep a text input and toCents.
2453
+ */
2454
+ export default function NumberInput({
2455
+ label,
2456
+ value,
2457
+ onChange,
2458
+ hint,
2459
+ error,
2460
+ required,
2461
+ disabled,
2462
+ min,
2463
+ max,
2464
+ step,
2465
+ placeholder,
2466
+ }: {
2467
+ label: string;
2468
+ value: number | null;
2469
+ onChange: (value: number | null) => void;
2470
+ hint?: ReactNode;
2471
+ error?: string | null;
2472
+ required?: boolean;
2473
+ disabled?: boolean;
2474
+ min?: number;
2475
+ max?: number;
2476
+ step?: number;
2477
+ placeholder?: string;
2478
+ }) {
2479
+ return (
2480
+ <Field label={label} hint={hint} error={error} required={required}>
2481
+ <input
2482
+ type="number"
2483
+ inputMode="decimal"
2484
+ value={value ?? ""}
2485
+ min={min}
2486
+ max={max}
2487
+ step={step}
2488
+ placeholder={placeholder}
2489
+ disabled={disabled}
2490
+ aria-invalid={error ? true : undefined}
2491
+ aria-required={required ? true : undefined}
2492
+ onChange={(e) => {
2493
+ const next = e.target.value === "" ? null : Number(e.target.value);
2494
+ onChange(next === null || Number.isNaN(next) ? null : next);
2495
+ }}
2496
+ />
2497
+ </Field>
2498
+ );
2499
+ }
2500
+ `,
2501
+ "components/SelectInput.tsx": `import type { ReactNode } from "react";
2502
+ import Field from "./Field";
2503
+
2504
+ /**
2505
+ * A labelled choice from a few options: each a string, or a value with its label. value is the chosen one or
2506
+ * null, shown as placeholder. For a CHECK column pass schema.column(table, column)?.values ?? []; for a
2507
+ * reference to another Table use RefPicker.
2508
+ */
2509
+ export default function SelectInput({
2510
+ label,
2511
+ value,
2512
+ onChange,
2513
+ options,
2514
+ placeholder = "Choose…",
2515
+ hint,
2516
+ error,
2517
+ required,
2518
+ disabled,
2519
+ }: {
2520
+ label: string;
2521
+ value: string | null;
2522
+ onChange: (value: string | null) => void;
2523
+ options: readonly (string | { value: string; label: string })[];
2524
+ placeholder?: string;
2525
+ hint?: ReactNode;
2526
+ error?: string | null;
2527
+ required?: boolean;
2528
+ disabled?: boolean;
2529
+ }) {
2530
+ return (
2531
+ <Field label={label} hint={hint} error={error} required={required}>
2532
+ <select
2533
+ value={value ?? ""}
2534
+ disabled={disabled}
2535
+ aria-invalid={error ? true : undefined}
2536
+ aria-required={required ? true : undefined}
2537
+ onChange={(e) => onChange(e.target.value === "" ? null : e.target.value)}
2538
+ >
2539
+ <option value="">{placeholder}</option>
2540
+ {options.map((o) => {
2541
+ const option = typeof o === "string" ? { value: o, label: o } : o;
2542
+ return (
2543
+ <option key={option.value} value={option.value}>
2544
+ {option.label}
2545
+ </option>
2546
+ );
2547
+ })}
2548
+ </select>
2549
+ </Field>
2550
+ );
2551
+ }
2552
+ `,
2553
+ "components/Stats.tsx": `import type { ReactNode } from "react";
2554
+
2555
+ /** A row of Stat tiles, all one width, wrapping as the page narrows: put Stat inside. */
2556
+ export default function Stats({ children }: { children: ReactNode }) {
2557
+ return <div className="stats">{children}</div>;
2558
+ }
2559
+ `,
2560
+ "components/TextArea.tsx": `import type { ReactNode } from "react";
2561
+ import Field from "./Field";
2562
+
2563
+ /** A labelled multi-line text input: value is its text, and onChange answers the new text. */
2564
+ export default function TextArea({
2565
+ label,
2566
+ value,
2567
+ onChange,
2568
+ hint,
2569
+ error,
2570
+ required,
2571
+ disabled,
2572
+ placeholder,
2573
+ rows = 3,
2574
+ }: {
2575
+ label: string;
2576
+ value: string;
2577
+ onChange: (value: string) => void;
2578
+ hint?: ReactNode;
2579
+ error?: string | null;
2580
+ required?: boolean;
2581
+ disabled?: boolean;
2582
+ placeholder?: string;
2583
+ rows?: number;
2584
+ }) {
2585
+ return (
2586
+ <Field label={label} hint={hint} error={error} required={required}>
2587
+ <textarea
2588
+ value={value}
2589
+ rows={rows}
2590
+ placeholder={placeholder}
2591
+ disabled={disabled}
2592
+ aria-invalid={error ? true : undefined}
2593
+ aria-required={required ? true : undefined}
2594
+ onChange={(e) => onChange(e.target.value)}
2595
+ />
2596
+ </Field>
2597
+ );
2598
+ }
2599
+ `,
2600
+ "components/TextInput.tsx": `import type { ReactNode } from "react";
2601
+ import Field from "./Field";
2602
+
2603
+ /** A labelled one-line text input: value is its text, and onChange answers the new text. */
2604
+ export default function TextInput({
2605
+ label,
2606
+ value,
2607
+ onChange,
2608
+ hint,
2609
+ error,
2610
+ required,
2611
+ disabled,
2612
+ placeholder,
2613
+ type = "text",
2614
+ autoFocus,
2615
+ }: {
2616
+ label: string;
2617
+ value: string;
2618
+ onChange: (value: string) => void;
2619
+ hint?: ReactNode;
2620
+ error?: string | null;
2621
+ required?: boolean;
2622
+ disabled?: boolean;
2623
+ placeholder?: string;
2624
+ type?: "text" | "email" | "tel" | "url" | "password";
2625
+ autoFocus?: boolean;
2626
+ }) {
2627
+ return (
2628
+ <Field label={label} hint={hint} error={error} required={required}>
2629
+ <input
2630
+ type={type}
2631
+ value={value}
2632
+ placeholder={placeholder}
2633
+ disabled={disabled}
2634
+ autoFocus={autoFocus}
2635
+ aria-invalid={error ? true : undefined}
2636
+ aria-required={required ? true : undefined}
2637
+ onChange={(e) => onChange(e.target.value)}
2638
+ />
2639
+ </Field>
2640
+ );
2641
+ }
2642
+ `,
2643
+ "components/Toolbar.tsx": `import type { ReactNode } from "react";
2644
+
2645
+ /**
2646
+ * The controls above a list, in one row that wraps: a SearchBox, FilterChips or a select as children, and
2647
+ * aside (a button, a count) at the far end. First inside a Panel it draws as the Panel's top strip.
2648
+ */
2649
+ export default function Toolbar({ children, aside }: { children: ReactNode; aside?: ReactNode }) {
2650
+ return (
2651
+ <div className="toolbar">
2652
+ {children}
2653
+ {aside ? <div className="toolbar-aside">{aside}</div> : null}
2654
+ </div>
2655
+ );
2656
+ }
2256
2657
  `,
2257
2658
  [CONSTANTS_FILE]: `/** The Instance's name as the starter Shell's top bar shows it. */
2258
2659
  export const BRAND = "My company";
@@ -2286,8 +2687,10 @@ export default function Shell({ children }: { children: ReactNode }) {
2286
2687
  // ---- the structural Rules: what push can check with no parser ----------------------------------------------
2287
2688
  //
2288
2689
  // The full Rules (which parts of React, banned globals, constant shapes) need a parser and run on `bun lint` in
2289
- // the Pipeline (docs/adr/0121, 0122); deploy and `ez check` run them on the platform. This subset is regex over import
2290
- // statements and export lines, enough for push to refuse a Working Copy that could never deploy.
2690
+ // the Pipeline (docs/adr/0236, 0237); deploy and `ez check` run them on the platform. This subset is regex over import
2691
+ // statements and export lines, enough for push to refuse a Working Copy that could never deploy. Anything that
2692
+ // must tell code from text (a dynamic `import()`, `import.meta`) is a parser Rule, never a regex here: page
2693
+ // text, strings and comments say "import (" too.
2291
2694
 
2292
2695
  /** @typedef {{ file: string, range: { start: { line: number, character: number }, end: { line: number, character: number } }, severity: 1, code: string, message: string }} Diagnostic */
2293
2696
 
@@ -2296,11 +2699,10 @@ export default function Shell({ children }: { children: ReactNode }) {
2296
2699
  // `export default function` and JSX text such as `from "the list"` from matching.
2297
2700
  const IMPORT_RE =
2298
2701
  /^[ \t]*(?:import|export)\s+(type\s+)?(?:(?:\*\s+as\s+\w+|\{[^}'"]*\}|\w+)(?:\s*,\s*(?:\{[^}'"]*\}|\*\s+as\s+\w+))?\s+from\s+)?["']([^"'\n]+)["']/gm;
2299
- const DYNAMIC_IMPORT_RE = /\bimport\s*\(/g;
2300
2702
  const DEFAULT_EXPORT_RE = /^export\s+default\s+function\s+([A-Za-z_$][\w$]*)/m;
2301
2703
  const OTHER_EXPORT_RE = /^export\s+(?!default\s)/m;
2302
2704
  const APP_OTHER_EXPORT_RE = /^export\s+(?!default\s|type\s+Provided\s*=)/m;
2303
- /** A page may also say who opens it (docs/adr/0098): `export const access = "group(<name>)"`. */
2705
+ /** A page may also say who opens it (docs/adr/0225): `export const access = "group(<name>)"`. */
2304
2706
  const PAGE_OTHER_EXPORT_RE = /^export\s+(?!default\s|const\s+access\s*=)/m;
2305
2707
  const PAGE_ACCESS_RE = /^export\s+const\s+access\s*=\s*(.*)$/m;
2306
2708
  const PAGE_ACCESS_LITERAL_RE = /^(["'])([^"'\\]*)\1\s*;?\s*$/;
@@ -2353,23 +2755,26 @@ function resolveRelative(from, specifier) {
2353
2755
  return parts.join("/");
2354
2756
  }
2355
2757
 
2356
- const IMPORT_SHAPE = `Site code imports only react, @ezship/react, ${SITE_PACKAGES.join(", ")}, global/<Name>, global/documents/<Name>, global/hooks/use<Name>, global/constants, global/lib/<name>, ./constants, ./components/<Name>, ./hooks/use<Name>, ./functions/<name>, ./local/<name> (../constants, ../components/<Name>, ../hooks/use<Name>, ../functions/<name> and ../local/<name> from a page, component or hook), and \`import type\` from global/db/types (no extensions).`;
2357
- /** A component of the Instance's Global Workspace. Whether it exists is the platform's check, not this one. */
2358
- const GLOBAL_RE = /^global\/[A-Z][A-Za-z0-9]*$/;
2359
- /** A Document of the Global Workspace (docs/adr/0105): Site code imports its default, a typed descriptor. */
2758
+ const IMPORT_SHAPE = `Site code imports only react, @ezship/react, ${SITE_PACKAGES.join(", ")}, global/<Name>, global/documents/<Name>, global/hooks/use<Name>, global/constants, global/lib/<name>, ./constants, ./components/<Name>, ./hooks/use<Name>, ./lib/<name>, ./functions/<name>, ./local/<name> (../constants, ../components/<Name>, ../hooks/use<Name>, ../lib/<name>, ../functions/<name> and ../local/<name> from a page, component or hook), and \`import type\` from global/db/types (no extensions).`;
2759
+ /**
2760
+ * A component of the Instance's Global Workspace, by its short name or by its path (`global/components/<Name>`,
2761
+ * docs/adr/0204). Whether it exists is the platform's check, not this one.
2762
+ */
2763
+ const GLOBAL_RE = /^global\/(?:components\/)?[A-Z][A-Za-z0-9]*$/;
2764
+ /** A Document of the Global Workspace (docs/adr/0233): Site code imports its default, a typed descriptor. */
2360
2765
  const GLOBAL_DOCUMENT_RE = /^global\/documents\/[A-Z][A-Za-z0-9]*$/;
2361
2766
  /** Why a `global/lib/...` specifier is malformed, or null. Whether the module exists is the type check's. */
2362
2767
  const libSpecifierError = (/** @type {string} */ specifier) =>
2363
2768
  libModuleName(specifier.slice("global/".length) + ".ts")
2364
2769
  ? null
2365
2770
  : `"${specifier}": a Global lib module is imported as global/lib/<name> (global/lib/accounting), no extension.`;
2366
- /** Why a `global/hooks/...` specifier is malformed, or null (ADR 0091). */
2771
+ /** Why a `global/hooks/...` specifier is malformed, or null (ADR 0209). */
2367
2772
  const hookSpecifierError = (/** @type {string} */ specifier) =>
2368
2773
  hookName(specifier.slice("global/".length) + ".ts")
2369
2774
  ? null
2370
2775
  : `"${specifier}": a Global hook is imported as global/hooks/use<Name> (global/hooks/useOpenOrders), no extension.`;
2371
2776
  const GLOBAL_SPECIFIER_HINT = (/** @type {string} */ specifier) =>
2372
- `"${specifier}": use global/<Name> for a PascalCase component, global/documents/<Name> for a Document, global/hooks/use<Name> for a custom hook, global/lib/<name> for shared logic or global/constants for plain values, no extension.`;
2777
+ `"${specifier}": use global/<Name> (or global/components/<Name>) for a PascalCase component, global/documents/<Name> for a Document, global/hooks/use<Name> for a custom hook, global/lib/<name> for shared logic or global/constants for plain values, no extension.`;
2373
2778
 
2374
2779
  /**
2375
2780
  * Why `path` may not import `specifier`, or null.
@@ -2387,10 +2792,46 @@ export function importError(path, specifier, typeOnly, files) {
2387
2792
  if (target && localFunctionName(target + ".ts") && target + ".ts" in files) return null;
2388
2793
  return `${specifier}: local functions import @ezship/react/local, node:* built-ins, constants, sibling local functions, and type-only global/db/types.`;
2389
2794
  }
2795
+ // A Site's own lib module (ADR 0209): a Global lib module's imports, and the constants.
2796
+ if (libModuleName(path)) {
2797
+ if (specifier === "global/constants") return null;
2798
+ if (
2799
+ specifier === "@ezship/react/server" ||
2800
+ specifier === "@ezship/react" ||
2801
+ specifier === "global/db/types"
2802
+ )
2803
+ return typeOnly
2804
+ ? null
2805
+ : `"${specifier}": a lib module imports only types from it; use import type.`;
2806
+ if (specifier.startsWith("global/lib/")) return libSpecifierError(specifier);
2807
+ const target =
2808
+ specifier.startsWith("./") || specifier.startsWith("../")
2809
+ ? resolveRelative(path, specifier)
2810
+ : null;
2811
+ if (target === "constants") return null;
2812
+ if (target && libModuleName(target + ".ts")) {
2813
+ if (target + ".ts" === path) return `"${specifier}": a module cannot import itself.`;
2814
+ return target + ".ts" in files
2815
+ ? null
2816
+ : `"${specifier}": there is no ${target}.ts in the working copy.`;
2817
+ }
2818
+ return `"${specifier}" cannot be imported. ${SITE_LIB_IMPORT_SHAPE}`;
2819
+ }
2820
+ // What a Site's own lib module is to its importers: a file of the working copy.
2821
+ const siteLib = () => {
2822
+ const target =
2823
+ specifier.startsWith("./") || specifier.startsWith("../")
2824
+ ? resolveRelative(path, specifier)
2825
+ : null;
2826
+ if (!target || !libModuleName(target + ".ts")) return undefined;
2827
+ return target + ".ts" in files
2828
+ ? null
2829
+ : `"${specifier}": there is no ${target}.ts in the working copy.`;
2830
+ };
2390
2831
  const importedListener = specifier.startsWith(".") ? resolveRelative(path, specifier) : null;
2391
2832
  if (importedListener && listenerName(importedListener + ".ts"))
2392
2833
  return `${specifier}: listeners are never imported; ${LISTENERS_FILE} delivers events to them.`;
2393
- // A Listener (ADR 0092) imports what a server function imports, but no Document.
2834
+ // A Listener (ADR 0231) imports what a server function imports, but no Document.
2394
2835
  if (listenerName(path)) {
2395
2836
  if (specifier === "@ezship/react/server" || specifier === "global/constants") return null;
2396
2837
  if (specifier === "global/db/types" && typeOnly) return null;
@@ -2398,7 +2839,9 @@ export function importError(path, specifier, typeOnly, files) {
2398
2839
  const target = resolveRelative(path, specifier);
2399
2840
  if (target === "constants") return null;
2400
2841
  if (target && functionName(target + ".ts") && target + ".ts" in files) return null;
2401
- return `${specifier}: listeners import @ezship/react/server, constants, sibling functions, global/lib/<name> modules and type-only global/db/types.`;
2842
+ const lib = siteLib();
2843
+ if (lib !== undefined) return lib;
2844
+ return `${specifier}: listeners import @ezship/react/server, constants, sibling functions, lib modules (../lib/<name>, global/lib/<name>) and type-only global/db/types.`;
2402
2845
  }
2403
2846
  if (functionName(path)) {
2404
2847
  if (specifier === "@ezship/react/server" || specifier === "global/constants") return null;
@@ -2408,7 +2851,9 @@ export function importError(path, specifier, typeOnly, files) {
2408
2851
  const target = resolveRelative(path, specifier);
2409
2852
  if (target === "constants") return null;
2410
2853
  if (target && functionName(target + ".ts") && target + ".ts" in files) return null;
2411
- return `${specifier}: server functions import @ezship/react/server, constants, sibling functions, global/lib/<name> modules, global/documents/<Name> and type-only global/db/types.`;
2854
+ const lib = siteLib();
2855
+ if (lib !== undefined) return lib;
2856
+ return `${specifier}: server functions import @ezship/react/server, constants, sibling functions, lib modules (../lib/<name>, global/lib/<name>), global/documents/<Name> and type-only global/db/types.`;
2412
2857
  }
2413
2858
  if (path === CONSTANTS_FILE)
2414
2859
  return `${CONSTANTS_FILE} imports nothing: it holds plain values only.`;
@@ -2429,7 +2874,7 @@ export function importError(path, specifier, typeOnly, files) {
2429
2874
  return `"${specifier}": write the import without the extension. ${IMPORT_SHAPE}`;
2430
2875
  const target = resolveRelative(path, specifier);
2431
2876
  if (target === "constants") return null;
2432
- // ADR 0088: the type of the values App.tsx provides, for useProvided<Provided>().
2877
+ // ADR 0214: the type of the values App.tsx provides, for useProvided<Provided>().
2433
2878
  if (target === "App" && path !== MAIN_FILE)
2434
2879
  return typeOnly
2435
2880
  ? null
@@ -2445,8 +2890,6 @@ export function importError(path, specifier, typeOnly, files) {
2445
2890
  return `"${specifier}" points inside pages/; from a page, write "../${meant}".`;
2446
2891
  return `"${specifier}": pages are never imported; the router renders them by route. Shared markup is a component.`;
2447
2892
  }
2448
- if (target === "db/types")
2449
- return `"${specifier}" moved to "global/db/types"; update this type import.`;
2450
2893
  if (target && componentName(target + ".tsx")) {
2451
2894
  if (target + ".tsx" === path) return `"${specifier}": a component cannot import itself.`;
2452
2895
  return target + ".tsx" in files
@@ -2459,11 +2902,14 @@ export function importError(path, specifier, typeOnly, files) {
2459
2902
  ? null
2460
2903
  : `"${specifier}": there is no ${target}.ts in the working copy.`;
2461
2904
  }
2905
+ const lib = siteLib();
2906
+ if (lib !== undefined) return lib;
2462
2907
  return `"${specifier}" cannot be imported. ${IMPORT_SHAPE}`;
2463
2908
  }
2464
2909
 
2465
2910
  const DOCUMENT_IMPORT_SHAPE = `A Document imports only @ezship/react/pdf, global/constants (or ../constants), type-only global/db/types and sibling Documents (./<Name>).`;
2466
2911
  const GLOBAL_IMPORT_SHAPE = `Global Workspace code imports only react, @ezship/react, ${SITE_PACKAGES.join(", ")}, type-only global/db/types, global/constants (or ./constants from ${SHELL_FILE}, ../constants from a component or hook), global/lib/<name> modules, global hooks (global/hooks/use<Name>, or ../hooks/use<Name> from a component, ./use<Name> from a hook and ./hooks/use<Name> from ${SHELL_FILE}) and other global components (global/<Name>, or ./<Name> from a component and ./components/<Name> from ${SHELL_FILE}).`;
2912
+ const SITE_LIB_IMPORT_SHAPE = `A Site's lib module imports only other lib modules (./<name> or global/lib/<name>), constants (../constants, global/constants) and types: \`import type\` from @ezship/react, @ezship/react/server and global/db/types. No packages, no network, no components or hooks.`;
2467
2913
  const LIB_IMPORT_SHAPE = `A lib module imports only other lib modules (global/lib/<name> or ./<name>) and types: \`import type\` from @ezship/react/server and global/db/types. No packages, no network, no components or constants.`;
2468
2914
 
2469
2915
  /**
@@ -2486,7 +2932,7 @@ function libTarget(path, specifier) {
2486
2932
  export function globalImportError(path, specifier, files, typeOnly = false) {
2487
2933
  if (path === CONSTANTS_FILE)
2488
2934
  return `${CONSTANTS_FILE} imports nothing: it holds plain values only.`;
2489
- // ADR 0088: the declaration holds types and its defaults; it names row types and the Framework's brands.
2935
+ // ADR 0214: the declaration holds types and its defaults; it names row types and the Framework's brands.
2490
2936
  if (path === SESSION_FILE)
2491
2937
  return (specifier === "@ezship/react" ||
2492
2938
  specifier === "global/db/types" ||
@@ -2515,7 +2961,7 @@ export function globalImportError(path, specifier, files, typeOnly = false) {
2515
2961
  ? null
2516
2962
  : `"${specifier}": there is no ${lib}.ts in the Global Workspace.`;
2517
2963
  }
2518
- // A scheduled job (ADR 0136) imports what a Table rule imports; nothing imports a job.
2964
+ // A scheduled job (ADR 0230) imports what a Table rule imports; nothing imports a job.
2519
2965
  if (jobName(path)) {
2520
2966
  if (specifier === "@ezship/react/server") return null;
2521
2967
  if (specifier === "global/constants" || resolveRelative(path, specifier) === "constants")
@@ -2527,7 +2973,7 @@ export function globalImportError(path, specifier, files, typeOnly = false) {
2527
2973
  const importedJob = specifier.startsWith(".") ? resolveRelative(path, specifier) : null;
2528
2974
  if (importedJob && jobName(importedJob + ".ts"))
2529
2975
  return `"${specifier}": jobs are never imported; ${SCHEDULES_FILE} runs them.`;
2530
- // A Table rule (docs/adr/0099) or a workflow (docs/adr/0103) imports what server code may.
2976
+ // A Table rule (docs/adr/0226) or a workflow (docs/adr/0227) imports what server code may.
2531
2977
  if (liveCodeTable(path)) {
2532
2978
  if (specifier === "@ezship/react/server") return null;
2533
2979
  if (specifier === "global/constants" || resolveRelative(path, specifier) === "constants")
@@ -2600,7 +3046,7 @@ export function checkGlobalStructure(files) {
2600
3046
  });
2601
3047
  const context = contextError(files[CONTEXT_FILE]);
2602
3048
  if (context) top(CONTEXT_FILE, "context", context);
2603
- // The Instance's schedules (ADR 0136), checked as a Push checks them.
3049
+ // The Instance's schedules (ADR 0230), checked as a Push checks them.
2604
3050
  if (SCHEDULES_FILE in files)
2605
3051
  for (const error of parseSchedules(files[SCHEDULES_FILE], files).errors)
2606
3052
  top(SCHEDULES_FILE, "schedules", error);
@@ -2618,14 +3064,14 @@ export function checkGlobalStructure(files) {
2618
3064
  const declared = parseSessionDeclaration(source);
2619
3065
  if ("error" in declared) top(path, "session-shape", declared.error);
2620
3066
  }
2621
- // A rules or workflow file names a Table of the schema beside it (docs/adr/0099, 0103).
3067
+ // A rules or workflow file names a Table of the schema beside it (docs/adr/0226, 0227).
2622
3068
  const ruled = liveCodeTable(path);
2623
3069
  if (ruled) {
2624
3070
  const schema = parseGlobalSchema(files[SCHEMA_FILE] ?? "");
2625
3071
  if (!("error" in schema) && !Object.hasOwn(schema.tables, ruled))
2626
3072
  top(path, "path", `${path}: no Table "${ruled}" in ${SCHEMA_FILE}.`);
2627
3073
  }
2628
- // A workflow's names are read from the file without running it, to type its column (docs/adr/0103).
3074
+ // A workflow's names are read from the file without running it, to type its column (docs/adr/0227).
2629
3075
  if (workflowTableName(path)) {
2630
3076
  const shape = readWorkflow(source);
2631
3077
  if ("error" in shape)
@@ -2639,8 +3085,15 @@ export function checkGlobalStructure(files) {
2639
3085
  code: "workflow-shape",
2640
3086
  message: `${path}: ${shape.error}.`,
2641
3087
  });
3088
+ else {
3089
+ // The names a Push would refuse (docs/adr/0227) are refused here first: the check is the gate.
3090
+ const schema = parseGlobalSchema(files[SCHEMA_FILE] ?? "");
3091
+ const table = workflowTableName(path);
3092
+ const wrong = "error" in schema || !table ? null : checkWorkflowNames(table, shape, schema);
3093
+ if (wrong) top(path, "workflow-shape", wrong);
3094
+ }
2642
3095
  }
2643
- // Access rules (docs/adr/0098) are checked against the schema beside them, as a Push checks them.
3096
+ // Access rules (docs/adr/0225) are checked against the schema beside them, as a Push checks them.
2644
3097
  if (path === ACCESS_FILE) {
2645
3098
  const schema = parseGlobalSchema(files[SCHEMA_FILE] ?? "");
2646
3099
  const checked = "error" in schema ? null : checkAccess(source, schema);
@@ -2670,17 +3123,6 @@ export function checkGlobalStructure(files) {
2670
3123
  const why = globalImportError(path, m[2], files, m[1] !== undefined);
2671
3124
  if (why) out.push(diag(path, source, m.index, m[0].length, "import", why));
2672
3125
  }
2673
- for (const m of source.matchAll(DYNAMIC_IMPORT_RE))
2674
- out.push(
2675
- diag(
2676
- path,
2677
- source,
2678
- m.index,
2679
- m[0].length,
2680
- "dynamic-import",
2681
- "Global Workspace code never loads code at runtime; import at the top of the file.",
2682
- ),
2683
- );
2684
3126
  // A job's shape (one default job() call) is the Pipeline's `function-export` Rule, as a rule's is.
2685
3127
  if (
2686
3128
  path === CONSTANTS_FILE ||
@@ -2784,7 +3226,7 @@ export function checkStructure(files) {
2784
3226
  "entry-missing",
2785
3227
  `The working copy has no ${MAIN_FILE}; the app needs one at the root.`,
2786
3228
  );
2787
- // ADR 0092: listeners.json, and the listeners/ files nothing delivers to (a warning).
3229
+ // ADR 0231: listeners.json, and the listeners/ files nothing delivers to (a warning).
2788
3230
  const listeners =
2789
3231
  LISTENERS_FILE in files
2790
3232
  ? parseListeners(files[LISTENERS_FILE], files)
@@ -2809,17 +3251,6 @@ export function checkStructure(files) {
2809
3251
  const why = importError(path, m[2], m[1] !== undefined, files);
2810
3252
  if (why) out.push(diag(path, source, m.index, m[0].length, "import", why));
2811
3253
  }
2812
- for (const m of source.matchAll(DYNAMIC_IMPORT_RE))
2813
- out.push(
2814
- diag(
2815
- path,
2816
- source,
2817
- m.index,
2818
- m[0].length,
2819
- "dynamic-import",
2820
- "Site code never loads code at runtime; import at the top of the file.",
2821
- ),
2822
- );
2823
3254
  // App.tsx, components and hooks must default-export the named function; a page default-exports any name.
2824
3255
  const hook = hookName(path);
2825
3256
  const want = path === MAIN_FILE ? "App" : (hook ?? componentName(path));
@@ -2847,7 +3278,7 @@ export function checkStructure(files) {
2847
3278
  `${path} must export ${want}, not ${d[1]}: the file name is the ${kind} name.`,
2848
3279
  ),
2849
3280
  );
2850
- // ADR 0098: a page's access is a literal row-free condition the Framework checks before it renders.
3281
+ // ADR 0225: a page's access is a literal row-free condition the Framework checks before it renders.
2851
3282
  const access = isPage ? PAGE_ACCESS_RE.exec(source) : null;
2852
3283
  if (access) {
2853
3284
  const literal = PAGE_ACCESS_LITERAL_RE.exec(access[1] ?? "");
@@ -2866,7 +3297,7 @@ export function checkStructure(files) {
2866
3297
  ),
2867
3298
  );
2868
3299
  }
2869
- // ADR 0088: App.tsx may also export the type of the values it provides on top of the Shell's.
3300
+ // ADR 0214: App.tsx may also export the type of the values it provides on top of the Shell's.
2870
3301
  const o = (
2871
3302
  path === MAIN_FILE ? APP_OTHER_EXPORT_RE : isPage ? PAGE_OTHER_EXPORT_RE : OTHER_EXPORT_RE
2872
3303
  ).exec(source);
@@ -2879,7 +3310,7 @@ export function checkStructure(files) {
2879
3310
  o[0].length,
2880
3311
  code,
2881
3312
  path === MAIN_FILE
2882
- ? `${path} exports only App and \`type Provided\`, the values it provides to its pages (ADR 0088). Shared values go in ${CONSTANTS_FILE}.`
3313
+ ? `${path} exports only App and \`type Provided\`, the values it provides to its pages (ADR 0214). Shared values go in ${CONSTANTS_FILE}.`
2883
3314
  : `${path} exports only its ${kind}. Shared values go in ${CONSTANTS_FILE}; shared markup is a component.`,
2884
3315
  ),
2885
3316
  );
@@ -2888,7 +3319,7 @@ export function checkStructure(files) {
2888
3319
  return out;
2889
3320
  }
2890
3321
 
2891
- // ---- the rule table (docs/adr/0078) ------------------------------------------------------------------------
3322
+ // ---- the rule table (docs/adr/0236) ------------------------------------------------------------------------
2892
3323
  //
2893
3324
  // Every diagnostic's `code` is one of these ids, stable across releases. A warning never fails a Check, Push,
2894
3325
  // Preview or Deploy; it becomes an error only by a platform release that changes its row here.
@@ -2924,7 +3355,7 @@ export const CHECK_RULES = Object.freeze(
2924
3355
  [
2925
3356
  "hook-export",
2926
3357
  "error",
2927
- "a hooks/ file that does not default-export its named hook, or exports more (ADR 0091)",
3358
+ "a hooks/ file that does not default-export its named hook, or exports more (ADR 0209)",
2928
3359
  "export default function use<Name>()",
2929
3360
  ],
2930
3361
  [
@@ -2948,13 +3379,13 @@ export const CHECK_RULES = Object.freeze(
2948
3379
  [
2949
3380
  "page-access",
2950
3381
  "error",
2951
- "a page's access that is not a literal group condition (docs/adr/0098)",
3382
+ "a page's access that is not a literal group condition (docs/adr/0225)",
2952
3383
  'export const access = "group(payroll) OR group(admins)"',
2953
3384
  ],
2954
3385
  [
2955
3386
  "function-options",
2956
3387
  "error",
2957
- "server function options that are not literal access, authority and api (docs/adr/0098, 0119)",
3388
+ "server function options that are not literal access, authority and api (docs/adr/0225, 0232)",
2958
3389
  'serverFunction(input, handler, { access: "group(payroll)", authority: "site", api: true })',
2959
3390
  ],
2960
3391
  [
@@ -2972,7 +3403,7 @@ export const CHECK_RULES = Object.freeze(
2972
3403
  [
2973
3404
  "no-restricted-imports",
2974
3405
  "error",
2975
- "a React import other than useState, useActionState, useTransition, startTransition, useOptimistic and types",
3406
+ "a React import other than useState, useActionState, useTransition, startTransition, useOptimistic, useMemo, useCallback and types",
2976
3407
  "use the @ezship/react equivalent",
2977
3408
  ],
2978
3409
  [
@@ -2990,12 +3421,12 @@ export const CHECK_RULES = Object.freeze(
2990
3421
  ],
2991
3422
  ["schema", "error", "a db/schema.sql problem", "follow `ez help db`"],
2992
3423
  ["schedules", "error", "a schedules.json problem", "follow `ez help jobs`"],
2993
- ["listeners", "error", "a listeners.json problem (docs/adr/0092)", "follow `ez help jobs`"],
2994
- ["page", "error", "a page.json problem (docs/adr/0148)", "follow `ez help files`"],
3424
+ ["listeners", "error", "a listeners.json problem (docs/adr/0231)", "follow `ez help jobs`"],
3425
+ ["page", "error", "a page.json problem (docs/adr/0209)", "follow `ez help files`"],
2995
3426
  [
2996
3427
  "listener-unlisted",
2997
3428
  "warning",
2998
- "a listeners/ file that listeners.json does not name (docs/adr/0092)",
3429
+ "a listeners/ file that listeners.json does not name (docs/adr/0231)",
2999
3430
  "add it to listeners.json, or delete it",
3000
3431
  ],
3001
3432
  [
@@ -3007,7 +3438,7 @@ export const CHECK_RULES = Object.freeze(
3007
3438
  [
3008
3439
  "workflow-shape",
3009
3440
  "error",
3010
- "a global/workflows/<table>.ts whose column, initial, states or actions are not written out as literals (docs/adr/0103)",
3441
+ "a global/workflows/<table>.ts whose column, initial, states or actions are not written out as literals (docs/adr/0227)",
3011
3442
  "write column and initial as strings and states and actions as object literals, each automatic action with auto: true",
3012
3443
  ],
3013
3444
  [
@@ -3051,7 +3482,7 @@ export const CHECK_RULES = Object.freeze(
3051
3482
  [
3052
3483
  "integration-literal",
3053
3484
  "error",
3054
- "context.integration(...) with anything but a string literal name (docs/adr/0092)",
3485
+ "context.integration(...) with anything but a string literal name (docs/adr/0231)",
3055
3486
  'context.integration("<name>"), the name an Admin set with ez integration set',
3056
3487
  ],
3057
3488
  [
@@ -3069,19 +3500,19 @@ export const CHECK_RULES = Object.freeze(
3069
3500
  [
3070
3501
  "disable-comment",
3071
3502
  "warning",
3072
- "an eslint-disable or oxlint-disable comment: Site code has no escape hatch, so it turns nothing off (docs/adr/0121)",
3503
+ "an eslint-disable or oxlint-disable comment: Site code has no escape hatch, so it turns nothing off (docs/adr/0236)",
3073
3504
  "fix the finding it meant to hide, and delete the comment",
3074
3505
  ],
3075
3506
  [
3076
3507
  "@typescript-eslint/switch-exhaustiveness-check",
3077
3508
  "warning",
3078
- "a switch over a union (a CHECK list's values, a workflow's states) that names neither every member nor a default (docs/adr/0154)",
3509
+ "a switch over a union (a CHECK list's values, a workflow's states) that names neither every member nor a default (docs/adr/0236)",
3079
3510
  "add a case for each value the message lists, or a default (an empty column's null need not be named)",
3080
3511
  ],
3081
3512
  [
3082
3513
  "floating-write",
3083
3514
  "warning",
3084
- "a db write or server-function call whose promise nobody awaits (one handed to a component whose prop takes a promise passes, docs/adr/0154)",
3515
+ "a db write or server-function call whose promise nobody awaits (one handed to a component whose prop takes a promise passes, docs/adr/0236)",
3085
3516
  "one click: onClick={() => run(() => db.update(...))}; a form: await it in useActionState(attempt(async () => ...), null)",
3086
3517
  ],
3087
3518
  [
@@ -3102,23 +3533,11 @@ export const CHECK_RULES = Object.freeze(
3102
3533
  "a list key from the .map index",
3103
3534
  "use the row's id as key: key={row.id}",
3104
3535
  ],
3105
- [
3106
- "ne-nullable",
3107
- "warning",
3108
- "{ col: { ne: x } } on a nullable column: it also drops rows where col is NULL (a type error too on a Table named in the code, docs/adr/0154)",
3109
- "{ nin: [x] } keeps the NULL rows, { nin: [x], null: false } drops them; ne only on id and created_at",
3110
- ],
3111
- [
3112
- "reduce-rows",
3113
- "warning",
3114
- "a total or count computed from capped rows (1000 at most): .reduce, a filtered .length, or a loop adding up per row or per group",
3115
- "use useLive.aggregate / useLive.count / db.aggregate",
3116
- ],
3117
3536
  [
3118
3537
  "filter-rows",
3119
3538
  "warning",
3120
3539
  "capped rows (100 by default) searched, filtered or paged in the page by what the user typed or picked",
3121
- "put the condition in the query's where ({ col: { like } }) and paging in limit/offset; show useLive.query's truncated",
3540
+ "put the condition in the query's where ({ col: { contains } }) and paging in limit/offset; show useLive.query's truncated",
3122
3541
  ],
3123
3542
  [
3124
3543
  "in-list-size",
@@ -3126,12 +3545,6 @@ export const CHECK_RULES = Object.freeze(
3126
3545
  "an in filter built from a query whose limit is above 400",
3127
3546
  "split the list into chunks, or filter on a column instead",
3128
3547
  ],
3129
- [
3130
- "fn-op-budget",
3131
- "warning",
3132
- "a write inside a loop that is unbounded or may run more than 250 times (900 if it reads Date.now()) in a server function or job",
3133
- "a call has 5 seconds of database time and 1,000 database operations: use insertMany, updateMany or deleteMany with a limit (ez help functions), bound the loop, or write in chunks from several calls",
3134
- ],
3135
3548
  [
3136
3549
  "redundant-transaction",
3137
3550
  "warning",
@@ -3153,43 +3566,49 @@ export const CHECK_RULES = Object.freeze(
3153
3566
  [
3154
3567
  "schema-real-money",
3155
3568
  "warning",
3156
- "a REAL column named like money (price, amount, total, ...) (docs/adr/0107)",
3569
+ "a REAL column named like money (price, amount, total, ...) (docs/adr/0217)",
3157
3570
  "declare <col> MONEY: whole cents, typed Cents; convert input with toCents()",
3158
3571
  ],
3159
3572
  [
3160
3573
  "table-cast",
3161
3574
  "warning",
3162
- 'a cast in a Table argument (name as "orders") or to Query, Insert, Update, Where or Row (docs/adr/0109)',
3163
- "a Table named at run time: db.table(name) or useLive.table(name, query); otherwise a literal name and no cast",
3575
+ 'a cast in a Table argument (name as "orders") or to Query, Insert, Update, Where or Row (docs/adr/0222)',
3576
+ "a Table or History named at run time: db.table(name) or useLive.table(name, query); otherwise a literal name and no cast",
3164
3577
  ],
3165
3578
  [
3166
3579
  "query-sentinel",
3167
3580
  "warning",
3168
- 'an empty id cast to match nothing: where: { id: "" as Id<...> } (docs/adr/0109)',
3581
+ 'an empty id cast to match nothing: where: { id: "" as Id<...> } (docs/adr/0222)',
3169
3582
  "skip the query: useLive(table, null), useLive.query(table, null), useLive.count(table, null)",
3170
3583
  ],
3171
3584
  [
3172
3585
  "error-text-match",
3173
3586
  "warning",
3174
- "an error's message tested for words: errorMessage(e).includes(...), /x/.test(e.message) (docs/adr/0109)",
3587
+ "an error's message tested for words: errorMessage(e).includes(...), /x/.test(e.message) (docs/adr/0222)",
3175
3588
  'test the code: e instanceof WriteError && e.code === "unique"',
3176
3589
  ],
3177
3590
  [
3178
3591
  "enum-literal-copy",
3179
3592
  "warning",
3180
- "an array of strings that copies a CHECK list from global/db/schema.sql (docs/adr/0109)",
3593
+ "an array of strings that copies a CHECK list from global/db/schema.sql, in a page, component, hook or constants.ts; server code, which cannot read the descriptor, keeps its own (docs/adr/0222)",
3181
3594
  'read schema.column("<table>", "<col>")?.values, or let RecordForm and RecordList draw the choices',
3182
3595
  ],
3183
3596
  [
3184
3597
  "inline-style",
3185
3598
  "warning",
3186
- "a JSX style={{ ... }} whose every value is a literal (docs/adr/0108)",
3599
+ "a JSX style={{ ... }} whose every value is a literal (docs/adr/0215)",
3187
3600
  "move these to a class in style.css and use className",
3188
3601
  ],
3602
+ [
3603
+ "theme-override",
3604
+ "warning",
3605
+ "a Site's style.css that sets a token of the Theme (global/style.css) or restyles a selector the Theme styles, such as body, input or .row (docs/adr/0210)",
3606
+ "change the Theme in global/style.css, or use a name and a class of the Site's own",
3607
+ ],
3189
3608
  ]).map(([id, severity, summary, fix]) => Object.freeze({ id, severity, summary, fix })),
3190
3609
  );
3191
3610
 
3192
- /** The date before which no warning in `CHECK_RULES` becomes an error (docs/adr/0078). */
3611
+ /** The date before which no warning in `CHECK_RULES` becomes an error (docs/adr/0236). */
3193
3612
  const WARNINGS_UNTIL = "2026-12-01";
3194
3613
 
3195
3614
  /** @type {typeof import("./commands.d.mts").helpRules} */
@@ -3290,7 +3709,7 @@ export const RESERVED_INSTANCE_IDS = new Set([
3290
3709
  "agents",
3291
3710
  "i",
3292
3711
  "s",
3293
- // Names under the managed domain that are not Instances (ADR 0064).
3712
+ // Names under the managed domain that are not Instances (ADR 0245).
3294
3713
  "www",
3295
3714
  "chatgpt",
3296
3715
  // The Developers' admin portal, a Worker beside the Studio (ezship-ops).
@@ -3303,49 +3722,29 @@ export function isValidInstanceId(id) {
3303
3722
  }
3304
3723
 
3305
3724
  /**
3306
- * Site ids are permanent and public. The platform assigns random IDs at creation (ADR 0032);
3307
- * this shape also accepts existing named IDs, whose links remain valid.
3725
+ * Site ids are permanent and public: 12 characters of Crockford's base 32 in lowercase (no i, l, o or u), which
3726
+ * the platform draws at random when it creates the Site (ADR 0201).
3308
3727
  * @type {typeof import("./commands.d.mts").SITE_ID_RE}
3309
3728
  */
3310
- export const SITE_ID_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
3311
- /**
3312
- * Path segments the Worker or studio use themselves; never a Site id.
3313
- * @type {typeof import("./commands.d.mts").RESERVED_SITE_IDS}
3314
- */
3315
- export const RESERVED_SITE_IDS = new Set([
3316
- "app",
3317
- "s",
3318
- "i",
3319
- "api",
3320
- "auth",
3321
- "studio",
3322
- "static",
3323
- "assets",
3324
- "cli",
3325
- "preview",
3326
- "agents",
3327
- "settings",
3328
- "global", // the Global Workspace's target id
3329
- ]);
3330
-
3729
+ export const SITE_ID_RE = /^[0-9a-hjkmnp-tv-z]{12}$/;
3331
3730
  /** @type {typeof import("./commands.d.mts").isValidSiteId} */
3332
3731
  export function isValidSiteId(id) {
3333
- return typeof id === "string" && SITE_ID_RE.test(id) && !RESERVED_SITE_IDS.has(id);
3732
+ return typeof id === "string" && SITE_ID_RE.test(id);
3334
3733
  }
3335
3734
 
3336
3735
  /**
3337
- * An Instance folder on disk holds `global/` and `sites/<folder>/`, one per Site (ADR 0079).
3736
+ * An Instance folder on disk holds `global/` and `sites/<folder>/`, one per Site (ADR 0205).
3338
3737
  * @type {typeof import("./commands.d.mts").SITES_FOLDER}
3339
3738
  */
3340
3739
  export const SITES_FOLDER = "sites";
3341
3740
  /**
3342
- * The folder names an Instance folder keeps for itself; no Site name may slugify to one (ADR 0079).
3741
+ * The folder names an Instance folder keeps for itself; no Site name may slugify to one (ADR 0205).
3343
3742
  * @type {typeof import("./commands.d.mts").RESERVED_FOLDER_NAMES}
3344
3743
  */
3345
3744
  export const RESERVED_FOLDER_NAMES = new Set([GLOBAL_ID, SITES_FOLDER]);
3346
3745
 
3347
3746
  /**
3348
- * A display name as a folder name: lowercase, hyphen-separated, never empty (ADR 0034).
3747
+ * A display name as a folder name: lowercase, hyphen-separated, never empty (ADR 0205).
3349
3748
  * @type {typeof import("./commands.d.mts").siteFolderName}
3350
3749
  */
3351
3750
  export function siteFolderName(name) {
@@ -3366,7 +3765,7 @@ export function siteNameError(name) {
3366
3765
  return null;
3367
3766
  }
3368
3767
 
3369
- // ---- Previews (docs/adr/0013) ---------------------------------------------------------------------------
3768
+ // ---- Previews (docs/adr/0212) ---------------------------------------------------------------------------
3370
3769
 
3371
3770
  /**
3372
3771
  * The path segment under a Site's prefix that serves a Preview: <prefix>/~preview/<id>/.
@@ -3386,13 +3785,13 @@ export const MAX_PREVIEWS_PER_BUILDER = 10;
3386
3785
  */
3387
3786
  export const PREVIEW_IDLE_MS = 7 * 24 * 60 * 60 * 1000;
3388
3787
  /**
3389
- * One-time app links (docs/adr/0059): `ez link` opens the app or a Preview signed in as the caller's own
3788
+ * One-time app links (docs/adr/0203): `ez link` opens the app or a Preview signed in as the caller's own
3390
3789
  * Member identity; the link works once, within this long.
3391
3790
  * @type {typeof import("./commands.d.mts").APP_LINK_TTL_MS}
3392
3791
  */
3393
3792
  export const APP_LINK_TTL_MS = 5 * 60 * 1000;
3394
3793
  /**
3395
- * Support Requests (docs/adr/0080): a subject and a body for the Host's Developers, a few a day per Builder.
3794
+ * Support Requests (docs/adr/0208): a subject and a body for the Host's Developers, a few a day per Builder.
3396
3795
  * @type {typeof import("./commands.d.mts").SUPPORT_SUBJECT_MAX}
3397
3796
  */
3398
3797
  export const SUPPORT_SUBJECT_MAX = 200;
@@ -3401,7 +3800,7 @@ export const SUPPORT_BODY_MAX = 20_000;
3401
3800
  /** @type {typeof import("./commands.d.mts").SUPPORT_REQUESTS_PER_DAY} */
3402
3801
  export const SUPPORT_REQUESTS_PER_DAY = 10;
3403
3802
 
3404
- // ---- Emails (docs/adr/0149) ---------------------------------------------------------------------------
3803
+ // ---- Emails (docs/adr/0234) ---------------------------------------------------------------------------
3405
3804
 
3406
3805
  /**
3407
3806
  * What `email.send` takes and how much the Host sends: Emails per invocation, the subject's and the body's
@@ -3429,7 +3828,7 @@ export const EMAIL_STATUSES = Object.freeze([
3429
3828
  "dropped",
3430
3829
  ]);
3431
3830
 
3432
- // ---- Integrations (docs/adr/0092, 0094) -----------------------------------------------------------------
3831
+ // ---- Integrations (docs/adr/0231) -----------------------------------------------------------------
3433
3832
  //
3434
3833
  // An Instance's named external services, set by Admins, called by server code with a credential it never
3435
3834
  // sees. The names, kinds, credential types and limits are data here, for the CLI, the Pipeline and the Host.
@@ -3459,7 +3858,7 @@ export const INTEGRATION_LIMITS = Object.freeze({
3459
3858
  inFlightPerInstance: 4,
3460
3859
  perSecond: 10,
3461
3860
  burst: 60,
3462
- // ADR 0138: a binding's values, the headers it may add in all, and the shortest secret the Host looks
3861
+ // ADR 0231: a binding's values, the headers it may add in all, and the shortest secret the Host looks
3463
3862
  // for in an answer (and shows a hint of).
3464
3863
  valuesPerBinding: 20,
3465
3864
  addedHeaderBytes: 8192,
@@ -3539,7 +3938,7 @@ export function basicUserError(user) {
3539
3938
  return null;
3540
3939
  }
3541
3940
 
3542
- // ---- OAuth (docs/adr/0140, a draft) --------------------------------------------------------------------
3941
+ // ---- OAuth (docs/adr/0252, a draft) --------------------------------------------------------------------
3543
3942
  //
3544
3943
  // An OAuth credential is stored and listed, and every call on it is refused `grant` ("not connected"),
3545
3944
  // until the draft's flows (connect, the callback, refresh) are built. Presets are provider facts, data here.
@@ -3553,10 +3952,10 @@ export const OAUTH_CLIENT_AUTH = Object.freeze(/** @type {const} */ (["basic", "
3553
3952
  /** What `ez integration` says of an OAuth credential while the draft's flows are not built. */
3554
3953
  /** @type {typeof import("./commands.d.mts").OAUTH_NOT_BUILT} */
3555
3954
  export const OAUTH_NOT_BUILT =
3556
- "OAuth flows are not implemented yet (ADR 0140, a draft): the credential is stored, but nothing can connect it, so every call is refused until they are.";
3955
+ "OAuth flows are not implemented yet (ADR 0231, a draft): the credential is stored, but nothing can connect it, so every call is refused until they are.";
3557
3956
 
3558
3957
  /**
3559
- * Providers whose OAuth facts are certain (docs/adr/0140): the API's origin and its sandbox's, the URLs, the
3958
+ * Providers whose OAuth facts are certain (docs/adr/0231): the API's origin and its sandbox's, the URLs, the
3560
3959
  * default scopes, the client's authentication, and the plain values every request needs.
3561
3960
  * @type {typeof import("./commands.d.mts").OAUTH_PRESETS}
3562
3961
  */
@@ -3643,9 +4042,9 @@ export function oauthCredentialError(c, allowHttp = false) {
3643
4042
  return null;
3644
4043
  }
3645
4044
 
3646
- // ---- invites (docs/adr/0025) ----------------------------------------------------------------------------
4045
+ // ---- invites (docs/adr/0202) ----------------------------------------------------------------------------
3647
4046
  //
3648
- // An invite is a pre-created identity row (docs/adr/0002) that the person claims by signing in. It is claimable
4047
+ // An invite is a pre-created identity row (docs/adr/0202) that the person claims by signing in. It is claimable
3649
4048
  // for INVITE_TTL_MS after the last invite from any Instance; re-adding the person restarts the window.
3650
4049
 
3651
4050
  /** @type {typeof import("./commands.d.mts").INVITE_TTL_MS} */
@@ -3752,7 +4151,7 @@ export const ROUTES = Object.freeze({
3752
4151
  instanceStatus: { method: "GET", path: INSTANCE },
3753
4152
  updateInstance: { method: "PATCH", path: INSTANCE, args: (patch) => body(patch) },
3754
4153
  listAudit: { method: "GET", path: `${INSTANCE}/audit`, args: (filter) => ({ query: filter }) },
3755
- // the App Database is the Instance's (docs/adr/0007): no Site in the path
4154
+ // the App Database is the Instance's (docs/adr/0217): no Site in the path
3756
4155
  dbSchema: { method: "GET", path: `${INSTANCE}/db/schema` },
3757
4156
  dbTables: { method: "GET", path: `${INSTANCE}/db/tables` },
3758
4157
  dbSql: { method: "POST", path: `${INSTANCE}/db/sql`, args: (statement) => body({ statement }) },
@@ -3762,15 +4161,15 @@ export const ROUTES = Object.freeze({
3762
4161
  args: (table, query) => ({ params: { table }, body: query }),
3763
4162
  },
3764
4163
  dbActors: { method: "POST", path: `${INSTANCE}/db/actors`, args: (query) => body(query) },
3765
- // A read-only query as one Member sees the rows (docs/adr/0098), for testing access rules.
4164
+ // A read-only query as one Member sees the rows (docs/adr/0225), for testing access rules.
3766
4165
  dbQueryAs: {
3767
4166
  method: "POST",
3768
4167
  path: `${INSTANCE}/db/query/:table`,
3769
4168
  args: (table, as, query) => ({ params: { table }, body: { as, query } }),
3770
4169
  },
3771
- // the one write to a History (docs/adr/0106); Admins only, and no Site code reaches it
4170
+ // the one write to a History (docs/adr/0218); Admins only, and no Site code reaches it
3772
4171
  dbRedact: { method: "POST", path: `${INSTANCE}/db/redact`, args: (input) => body(input) },
3773
- // App Attachments (docs/adr/0047); the bytes go to the ticket's URL (`.../db/attachments/:id/bytes`), outside this table
4172
+ // App Attachments (docs/adr/0221); the bytes go to the ticket's URL (`.../db/attachments/:id/bytes`), outside this table
3774
4173
  requestAttachment: {
3775
4174
  method: "POST",
3776
4175
  path: `${INSTANCE}/db/attachments`,
@@ -3797,24 +4196,24 @@ export const ROUTES = Object.freeze({
3797
4196
  args: (id, status) => ({ params: { id }, body: { status } }),
3798
4197
  },
3799
4198
  removeUser: { method: "DELETE", path: `${INSTANCE}/users/:id`, args: byId },
3800
- // Member groups on the roster (docs/adr/0098): the whole list at once.
4199
+ // Member groups on the roster (docs/adr/0225): the whole list at once.
3801
4200
  setUserGroups: {
3802
4201
  method: "PUT",
3803
4202
  path: `${INSTANCE}/users/:id/groups`,
3804
4203
  args: (id, groups) => ({ params: { id }, body: { groups } }),
3805
4204
  },
3806
- // Support Requests to the Host's Developers (docs/adr/0080)
4205
+ // Support Requests to the Host's Developers (docs/adr/0208)
3807
4206
  openSupportRequest: { method: "POST", path: `${INSTANCE}/support`, args: (input) => body(input) },
3808
4207
  listSupportRequests: { method: "GET", path: `${INSTANCE}/support` },
3809
4208
  supportRequest: { method: "GET", path: `${INSTANCE}/support/:id`, args: byId },
3810
- // Emails server code sent (docs/adr/0149): every Builder reads them; a Limited Builder only their Sites'.
4209
+ // Emails server code sent (docs/adr/0234): every Builder reads them; a Limited Builder only their Sites'.
3811
4210
  listEmails: {
3812
4211
  method: "GET",
3813
4212
  path: `${INSTANCE}/emails`,
3814
4213
  args: (filter) => ({ query: { ...filter } }),
3815
4214
  },
3816
4215
  emailInfo: { method: "GET", path: `${INSTANCE}/emails/:id`, args: byId },
3817
- // Integrations (docs/adr/0092): Admins set them; every Builder lists them and their calls.
4216
+ // Integrations (docs/adr/0231): Admins set them; every Builder lists them and their calls.
3818
4217
  listIntegrations: { method: "GET", path: `${INSTANCE}/integrations` },
3819
4218
  setIntegration: {
3820
4219
  method: "PUT",
@@ -3826,7 +4225,7 @@ export const ROUTES = Object.freeze({
3826
4225
  path: `${INSTANCE}/integrations/:name/preview`,
3827
4226
  args: (name, input) => ({ params: { name }, body: input }),
3828
4227
  },
3829
- // ADR 0138: one header or parameter the Host adds to a binding's every request.
4228
+ // ADR 0231: one header or parameter the Host adds to a binding's every request.
3830
4229
  setIntegrationValue: {
3831
4230
  method: "PUT",
3832
4231
  path: `${INSTANCE}/integrations/:name/values`,
@@ -3855,7 +4254,7 @@ export const ROUTES = Object.freeze({
3855
4254
  path: `${INSTANCE}/integrations/:name/test`,
3856
4255
  args: (name, input) => ({ params: { name }, body: input }),
3857
4256
  },
3858
- // the Instance's schedules (ADRs 0076, 0136), from the pushed global/schedules.json; ADR 0120: a pause is
4257
+ // the Instance's schedules (ADR 0230), from the pushed global/schedules.json; ADR 0230: a pause is
3859
4258
  // the Host's, on the active schedule, and a resume never catches up
3860
4259
  listSchedules: { method: "GET", path: `${INSTANCE}/schedules` },
3861
4260
  listScheduleRuns: {
@@ -3878,15 +4277,10 @@ export const ROUTES = Object.freeze({
3878
4277
  path: `${INSTANCE}/schedules/:name/resume`,
3879
4278
  args: (name) => ({ params: { name } }),
3880
4279
  },
3881
- // the Instance's assets (docs/adr/0014); the bytes go to the ticket's URL, outside this table
4280
+ // the Instance's assets (docs/adr/0213); the bytes go to the ticket's URL, outside this table
3882
4281
  listAssets: { method: "GET", path: `${INSTANCE}/assets` },
3883
4282
  requestUpload: { method: "POST", path: `${INSTANCE}/assets`, args: (input) => body(input) },
3884
4283
  finalizeUpload: { method: "POST", path: `${INSTANCE}/assets/:id/ready`, args: byId },
3885
- deleteAsset: {
3886
- method: "DELETE",
3887
- path: `${INSTANCE}/assets/:id`,
3888
- args: (id, force) => ({ params: { id }, query: force ? { force: 1 } : {} }),
3889
- },
3890
4284
  // the Site
3891
4285
  remoteStatus: { method: "GET", path: `${SITE}/workspace` },
3892
4286
  updateSettings: { method: "PATCH", path: `${SITE}/workspace`, args: (patch) => body(patch) },
@@ -3895,12 +4289,12 @@ export const ROUTES = Object.freeze({
3895
4289
  pushAll: {
3896
4290
  method: "POST",
3897
4291
  path: `${SITE}/push`,
3898
- // `options`: the message (docs/adr/0093) and a Global push's dryRun, acknowledgeExposure and force
3899
- // (docs/adr/0096, 0098).
4292
+ // `options`: the message (docs/adr/0211) and a Global push's dryRun, acknowledgeExposure and force
4293
+ // (docs/adr/0224, 0225).
3900
4294
  args: (files, prune, deleted = [], options = {}) => body({ files, prune, deleted, ...options }),
3901
4295
  },
3902
4296
  deploy: { method: "POST", path: `${SITE}/deploy` },
3903
- // Listeners (docs/adr/0092): any Builder of the Site; a secret travels once, in a PUT's body.
4297
+ // Listeners (docs/adr/0231): any Builder of the Site; a secret travels once, in a PUT's body.
3904
4298
  listListeners: { method: "GET", path: `${SITE}/listeners` },
3905
4299
  setListenerSecret: {
3906
4300
  method: "PUT",
@@ -3927,7 +4321,7 @@ export const ROUTES = Object.freeze({
3927
4321
  path: `${SITE}/listeners/:name/events/:id/retry`,
3928
4322
  args: (name, id) => ({ params: { name, id } }),
3929
4323
  },
3930
- // API Keys (docs/adr/0119, docs/adr/0151): the Instance's; Admins create and revoke, every Builder lists.
4324
+ // API Keys (docs/adr/0232): the Instance's; Admins create and revoke, every Builder lists.
3931
4325
  listApiKeys: { method: "GET", path: `${INSTANCE}/keys` },
3932
4326
  createApiKey: { method: "POST", path: `${INSTANCE}/keys`, args: (input) => body(input) },
3933
4327
  revokeApiKey: {
@@ -3946,7 +4340,7 @@ export const ROUTES = Object.freeze({
3946
4340
  args: (files, global) => body({ files, ...(global ? { global } : {}) }),
3947
4341
  },
3948
4342
  format: { method: "POST", path: `${SITE}/format`, args: (files) => body({ files }) },
3949
- // Documents (docs/adr/0105): in a Site a queued Render; in the Global Workspace (`files`) an immediate one
4343
+ // Documents (docs/adr/0233): in a Site a queued Render; in the Global Workspace (`files`) an immediate one
3950
4344
  renderDocument: {
3951
4345
  method: "POST",
3952
4346
  path: `${SITE}/renders`,
@@ -3977,7 +4371,7 @@ export const ROUTES = Object.freeze({
3977
4371
  denyBuilder: { method: "DELETE", path: `${SITE}/access/builders/:id`, args: byId },
3978
4372
  allowUser: { method: "POST", path: `${SITE}/access/members`, args: (id) => body({ id }) },
3979
4373
  denyUser: { method: "DELETE", path: `${SITE}/access/members/:id`, args: byId },
3980
- // A Restricted Site's groups (docs/adr/0101): their Members may open it too.
4374
+ // A Restricted Site's groups (docs/adr/0225): their Members may open it too.
3981
4375
  allowGroup: {
3982
4376
  method: "POST",
3983
4377
  path: `${SITE}/access/groups`,
@@ -4090,7 +4484,7 @@ export const AUDIT_KINDS = Object.freeze([
4090
4484
  "site.archive",
4091
4485
  "site.config",
4092
4486
  "site.access",
4093
- "builder.password-setup", // Historical (docs/adr/0025 retired setup links); events remain readable.
4487
+ "builder.password-setup", // Historical (docs/adr/0202 retired setup links); events remain readable.
4094
4488
  "member.password-setup",
4095
4489
  "builder.add",
4096
4490
  "builder.role",
@@ -4100,28 +4494,28 @@ export const AUDIT_KINDS = Object.freeze([
4100
4494
  "member.unblock",
4101
4495
  "member.remove",
4102
4496
  "member.session",
4103
- "member.groups", // a Member's roster groups changed (docs/adr/0098)
4497
+ "member.groups", // a Member's roster groups changed (docs/adr/0225)
4104
4498
  "files.push",
4105
4499
  "deploy",
4106
4500
  "preview.schema",
4107
4501
  "asset.add",
4108
4502
  "asset.remove",
4109
4503
  "db.sql", // a write through `ez db sql`; details keep the capped statement text
4110
- "db.attach", // `ez db attach`: an attachment bound to a row (docs/adr/0047)
4111
- "db.query-as", // `ez db query --as`: a Builder read rows as one Member sees them (docs/adr/0098)
4112
- "schedule.run", // `ez schedule run`: a schedule's job run now (docs/adr/0076)
4113
- "schedule.pause", // `ez schedule pause`: a schedule's due times stopped (docs/adr/0120)
4504
+ "db.attach", // `ez db attach`: an attachment bound to a row (docs/adr/0221)
4505
+ "db.query-as", // `ez db query --as`: a Builder read rows as one Member sees them (docs/adr/0225)
4506
+ "schedule.run", // `ez schedule run`: a schedule's job run now (docs/adr/0230)
4507
+ "schedule.pause", // `ez schedule pause`: a schedule's due times stopped (docs/adr/0230)
4114
4508
  "schedule.resume", // `ez schedule resume`: started again from now
4115
- "integration.set", // an Integration's production binding, Sites or timeout (docs/adr/0092)
4509
+ "integration.set", // an Integration's production binding, Sites or timeout (docs/adr/0231)
4116
4510
  "integration.preview", // an Integration's Preview binding
4117
- "integration.value", // a header or parameter a binding adds (docs/adr/0138); a secret one never in details
4511
+ "integration.value", // a header or parameter a binding adds (docs/adr/0231); a secret one never in details
4118
4512
  "integration.remove",
4119
4513
  "integration.test", // `ez integration test`: one request, its path omitted
4120
- "listener.secret", // a Listener's verification secret set or removed (docs/adr/0092)
4514
+ "listener.secret", // a Listener's verification secret set or removed (docs/adr/0231)
4121
4515
  "listener.retry", // a dead event put back to pending
4122
- "api.key", // an API Key created or revoked (docs/adr/0119); never the key
4123
- "document.render", // `ez document render` or `ez global document render` (docs/adr/0105)
4124
- "db.redact", // `ez db redact`: columns blanked in rows and their History (docs/adr/0106); never values
4516
+ "api.key", // an API Key created or revoked (docs/adr/0232); never the key
4517
+ "document.render", // `ez document render` or `ez global document render` (docs/adr/0233)
4518
+ "db.redact", // `ez db redact`: columns blanked in rows and their History (docs/adr/0218); never values
4125
4519
  ]);
4126
4520
 
4127
4521
  // ---- change tracking -----------------------------------------------------------------------------------
@@ -4170,7 +4564,7 @@ export const countChanges = (c) => c.added.length + c.modified.length + c.delete
4170
4564
  // Tags say what kind of statement a line is: [check] ez check (and push/preview/deploy) refuses it with a rule
4171
4565
  // id, [runtime] the Host refuses or limits it when it runs, [advice] a default to follow that nothing checks.
4172
4566
 
4173
- /** `ez help` and `ez help lifecycle`: what each command reads, changes and shows (docs/adr/0013, 0016, 0021, 0096). */
4567
+ /** `ez help` and `ez help lifecycle`: what each command reads, changes and shows (docs/adr/0212, 0210, 0217, 0224). */
4174
4568
  const LIFECYCLE = `The lifecycle: what each command builds from, changes and shows. There are six states: your Site files
4175
4569
  (this Working Copy), your Global files (global/ beside it), the pushed Site and Global Versions (the Shared
4176
4570
  Files every Builder pulls), the deployed Site (a build Members use), the published schema (global
@@ -4237,6 +4631,11 @@ const SITE_FILES = `${aligned([
4237
4631
  "custom hooks, one per file, `export default function use<Name>()`, no markup",
4238
4632
  "ez help frame",
4239
4633
  ],
4634
+ [
4635
+ `${LIB_DIR}<name>.ts`,
4636
+ "this Site's own helpers: named exports, pure TypeScript, imported as ./lib/<name>",
4637
+ "ez help functions",
4638
+ ],
4240
4639
  [
4241
4640
  `${FUNCTIONS_DIR}<name>.ts`,
4242
4641
  "server functions: default-export serverFunction(inputSchema, handler)",
@@ -4355,7 +4754,7 @@ files. What a React developer reaches for, and what to write here:
4355
4754
  ${aligned([
4356
4755
  [
4357
4756
  "load data, live",
4358
- 'useLive("orders", { where: { status: "open" } }); useLive.count, useLive.aggregate',
4757
+ 'useLive.query("orders", { where: { status: "open" } }) -> { rows, truncated, loading }; useLive.count',
4359
4758
  "data",
4360
4759
  ],
4361
4760
  [
@@ -4383,6 +4782,11 @@ ${aligned([
4383
4782
  "functions/<name>.ts: serverFunction(z.object(...), handler)",
4384
4783
  "functions",
4385
4784
  ],
4785
+ [
4786
+ "a rule nobody may get around",
4787
+ "a function that checks, then writes; WRITE <table> BY functions; a Table rule; a workflow",
4788
+ "recipes, db",
4789
+ ],
4386
4790
  [
4387
4791
  "logic pages and functions share",
4388
4792
  "global/lib/<name>.ts: named exports, the db passed in",
@@ -4401,6 +4805,7 @@ ${aligned([
4401
4805
  ["a viewer's preference across pages", 'useSession("activeCompanyId"), Session State', "frame"],
4402
4806
  ["state a link carries", 'useSearchParam("state"); <Link to="/orders?state=open">', "frame"],
4403
4807
  ["stateful logic components share", "hooks/use<Name>.ts, a custom hook", "frame"],
4808
+ ["helpers only this Site uses", "lib/<name>.ts: named exports, pure TypeScript", "functions"],
4404
4809
  ["routes", "pages/<route>.tsx; <Link to>, useNavigate(), useParams()", "files"],
4405
4810
  [
4406
4811
  "who sees which rows",
@@ -4412,7 +4817,7 @@ ${aligned([
4412
4817
  "useAuth() -> { user, membership, me, groups }; sign-in is the platform's",
4413
4818
  "access",
4414
4819
  ],
4415
- ["styling", "className and style.css; the global theme loads first", "files"],
4820
+ ["styling", "className, the Theme's tokens and classes; style.css adds a Site's own", "files"],
4416
4821
  [
4417
4822
  "cron, webhooks, desktop files, PDFs",
4418
4823
  "jobs/, listeners/, local/, global/documents/",
@@ -4420,12 +4825,13 @@ ${aligned([
4420
4825
  ],
4421
4826
  ])}
4422
4827
  Restrictions, each with its replacement:
4423
- [check] From react only useState, useActionState, useTransition, startTransition, useOptimistic and types:
4424
- no useEffect, useRef, useMemo, useCallback, createContext or useContext (data comes from useLive and
4425
- useCall, the React Compiler memoizes, frame values are useProvided). (no-restricted-imports)
4828
+ [check] From react only useState, useActionState, useTransition, startTransition, useOptimistic, useMemo,
4829
+ useCallback and types: no useEffect, useRef, createContext or useContext (data comes from useLive
4830
+ and useCall, frame values are useProvided; the React Compiler memoizes, so useMemo and
4831
+ useCallback are never needed). (no-restricted-imports)
4426
4832
  [check] No fetch, window, document, timers or storage: db and useLive for data, Integrations for other
4427
- services, useSession for preferences, useInterval and useDebounced for time. confirm(), alert()
4428
- and prompt() are allowed in event handlers. (no-restricted-globals)
4833
+ services, useSession for preferences, useInterval and useDebounced for time. confirm(), alert(),
4834
+ prompt() and print() are allowed in event handlers. (no-restricted-globals)
4429
4835
  [check] No packages but recharts, no URLs, dynamic import() or file extensions in imports; only what
4430
4836
  \`ez help files\` lists. Pages are never imported. (import)
4431
4837
  [check] No classes; constants.ts holds plain values only. (class, constant-shape)
@@ -4441,6 +4847,12 @@ Restrictions, each with its replacement:
4441
4847
  [runtime] Preview data is production data: every Preview write is real.
4442
4848
  [advice] Await every write; key list items by the row's id; use errorMessage(e), never \`e as Error\`;
4443
4849
  call hooks at the top of a component. (ez check warns on each: fix warnings too.)
4850
+ [advice] A rule the request states as never, only or must (steps in order, a hold, a gate before release)
4851
+ is enforced on the server, never by a hidden button or a check in a page, which a second tab or
4852
+ another Site gets around: a server function that reads, checks and writes in its one transaction,
4853
+ with \`WRITE <table> BY functions\` in access.sql so no page writes around it; a Table rule when
4854
+ every write of the Table must pass; a workflow when it is which moves a status may make. Record who
4855
+ did it from the function's user.me, never from a typed name. (ez help recipes: enforced-rule)
4444
4856
  [advice] One Site is one audience and a few pages: when a request needs another audience or grows past a
4445
4857
  few pages, say it belongs in another Site. A request outside this shape is a limit to report to
4446
4858
  the user, not a workaround to find.
@@ -4477,6 +4889,24 @@ for a problem in the code you are writing. Keep replies brief.
4477
4889
 
4478
4890
  ${LIFECYCLE}`;
4479
4891
 
4892
+ /**
4893
+ * The starter Theme's tokens, as `ez help files` names them: read from the Theme itself, so they cannot drift,
4894
+ * in lines of the help's width.
4895
+ */
4896
+ const THEME_TOKENS = [
4897
+ ...(/:root \{([^}]*)\}/.exec(STARTER_GLOBAL_FILES[STYLE_FILE])?.[1] ?? "").matchAll(
4898
+ /^\s*(--[\w-]+):/gm,
4899
+ ),
4900
+ ]
4901
+ .map((m) => m[1])
4902
+ .reduce((lines, name) => {
4903
+ const line = lines.at(-1);
4904
+ if (line && (line + ", " + name).length <= 104) lines[lines.length - 1] = line + ", " + name;
4905
+ else lines.push(name);
4906
+ return lines;
4907
+ }, /** @type {string[]} */ ([]))
4908
+ .join(",\n");
4909
+
4480
4910
  /** `ez help files`: the shapes and what each kind of file may import, from the contract's own messages. */
4481
4911
  const FILES_TOPIC = `Files and imports. The Site:
4482
4912
  ${SITE_FILES}
@@ -4484,12 +4914,15 @@ The Global Workspace:
4484
4914
  ${GLOBAL_FILES}
4485
4915
  [check] What each file may import (the same sentences ez check prints):
4486
4916
  Pages, components, hooks and App.tsx: ${IMPORT_SHAPE}
4487
- From react: useState, useActionState, useTransition, startTransition, useOptimistic and types. A page
4917
+ From react: useState, useActionState, useTransition, startTransition, useOptimistic, useMemo, useCallback
4918
+ and types. A global component is global/<Name> or, by its path, global/components/<Name>. A page
4488
4919
  imports \`import type { Provided } from "../App"\` for App.tsx's values (ez help frame).
4489
4920
  Server functions (functions/): @ezship/react/server (serverFunction, z and types), constants, sibling
4490
- functions, global/constants, global/lib/<name>, global/documents/<Name> and type-only global/db/types.
4491
- Listeners: @ezship/react/server, constants, global/constants, global/lib/<name>, type-only
4921
+ functions, ../lib/<name>, global/constants, global/lib/<name>, global/documents/<Name> and type-only
4922
+ global/db/types.
4923
+ Listeners: @ezship/react/server, constants, ../lib/<name>, global/constants, global/lib/<name>, type-only
4492
4924
  global/db/types and sibling functions (not global/documents); nothing imports a listener.
4925
+ Site lib (lib/): ${SITE_LIB_IMPORT_SHAPE}
4493
4926
  Global jobs (global/jobs/): @ezship/react/server, global/lib/<name>, global/constants and type-only
4494
4927
  global/db/types; nothing imports a job.
4495
4928
  Local functions (local/): @ezship/react/local, node:* built-ins, constants, sibling local functions and
@@ -4506,13 +4939,24 @@ Routes: the page file name is the route. index.tsx is /, orders.tsx is /orders,
4506
4939
  /orders/:id (useParams().id), orders.new.tsx is /orders/new. <Link to="/orders/42">, <Link to="/orders"
4507
4940
  site="kitchen"> (another Site of the Instance), useNavigate()(path), useSites() -> [{ id, name, url, current }].
4508
4941
  A Link to the open route has aria-current="page", to its section aria-current="true": style a[aria-current].
4509
- Styling: className and the Site's style.css; the global theme's classes (btn, btn primary, panel, field,
4510
- notice danger, badge, table.data, stack, row, muted, ...) come first. [check] CSS url(), @import and fonts
4511
- only through Assets: asset("logo") is the URL of an image an Admin uploaded with \`ez asset add\` (\`ez asset
4512
- ls\`). [advice] Move a style={{ ... }} of literals into a class (inline-style warns).`;
4513
-
4514
- /**
4515
- * The code blocks of the help topics, as data (docs/adr/0153): a topic prints `code`, and the Pipeline's
4942
+ A Link whose to names a query (/orders?state=open) is "page" only while the route's query has those values,
4943
+ so link tabs tell views of one route apart; /orders is then "true".
4944
+ Styling: className and the Site's style.css, which loads after the Theme (global/style.css). The Theme owns
4945
+ the look of every Site, with its tokens:
4946
+ ${THEME_TOKENS}
4947
+ (read global/style.css for this Instance's) and its classes (btn, btn primary, panel, field, notice danger,
4948
+ badge, table.data, stack, row, muted, ...), which the starter components draw with. [advice] A Site's style.css
4949
+ adds layout and classes of its own, and takes every colour, radius and shadow from a token (background:
4950
+ var(--surface); color: var(--text); border: 1px solid var(--line)): a literal colour does not follow the
4951
+ Theme, and a dark one under the Theme's text cannot be read. Never set a Theme token or restyle what the
4952
+ Theme styles (body, input, .row, .muted) from a Site (theme-override warns). A new look (a dark theme,
4953
+ another brand colour) is a change to the tokens in global/style.css, for every Site at once, when the
4954
+ request is for one. [check] CSS url(), @import and fonts only through Assets: asset("logo") is the URL of
4955
+ an image an Admin uploaded with \`ez asset add\` (\`ez asset ls\`). [advice] Move a style={{ ... }} of
4956
+ literals into a class (inline-style warns).`;
4957
+
4958
+ /**
4959
+ * The code blocks of the help topics, as data (docs/adr/0236): a topic prints `code`, and the Pipeline's
4516
4960
  * `help.test.ts` checks `before + code + after` as the file `path`, with no warnings, against the starter
4517
4961
  * Global Workspace and `HELP_SNIPPET_SCHEMA`. Change a block only to code that checks clean.
4518
4962
  * @type {readonly import("./commands.d.mts").HelpSnippet[]}
@@ -4544,10 +4988,10 @@ export default function Chart() {
4544
4988
  before: `import { useLive } from "@ezship/react";
4545
4989
 
4546
4990
  /** Analyses of received samples, with what each references. */
4547
- export default function Analyses({ like }: { like: string }) {
4991
+ export default function Analyses({ search }: { search: string }) {
4548
4992
  `,
4549
4993
  code: `const { rows } = useLive.query("analysis", {
4550
- where: { "sample_id.status": "received", or: [{ code: { like } }, { ref: { like } }] }, // paths filter before paging
4994
+ where: { "sample_id.status": "received", or: [{ code: { contains: search } }, { ref: { contains: search } }] }, // paths filter before paging
4551
4995
  include: { sample_id: ["code"], "sample_id.client_id": ["name"], analyst: ["name"], method_instrument: { instrument_id: ["title"] } },
4552
4996
  order: ["sort_key nulls last"],
4553
4997
  });
@@ -4633,9 +5077,9 @@ export const defaults: Saved & SignedIn = { activeCompanyId: null, favorites: []
4633
5077
  `,
4634
5078
  code: `import { useLive } from "@ezship/react";
4635
5079
  export default function useOpenOrders(customerId: string) {
4636
- const orders = useLive("orders", { where: { customer_id: customerId, status: "open" } });
5080
+ const orders = useLive.query("orders", { where: { customer_id: customerId, status: "open" } });
4637
5081
  const total = useLive.aggregate("orders", { where: { customer_id: customerId, status: "open" }, sum: ["amount"] });
4638
- return { orders, total: total.rows[0]?.sum.amount ?? 0 };
5082
+ return { orders: orders.rows, loading: orders.loading, total: total.rows[0]?.sum.amount ?? 0 };
4639
5083
  }
4640
5084
  `,
4641
5085
  },
@@ -4660,7 +5104,7 @@ export default serverFunction(z.object({ title: z.string().min(1) }), async ({ d
4660
5104
  /** Marks one page of items synced and says whether more remain. */
4661
5105
  export default serverFunction(z.object({}), async ({ db }) => {
4662
5106
  `,
4663
- code: `const { more } = await db.updateMany("items", { where: { synced: 0 }, limit: 100 }, { synced: 1 });
5107
+ code: `const { more } = await db.updateMany("items", { where: { synced: { ne: true } }, limit: 100 }, { synced: true });
4664
5108
  return { more };
4665
5109
  `,
4666
5110
  after: `});
@@ -4672,15 +5116,17 @@ return { more };
4672
5116
  path: "functions/syncSome.ts",
4673
5117
  before: `import { serverFunction, z } from "@ezship/react/server";
4674
5118
 
4675
- /** Marks items synced one by one for as long as the call has time. */
4676
- export default serverFunction(z.object({}), async ({ db }) => {
5119
+ /** Marks items synced one by one for as long as the call has time, and says whether more remain. */
5120
+ export default serverFunction(z.object({}), async ({ db, timeLeft }) => {
4677
5121
  `,
4678
- code: `const from = Date.now(); // in code that calls an integration, take it just before the first write
4679
- const rows = await db.list("items", { where: { synced: 0 }, limit: 900 });
5122
+ code: `const { rows, truncated } = await db.query("items", { where: { synced: { ne: true } }, limit: 500 });
5123
+ let done = 0;
4680
5124
  for (const row of rows) {
4681
- if (Date.now() - from > 4000) break;
4682
- await db.update("items", row.id, { synced: 1 });
5125
+ if (timeLeft() === 0) break;
5126
+ await db.update("items", row.id, { synced: true });
5127
+ done++;
4683
5128
  }
5129
+ return { more: truncated || done < rows.length };
4684
5130
  `,
4685
5131
  after: `});
4686
5132
  `,
@@ -4709,7 +5155,7 @@ CREATE TABLE orders (
4709
5155
  status TEXT CHECK (status IN ('open', 'shipped', 'paid')),
4710
5156
  amount MONEY
4711
5157
  );
4712
- CREATE TABLE items (title TEXT, hours REAL, synced INTEGER);
5158
+ CREATE TABLE items (title TEXT, hours REAL, synced BOOLEAN);
4713
5159
  CREATE TABLE accounting_periods (ends_on DATE, closed INTEGER);
4714
5160
  CREATE TABLE client (name TEXT);
4715
5161
  CREATE TABLE sample (
@@ -4747,42 +5193,52 @@ function snippet(name) {
4747
5193
  const DATA_TOPIC = `Data: reading and writing the App Database from pages, components and hooks (all from @ezship/react).
4748
5194
  Tables belong to the Instance: every Site shares them. Declare them in global/db/schema.sql (\`ez help db\`);
4749
5195
  types come from \`import type { Order } from "global/db/types"\`, and rows are Row<"orders">.
4750
- useLive("orders", { where: { status: "open" }, order: ["-created_at"] }) -> Row<"orders">[], re-renders when the table changes
4751
- useLive("orders", null) -> [] and no subscription: a query waiting on another's answer (never { id: "" })
4752
- useLive.query(table, query) / db.query(table, query) -> { rows, truncated } (live queries add loading)
5196
+ One read shape (docs/adr/0219): a read answers { rows, truncated }, live in a component and one-shot in a handler.
5197
+ const { rows, truncated, loading } = useLive.query("orders", { where: { status: "open" }, order: ["-created_at"] })
5198
+ -> rows: Row<"orders">[], re-rendered when the Table changes; truncated: more rows match than limit took
5199
+ const { rows, truncated } = await db.query("orders", query) -> the same read once, in an event handler or server code
5200
+ useLive.query("orders", null) -> no rows and no subscription: a query waiting on another's answer (never { id: "" })
5201
+ useLive("orders", query) and db.list("orders", query) are shorthand for the rows alone, for a read that cannot
5202
+ reach its limit (one parent's children, a short lookup Table); they cannot say that rows were left out
4753
5203
  useLive.count("orders", { where: { status: "shipped" } }) -> the complete count, undefined while loading
4754
5204
  useLive.aggregate("orders", { group: ["status"], sum: ["amount"] }) -> { rows: [{ group, count, sum }], truncated, loading, version }
4755
- Charts are recharts (ADR 0114), fed an aggregate's rows (stats = the useLive.aggregate above):
5205
+ Charts are recharts (ADR 0209), fed an aggregate's rows (stats = the useLive.aggregate above):
4756
5206
  ${snippet("chart")}
4757
- db.list(table, query) / db.get(table, id) / db.count(table, { where }) / db.aggregate(table, query) -> one-shot, in event handlers
5207
+ db.get(table, id) / db.count(table, { where }) / db.aggregate(table, query) -> one-shot, in event handlers
4758
5208
  db.insert("orders", { customer, status: "new" }); db.update("orders", id, { status: "ready" }); db.delete("orders", id)
4759
5209
  db.update("orders", id, { status: "paid" }, { why: "Invoice paid by card" }) -> the reason lands in that write's History row
4760
5210
  db.settings("company_settings") -> a SINGLETON Table's row or null
4761
- db.table(name) / useLive.table(name, query | null) / useLive.tableCount(name, query) -> a Table named at run time (no casts)
5211
+ db.table(name) / useLive.table(name, query | null) / useLive.tableCount(name, query) -> a Table or a History (\`\${table}_history\`) named at run time (no casts)
4762
5212
  db.upload("expenses", "receipt", file) -> a FileId for a FILE column (file from <input type="file">); then insert or update with it
4763
5213
  attachment(id) -> that file's URL for <img>, <video> or a download link
4764
5214
  useLive("actors", { where: { id: { in: actorIds } } }) -> { id, kind, name, email }[]: current names for History actor ids
4765
5215
  today(), toDate(2026, 3, 1), toDate(date), toEpoch("2026-03-01"), now() -> DATE (DateString) and TIMESTAMP (EpochMs) values
4766
5216
  toCents("1,234.50"), toCents(12.5), fromCents(cents) -> MONEY values (whole cents; null when unreadable)
4767
5217
  where: { col: value } is equality ({ col: null } is IS NULL); { col: { gte: 2 } } uses eq ne lt lte gt gte in
4768
- nin like null has; or: [{ ... }, { ... }]; and: [{ or: [...] }, { or: [...] }] for several ors. { in: [] }
4769
- matches nothing. [check] ne is typed only for a column no row leaves empty (id, created_at): anywhere else it
4770
- would also drop the NULL rows, so say which you mean: { nin: [x] } keeps them, { nin: [x], null: false }
4771
- drops them (types, ne-nullable).
4772
- [runtime] like matches the whole value: % is any run of characters and _ is one, and it ignores case for ASCII
4773
- letters only (A and a match; É and é do not).
4774
- [runtime] Row queries default to 100 rows and cap at 1000. [check, warning] Never compute a total or count
4775
- from rows, by reduce or by a loop (reduce-rows): use count and aggregate, which are complete. Never search,
4776
- filter or page loaded rows by what the user typed or picked (filter-rows): put it in where and limit/offset,
4777
- and show useLive.query's truncated. Aggregate filters apply before grouping; limit/offset page the groups,
4778
- which can be truncated too. Ungrouped empty input counts zero.
4779
- Relations (ADR 0102): [advice] never join in the browser or build id maps; one query follows REFERENCES.
5218
+ nin contains startsWith endsWith like null has; or: [{ ... }, { ... }]; and: [{ or: [...] }, { or: [...] }] for
5219
+ several ors. { in: [] } matches nothing.
5220
+ [runtime] A filter means what the same test on a row would in TypeScript (docs/adr/0219): { col: { ne: x } } is
5221
+ row.col !== x and { col: { nin: [x, y] } } is "neither", so both keep the rows where col is empty; add
5222
+ null: false to drop those ({ ne: x, null: false }). { ne: null } is "has a value". The ordering operators
5223
+ (lt lte gt gte) and the text ones never match an empty column. A path through a reference tests the referenced
5224
+ row: { "sample_id.code": { ne: x } } leaves out the rows whose sample_id is empty, ne and nin included; or it
5225
+ with { sample_id: null } to keep them.
5226
+ [runtime] Text search is { name: { contains: text } }, startsWith or endsWith: text is taken as written (a % or _
5227
+ in it is that character), on a TEXT column, ignoring case for ASCII letters only (A and a match; É and é do
5228
+ not). like is the same match against a pattern over the whole value, % any run of characters and _ one.
5229
+ [runtime] Row queries default to 100 rows and cap at 1000, and a Preview says when a plain useLive read stopped
5230
+ at its limit. [advice] A total or count comes from count and aggregate, which are complete, never from adding
5231
+ up rows that may have stopped. [check, warning] Never search, filter or page loaded rows by what the user typed
5232
+ or picked (filter-rows): put it in where ({ col: { contains } }) and limit/offset, and show truncated. Aggregate
5233
+ filters apply before grouping; limit/offset page the groups, which can be truncated too. Ungrouped empty
5234
+ input counts zero.
5235
+ Relations (ADR 0219): [advice] never join in the browser or build id maps; one query follows REFERENCES.
4780
5236
  ${snippet("relations")}
4781
5237
  -> row.sample?.code, row.sample?.client?.name, row.analyst_row?.name (an actor), row.method_instrument[i].instrument?.title
4782
5238
  A <name>_id include lands on row.<name>, <name>_ids (an id list) on row.<name> as an array, any other column c
4783
5239
  on row.c_row; a child Table on row.<child> (up to 100, oldest first; truncatedChildren says more exist; its
4784
5240
  column needs an index). Unreadable rows are null or left out. { ids: { has: id } } tests an id list.
4785
- db.list, query and aggregate take the same where and include, in pages, functions and rules.
5241
+ db.query, db.list and aggregate take the same where and include, in pages, functions and rules.
4786
5242
  History: every Table has a read-only \`<table>_history\` the platform writes on every change, with the actor
4787
5243
  and the write's why. [advice] Never build a log or audit table; an activity feed reads the History
4788
5244
  (\`ez help db\`). The actors view is read-only: match History's by to actors.id, show the current name, and
@@ -4793,7 +5249,7 @@ Refused writes reject with a WriteError: \`catch (e) { if (e instanceof WriteErr
4793
5249
 
4794
5250
  /** `ez help forms`: writes from the UI, actions and the schema-driven record components. */
4795
5251
  const FORMS_TOPIC = `Forms and actions: how the UI writes, and the schema's record components.
4796
- Records from the schema (ADR 0109): reach for these before writing a list, a form, a picker or a reference
5252
+ Records from the schema (ADR 0222): reach for these before writing a list, a form, a picker or a reference
4797
5253
  label by hand. They draw labels, inputs, choices and refusals from global/db/schema.sql (LABEL, DISPLAY,
4798
5254
  CHECK, REFERENCES; \`ez help db\`), so [advice] never re-declare those in Site code.
4799
5255
  <RecordList table="dealers" columns={["customer_code", "name", "credit_hold"]} search={["name", "customer_code"]}
@@ -4807,6 +5263,18 @@ CHECK, REFERENCES; \`ez help db\`), so [advice] never re-declare those in Site c
4807
5263
  <MemberPicker value={m} onChange={setM} />, <CellValue table="dealers" column="credit_hold" value={v} />
4808
5264
  schema.table("dealers") -> { label, plural, display, columns, referencedBy, ... }; schema.label("dealers", row)
4809
5265
  schema.column("orders", "status")?.values -> a CHECK list's choices (never copy them: enum-literal-copy warns)
5266
+ A form the schema cannot draw (it calls a server function, or its fields are not one Table's columns) is the
5267
+ starter's Form with its typed inputs, which hold the label, the hint, the error and the pending state:
5268
+ <Form submit="Log visit" columns={2} onCancel={onClose} action={async () => { await logVisit(input); onClose(); }}>
5269
+ <TextInput label="Name" value={name} onChange={setName} required /> -> string
5270
+ <NumberInput label="Minutes" value={minutes} onChange={setMinutes} /> -> number | null
5271
+ <DateInput label="Date" value={on} onChange={setOn} /> -> DateString | null
5272
+ <SelectInput label="Kind" value={kind} onChange={setKind} options={kinds} />, <TextArea ... />, <Checkbox ... />
5273
+ </Form>
5274
+ [advice] Reach for these before a raw <input>, <select>, <textarea> or <form>; what the action throws shows
5275
+ above the fields (ez help recipes: function-form). Layout is the starter's too: <Stats> around Stat tiles,
5276
+ <Toolbar aside={...}> for the controls above a list, <Board> of <BoardColumn> of <Card> for columns of cards
5277
+ (recipes: board), so a page rarely needs a class of its own. The starter Button takes action or onClick.
4810
5278
  A one-click write (delete, toggle) is onClick={() => run(() => db.delete("orders", id))}: run() awaits it and
4811
5279
  shows the standard failure notice.
4812
5280
  A write with fields or a pending state (a modal's Save, a form) is an action, which replaces the saving flag,
@@ -4819,14 +5287,16 @@ Dispatch the action from onClick={() => startTransition(save)} (both from react)
4819
5287
  id="hours" action={save} noValidate> around the fields and a Save button with form="hours" (it may sit in a
4820
5288
  footer outside the form). A form submits on Enter, but every <button> inside it without type="button" submits
4821
5289
  it too, a child component's (a picker's) included: use the form only when its buttons are typed. noValidate
4822
- leaves validation to the action. [check, warning] Never onClick={save}: React runs it as an action only from
5290
+ leaves validation to the action. React resets a form after its action, which shows a controlled <select> or
5291
+ checkbox at its first value while its state keeps the chosen one: with those inside, submit with
5292
+ onSubmit={(e) => { e.preventDefault(); startTransition(save); }}, as the starter Form does. [check, warning] Never onClick={save}: React runs it as an action only from
4823
5293
  a form, formAction or a transition (form-action). useFormStatus() (from @ezship/react) gives pending to a
4824
5294
  child component inside the form; useTransition gives a pending flag to any async work; useOptimistic shows a
4825
5295
  value before its write lands. An action that throws outside attempt() shows its error in place of the page.
4826
5296
  There is no Modal in the Framework: a dialog is your own component (\`ez help recipes\`, modal-save).
4827
5297
  errorMessage(e) is the message of anything a catch caught. [check, warning] Never cast it (no-cast).`;
4828
5298
 
4829
- /** `ez help frame`: provided values, Session State, query parameters and custom hooks (ADRs 0088, 0091). */
5299
+ /** `ez help frame`: provided values, Session State, query parameters and custom hooks (ADRs 0214 and 0209). */
4830
5300
  const FRAME_TOPIC = `The frame: provided values, Session State, query parameters, custom hooks, the Shell and the viewer.
4831
5301
  Pick by what the value is:
4832
5302
  data the frame works out once (who the viewer is in the app's terms) -> provided values: useProvided()
@@ -4857,7 +5327,7 @@ access by it; a function given activeCompanyId still checks in the App Database
4857
5327
  that company.
4858
5328
  useSearchParam("state") -> that query parameter of the current route, string | null (re-renders when it changes)
4859
5329
  <Link site="dispatch" to="/orders?state=needs_dispatch">; useNavigate()("/orders?driver=" + encodeURIComponent(id))
4860
- Custom hooks (ADR 0091): when a second page or component needs the same live query, Session State or derived
5330
+ Custom hooks (ADR 0209): when a second page or component needs the same live query, Session State or derived
4861
5331
  values, move them into \`hooks/use<Name>.ts\` (or \`global/hooks/use<Name>.ts\` when several Sites share it,
4862
5332
  imported as "global/hooks/use<Name>") rather than copying them. A hook has a component's imports and rules,
4863
5333
  calls hooks at its top level and returns values, never markup:
@@ -4872,7 +5342,7 @@ The viewer: sign-in and membership are the platform's. useAuth() -> { user: { id
4872
5342
  membership: "active" | "blocked" | null, me (the viewer as a MEMBER column holds them), groups, loading };
4873
5343
  signIn() and signOut() are their own imports, not fields of useAuth().`;
4874
5344
 
4875
- /** `ez help functions`: server functions, useCall and Global lib modules (ADRs 0041, 0077). */
5345
+ /** `ez help functions`: server functions, useCall and Global lib modules (ADRs 0228 and 0210). */
4876
5346
  const FUNCTIONS_TOPIC = `Server functions, useCall and shared logic.
4877
5347
  Server functions belong to this Site's Version and deploy with its UI. In functions/save.ts:
4878
5348
  ${snippet("function")}
@@ -4882,8 +5352,8 @@ one when the page opens. useCall takes any async function of its input, so a rep
4882
5352
  limits can load from the page: useCall(({ companyId }) => computeAging(db, companyId), { companyId }), with
4883
5353
  computeAging a global/lib function given the page's db; its db calls are separate requests under the same
4884
5354
  access rules, so prefer aggregates to loops. Neither form is live: refresh() reloads it.
4885
- The handler's context: { db, user, session, documents, integration, members } (ez help integrations, access,
4886
- documents). The db has the caller's access rules and list/query/aggregate/count/get/insert/update/delete and
5355
+ The handler's context: { db, user, session, timeLeft, documents, integration, members } (ez help integrations,
5356
+ access, documents). The db has the caller's access rules and list/query/aggregate/count/get/insert/update/delete and
4887
5357
  insertMany/updateMany/deleteMany (below), typed; user is the validated caller.
4888
5358
  [runtime] Each call is one transaction: all writes and History commit together or all roll back, so never wrap
4889
5359
  a handler's body in db.transaction (redundant-transaction warns); one inside a try still fails the call when
@@ -4904,7 +5374,7 @@ past either, the whole call rolls back ("Function database deadline exceeded").
4904
5374
  counts from its first write instead (ez help integrations). So does a call the Host has not yet seen write, so
4905
5375
  a function can pass once and fail the next time: plan for the first operation. A write takes from about 1 ms on
4906
5376
  an idle Host to 15 ms or more, by its Table and the Host's load, so the 1,000 operations may not fit: plan on 250
4907
- writes per call. (fn-op-budget warns on a write loop that is unbounded or may run more than 250 times.) Other
5377
+ writes per call, and write many rows with insertMany, updateMany or deleteMany (below), one operation each. Other
4908
5378
  writes wait while a call holds the database, so keep what people wait on short.
4909
5379
  [runtime] On a Host that several Instances share, an Instance's calls share 1 second of execution and 250 ms of
4910
5380
  database time a second, with bursts of 60 s and 20 s; past either, a call is refused with 429 and Retry-After. A
@@ -4917,25 +5387,35 @@ others. Each is one database operation and means exactly that many single writes
4917
5387
  rules, workflows (the status column is refused as in an update), unique keys and a History row each. A refusal
4918
5388
  rolls the call back, so none of its rows stand: that includes a row where matches that the caller may read but not
4919
5389
  write (403, naming the row), so narrow where to rows it may write. The 256-KB limit holds for what you pass.
4920
- [advice] Move bulk work in pages, one per call, and let the next call continue while more is true:
5390
+ [runtime] Work too big for one call is done in pieces (docs/adr/0228). context.timeLeft() is the milliseconds the
5391
+ call may still work before it should return: what is left of its deadlines, whichever is nearer, less room for
5392
+ the last write and the commit. It is the Host's count, so the code needs none of the numbers above: loop while
5393
+ it is above 0, then answer { more: true } and let the next call pick up the rest. What a call wrote commits
5394
+ when its handler returns.
5395
+ ${snippet("timed-loop")}
5396
+ The 1,000 operations still hold, so read a bounded batch per call as above. Who calls again:
5397
+ a page await whileMore(syncSome, {}) (from @ezship/react) calls the function until its answer has no
5398
+ more: true, each call its own transaction, and resolves with the last answer (100 calls at most);
5399
+ a call the Host refused with Retry-After (the caller's rate, a busy Host) is made again after it
5400
+ a job a job that answers { more: true } is called again at once in the same run, up to 50 calls or
5401
+ 5 minutes; what is left waits for the schedule's next run (ez help jobs)
5402
+ an API Key the caller repeats the request while the answer says more
5403
+ [advice] A fixed patch over many rows is one operation: page it with updateMany's limit and answer its more:
4921
5404
  ${snippet("many-rows")}
4922
5405
  Page by a condition the write changes: a patch that leaves where true matches the same rows again. The database
4923
- deadline still holds for the whole operation, and past it the call rolls back: 1,000 rows take about half a second
4924
- on an idle Host, or about 2.5 seconds on a Table with rules, and longer on a busy one, so on a Table with rules
4925
- choose a limit well inside 1,000.
4926
- [advice] To adapt to a busy Host, write row by row and stop by time with Date.now(): it is the Host's clock and
4927
- keeps moving while a call waits. Stop at about 4 seconds, which leaves room for the last write and the commit, and
4928
- stay under the 1,000 operations too, since a fast Host reaches them first (fn-op-budget allows up to 900 items in a
4929
- loop that reads Date.now()):
4930
- ${snippet("timed-loop")}
4931
- What it wrote commits when the handler returns; the next call picks up the rest.
5406
+ deadline holds for the whole operation, so on a Table with rules choose a limit well inside 1,000.
4932
5407
  [check] Each function file is one default serverFunction(...) call; keep private helpers inside that file, or in
4933
- a global/lib module once a second file needs them. Options are literals: serverFunction(input, handler,
5408
+ a lib module once a second file needs them (lib/<name>.ts for this Site, global/lib for several; below). Options are literals: serverFunction(input, handler,
4934
5409
  { access: "group(payroll)", authority: "site" }) (ez help access); { api: true } also lets an API Key call it
4935
5410
  (ez help api).
4936
- Test with \`ez function call save '{"title":"Test"}' [--preview <name>]\`; its writes are real (ask first).
4937
- Global lib modules (ADR 0077) hold the logic several Sites or files share: guards, calculations, formatting,
4938
- paged reads. Pages, components, hooks, App.tsx, the Shell, server functions, jobs, listeners, Table rules and
5411
+ Test with \`ez function call save '{"title":"Test"}' [--preview <name>]\`; its writes are real (ask first). It
5412
+ runs as you, under your access rules, and --preview names a Preview of yours.
5413
+ Lib modules hold logic that is not a component, a hook or a function: guards, calculations, parsing, paged
5414
+ reads. lib/<name>.ts is this Site's own (docs/adr/0209): its pages, components, hooks, App.tsx, server functions
5415
+ and listeners import it by path (\`import { priceOf } from "../lib/pricing"\`, "./lib/pricing" from App.tsx), it
5416
+ deploys with the Site, and it may also import the Site's constants. Start there; move a module to global/lib
5417
+ when a second Site needs it.
5418
+ Global lib modules (ADR 0210) hold the logic several Sites share. Pages, components, hooks, App.tsx, the Shell, server functions, jobs, listeners, Table rules and
4939
5419
  workflows import them by name (\`import { periodGuard } from "global/lib/accounting"\`).
4940
5420
  [check] A lib module has named exports only and imports only other lib modules (\`./names\` or
4941
5421
  \`global/lib/names\`) and \`import type\` from \`@ezship/react/server\` and \`global/db/types\`: pure TypeScript with
@@ -4948,7 +5428,7 @@ function, in its transaction. [advice] Move code to lib when a second file needs
4948
5428
  \`ez global check\` checks lib against every Site; a Site's \`ez check\` and \`ez preview\` use the lib in your
4949
5429
  Global Working Copy, unpushed edits included; \`ez deploy\` uses the pushed lib (ez help lifecycle).`;
4950
5430
 
4951
- /** `ez help integrations` (ADRs 0092, 0094). */
5431
+ /** `ez help integrations` (ADR 0231). */
4952
5432
  const INTEGRATIONS_TOPIC = `Integrations let server code (a function, job, listener) reach another service without seeing its
4953
5433
  credentials. [runtime] Pages and local functions have no integrations, and there is no fetch anywhere.
4954
5434
  An Admin sets one in a terminal (\`ez integration set stripe --origin https://api.stripe.com --header
@@ -4973,7 +5453,8 @@ can read the same stock and both write; wrap a read-check-write in db.transactio
4973
5453
  takes the writer at once (no integration call inside or after it). A rollback never undoes a request: pass
4974
5454
  the service an idempotency key where it takes one, and remember a timed-out POST may have happened.
4975
5455
  [runtime] Per call: 5 requests, each within the integration's timeout (default 10 s, at most 30), 60 s in all,
4976
- 256 KB each way, no redirects followed.
5456
+ 256 KB each way, no redirects followed. Per Instance: 4 requests in flight and 10 a second (bursts of 60).
5457
+ Past any limit a request is refused, never queued.
4977
5458
  [runtime] While a service answers, the call's 10-second deadline pauses and it holds no database, so neither its
4978
5459
  requests nor its reads before the first write count toward the 5-second database deadline (ez help functions).
4979
5460
  That deadline starts at the first write or db.transaction: the writes and whatever follows them must fit in it.
@@ -4987,10 +5468,11 @@ are not built yet: every call on one is refused (grant), and \`context.integrati
4987
5468
  [advice] Put a typed wrapper for a service in global/lib (it imports the type IntegrationClient from
4988
5469
  @ezship/react/server and takes the client as an argument, like the database); defaults code may override
4989
5470
  belong there, not on the binding.
4990
- \`ez integration test <name> <path>\` makes one request; \`ez integration calls <name>\` shows recent calls and
5471
+ \`ez integration test <name> <path>\` makes one request (Builders GET and HEAD, Admins any method);
5472
+ \`ez integration calls <name>\` shows recent calls and
4991
5473
  their refusals. A deploy warns when the code names an integration the Instance has not set.`;
4992
5474
 
4993
- /** `ez help jobs`: scheduled jobs and listeners (ADRs 0076, 0092, 0136). */
5475
+ /** `ez help jobs`: scheduled jobs and listeners (ADRs 0230 and 0231). */
4994
5476
  const JOBS_TOPIC = `Scheduled jobs and listeners: server code nothing in the browser calls.
4995
5477
  Scheduled jobs belong to the Instance, not a Site: they live in the Global Workspace and run from its pushed
4996
5478
  schedules.json. In global/jobs/closeDay.ts (\`ez global put jobs/closeDay.ts\`):
@@ -4999,21 +5481,29 @@ schedules.json. In global/jobs/closeDay.ts (\`ez global put jobs/closeDay.ts\`):
4999
5481
  // run.due is the scheduled time (ISO, UTC): use it, not the clock, so a run is idempotent per due time
5000
5482
  });
5001
5483
  and in global/schedules.json: [{ "name": "nightly", "cron": "0 2 * * *", "job": "closeDay", "input": { "days": 1 } }]
5002
- [check] Cron is five UTC fields (minute hour day-of-month month day-of-week); schedules.json is checked
5003
- (schedules), and a Site may hold neither it nor jobs/. A job has a server function's db and limits with Site
5004
- authority (every row but BY none Tables, and context.members); History records it as schedule:<name>.
5484
+ [check] Cron is five UTC fields (minute hour day-of-month month day-of-week; jan-dec and sun-sat names,
5485
+ no @daily or seconds); schedules.json is checked (schedules): at most 20 entries, each input at most 16 KB.
5486
+ A Site may hold neither it nor jobs/. The job's schema checks the input on every run, and a mismatch fails
5487
+ that run. run is { schedule, due, trigger: "schedule" | "manual" }. A job has a server function's db and
5488
+ limits with Site authority (every row but BY none Tables, and context.members); History records it as
5489
+ schedule:<name>.
5005
5490
  Nothing imports a job and no browser can call one; it imports what \`ez help files\` lists for Global jobs, so
5006
5491
  logic it shares with a Site goes in global/lib and its constants in global/constants.
5007
5492
  [runtime] \`ez global push\` activates the schedules and the jobs at once ("Takes effect now"); only Admins
5008
5493
  change schedules.json. Previews never run them. A job sees the Tables and columns a Preview or Deploy has
5009
5494
  created: push alone creates none. Each due time runs at most once; after the Host was down, only the latest
5010
5495
  missed time runs. One run has a function's limits, the 5-second database deadline included (ez help functions),
5011
- and a run past one rolls back whole and is not retried: a long job is several short runs, each writing a bounded
5012
- batch the next continues from, with updateMany's limit and more (ez help functions) or a Date.now() bound; take
5013
- what it stores or keys on from run.due.
5496
+ and a call past one rolls back whole. A run refused because the Host is busy (429, 503) is tried again
5497
+ while it is the latest due time; any other failure is recorded and not retried. A long job works in pieces
5498
+ (docs/adr/0228): it writes a bounded batch, stops when context.timeLeft() reaches 0 or updateMany answers
5499
+ more, and returns { more: true }; the Host then calls it again at once in the same run, each call its own
5500
+ transaction, up to 50 calls or 5 minutes, and the schedule's next run continues what is left. Take what it
5501
+ stores or keys on from run.due.
5014
5502
  \`ez schedule list\` shows each schedule's next due time and last run, \`ez schedule runs <name>\` its recent runs and errors,
5015
5503
  and \`ez schedule run <name>\` runs it now (writes are real). \`ez schedule pause <name>\` stops its due times
5016
- with no push; \`ez schedule resume <name>\` starts them again from now, skipping the times missed while paused.
5504
+ with no push, and every push keeps the pause; \`ez schedule resume <name>\` starts them again from now,
5505
+ skipping the times missed while paused. Run, pause and resume are for Admins and Builders, not Limited
5506
+ Builders.
5017
5507
  Listeners receive webhooks: other services post events to the Site, verified with the secret the service
5018
5508
  issued. In listeners/stripeEvents.ts:
5019
5509
  import { listener, z } from "@ezship/react/server";
@@ -5030,13 +5520,16 @@ with Site authority, and integrations, plus event: { id, deliveryId, receivedAt,
5030
5520
  JSON (or its text), checked by the schema. Nothing imports a listener; browsers cannot post to one.
5031
5521
  After deploying, \`ez listener list\` shows the URL to give the sending service; the person who registers it
5032
5522
  runs \`ez listener secret <name>\` in a terminal with the secret the service issued (never through this
5033
- conversation); until then every delivery is refused.
5034
- [runtime] Delivery is at least once and unordered, with retries for a day: replays are refused within minutes
5035
- (standard, stripe) or days (github, or token with an idHeader), never forever. [advice] Key every once-only
5036
- effect on the payload's own id with a unique index, and pass event.deliveryId to services as the idempotency
5037
- key. \`ez listener events <name> [--dead]\`, \`show\` and \`retry\` inspect and replay events.`;
5038
-
5039
- /** `ez help api`: the Data API and its API Keys (docs/adr/0119, docs/adr/0151). */
5523
+ conversation); until then every delivery is refused. A new secret leaves the old one verifying for 24 hours
5524
+ (--overlap <hours>). Every refusal at the door is the same 404, so a missing secret looks like a bad
5525
+ signature: \`ez listener list\` counts them. A Preview has no listeners.
5526
+ [runtime] An event the schema refuses is dead at once. Delivery is at least once and unordered, with
5527
+ retries for a day: replays are refused within minutes (standard, stripe) or days (github, or token with an
5528
+ idHeader), never forever. [advice] Key every once-only effect on the payload's own id with a unique index,
5529
+ and pass event.deliveryId to services as the idempotency key. \`ez listener events <name> [--dead]\`, \`show\`
5530
+ and \`retry\` inspect and replay events.`;
5531
+
5532
+ /** `ez help api`: the Data API and its API Keys (docs/adr/0232). */
5040
5533
  const API_TOPIC = `The Data API lets another system (a sync job, a reporting tool, a script on the customer's server) read
5041
5534
  and write this Instance's data over HTTPS. Pages never use it: they have useLive and db.
5042
5535
  An Admin creates an API Key in a terminal, from any Working Copy of the Instance: \`ez key create warehouse
@@ -5055,12 +5548,15 @@ describes what it may reach. It serves the published schema as far as the App Da
5055
5548
  column is there once a Preview or Deploy has created it. _ez/api/db/<table> is the page's data API: POST <table>/query, POST
5056
5549
  <table>/aggregate, GET <table>/<id>, POST <table> (insert), PATCH and DELETE <table>/<id>, POST
5057
5550
  <table>/<id>/actions/<action>; ?why= gives a write its reason. The change feed is the History:
5058
- POST _ez/api/db/<table>_history/query {"where":{"version":{"gt":<last seen>}},"order":["version"]}.
5551
+ POST _ez/api/db/<table>_history/query {"where":{"version":{"gt":<last seen>}},"order":["version"]}. Also
5552
+ GET <table>/<id>/actions (what the key may run on the row), GET db/versions, and ?action= on an insert.
5059
5553
  Server functions are callable by a key only when they say so: serverFunction(input, handler, { api: true })
5060
5554
  [check: function-options], and only on the Sites its --sites allows. [runtime] Without --sites a key calls no
5061
5555
  functions, all means every unrestricted Site, and a Restricted Site is reached only by a key that names its id;
5062
5556
  --sites never narrows data, which groups do. POST _ez/api/sites/<site>/functions/<name> {"input": ...} answers
5063
- {"result": ...}, against that Site's deployed artifact, under the function's own access and authority. In the
5557
+ {"result": ...}, against that Site's deployed artifact, under the function's own access and authority, the
5558
+ caller rate and the Instance's budgets (ez help functions). A Site the key may not call, an archived or
5559
+ undeployed Site and a function without { api: true } all answer the same 404. In the
5064
5560
  handler a key's user is { id: "key:<name>", email: "", name, me: null, groups }. Files: POST
5065
5561
  _ez/api/attachments/<table>/<column>?name=<file> with the bytes, GET _ez/api/attachments/<id>.
5066
5562
  [runtime] Each key may make ${API_KEY_RATE.burst} requests at once, refilled at ${API_KEY_RATE.perSecond} a second (429 with Retry-After
@@ -5068,7 +5564,7 @@ past that). A key lasts ${API_KEY_DAYS.default} days by default, at most ${API_K
5068
5564
  name is never reused: to rotate, create a new key, switch the other system to it, revoke the old one.
5069
5565
  Previews have no API.`;
5070
5566
 
5071
- /** `ez help local` (ADR 0048). */
5567
+ /** `ez help local` (ADR 0235). */
5072
5568
  const LOCAL_TOPIC = `Local functions run on the Member's own computer, inside ezship Desktop, and never on the Host.
5073
5569
  In local/readEmpty.ts:
5074
5570
  import { localFunction, z } from "@ezship/react/local";
@@ -5083,7 +5579,9 @@ the Member (user), the Site (site) and desktop.dataDir, a folder the Desktop kee
5083
5579
  computer; it has no db: the page saves results with db.insert or a server function.
5084
5580
  [check] Local functions import only @ezship/react/local (localFunction, z and types), node:* built-ins (with
5085
5581
  the prefix), constants, sibling local functions and type-only global/db/types; no packages.
5086
- [runtime] One call runs at most 60 seconds. In an ordinary browser, the Studio's preview included, a call
5582
+ [runtime] One call runs at most 60 seconds; input, result and errors cross as JSON. It is arbitrary Node code,
5583
+ child processes included, on every Member's computer that opens the Site in ezship Desktop, and Members who
5584
+ share a computer share its files. In an ordinary browser, the Studio's preview included, a call
5087
5585
  fails and the Framework shows a notice that the app needs ezship Desktop; useDesktop() -> { available,
5088
5586
  version } lets a page offer manual entry instead.
5089
5587
  [advice] Use local functions for station configuration, caches, exports and exchanging files with programs on
@@ -5091,7 +5589,7 @@ that computer; the App Database stays the shared record, and nothing in a local
5091
5589
  Members or computers. Never write credentials or Host tokens to disk. Test by opening the Preview URL in
5092
5590
  ezship Desktop (ez preview prints it; ez dev keeps it fresh).`;
5093
5591
 
5094
- /** `ez help documents` (ADR 0105). */
5592
+ /** `ez help documents` (ADR 0233). */
5095
5593
  const DOCUMENTS_TOPIC = `Documents: PDFs from Global templates in \`global/documents/<Name>.tsx\` (\`ez global put documents/Invoice.tsx\`):
5096
5594
  import { document, z, Document, Page, View, Text, Image, PageNumber, asset } from "@ezship/react/pdf";
5097
5595
  export default document(
@@ -5125,6 +5623,9 @@ context and exported by @ezship/react:
5125
5623
  const r = await documents.render(Invoice, data, { filename: "invoice-1.pdf", attachTo: { table: "invoices", id, column: "pdf" } });
5126
5624
  Rendering is asynchronous: useRender(r.id) -> { status: "queued" | "rendering" | "ready" | "failed", file, error }.
5127
5625
  With attachTo the FILE column is set when the PDF is ready (useLive shows it); without it, keep r.file yourself.
5626
+ In a server function the render only joins the queue: r.status is "queued" and r.file is null there, and the
5627
+ PDF exists after the function has returned. Never build a URL from r.file in the function; a page reads the
5628
+ FILE column (or useRender) and links attachment(id). To email a PDF, see \`ez help email\`: link to that page.
5128
5629
  [runtime] Every PDF is permanent; a FILE column holding its id shares it with the Table's readers, and History
5129
5630
  keeps the ids a column held before. Input is JSON up to 1 MB; at most 200 pages.
5130
5631
  Test a deployed one: \`ez document render Invoice '<json>'\`.`;
@@ -5146,6 +5647,10 @@ The body is Markdown, never HTML: paragraphs, # headings, **bold**, *italic*, \`
5146
5647
  - and 1. lists, pipe tables (good for reports) and fenced code. The subject is one line.
5147
5648
  link("/path") is the absolute URL of a page of this Site (of your Preview, from a Preview);
5148
5649
  link("<site>", "/path") of another Site. A job has no Site of its own, so it always names one.
5650
+ link is for pages only: it is never the URL of a file, an Attachment or an API path.
5651
+ An Email carries no attachment; \`to\`, \`subject\`, \`body\` and \`button\` are the whole message. To send a file or
5652
+ a PDF (\`ez help documents\`), keep it in a FILE column of a row, link to the page that shows that row, and draw
5653
+ the download there: <a href={attachment(row.pdf)} download>. Never write "attached" in a body.
5149
5654
  [runtime] Limits: ${EMAIL_LIMITS.perInvocation} Emails per invocation, a ${EMAIL_LIMITS.subject}-character subject, a ${EMAIL_LIMITS.body / 1000} KB body; ${EMAIL_LIMITS.perDay}
5150
5655
  a day per Instance and ${EMAIL_LIMITS.perMinute} a minute per Site function or job, over which an Email is dropped (quota). A digest in a
5151
5656
  job (one Email per person, a table of their items) stays under them.
@@ -5323,14 +5828,15 @@ import CreditLimitDialog from "../components/CreditLimitDialog";
5323
5828
 
5324
5829
  /** Active customers and their credit limits; a row opens the dialog that changes one. */
5325
5830
  export default function Credit() {
5326
- const customers = useLive("customers", { where: { status: "active" }, order: ["name"] });
5831
+ const customers = useLive.query("customers", { where: { status: "active" }, order: ["name"] });
5327
5832
  const [editing, setEditing] = useState<Customer | null>(null);
5328
5833
  return (
5329
5834
  <>
5330
5835
  <PageHeader title="Credit limits" description="Open a customer to change their limit." />
5331
5836
  <Panel flush>
5332
5837
  <DataTable
5333
- rows={customers}
5838
+ rows={customers.rows}
5839
+ loading={customers.loading}
5334
5840
  columns={[
5335
5841
  { label: "Customer", cell: (c) => c.name },
5336
5842
  { label: "Limit", cell: (c) => <Money cents={c.credit_limit} />, align: "right" },
@@ -5534,6 +6040,263 @@ Site's ez check and ez preview already use your unpushed copy; ez deploy uses th
5534
6040
  computes the stored total itself rather than trusting the page's. Lib modules format nothing (no Intl on the
5535
6041
  server): the page shows cents with the starter's Money.`,
5536
6042
  },
6043
+ {
6044
+ name: "enforced-rule",
6045
+ title: "A rule nobody can get around: steps in order, enforced on the server",
6046
+ topics: ["functions", "access", "db"],
6047
+ schema: `CREATE TABLE work_steps (
6048
+ work_order TEXT,
6049
+ position INTEGER,
6050
+ title TEXT,
6051
+ held INTEGER,
6052
+ started_by MEMBER,
6053
+ started_at TIMESTAMP,
6054
+ finished_at TIMESTAMP
6055
+ );
6056
+ CREATE INDEX ON work_steps (work_order);
6057
+ `,
6058
+ global: {},
6059
+ files: {
6060
+ "functions/startStep.ts": `import { serverFunction, z } from "@ezship/react/server";
6061
+
6062
+ /** Starts a step of a work order: refused while it is on hold or an earlier step is unfinished. */
6063
+ export default serverFunction(z.object({ id: z.string().min(1) }), async ({ db, user }, input) => {
6064
+ const step = await db.get("work_steps", input.id);
6065
+ if (!step) throw new Error("This step no longer exists.");
6066
+ if (step.started_at !== null) throw new Error("This step has already started.");
6067
+ if (step.held) throw new Error("This step is on hold.");
6068
+ const unfinished = await db.count("work_steps", {
6069
+ where: { work_order: step.work_order, position: { lt: step.position ?? 0 }, finished_at: null },
6070
+ });
6071
+ if (unfinished > 0) throw new Error("Finish the earlier steps first.");
6072
+ return db.update("work_steps", step.id, { started_by: user.me, started_at: Date.now() });
6073
+ });
6074
+ `,
6075
+ "pages/steps.tsx": `import { useLive } from "@ezship/react";
6076
+ import Button from "global/Button";
6077
+ import DataTable from "global/DataTable";
6078
+ import PageHeader from "global/PageHeader";
6079
+ import Panel from "global/Panel";
6080
+ import When from "global/When";
6081
+ import startStep from "../functions/startStep";
6082
+
6083
+ /** The steps of every work order in order; Start asks the server, which refuses a step out of turn. */
6084
+ export default function Steps() {
6085
+ const steps = useLive.query("work_steps", { order: ["work_order", "position"] });
6086
+ return (
6087
+ <>
6088
+ <PageHeader title="Work steps" description="A step starts only when the ones before it are finished." />
6089
+ <Panel flush>
6090
+ <DataTable
6091
+ rows={steps.rows}
6092
+ loading={steps.loading}
6093
+ columns={[
6094
+ { label: "Work order", cell: (s) => s.work_order },
6095
+ { label: "Step", cell: (s) => s.title },
6096
+ { label: "Started", cell: (s) => <When at={s.started_at} /> },
6097
+ {
6098
+ label: "",
6099
+ cell: (s) =>
6100
+ s.started_at === null ? <Button action={() => startStep({ id: s.id })}>Start</Button> : null,
6101
+ },
6102
+ ]}
6103
+ empty="No steps yet."
6104
+ />
6105
+ </Panel>
6106
+ </>
6107
+ );
6108
+ }
6109
+ `,
6110
+ },
6111
+ notes: `The rule lives in the function, not the page: the function reads, checks and writes in one transaction that
6112
+ runs as if alone, so two people starting steps at once cannot both pass, and the page only shows the refusal
6113
+ (the starter Button's action shows what the function threw). Close the other door in global/db/access.sql
6114
+ with \`WRITE work_steps BY functions;\`: pages are then refused any write of the Table, and every change goes
6115
+ through a function that checks. The page still hides Start on a started step, but that is a convenience, never
6116
+ the rule. started_by is the function's user.me, the signed-in Member, never a name someone typed. The same
6117
+ shape holds any "never", "only" or "must": a hold that blocks a record, a gate before release, a post that
6118
+ must not run twice. When every write of a Table must pass a check, write it once as a Table rule's guard
6119
+ (global/rules/<table>.ts); when the rule is which moves a status may make, a workflow (ez help db).`,
6120
+ },
6121
+ {
6122
+ name: "function-form",
6123
+ title: "A form in a dialog that calls a server function",
6124
+ topics: ["forms", "functions"],
6125
+ schema: `CREATE TABLE visits (
6126
+ customer REFERENCES customers,
6127
+ visited_on DATE,
6128
+ minutes INTEGER,
6129
+ kind TEXT,
6130
+ notes TEXT
6131
+ );
6132
+ CREATE INDEX ON visits (customer);
6133
+ `,
6134
+ global: {},
6135
+ files: {
6136
+ "functions/logVisit.ts": `import { serverFunction, z } from "@ezship/react/server";
6137
+
6138
+ /** Logs a visit to a customer; one dated after today is refused. */
6139
+ export default serverFunction(
6140
+ z.object({
6141
+ customerId: z.string().min(1),
6142
+ visitedOn: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),
6143
+ minutes: z.number().int().min(1).max(600),
6144
+ kind: z.string().min(1),
6145
+ notes: z.string().max(2000),
6146
+ }),
6147
+ async ({ db }, input) => {
6148
+ // The server cannot know the viewer's day: refuse only what is after today everywhere (UTC+14).
6149
+ if (input.visitedOn > new Date(Date.now() + 14 * 3_600_000).toISOString().slice(0, 10))
6150
+ throw new Error("A visit cannot be dated after today.");
6151
+ const customer = await db.get("customers", input.customerId);
6152
+ return db.insert("visits", {
6153
+ customer: customer.id,
6154
+ visited_on: input.visitedOn,
6155
+ minutes: input.minutes,
6156
+ kind: input.kind,
6157
+ notes: input.notes,
6158
+ });
6159
+ },
6160
+ );
6161
+ `,
6162
+ "components/LogVisitDialog.tsx": `import { useState } from "react";
6163
+ import { today, type DateString } from "@ezship/react";
6164
+ import type { Customer } from "global/db/types";
6165
+ import DateInput from "global/DateInput";
6166
+ import Dialog from "global/Dialog";
6167
+ import Form from "global/Form";
6168
+ import NumberInput from "global/NumberInput";
6169
+ import SelectInput from "global/SelectInput";
6170
+ import TextArea from "global/TextArea";
6171
+ import logVisit from "../functions/logVisit";
6172
+
6173
+ /** Logs a visit to one customer: the fields, the server's refusal in place, closed when it is saved. */
6174
+ export default function LogVisitDialog({
6175
+ customer,
6176
+ onClose,
6177
+ }: {
6178
+ customer: Customer;
6179
+ onClose: () => void;
6180
+ }) {
6181
+ const [visitedOn, setVisitedOn] = useState<DateString | null>(today());
6182
+ const [minutes, setMinutes] = useState<number | null>(30);
6183
+ const [kind, setKind] = useState<string | null>(null);
6184
+ const [notes, setNotes] = useState("");
6185
+ return (
6186
+ <Dialog title="Log a visit" description={customer.name} onClose={onClose}>
6187
+ <Form
6188
+ submit="Log visit"
6189
+ columns={2}
6190
+ onCancel={onClose}
6191
+ action={async () => {
6192
+ if (!visitedOn || !minutes || !kind) throw new Error("Give the date, the minutes and the kind.");
6193
+ await logVisit({ customerId: customer.id, visitedOn, minutes, kind, notes });
6194
+ onClose();
6195
+ }}
6196
+ >
6197
+ <DateInput label="Date" value={visitedOn} onChange={setVisitedOn} required />
6198
+ <NumberInput label="Minutes" value={minutes} onChange={setMinutes} min={1} max={600} required />
6199
+ <SelectInput
6200
+ label="Kind"
6201
+ value={kind}
6202
+ onChange={setKind}
6203
+ options={["Call", "On site", "Email"]}
6204
+ required
6205
+ />
6206
+ <TextArea label="Notes" value={notes} onChange={setNotes} hint="What was agreed." />
6207
+ </Form>
6208
+ </Dialog>
6209
+ );
6210
+ }
6211
+ `,
6212
+ },
6213
+ notes: `Uses the customers Table of record-list. Form runs its action on submit, keeps the submit button busy while
6214
+ it runs and shows what it throws above the fields, the function's own refusal included, so the component
6215
+ holds no error state, no pending flag and no try/catch. The typed inputs carry their label, hint and error
6216
+ and answer the value in its type (a number or null, a DateString or null), so no input, select or textarea
6217
+ is written by hand and nothing is parsed. Render it where a button opens it: {logging ? <LogVisitDialog
6218
+ customer={customer} onClose={() => setLogging(false)} /> : null}. A form that only writes one Table's row
6219
+ needs none of this: RecordForm draws it from the schema (record-form).`,
6220
+ },
6221
+ {
6222
+ name: "board",
6223
+ title: "A page of totals, filters and a board of cards",
6224
+ topics: ["data", "files"],
6225
+ schema: null,
6226
+ global: {},
6227
+ files: {
6228
+ "pages/pipeline.tsx": `import { useState } from "react";
6229
+ import { useLive } from "@ezship/react";
6230
+ import Badge from "global/Badge";
6231
+ import Board from "global/Board";
6232
+ import BoardColumn from "global/BoardColumn";
6233
+ import Button from "global/Button";
6234
+ import Card from "global/Card";
6235
+ import Money from "global/Money";
6236
+ import PageHeader from "global/PageHeader";
6237
+ import SearchBox from "global/SearchBox";
6238
+ import Stat from "global/Stat";
6239
+ import Stats from "global/Stats";
6240
+ import Toolbar from "global/Toolbar";
6241
+
6242
+ /** Customers by status: how many in each, and a column of cards for each, searched by name. */
6243
+ export default function Pipeline() {
6244
+ const [q, setQ] = useState("");
6245
+ const counts = useLive.aggregate("customers", { group: ["status"] });
6246
+ const count = (status: string) => counts.rows.find((r) => r.group.status === status)?.count ?? 0;
6247
+ const like = q ? { name: { contains: q } } : {};
6248
+ const leads = useLive.query("customers", { where: { status: "lead", ...like }, order: ["name"], limit: 50 });
6249
+ const active = useLive.query("customers", { where: { status: "active", ...like }, order: ["name"], limit: 50 });
6250
+ const closed = useLive.query("customers", { where: { status: "closed", ...like }, order: ["name"], limit: 50 });
6251
+ const columns = [
6252
+ { title: "Leads", found: leads },
6253
+ { title: "Active", found: active },
6254
+ { title: "Closed", found: closed },
6255
+ ];
6256
+ return (
6257
+ <div className="stack">
6258
+ <PageHeader title="Pipeline" description="Every customer by where they stand." />
6259
+ <Stats>
6260
+ <Stat label="Leads" value={count("lead")} tone="info" />
6261
+ <Stat label="Active" value={count("active")} tone="ok" />
6262
+ <Stat label="Closed" value={count("closed")} />
6263
+ </Stats>
6264
+ <Toolbar aside={<Button to="/customers/new" variant="primary">New customer</Button>}>
6265
+ <SearchBox value={q} onChange={setQ} hideLabel />
6266
+ </Toolbar>
6267
+ <Board>
6268
+ {columns.map((column) => (
6269
+ <BoardColumn
6270
+ key={column.title}
6271
+ title={column.title}
6272
+ count={column.found.rows.length}
6273
+ hint={column.found.truncated ? "Showing the first 50." : undefined}
6274
+ empty="No customers here."
6275
+ >
6276
+ {column.found.rows.map((c) => (
6277
+ <Card
6278
+ key={c.id}
6279
+ to={\`/customers/\${c.id}\`}
6280
+ title={c.name}
6281
+ aside={c.vip ? <Badge value="VIP" tone="warn" /> : null}
6282
+ meta={c.email}
6283
+ >
6284
+ <Money cents={c.credit_limit} />
6285
+ </Card>
6286
+ ))}
6287
+ </BoardColumn>
6288
+ ))}
6289
+ </Board>
6290
+ </div>
6291
+ );
6292
+ }
6293
+ `,
6294
+ },
6295
+ notes: `Uses the customers Table of record-list. Stats, Toolbar, Board, BoardColumn and Card are the starter's layout:
6296
+ a row of tiles of one width, the controls above a list with a button at the far end, and columns of cards that
6297
+ wrap on a narrow screen, so the page writes no class and no CSS of its own. The totals are one aggregate, which
6298
+ is complete; each column is its own query with the search in its where and says when it stopped at its limit.`,
6299
+ },
5537
6300
  ]),
5538
6301
  );
5539
6302
 
@@ -5560,12 +6323,13 @@ against the starter Global Workspace). They share one customers Table, declared
5560
6323
 
5561
6324
  ${RECIPES.map(recipeText).join("\n\n")}`;
5562
6325
 
5563
- /** `ez help access`: the doors around the App Database's rows (ADRs 0036, 0098, 0101, 0110). */
6326
+ /** `ez help access`: the doors around the App Database's rows (ADRs 0203 and 0225). */
5564
6327
  const accessTopic =
5565
6328
  () => `Access: who opens a Site, who reads and writes which rows, who runs which code.
5566
6329
  Every Site and Preview requires a signed-in active Member; Builders are Members too. An Admin may restrict a
5567
6330
  Site to allow-lists and groups (\`ez site access\`); the Admin who restricts it stays on its lists, so
5568
6331
  \`ez site access restrict\` alone makes an app theirs only. Sign-in is the platform's: never build a login page.
6332
+ Members sign in with an emailed code, or with a username and password they set on that page.
5569
6333
  Rows: global/db/access.sql is the one place that says who reads and writes which rows. [runtime] The Host
5570
6334
  applies it to every page, function, job and attachment request, for deployed Sites and Previews alike, from
5571
6335
  the moment an Admin pushes it (ez help lifecycle); a row a Member may not read is "Not found".
@@ -5603,7 +6367,7 @@ export const HELP_TOPICS = Object.freeze([
5603
6367
  {
5604
6368
  name: "recipes",
5605
6369
  summary:
5606
- "complete examples: a searchable list, a record form, a modal save, an external call, shared logic",
6370
+ "complete examples: a searchable list, a record form, a modal save, a form that calls a function, a board of cards, an external call, shared logic, an enforced rule",
5607
6371
  text: () => RECIPES_TOPIC,
5608
6372
  },
5609
6373
  {
@@ -5725,6 +6489,10 @@ export const COMMANDS = [
5725
6489
  usage: "ez function call <name> <json> [--preview <name>]",
5726
6490
  help: "invoke a Site function from its deployment or your Preview; writes are real",
5727
6491
  },
6492
+ {
6493
+ usage: "ez function ls",
6494
+ help: "the server functions in this working copy; one is callable once a Preview or a Deploy has built it",
6495
+ },
5728
6496
  {
5729
6497
  usage: "ez schedule list",
5730
6498
  help: "the Instance's pushed global/schedules.json: each schedule's cron, job, next due time and last run",
@@ -5767,7 +6535,7 @@ export const COMMANDS = [
5767
6535
  },
5768
6536
  {
5769
6537
  usage: "ez help [<topic> | all]",
5770
- help: "the short guide every task needs; a topic adds detail (lifecycle, files, recipes, data, forms, frame, functions, access, integrations, jobs, local, documents, db, rules, commands); all prints everything",
6538
+ help: "the short guide every task needs; a topic adds detail (lifecycle, files, recipes, data, forms, frame, functions, access, integrations, jobs, api, local, documents, email, db, rules, commands); all prints everything",
5771
6539
  },
5772
6540
  {
5773
6541
  usage: "ez status",
@@ -5803,7 +6571,7 @@ export const COMMANDS = [
5803
6571
  help: "your previews of this site: name, status, URL, last activity; --others lists the other Builders' previews of it instead (who, name, what it builds, status, last activity; never their URLs)",
5804
6572
  },
5805
6573
  {
5806
- usage: "ez preview delete|rm [<name>]",
6574
+ usage: "ez preview delete [<name>]",
5807
6575
  help: "delete a preview (the default one when no name is given)",
5808
6576
  },
5809
6577
  {
@@ -5818,7 +6586,6 @@ export const COMMANDS = [
5818
6586
  usage: "ez delete <path>",
5819
6587
  help: `delete a file (${MAIN_FILE} and ${CONTEXT_FILE} cannot be deleted)`,
5820
6588
  },
5821
- { usage: "ez rm <path>", help: "alias for delete" },
5822
6589
  { usage: "ez mv <from> <to>", help: "rename a file" },
5823
6590
  {
5824
6591
  usage: "ez config",
@@ -5842,7 +6609,6 @@ export const COMMANDS = [
5842
6609
  usage: "ez site archive <id>",
5843
6610
  help: "admins: archive a site, retaining its files, data and id",
5844
6611
  },
5845
- { usage: "ez site rm <id>", help: "alias for site archive" },
5846
6612
  {
5847
6613
  usage: "ez site access",
5848
6614
  help: "who may open this site: every builder and member, or the allow-lists",
@@ -5852,11 +6618,11 @@ export const COMMANDS = [
5852
6618
  help: "admins: switch between the allow-lists and everyone in the instance; whoever restricts a site stays on its lists",
5853
6619
  },
5854
6620
  {
5855
- usage: "ez site access add|remove|rm builder|user <who>",
6621
+ usage: "ez site access add|remove builder|user <who>",
5856
6622
  help: "admins: edit the allow-lists (who is an id or email)",
5857
6623
  },
5858
6624
  {
5859
- usage: "ez site access add|remove|rm group <name>",
6625
+ usage: "ez site access add|remove group <name>",
5860
6626
  help: "admins: let a group's members (implied groups included) open the restricted site, or stop",
5861
6627
  },
5862
6628
  {
@@ -5872,7 +6638,7 @@ export const COMMANDS = [
5872
6638
  help: "admins: change a builder's role (who is an id or email); limited builders neither push global nor create sites",
5873
6639
  },
5874
6640
  {
5875
- usage: "ez builder remove|rm <who>",
6641
+ usage: "ez builder remove <who>",
5876
6642
  help: "admins: remove a builder (and their membership) from the instance",
5877
6643
  },
5878
6644
  {
@@ -5885,7 +6651,7 @@ export const COMMANDS = [
5885
6651
  },
5886
6652
  { usage: "ez user block <who>", help: "block a member (who is an id or email)" },
5887
6653
  { usage: "ez user unblock <who>", help: "unblock a member" },
5888
- { usage: "ez user remove|rm <who>", help: "remove a member from the instance" },
6654
+ { usage: "ez user remove <who>", help: "remove a member from the instance" },
5889
6655
  {
5890
6656
  usage: "ez user group add|remove <who> <group>",
5891
6657
  help: "admins: put a member in a group, or take them out; access rules name groups as group(<name>); server code with Site authority assigns the groups access.sql declares; ez-admin and ez-builder follow the Builder roster and are never assigned",
@@ -5895,21 +6661,17 @@ export const COMMANDS = [
5895
6661
  help: 'admins: upload an image, video or document once for the whole instance; site code then says asset("<name>")',
5896
6662
  },
5897
6663
  { usage: "ez asset ls", help: "the instance's assets: name, type, size" },
5898
- {
5899
- usage: "ez asset delete|rm <name> [--force]",
5900
- help: "disabled: assets cannot be deleted, even with --force; upload with a new name",
5901
- },
5902
6664
  {
5903
6665
  usage: "ez audit [--site <id>] [--kind <kind>] [--limit N] [--before <id>]",
5904
6666
  help: "who did what in this instance, newest first",
5905
6667
  },
5906
6668
  {
5907
6669
  usage: "ez db tables",
5908
- help: "every table in the app database: columns, indexes, rows, which sites declare it",
6670
+ help: "every table in the app database: columns, indexes, rows",
5909
6671
  },
5910
6672
  {
5911
6673
  usage: "ez db schema",
5912
- help: "the live schema as nullable CREATE TABLE statements, to consolidate into global/db/schema.sql",
6674
+ help: "the live schema as CREATE TABLE statements",
5913
6675
  },
5914
6676
  {
5915
6677
  usage: "ez db sql <statement>",
@@ -5951,7 +6713,7 @@ export const COMMANDS = [
5951
6713
  {
5952
6714
  usage:
5953
6715
  "ez integration set <name> (--preset <preset> | --origin <url> --oauth <grant> --token-url <url> [--authorize-url <url>] [--revoke-url <url>] [--client-auth basic|post] [--user <user>]) --client-id <id> [--scope <scopes>]",
5954
- help: "admins: an OAuth credential (presets: quickbooks), the client secret (then a password grant's password) from stdin; stored only, since OAuth flows are not built yet (ADR 0140)",
6716
+ help: "admins: an OAuth credential (presets: quickbooks), the client secret (then a password grant's password) from stdin; stored only, since OAuth flows are not built yet (ADR 0231)",
5955
6717
  },
5956
6718
  {
5957
6719
  usage:
@@ -6016,7 +6778,7 @@ export const COMMANDS = [
6016
6778
  function formatHelp(commands) {
6017
6779
  const width = Math.max(...commands.map((c) => c.usage.length));
6018
6780
  const lines = commands.map((c) => ` ${c.usage.padEnd(width)} ${c.help}`);
6019
- return `Commands (add --json to any of them for machine-readable output; rm is a compatibility alias):\n${lines.join("\n")}`;
6781
+ return `Commands (add --json to any of them for machine-readable output):\n${lines.join("\n")}`;
6020
6782
  }
6021
6783
 
6022
6784
  /** @type {typeof import("./commands.d.mts").HELP} */
@@ -6094,7 +6856,7 @@ export const pinnedGlobalPath = (path) =>
6094
6856
  path !== TYPES_FILE;
6095
6857
 
6096
6858
  /**
6097
- * A Global push's two kinds of change (docs/adr/0096): Live ones took effect for every deployed Site at once;
6859
+ * A Global push's two kinds of change (docs/adr/0224): Live ones took effect for every deployed Site at once;
6098
6860
  * the rest reach each Site at its next Preview or Deploy.
6099
6861
  * @param {import("./types.d.mts").PushResult} result
6100
6862
  */
@@ -6176,7 +6938,7 @@ function liveLines(result) {
6176
6938
  }
6177
6939
 
6178
6940
  /**
6179
- * What changed access rules do to Members' rows (docs/adr/0098), Member by Member, the first 20 per rule.
6941
+ * What changed access rules do to Members' rows (docs/adr/0225), Member by Member, the first 20 per rule.
6180
6942
  * @param {import("./types.d.mts").PushResult} result
6181
6943
  */
6182
6944
  function reportLines(result) {
@@ -6205,7 +6967,7 @@ function reportLines(result) {
6205
6967
 
6206
6968
  /**
6207
6969
  * A Site's Check and Preview build with the Global Working Copy beside it, unpushed edits included (ADR
6208
- * 0021); a failure in global/ says so, since the edit may be another agent's in a shared folder.
6970
+ * 0217); a failure in global/ says so, since the edit may be another agent's in a shared folder.
6209
6971
  * @param {Record<string, string> | undefined} globalCopy @param {import("./commands.d.mts").Diagnostic[]} diagnostics
6210
6972
  */
6211
6973
  const globalCopyNote = (globalCopy, diagnostics) =>
@@ -6216,7 +6978,7 @@ const globalCopyNote = (globalCopy, diagnostics) =>
6216
6978
  const versionLine = (v) => `v${v.n}${v.by ? ` by ${v.by}` : ""}${v.at ? ` ${ago(v.at)}` : ""}`;
6217
6979
 
6218
6980
  /**
6219
- * After a write to db/schema.sql or a workflow (docs/adr/0103): rewrite db/types.d.ts when the declaration
6981
+ * After a write to db/schema.sql or a workflow (docs/adr/0227): rewrite db/types.d.ts when the declaration
6220
6982
  * parses (a parse error is reported by check and push, not here).
6221
6983
  * @param {Workspace} ws @param {string} path
6222
6984
  */
@@ -6231,7 +6993,7 @@ async function regenerateTypes(ws, path) {
6231
6993
  }
6232
6994
 
6233
6995
  /**
6234
- * Before a check or push (docs/adr/0108): rewrite CONTEXT.md's file inventory when it has text and its block
6996
+ * Before a check or push (docs/adr/0215): rewrite CONTEXT.md's file inventory when it has text and its block
6235
6997
  * is missing or stale (an empty CONTEXT.md is the \`context\` error's, not this).
6236
6998
  * @param {Workspace} ws
6237
6999
  */
@@ -6245,28 +7007,24 @@ async function regenerateInventory(ws) {
6245
7007
 
6246
7008
  /**
6247
7009
  * `ez status`'s schema lines: the Global Working Copy's changes relative to the live App Database.
6248
- * @param {Workspace} ws @param {Record<string,string>} files @param {string} instance @param {string} siteId
7010
+ * @param {Workspace} ws @param {Record<string,string>} files @param {string} instance
6249
7011
  */
6250
- async function schemaStatus(ws, files, instance, siteId) {
7012
+ async function schemaStatus(ws, files, instance) {
6251
7013
  if (!(SCHEMA_FILE in files)) return null;
6252
7014
  const decl = parseGlobalSchema(files[SCHEMA_FILE]);
6253
7015
  if ("error" in decl) {
6254
7016
  const message = `${SCHEMA_FILE} line ${decl.line}: ${decl.error}`;
6255
7017
  return { lines: [`schema: ${message}`], data: { ok: false, error: message } };
6256
7018
  }
6257
- const plan = planSchema(await ws.dbSchema(), decl, instance, siteId);
7019
+ const plan = planSchema(await ws.dbSchema(), decl, instance);
6258
7020
  if ("error" in plan)
6259
7021
  return { lines: [`schema: ${plan.error}`], data: { ok: false, error: plan.error } };
6260
7022
  const { created, added, indexed } = plan.summary;
6261
7023
  const lines = [];
6262
7024
  if (plan.conflicts.length > 0) {
6263
- lines.push(
6264
- "schema: conflicts with other sites; deploy would be refused until they change their declaration",
6265
- );
7025
+ lines.push("schema: conflicts with the App Database; deploy would be refused");
6266
7026
  for (const c of plan.conflicts)
6267
- lines.push(
6268
- ` ${c.table}.${c.column}: you declare ${c.mine}; ${c.site ? `site "${c.site}" declares ${c.theirs}` : `it is ${c.theirs}`}`,
6269
- );
7027
+ lines.push(` ${c.table}.${c.column}: declared ${c.mine}; it is ${c.theirs}`);
6270
7028
  } else if (created.length + added.length + indexed.length === 0) {
6271
7029
  lines.push("schema: up to date");
6272
7030
  } else {
@@ -6280,14 +7038,14 @@ async function schemaStatus(ws, files, instance, siteId) {
6280
7038
  }
6281
7039
 
6282
7040
  /**
6283
- * What the Site's next deploy brings in from the Global Workspace (docs/adr/0141): the pushed Global files that
7041
+ * What the Site's next deploy brings in from the Global Workspace (docs/adr/0211): the pushed Global files that
6284
7042
  * changed since the Version its live app was built with, as the Host recorded that deploy. A deploy builds the
6285
7043
  * pushed Global, so unpushed Global changes are not among them.
6286
7044
  * @type {typeof import("./commands.d.mts").globalSinceDeploy}
6287
7045
  */
6288
7046
  export async function globalSinceDeploy(site, global) {
6289
7047
  const deployed = site.deployedGlobal;
6290
- if (site.deployedAt === null || typeof deployed !== "number") return null;
7048
+ if (site.deployedAt === null || deployed === null) return null;
6291
7049
  const newest = (await global.remoteStatus()).version.n;
6292
7050
  if (newest <= deployed)
6293
7051
  return { deployed, current: newest, paths: { added: [], changed: [], removed: [] } };
@@ -6340,7 +7098,7 @@ export function describeCommand(argv) {
6340
7098
  const [cmd, a, b] = argv;
6341
7099
  switch (cmd) {
6342
7100
  case "function":
6343
- return `Called function ${b ?? ""}`.trim();
7101
+ return a === "ls" ? "Listed the functions" : `Called function ${b ?? ""}`.trim();
6344
7102
  case "schedule":
6345
7103
  return a === "run"
6346
7104
  ? `Ran schedule ${b ?? ""}`.trim()
@@ -6371,7 +7129,7 @@ export function describeCommand(argv) {
6371
7129
  : "Formatted the working copy";
6372
7130
  case "preview":
6373
7131
  if (a === "ls") return "Listed the previews";
6374
- if (a === "delete" || a === "rm") return `Deleted the ${b ?? ""} preview`.trim();
7132
+ if (a === "delete") return `Deleted the ${b ?? ""} preview`.trim();
6375
7133
  return "Previewed the working copy";
6376
7134
  case "link":
6377
7135
  if (a !== "--preview") return "Made a sign-in link to the app";
@@ -6385,7 +7143,6 @@ export function describeCommand(argv) {
6385
7143
  case "edit":
6386
7144
  return `Edited ${a ?? ""}`.trim();
6387
7145
  case "delete":
6388
- case "rm":
6389
7146
  return `Deleted ${a ?? ""}`.trim();
6390
7147
  case "mv":
6391
7148
  return `Renamed ${a ?? ""} to ${b ?? ""}`.trim();
@@ -6398,13 +7155,13 @@ export function describeCommand(argv) {
6398
7155
  case "site":
6399
7156
  if (a === "ls") return "Listed the instance's sites";
6400
7157
  if (a === "create") return `Created site ${b ?? ""}`.trim();
6401
- if (a === "archive" || a === "rm") return `Archived site ${b ?? ""}`.trim();
7158
+ if (a === "archive") return `Archived site ${b ?? ""}`.trim();
6402
7159
  if (a === "access") {
6403
7160
  const [, , verb, , who] = argv;
6404
7161
  if (verb === "restrict") return "Restricted the site";
6405
7162
  if (verb === "open") return "Opened the site to the instance";
6406
7163
  if (verb === "add") return `Allowed ${who ?? ""}`.trim();
6407
- if (verb === "remove" || verb === "rm") return `Disallowed ${who ?? ""}`.trim();
7164
+ if (verb === "remove") return `Disallowed ${who ?? ""}`.trim();
6408
7165
  return "Read who may open the site";
6409
7166
  }
6410
7167
  return `Ran ez ${argv.join(" ")}`.trim();
@@ -6413,7 +7170,7 @@ export function describeCommand(argv) {
6413
7170
  case "builder":
6414
7171
  if (a === "add") return `Invited ${b ?? ""}`.trim();
6415
7172
  if (a === "set-role") return `Changed ${b ?? ""}'s role`.trim();
6416
- if (a === "remove" || a === "rm") return `Removed ${b ?? ""}`.trim();
7173
+ if (a === "remove") return `Removed ${b ?? ""}`.trim();
6417
7174
  return `Ran ez ${argv.join(" ")}`.trim();
6418
7175
  case "users":
6419
7176
  return "Listed the app members";
@@ -6421,7 +7178,7 @@ export function describeCommand(argv) {
6421
7178
  if (a === "add") return `Added ${b ?? ""}`.trim();
6422
7179
  if (a === "block") return `Blocked ${b ?? ""}`.trim();
6423
7180
  if (a === "unblock") return `Unblocked ${b ?? ""}`.trim();
6424
- if (a === "remove" || a === "rm") return `Removed ${b ?? ""}`.trim();
7181
+ if (a === "remove") return `Removed ${b ?? ""}`.trim();
6425
7182
  return `Ran ez ${argv.join(" ")}`.trim();
6426
7183
  case "audit":
6427
7184
  return "Read the instance's audit trail";
@@ -6452,7 +7209,6 @@ export function describeCommand(argv) {
6452
7209
  : "Listed the support requests";
6453
7210
  case "asset":
6454
7211
  if (a === "add") return `Uploaded asset ${b ?? ""}`.trim();
6455
- if (a === "delete" || a === "rm") return `Deleted asset ${b ?? ""}`.trim();
6456
7212
  return "Listed the instance's assets";
6457
7213
  case "db":
6458
7214
  if (a === "tables") return "Listed the app database's tables";
@@ -6516,35 +7272,6 @@ export async function runCommand(ws, argv, stdin) {
6516
7272
  : text;
6517
7273
  }
6518
7274
 
6519
- const MISSING_EXPORT_RE =
6520
- /^TS(?:2305|2724): (?:Module )?'"(@ezship\/react(?:\/server|\/local)?)"' has no exported member (?:named )?'([\w$]+)'/;
6521
-
6522
- /**
6523
- * The Host's Builder says the Framework lacks a name this client's editor declarations export: the Host runs
6524
- * an older Framework than this \`ez\` (docs/adr/0078). Says so on that diagnostic instead of leaving a Builder
6525
- * to work around an editor and a checker that disagree.
6526
- * @param {import("./commands.d.mts").Workspace} ws
6527
- */
6528
- const noteSkew =
6529
- (ws) =>
6530
- /** @param {{ diagnostics: import("./commands.d.mts").Diagnostic[] }} result */
6531
- async (result) => {
6532
- const missing = result.diagnostics.filter((d) => MISSING_EXPORT_RE.test(d.message));
6533
- if (!missing.length || !ws.editorExports) return result;
6534
- /** @type {Record<string, string[]>} */
6535
- const exported = await ws.editorExports().catch(() => ({}));
6536
- return {
6537
- diagnostics: result.diagnostics.map((d) => {
6538
- const m = MISSING_EXPORT_RE.exec(d.message);
6539
- if (!m || !exported[m[1]]?.includes(m[2])) return d;
6540
- return {
6541
- ...d,
6542
- message: `${d.message}\nYour editor's declarations have ${m[2]}, so this Host runs an older Framework than your ez: don't use ${m[2]} here, or ask the Host's operator to update it.`,
6543
- };
6544
- }),
6545
- };
6546
- };
6547
-
6548
7275
  /**
6549
7276
  * A command that failed with a result: `message` is what to print, `data` what `--json` prints instead. The
6550
7277
  * command still fails (`ez` exits non-zero), and under --json the message is the JSON.
@@ -6734,7 +7461,22 @@ async function execute(ws, argv, stdin) {
6734
7461
  return out(renderLine(row), row);
6735
7462
  }
6736
7463
  case "function": {
6737
- const syntax = "ez function call <name> <json> [--preview <name>]";
7464
+ const syntax = "ez function call <name> <json> [--preview <name>] | ez function ls";
7465
+ /** The working copy's server functions, by name. */
7466
+ const written = async () =>
7467
+ Object.keys(await ws.files())
7468
+ .map((p) => functionName(p))
7469
+ .filter((n) => n !== null)
7470
+ .sort();
7471
+ if (args[0] === "ls" && args.filter((a) => a !== "--json").length === 1) {
7472
+ const names = await written();
7473
+ return out(
7474
+ names.length
7475
+ ? `${names.join("\n")}\nA function runs from the live Version or a Preview, never from unpushed files: \`ez preview\`, then \`ez function call <name> '<json>' --preview <name>\`.`
7476
+ : `This working copy has no server functions (${FUNCTIONS_DIR}<name>.ts).`,
7477
+ names,
7478
+ );
7479
+ }
6738
7480
  if (
6739
7481
  args[0] !== "call" ||
6740
7482
  !FUNCTION_NAME_RE.test(args[1] ?? "") ||
@@ -6748,7 +7490,18 @@ async function execute(ws, argv, stdin) {
6748
7490
  } catch {
6749
7491
  throw usage(`${syntax}: input must be JSON`);
6750
7492
  }
6751
- const result = await ws.callFunction(args[1], input, args[4]);
7493
+ const result = await ws.callFunction(args[1], input, args[4]).catch(async (e) => {
7494
+ // "No such function." is three things to the caller: no such file, a file nothing has built yet, or a
7495
+ // Preview that was built before it. The working copy says which.
7496
+ if (!(e instanceof Error) || !/No such function/.test(e.message)) throw e;
7497
+ const names = await written().catch(() => null);
7498
+ if (!names) throw e;
7499
+ const where = args[4] ? `the Preview ${args[4]}` : "the live Version";
7500
+ e.message = names.includes(args[1])
7501
+ ? `${e.message} ${FUNCTIONS_DIR}${args[1]}.ts is in this working copy, but ${where} was built without it: run \`ez preview\`, then \`ez function call ${args[1]} '<json>' --preview <name>\` (\`ez preview ls\` names it)${args[4] ? "" : ", or push and deploy"}.`
7502
+ : `${e.message} This working copy has no ${FUNCTIONS_DIR}${args[1]}.ts${names.length ? `; its functions: ${names.join(", ")}` : ""}.`;
7503
+ throw e;
7504
+ });
6752
7505
  return out(JSON.stringify(result.result, null, 2), result);
6753
7506
  }
6754
7507
  case "schedule": {
@@ -6767,7 +7520,6 @@ async function execute(ws, argv, stdin) {
6767
7520
  s.name,
6768
7521
  s.cron,
6769
7522
  s.job,
6770
- // An older Host answers no `paused`.
6771
7523
  s.paused ? `paused by ${s.paused.by}` : `next ${utcMinute(s.next)}`,
6772
7524
  s.last ? `last ${s.last.status} ${utcMinute(s.last.due)}` : "never run",
6773
7525
  ].join(" "),
@@ -6837,9 +7589,9 @@ async function execute(ws, argv, stdin) {
6837
7589
  for (const p of changes.deleted) lines.push(` deleted ${p}`);
6838
7590
  const schema = global
6839
7591
  ? null
6840
- : await schemaStatus(ws, (await ws.globalFiles?.()) ?? {}, remote.instance, remote.id);
7592
+ : await schemaStatus(ws, (await ws.globalFiles?.()) ?? {}, remote.instance);
6841
7593
  if (schema) lines.push(...schema.lines);
6842
- // What the deploy also brings in from the Global Workspace (docs/adr/0141); never fails the status.
7594
+ // What the deploy also brings in from the Global Workspace (docs/adr/0211); never fails the status.
6843
7595
  const brings = global
6844
7596
  ? null
6845
7597
  : await (async () => {
@@ -6921,7 +7673,7 @@ async function execute(ws, argv, stdin) {
6921
7673
  throw usage('ez push [-m "<message>"] [--prune] [--force]');
6922
7674
  const checked = messageText(message, "The message");
6923
7675
  if ("error" in checked) throw new Error(checked.error);
6924
- // --dry-run reports a Global push's Live changes (docs/adr/0096). A Site push has none, and ignoring the
7676
+ // --dry-run reports a Global push's Live changes (docs/adr/0224). A Site push has none, and ignoring the
6925
7677
  // flag would push for real, so it is refused before anything is sent.
6926
7678
  if (!global && flags.has("--dry-run"))
6927
7679
  throw new Error(
@@ -6936,7 +7688,7 @@ async function execute(ws, argv, stdin) {
6936
7688
  for (const [p, c] of Object.entries(files))
6937
7689
  if (c.length > MAX_FILE_BYTES)
6938
7690
  throw new Error(`${p} is too large (max ${MAX_FILE_BYTES} bytes)`);
6939
- // A Global push first checks every Site against these files (docs/adr/0078); --force pushes regardless.
7691
+ // A Global push first checks every Site against these files (docs/adr/0236); --force pushes regardless.
6940
7692
  if (global && !flags.has("--force")) {
6941
7693
  const { diagnostics } = await ws.check(files).catch((error) => {
6942
7694
  throw new Error(
@@ -6952,7 +7704,7 @@ async function execute(ws, argv, stdin) {
6952
7704
  // A file this copy pulled and then deleted is deleted on the shared side too; --prune additionally
6953
7705
  // deletes shared files this copy never tracked (pushed by someone else since the pull).
6954
7706
  const deleted = localChanges(files, await ws.pulled()).deleted;
6955
- // A Global push's Live changes (docs/adr/0096): --dry-run reports them without saving,
7707
+ // A Global push's Live changes (docs/adr/0224): --dry-run reports them without saving,
6956
7708
  // --acknowledge-exposure accepts rules that let Members read more, --force is an Admin's (server-checked).
6957
7709
  /** @type {{ message?: string, dryRun?: boolean, acknowledgeExposure?: boolean, force?: boolean }} */
6958
7710
  const options = {};
@@ -6979,9 +7731,9 @@ async function execute(ws, argv, stdin) {
6979
7731
  const lines = [
6980
7732
  `Deployed ${plural(r.files.length, "file")} at ${new Date(r.deployedAt).toLocaleString()}${r.global ? ` with global v${r.global}` : ""}.${r.appUrl ? ` ${r.appUrl}` : ""}`,
6981
7733
  ];
6982
- for (const t of r.schema?.created ?? []) lines.push(`created table ${t}`);
6983
- for (const c of r.schema?.added ?? []) lines.push(`added column ${c}`);
6984
- for (const i of r.schema?.indexed ?? []) lines.push(`indexed ${i}`);
7734
+ for (const t of r.schema.created) lines.push(`created table ${t}`);
7735
+ for (const c of r.schema.added) lines.push(`added column ${c}`);
7736
+ for (const i of r.schema.indexed) lines.push(`indexed ${i}`);
6985
7737
  for (const w of r.warnings ?? []) lines.push(`warning: ${w}`);
6986
7738
  return out(lines.join("\n"), r);
6987
7739
  }
@@ -6989,7 +7741,7 @@ async function execute(ws, argv, stdin) {
6989
7741
  case "versions": {
6990
7742
  const rows = await ws.listVersions();
6991
7743
  if (rows.length === 0) return out("No versions yet. Push first.", rows);
6992
- // A Site's rows say which Version Members see and which a deploy shipped before (docs/adr/0141).
7744
+ // A Site's rows say which Version Members see and which a deploy shipped before (docs/adr/0211).
6993
7745
  /** @param {Version} v */
6994
7746
  const shipped = (v) =>
6995
7747
  v.live ? " [live]" : v.deployedAt ? ` [deployed ${ago(v.deployedAt)}]` : "";
@@ -7007,12 +7759,10 @@ async function execute(ws, argv, stdin) {
7007
7759
  await regenerateInventory(ws);
7008
7760
  Object.assign(files, await ws.files());
7009
7761
  const local = global ? checkGlobalStructure(files) : checkStructure(files);
7010
- // A Site checks against the Global Working Copy its Preview would upload (ADR 0021).
7762
+ // A Site checks against the Global Working Copy its Preview would upload (ADR 0217).
7011
7763
  const globalCopy = global || local.length > 0 ? undefined : await ws.globalFiles?.();
7012
7764
  const { diagnostics } =
7013
- local.length > 0
7014
- ? { diagnostics: local }
7015
- : await ws.check(files, globalCopy).then(noteSkew(ws));
7765
+ local.length > 0 ? { diagnostics: local } : await ws.check(files, globalCopy);
7016
7766
  const entries = checkEntries(diagnostics);
7017
7767
  if (diagnostics.some((d) => d.severity !== 2))
7018
7768
  throw new CommandFailure(
@@ -7025,7 +7775,7 @@ async function execute(ws, argv, stdin) {
7025
7775
  );
7026
7776
  }
7027
7777
 
7028
- // `ez format` (docs/adr/0089): the Host formats the .ts/.tsx files and answers the ones that change; a file
7778
+ // `ez format` (docs/adr/0237): the Host formats the .ts/.tsx files and answers the ones that change; a file
7029
7779
  // that does not parse stops it before anything is written. --check writes nothing and fails on a change.
7030
7780
  case "format": {
7031
7781
  if (pos.length || [...flags].some((f) => f !== "--check")) throw usage("ez format [--check]");
@@ -7053,7 +7803,7 @@ async function execute(ws, argv, stdin) {
7053
7803
  );
7054
7804
  }
7055
7805
 
7056
- // `ez preview` (docs/adr/0013): the working copy (or a retained Version) built on the Host and served at a
7806
+ // `ez preview` (docs/adr/0212): the working copy (or a retained Version) built on the Host and served at a
7057
7807
  // private URL against the live data. The name defaults to the client's (`ws.previewName`: the CLI's folder,
7058
7808
  // the studio's remembered name). A successful upload is also a check; a failed one keeps the last good build.
7059
7809
  case "preview": {
@@ -7070,7 +7820,7 @@ async function execute(ws, argv, stdin) {
7070
7820
  else if (!args[i].startsWith("--")) words.push(args[i]);
7071
7821
  }
7072
7822
  const [sub, ...rest] = words;
7073
- // Other Builders' Previews of this Site (docs/adr/0141): who is changing it, never their URLs.
7823
+ // Other Builders' Previews of this Site (docs/adr/0211): who is changing it, never their URLs.
7074
7824
  if (sub === "ls" && others) {
7075
7825
  const rows = await ws.listOtherPreviews();
7076
7826
  if (rows.length === 0) return out("No other Builder has a preview of this site.", rows);
@@ -7107,7 +7857,7 @@ async function execute(ws, argv, stdin) {
7107
7857
  throw usage("ez preview --name <name> (this client has no default preview name)");
7108
7858
  return name;
7109
7859
  };
7110
- if (sub === "delete" || sub === "rm") {
7860
+ if (sub === "delete") {
7111
7861
  const name = rest[0] ?? (await defaultName());
7112
7862
  const why = previewNameError(name);
7113
7863
  if (why) throw new Error(why);
@@ -7138,9 +7888,9 @@ async function execute(ws, argv, stdin) {
7138
7888
  });
7139
7889
  }
7140
7890
  const lines = [];
7141
- for (const t of result.schema?.created ?? []) lines.push(`created table ${t}`);
7142
- for (const c of result.schema?.added ?? []) lines.push(`added column ${c}`);
7143
- for (const i of result.schema?.indexed ?? []) lines.push(`indexed ${i}`);
7891
+ for (const t of result.schema.created) lines.push(`created table ${t}`);
7892
+ for (const c of result.schema.added) lines.push(`added column ${c}`);
7893
+ for (const i of result.schema.indexed) lines.push(`indexed ${i}`);
7144
7894
  const from = result.source.kind === "version" ? ` (v${result.source.n})` : "";
7145
7895
  if (result.status === "failed")
7146
7896
  throw new Error(
@@ -7150,7 +7900,7 @@ async function execute(ws, argv, stdin) {
7150
7900
  return out(lines.join("\n"), result);
7151
7901
  }
7152
7902
 
7153
- // `ez link` (docs/adr/0059): an address that opens the deployed app, or one of the caller's Previews (a
7903
+ // `ez link` (docs/adr/0203): an address that opens the deployed app, or one of the caller's Previews (a
7154
7904
  // bare --preview is the default name, as for `ez preview`), signed in as the caller's own Member identity.
7155
7905
  // The token travels in the fragment; the platform's handoff page spends it once.
7156
7906
  case "link": {
@@ -7227,8 +7977,7 @@ async function execute(ws, argv, stdin) {
7227
7977
  return out(`Edited ${path}.`, { path });
7228
7978
  }
7229
7979
 
7230
- case "delete":
7231
- case "rm": {
7980
+ case "delete": {
7232
7981
  const [path] = pos;
7233
7982
  if (!path) throw usage("ez delete <path>");
7234
7983
  if (path === CONTEXT_FILE)
@@ -7284,10 +8033,6 @@ async function execute(ws, argv, stdin) {
7284
8033
  const updated = await ws.updateSettings({ name });
7285
8034
  return out(`name: ${updated.name}`, updated);
7286
8035
  }
7287
- if (field === "signup")
7288
- throw new Error(
7289
- "There is no sign-up mode: the deployed apps are invite-only (ez user add <email>).",
7290
- );
7291
8036
  throw usage("ez config set name <value>");
7292
8037
  }
7293
8038
 
@@ -7308,10 +8053,6 @@ async function execute(ws, argv, stdin) {
7308
8053
  const updated = await ws.updateInstance({ name });
7309
8054
  return out(`name: ${updated.name}`, updated);
7310
8055
  }
7311
- if (field === "signup")
7312
- throw new Error(
7313
- "There is no sign-up mode: the deployed apps are invite-only (ez user add <email>).",
7314
- );
7315
8056
  throw usage("ez instance config set name <value>");
7316
8057
  }
7317
8058
 
@@ -7338,7 +8079,7 @@ async function execute(ws, argv, stdin) {
7338
8079
  { instance: inst.id, ...site },
7339
8080
  );
7340
8081
  }
7341
- if (sub === "archive" || sub === "rm") {
8082
+ if (sub === "archive") {
7342
8083
  const [, id] = pos;
7343
8084
  if (!id) throw usage("ez site archive <id>");
7344
8085
  const inst = await ws.instanceStatus();
@@ -7354,7 +8095,7 @@ async function execute(ws, argv, stdin) {
7354
8095
  const render = (a) => {
7355
8096
  if (!a.restricted)
7356
8097
  return out(
7357
- `open to every builder and member of the instance (run \`ez site access restrict\` to use allow-lists)${(a.groups ?? []).length ? `; restricting admits the groups ${a.groups.join(", ")}` : ""}`,
8098
+ `open to every builder and member of the instance (run \`ez site access restrict\` to use allow-lists)${a.groups.length ? `; restricting admits the groups ${a.groups.join(", ")}` : ""}`,
7358
8099
  a,
7359
8100
  );
7360
8101
  const lines = [
@@ -7367,14 +8108,14 @@ async function execute(ws, argv, stdin) {
7367
8108
  for (const p of a.members) lines.push(` ${p.email}${p.name ? ` ${p.name}` : ""}`);
7368
8109
  if (a.members.length === 0) lines.push(" (none)");
7369
8110
  lines.push("groups (their members, implied groups included):");
7370
- for (const g of a.groups ?? []) lines.push(` ${g}`);
7371
- if ((a.groups ?? []).length === 0) lines.push(" (none)");
8111
+ for (const g of a.groups) lines.push(` ${g}`);
8112
+ if (a.groups.length === 0) lines.push(" (none)");
7372
8113
  return out(lines.join("\n"), a);
7373
8114
  };
7374
8115
  if (verb === undefined) return render(await ws.siteAccess());
7375
8116
  if (verb === "restrict") return render(await ws.setRestricted(true));
7376
8117
  if (verb === "open") return render(await ws.setRestricted(false));
7377
- if ((verb === "add" || verb === "remove" || verb === "rm") && kind === "group" && who) {
8118
+ if ((verb === "add" || verb === "remove") && kind === "group" && who) {
7378
8119
  if (!GROUP_RE.test(who))
7379
8120
  throw new Error(
7380
8121
  `A group name is lowercase letters, digits and -, starting with a letter (at most 40): ${who}`,
@@ -7388,7 +8129,7 @@ async function execute(ws, argv, stdin) {
7388
8129
  );
7389
8130
  }
7390
8131
  if (
7391
- (verb === "add" || verb === "remove" || verb === "rm") &&
8132
+ (verb === "add" || verb === "remove") &&
7392
8133
  (kind === "builder" || kind === "user") &&
7393
8134
  who
7394
8135
  ) {
@@ -7410,7 +8151,7 @@ async function execute(ws, argv, stdin) {
7410
8151
  "ez site access [restrict|open|add builder|user <who>|add group <name>|remove builder|user <who>|remove group <name>]",
7411
8152
  );
7412
8153
  }
7413
- throw usage("ez site <ls|create|archive|rm|access> ...");
8154
+ throw usage("ez site <ls|create|archive|access> ...");
7414
8155
  }
7415
8156
 
7416
8157
  case "builders": {
@@ -7457,7 +8198,7 @@ async function execute(ws, argv, stdin) {
7457
8198
  await ws.setBuilderRole(target.id, role);
7458
8199
  return out(`${target.email} is now ${role}.`, { id: target.id, email: target.email, role });
7459
8200
  }
7460
- if (sub === "remove" || sub === "rm") {
8201
+ if (sub === "remove") {
7461
8202
  const [, who] = pos;
7462
8203
  if (!who) throw usage("ez builder remove <who>");
7463
8204
  const target = await resolvePerson(() => ws.listBuilders(), who, "builder");
@@ -7515,15 +8256,7 @@ async function execute(ws, argv, stdin) {
7515
8256
  row,
7516
8257
  );
7517
8258
  }
7518
- if (sub === "delete" || sub === "rm") {
7519
- if (!name) throw usage("ez asset delete <name> [--force]");
7520
- const rows = await ws.listAssets();
7521
- const hit = rows.find((r) => r.name === name);
7522
- if (!hit) throw new Error(`No such asset: ${name}`);
7523
- await ws.deleteAsset(hit.id, flags.has("--force"));
7524
- return out(`Deleted asset ${name}.`, { id: hit.id, name });
7525
- }
7526
- throw usage("ez asset add <name> <file> | ls | delete <name> [--force]");
8259
+ throw usage("ez asset add <name> <file> | ls");
7527
8260
  }
7528
8261
 
7529
8262
  case "users": {
@@ -7534,7 +8267,7 @@ async function execute(ws, argv, stdin) {
7534
8267
  .sort((a, b) => a.email.localeCompare(b.email))
7535
8268
  .map(
7536
8269
  (u) =>
7537
- `${u.email} ${u.status}${u.name ? ` ${u.name}` : ""}${u.groups?.length ? ` groups: ${u.groups.join(", ")}` : ""}${inviteSuffix(u)}`,
8270
+ `${u.email} ${u.status}${u.name ? ` ${u.name}` : ""}${u.groups.length ? ` groups: ${u.groups.join(", ")}` : ""}${inviteSuffix(u)}`,
7538
8271
  )
7539
8272
  .join("\n"),
7540
8273
  rows,
@@ -7569,7 +8302,7 @@ async function execute(ws, argv, stdin) {
7569
8302
  status: sub === "block" ? "blocked" : "active",
7570
8303
  });
7571
8304
  }
7572
- if (sub === "remove" || sub === "rm") {
8305
+ if (sub === "remove") {
7573
8306
  const [, who] = pos;
7574
8307
  if (!who) throw usage("ez user remove <who>");
7575
8308
  const target = await resolvePerson(() => ws.listUsers(), who, "member");
@@ -7581,14 +8314,14 @@ async function execute(ws, argv, stdin) {
7581
8314
  }
7582
8315
  if (sub === "group") {
7583
8316
  const [, verb, who, group] = pos;
7584
- if ((verb !== "add" && verb !== "remove" && verb !== "rm") || !who || !group)
8317
+ if ((verb !== "add" && verb !== "remove") || !who || !group)
7585
8318
  throw usage("ez user group add|remove <who> <group>");
7586
8319
  if (!GROUP_RE.test(group))
7587
8320
  throw new Error(
7588
8321
  `A group name is lowercase letters, digits and -, starting with a letter (at most 40): ${group}`,
7589
8322
  );
7590
8323
  const target = await resolvePerson(() => ws.listUsers(), who, "member");
7591
- const had = target.groups ?? [];
8324
+ const had = target.groups;
7592
8325
  const groups =
7593
8326
  verb === "add" ? [...new Set([...had, group])].sort() : had.filter((g) => g !== group);
7594
8327
  if (groups.length !== had.length) await ws.setUserGroups(target.id, groups);
@@ -7639,7 +8372,7 @@ async function execute(ws, argv, stdin) {
7639
8372
  }
7640
8373
 
7641
8374
  case "integration": {
7642
- // docs/adr/0092, 0138, 0140: every secret (a credential's value, a basic password, an OAuth client
8375
+ // docs/adr/0231, 0252: every secret (a credential's value, a basic password, an OAuth client
7643
8376
  // secret, a secret value) arrives on stdin (piped, or the CLI's hidden prompt), never as an argument,
7644
8377
  // and no result carries it.
7645
8378
  const credentialSyntax =
@@ -7793,7 +8526,7 @@ async function execute(ws, argv, stdin) {
7793
8526
  if (originError) throw new Error(originError);
7794
8527
  return { binding: { origin: new URL(origin).origin, credential }, preset };
7795
8528
  };
7796
- /** A preset's plain values, set on the binding after it (docs/adr/0138), the last answer kept. */
8529
+ /** A preset's plain values, set on the binding after it (docs/adr/0231), the last answer kept. */
7797
8530
  const presetValues = async (
7798
8531
  /** @type {import("./commands.d.mts").OAuthPreset | null} */ preset,
7799
8532
  /** @type {"production" | "preview"} */ bindingName,
@@ -7836,7 +8569,7 @@ async function execute(ws, argv, stdin) {
7836
8569
  const sites = given["--sites"];
7837
8570
  if (sites !== undefined) {
7838
8571
  const ids = sites === "all" ? "all" : sites.split(",").map((id) => id.trim());
7839
- // `global` names the Global Workspace's jobs (ADR 0136).
8572
+ // `global` names the Global Workspace's jobs (ADR 0230).
7840
8573
  if (
7841
8574
  ids !== "all" &&
7842
8575
  (!ids.length || ids.some((id) => id !== GLOBAL_ID && !isValidSiteId(id)))
@@ -7972,7 +8705,7 @@ async function execute(ws, argv, stdin) {
7972
8705
  }
7973
8706
 
7974
8707
  case "listener": {
7975
- // docs/adr/0092: a secret arrives on stdin (piped, or the CLI's hidden prompt), never as an argument.
8708
+ // docs/adr/0231: a secret arrives on stdin (piped, or the CLI's hidden prompt), never as an argument.
7976
8709
  const syntax =
7977
8710
  "ez listener list | secret <name> [--overlap <hours>] | secret <name> --remove | events <name> [--dead] | show <name> <event-id> | retry <name> <event-id>";
7978
8711
  const [sub, name, ...extra] = pos;
@@ -8085,7 +8818,7 @@ async function execute(ws, argv, stdin) {
8085
8818
  }
8086
8819
 
8087
8820
  case "key": {
8088
- // docs/adr/0119, docs/adr/0151: the Instance's API Keys, each shown once, by create, and never again.
8821
+ // docs/adr/0232: the Instance's API Keys, each shown once, by create, and never again.
8089
8822
  const syntax =
8090
8823
  "ez key list | create <name> [--groups <a,b>] [--sites <all | ids>] [--expires <days>] | revoke <name>";
8091
8824
  const VALUES = ["--groups", "--sites", "--expires"];
@@ -8178,7 +8911,7 @@ async function execute(ws, argv, stdin) {
8178
8911
  }
8179
8912
 
8180
8913
  case "email": {
8181
- // docs/adr/0149: the Emails the Instance's server code sent, newest first.
8914
+ // docs/adr/0234: the Emails the Instance's server code sent, newest first.
8182
8915
  const syntax =
8183
8916
  "ez email list [--site <id>] [--status <status>] [--since <YYYY-MM-DD>] [--limit <n>] | ez email show <id> [--html]";
8184
8917
  const [sub, ...rest] = args;
@@ -8241,7 +8974,7 @@ async function execute(ws, argv, stdin) {
8241
8974
  }
8242
8975
 
8243
8976
  case "support": {
8244
- // docs/adr/0080: a request to the Host's Developers, not to this Instance's Admins.
8977
+ // docs/adr/0208: a request to the Host's Developers, not to this Instance's Admins.
8245
8978
  const syntax =
8246
8979
  "ez support open <subject> [--body <text>] | ez support list | ez support show <id>";
8247
8980
  const [sub, ...rest] = args;
@@ -8332,11 +9065,11 @@ async function execute(ws, argv, stdin) {
8332
9065
  const lines = [];
8333
9066
  for (const t of tables) {
8334
9067
  lines.push(
8335
- `${t.name} ${plural(t.rows, "row")} ${t.history ? `the History of ${t.history} (read-only)` : `declared by ${t.sites.length ? t.sites.join(", ") : "no site"}`}`,
9068
+ `${t.name} ${plural(t.rows, "row")}${t.history ? ` the History of ${t.history} (read-only)` : ""}`,
8336
9069
  );
8337
9070
  for (const [c, d] of Object.entries(t.columns)) lines.push(` ${c} ${d}`);
8338
9071
  for (const cols of t.indexes) lines.push(` index (${cols.join(", ")})`);
8339
- for (const cols of t.unique ?? []) lines.push(` unique index (${cols.join(", ")})`);
9072
+ for (const cols of t.unique) lines.push(` unique index (${cols.join(", ")})`);
8340
9073
  }
8341
9074
  return out(lines.join("\n"), tables);
8342
9075
  }
@@ -8345,6 +9078,12 @@ async function execute(ws, argv, stdin) {
8345
9078
  return out(renderSchema(schema).trimEnd(), schema);
8346
9079
  }
8347
9080
  if (sub === "sql") {
9081
+ // A flag is never part of the statement: dropped silently, its value would be read as SQL.
9082
+ const stray = args.filter((a) => /^--[a-z]/.test(a) && a !== "--json");
9083
+ if (stray.length)
9084
+ throw usage(
9085
+ `ez db sql <statement> (or pipe the statement on stdin). It takes no ${stray[0]}${stray[0] === "--preview" ? ": the App Database is one, for the live app and every Preview alike" : " and no other flag: put the whole statement in quotes"}`,
9086
+ );
8348
9087
  const statement = (pos.slice(1).join(" ") || stdin || "").trim();
8349
9088
  if (!statement) throw usage("ez db sql <statement> (or pipe the statement on stdin)");
8350
9089
  const r = await ws.dbSql(statement);