@quickback-dev/cli 0.72.8 → 0.72.10

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.
Files changed (240) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +8 -1
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/commands/db-explain.d.ts +67 -0
  5. package/dist/commands/db-explain.d.ts.map +1 -0
  6. package/dist/commands/db-explain.js +141 -0
  7. package/dist/commands/db-explain.js.map +1 -0
  8. package/dist/commands/db-export.d.ts +34 -0
  9. package/dist/commands/db-export.d.ts.map +1 -0
  10. package/dist/commands/db-export.js +250 -0
  11. package/dist/commands/db-export.js.map +1 -0
  12. package/dist/commands/db-insights.d.ts +60 -0
  13. package/dist/commands/db-insights.d.ts.map +1 -0
  14. package/dist/commands/db-insights.js +106 -0
  15. package/dist/commands/db-insights.js.map +1 -0
  16. package/dist/commands/db-recovery.d.ts +98 -0
  17. package/dist/commands/db-recovery.d.ts.map +1 -0
  18. package/dist/commands/db-recovery.js +558 -0
  19. package/dist/commands/db-recovery.js.map +1 -0
  20. package/dist/commands/db-target.d.ts +27 -0
  21. package/dist/commands/db-target.d.ts.map +1 -0
  22. package/dist/commands/db-target.js +83 -0
  23. package/dist/commands/db-target.js.map +1 -0
  24. package/dist/commands/db.d.ts +3 -0
  25. package/dist/commands/db.d.ts.map +1 -0
  26. package/dist/commands/db.js +43 -0
  27. package/dist/commands/db.js.map +1 -0
  28. package/dist/commands/effects.d.ts +8 -0
  29. package/dist/commands/effects.d.ts.map +1 -0
  30. package/dist/commands/effects.js +48 -0
  31. package/dist/commands/effects.js.map +1 -0
  32. package/dist/commands/platform-budget.d.ts +143 -0
  33. package/dist/commands/platform-budget.d.ts.map +1 -0
  34. package/dist/commands/platform-budget.js +619 -0
  35. package/dist/commands/platform-budget.js.map +1 -0
  36. package/dist/commands/preview.d.ts +57 -0
  37. package/dist/commands/preview.d.ts.map +1 -0
  38. package/dist/commands/preview.js +268 -0
  39. package/dist/commands/preview.js.map +1 -0
  40. package/dist/commands/search.d.ts +20 -0
  41. package/dist/commands/search.d.ts.map +1 -0
  42. package/dist/commands/search.js +133 -0
  43. package/dist/commands/search.js.map +1 -0
  44. package/dist/index.js +35 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/lib/api-client.d.ts +4 -0
  47. package/dist/lib/api-client.d.ts.map +1 -1
  48. package/dist/lib/api-client.js.map +1 -1
  49. package/dist/lib/cloudflare-spend-policies.d.ts +92 -0
  50. package/dist/lib/cloudflare-spend-policies.d.ts.map +1 -0
  51. package/dist/lib/cloudflare-spend-policies.js +289 -0
  52. package/dist/lib/cloudflare-spend-policies.js.map +1 -0
  53. package/dist/lib/compiler-stubs.d.ts +2 -0
  54. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  55. package/dist/lib/compiler-stubs.js +2 -0
  56. package/dist/lib/compiler-stubs.js.map +1 -1
  57. package/dist/lib/d1-fingerprint.d.ts +8 -0
  58. package/dist/lib/d1-fingerprint.d.ts.map +1 -0
  59. package/dist/lib/d1-fingerprint.js +113 -0
  60. package/dist/lib/d1-fingerprint.js.map +1 -0
  61. package/dist/lib/file-loader.d.ts +12 -0
  62. package/dist/lib/file-loader.d.ts.map +1 -1
  63. package/dist/lib/file-loader.js +27 -1
  64. package/dist/lib/file-loader.js.map +1 -1
  65. package/dist/lib/migrations/plan.js +3 -0
  66. package/dist/lib/migrations/plan.js.map +1 -1
  67. package/dist/lib/migrations/postprocessors/index.d.ts +6 -5
  68. package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
  69. package/dist/lib/migrations/postprocessors/index.js +24 -12
  70. package/dist/lib/migrations/postprocessors/index.js.map +1 -1
  71. package/dist/lib/migrations/postprocessors/search.d.ts +49 -0
  72. package/dist/lib/migrations/postprocessors/search.d.ts.map +1 -0
  73. package/dist/lib/migrations/postprocessors/search.js +160 -0
  74. package/dist/lib/migrations/postprocessors/search.js.map +1 -0
  75. package/dist/lib/migrations/prior-state.d.ts +7 -0
  76. package/dist/lib/migrations/prior-state.d.ts.map +1 -1
  77. package/dist/lib/migrations/prior-state.js +3 -0
  78. package/dist/lib/migrations/prior-state.js.map +1 -1
  79. package/dist/lib/migrations/types.d.ts +1 -1
  80. package/dist/lib/migrations/types.d.ts.map +1 -1
  81. package/dist/lib/migrations/types.js +1 -0
  82. package/dist/lib/migrations/types.js.map +1 -1
  83. package/dist/lib/preview-lifecycle.d.ts +139 -0
  84. package/dist/lib/preview-lifecycle.d.ts.map +1 -0
  85. package/dist/lib/preview-lifecycle.js +429 -0
  86. package/dist/lib/preview-lifecycle.js.map +1 -0
  87. package/dist/lib/preview.d.ts +146 -0
  88. package/dist/lib/preview.d.ts.map +1 -0
  89. package/dist/lib/preview.js +417 -0
  90. package/dist/lib/preview.js.map +1 -0
  91. package/dist/lib/wrangler-resources.d.ts.map +1 -1
  92. package/dist/lib/wrangler-resources.js +4 -2
  93. package/dist/lib/wrangler-resources.js.map +1 -1
  94. package/dist/skill/SKILL.md +9 -3
  95. package/dist/skill/agents/quickback-specialist/AGENT.md +9 -11
  96. package/dist/skill/docs/api/batch-operations.md +19 -0
  97. package/dist/skill/docs/api/caching.md +17 -0
  98. package/dist/skill/docs/api/crud.md +9 -0
  99. package/dist/skill/docs/api/errors.md +31 -2
  100. package/dist/skill/docs/api/query-params.md +6 -0
  101. package/dist/skill/docs/changelog/index.md +1 -0
  102. package/dist/skill/docs/configure/agents.md +1 -1
  103. package/dist/skill/docs/configure/bindings.md +177 -1
  104. package/dist/skill/docs/configure/cloudflare-access.md +43 -0
  105. package/dist/skill/docs/configure/domains.md +2 -2
  106. package/dist/skill/docs/configure/index.md +2 -2
  107. package/dist/skill/docs/configure/providers.md +5 -0
  108. package/dist/skill/docs/configure/single-tenant.md +1 -0
  109. package/dist/skill/docs/configure/tenant-databases.md +627 -14
  110. package/dist/skill/docs/define/access.md +26 -0
  111. package/dist/skill/docs/define/actions/defining.md +7 -1
  112. package/dist/skill/docs/define/actions/index.md +5 -0
  113. package/dist/skill/docs/define/actions/scoped-db.md +127 -1
  114. package/dist/skill/docs/define/authoring-basics.md +92 -0
  115. package/dist/skill/docs/define/changesets.md +8 -0
  116. package/dist/skill/docs/define/encryption.md +48 -2
  117. package/dist/skill/docs/define/feature.md +17 -2
  118. package/dist/skill/docs/define/guards.md +11 -3
  119. package/dist/skill/docs/define/index.md +1 -1
  120. package/dist/skill/docs/define/invariants.md +321 -0
  121. package/dist/skill/docs/define/issue-tracker-example.md +225 -0
  122. package/dist/skill/docs/define/masking.md +3 -3
  123. package/dist/skill/docs/define/rate-limit.md +63 -22
  124. package/dist/skill/docs/define/read.md +332 -5
  125. package/dist/skill/docs/define/relationships.md +10 -0
  126. package/dist/skill/docs/define/schema.md +137 -10
  127. package/dist/skill/docs/define/scopes.md +1 -0
  128. package/dist/skill/docs/define/transitions.md +9 -0
  129. package/dist/skill/docs/define/triggers.md +127 -1
  130. package/dist/skill/docs/platform/api-contract/index.md +35 -4
  131. package/dist/skill/docs/platform/auth/api-keys.md +26 -3
  132. package/dist/skill/docs/platform/auth/index.md +5 -2
  133. package/dist/skill/docs/platform/auth/plugins/index.md +1 -1
  134. package/dist/skill/docs/platform/auth/plugins/organization-defaults.md +37 -0
  135. package/dist/skill/docs/platform/auth/using-auth.md +2 -0
  136. package/dist/skill/docs/platform/database/d1.md +73 -1
  137. package/dist/skill/docs/platform/database/durable-effects.md +224 -0
  138. package/dist/skill/docs/platform/database/read-replication.md +9 -0
  139. package/dist/skill/docs/platform/database/recovery.md +292 -0
  140. package/dist/skill/docs/platform/database/using-d1.md +152 -2
  141. package/dist/skill/docs/platform/index.md +1 -0
  142. package/dist/skill/docs/platform/operations/budgets.md +224 -0
  143. package/dist/skill/docs/platform/queues/handlers.md +1 -0
  144. package/dist/skill/docs/platform/queues/index.md +18 -0
  145. package/dist/skill/docs/platform/realtime/table-changes.md +1 -0
  146. package/dist/skill/docs/platform/storage/using-r2.md +13 -0
  147. package/dist/skill/docs/platform/vector/embeddings.md +28 -4
  148. package/dist/skill/docs/platform/vector/using-embeddings.md +17 -0
  149. package/dist/skill/docs/platform/workflows/index.md +385 -0
  150. package/dist/skill/docs/start/deploy-browser.md +51 -0
  151. package/dist/skill/docs/start/deploy.md +97 -1
  152. package/dist/skill/docs/tooling/cli.md +117 -0
  153. package/dist/skill/docs/tooling/cloud-compiler/index.md +15 -0
  154. package/dist/skill/docs/ui/account/customization.md +6 -2
  155. package/dist/skill/docs/ui/account/environment-variables.md +7 -1
  156. package/dist/skill/docs/ui/account/features/admin.md +2 -2
  157. package/dist/skill/docs/ui/account/features/api-keys.md +1 -1
  158. package/dist/skill/docs/ui/account/features/index.md +10 -8
  159. package/dist/skill/docs/ui/account/features/organizations.md +19 -9
  160. package/dist/skill/docs/ui/account/features/passkeys.md +6 -2
  161. package/dist/skill/docs/ui/account/features/sessions.md +2 -2
  162. package/dist/skill/docs/ui/account/index.md +61 -30
  163. package/dist/skill/docs/ui/account/with-quickback.md +1 -1
  164. package/dist/skill/docs/ui/admin/connecting.md +1 -1
  165. package/dist/skill/docs/ui/admin/index.md +1 -1
  166. package/dist/skill/docs/ui/admin/record-layouts.md +3 -3
  167. package/package.json +1 -1
  168. package/src/skill/SKILL.md +9 -3
  169. package/src/skill/agents/quickback-specialist/AGENT.md +9 -11
  170. package/src/skill/docs/api/batch-operations.md +19 -0
  171. package/src/skill/docs/api/caching.md +17 -0
  172. package/src/skill/docs/api/crud.md +9 -0
  173. package/src/skill/docs/api/errors.md +31 -2
  174. package/src/skill/docs/api/query-params.md +6 -0
  175. package/src/skill/docs/changelog/index.md +1 -0
  176. package/src/skill/docs/configure/agents.md +1 -1
  177. package/src/skill/docs/configure/bindings.md +177 -1
  178. package/src/skill/docs/configure/cloudflare-access.md +43 -0
  179. package/src/skill/docs/configure/domains.md +2 -2
  180. package/src/skill/docs/configure/index.md +2 -2
  181. package/src/skill/docs/configure/providers.md +5 -0
  182. package/src/skill/docs/configure/single-tenant.md +1 -0
  183. package/src/skill/docs/configure/tenant-databases.md +627 -14
  184. package/src/skill/docs/define/access.md +26 -0
  185. package/src/skill/docs/define/actions/defining.md +7 -1
  186. package/src/skill/docs/define/actions/index.md +5 -0
  187. package/src/skill/docs/define/actions/scoped-db.md +127 -1
  188. package/src/skill/docs/define/authoring-basics.md +92 -0
  189. package/src/skill/docs/define/changesets.md +8 -0
  190. package/src/skill/docs/define/encryption.md +48 -2
  191. package/src/skill/docs/define/feature.md +17 -2
  192. package/src/skill/docs/define/guards.md +11 -3
  193. package/src/skill/docs/define/index.md +1 -1
  194. package/src/skill/docs/define/invariants.md +321 -0
  195. package/src/skill/docs/define/issue-tracker-example.md +225 -0
  196. package/src/skill/docs/define/masking.md +3 -3
  197. package/src/skill/docs/define/rate-limit.md +63 -22
  198. package/src/skill/docs/define/read.md +332 -5
  199. package/src/skill/docs/define/relationships.md +10 -0
  200. package/src/skill/docs/define/schema.md +137 -10
  201. package/src/skill/docs/define/scopes.md +1 -0
  202. package/src/skill/docs/define/transitions.md +9 -0
  203. package/src/skill/docs/define/triggers.md +127 -1
  204. package/src/skill/docs/platform/api-contract/index.md +35 -4
  205. package/src/skill/docs/platform/auth/api-keys.md +26 -3
  206. package/src/skill/docs/platform/auth/index.md +5 -2
  207. package/src/skill/docs/platform/auth/plugins/index.md +1 -1
  208. package/src/skill/docs/platform/auth/plugins/organization-defaults.md +37 -0
  209. package/src/skill/docs/platform/auth/using-auth.md +2 -0
  210. package/src/skill/docs/platform/database/d1.md +73 -1
  211. package/src/skill/docs/platform/database/durable-effects.md +224 -0
  212. package/src/skill/docs/platform/database/read-replication.md +9 -0
  213. package/src/skill/docs/platform/database/recovery.md +292 -0
  214. package/src/skill/docs/platform/database/using-d1.md +152 -2
  215. package/src/skill/docs/platform/index.md +1 -0
  216. package/src/skill/docs/platform/operations/budgets.md +224 -0
  217. package/src/skill/docs/platform/queues/handlers.md +1 -0
  218. package/src/skill/docs/platform/queues/index.md +18 -0
  219. package/src/skill/docs/platform/realtime/table-changes.md +1 -0
  220. package/src/skill/docs/platform/storage/using-r2.md +13 -0
  221. package/src/skill/docs/platform/vector/embeddings.md +28 -4
  222. package/src/skill/docs/platform/vector/using-embeddings.md +17 -0
  223. package/src/skill/docs/platform/workflows/index.md +385 -0
  224. package/src/skill/docs/start/deploy-browser.md +51 -0
  225. package/src/skill/docs/start/deploy.md +97 -1
  226. package/src/skill/docs/tooling/cli.md +117 -0
  227. package/src/skill/docs/tooling/cloud-compiler/index.md +15 -0
  228. package/src/skill/docs/ui/account/customization.md +6 -2
  229. package/src/skill/docs/ui/account/environment-variables.md +7 -1
  230. package/src/skill/docs/ui/account/features/admin.md +2 -2
  231. package/src/skill/docs/ui/account/features/api-keys.md +1 -1
  232. package/src/skill/docs/ui/account/features/index.md +10 -8
  233. package/src/skill/docs/ui/account/features/organizations.md +19 -9
  234. package/src/skill/docs/ui/account/features/passkeys.md +6 -2
  235. package/src/skill/docs/ui/account/features/sessions.md +2 -2
  236. package/src/skill/docs/ui/account/index.md +61 -30
  237. package/src/skill/docs/ui/account/with-quickback.md +1 -1
  238. package/src/skill/docs/ui/admin/connecting.md +1 -1
  239. package/src/skill/docs/ui/admin/index.md +1 -1
  240. package/src/skill/docs/ui/admin/record-layouts.md +3 -3
@@ -0,0 +1,321 @@
1
+ # Invariants - Rules the Database Enforces
2
+
3
+ `invariants:` declares record rules that the **database** enforces. Each rule
4
+ compiles to compiler-owned SQLite triggers, so it holds on every write path:
5
+ CRUD routes, batch routes, actions writing through the scoped `db` or
6
+ `unsafeDb`, changesets, cascades, queue and cron handlers, and raw SQL on the
7
+ binding. A bug in an action can't get past it.
8
+
9
+ [Guards](/define/guards), [access](/define/access) and
10
+ [transitions](/define/transitions) decide what the **API** accepts. Invariants
11
+ decide what the **data** may become. Use both: guards shape the routes, and
12
+ invariants are the backstop.
13
+
14
+ ```typescript
15
+ // features/books/bills.ts
16
+ import { feature, q } from '@quickback/compiler';
17
+
18
+ export default feature('bills', {
19
+ columns: {
20
+ id: q.id(),
21
+ status: q.enum(['draft', 'posted', 'void']).default('draft').required(),
22
+ totalCents: q.int().required(),
23
+ memo: q.text({ maxLength: 200 }).optional(),
24
+ organizationId: q.scope('organization'),
25
+ ...q.audit(),
26
+ ...q.softDelete(),
27
+ },
28
+ guards: { createable: ['totalCents', 'memo'], updatable: ['totalCents', 'memo'], protected: { status: ['post', 'void'] } },
29
+ read: { access: { roles: ['owner'] } },
30
+ create: { access: { roles: ['owner'] } },
31
+ update: { access: { roles: ['owner'] } },
32
+ transitions: {
33
+ post: { field: 'status', from: 'draft', to: 'posted', access: { roles: ['owner'] } },
34
+ void: { field: 'status', from: ['draft', 'posted'], to: 'void', access: { roles: ['owner'] } },
35
+ },
36
+ invariants: {
37
+ permanent: { message: 'bills are never deleted; void the bill instead' },
38
+ frozen: [
39
+ { when: { status: 'posted' }, allow: ['status'] },
40
+ { when: { status: 'void' } },
41
+ ],
42
+ },
43
+ });
44
+ ```
45
+
46
+ A refused write returns **422 `TRIGGER_REJECTED`** on every path. The rule's
47
+ code is in `details.code`, and its message is the error text:
48
+
49
+ ```json
50
+ { "code": "TRIGGER_REJECTED", "error": "this bills row is frozen in its current state", "details": { "code": "RECORD_FROZEN" } }
51
+ ```
52
+
53
+ Every rule takes an optional `code` (uppercase letters, digits and
54
+ underscores) and `message`, so you can keep the codes your clients already
55
+ read. In an action, the refusal reaches the caller the same way. Inside a
56
+ `db.batch` it rolls the whole batch back, and the response carries
57
+ `details.committed: false`.
58
+
59
+ ## The rules
60
+
61
+ | Rule | Holds | Default code |
62
+ |---|---|---|
63
+ | [`permanent`](#permanent) | No hard delete and no soft delete. Never a cascade target. | `RECORD_PERMANENT` |
64
+ | [`appendOnly`](#appendonly) | No update after insert, except one-time `setOnce` stamps. | `RECORD_APPEND_ONLY` |
65
+ | [`frozen`](#frozen) | Fields stop changing once the stored row matches `when` (or always). | `RECORD_FROZEN` |
66
+ | [`lockedBy`](#lockedby) | Child rows can't be inserted, changed or deleted while the parent matches `when`. | `PARENT_LOCKED` |
67
+ | [`requires`](#requires-on-references) (on `.references()`) | The referenced row must match a condition. | `REFERENCE_REQUIREMENT` |
68
+ | [`restrict`](#restrict) | No delete, listed-column change or state entry while matching rows point here. | `RESTRICTED_BY_REFERENCE` |
69
+ | [`derived`](#derived) | A column equals an aggregate of child rows. Only the database writes it. | `DERIVED_COLUMN` |
70
+ | [`balanced`](#balanced) | Σ debit = Σ credit per row across its lines, when each write commits. | `UNBALANCED` |
71
+
72
+ ### Conditions
73
+
74
+ `when`, `where` and `target` take a **row condition**: an object of column
75
+ tests that must all hold.
76
+
77
+ | Test | Means |
78
+ |---|---|
79
+ | `status: 'posted'` | equal (null-safe: `null` matches a null column) |
80
+ | `status: ['posted', 'void']` | one of |
81
+ | `status: { not: 'draft' }` / `{ not: ['a', 'b'] }` | anything else, **including null** |
82
+ | `voidedAt: { null: true }` / `{ notNull: true }` | null / not null |
83
+ | `proposalId: { ref: { status: 'sent' } }` | the FK's row matches (one hop per `ref`; nest them for more) |
84
+ | `any: [cond, cond]` | one of the conditions |
85
+ | `exists: { by: 'table.column', on?, where? }` | a row of `table` points at this row (`notExists` for none) |
86
+
87
+ Soft-deleted rows are not skipped implicitly. Write `deletedAt: null` where a
88
+ deleted row should stop counting. Conditions compile to SQL that is never
89
+ NULL, so `{ not: 'draft' }` on a null status is true, and `['a']` on a null
90
+ column is false.
91
+
92
+ ## `permanent`
93
+
94
+ ```ts
95
+ invariants: { permanent: true },
96
+ ```
97
+
98
+ Refuses a hard `DELETE` and the soft-delete transition (`deletedAt` becoming
99
+ set), whoever runs it. A permanent table:
100
+
101
+ - can't declare `delete:`, because that would generate a route the database
102
+ refuses. That's a compile error.
103
+ - is **never a soft-delete cascade target**. Deleting a parent leaves its
104
+ permanent children in place. To refuse the parent's delete instead, add a
105
+ [`restrict`](#restrict) rule to the parent.
106
+
107
+ This is stronger than leaving out `delete:`, which only removes the route.
108
+ The rows also survive cascades, actions and raw SQL.
109
+
110
+ ## `appendOnly`
111
+
112
+ ```ts
113
+ invariants: { appendOnly: true }, // journal lines
114
+ invariants: { appendOnly: { setOnce: ['unappliedAt'] } }, // one-time unapply
115
+ ```
116
+
117
+ After insert, no column changes. Each `setOnce` column may go from null to a
118
+ value **once**, together with the audit columns (`modifiedAt`, `modifiedBy`),
119
+ and never back. That fits a transition with a `stamp`:
120
+
121
+ ```ts
122
+ transitions: {
123
+ unapply: { field: null, guard: { unappliedAt: { null: true } }, stamp: { at: 'unappliedAt' }, access: { roles: ['owner'] } },
124
+ },
125
+ ```
126
+
127
+ Deleting is a separate rule: pair `appendOnly` with `permanent` for a ledger.
128
+ An append-only table can't have a general `update:` route. Declare none, or
129
+ limit `guards.updatable` to the `setOnce` columns, or the compile fails.
130
+
131
+ ## `frozen`
132
+
133
+ ```ts
134
+ invariants: {
135
+ frozen: [
136
+ { when: { status: 'posted' }, allow: ['status'] }, // a posted bill can only change status
137
+ { when: { status: 'void' } }, // a void bill never changes
138
+ { fields: ['kind'] }, // kind never changes, in any state
139
+ ],
140
+ },
141
+ ```
142
+
143
+ `when` is tested on the **stored** row, so the update that moves a row into a
144
+ frozen state still goes through. Give `fields` to freeze only those columns,
145
+ or `allow` to freeze every column except those. With neither, every column is
146
+ frozen except the audit columns (`modifiedAt`, `modifiedBy`) and the
147
+ soft-delete pair, because deleting is the job of `permanent` or `restrict`.
148
+ Without `when`, `frozen: { fields }` makes columns immutable at the database,
149
+ including for actions. [`guards.immutable`](/define/guards) only binds the
150
+ routes.
151
+
152
+ ## `lockedBy`
153
+
154
+ ```ts
155
+ // features/bills/bill-allocations.ts
156
+ invariants: {
157
+ lockedBy: { parent: 'billId', when: { status: ['posted', 'void'] } },
158
+ },
159
+ ```
160
+
161
+ While the row `parent` points at matches `when`, a child row can't be
162
+ inserted, updated, moved to or from that parent, soft-deleted or deleted.
163
+ `allow` lists columns that may still change. For a grandparent, nest a `ref`:
164
+
165
+ ```ts
166
+ lockedBy: { parent: 'clientInvoiceLineId', when: { invoiceId: { ref: { status: ['issued', 'void'] } } } },
167
+ ```
168
+
169
+ `parent` must be a `.references()` column.
170
+
171
+ ## `requires` (on `.references()`)
172
+
173
+ The referenced row must meet a condition while the reference is set:
174
+
175
+ ```ts
176
+ itemLineId: q.text().required().references(() => itemLines.id, {
177
+ match: { source: 'projectId', target: 'projectId' },
178
+ requires: { kind: 'reimbursable' },
179
+ }),
180
+ ```
181
+
182
+ It's checked from both sides. A source insert or update that points at a row
183
+ failing the condition is refused. So is a **target** update that would leave a
184
+ live reference pointing at a row that no longer meets it. Soft-deleted source
185
+ rows don't hold the target.
186
+
187
+ The list form gives each rule its own `when` (on this row), `code` and
188
+ `message`:
189
+
190
+ ```ts
191
+ appliesToLineId: q.text().optional().references('self', {
192
+ requires: [
193
+ { when: { kind: 'vendor_tax' }, target: { kind: ['merchandise', 'reimbursable'] }, code: 'CHECK_APPLIES_TO' },
194
+ { when: { kind: { not: 'vendor_tax' } }, target: { kind: 'merchandise' }, code: 'CHECK_APPLIES_TO' },
195
+ ],
196
+ }),
197
+ ```
198
+
199
+ Values must be inline literals: the source path reads them from the file.
200
+
201
+ ## `restrict`
202
+
203
+ Refuse a change to **this** row while rows of another table point at it:
204
+
205
+ ```ts
206
+ // features/items/items.ts
207
+ invariants: {
208
+ restrict: [
209
+ { by: 'billAllocations.itemLineId', blocks: 'delete' },
210
+ { by: 'approvals.itemId', where: { revokedAt: null }, blocks: ['delete', { enter: { archivedAt: { notNull: true } } }] },
211
+ { by: 'proposalLines.itemLineId', where: { deletedAt: null, proposalId: { ref: { status: 'sent' } } }, blocks: { update: ['cost', 'price'] }, code: 'LINE_LOCKED' },
212
+ ],
213
+ },
214
+ ```
215
+
216
+ `by` names the referencing column as `'table.column'`. It points at this
217
+ row's id, or at the column you name in `on`. `blocks` takes one value or a
218
+ list:
219
+
220
+ | Block | Refuses |
221
+ |---|---|
222
+ | `'delete'` | a hard delete or the soft-delete transition |
223
+ | `'update'` | any column change |
224
+ | `{ update: ['cost', 'price'] }` | a change to those columns |
225
+ | `{ enter: { status: 'withdrawn' } }` | an update after which the row matches the condition, from a state where it didn't |
226
+
227
+ `{ enter }` is how a transition gets an existence check at the database:
228
+ "a proposal can't be withdrawn while it has live approvals" is
229
+ `{ by: 'approvals.proposalId', where: { revokedAt: null }, blocks: { enter: { status: 'withdrawn' } } }`.
230
+
231
+ ## `derived`
232
+
233
+ A column the database keeps equal to an aggregate of child rows:
234
+
235
+ ```ts
236
+ // features/shipments/shipments.ts
237
+ invariants: {
238
+ derived: {
239
+ projectId: { single: 'packageId.projectId', from: 'shipmentPackages.shipmentId', where: { deletedAt: null } },
240
+ },
241
+ },
242
+ ```
243
+
244
+ `from` names the children as `'table.column'`, where the column is the child's
245
+ FK to this row. Give one aggregate:
246
+
247
+ | Aggregate | Value |
248
+ |---|---|
249
+ | `single: 'col'` | the one distinct non-null value of the children, else null |
250
+ | `count: true` | the number of children |
251
+ | `sum: 'col'` | their sum, 0 for none |
252
+ | `min: 'col'` / `max: 'col'` | their minimum / maximum |
253
+
254
+ The value path may take one hop through a child's FK (`'packageId.projectId'`).
255
+ The column is recomputed in the same statement as any child insert, update,
256
+ soft delete or delete, and when the hop table's value changes. Writing the
257
+ column directly is refused unless the value equals the aggregate. Rows
258
+ written before the rule was added correct themselves on their next child
259
+ write. Other rules (`frozen`, `appendOnly`, `lockedBy`) don't count the
260
+ recompute as a change.
261
+
262
+ ## `balanced`
263
+
264
+ A journal entry's lines must balance, checked once the whole write has run,
265
+ not row by row:
266
+
267
+ ```ts
268
+ // features/journal/journal-entries.ts
269
+ invariants: {
270
+ permanent: true,
271
+ appendOnly: true,
272
+ balanced: { lines: 'journalLines.entryId', debit: 'debitCents', credit: 'creditCents' },
273
+ },
274
+ ```
275
+
276
+ `debit` and `credit` must be **integer** columns (`q.int` or `q.bigint`). Store
277
+ money as integer cents. Decimal columns are refused at compile time.
278
+
279
+ SQLite has no deferred constraints, so balance can't be a row trigger. The
280
+ compiler emits two pieces:
281
+
282
+ 1. Triggers on the line table keep `_quickback_unbalanced` equal to the set of
283
+ keys whose lines don't balance right now.
284
+ 2. The runtime ends every **write unit** with a commit check. Inserting into
285
+ `_quickback_invariant_check` fails with `QB_TRIGGER_REJECTED:UNBALANCED`
286
+ while any key is listed, and that rolls the unit back.
287
+
288
+ A write unit is one transaction:
289
+
290
+ | Where | Unit |
291
+ |---|---|
292
+ | Shared D1 | one statement, or one `db.batch([...])` (a D1 batch is a transaction) |
293
+ | [Tenant object](/configure/tenant-databases#record-invariants) | `db.transaction(cb)`, an atomic batch, a changeset, or one statement outside them |
294
+
295
+ So write an entry's lines **together**: one `db.batch`, one multi-row
296
+ `insert(...).values([...])`, a batch route, or (in a tenant object) a
297
+ changeset or `db.transaction`. Awaiting one line at a time fails at the first
298
+ line, because that statement commits alone. On shared D1 a changeset is not
299
+ one transaction (it writes op by op), so it can't create an entry with
300
+ balanced lines in one request. Use an action with `db.batch` there.
301
+
302
+ The check is appended by the features database handle (`createDb`) and by the
303
+ queue, cron and email runners. SQL run through `env.DB` directly, or with
304
+ `exec`, bypasses the check but not the triggers. An unbalanced key it leaves
305
+ behind makes the next checked write fail until the key is fixed.
306
+
307
+ ## In tenant databases
308
+
309
+ Under [`tenancy.isolation: 'durable-object'`](/configure/tenant-databases#record-invariants),
310
+ a tenant table's invariants install **inside each tenant object**, exactly like
311
+ its `sql:` triggers. Every table a rule names must live in the same object,
312
+ or the build fails with `TENANCY_TRIGGER_CROSS_OBJECT`.
313
+
314
+ ## Not covered
315
+
316
+ - **Postgres.** Invariants and `requires` lower to SQLite only (D1 and tenant
317
+ objects). A Postgres project declaring them fails the build.
318
+ - **Rules that compare against another table's date or setting** (a closed
319
+ books period, a cut-over date). Keep those as `sql:` [triggers](/define/triggers).
320
+ - **Existing rows.** A new rule checks future writes. Check existing rows
321
+ before rollout.
@@ -0,0 +1,225 @@
1
+ # Connected issue tracker example
2
+
3
+ This project uses organization roles for workspace membership and a scoped
4
+ update action for reporter-or-assignee editing. Members edit issues they reported **or** are
5
+ assigned to; admins manage all workspace data through the API. The CMS is restricted to
6
+ platform sysadmins (`cms.access: "sysadmin"`); `"admin"` is not a CMS access mode. The reporter is the verified
7
+ `createdBy`, never a client-selected identity. Workflow advancement and assignment
8
+ are admin operations in this example. Every FK shares its organization with its
9
+ target. Better Auth users stay in `AUTH_DB`; no feature-table SQL FK points there.
10
+
11
+ Copy the files below together. The configuration is applied to the following multi-file feature by the doc
12
+ compile gate, including its actual imports. The update action uses a strict input contract
13
+ and persists the change; it is not a no-op authorization stub.
14
+
15
+ ```typescript
16
+ // quickback.config.ts
17
+ import { defineConfig } from "@quickback/compiler";
18
+ export default defineConfig({
19
+ name: "issue-tracker", template: "hono", account: true,
20
+ cms: { access: "sysadmin", sysadmin: true },
21
+ features: { organizations: true },
22
+ auth: { roleHierarchy: ["member", "admin", "owner"] },
23
+ providers: {
24
+ runtime: { name: "cloudflare", config: {} },
25
+ database: { name: "cloudflare-d1", config: { splitDatabases: true, authBinding: "AUTH_DB", featuresBinding: "DB" } },
26
+ auth: { name: "better-auth", config: { emailAndPassword: { enabled: true } } },
27
+ },
28
+ });
29
+
30
+ ```
31
+
32
+ ```typescript
33
+ // features/projects/projects.ts
34
+ import { feature, q } from "@quickback/compiler";
35
+
36
+ export default feature("projects", {
37
+ columns: {
38
+ id: q.id(), organizationId: q.scope("organization"),
39
+ ...q.audit(), ...q.softDelete(),
40
+ name: q.text().required(),
41
+ },
42
+ guards: { createable: ["name"], updatable: ["name"] },
43
+ read: { access: { roles: ["member+"] } },
44
+ create: { access: { roles: ["admin+"] } }, update: { access: { roles: ["admin+"] } }, delete: { access: { roles: ["admin+"] } },
45
+ displayColumn: "name",
46
+ });
47
+
48
+ // features/projects/issues.ts
49
+ import { feature, q } from "@quickback/compiler";
50
+ import projects from "./projects";
51
+ export default feature("issues", {
52
+ columns: {
53
+ id: q.id(), organizationId: q.scope("organization"),
54
+ ...q.audit(), ...q.softDelete(),
55
+ projectId: q.text().required().references(() => projects.id, { match: { source: "organizationId", target: "organizationId" } }),
56
+ title: q.text().required(), description: q.text().optional(),
57
+ status: q.enum(["backlog", "ready", "in_progress", "done"]).default("backlog").required(),
58
+ },
59
+ guards: { createable: ["projectId", "title", "description"], updatable: ["title", "description"],
60
+ protected: { status: ["ready", "start", "finish"] } },
61
+ read: { access: { roles: ["member+"] }, defaultView: "summary", views: {
62
+ summary: { fields: ["id", "projectId", "title", "status", "createdBy"], access: { roles: ["member+"] } },
63
+ admin: { fields: ["id", "projectId", "title", "description", "status", "createdBy", "createdAt", "modifiedAt"], access: { roles: ["admin+"] } },
64
+ } },
65
+ create: { access: { roles: ["member+"] } },
66
+ update: { access: { roles: ["member+"] }, action: "edit" },
67
+ delete: { access: { roles: ["admin+"] } },
68
+ transitions: {
69
+ ready: { field: "status", from: "backlog", to: "ready", access: { roles: ["admin+"] } },
70
+ start: { field: "status", from: "ready", to: "in_progress", access: { roles: ["admin+"] } },
71
+ finish: { field: "status", from: "in_progress", to: "done", access: { roles: ["admin+"] } },
72
+ },
73
+ realtime: { enabled: true, emitFromActions: true, access: { roles: ["member+"] } },
74
+ displayColumn: "title",
75
+ });
76
+
77
+ // features/projects/comments.ts
78
+ import { feature, q } from "@quickback/compiler";
79
+ import issues from "./issues";
80
+ export default feature("comments", {
81
+ columns: {
82
+ id: q.id(), organizationId: q.scope("organization"),
83
+ ...q.audit(), ...q.softDelete(),
84
+ issueId: q.text().required().references(() => issues.id, { match: { source: "organizationId", target: "organizationId" } }),
85
+ body: q.text().required(),
86
+ },
87
+ guards: { createable: ["issueId", "body"], updatable: ["body"] },
88
+ read: { access: { roles: ["member+"] } },
89
+ create: { access: { roles: ["member+"] } },
90
+ update: { access: { or: [{ roles: ["admin+"] }, { roles: ["member+"], record: { createdBy: { equals: "$ctx.userId" } } }] } },
91
+ delete: { access: { roles: ["admin+"] } },
92
+ realtime: { enabled: true, emitFromActions: true, access: { roles: ["member+"] } }, displayColumn: "body",
93
+ });
94
+
95
+ // features/projects/labels.ts
96
+ import { feature, q } from "@quickback/compiler";
97
+
98
+ export default feature("labels", {
99
+ columns: {
100
+ id: q.id(), organizationId: q.scope("organization"),
101
+ ...q.audit(), ...q.softDelete(),
102
+ name: q.text().required(),
103
+ },
104
+ guards: { createable: ["name"], updatable: ["name"] },
105
+ read: { access: { roles: ["member+"] } },
106
+ create: { access: { roles: ["admin+"] } }, update: { access: { roles: ["admin+"] } }, delete: { access: { roles: ["admin+"] } },
107
+ displayColumn: "name",
108
+ });
109
+
110
+ // features/projects/issueLabels.ts
111
+ import { feature, q } from "@quickback/compiler";
112
+ import issues from "./issues";
113
+ import labels from "./labels";
114
+ export default feature("issueLabels", {
115
+ columns: {
116
+ id: q.id(), organizationId: q.scope("organization"),
117
+ ...q.audit(), ...q.softDelete(),
118
+ issueId: q.text().required().references(() => issues.id, { match: { source: "organizationId", target: "organizationId" } }),
119
+ labelId: q.text().required().references(() => labels.id, { match: { source: "organizationId", target: "organizationId" } }),
120
+ },
121
+ guards: { createable: ["issueId", "labelId"], updatable: [] },
122
+ unique: [{ columns: ["issueId", "labelId"], whereNotDeleted: true }],
123
+ read: { access: { roles: ["member+"] } },
124
+ create: { access: { roles: ["admin+"] } }, update: { access: { roles: ["admin+"] } }, delete: { access: { roles: ["admin+"] } },
125
+ displayColumn: "id",
126
+ });
127
+
128
+ // features/projects/issueAssignees.ts
129
+ import { feature, q } from "@quickback/compiler";
130
+ import issues from "./issues";
131
+ export default feature("issueAssignees", {
132
+ columns: {
133
+ id: q.id(), organizationId: q.scope("organization"),
134
+ ...q.audit(), ...q.softDelete(),
135
+ issueId: q.text().required().references(() => issues.id, { match: { source: "organizationId", target: "organizationId" } }),
136
+ userId: q.text().required(),
137
+ },
138
+ guards: { createable: [], updatable: [], immutable: ["issueId", "userId"] },
139
+ unique: [{ columns: ["issueId", "userId"], whereNotDeleted: true }],
140
+ read: { access: { roles: ["member+"] } },
141
+ create: { access: { roles: ["NONE"] } }, update: { access: { roles: ["NONE"] } },
142
+ delete: { access: { roles: ["admin+"] } }, displayColumn: "id",
143
+ });
144
+
145
+ // features/projects/actions/issues/assign.ts
146
+ import { z } from "zod";
147
+ import { ActionError } from "@quickback/compiler";
148
+ import { defineAction } from "../../.quickback/define-action.issues";
149
+ import { row, issueAssignees } from "../../.quickback/define-action";
150
+ import { getOrgMemberRole } from "../../../../lib/org-access";
151
+
152
+ export default defineAction({
153
+ description: "Assign an organization member to this issue",
154
+ input: z.object({ userId: z.string().min(1) }),
155
+ output: row(issueAssignees),
156
+ access: { roles: ["admin+"] },
157
+ async execute({ db, record, input, ctx, c }) {
158
+ const role = await getOrgMemberRole(c.get("authDb"), input.userId, ctx.activeOrgId!);
159
+ if (!role) throw new ActionError("Assignee is not an organization member", "NOT_A_MEMBER", 400);
160
+ // record was loaded through the issue firewall; scope/audit values are stamped.
161
+ const [assignment] = await db.insert(issueAssignees)
162
+ .values({ issueId: record.id, userId: input.userId }).returning();
163
+ return assignment;
164
+ },
165
+ ui: { label: "Assign member", onSuccess: "refresh" },
166
+ });
167
+ // features/projects/actions/issues/edit.ts
168
+ import { z } from "zod";
169
+ import { and, eq } from "drizzle-orm";
170
+ import { ActionError } from "@quickback/compiler";
171
+ import { defineAction } from "../../.quickback/define-action.issues";
172
+ import { row, issues, issueAssignees } from "../../.quickback/define-action";
173
+
174
+ export default defineAction({
175
+ description: "Edit an issue as its reporter, assignee, or workspace admin",
176
+ input: z.object({ title: z.string().min(1).optional(), description: z.string().optional() }).strict(),
177
+ output: row(issues),
178
+ access: { roles: ["member+"] },
179
+ async execute({ db, record, input, ctx, whereRecord }) {
180
+ const admin = ctx.roles?.some((role) => role === "admin" || role === "owner");
181
+ if (!admin && record.createdBy !== ctx.userId) {
182
+ const [assignment] = await db.select({ id: issueAssignees.id }).from(issueAssignees)
183
+ .where(and(eq(issueAssignees.issueId, record.id), eq(issueAssignees.userId, ctx.userId!))).limit(1);
184
+ if (!assignment) throw new ActionError("Only the reporter or an assignee may edit", "ISSUE_EDIT_DENIED", 403);
185
+ }
186
+ const [updated] = await db.update(issues).set(input).where(whereRecord!(issues)).returning();
187
+ return updated;
188
+ },
189
+ });
190
+
191
+ ```
192
+
193
+ A relationship role currently compares the **same named column** on the
194
+ consuming row and relationship table. `resource.column: "issueId"` does not map
195
+ `issues.id` to `issueAssignees.issueId`; using that role directly here denies
196
+ assignee edits. The scoped update action above expresses that join explicitly.
197
+ Keep the edit action’s outer `access` at `member+`: a reporter-only record gate
198
+ would reject assignees before execute can check the junction, and admins need
199
+ an explicit bypass inside execute. Keep these three cases intact. Use
200
+ `output: row(issues)` for a returned row instead of inventing non-null Zod fields
201
+ for nullable audit values.
202
+
203
+ Its strict input excludes status, scope, reporter, and audit fields, because a
204
+ mapped action owns its input contract rather than the generated CRUD guards.
205
+ It also suppresses batch update routes that would bypass its policy.
206
+ `emitFromActions: true` makes scoped action writes publish realtime changes
207
+ after commit; `enabled` alone covers generated CRUD broadcasts.
208
+
209
+ The generated helper exports every table in this feature. The assignment action
210
+ is bound to sibling `issues` by its directory, loads the issue through its
211
+ firewall, validates the submitted user's org membership, and writes the junction
212
+ through the scoped DB. Direct junction creates/updates are denied so callers
213
+ cannot skip that validation. A duplicate live assignment returns a uniqueness
214
+ error; deleting a junction row permits reassignment through the partial index.
215
+
216
+ The graph comments → issues → projects is acyclic. `displayColumn` controls
217
+ labels; column `.references()` and `match` control integrity. The resource
218
+ `references` map is unnecessary here. See [schema](/define/schema#references),
219
+ [relationship roles](/define/relationships), and [scoped DB](/define/actions/scoped-db).
220
+
221
+ Validate runtime behavior independently: reporter and assignee edits succeed;
222
+ unrelated members and other organizations cannot edit; out-of-org assignees and
223
+ cross-org parent pointers fail without writes; valid workflow steps persist;
224
+ direct status changes and invalid transitions fail. CMS/view/realtime settings
225
+ compiling does not establish a browser or subscription test.
@@ -151,9 +151,9 @@ export default feature('candidates', {
151
151
  phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
152
152
  },
153
153
  read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },
154
- create: { /* ... */ },
155
- update: { /* ... */ },
156
- delete: { /* ... */ },
154
+ create: { access: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
155
+ update: { access: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
156
+ delete: { access: { roles: ['owner', 'hiring-manager'] } },
157
157
  });
158
158
  ```
159
159