@quickback-dev/cli 0.51.1 → 0.52.1

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.
@@ -35,11 +35,21 @@ export default defineTable(applications, {
35
35
  onDelete: true, // Broadcast on DELETE (default: true)
36
36
  access: { roles: ["recruiter", "hiring-manager"] }, // Audience — MANDATORY, fail-closed
37
37
  fields: ["id", "candidateId", "stage"], // Fields to include (optional)
38
+ scopeKeyFrom: "events:{eventId}", // Sugar for scopeTable + scopeField (optional)
39
+ emitFromActions: true, // Custom-action writes auto-emit after commit (optional)
38
40
  },
39
41
  // ... guards, crud
40
42
  });
41
43
  ```
42
44
 
45
+ `scopeKeyFrom` routes broadcasts to a resource lane instead of the default
46
+ org room — the template form (`"events:{eventId}"`) names the prefix and the
47
+ row column in one string; a bare column name inherits the prefix from
48
+ `scopeTable` (or the project-level ws-ticket default). `emitFromActions`
49
+ extends the same broadcasts to writes made through the scoped `db` inside
50
+ custom record-bound and bulk actions — see the boundary table below. It
51
+ triggers the same mandatory-audience check auto-CRUD broadcasts have.
52
+
43
53
  When any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.
44
54
 
45
55
  At the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need resource-scoped tickets. The mint gate accepts three authorization vocabularies via the discriminated `access` form — pick exactly one arm:
@@ -123,17 +133,20 @@ function can't be replicated by the Broadcaster, so those columns broadcast
123
133
  as `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,
124
134
  as before.
125
135
 
126
- Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.
136
+ Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually **unless the table opts in to action emission** (see below). In action handlers on realtime-enabled projects, Quickback injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.
127
137
 
128
138
  | Mutation site | Auto-broadcast? | Why |
129
139
  |---|---|---|
130
140
  | Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |
131
141
  | Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |
132
- | `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |
133
- | `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |
142
+ | `db.insert/update/delete` inside a record-bound action, table declares `realtime.emitFromActions: true` | Yes — after commit | The scoped db records each write into a per-request capture collector (recording only — it never calls the transport itself); the route emits identical auto-CRUD frames after `execute` succeeds, via the after-commit effects machinery. |
143
+ | `db.insert/update/delete` inside an action handler (no `emitFromActions`) | No — manual | Scoped-db stays a query-shape wrapper (firewall + soft-delete WHERE injection) with no broadcast side-effects. |
144
+ | `unsafeDb` writes in actions (or any custom route) | No — manual | `unsafeDb` is the un-wrapped escape hatch — invisible to capture too. |
134
145
  | Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |
135
146
 
136
- The rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.
147
+ The rule of thumb: opt the table into `realtime: { emitFromActions: true }` (or give the action an `emit:` block for the pre-bound `emitCrud(row, oldRow?)` helper) and the frames take care of themselves; otherwise, if your code calls `db.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line.
148
+
149
+ Two capture caveats: inserts that skip `.returning()` emit the values as written (DB-default columns absent), and updates/deletes cost one extra pre-select on the same WHERE — it replaces the hand-written read every manual emit needed anyway. Capture covers the feature's own table on record-bound and bulk routes; standalone actions and cross-feature writes use `emit:`/`emitCrud` or the raw `realtime.*` API.
137
150
 
138
151
  ## Generated Helper
139
152
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.51.1",
3
+ "version": "0.52.1",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -1,7 +1,92 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
4
-
3
+ ## v0.52.1 — July 17, 2026
4
+
5
+ ### CLI: cold-start tolerance for the cloud compiler
6
+
7
+ Right after a service deploy, the first compile pays a fresh container image
8
+ pull — which routinely exceeds the CLI's old 60-second readiness budget and
9
+ surfaced as `Compiler container did not become ready in time` even while
10
+ `/health` was green. `waitForReady` now allows 4 minutes, reports elapsed
11
+ warm-up progress, and the timeout message explains the deploy-in-progress
12
+ case.
13
+
14
+ ## v0.52.0 — July 17, 2026
15
+
16
+ ### Five action primitives: afterCommit, realtime emit, transitions v2, refs, bundles
17
+
18
+ One release, five primitives that collapse the most-repeated hand-written
19
+ patterns in real Quickback projects (measured across a 349-action production
20
+ corpus). Every one is additive — existing projects compile unchanged, and
21
+ plain `{ field, fromTo, to|via }` transitions keep their emission
22
+ byte-identical.
23
+
24
+ - **`afterCommit` hooks + `effects.enqueue`** — named best-effort side
25
+ effects that run after `execute` returns. Each hook is independently
26
+ wrapped (failures log as `[<action>] afterCommit:<hook> failed`, never
27
+ touching the response), non-blocking hooks ride `executionCtx.waitUntil`,
28
+ `{ blocking: true }` awaits before responding, and everything skips when
29
+ `execute` throws or returns `dryRun: true`. The execute context also gains
30
+ `effects.enqueue(name, fn)` for mid-execute captures and `now` — one ISO
31
+ timestamp per invocation. Replaces the per-leg `try/catch + waitUntil`
32
+ idiom. See [After-commit hooks](/compiler/definitions/actions#after-commit-hooks).
33
+
34
+ - **Realtime emit for custom actions** — tables that lock auto-CRUD no
35
+ longer hand-roll frames. `realtime: { emitFromActions: true, scopeKeyFrom:
36
+ "events:{eventId}" }` makes scoped-db writes inside record-bound and bulk
37
+ actions emit auto-CRUD-byte-compatible frames after commit (masking +
38
+ audience applied at fanout; the fail-closed audience requirement extends to
39
+ action emission). Actions can also declare `emit:` for a pre-bound
40
+ `emitCrud(row, oldRow?)`. Updates/deletes pre-select old rows on the same
41
+ WHERE; raw `unsafeDb` writes stay invisible. See
42
+ [When auto-broadcast fires](/stack/realtime/durable-objects#when-auto-broadcast-fires-and-when-you-call-it-manually).
43
+
44
+ - **Transitions v2** — `transition` grows `guard` (equality / null / notNull
45
+ / `custom(record)`), `onIllegal { code, status, message }`, `idempotent:
46
+ "noop"`, and `stamp`/`clears` that ride a compiler-applied, TOCTOU-safe
47
+ UPDATE (guards fold into the WHERE; a lost race is 409
48
+ `ACCESS_TRANSITION_LOST`). With an applied write, `execute` becomes
49
+ optional. Table-level `transitions: { publish: { field, from, to, access } }`
50
+ *generates* the action files — including `undo:` inverses and `onEnter`
51
+ cascades — mounted exactly where hand-written files would be (explicit
52
+ files win, with a warning). The ten byte-identical publish/revert files in
53
+ the podcast fixture become two lines per entity. See
54
+ [Transitions](/compiler/definitions/transitions).
55
+
56
+ - **`refs` — scoped foreign-key inputs** — the "load the id, 404 if missing,
57
+ assert it belongs to this event" preamble becomes declarative. Loads run
58
+ through the scoped db (a cross-org id 404s by construction), batch into one
59
+ `Promise.all`, assert `matchScope` / cross-input `matchWith` parenthood, and
60
+ inject rows under their `as` names. Ref keys are validated against the
61
+ inline `z.object` input (with agreeing optionality) at compile time. See
62
+ [Refs](/compiler/definitions/actions#refs-scoped-foreign-key-inputs).
63
+
64
+ - **`defineBundle` — single-round-trip bootstrap reads** — declarative
65
+ `list()` slices with the firewall, the table's *real* mask functions, and
66
+ `{ data }` cache-seed envelopes; `custom()` escape-hatch sections; a SHA-1
67
+ ETag over `{ scopeSeed, userId, payload }` with the `ifNoneMatch →
68
+ notModified` short-circuit; and `Server-Timing`. Fail-closed: a bundle's
69
+ roles must be a subset of every list table's `read.access` roles — a bundle
70
+ can never widen read access. The digest ships as `sha1Hex` in `lib/etag`
71
+ so hand-written reads can delete their copies. See
72
+ [Bundles](/compiler/definitions/bundles).
73
+
74
+ Supporting changes: `ActionError` / `TransitionLostError` are re-exported
75
+ from the generated `.quickback/define-action` helpers (routes duck-type on
76
+ `error.name`, so project-local copies keep working); `sendQueueBatched` in
77
+ `lib/effects` chunks queue sends at the Cloudflare 100-message cap; and the
78
+ `$record.*` / `$ctx.*` substitution grammar used by `onEnter` and bundle
79
+ `where` is one strict allowlist, always parameterized — never interpolated
80
+ into SQL.
81
+
82
+ ### CLI device login fixed: /cli/authorize now claims the code before approving
83
+
84
+ Better Auth's `deviceAuthorization` plugin requires the verifying session to
85
+ claim a device code (`GET /device?user_code=…`) before it accepts an approve
86
+ or deny. The account SPA's `/cli/authorize` page posted the approval directly,
87
+ so every `quickback login` failed with *"Device code has not been claimed by
88
+ a verifying session."* The page now claims first, then approves — and surfaces
89
+ claim failures (expired or mistyped codes) with the server's message.
5
90
  ### Generated builds no longer rewrite the auth schema
6
91
 
7
92
  Generated Better Auth projects now run `tsc` directly from `npm run build`.
@@ -1305,6 +1305,117 @@ The same 409 code is used when an `access.record` predicate (without
1305
1305
  called against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,
1306
1306
  not a misleading 403.
1307
1307
 
1308
+ Transitions grew a v2 surface — guards, timestamp/actor stamps, idempotent
1309
+ no-ops, compiler-applied writes with optional `execute`, `undo` pairs, and
1310
+ table-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.
1311
+
1312
+ ## After-commit hooks
1313
+
1314
+ Secondary effects — activity feeds, notification nudges, cache warmers — must
1315
+ never roll back or delay the primary write. Instead of hand-wrapping each leg
1316
+ in `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:
1317
+
1318
+ ```typescript
1319
+ export default defineAction({
1320
+ // ...
1321
+ execute: async ({ db, record, ctx, now }) => {
1322
+ await db.update(guests).set({ checkedInAt: now }).where(/* … */);
1323
+ return { success: true, checkedInAt: now };
1324
+ },
1325
+ afterCommit: {
1326
+ // Named hooks run after execute returns successfully, in declared order.
1327
+ activityFeed: async ({ db, env, record, ctx }, result) => {
1328
+ await recordActivity(db, env, { verb: "guest.checked_in", /* … */ });
1329
+ },
1330
+ // blocking: true is awaited before the response (client depends on it).
1331
+ issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },
1332
+ },
1333
+ });
1334
+ ```
1335
+
1336
+ The contract:
1337
+
1338
+ - Hooks receive `(actx, result)` — the same context `execute` got, plus its
1339
+ return value.
1340
+ - Each hook is **independently wrapped**: a throw is logged as
1341
+ `[<action>] afterCommit:<hook> failed` and never affects the response or
1342
+ other hooks.
1343
+ - Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking
1344
+ hooks are awaited before responding.
1345
+ - If `execute` throws, no hooks run. A result carrying `dryRun: true` also
1346
+ skips them (preview branches never fire side effects).
1347
+ - Bulk twins run hooks **once per invocation** with the bulk envelope as
1348
+ `result` — per-record fan-out is the hook author's job.
1349
+
1350
+ For effects that need mid-execute data, the context carries an imperative
1351
+ escape hatch with the same semantics:
1352
+
1353
+ ```typescript
1354
+ execute: async ({ db, effects }) => {
1355
+ // …
1356
+ effects.enqueue("cohortRecalc", () => recalculate(/* … */));
1357
+ return { success: true };
1358
+ }
1359
+ ```
1360
+
1361
+ Effects enqueued by an `execute` that later throws are dropped. The context
1362
+ also carries `now` — one ISO timestamp per invocation; prefer it over
1363
+ `new Date().toISOString()`.
1364
+
1365
+ ## Realtime emit from actions
1366
+
1367
+ Tables that lock auto-CRUD but mutate through custom actions no longer need
1368
+ hand-written `realtime.insert/update/delete` blocks. Opt the table in:
1369
+
1370
+ ```typescript
1371
+ realtime: {
1372
+ enabled: true,
1373
+ access: { roles: ["member+"] },
1374
+ scopeKeyFrom: "events:{eventId}", // sugar for scopeTable + scopeField
1375
+ emitFromActions: true, // scoped-db writes auto-emit after commit
1376
+ }
1377
+ ```
1378
+
1379
+ Writes to the table through the scoped `db` inside record-bound and bulk
1380
+ actions emit frames byte-compatible with auto-CRUD (same envelope, masking,
1381
+ audience), after commit, best-effort. For projections, standalone actions, or
1382
+ cross-feature targets, declare an action-level `emit:` to get a pre-bound
1383
+ `emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in
1384
+ the [realtime docs](/stack/realtime/durable-objects).
1385
+
1386
+ ## Refs (scoped foreign-key inputs)
1387
+
1388
+ The most common action preamble — load an input id, 404 if missing, assert it
1389
+ belongs to the caller's event/org — becomes declarative:
1390
+
1391
+ ```typescript
1392
+ export default defineAction({
1393
+ input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),
1394
+ refs: {
1395
+ agendaItemId: { table: "agendaItems", as: "agendaItem",
1396
+ matchScope: "event", // row.eventId === ctx.event.id
1397
+ notFound: { code: "ITEM_NOT_FOUND" } }, // status defaults to 404
1398
+ guestId: { table: "guests", as: "guest",
1399
+ matchWith: { ref: "agendaItem", on: "eventId" }, // cross-input parenthood
1400
+ mismatch: { code: "EVENT_MISMATCH", status: 400 } },
1401
+ locationId: { table: "locations", as: "location", optional: true, matchScope: "event" },
1402
+ },
1403
+ execute: async ({ input, agendaItem, guest, location }) => { /* … */ },
1404
+ });
1405
+ ```
1406
+
1407
+ - Loads run **through the scoped db** before `execute` — the org firewall and
1408
+ soft-delete filter apply by construction, so a cross-org id 404s with zero
1409
+ hand-written tenancy checks. All loads batch into one `Promise.all`.
1410
+ - `matchScope: "<scope>"` asserts `row.<scope>Id === ctx.<scope>.id` and
1411
+ fail-closes (500) if the scope object isn't hydrated. The explicit form
1412
+ `{ column, equals: "ctx.activeOrgId" }` is also accepted.
1413
+ - `matchWith` compares a column against an earlier-declared ref — declaration
1414
+ order defines resolution order; forward references are compile errors.
1415
+ - Ref keys must exist on the inline `z.object` input with agreeing
1416
+ optionality; `as` names can't shadow reserved context keys. Injected rows
1417
+ are the **unmasked** DB rows (masking remains a read-projection concern).
1418
+
1308
1419
  ## Examples
1309
1420
 
1310
1421
  ### Bulk Import (Standalone, No Record)
@@ -0,0 +1,69 @@
1
+ # Bundles
2
+
3
+ ## Overview
4
+
5
+ Client bootstrap screens want many small lists in one request. Hand-written
6
+ "bundle" endpoints all repeat the same 150 lines: a `Promise.all` of selects
7
+ shaped byte-identically to the CRUD list endpoints they replace, a
8
+ `sections: string[]` subset filter, a copy-pasted SHA-1 ETag +
9
+ `ifNoneMatch → notModified` short-circuit, a `Server-Timing` header, and
10
+ hand-re-derived per-slice masking. `defineBundle` generates all of it.
11
+
12
+ ```typescript
13
+ // features/events/actions/getOverviewBundle.ts
14
+ import { defineBundle, list, custom } from "../.quickback/define-bundle";
15
+
16
+ export default defineBundle({
17
+ path: "/event/:eventId/overview-bundle",
18
+ description: "Console Overview bootstrap",
19
+ access: { roles: ["member", "admin"] },
20
+ etag: true, // default true
21
+ serverTiming: "overview", // optional
22
+ sections: {
23
+ guests: list("guests", {
24
+ columns: ["id", "status", "modifiedAt", "createdAt", "displayName"],
25
+ where: { eventId: "$ctx.event.id" },
26
+ orderBy: [{ createdAt: "desc" }],
27
+ limit: 500,
28
+ }),
29
+ tickets: list("supportTickets", { where: { eventId: "$ctx.event.id" }, orderBy: [{ modifiedAt: "desc" }], limit: 100 }),
30
+ counts: custom(async ({ db, ctx }) => ({ open: 0 })), // computed slice — author owns masking
31
+ },
32
+ });
33
+ ```
34
+
35
+ ## Semantics
36
+
37
+ - **Generated POST action** with input `{ sections?: string[], ifNoneMatch?: string }`,
38
+ mounted through the standard standalone pipeline — auth, access, org/team
39
+ preconditions, rate limits, OpenAPI, MCP tools, security contracts all
40
+ apply.
41
+ - **`list()` sections run through the scoped db** — the org firewall and
42
+ soft-delete filter apply by construction — and the target table's REAL
43
+ mask function is applied (the same read projection the CRUD list endpoint
44
+ runs), so masked columns are safe to include. Every list slice lands as
45
+ `{ data: rows }` (the per-resource cache-seed contract).
46
+ - **`sections` filter**: omitted/empty = all. An un-wanted list section
47
+ returns `{ data: [] }` (drop-in compatible with existing clients);
48
+ un-wanted `custom` sections are absent.
49
+ - **All sections run in one `Promise.all`.**
50
+ - **ETag**: SHA-1 hex over `{ scopeSeed: <path params>, userId, payload }`.
51
+ An `ifNoneMatch` match returns `{ success: true, etag, notModified: true }`
52
+ with **no sections**. The digest is also exported as `sha1Hex` from
53
+ `lib/etag` so remaining hand-written reads can delete their copies.
54
+ - **`custom()` sections** receive the full action context and are embedded
55
+ verbatim under the section name — the author owns masking there.
56
+
57
+ ## Compile-time validation (fail-closed)
58
+
59
+ - Unknown section tables error, listing candidates.
60
+ - `columns` / `where` / `orderBy` must name declared columns
61
+ (compiler-injected audit columns like `createdAt`/`modifiedAt` are allowed).
62
+ - `where` values are literals or the strict substitution allowlist
63
+ (`$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id`) — always
64
+ parameterized. Anything richer belongs in a `custom()` section.
65
+ - Section names may not shadow the response envelope
66
+ (`success`, `etag`, `notModified`, `sections`).
67
+ - **A bundle must never widen read access**: its `access.roles` must be a
68
+ subset of every list section table's `read.access` roles — a violation is
69
+ a compile error, not a warning.
@@ -204,7 +204,7 @@ read: {
204
204
  Masking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths — a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:
205
205
 
206
206
  - **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).
207
- - **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (`sql\`…\${record.col}\``) are fine — only the storage/payload sinks are flagged.
207
+ - **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (``sql`…${record.col}` ``) are fine — only the storage/payload sinks are flagged.
208
208
  - **Realtime → webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.
209
209
 
210
210
  ### Revealing a value on purpose: `unmask()`
@@ -229,7 +229,7 @@ masking: {
229
229
  }
230
230
  ```
231
231
 
232
- `egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/docs/compiler/definitions/encryption).
232
+ `egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/compiler/definitions/encryption).
233
233
 
234
234
  ## Complete Example
235
235
 
@@ -0,0 +1,149 @@
1
+ # Transitions
2
+
3
+ ## Overview
4
+
5
+ Most state changes follow the same shape: check the row is in a legal state,
6
+ flip a column, stamp who/when, maybe cascade. Before transitions v2 every one
7
+ of those was a hand-written action file — a podcast app had **ten files that
8
+ were byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`
9
+ across five entities), and an events app had eight near-identical
10
+ check-in/check-out files.
11
+
12
+ Transitions v2 collapses both patterns:
13
+
14
+ - **Action-level extensions** on `defineAction({ transition })` — guards,
15
+ stamps, idempotency, compiler-applied writes.
16
+ - **Table-level `transitions`** on `defineTable` — the compiler *generates*
17
+ the action files, including `undo` inverses and `onEnter` cascades.
18
+
19
+ ## The marquee example: 10 files → 2 lines each
20
+
21
+ Before (×10 files across episodes/shows/seasons/collections/profiles):
22
+
23
+ ```typescript
24
+ // actions/episodes/publish.ts — and nine siblings like it
25
+ export default defineAction({
26
+ description: "Publish an episode",
27
+ input: z.object({}),
28
+ access: { roles: ["admin+"] },
29
+ async execute({ db, record }) {
30
+ const [updated] = await db.update(episodes)
31
+ .set({ isPublished: true })
32
+ .where(eq(episodes.id, record.id)).returning();
33
+ return updated;
34
+ },
35
+ });
36
+ ```
37
+
38
+ After — on each entity's `defineTable`:
39
+
40
+ ```typescript
41
+ export default defineTable(episodes, {
42
+ // ...
43
+ transitions: {
44
+ publish: { field: "isPublished", from: false, to: true, access: { roles: ["admin+"] } },
45
+ revertToDraft: { field: "isPublished", from: true, to: false, access: { roles: ["admin+"] } },
46
+ },
47
+ });
48
+ ```
49
+
50
+ The generated actions mount exactly where the hand-written files did
51
+ (`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool
52
+ name), ride the same OpenAPI/security-contract pipeline, and delete cleanly:
53
+ **an explicit `actions/<name>.ts` file always wins** (the compiler warns about
54
+ the shadowed transitions entry).
55
+
56
+ ## Action-level extensions
57
+
58
+ All new keys are optional — a plain `{ field, fromTo, to|via }` transition
59
+ behaves exactly as before.
60
+
61
+ ```typescript
62
+ transition: {
63
+ field: "status",
64
+ to: "confirmed",
65
+ fromTo: { pending: ["confirmed"] },
66
+ // v2:
67
+ guard: { // extra row preconditions
68
+ status: "confirmed", // equality
69
+ checkedInAt: { null: true }, // or { notNull: true }
70
+ custom: (record) => record.eventId !== null, // escape hatch; may throw ActionError
71
+ },
72
+ onIllegal: { code: "GUEST_NOT_CONFIRMED", status: 409, message: "Only confirmed guests can be checked in" },
73
+ idempotent: "noop", // already-in-target → { success: true, unchanged: true }
74
+ stamp: { at: "checkedInAt", by: "checkedInById" }, // now-ISO / ctx.userId
75
+ clears: ["checkedOutAt", "checkedOutById"], // nulled on transition
76
+ }
77
+ ```
78
+
79
+ Semantics:
80
+
81
+ - **Guards** run against the fetched record *and* fold into the UPDATE's
82
+ WHERE, so preconditions re-validate atomically at the SQL layer (an empty
83
+ `RETURNING` maps to 409 `ACCESS_TRANSITION_LOST`). Guard failures return
84
+ `onIllegal` (default 409 `TRANSITION_GUARD_FAILED`); on bulk twins they
85
+ report per-id in the batch envelope.
86
+ - **Compiler-applied writes**: declaring `stamp`/`clears` (or
87
+ `applyBefore: true`) makes the compiler execute the UPDATE itself before
88
+ `execute` — and `execute` becomes optional. An omitted `execute` returns
89
+ `{ success: true, <field>: <to>, <stamp.at>: <now> }`. Set
90
+ `applyBefore: false` to keep the write in your own `execute` (today's
91
+ behavior).
92
+ - **`field: null`** declares a pure stamp transition (check-in/check-out
93
+ style) — guards + stamps with no state column.
94
+ - **`actx.now`**: every action's execute context now carries `now` — one ISO
95
+ timestamp per invocation. Prefer it over `new Date().toISOString()`.
96
+
97
+ ## Table-level generation
98
+
99
+ ```typescript
100
+ export default defineTable(guests, {
101
+ // ...
102
+ transitions: {
103
+ checkIn: {
104
+ field: null, // pure stamp transition
105
+ guard: { status: "confirmed", checkedInAt: { null: true } },
106
+ stamp: { at: "checkedInAt", by: "checkedInById" },
107
+ undo: "cancelCheckIn", // generates the inverse
108
+ access: { roles: ["member+"] },
109
+ bulkVariant: true,
110
+ },
111
+ cancel: {
112
+ field: "status",
113
+ fromTo: { published: ["cancelled"] },
114
+ to: "cancelled",
115
+ stamp: { at: "cancelledAt" },
116
+ access: { roles: ["admin+"] },
117
+ onEnter: [
118
+ { update: "eventGuests",
119
+ set: { status: "rescinded" },
120
+ where: { eventId: "$record.id", status: { in: ["invited", "confirmed"] } } },
121
+ { enqueue: { queue: "COMMS_QUEUE",
122
+ message: { kind: "eventCancelled", eventId: "$record.id", actorId: "$ctx.userId" } } },
123
+ ],
124
+ },
125
+ },
126
+ });
127
+ ```
128
+
129
+ - **`undo: "<name>"`** generates the inverse action: the guard flips to
130
+ `{ notNull: true }` on the stamp column, the SET nulls the stamp columns,
131
+ and `from`/`to` reverse for field transitions.
132
+ - **`onEnter` steps** run in the generated `execute`, *after* the
133
+ compiler-applied primary write (parent row first). `update` steps go
134
+ through the scoped db — cross-feature targets resolve automatically and
135
+ inherit the firewall. `enqueue` steps ride the after-commit effects queue.
136
+ Substitution values are a strict allowlist — `$record.<col>`,
137
+ `$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id` — always
138
+ parameterized, never interpolated into SQL.
139
+ - **`access` is required** on every transition (fail-closed, like
140
+ `defineAction`).
141
+ - Boolean `from` values match integer-boolean columns too (`from: false`
142
+ matches both `false` and `0`).
143
+
144
+ ### Not yet supported (fail loudly)
145
+
146
+ `guard.custom` at table level, `onEnter.enqueue` with `perRowOf` or function
147
+ messages, and via-style (input-driven) targets all error with a pointer to a
148
+ hand-written action. For manual fan-out enqueues, `sendQueueBatched` in
149
+ `lib/effects` chunks at the Cloudflare Queues 100-message cap.
@@ -35,11 +35,21 @@ export default defineTable(applications, {
35
35
  onDelete: true, // Broadcast on DELETE (default: true)
36
36
  access: { roles: ["recruiter", "hiring-manager"] }, // Audience — MANDATORY, fail-closed
37
37
  fields: ["id", "candidateId", "stage"], // Fields to include (optional)
38
+ scopeKeyFrom: "events:{eventId}", // Sugar for scopeTable + scopeField (optional)
39
+ emitFromActions: true, // Custom-action writes auto-emit after commit (optional)
38
40
  },
39
41
  // ... guards, crud
40
42
  });
41
43
  ```
42
44
 
45
+ `scopeKeyFrom` routes broadcasts to a resource lane instead of the default
46
+ org room — the template form (`"events:{eventId}"`) names the prefix and the
47
+ row column in one string; a bare column name inherits the prefix from
48
+ `scopeTable` (or the project-level ws-ticket default). `emitFromActions`
49
+ extends the same broadcasts to writes made through the scoped `db` inside
50
+ custom record-bound and bulk actions — see the boundary table below. It
51
+ triggers the same mandatory-audience check auto-CRUD broadcasts have.
52
+
43
53
  When any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.
44
54
 
45
55
  At the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need resource-scoped tickets. The mint gate accepts three authorization vocabularies via the discriminated `access` form — pick exactly one arm:
@@ -123,17 +133,20 @@ function can't be replicated by the Broadcaster, so those columns broadcast
123
133
  as `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,
124
134
  as before.
125
135
 
126
- Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.
136
+ Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually **unless the table opts in to action emission** (see below). In action handlers on realtime-enabled projects, Quickback injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.
127
137
 
128
138
  | Mutation site | Auto-broadcast? | Why |
129
139
  |---|---|---|
130
140
  | Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |
131
141
  | Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |
132
- | `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |
133
- | `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |
142
+ | `db.insert/update/delete` inside a record-bound action, table declares `realtime.emitFromActions: true` | Yes — after commit | The scoped db records each write into a per-request capture collector (recording only — it never calls the transport itself); the route emits identical auto-CRUD frames after `execute` succeeds, via the after-commit effects machinery. |
143
+ | `db.insert/update/delete` inside an action handler (no `emitFromActions`) | No — manual | Scoped-db stays a query-shape wrapper (firewall + soft-delete WHERE injection) with no broadcast side-effects. |
144
+ | `unsafeDb` writes in actions (or any custom route) | No — manual | `unsafeDb` is the un-wrapped escape hatch — invisible to capture too. |
134
145
  | Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |
135
146
 
136
- The rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.
147
+ The rule of thumb: opt the table into `realtime: { emitFromActions: true }` (or give the action an `emit:` block for the pre-bound `emitCrud(row, oldRow?)` helper) and the frames take care of themselves; otherwise, if your code calls `db.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line.
148
+
149
+ Two capture caveats: inserts that skip `.returning()` emit the values as written (DB-default columns absent), and updates/deletes cost one extra pre-select on the same WHERE — it replaces the hand-written read every manual emit needed anyway. Capture covers the feature's own table on record-bound and bulk routes; standalone actions and cross-feature writes use `emit:`/`emitCrud` or the raw `realtime.*` API.
137
150
 
138
151
  ## Generated Helper
139
152