@jskit-ai/agent-docs 0.1.283 → 0.1.285

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 (152) hide show
  1. package/guide/agent/app-extras/assistant.md +14 -2
  2. package/guide/agent/app-extras/realtime.md +38 -1
  3. package/guide/agent/app-setup/authentication.md +76 -14
  4. package/guide/agent/app-setup/console.md +8 -0
  5. package/guide/agent/app-setup/database-layer.md +23 -103
  6. package/guide/agent/app-setup/existing-application-migration.md +134 -72
  7. package/guide/agent/app-setup/multi-homing.md +94 -32
  8. package/guide/agent/app-setup/quickstart.md +1 -1
  9. package/guide/agent/app-setup/run-an-accounts-hub.md +1 -1
  10. package/guide/agent/app-setup/upgrading-jskit.md +17 -3
  11. package/guide/agent/app-setup/users.md +8 -5
  12. package/guide/agent/framework/application-operations.md +1 -1
  13. package/guide/agent/framework/crud-operations.md +63 -45
  14. package/guide/agent/framework/data-access.md +1207 -0
  15. package/guide/agent/framework/sanity-checks.md +26 -27
  16. package/guide/agent/framework/typed-features.md +117 -248
  17. package/guide/agent/index.md +2 -0
  18. package/package.json +6 -3
  19. package/patterns/feature-package/PATTERN.md +25 -17
  20. package/patterns/feature-package/example/booking-engine/package.json +1 -1
  21. package/patterns/feature-package/example/variations/InvoiceRollupFeature.js +6 -7
  22. package/patterns/feature-package/example/variations/invoiceResource.js +15 -0
  23. package/patterns/feature-package/example/variations/invoiceRollupActions.js +4 -4
  24. package/patterns/feature-package/example/variations/ownedTableRepository.js +27 -0
  25. package/patterns/feature-package/example/variations/types.js +1 -1
  26. package/patterns/minimal-foundation/example/AGENTS.md +4 -0
  27. package/patterns/minimal-foundation/example/package.json +4 -4
  28. package/patterns/minimal-foundation/example/server.js +4 -1
  29. package/patterns/shell-foundation/example/AGENTS.md +4 -0
  30. package/patterns/shell-foundation/example/package.json +5 -5
  31. package/patterns/shell-foundation/example/packages/main/package.json +1 -1
  32. package/patterns/shell-foundation/example/server.js +4 -1
  33. package/reference/autogen/KERNEL_MAP.md +3 -1
  34. package/reference/autogen/PATTERN_INDEX.md +70 -59
  35. package/reference/autogen/README.md +1 -1
  36. package/reference/autogen/packages/agent-docs.md +7 -3
  37. package/reference/autogen/packages/agent-runtime.md +48 -11
  38. package/reference/autogen/packages/architecture-inspector.md +6 -2
  39. package/reference/autogen/packages/assistant-core.md +4 -4
  40. package/reference/autogen/packages/assistant-runtime.md +33 -13
  41. package/reference/autogen/packages/auth-provider-local-core.md +3 -1
  42. package/reference/autogen/packages/auth-provider-local-db-core.md +69 -14
  43. package/reference/autogen/packages/auth-provider-oidc-core.md +5 -1
  44. package/reference/autogen/packages/auth-provider-supabase-core.md +1 -1
  45. package/reference/autogen/packages/connectors-core.md +22 -2
  46. package/reference/autogen/packages/console-core.md +9 -5
  47. package/reference/autogen/packages/crud-core.md +45 -175
  48. package/reference/autogen/packages/database-runtime-mysql.md +0 -26
  49. package/reference/autogen/packages/database-runtime.md +11 -33
  50. package/reference/autogen/packages/http-runtime.md +3 -3
  51. package/reference/autogen/packages/http-web.md +12 -0
  52. package/reference/autogen/packages/kernel.md +27 -2
  53. package/reference/autogen/packages/oidc-issuer-core.md +4 -0
  54. package/reference/autogen/packages/payments-core.md +28 -6
  55. package/reference/autogen/packages/realtime.md +15 -6
  56. package/reference/autogen/packages/resource-core.md +32 -5
  57. package/reference/autogen/packages/resource-crud-core.md +30 -34
  58. package/reference/autogen/packages/resource-runtime.md +220 -0
  59. package/reference/autogen/packages/rewarded-core.md +16 -10
  60. package/reference/autogen/packages/shell-web.md +1 -0
  61. package/reference/autogen/packages/users-core.md +33 -14
  62. package/reference/autogen/packages/workspaces-core.md +17 -10
  63. package/reference/autogen/tooling/config-eslint.md +74 -0
  64. package/reference/autogen/tooling/jskit-catalog.md +50 -1
  65. package/reference/autogen/tooling/jskit-release.md +5 -0
  66. package/skills/jskit/SKILL.md +4 -1
  67. package/skills/jskit/references/app-operations.md +1 -1
  68. package/skills/jskit/references/crud-operations.md +62 -44
  69. package/skills/jskit/references/data-access.md +1202 -0
  70. package/skills/jskit/references/database-layer.md +411 -0
  71. package/skills/jskit/references/existing-application-migration.md +134 -72
  72. package/skills/jskit/references/heuristics/INDEX.md +6 -4
  73. package/skills/jskit/references/heuristics/crud-authoring.md +26 -15
  74. package/skills/jskit/references/heuristics/data-access.md +19 -0
  75. package/skills/jskit/references/heuristics/filters.md +6 -6
  76. package/skills/jskit/references/heuristics/row-policies.md +40 -16
  77. package/skills/jskit/references/heuristics/server-search.md +30 -42
  78. package/skills/jskit/references/heuristics/table-resource-fields.md +78 -0
  79. package/skills/jskit/references/heuristics/typed-features.md +3 -3
  80. package/skills/jskit/references/multi-homing.md +94 -32
  81. package/skills/jskit/references/pattern-index.md +70 -59
  82. package/skills/jskit/references/patterns/app/minimal-foundation/example/AGENTS.md +4 -0
  83. package/skills/jskit/references/patterns/app/minimal-foundation/example/package.json +4 -4
  84. package/skills/jskit/references/patterns/app/minimal-foundation/example/server.js +4 -1
  85. package/skills/jskit/references/patterns/app/shell-foundation/example/AGENTS.md +4 -0
  86. package/skills/jskit/references/patterns/app/shell-foundation/example/package.json +5 -5
  87. package/skills/jskit/references/patterns/app/shell-foundation/example/packages/main/package.json +1 -1
  88. package/skills/jskit/references/patterns/app/shell-foundation/example/server.js +4 -1
  89. package/skills/jskit/references/patterns/assistant/assistant-surface/PATTERN.md +5 -2
  90. package/skills/jskit/references/patterns/auth/accounts-hub/example/package.json +3 -2
  91. package/skills/jskit/references/patterns/auth/auth-surface/PATTERN.md +15 -0
  92. package/skills/jskit/references/patterns/auth/oidc-sign-in/example/package.json +2 -2
  93. package/skills/jskit/references/patterns/auth/supabase-auth/example/package.json +1 -1
  94. package/skills/jskit/references/patterns/connectors/calendar-cli/example/package.json +4 -4
  95. package/skills/jskit/references/patterns/crud/crud-contract/PATTERN.md +133 -0
  96. package/skills/jskit/references/patterns/crud/crud-contract/example/bookResource.js +74 -0
  97. package/skills/jskit/references/patterns/crud/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  98. package/skills/jskit/references/patterns/crud/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  99. package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  100. package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  101. package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  102. package/skills/jskit/references/patterns/crud/crud-screen-set/PATTERN.md +26 -8
  103. package/skills/jskit/references/patterns/crud/crud-screen-set/example/books/BookEditPage.vue +2 -2
  104. package/skills/jskit/references/patterns/crud/crud-screen-set/example/books/BookListPage.vue +2 -2
  105. package/skills/jskit/references/patterns/crud/crud-screen-set/example/books/BookNewPage.vue +2 -2
  106. package/skills/jskit/references/patterns/crud/crud-screen-set/example/books/BookViewPage.vue +3 -3
  107. package/skills/jskit/references/patterns/database/mysql-application/PATTERN.md +9 -4
  108. package/skills/jskit/references/patterns/database/mysql-application/example/package.json +2 -1
  109. package/skills/jskit/references/patterns/database/mysql-application/example/scripts/prepare-database.js +8 -0
  110. package/skills/jskit/references/patterns/database/postgres-application/PATTERN.md +8 -4
  111. package/skills/jskit/references/patterns/database/postgres-application/example/package.json +2 -1
  112. package/skills/jskit/references/patterns/database/postgres-application/example/scripts/prepare-database.js +8 -0
  113. package/skills/jskit/references/patterns/database/table-resource/PATTERN.md +120 -0
  114. package/skills/jskit/references/patterns/database/table-resource/example/orderResource.js +25 -0
  115. package/skills/jskit/references/patterns/realtime/realtime-application/PATTERN.md +7 -0
  116. package/skills/jskit/references/patterns/realtime/realtime-application/example/package.json +2 -2
  117. package/skills/jskit/references/patterns/rewards/google-rewarded/PATTERN.md +1 -1
  118. package/skills/jskit/references/patterns/server/feature-package/PATTERN.md +25 -17
  119. package/skills/jskit/references/patterns/server/feature-package/example/booking-engine/package.json +1 -1
  120. package/skills/jskit/references/patterns/server/feature-package/example/variations/InvoiceRollupFeature.js +6 -7
  121. package/skills/jskit/references/patterns/server/feature-package/example/variations/invoiceResource.js +15 -0
  122. package/skills/jskit/references/patterns/server/feature-package/example/variations/invoiceRollupActions.js +4 -4
  123. package/skills/jskit/references/patterns/server/feature-package/example/variations/ownedTableRepository.js +27 -0
  124. package/skills/jskit/references/patterns/server/feature-package/example/variations/types.js +1 -1
  125. package/skills/jskit/references/patterns/users/user-administration-server/PATTERN.md +63 -10
  126. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/package.json +5 -4
  127. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
  128. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/src/shared/index.js +1 -1
  129. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
  130. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/package.json +11 -5
  131. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
  132. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
  133. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
  134. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
  135. package/skills/jskit/references/patterns/workspaces/workspace-server/PATTERN.md +9 -9
  136. package/skills/jskit/references/patterns/workspaces/workspace-surfaces/PATTERN.md +16 -0
  137. package/skills/jskit/references/patterns/workspaces/workspace-surfaces/example/src/pages/home/workspaces/index.vue +2 -0
  138. package/skills/jskit/references/sanity-checks.md +27 -28
  139. package/skills/jskit/references/typed-features.md +117 -248
  140. package/patterns/feature-package/example/variations/customKnexRepository.js +0 -40
  141. package/reference/autogen/packages/json-rest-api-core.md +0 -66
  142. package/skills/jskit/references/heuristics/crud-repository-mapping.md +0 -140
  143. package/skills/jskit/references/patterns/crud/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  144. package/skills/jskit/references/patterns/crud/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  145. package/skills/jskit/references/patterns/crud/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  146. package/skills/jskit/references/patterns/crud/resource-contract/PATTERN.md +0 -155
  147. package/skills/jskit/references/patterns/crud/resource-contract/example/bookResource.js +0 -87
  148. package/skills/jskit/references/patterns/server/feature-package/example/variations/customKnexRepository.js +0 -40
  149. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
  150. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
  151. /package/skills/jskit/references/patterns/crud/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  152. /package/skills/jskit/references/patterns/crud/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -0,0 +1,1202 @@
1
+ <!-- Generated from `packages/agent-docs/site/guide/framework/data-access.md`. -->
2
+
3
+ # Data access
4
+
5
+ Read this before writing code that reads or writes a database table, with or
6
+ without screens. [Typed features](typed-features.md) covers how
7
+ the code around it is shaped; this page covers how it reaches the data.
8
+
9
+ ## The resource is the only door
10
+
11
+ Every table has exactly one **table resource**. Only the feature that owns the
12
+ table reads or writes it, through the resource's handle. Ownership, the row
13
+ policy, validation, ownership stamping, audits and change events run only on
14
+ that path. Knex reaches the table past all of them, and putting it in a file
15
+ named "repository" protects nothing.
16
+
17
+ Bad: a repository raised a version counter on a record id it was handed, with
18
+ no workspace predicate, so one workspace could change another workspace's
19
+ booking.
20
+
21
+ Good: the owner's repository calls `bookings.patch(id, { version }, options)`,
22
+ which changes the row only when the caller's scope owns it.
23
+
24
+ ## The handle's calls
25
+
26
+ One table, one table resource, one owner feature. The owner reaches its table
27
+ through its handle's calls, and every call takes the call's `options` last:
28
+
29
+ | Call | Does |
30
+ | --- | --- |
31
+ | `query({ filters, sort, page, include }, options)` | one page: `{ records, page }` |
32
+ | `queryAll({ filters, sort, include }, options)` | every matching row, for jobs, id lists and one parent's rows |
33
+ | `get(id, params, options)` | one record |
34
+ | `aggregate({ measures, groupBy, filters, sort }, options)` | totals, grouped by fields or date buckets |
35
+ | `create(data, options)`, `findOrCreate({ id, ...data }, options)` | one record; a keyed one, created once |
36
+ | `patch(id, changes, options)`, `delete(id, options)` | one record |
37
+ | `createMany(rows, options)` | many records, or an upsert with `onConflict` |
38
+ | `patchMany(rows, options)` | many records, each with its own changes |
39
+ | `patchWhere(filters, changes, options)`, `deleteWhere(filters, options)` | every matching row |
40
+ | `lock(id, txOptions)`, `lockMany(ids, txOptions)`, `lockWhere(filters, txOptions)` | rows locked until the transaction ends |
41
+ | `lockOrCreate({ id, ...initial }, options, work)` | a keyed record locked, created first when missing, for `work` |
42
+ | `claim({ filters, sort, take }, txOptions)` | the next rows no other worker holds |
43
+ | `withTransaction(options, work)` | one transaction; `work` gets its `txOptions` |
44
+ | `changeHorizon(options)` | PostgreSQL's snapshot horizon, where a read of what changed since starts ([What changed since](#what-changed-since)) |
45
+ | `scopedQuery(params, options)` | a read-only builder for a report ([Layer 5](#layer-5-reports-the-resource-cannot-express)) |
46
+
47
+ ```js
48
+ // How many invoices of each status the workspace issued each month, and their total.
49
+ function totalsByMonth(options) {
50
+ return invoices.aggregate({
51
+ groupBy: ["status", { field: "issuedAt", bucket: "month", as: "month" }],
52
+ measures: { invoices: { count: "*" }, amount: { sum: "amount" } },
53
+ sort: ["month"]
54
+ }, options);
55
+ }
56
+ ```
57
+
58
+ ## Words
59
+
60
+ | Word | Meaning |
61
+ | --- | --- |
62
+ | table resource | The one description of one table: fields and their columns, ownership, relationships, search and lock version. `defineTableResource()`, shared with the client. |
63
+ | owner feature | The feature whose `owns` lists the table resource. It is the only feature that reads or writes the table. |
64
+ | handle | What the owner gets for each resource it owns. Every method applies the scope of the call's `options.context`. |
65
+ | repository | The owner's module that holds every query, built on its handles. Its methods have domain names. A plain CRUD feature's repository is its table's handle itself. |
66
+ | service | Orchestration. It calls repositories (its own, or another feature's through that feature's capability: an owner API, or a CRUD feature's `repository`) and other features' services. It never builds a query (no Knex, no `scopedQuery`) and never reaches another feature's table any other way. |
67
+ | owner API | The capability through which a table's owner lets other features read and write its records, such as `users.profiles`. |
68
+ | CRUD contract | The optional HTTP and screen surface on a table resource: `defineCrudContract()`. |
69
+ | CRUD feature | The feature `defineCrudFeature()` builds from a CRUD contract: its repository, service, actions, routes and screens. |
70
+ | ownership | Who owns a row, required in every table resource: `public`, `workspace`, `user`, `workspace_user`, `workspace_or_shared` (a workspace's own rows, or rows shared with every workspace when the owner is empty), or `system` (rows of no workspace or user, which only the owning feature's system context reaches). |
71
+ | row policy | A server-only rule narrowing which rows a context sees, applied to every statement, joins, includes and locks included. |
72
+ | scoped query | The read-only Knex builder `scopedQuery()` returns, with ownership and the row policy already applied. |
73
+ | system scope | Why a feature works across every workspace and user, declared with `systemScope`. |
74
+ | system context | The context of that work, from `systemContext(reason)`; `forWorkspace`, `forUser` and `forWorkspaceUser` narrow it. |
75
+ | `txOptions` | What `withTransaction(options, work)` hands `work`: only the call's context and its transaction, `{ context, trx }`, passed to every call inside. |
76
+ | record | What a handle answers: `{ id, ...fields }`, relationships as ids, included records nested. |
77
+
78
+ ## Layer 1: the table resource
79
+
80
+ Every table your app owns has one table resource. The feature that owns the
81
+ table lists it in `owns`, and only that feature's setup receives its handle.
82
+ Every read and write goes through the handle. On every statement the handle
83
+ adds the ownership predicate and the row policy, validates what you write and
84
+ stamps the workspace or user on new rows. A table whose schema stores
85
+ `createdAt` and `updatedAt` as `dateTime` fields gets them stamped by every
86
+ write: both on a create (`createMany` too), `updatedAt` on every change
87
+ (`patch`, `patchMany`, `patchWhere`, an upsert merge, which keeps the stored
88
+ `createdAt`). The stamps replace what any other caller sends, and a CRUD
89
+ contract offers them as output only; only a system context (an import, a
90
+ migration, a seed) sets its own. Pass the call's `options` (its context and
91
+ transaction) to every handle call; a call without a context throws instead of
92
+ guessing.
93
+
94
+ ```js
95
+ // shared/receivalResource.js: the table's facts, shared with the client
96
+ const receivalResource = defineTableResource({
97
+ name: "receivals",
98
+ tableName: "receivals",
99
+ ownership: "workspace",
100
+ schema: {
101
+ status: { type: "string", required: true, search: true },
102
+ arrivedAt: { type: "dateTime", nullable: true }
103
+ }
104
+ });
105
+
106
+ // server/ReceivalsFeature.js: the owner
107
+ const ReceivalsFeature = defineFeature({
108
+ id: "receivals",
109
+ owns: [receivalResource, { resource: receivalNoteResource, rowPolicy: authorOrManager }],
110
+ provides: { receivals: "receivals" },
111
+ setup: ({ resources }) => ({ receivals: createReceivalsService(createReceivalsRepository(resources)) })
112
+ });
113
+
114
+ /**
115
+ * server/receivalsRepository.js: every query, by domain name.
116
+ * @param {{ receivals: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} handles
117
+ */
118
+ function createReceivalsRepository({ receivals }) {
119
+ /**
120
+ * One page of the open receivals.
121
+ * @param {{ size: number, after?: string }} page
122
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
123
+ */
124
+ function listOpen(page, options) {
125
+ return receivals.query({ filters: { status: "open" }, page }, options);
126
+ }
127
+
128
+ /**
129
+ * @param {string} id
130
+ * @param {string} arrivedAt
131
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
132
+ */
133
+ function markArrived(id, arrivedAt, options) {
134
+ return receivals.patch(id, { status: "arrived", arrivedAt }, options);
135
+ }
136
+
137
+ return Object.freeze({
138
+ withTransaction: receivals.withTransaction,
139
+ listOpen,
140
+ markArrived
141
+ });
142
+ }
143
+ ```
144
+
145
+ A field's type says what its column holds, not the column's SQL type. A
146
+ whole-number column that is not an id (a counter, a byte count, a position),
147
+ BIGINT included, is `type: "integer"`. Every handle read answers it as a
148
+ number on MySQL, MariaDB and PostgreSQL alike, although both drivers read
149
+ BIGINT as text. A column that holds another row's id is `type: "id"` and
150
+ reads as text, as ids do. Past 2^53 − 1 a JavaScript number cannot hold a
151
+ whole number exactly, so json-rest-api answers those digits as text rather
152
+ than a rounded number. A value that can grow that large gets a decimal field
153
+ (`precision` and `scale`), whose digits stay text.
154
+
155
+ A package whose features own tables or declare `systemScope` lists
156
+ `runtime.resources` in its descriptor's `capabilities.requires`, or boot
157
+ refuses it; the feature never requires it itself, since it receives its
158
+ handles.
159
+
160
+ Reads take `(params, options)` and writes `(data, options)`: `get(id, {},
161
+ options)`. A call's settings ride in its options, added on the call they are
162
+ for and spread from the options the method received: `{ ...options, missing:
163
+ "skip" }`, `{ ...options, returning: "id" }`. A method passes on only the
164
+ options it received, never a setting it added for one of its own calls, and
165
+ another table gets only `{ context, trx }`: `passedOn(options)` from
166
+ `@jskit-ai/resource-runtime/server`. An owner API, called with another
167
+ feature's options, hands each of its calls `passedOn(options)` plus the
168
+ settings that call needs, never the caller's options whole. `withTransaction`
169
+ hands its work only the context and the transaction, and so does a handle to
170
+ its hooks and its own nested calls.
171
+
172
+ `txOptions` is `{ context, trx }` and nothing else: every other key of the
173
+ method's `options`, the application's own included (a flag that skips an
174
+ email, a `limit`, a per-request cache), is gone inside the work. Read what the
175
+ work needs from `options` itself, never from `txOptions`. A method that wraps
176
+ a write on its own table in `withTransaction` passes that write `{ ...options,
177
+ ...txOptions }`, or the caller's `returning`, `missing` or `format` never
178
+ reaches it and the method answers something its caller did not ask for.
179
+ Another table's call still gets `txOptions`:
180
+
181
+ ```js
182
+ const addLines = (rows, options) => lines.withTransaction(options, async (txOptions) => {
183
+ const added = await lines.createMany(rows, { ...options, ...txOptions });
184
+ await orders.patch(rows[0].orderId, { linesChangedAt: new Date() }, txOptions);
185
+ return added;
186
+ });
187
+ ```
188
+
189
+ A filter key is one of the resource's `search: true` fields or a
190
+ `searchSchema` entry. `id` is every handle's own filter (a resource never
191
+ declares an `id` search entry) and takes one id or a list; an empty list
192
+ matches no row. Another list of values needs an entry with `filterOperator:
193
+ "in"`. A `null` value matches the rows where the field is null: `filters: {
194
+ archivedAt: null }`.
195
+
196
+ A filter on another table's field (`searchSchema: { supplierName: { type:
197
+ "string", actualField: "suppliers.name" } }`) needs that field declared
198
+ `indexed: true` on its own table resource, with a database index on its column,
199
+ even when the join is on the other table's id; `own()` refuses it at startup
200
+ otherwise, naming both.
201
+
202
+ A table keyed by a `uuid` or `string` primary key takes its ids as text; an
203
+ `owns` entry's `normalizeId` is only for an id written some other way.
204
+
205
+ A handle finds every row by one `id`. A table whose rows another key
206
+ identifies (a workspace and a day, or one row per user keyed by the user's id)
207
+ still gets an integer `id` primary key, and keeps that key as a unique index
208
+ on exactly the columns its upsert names, the ownership column among them. The
209
+ code reads by the key with a filter and writes by it with an upsert,
210
+ `onConflict: { keys: ["workspaceId", "day"] }`
211
+ ([Layer 3](#layer-3-many-rows-at-once)). The [port
212
+ guide](existing-application-migration.md#moving-hand-written-sql-behind-resources)
213
+ has the migration for a table that exists already.
214
+
215
+ A route that reads or writes without an action (a provider's callback, a
216
+ download it streams) takes its options from `await request.callOptions()`: the
217
+ context the same request's action would get, its user, workspace and route
218
+ scope resolved by the same contributors. No action's permission runs, so the
219
+ route's own `auth` and `permission` are its gate. Never build a request's
220
+ context by hand.
221
+
222
+ A `workspace_or_shared` table's shared rows (no workspace) belong to every
223
+ workspace, so no request or job writes one: a create stamps the caller's
224
+ workspace, a patch or delete of a shared row is refused, and many-row writes
225
+ and locks leave shared rows out. When a request may change one (a permission
226
+ says so, or the row is the person's own), the owner reads the row in the
227
+ request's own context, which proves the caller reaches it, decides in code
228
+ whether this caller may change it, and only then writes it in a system
229
+ context, `systemContext(reason)` itself (one `forUser` or its kin derived is
230
+ not a system context), naming the empty owner: `create({ ...fields,
231
+ workspaceId: null }, …)`, or `patchWhere({ id: [id], workspaceId: null },
232
+ changes, …)` and `deleteWhere` with the same filters, which never reach a
233
+ workspace's row. `{ ...txOptions, context: systemContext(reason) }` joins
234
+ the request's transaction.
235
+
236
+ A read answers every field unless `fields` names the ones it needs (a
237
+ belongs-to field by its own key, such as `customerId`, or its relationship);
238
+ the locks (`lock`, `lockMany`, `lockWhere` and `claim`) take it in their
239
+ options, `{ ...txOptions, fields }`.
240
+ Each belongs-to field a read answers costs a check that its related record is
241
+ visible, so a hot path names its fields. A collection relation with
242
+ `hydrateOnList: false` or `hydrateOnView: false` loads its rows on that kind of
243
+ read only when the read includes it.
244
+
245
+ `foreignKeys` declares the table's real database foreign keys, in json-rest-api's
246
+ shape: `foreignKeys: [{ columns: ["customerId"], referencedTableName: "customers" }]`,
247
+ `columns` naming schema fields and `referencedColumns` the other table's columns
248
+ when they are not its `id`. json-rest-api relies on a declared key to skip work,
249
+ so a declaration the database lacks changes results: before any test runs,
250
+ `jskit test --databases` compares every declaration with the test database's keys,
251
+ fails on one the database lacks and lists the keys of your tables that nothing
252
+ declares.
253
+
254
+ A `hidden: true` field (an ownership id, a bearer token, a storage key) never
255
+ reaches a request: no CRUD route or JSON:API document (`format: "jsonapi"`)
256
+ carries it, even when `fields` names it. The owner's own code reads one by
257
+ naming it in a handle read's `fields`, `get(id, { fields: ["publicToken"] },
258
+ options)` or `{ ...txOptions, fields }` for a lock, which costs one more
259
+ statement per 1,000 records, scoped as the read is; a read without `fields`
260
+ never answers it. It may be an id, string, integer, number or boolean, and
261
+ naming any other kind refuses the read. The repository a CRUD feature gives
262
+ other features, and its own actions, refuses any call whose `fields` names a
263
+ hidden field, whatever the method (`decorateRepository`'s included), and any
264
+ `scopedQuery()` or answered builder other than a `joinSource()`'s (either can
265
+ select every column), and every method it holds answers without the hidden
266
+ fields of the tables its owner owns, unless the call runs in a system context.
267
+ It tells hidden fields by name, so a feature whose tables hide a field in one
268
+ and show it in another fails to start: hide it in both, or rename one. So the
269
+ owner checks a token in a method `decorateRepository` adds, with the handle it
270
+ receives, and answers only the outcome. Work in another feature that needs the
271
+ value itself (a key it signs with, an address it sends to) calls a method the
272
+ owner's `decorateService` adds: that receives the repository before the guard,
273
+ so it reads the field, named in `fields`, in the caller's own context, with no
274
+ system context. A test of such a path asserts the value the other feature uses,
275
+ not only that the call succeeded: a hidden field left out of a record reads as
276
+ `undefined`, not as an error. Never unhide a field to read it, and
277
+ never read it with `scopedQuery`.
278
+
279
+ `create` and `patch` answer the written record by default, read back through
280
+ the row policy. Server code that does not use it passes `returning: "id"` or
281
+ `"none"`, which skips that read; `delete` answers the id. One rule covers a
282
+ record that is missing or outside the caller's scope: `get`, `patch`, `delete`
283
+ and `lock` throw json-rest-api's not-found error (a 404), and with
284
+ `missing: "skip"` they answer `null` instead, without failing the caller's
285
+ transaction. A row keyed by an id the code computes (a fingerprint, a
286
+ conversation id) is read or created once with `findOrCreate({ id,
287
+ ...attributes }, options)`, outside the transaction that then locks it: inside
288
+ one, losing the race to create it fails the whole transaction. Compute such an
289
+ id from the owner too (the workspace or user id in the fingerprint): an id
290
+ another scope's row holds answers a missing record. That answer still says the
291
+ id is taken, so `findOrCreate` and `lockOrCreate` take only ids the server
292
+ computes or generates, never an id a request supplies.
293
+
294
+ A write that the caller's row policy then hides fails, because its read-back
295
+ finds nothing. The `create` or `patch` answers json-rest-api's 404
296
+ (`REST_API_RESOURCE`, "Resource not found") and its transaction rolls back. A
297
+ staff member who sees only the bookings they run cannot book a colleague this
298
+ way. Decide which way the rule goes. Either the policy lets the writer see
299
+ what they may write, or the action refuses the write before it runs, with a
300
+ 403 or 422 that says why.
301
+
302
+ You never write `where workspace_id = ?`, so you cannot forget it. The row
303
+ policy and write hooks go in the `owns` entry on the server, never in the
304
+ shared definition, which ships to the browser. Another feature's contribution
305
+ to a row policy can only narrow it. A row policy adds one predicate correlated
306
+ with the row being read, on indexed columns, and reads the owner's other
307
+ tables through `ownTable(name)`, a read-only subquery, never by table name. It
308
+ never loads everything the subject was ever linked to into an `IN` list, and
309
+ never calls another owner's check once per item: it runs on every read, write
310
+ read-back and lookup, so every request pays what it costs. A policy is told
311
+ who the call runs for as `caller`: `{ kind: "user", userId }` for a signed-in
312
+ request, `{ kind: "anonymous" }` for one by no one, and `{ kind: "system" }` or
313
+ `{ kind: "job" }` (a context `forWorkspace` and its kin derived), each with its
314
+ `reason`, for background work. A job names a user only as `actorId`, the
315
+ person it works for ([below](#background-work)), so never read a missing actor
316
+ as an anonymous request.
317
+
318
+ ```js
319
+ // good: one predicate on the row being read
320
+ function noticeVisibilityPolicy({ query, caller, column, value, ownTable }) {
321
+ if (caller.kind !== "user") {
322
+ return caller.kind !== "anonymous";
323
+ }
324
+ query.where(column("recipientId"), value("recipientId", caller.userId)).whereExists(
325
+ ownTable("sources").select(1).whereColumn("sources.id", column("sourceId")).where("sources.status", "published")
326
+ );
327
+ return true;
328
+ }
329
+
330
+ // bad: every source the recipient was ever notified about, checked one by one
331
+ async function noticeVisibilityPolicy({ query, caller, context, column, value }) {
332
+ const readable = [];
333
+ for (const sourceId of await noticeHistory.listSourceIds(caller.userId)) {
334
+ if (await sources.canRead(sourceId, context)) readable.push(sourceId);
335
+ }
336
+ query.whereIn(column("sourceId"), readable.map((id) => value("sourceId", id)));
337
+ return true;
338
+ }
339
+ ```
340
+
341
+ A rule that depends on the caller's role reads `context.permissions` with
342
+ `hasPermission(context.permissions, "bookings.view-all")` from
343
+ `@jskit-ai/kernel/shared/support`, never with `includes()`. A role may hold
344
+ `*` (an owner does) or `bookings.*`, and `includes()` misses both, so the
345
+ owner would see only the rows a narrower rule leaves.
346
+
347
+ ```js
348
+ import { hasPermission } from "@jskit-ai/kernel/shared/support";
349
+
350
+ // good: staff see the bookings they run; bookings.view-all, the owner's * included, sees them all
351
+ function staffSeeTheirOwnBookings({ query, caller, context, column, value }) {
352
+ if (caller.kind !== "user") {
353
+ return caller.kind !== "anonymous";
354
+ }
355
+ if (hasPermission(context.permissions, "bookings.view-all")) {
356
+ return true;
357
+ }
358
+ query.where(column("staffUserId"), value("staffUserId", caller.userId));
359
+ return true;
360
+ }
361
+
362
+ // bad: an owner holding "*" sees only the bookings they run
363
+ if (context.permissions.includes("bookings.view-all")) return true;
364
+ ```
365
+
366
+ A policy trusts `caller`. In a workspace request it also trusts what the
367
+ server resolved from the route's workspace slug and the caller's membership
368
+ before any handle ran:
369
+ - `context.workspace.id`;
370
+ - `context.membership.roleSid`;
371
+ - `context.permissions`, the role's permissions in that workspace.
372
+
373
+ On a surface whose access policy sets `requireWorkspaceMembership: false`, a
374
+ caller who is not a member has `context.membership` null and
375
+ `context.permissions` empty. Never decide on a value from the request's input.
376
+
377
+ A row policy hides a row everywhere, also as the target of a visible record's
378
+ link: an order whose supplier the reader cannot see reads `supplierId: null`.
379
+ A form that saves the order back sends that null, and the write keeps the
380
+ stored link: a null for a link whose target exists but is hidden from the
381
+ writer counts as unchanged. Send that null, never the hidden id: a write naming
382
+ a target the writer cannot see is refused as a missing target, since accepting
383
+ the right hidden id would tell the writer which record is linked. The link is
384
+ still unreadable to that reader, so a row policy says who may see a row at all;
385
+ narrowing what one screen lists is a filter on that screen's read.
386
+
387
+ ```js
388
+ // bad: a row policy to list only the suppliers a user added; every order whose
389
+ // supplier someone else added now reads supplierId: null for that user
390
+ owns: [{ resource: supplierResource, rowPolicy: addedByActor }]
391
+
392
+ // good: the screen's read filters; orders keep their suppliers
393
+ function listAddedByMe(params, options) {
394
+ return suppliers.query({ ...params, filters: { ...params.filters, addedBy: resolveActorId(options.context) } }, options);
395
+ }
396
+ ```
397
+
398
+ ## Layer 2: the CRUD surface
399
+
400
+ When people list, view, create, edit or delete the rows over HTTP, add a CRUD
401
+ contract to the same table resource. It says which operations exist and which
402
+ fields each one takes and returns; `defineCrudFeature` builds the standard
403
+ repository, service, actions, routes and screens from it. A table without
404
+ screens skips this layer and still uses Layer 1. A table never gets a second
405
+ resource for its CRUD. [CRUD operations](crud-operations.md)
406
+ covers this layer in depth.
407
+
408
+ ```js
409
+ const receivalCrud = defineCrudContract(receivalResource, {
410
+ namespace: "receivals",
411
+ apiAccess: "authenticated",
412
+ operations: ["list", "view", "create", "patch"],
413
+ fields: {
414
+ status: { output: "required", create: "required", patch: "optional" },
415
+ arrivedAt: { output: "optional" }
416
+ }
417
+ });
418
+ ```
419
+
420
+ A contract shows and accepts only the fields it names, and so does an included
421
+ record: it shows its id, its relation's `labelKey`, and only what the including
422
+ contract lists, a record it links to only when the list names that
423
+ relationship, at any depth. Another table's contract never shapes it, since
424
+ that contract may be served to another surface or behind another permission:
425
+
426
+ ```js
427
+ fields: {
428
+ ownerId: { output: { required: false, includeFields: ["displayName"] } },
429
+ // ?include=pet,pet.breed shows the pet's name and its breed's name
430
+ petId: { output: { required: false, includeFields: ["name", { breed: ["name"] }] } }
431
+ }
432
+ ```
433
+ A `decorateService` that also needs the record it wrote (for an audit or a
434
+ history row) reads it from its own answer, `simplifyJsonApiResult(answer)`
435
+ from `@jskit-ai/http-runtime/shared`, never with a second read; a relationship
436
+ whose field key is not its name plus `Id` passes
437
+ `{ lookupFieldMap: { owner: "ownerUserId" } }`.
438
+ A second surface on the same table (a customer's view beside the staff's) is
439
+ a second CRUD contract on the same resource, never a second resource, with
440
+ its own namespace. One plain feature owns the table and provides its handle.
441
+ Each surface is a `defineCrudFeature` that serves its contract through that
442
+ handle with `ownerRepository`. A CRUD feature that owns the table provides
443
+ `{ repository, crud, service }` rather than a handle, so it cannot be another
444
+ one's `ownerRepository`.
445
+
446
+ ```js
447
+ const ServicesFeature = defineFeature({
448
+ id: "app.services",
449
+ owns: [serviceResource],
450
+ provides: { services: "app.services" },
451
+ setup: ({ resources }) => ({ services: resources.services })
452
+ });
453
+ const ServiceAdminFeature = defineCrudFeature({
454
+ crud: serviceAdminCrud,
455
+ surface: "admin",
456
+ ownerRepository: "app.services",
457
+ scope: WORKSPACE_CRUD_SCOPE,
458
+ relativePath: "/services"
459
+ });
460
+ const ServiceCatalogFeature = defineCrudFeature({
461
+ crud: serviceCatalogCrud,
462
+ surface: "app",
463
+ ownerRepository: "app.services",
464
+ scope: WORKSPACE_CRUD_SCOPE,
465
+ relativePath: "/service-catalog"
466
+ });
467
+ ```
468
+
469
+ `WORKSPACE_CRUD_SCOPE` is from
470
+ `@jskit-ai/workspaces-core/server/support/workspaceCrud`; the two contracts'
471
+ namespaces differ because `crud.contracts` refuses two contracts under one
472
+ namespace. A field
473
+ fragment several resources spread into their schemas carries only the field:
474
+ each contract that shows it states its operations in its own `fields`.
475
+
476
+ ## Layer 3: many rows at once
477
+
478
+ When one action creates, changes or deletes many rows, use the handle's
479
+ many-row operations: `createMany`, `patchMany`, `patchWhere` and `deleteWhere`.
480
+ Every filter takes `id`, one id or a list, so `patchWhere({ id: ids },
481
+ changes, options)` and `deleteWhere({ id: ids }, options)` change a known
482
+ list. Each checks every row against the resource first, reads which of the
483
+ rows the caller may touch, then writes each chunk with one statement, in one
484
+ transaction. Audits and change events run once for the batch, so the
485
+ statements are the same for 10 rows as for 200. `patchWhere` and
486
+ `deleteWhere` check the scope and filters on each row once they hold its lock,
487
+ so a row gone meanwhile, or changed so that it no longer matches, is skipped,
488
+ and they take no `missing`. That makes them a compare-and-set on their filters
489
+ on every database: of two writers whose filters both matched a row (open to
490
+ booked), only one writes it, and the other's answer says so
491
+ (`returning: "ids"` lists only the rows it wrote). The one that waited for the
492
+ other's lock leaves the row out; SQLite gets there by failing the second writer
493
+ with `SQLITE_BUSY`, and MariaDB with `innodb_snapshot_isolation` fails the
494
+ waiter with errno 1020 ("Record has changed since last read"), which a write
495
+ that owns its transaction runs again. For one row,
496
+ `patch(id, changes, { ...options, onlyIf: { status: "open" } })` does the same.
497
+ A filter on another table (a search field whose `actualField` reaches a
498
+ related table) is refused on MySQL and MariaDB (`RestApiValidationError`, rule
499
+ `selection_cross_table`), even when it matches no row. A search entry's own
500
+ `applyFilter` that reads another table through a subquery is not detected, and
501
+ is no compare-and-set there either. Filter on the row's own columns instead, for example
502
+ on the link after locking its targets with `lockMany` in the same transaction
503
+ (Layer 4), or move the value onto the row itself for `onlyIf`, or use a
504
+ `claim`. A many-row write answers
505
+ nothing unless `returning` asks: `"ids"`, `"records"`, or `"count"`, which
506
+ reads nothing back.
507
+
508
+ Bad: a batch intake patched each record through the resource: 705 statements
509
+ for 10 records, 11,915 for 200. Written with `patchMany`, it sends the same
510
+ number at both sizes.
511
+
512
+ An upsert (`createMany(rows, { ...options, onConflict })`) on an owned table
513
+ names the ownership field among its conflict keys, or it throws: otherwise it
514
+ could update or hide another workspace's row. `merge` is refused under a row
515
+ policy; use `ignore`, then `patchMany`. A table with no owners and no row
516
+ policy, keyed by a natural id such as an email, may key the upsert on the id
517
+ alone: `onConflict: { keys: ["id"], action: "merge" }`, with an id on every
518
+ row, creates the record or replaces the fields given in one statement. Of two
519
+ upserts at once the later stays, so a counter that must count both is created
520
+ plainly and its duplicate retried instead. Inserting and catching the
521
+ duplicate works only outside a transaction: inside one, the failed insert
522
+ fails the whole transaction, so use an upsert there.
523
+
524
+ A transaction whose insert loses a race for a unique key (another request with
525
+ the same idempotency key committed first) runs once more:
526
+ `retryLostInsertRace(options, () => repository.withTransaction(options, work))`
527
+ from `@jskit-ai/database-runtime/shared`. The database reports the duplicate
528
+ only once the winner has committed, so the second run's lookup by the key
529
+ finds the winner's row. A second duplicate is final, and inside a caller's
530
+ transaction nothing runs again: the caller's transaction has failed, and the
531
+ caller's own retry runs the whole of it. Never write this retry by hand.
532
+
533
+ ```js
534
+ // A repeated payment request answers the first one's record.
535
+ const recordPayment = (input, options) => retryLostInsertRace(options, () => payments.withTransaction(options, async (txOptions) => {
536
+ const [paid] = await payments.queryAll({ filters: { requestKey: input.requestKey } }, txOptions);
537
+ return paid ?? payments.create(input, txOptions);
538
+ }));
539
+ ```
540
+
541
+ ## Layer 4: locks
542
+
543
+ When two requests could change the same rows at once (allocating stock,
544
+ numbering documents, moving items into a batch), lock the rows first, inside
545
+ the transaction: `lock(id, txOptions)`, `lockMany(ids, txOptions)` or
546
+ `lockWhere(filters, txOptions)`. The handle locks only rows the caller may
547
+ see, in id order, so nobody locks another workspace's rows: a missing or
548
+ hidden id throws not-found, as for `get`, or with `missing: "skip"` is left
549
+ out. A check-then-write that must not race (is the drier empty? then load it)
550
+ locks the record first, so another lock or write of it waits until the
551
+ transaction ends. Locks cover existing rows only: number with a unique index
552
+ or a counter row taken with `lock(id)`. Every lock needs a transaction; SQLite
553
+ runs one transaction at a time, so there is no row lock to take. Take locks in
554
+ one order on every path, a parent before its children.
555
+
556
+ On MySQL and MariaDB a locking read locks every row it examines, so two rules
557
+ apply there. Lock ids taken from your own scoped reads, never a list straight
558
+ from a request: every id listed is locked, a hidden one too, before it is left
559
+ out. And `lockWhere` needs an index that starts with the ownership columns (on
560
+ a table with no owners, with a column the filters compare); without one it
561
+ refuses with `RestApiBulkWriteUnsupportedError` naming the index to add in a
562
+ migration.
563
+
564
+ A worker taking the next job uses `claim({ filters, sort, take }, txOptions)`,
565
+ which skips rows another worker holds. A record that serializes work on a key
566
+ and may not exist yet (an account's balance, a connection to a provider), on a
567
+ table with no owners, takes `lockOrCreate({ id, ...initial }, options, work)`:
568
+ it locks the record, creating it from the row first when it is missing, and
569
+ runs `work(record, txOptions)` in the same transaction, so failed work leaves
570
+ no record behind. On its own it runs work once, so work may call a provider:
571
+ two first uses of one id at once can collide on the insert, and the loser runs
572
+ again before its work starts.
573
+
574
+ Every lock takes `FOR UPDATE`, as `patchWhere` does for the rows it selects,
575
+ which also keeps out another transaction's insert of a row that references the
576
+ locked one (a foreign key's check). Where work locks a parent only to change
577
+ its own fields while children may be added meanwhile (a balance others post
578
+ entries to), pass `lockMode: "noKeyUpdate"` to `lock`, `lockMany`,
579
+ `lockWhere`, `claim`, `lockOrCreate` or `patchWhere`: on PostgreSQL it
580
+ is `FOR NO KEY UPDATE`, which still keeps every other lock and write of the row
581
+ out but lets those inserts through; MySQL, MariaDB and SQLite lock as for the
582
+ default `"update"`. Any other value throws a `TypeError` before anything runs.
583
+
584
+ A record that a person edits from a form it read earlier carries a version
585
+ number: the table resource names it with `lockVersionField`, an integer field
586
+ over a non-null integer column with `defaultTo: 0`.
587
+ `patch(id, changes, { ...options, lockVersion })` then locks the row, applies
588
+ `changes` only while it still holds that version, and advances it. A record
589
+ whose version moved on rejects with a 409 coded
590
+ `crud.document.lockVersionConflict` ("This record changed. Reload and try
591
+ again.") and nothing is written; a missing or hidden record follows the
592
+ missing-row rule. The changes leave the version field out. Every update
593
+ advances the version, a plain `patch`, `patchMany`, `patchWhere` or upsert
594
+ merge too, so a form that read version 3 and saves after a background job's
595
+ plain patch of the same record (now version 4) gets the 409 and reloads, even
596
+ though the job changed other fields. `patch(id, changes, { ...options, onlyIf:
597
+ { status: "open" } })` is the same check on stored values, answering `null`
598
+ when they differ.
599
+
600
+ ## Layer 5: reports the resource cannot express
601
+
602
+ Some reads are reports, not records: totals by status and month, the newest
603
+ row per group, distinct active days. Try `aggregate` (counts, sums, buckets by
604
+ day, week, month or year) and an include with `strategy: "window"` (newest per
605
+ group) first. A window include is declared on the table resource's
606
+ relationship, never in the query, and read with `include: ["snapshots"]`:
607
+
608
+ ```js
609
+ relationships: {
610
+ snapshots: { type: "hasMany", target: "snapshots", foreignKey: "booking_id", include: { strategy: "window", limit: 1, orderBy: ["-revision"] } }
611
+ }
612
+ ```
613
+
614
+ When neither can express it, the owner's repository builds it from
615
+ `scopedQuery()`, the table's builder with ownership and the row policy already
616
+ applied:
617
+
618
+ ```js
619
+ // Knex: report - the days each member was active, counted per member
620
+ async function activeDays(memberIds, options) {
621
+ const { query } = await visits.scopedQuery({}, options);
622
+ return query
623
+ .select({ memberId: visits.column("memberId") })
624
+ .countDistinct({ days: visits.raw("DATE(??)", [visits.column("visitedAt")]) })
625
+ .whereIn(visits.column("memberId"), memberIds)
626
+ .groupBy(visits.column("memberId"));
627
+ }
628
+ ```
629
+
630
+ - Each report is one named method in its owner's repository file
631
+ (`*Repository.js`, `repository.js`, or a file under `repositories/`;
632
+ `jskit/knex-reason` refuses `scopedQuery()` anywhere else), under
633
+ `// Knex: <kind> - <reason>`. The kinds:
634
+ - `totals`: sums or counts `aggregate` cannot group;
635
+ - `report`: rows shaped across tables;
636
+ - `newest-per-group`: one row per group, such as each customer's latest
637
+ visit;
638
+ - `subquery`: a scoped set another query joins;
639
+ - `hot-path`: a measured path the handle makes too slow, with its JSKIT
640
+ ticket (`// Knex: hot-path #123 - <reason>`);
641
+ - `runtime-tables`: tables people define while the app runs, which no table
642
+ resource in the code describes.
643
+ - `column()` names columns; `raw` takes one expression as a string literal,
644
+ with its values as bindings.
645
+ - Its rows are the driver's, with no field types applied: a BIGINT column
646
+ (ids and counters alike) and a `COUNT` read as text on MySQL and MariaDB
647
+ (the runtime's `bigNumberStrings`) and on PostgreSQL (int8). The method
648
+ turns the counts and totals it answers into numbers, such as `Number(days)`
649
+ for `activeDays` above.
650
+ - The builder only reads, and only its own table is scoped. A `.join()` or
651
+ `.from()` of a table by name, or a table named inside `raw()`, reads that
652
+ table's rows past its owner and row policy, and so does a subquery callback
653
+ (`whereIn("id", (sub) => sub.from(...))`), whose builder is Knex's own. Nothing
654
+ at run time stops it: `jskit/no-direct-knex` and `jskit/sql-literal` flag it
655
+ (a name as text, an alias object such as `{ p: "projects" }`, a variable
656
+ whose name says table or name, a const holding one, either branch of a `?:`
657
+ or `??`, any `fromRaw()` or `joinRaw()`, and in a subquery callback any
658
+ variable but a scoped subquery or one destructured from a call, such as
659
+ `const { query } = await lots.scopedQuery(...)`), and `expectScoped` catches it
660
+ only when the test seeds another owner's rows the join matches. Join another
661
+ table only as that table's scoped subquery.
662
+ - When a report needs another owner's rows side by side, it joins that
663
+ table's join source in one statement. `joinSource({ alias, filters },
664
+ options)` on the owner's handle, or on the repository a CRUD feature gives
665
+ other features, answers `{ query, column }`: the caller's scoped rows under
666
+ that alias (ownership, the row policy and the filters applied) with the
667
+ columns a read answers, never a hidden one, and `column(field)` naming each
668
+ under the alias. The builder comes wrapped, since a builder is thenable and
669
+ an async function would run it. The report shapes it (select, group), names
670
+ it with `.as()` and joins it, so every owner's scope and row policy stay
671
+ applied. The report lives with the main table's owner, or in a feature that
672
+ requires both. Never hand-build a join source on `scopedQuery()`: its
673
+ builder carries every column, so a CRUD feature's repository refuses
674
+ `scopedQuery()`, and any method answering a builder other than a
675
+ `joinSource()`'s, outside a system context. A report that needs another
676
+ owner's hidden value asks that owner for a method answering what it needs.
677
+
678
+ ```js
679
+ // Knex: report - open tasks and billed totals per project, joined on billing's scoped invoices
680
+ async function projectSummary(options) {
681
+ const source = await billing.joinSource({ alias: "i" }, options);
682
+ const billed = source.query
683
+ .select({ projectId: source.column("projectId") })
684
+ .sum({ billed: source.column("amount") })
685
+ .groupBy(source.column("projectId"))
686
+ .as("b");
687
+ const { query } = await tasks.scopedQuery({ alias: "t" }, options);
688
+ const projectId = tasks.column("projectId", "t");
689
+ return query
690
+ .leftJoin(billed, "b.projectId", projectId)
691
+ .select({ projectId })
692
+ .count({ open: tasks.column("id", "t") })
693
+ .max({ billed: "b.billed" })
694
+ .groupBy(projectId);
695
+ }
696
+ ```
697
+
698
+ - When each owner can answer on its own (keys in, grouped totals out), the
699
+ report is a feature of its own that calls each owner's method and merges the
700
+ answers in memory: one statement per owner, never a call per row.
701
+ - Give each report a scope test and a flat-query test (see [Tests](#tests)).
702
+
703
+ ## Reads shaped for the screen
704
+
705
+ - A list reads one page with `query`; it needs `page.size`, at most the
706
+ resource's `queryMaxLimit`. A scrolling list passes the previous page's
707
+ `page.next` as `page.after`; numbered pages, or restoring a known page, pass
708
+ `page.number` (from 1) and answer `page: { size, number, hasMore, next }`.
709
+ `page.number` reads with OFFSET, which slows as the rows grow, so anything
710
+ that grows pages with `page.after`. Each page is one statement, with no
711
+ count: never walk pages to reach one.
712
+ - A screen list never uses `queryAll`.
713
+ - Related rows come by id list (`filters: { id: ids }`, or an `in` filter on
714
+ another field) or `include`, grouped in memory. Never a query per row, however
715
+ the loop is spelled (`for`, `map` with `Promise.all`, a helper called per
716
+ item).
717
+ - `queryAll` reads every matching row, in cursor pages that skip and repeat
718
+ none. Use it for id lists, one parent's rows and jobs: a read its callers
719
+ treat as complete, which a `query` would silently cut at one page. In a
720
+ request it stops past the request row limit (10,000 rows) with a 400 coded
721
+ `RESOURCE_ROW_LIMIT`.
722
+
723
+ ```js
724
+ // good: one page of invoices, then all of that page's lines in one read
725
+ const { records, page: next } = await invoices.query({ sort: ["-issuedAt"], page }, options);
726
+ const lines = await invoiceLines.queryAll({ filters: { invoiceIds: records.map((invoice) => invoice.id) } }, options);
727
+ const linesByInvoice = Map.groupBy(lines, (line) => line.invoiceId);
728
+
729
+ // bad: one more read, and its row policy, for every invoice
730
+ for (const invoice of records) {
731
+ invoice.lines = await invoiceLines.queryAll({ filters: { invoiceIds: [invoice.id] } }, options);
732
+ }
733
+
734
+ // good: a delivery job reads every active subscriber
735
+ const subscribers = await subscriptions.queryAll({ filters: { newsletterId, status: "active" } }, options);
736
+
737
+ // bad: the first page only, whatever its size
738
+ const { records: firstPage } = await subscriptions.query({ filters: { newsletterId, status: "active" }, page: { size: 20 } }, options);
739
+ ```
740
+
741
+ Bad: a list read 100-row pages in a loop for each of 40 related sets.
742
+
743
+ ## What changed since
744
+
745
+ A page that catches up on a chat, a watch that acts on changes and a sync to
746
+ another system each read what changed since they last read. "Past the highest
747
+ id seen" misses a row whose id was taken before its transaction committed, and
748
+ every change to an older row; "`updatedAt` after the last read" misses a
749
+ transaction that committed after a later one. On PostgreSQL a change stamp and
750
+ the change horizon miss neither:
751
+
752
+ - The table stamps each row with the transaction that last wrote it, an `xid8`
753
+ column a trigger sets on every insert and update, whatever the write sent,
754
+ with an index that starts with the ownership columns:
755
+
756
+ ```js
757
+ // migrations/20261108120000_messages_changed.cjs
758
+ exports.up = async function up(knex) {
759
+ await knex.raw("alter table messages add column changed xid8 not null default pg_current_xact_id()");
760
+ await knex.raw("create function messages_changed() returns trigger language plpgsql as $$ begin new.changed := pg_current_xact_id(); return new; end $$");
761
+ await knex.raw("create trigger messages_changed before insert or update on messages for each row execute function messages_changed()");
762
+ await knex.raw("create index messages_changed_ix on messages (workspace_id, changed)");
763
+ };
764
+ ```
765
+ - The table resource reads it as an `xid8` field, which nothing writes, and
766
+ filters on it:
767
+
768
+ ```js
769
+ schema: { /* ... */ changed: { type: "xid8", nullable: true } },
770
+ searchSchema: {
771
+ changedSince: { type: "xid8", actualField: "changed", filterOperator: ">=" },
772
+ changedBefore: { type: "xid8", actualField: "changed", filterOperator: "<" }
773
+ }
774
+ ```
775
+ - The reader takes `changeHorizon(options)` before it reads and answers it as
776
+ the next cursor. Every transaction below the horizon had finished, so the
777
+ next read, `changedSince: cursor`, finds everything this read could not see.
778
+ A row can come twice, so the reader merges by id. A job that keeps its cursor
779
+ in a row reads the window `{ changedSince: cursor, changedBefore: horizon }`
780
+ and stores the horizon as the new cursor in the same transaction.
781
+
782
+ ```js
783
+ async function catchUp(conversationId, since, options) {
784
+ const cursor = await messages.changeHorizon(options);
785
+ const changed = await messages.queryAll({ filters: { conversationId, changedSince: since } }, options);
786
+ return { messages: changed, cursor };
787
+ }
788
+ ```
789
+
790
+ The horizon is the server's: a long transaction anywhere holds it back, so a
791
+ read repeats more rows, never misses one. MySQL, MariaDB and SQLite stamp no
792
+ row with its transaction: `changeHorizon` throws `UnsupportedDatabaseError`
793
+ there, and an `xid8` field is refused. A reader there takes the rows to handle
794
+ with `claim()`, marking each done in the same transaction.
795
+
796
+ ## Background work
797
+
798
+ Work over the whole population runs as a background job, never inside one
799
+ person's request. Its feature declares why with `systemScope`, and its setup
800
+ receives `systemContext(reason)`, which names its reason at every call:
801
+
802
+ ```js
803
+ const SettlementFeature = defineFeature({
804
+ id: "leagues.settlement",
805
+ owns: [cohortResource, memberResource],
806
+ systemScope: "settle finished weekly leagues for every user",
807
+ setup: ({ resources, systemContext }) => ({ settlement: createSettlement({ resources, systemContext }) })
808
+ });
809
+ ```
810
+
811
+ - Prefer `systemContext(reason).forWorkspace(id)`, `.forUser(id)` or
812
+ `.forWorkspaceUser(workspaceId, userId)`: each workspace or user is then one
813
+ unit of work, scoped as usual, in a transaction of its own. An event it
814
+ publishes carries that workspace's or user's scope, as a request there would,
815
+ so it reaches that audience, never everyone. An action it runs with
816
+ `actions.execute({ actionId, input, context })` keeps the context's kind:
817
+ inside it, a handle call still reads as the system context or job.
818
+ - Work a job does for one person (a request it carries out later) passes
819
+ `{ actorId }` last: `forWorkspace(id, { actorId: requestedBy })`. It says
820
+ whom the work is for and never sets the scope, which stays the workspace or
821
+ user the job was derived for, and it signs no one in: `resolveActorId` and
822
+ every `authenticated` check still see no one. Audit fields read it with
823
+ `resolveAuditActorId(context)`. A row policy is told it as `caller.actorId`,
824
+ and one that holds people to their own rows reads it as it reads a
825
+ request's `caller.userId`, so a job for a person sees what that person may
826
+ see, and a job for no one its whole scope. Work on one person's rows only
827
+ takes their scope (`forUser`, `forWorkspaceUser`) or filters its reads.
828
+ - A job finds its units with one `aggregate` grouped by the ownership field,
829
+ which a system context may group by (and count distinct) even when the table
830
+ hides it, then runs each unit scoped to it. A request's aggregate still
831
+ refuses a hidden field:
832
+
833
+ ```js
834
+ async function settleDue(options) {
835
+ const due = await cohorts.aggregate({ measures: { cohorts: { count: "id" } }, groupBy: ["workspaceId"], filters: { status: "finished" } }, options);
836
+ for (const { workspaceId } of due) {
837
+ await settleWorkspace({ context: systemContext("settle finished weekly leagues for every user").forWorkspace(workspaceId) });
838
+ }
839
+ }
840
+ ```
841
+ - A job that must learn each row's owner across workspaces names the hidden
842
+ ownership field in its read's `fields`, `queryAll({ filters, fields:
843
+ ["workspaceId", "email"] }, { context })`, as a system context may do through
844
+ another feature's CRUD repository too (see [Layer
845
+ 1](#layer-1-the-table-resource)). Never unhide it for the job.
846
+ - A request uses its own context. The exceptions are a console report
847
+ behind a console permission, with bounded output, and the write of a shared
848
+ row it has proved it reaches ([Layer 1](#layer-1-the-table-resource)).
849
+ - `jskit check` lists every system scope and every `systemContext` call with
850
+ its reason, read from the string literal at the call: a reason kept in a
851
+ constant reads as none.
852
+ - A system context comes only from `systemScope`, and a context's scope only
853
+ from the request or from `forWorkspace`, `forUser` and `forWorkspaceUser`:
854
+ lint refuses `createSystemContext` and hand-written `scopeValues`, and a
855
+ context naming two workspaces or two users throws.
856
+ - A table only the feature's own background work reads and writes, whose rows
857
+ belong to no workspace or user (an agent's runs, a server's leases, a queue
858
+ keyed by something other than an owner), takes ownership `system`. Every call
859
+ then needs the owner's `systemContext(reason)`: a request's context, a
860
+ `forWorkspace`, `forUser` or `forWorkspaceUser` job and no context at all
861
+ throw `SystemContextRequiredError` before any statement, since on such a
862
+ table they would reach every workspace's rows. Requests
863
+ reach the rows only through the owner's own methods, which decide what each
864
+ caller may see, and `defineCrudFeature` refuses a `system` table. A table
865
+ whose rows do belong to a workspace or user names that ownership instead.
866
+ - A job that runs on a schedule is a feature whose `boot()` starts a timer and
867
+ whose `shutdown()` stops it; JSKIT ships no scheduler. See
868
+ [typed features, Owned state](typed-features.md#owned-state).
869
+ Every server runs the timer, so a run takes its rows with `claim()`.
870
+
871
+ Bad: a job read every record of every workspace inside a request path, every
872
+ hour.
873
+
874
+ ## Transactions
875
+
876
+ Open a transaction with the repository's `withTransaction(options, work)` and
877
+ pass the `txOptions` it gives `work` to every call inside, spread over the
878
+ method's own `options` for the write the caller's settings are for. Never read the
879
+ transaction out of `options` by hand. A handle refuses every other
880
+ transaction, a raw Knex one or a savepoint, for reads as for writes. Inside an
881
+ open transaction it joins it; otherwise it opens one and runs events and other
882
+ after-effects after commit. Any failed write inside it fails the whole
883
+ transaction.
884
+
885
+ A deadlock victim's transaction (MySQL and MariaDB errno 1213, PostgreSQL
886
+ `40P01`), and one MariaDB fails as "Record has changed since last read" (errno
887
+ 1020, with `innodb_snapshot_isolation` on), runs its whole work again, up to
888
+ three more times, so the work must
889
+ be safe to repeat: an HTTP call or an email goes after commit, or into an
890
+ outbox row written inside it. Work that cannot be repeated passes `{ ...options, retry: false }`, and work that must
891
+ commit before its caller goes on passes `{ ...options, outermost: true }`.
892
+ Code never asks whether it runs in a transaction: `withTransaction` joins the
893
+ caller's, `outermost` refuses one, and `lock`, `lockMany`, `lockWhere` and
894
+ `claim` refuse to run outside one; `lockOrCreate` opens its own (and retries a
895
+ lost insert race only then).
896
+
897
+ When the work throws, the transaction rolls back and the caller gets the
898
+ work's own error, with its status and code, reporting `transactionOutcome:
899
+ "rolledBack"`, so `retryLostInsertRace` (Layer 3) also runs again work that
900
+ turned the duplicate into its own 409. A failed write inside the work, or a failed commit, reaches
901
+ the caller as json-rest-api's `RestApiWriteError` with the transaction's
902
+ outcome. It carries the failure's own `code` and `status` (a driver's
903
+ `ER_CHECKREAD`, a not-found's 404), and `REST_API_WRITE` only when the failure
904
+ has no code. Classify an error by its `code` or `status`,
905
+ never with `instanceof`: a second copy of a package makes a second class.
906
+
907
+ A database error never reaches a client. Its message carries the statement
908
+ and its values, so JSKIT's HTTP handler and the assistant's stream answer one,
909
+ thrown as it is or as a wrapper's cause, with a stand-in
910
+ (`hideDatabaseError` in `@jskit-ai/kernel/server/runtime`) and log it in full:
911
+ 409 `kernel.database.concurrentWrite` when the database refused the transaction for a concurrent one
912
+ (a deadlock or lock wait whose retries ran out, a row changed since the
913
+ transaction's snapshot, a serialization failure), which the client may send
914
+ again, else 500. To give a duplicate key or another database refusal its own
915
+ answer, throw an `AppError` (a `ConflictError`) with the driver's error as its
916
+ `cause`: an `AppError` keeps its answer whatever it wraps.
917
+
918
+ ```js
919
+ const allocate = (input, options) => repository.withTransaction(options, async (txOptions) => {
920
+ const invoices = await repository.lockOpenInvoices(input.invoiceIds, txOptions);
921
+ return repository.recordAllocations(allocationsFor(invoices, input.amount), txOptions);
922
+ });
923
+ ```
924
+
925
+ ## Tables you don't own
926
+
927
+ Ask the owner: its service, or for a JSKIT table its owner API, with the same
928
+ `options`. JSKIT's packages expose their tables this way: users
929
+ (`users.profiles`, `users.settings`), workspaces (`workspaces`,
930
+ `workspaces.memberships`), local sign-in (`auth.local.accounts`,
931
+ `auth.local.sessions`, `auth.local.recovery`) and the console
932
+ (`console.settings`). Local sign-in's owner APIs work in its system context,
933
+ so `jskit check` wants a reviewed reason for each module that requires one
934
+ (see [Hard rules](#hard-rules)). A realtime audience reaches its users the same way: its
935
+ `audienceUsers({ event, options })` asks the owners and answers user ids, in the
936
+ event's scope: for a customer's or a public surface's event, the workspace the
937
+ request resolved, never one its payload names (see [Realtime](/guide/app-extras/realtime)).
938
+
939
+ Code that names people by id (a conversation's members, a group's
940
+ participants) reads them with `users.profiles.listByIds(ids, options)`: every
941
+ profile in one call, however many ids, never `query` pages of 100 walked by
942
+ hand or one `findById` per person. `users.settings.listByUserIds(ids, options)`
943
+ does the same for their settings, and `workspaces.listByIds(ids, options)` for
944
+ workspaces.
945
+
946
+ An app that had a table resource of its own over a JSKIT table (such as
947
+ `users`) deletes it: its CRUD contract is built on the package's table resource
948
+ (users-core's `userProfileTableResource`) and served through the owner with
949
+ `defineCrudFeature({ crud, ownerRepository: "users.profiles" })` (the
950
+ `users/user-administration-server` pattern). The app's own facts about a
951
+ person (a staff role, a preference) live in the app's own table keyed by the
952
+ user id, owned by the app with ownership `user` or `workspace_user`, never as
953
+ new columns on `users`.
954
+
955
+ A surface over a table you don't own that may show only some of its rows (a
956
+ people picker limited to those who share a workspace with the caller) asks the
957
+ owner for exactly that read, as one owner API method that narrows with one
958
+ predicate over the owner's own tables. It never contributes the rule to the
959
+ owner's row policy, which narrows every read of the table (sign-in's too), and
960
+ never passes an id list of everyone the caller may see: an id list is fine for
961
+ the rows one screen shows, not for a rule over thousands of people. An owner
962
+ without such a method gets one added at the owner; until then the surface uses
963
+ the owner's own listing for that scope, such as
964
+ `workspaces.memberships.listActiveByWorkspaceId(workspaceId, options)`, which
965
+ reads the members with their users in one statement.
966
+
967
+ Bad: an app wrote sign-in sessions and memberships with Knex; the framework's
968
+ own checks and audits never ran.
969
+
970
+ ## Two features that need each other
971
+
972
+ When a parent's owner and its children's owners each need the other (the
973
+ parent's service reads its children, and a child's write must advance the
974
+ parent's version), split what both need into a feature of its own, so
975
+ capabilities point one way:
976
+
977
+ - The parent table's owner keeps the table and provides a small owner API,
978
+ such as `versions.advance(id, txOptions)`, and requires none of the
979
+ children.
980
+ - Each child's owner requires that API and calls it in its own write's
981
+ transaction, from its repository's write method. An `owns` entry's
982
+ `afterWrite` hook cannot do it: it is declared with the table, before any
983
+ capability arrives.
984
+ - The aggregate that reads or changes them together (the parent with its
985
+ children) is a third feature that requires both.
986
+
987
+ A version that moves on with no field changed is the parent's
988
+ `lockVersionField`: `lockMany(ids, txOptions)` locks the parents, and
989
+ `patchMany(ids.map((id) => ({ id })), { ...txOptions, returning: "none" })`
990
+ advances each by one, in one statement, whatever the field is called. An
991
+ advance is an update, so it stamps the parent's `updatedAt` too: the parent as
992
+ a whole changed, and a reader that compares either one sees it. A condition
993
+ named with no value, such as `lockVersion: record.lockVersion` on a field
994
+ called `version`, is refused (`options.lockVersion is undefined`), never run
995
+ without it.
996
+
997
+ ## Check and judge
998
+
999
+ Before calling data work done, apply the
1000
+ [sanity checks](sanity-checks.md#query-counts-and-batches) with
1001
+ JSKIT's tools: `expectFlatQueries` for statements that grow with rows,
1002
+ `expectScoped` for every read and write path, and a look at each `// Knex:`
1003
+ method, which `aggregate` or an include might do instead.
1004
+
1005
+ ## Tests
1006
+
1007
+ Each data path gets two one-line tests on the real test database, with the
1008
+ helpers from `@jskit-ai/resource-runtime/test`:
1009
+
1010
+ ```js
1011
+ import { expectEveryTableOwned, expectFlatQueries, expectScoped, startTestFeatures } from "@jskit-ai/resource-runtime/test";
1012
+
1013
+ test("allocation stays in its workspace", () => expectScoped({ environment: process.env, handles: [invoices, payments], systemContext, owners: [workspaceA, workspaceB], seed: seedInvoices, run: (owner) => billing.allocate(input, owner) }));
1014
+ test("allocation is flat", () => expectFlatQueries({ environment: process.env, knex, seed: seedInvoices, run: (seeded) => billing.allocate(inputFor(seeded), seeded.options) }));
1015
+ ```
1016
+
1017
+ `expectFlatQueries` (from `@jskit-ai/resource-runtime/test`) seeds each size,
1018
+ counts the statements the path sends, and fails when a larger size sends more,
1019
+ with the counts and the statements repeated most; the later chunks a many-row
1020
+ write reports are allowed. `expectScoped` runs the path as owner A before and
1021
+ after seeding owner B and fails when the answer changes, so it catches a report
1022
+ that sums, counts or joins B's rows, not only one that returns them; it also
1023
+ fails when the path changed or removed a row of B's. The path runs twice, so it
1024
+ answers the same for the same rows: a write answers what repeats, such as the
1025
+ ids it changed, not a fresh id or time.
1026
+
1027
+ An owner is whatever `seed` and `run` receive. On a workspace path it is a
1028
+ signed-in member's options, built as the request pipeline builds them:
1029
+ `{ context: { actor: { id: userId }, workspace: { id: workspaceId }, permissions } }`,
1030
+ where `permissions` holds the member's role permissions. Seed with a job's
1031
+ context, `{ context: systemContext(reason).forWorkspace(workspaceId) }`. A row
1032
+ policy sees that context as `caller.kind` `"job"`, never as the member.
1033
+
1034
+ A data test never skips: without `TEST_DB_NAME` it fails
1035
+ (`requireTestDatabase(process.env)`). Give `expectFlatQueries` the test's
1036
+ `knex` whenever the features run on it (`startTestFeatures`,
1037
+ `createTestResourceRuntime`). Without `knex` it counts through a server the
1038
+ test booted (`countRuntimeQueries(work)` from
1039
+ `@jskit-ai/database-runtime/server/testDatabases`). A check that measures
1040
+ nothing never passes: "The path sent no statement at any size" means pass
1041
+ `knex`, or the path never reached the database.
1042
+
1043
+ A package's own data test that creates its tables in the test takes its Knex
1044
+ from `createPackageTestKnex(t, { environment: process.env })` (from
1045
+ `@jskit-ai/resource-runtime/test`): an in-memory SQLite database, or on a
1046
+ `DB_CLIENT=pg` run a schema of the test's own in `TEST_DB_NAME`, dropped after
1047
+ it. The same file then proves its locks, many-row writes and upserts on
1048
+ PostgreSQL too; compare counts with `Number()` (PostgreSQL answers them as
1049
+ strings) and ids with `String()`.
1050
+
1051
+ `createTestResourceRuntime({ knex })` gives a test the resource runtime its
1052
+ features own their tables through: `runtime.own(featureId, [resource])`
1053
+ answers the handles, and `runtime.declareSystemScope(featureId, reason)` the
1054
+ `systemContext` function a test reads every owner's rows with. One more test
1055
+ proves every table has an owner:
1056
+ `expectEveryTableOwned({ knex, runtime, infrastructureTables, environment })`
1057
+ fails, naming them, when the migrated test database holds a table no feature
1058
+ owns and no package keeps as infrastructure. JSKIT's packages export their
1059
+ infrastructure tables for it: `LOCAL_AUTH_INFRASTRUCTURE_TABLES`
1060
+ (`@jskit-ai/auth-provider-local-db-core/server/lib/index`),
1061
+ `OIDC_CLIENT_INFRASTRUCTURE_TABLES` (`@jskit-ai/auth-provider-oidc-core/server/lib/index`)
1062
+ and `OIDC_ISSUER_INFRASTRUCTURE_TABLES` (`@jskit-ai/oidc-issuer-core/server`).
1063
+ `runtime` knows only the features the test started, so start every owner of a
1064
+ migrated table, JSKIT's own included, and pass `runtime: resources` from
1065
+ `startTestFeatures`. Local sign-in's tables belong to
1066
+ `AuthLocalDatabaseBackendProvider`
1067
+ (`@jskit-ai/auth-provider-local-db-core/server/providers/AuthLocalDatabaseBackendProvider`,
1068
+ given `inputs: { "runtime.database": { knex } }`).
1069
+ `LOCAL_AUTH_INFRASTRUCTURE_TABLES` lists only the identities table it keeps
1070
+ outside resources.
1071
+
1072
+ A test of a feature and the owner APIs it requires starts them as the server
1073
+ does, without HTTP: `startTestFeatures({ knex, features, requires, inputs,
1074
+ createTables })` orders the features by their requires, owns their tables
1075
+ through a test resource runtime, runs every boot (so `crud.contracts` is
1076
+ sealed) and answers `{ capabilities, resources, stop }`. JSKIT's owners start
1077
+ beside yours: `UsersExtensionsProvider` and `UsersIdentityProvider` give
1078
+ `users.profiles`, and `WorkspaceRecordsFeature`
1079
+ (`@jskit-ai/workspaces-core/test/WorkspaceRecordsFeature`) gives `workspaces`
1080
+ and `workspaces.memberships` without the workspace routes. Never import another
1081
+ package's repositories to build its owner API by hand.
1082
+
1083
+ A `defineCrudFeature` also requires `crud.contracts` and `runtime.http`, which
1084
+ an application's server supplies. In a test, add `CrudContractsProvider`
1085
+ (`@jskit-ai/crud-core/server/crudContracts`) to `features` and give
1086
+ `inputs: { "runtime.http": { router: { register() {} } } }`. The routes are
1087
+ then registered nowhere, and the test calls the feature's `service` and
1088
+ `repository` directly.
1089
+
1090
+ ```js
1091
+ const { capabilities, stop } = await startTestFeatures({
1092
+ knex,
1093
+ features: [RosterFeature, WorkspaceRecordsFeature, UsersIdentityProvider, UsersExtensionsProvider],
1094
+ requires: { roster: "roster" }
1095
+ });
1096
+ t.after(stop);
1097
+ ```
1098
+
1099
+ A test of the routes themselves boots the application's server and signs
1100
+ people in over `app.inject`. Keep one cookie jar per person and send the
1101
+ session's `csrfToken` as `csrf-token` with every write. The session answer
1102
+ carries no user id, so the test finds each person by email
1103
+ (`users.profiles.findByEmail(email)`).
1104
+
1105
+ ```js
1106
+ const app = await createServer({ runtimeEnv: { ...resolveRuntimeEnv(), AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1107
+
1108
+ async function signUp(email, password) {
1109
+ const cookies = new Map();
1110
+ const send = async (options) => {
1111
+ const cookie = [...cookies].map(([name, value]) => `${name}=${value}`).join("; ");
1112
+ const response = await app.inject({ ...options, headers: { ...options.headers, cookie } });
1113
+ for (const header of [response.headers["set-cookie"] ?? []].flat()) {
1114
+ const [name, ...value] = header.split(";")[0].split("=");
1115
+ cookies.set(name.trim(), value.join("="));
1116
+ }
1117
+ return response;
1118
+ };
1119
+ const csrf = async () => (await send({ method: "GET", url: "/api/session" })).json().csrfToken;
1120
+ await send({ method: "POST", url: "/api/register", headers: { "csrf-token": await csrf() }, payload: { email, password } });
1121
+ await send({ method: "POST", url: "/api/login", headers: { "csrf-token": await csrf() }, payload: { email, password } });
1122
+ return send;
1123
+ }
1124
+ ```
1125
+
1126
+ ## Hard rules
1127
+
1128
+ These are always wrong, and lint reports them as errors in all code but a
1129
+ package's client (`src/client`), the app's own `src/` included, since server
1130
+ code sits there too. Tests, migrations and seeds (a `test/`, `migrations/` or
1131
+ `seeds/` folder at the root of the app or of a package, or a `seed*` script in
1132
+ its `scripts/`, `bin/` or root) are outside them; such a folder deeper in
1133
+ server code is server code. Neither `eslint-disable`, an inline
1134
+ `/* eslint ... */` config nor the app's ESLint config can turn them off.
1135
+
1136
+ ### Lint rules
1137
+
1138
+ | Rule | Reports | Section |
1139
+ | --- | --- | --- |
1140
+ | `jskit/no-direct-knex` | a table reached by name with Knex, a `.knex` read or `knex` destructured, a transaction opened by hand | [The resource is the only door](#the-resource-is-the-only-door) |
1141
+ | `jskit/no-transaction-reader` | `options.trx`, `trx \|\| knex`, a `trx = knex` default, `trx` destructured from options, any key but `context` and `trx` read from the `txOptions` work receives | [Transactions](#transactions) |
1142
+ | `jskit/no-hand-scope` | a hand-written `where` on `workspace_id` or `workspaceId` | [Layer 1: the table resource](#layer-1-the-table-resource) |
1143
+ | `jskit/sql-literal` | raw SQL built from strings or templates instead of one literal with bindings | [Layer 5: reports the resource cannot express](#layer-5-reports-the-resource-cannot-express) |
1144
+ | `jskit/no-hand-context` | a system context made with `createSystemContext` or `declareSystemScope`, a context's `scopeValues` written by hand | [Background work](#background-work) |
1145
+ | `jskit/knex-reason` | a `scopedQuery()` report outside a named repository method under `// Knex: <kind> - <reason>` | [Layer 5: reports the resource cannot express](#layer-5-reports-the-resource-cannot-express) |
1146
+
1147
+ ### Exceptions
1148
+
1149
+ A module whose job is data access itself (a database runtime, a migration
1150
+ runner, test-database setup, an operator's data import or cutover tool, a
1151
+ database console that runs the person's own SQL) may opt out of
1152
+ `jskit/no-direct-knex`, `jskit/no-transaction-reader`, `jskit/no-hand-scope`
1153
+ and `jskit/sql-literal` as a whole, with one line per rule before its first
1154
+ line of code:
1155
+
1156
+ ```js
1157
+ // readable-check: allow no-direct-knex - infrastructure: the test databases' snapshot and restore
1158
+ ```
1159
+
1160
+ In a file excused from `jskit/no-direct-knex`, raw SQL runs on Knex itself,
1161
+ so `jskit/sql-literal` lets it hold a statement; it is still one literal with
1162
+ its values as bindings. Only a module that runs SQL it is given by design (a
1163
+ console's query runner) opts out of `jskit/sql-literal` itself, in that one
1164
+ header line with its reason; never with a per-line disable. `jskit check`
1165
+ lists every such file for review. `jskit/no-hand-context` and
1166
+ `jskit/knex-reason` take no exception.
1167
+
1168
+ A data import or cutover tool (loading another system's records into the app's
1169
+ tables before go-live, say) is the one application module that commonly takes
1170
+ it. Check and judge, for each file:
1171
+
1172
+ - it runs only as an operator's command; nothing a request can reach imports
1173
+ it;
1174
+ - it bypasses ownership and row policies on purpose, so every read and write
1175
+ names its workspace explicitly;
1176
+ - it writes in one transaction per batch, so a failed batch leaves nothing
1177
+ half-loaded;
1178
+ - its statements per row are still measured, as any write path's are: a batch
1179
+ of 200 rows costs about what a batch of 10 does.
1180
+
1181
+ `jskit check` also fails:
1182
+
1183
+ - a table with two table resources;
1184
+ - a system scope or `systemContext` call without a reason;
1185
+ - an infrastructure exception or a feature's system scope that the app's
1186
+ checked-in `jskit-data-access.json` does not list, so each new one is
1187
+ reviewed: `{ "infrastructure": [{ "file", "rule" }], "systemScopes":
1188
+ [{ "feature", "systemScope" }, { "file", "capability", "systemScope" }] }`;
1189
+ - a module that requires a capability handing out rows past their owners:
1190
+ `runtime.database` or `runtime.resources` without the infrastructure
1191
+ exception (features own their tables with `owns`), and
1192
+ `realtime.audience-scope`, `auth.local.accounts`, `auth.local.sessions`,
1193
+ `auth.local.recovery`, `connectors.store`, `assistant.repositories` or
1194
+ `payments.store` until `systemScopes` lists that file and capability with
1195
+ its reason, in any spelling the kernel resolves (`Runtime.Resources`); a
1196
+ feature's own id counts only where it provides that capability;
1197
+ - an `eslint-disable` that names a data-access rule, or no rule, or an inline
1198
+ `/* eslint ... */` config that sets one, outside client code;
1199
+ - an app file that the app's ESLint config lints without every data-access
1200
+ rule as an error (`"jskit/no-direct-knex": "off"`, `dataAccessConfig(files,
1201
+ "off")`), or server code (`src/server`, `src/shared`, `server/`) that it
1202
+ ignores, until `infrastructure` lists that file and rule.