@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.20

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 (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
package/src/policy.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { READ_ANY } from '@fabrika/auth-core'
1
2
  import type { Insertable, Selectable, SelectType, Updateable } from 'kysely'
2
3
  import {
3
4
  freeze,
@@ -8,21 +9,29 @@ import {
8
9
  type NameSet,
9
10
  nameSet,
10
11
  namesOf,
11
- OBJECT_PROTOTYPE,
12
- ownDescriptor,
13
12
  ownEntry,
14
13
  ownKeys,
15
- ownNames,
16
- ownSymbols,
17
14
  parseList,
18
- prototypeOf,
15
+ plainRecord,
19
16
  setOwn,
20
17
  } from './builtins'
18
+ import {
19
+ type ConditionHop,
20
+ type ConditionModel,
21
+ type ConditionPolicy,
22
+ conditionReach,
23
+ type ConditionTable,
24
+ type HopRule,
25
+ insertProblem,
26
+ parseCondition,
27
+ singleForeignKey,
28
+ splitPath,
29
+ } from './conditions'
21
30
  import { PolicyError } from './errors'
22
31
  import { isPlainIdentifier } from './identifier'
23
32
  import type { Unavailable } from './orm-types'
24
33
  export type { RowOf } from './orm-types'
25
- import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
34
+ import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
26
35
 
27
36
  export interface DimensionScope<Col extends string> {
28
37
  readonly dimension: string
@@ -50,6 +59,8 @@ export interface ApplicationScope<Col extends string> {
50
59
  /** One action, or a list of them: a table that staff and a public procedure both read names both actions. */
51
60
  export type TableAction<A extends string> = A | readonly A[]
52
61
 
62
+ export { READ_ANY }
63
+
53
64
  export interface TableActions<A extends string> {
54
65
  readonly read: TableAction<A>
55
66
  readonly insert?: TableAction<A>
@@ -57,6 +68,11 @@ export interface TableActions<A extends string> {
57
68
  readonly delete?: TableAction<A>
58
69
  }
59
70
 
71
+ /** An application table's actions: its read may be `'any'` instead of its actions (`READ_ANY`). */
72
+ export interface ApplicationActions<A extends string> extends Omit<TableActions<A>, 'read'> {
73
+ readonly read: TableAction<A> | typeof READ_ANY
74
+ }
75
+
60
76
  /**
61
77
  * A queue table's columns (ADR-0060's drain): `due` is when a row is next claimed, `null` once it is done; `attempts`
62
78
  * counts its claims, and a row with `maxAttempts` (default 10) of them is no longer claimed.
@@ -91,6 +107,98 @@ interface WritablePolicy<Col extends string, A extends string, V extends Col, Ac
91
107
  * file reference. The table's actions are the file's authority.
92
108
  */
93
109
  readonly files?: FilePolicies<Col>
110
+ /** The relations this table's rows confer (`relations` of the vocabulary): each row holds one principal at one node. */
111
+ readonly confers?: { readonly [relation: string]: ConfersPolicy<Col> }
112
+ /** Conditions that narrow an action of this table: a row the condition does not admit is out of that action's reach. */
113
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
114
+ /**
115
+ * Relation → action → a condition on the rows that relation reaches for that action: it narrows the relation's terms
116
+ * only, never an IAM grant, a member reveal or a path grant of the action.
117
+ */
118
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
119
+ /** Relation of this table's own dimension, or of one it reads through → the ancestor node a row the relation reaches reveals. */
120
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
121
+ /**
122
+ * Dimension outside the chain → the foreign key column a read reaches a row through: a `Within` of the dimension, or a
123
+ * relation at it, reads the row, and every write follows containment only. No update writes the column. Or
124
+ * `<nearest container column>.<its column>`: the row is read through its nearest container's own read path.
125
+ */
126
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
127
+ /**
128
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds on the table's rows, writes included:
129
+ * a grant of one of them at the node the path names, or above it, reaches the row for that action. Whoever inserts
130
+ * the path's column must hold every listed action at the node it names.
131
+ */
132
+ readonly writeThrough?: { readonly [dimension: string]: readonly A[] }
133
+ /**
134
+ * This table's own dimension, or one it reads through (`readThrough`) → the ancestor node a row reveals to its
135
+ * members: a grant of one of `actions` at the row's own node, or at the node its path names, holds that action at its
136
+ * node in `to` too, while `when` admits the row.
137
+ */
138
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
139
+ /**
140
+ * Relation → an access view that lists the rows the relation reaches: the escape path for a rule no structured
141
+ * declaration expresses. The view's SQL decides; the layer binds only the caller's principal and the nodes it holds
142
+ * the relation inside, never a handler value.
143
+ */
144
+ readonly access?: { readonly [relation: string]: AccessPolicy }
145
+ }
146
+
147
+ /** An access view: `row` names this table's key; `principal` is compared to the caller, `member` to the nodes it holds the relation inside. */
148
+ export interface AccessPolicy {
149
+ readonly view: string
150
+ readonly row: string
151
+ readonly principal?: string
152
+ readonly member?: string
153
+ }
154
+
155
+ /** What a row reveals to a caller with a grant at its node: its node in `to`, for `actions`, while `when` admits the row. */
156
+ export interface MemberRevealsPolicy<Col extends string, A extends string> {
157
+ readonly to: string
158
+ readonly actions: readonly A[]
159
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
160
+ readonly when?: ConditionPolicy<Col>
161
+ /** Through a path, on a table with an insert action: the writer picks the node, and `self` lets it pick its own. */
162
+ readonly assign?: { readonly self?: true }
163
+ }
164
+
165
+ /**
166
+ * A row of the table that a relation reaches reveals its node in `to`, an ancestor dimension of its chain: the relation
167
+ * then holds `actions` (those of them its roles list in `via`) there, while `when` admits the row.
168
+ */
169
+ export interface RevealsPolicy<Col extends string, A extends string> {
170
+ readonly to: string
171
+ readonly actions: readonly A[]
172
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
173
+ readonly when?: ConditionPolicy<Col>
174
+ /**
175
+ * Required on a reveal matched through `readThrough` of a table with an insert action: the row's writer picks the node,
176
+ * so an insert delegates. Without `self`, an insert that names a node where its writer holds the relation is refused.
177
+ */
178
+ readonly assign?: { readonly self?: true }
179
+ }
180
+
181
+ /**
182
+ * A relation source: each row says that the principal in `principal` stands in the relation to the node `node` holds,
183
+ * until `expires` (none: no deadline) and while `when` admits the row. Writing a row is delegation.
184
+ */
185
+ export interface ConfersPolicy<Col extends string> {
186
+ /**
187
+ * The column that holds the principal, or `<column>.<principal column>`: one foreign key of the table into the key of
188
+ * the table whose column holds it. The table's `createdBy` names the row's writer (it needs `assign.self`).
189
+ */
190
+ readonly principal: Col | `${Col}.${string}`
191
+ /** The column that names the node; by default the table's column for the relation's dimension (its key or its chain). */
192
+ readonly node?: Col
193
+ /** A timestamp column: the row confers nothing once it passed. */
194
+ readonly expires?: Col
195
+ /** A condition on the row's own columns (no foreign-key path): `{ revoked_at: { isNull: true } }`. */
196
+ readonly when?: ConditionPolicy<Col>
197
+ /**
198
+ * Inserting a row delegates the relation's actions to its principal, bounded by the inserting Ref's node: at most
199
+ * `maxDays` ahead (which needs `expires`), and to the inserting principal itself only with `self`.
200
+ */
201
+ readonly assign?: { readonly maxDays?: number; readonly self?: true }
94
202
  }
95
203
 
96
204
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
@@ -123,7 +231,9 @@ export interface ChildPolicy<Table extends string, Col extends string, A extends
123
231
  }
124
232
 
125
233
  /** An application table: written like a dimension table, by an `app` endpoint whose action is the operation's. */
126
- export interface ApplicationPolicy<Col extends string, A extends string, V extends Col = Col> extends WritablePolicy<Col, A, V> {
234
+ export interface ApplicationPolicy<Col extends string, A extends string, V extends Col = Col>
235
+ extends WritablePolicy<Col, A, V, ApplicationActions<A>>
236
+ {
127
237
  readonly scope: ApplicationScope<Col>
128
238
  }
129
239
 
@@ -160,6 +270,17 @@ export interface TableColumns<Col extends string = string, Table extends string
160
270
  readonly dates?: readonly Col[]
161
271
  /** The `timestamp` and `timestamptz` columns, which a write takes as a `Date` or strict ISO 8601 text; absent when none. */
162
272
  readonly timestamps?: readonly Col[]
273
+ /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
274
+ readonly booleans?: readonly Col[]
275
+ /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
276
+ readonly json?: readonly Col[]
277
+ /**
278
+ * The columns declared NOT NULL; absent when none. A foreign key that holds a row's tenant needs its ancestor columns
279
+ * among them: under MATCH SIMPLE a null in one skips the whole key.
280
+ */
281
+ readonly notNull?: readonly Col[]
282
+ /** A view: read-only, with no foreign key; absent for a table. */
283
+ readonly view?: true
163
284
  }
164
285
 
165
286
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -176,9 +297,17 @@ export type ScopeModel =
176
297
  | { readonly mode: 'reference'; readonly reason: string }
177
298
  | { readonly mode: 'app'; readonly reason: string; readonly key: string }
178
299
 
179
- /** Each operation's actions: any one of them allows it. `read` names at least one; an empty list allows no operation. */
300
+ /**
301
+ * Each operation's actions: any one of them allows it. `read` names at least one, unless `readAny`; an empty list
302
+ * allows no operation.
303
+ */
180
304
  export interface ActionModel {
181
305
  readonly read: readonly string[]
306
+ /**
307
+ * An application table read with `'any'`: every `app` endpoint, job and webhook reads it, whatever its action; never a
308
+ * public procedure or a scoped site. `read` is empty then, and a `when` narrows only the writes of its action.
309
+ */
310
+ readonly readAny: boolean
182
311
  readonly insert: readonly string[]
183
312
  readonly update: readonly string[]
184
313
  readonly delete: readonly string[]
@@ -221,13 +350,137 @@ export interface TableModel {
221
350
  readonly dates: NameSet
222
351
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
223
352
  readonly timestamps: NameSet
353
+ /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
354
+ readonly booleans: NameSet
355
+ /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
356
+ readonly json: NameSet
357
+ /** The columns the column list declares NOT NULL. */
358
+ readonly notNull: NameSet
224
359
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
225
360
  readonly foreignKeys: readonly ForeignKey[]
361
+ /** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
362
+ readonly view: boolean
226
363
  /**
227
364
  * The containment links this table carries a column for, nearest first: a dimension table's container and
228
365
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
229
366
  */
230
367
  readonly chain: readonly Container[]
368
+ /** The relations this table's rows confer, each with its columns, its condition and its delegation bound. */
369
+ readonly confers: readonly RelationSource[]
370
+ /** The condition each action of the table holds a row under; an action without one is not narrowed. */
371
+ readonly when: Readonly<Record<string, ConditionModel>>
372
+ /** Relation → action → the condition the rows that relation reaches hold for that action under; ANDed onto its terms only. */
373
+ readonly relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>
374
+ /** The ancestor nodes this table's rows reveal to a relation of its own dimension or of one it reads through. */
375
+ readonly reveals: readonly RevealModel[]
376
+ /** The secondary read paths: a dimension outside the chain, by the column that holds the row's node in it. */
377
+ readonly readThrough: readonly SecondaryPath[]
378
+ /** The ancestor nodes this table's rows reveal to a grant at their own node. */
379
+ readonly memberReveals: readonly MemberRevealModel[]
380
+ /** The access views of the relations whose reach a view's SQL decides. */
381
+ readonly access: readonly AccessModel[]
382
+ }
383
+
384
+ /** A relation's access view over this table: `T.<key> in (select V.<row> from V where <bindings>)`. */
385
+ export interface AccessModel {
386
+ readonly relation: string
387
+ /** The relation's dimension: a hold inside a node of it alone binds `member`. */
388
+ readonly dimension: string
389
+ readonly view: string
390
+ readonly row: string
391
+ readonly principal: string | undefined
392
+ readonly member: string | undefined
393
+ }
394
+
395
+ /**
396
+ * A read path to a dimension outside the chain: `column` holds a key of `table`, which owns `dimension` and lies in
397
+ * `chain`. The column's foreign key covers every ancestor the two chains share, so the node lies in the row's own tenant.
398
+ */
399
+ export interface SecondaryPath {
400
+ readonly dimension: string
401
+ readonly column: string
402
+ readonly table: string
403
+ readonly key: string
404
+ readonly chain: readonly Container[]
405
+ /**
406
+ * The nearest container whose own path this is: the row's `column` of it, its `table` and `key`. `column` above is
407
+ * then the container's column, and the path is read as `T.<via column> in (select C.<key> from C where …)`.
408
+ */
409
+ readonly via: ContainerHop | undefined
410
+ /** The actions a `Ref` held through the path holds on the table's rows (`writeThrough`); a `Within` reads through every path. */
411
+ readonly writes: readonly string[]
412
+ }
413
+
414
+ /** The row's nearest containment column, and the table and key it names. */
415
+ export interface ContainerHop {
416
+ readonly column: string
417
+ readonly table: string
418
+ readonly key: string
419
+ }
420
+
421
+ /**
422
+ * A row of `table` that `relation` reaches reveals its node in `dimension`, held in `column`: the relation holds
423
+ * `actions` at that node while `when` admits the row.
424
+ */
425
+ export interface RevealModel {
426
+ readonly relation: string
427
+ readonly table: string
428
+ /** The table's key, which the relation's nodes match unless the reveal is matched through `path`. */
429
+ readonly key: string
430
+ /**
431
+ * The secondary path whose node, or an ancestor of it, the relation's nodes match. A reveal matched through one holds
432
+ * a `Ref` of an action only where the path does (`writeThrough`).
433
+ */
434
+ readonly path: SecondaryPath | undefined
435
+ /** The bound on an insert's delegation through `path`: `undefined` when no handler inserts a row of the table. */
436
+ readonly assign: { readonly self: boolean } | undefined
437
+ readonly dimension: string
438
+ readonly column: string
439
+ readonly actions: readonly string[]
440
+ readonly when: ConditionModel | undefined
441
+ }
442
+
443
+ /**
444
+ * A row of `table`, a node of `source` (its own dimension, keyed by `key`), reveals its node in `dimension`, held in
445
+ * `column`: a grant of one of `actions` at the row's node holds the action there too, for a `Within`'s reads, while
446
+ * `when` admits the row. Only a grant at the node itself counts, never one at a container of it: an insert would
447
+ * otherwise reveal the ancestor to the container's members at once.
448
+ */
449
+ export interface MemberRevealModel {
450
+ readonly source: string
451
+ readonly table: string
452
+ /** The column a grant's nodes match: the table's key, or `path`'s column. */
453
+ readonly key: string
454
+ /** The secondary path whose node a grant names; a `Ref` holds an action through it only where the path does. */
455
+ readonly path: SecondaryPath | undefined
456
+ /** The bound on an insert's pick of the node through `path`: `undefined` when no handler inserts a row of the table. */
457
+ readonly assign: { readonly self: boolean } | undefined
458
+ readonly dimension: string
459
+ readonly column: string
460
+ readonly actions: readonly string[]
461
+ readonly when: ConditionModel | undefined
462
+ }
463
+
464
+ /** One relation's source table: what a relation term reads, and what a write of its rows is bounded by. */
465
+ export interface RelationSource {
466
+ readonly relation: string
467
+ readonly dimension: string
468
+ readonly table: string
469
+ /** The source's column that decides the principal: it holds it, or it references the row of `principalPath` that does. */
470
+ readonly principal: string
471
+ readonly principalPath: PrincipalPath | undefined
472
+ readonly node: string
473
+ readonly expires: string | undefined
474
+ readonly when: ConditionModel | undefined
475
+ /** `undefined` when the table has no insert action, so no handler writes a row of it. */
476
+ readonly assign: { readonly maxDays: number | undefined; readonly self: boolean } | undefined
477
+ }
478
+
479
+ /** `S.<principal>` references `key` of `table`, whose `column` holds the principal the source row names. */
480
+ export interface PrincipalPath {
481
+ readonly table: string
482
+ readonly key: string
483
+ readonly column: string
231
484
  }
232
485
 
233
486
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -241,7 +494,19 @@ type ParsedScope =
241
494
  readonly inherit: readonly string[] | undefined
242
495
  }
243
496
 
244
- type ParsedTable = Omit<TableModel, 'chain' | 'scope'> & { readonly scope: ParsedScope }
497
+ type ParsedTable =
498
+ & Omit<TableModel, 'chain' | 'scope' | 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
499
+ & {
500
+ readonly scope: ParsedScope
501
+ readonly confersInput: unknown
502
+ readonly whenInput: unknown
503
+ readonly relationWhenInput: unknown
504
+ readonly revealsInput: unknown
505
+ readonly readThroughInput: unknown
506
+ readonly writeThroughInput: unknown
507
+ readonly memberRevealsInput: unknown
508
+ readonly accessInput: unknown
509
+ }
245
510
 
246
511
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
247
512
  let hasModels: (value: object) => boolean = () => false
@@ -297,7 +562,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
297
562
  /** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
298
563
  export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
299
564
  ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
300
- : DefineVocabularyPolicies<ColumnTypes<C>, V>
565
+ : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
301
566
 
302
567
  /**
303
568
  * The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
@@ -314,8 +579,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
314
579
  interface VocabularyModel {
315
580
  readonly dimensions: Containment
316
581
  readonly actions: NameSet
582
+ /** Each relation of the vocabulary, by name, with the dimension its nodes are of. */
583
+ readonly relations: Readonly<Record<string, string>>
317
584
  }
318
585
 
586
+ /** A relation's name: it travels in a token's pseudo-scope `~rel:<name>`, so it is a plain word. */
587
+ const RELATION_NAME = /^[a-z][A-Za-z0-9]*$/
588
+
319
589
  function parseVocabulary(input: unknown): VocabularyModel {
320
590
  const vocabulary = plainRecord(input, 'the vocabulary')
321
591
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -339,12 +609,57 @@ function parseVocabulary(input: unknown): VocabularyModel {
339
609
  }
340
610
  }
341
611
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
342
- return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
612
+ if (includes(actions, READ_ANY)) {
613
+ throw new PolicyError(`the vocabulary may not declare the action '${READ_ANY}': a table's actions.read says '${READ_ANY}' for every action`)
614
+ }
615
+ const relationsInput = ownEntry(vocabulary, 'relations')
616
+ const relations: Record<string, string> = {}
617
+ if (relationsInput !== undefined) {
618
+ const declared = plainRecord(relationsInput, 'the vocabulary relations')
619
+ const relationNames = ownKeys(declared)
620
+ for (let index = 0; index < relationNames.length; index++) {
621
+ const relation = relationNames[index] ?? ''
622
+ if (!RELATION_NAME.test(relation)) {
623
+ throw new PolicyError(`the vocabulary relation ${relation}: a relation name must match ${RELATION_NAME.source}`)
624
+ }
625
+ const dimension = ownEntry(plainRecord(ownEntry(declared, relation), `the vocabulary relation ${relation}`), 'dimension')
626
+ if (typeof dimension !== 'string' || !hasOwn(dimensions, dimension)) {
627
+ throw new PolicyError(`the vocabulary relation ${relation} is of ${String(dimension)}, which is not one of its dimensions`)
628
+ }
629
+ setOwn(relations, relation, dimension)
630
+ }
631
+ }
632
+ return freeze({ dimensions: freeze(containment), actions: nameSet(actions), relations: freeze(relations) })
343
633
  }
344
634
 
345
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps'])
635
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
346
636
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
347
- const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
637
+ const POLICY_FIELDS = nameSet([
638
+ 'scope',
639
+ 'actions',
640
+ 'insert',
641
+ 'update',
642
+ 'version',
643
+ 'createdBy',
644
+ 'columns',
645
+ 'queue',
646
+ 'files',
647
+ 'confers',
648
+ 'when',
649
+ 'relationWhen',
650
+ 'reveals',
651
+ 'readThrough',
652
+ 'writeThrough',
653
+ 'memberReveals',
654
+ 'access',
655
+ ])
656
+ const REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
657
+ const MEMBER_REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
658
+ const REVEAL_ASSIGN_FIELDS = nameSet(['self'])
659
+ const CONFERS_FIELDS = nameSet(['principal', 'node', 'expires', 'when', 'assign'])
660
+ const ASSIGN_FIELDS = nameSet(['maxDays', 'self'])
661
+ /** A delegated row lasts at most ten years ahead: a bound, not a convenience. */
662
+ const MAX_ASSIGN_DAYS = 3650
348
663
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
349
664
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
350
665
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -354,25 +669,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
354
669
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
355
670
  const COLUMN_FIELDS = nameSet(['read', 'write'])
356
671
 
357
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
358
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
359
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
360
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
361
- throw new PolicyError(`${what} must be a plain object`)
362
- }
363
- const copy: Record<string, unknown> = {}
364
- const keys = ownNames(value)
365
- for (let index = 0; index < keys.length; index++) {
366
- const key = keys[index] ?? ''
367
- const descriptor = ownDescriptor(value, key)
368
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
369
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
370
- }
371
- setOwn(copy, key, descriptor.value)
372
- }
373
- return freeze(copy)
374
- }
375
-
376
672
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
377
673
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
378
674
  const keys = ownKeys(record)
@@ -396,15 +692,34 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
396
692
  }
397
693
  }
398
694
  const parsed: ParsedTable[] = []
695
+ const views: Record<string, ViewColumns> = {}
399
696
  for (let index = 0; index < tables.length; index++) {
400
697
  const table = tables[index] ?? ''
401
698
  const policy = ownEntry(policies, table)
699
+ const entry = ownEntry(columns, table)
700
+ if (isViewEntry(table, entry)) {
701
+ const names = parseList(ownEntry(plainRecord(entry, `${table}: the column list entry`), 'columns'), (name) => String(name))
702
+ setOwn(views, table, freeze({ columns: nameSet(names ?? []), policy: policy !== undefined }))
703
+ }
704
+ // A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
705
+ if (policy === undefined && isViewEntry(table, entry)) {
706
+ continue
707
+ }
402
708
  if (policy === undefined) {
403
709
  throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
404
710
  }
405
- parsed[index] = parseTable(table, ownEntry(columns, table), policy, vocabulary)
711
+ parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
712
+ }
713
+ return linkTables(parsed, vocabulary, views)
714
+ }
715
+
716
+ /** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
717
+ function isViewEntry(table: string, entry: unknown): boolean {
718
+ const view = ownEntry(plainRecord(entry, `${table}: the column list entry`), 'view')
719
+ if (view !== undefined && view !== true) {
720
+ throw new PolicyError(`${table}: the column list entry's view is true or absent`)
406
721
  }
407
- return linkTables(parsed, vocabulary.dimensions)
722
+ return view === true
408
723
  }
409
724
 
410
725
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
@@ -460,6 +775,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
460
775
  const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
461
776
  const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
462
777
  const scope = parseScope(table, scopeInput, { column, columnsOf, derived }, vocabulary.dimensions)
778
+ const view = isViewEntry(table, entry)
779
+ if (view && scope.mode !== 'child' && scope.mode !== 'reference') {
780
+ throw new PolicyError(
781
+ `${table}: a view is read-only, so it takes a child scope, { child, key?, column?, inherit? }, or { reference }; ${
782
+ scope.mode === 'app' ? 'an application' : 'a dimension'
783
+ } table's rows are written`,
784
+ )
785
+ }
463
786
  const action = (value: unknown, field: string): string => {
464
787
  const name = nonEmpty(table, value, field)
465
788
  if (!inSet(vocabulary.actions, name)) {
@@ -499,6 +822,9 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
499
822
  restricted[restricted.length] = name
500
823
  }
501
824
  }
825
+ if (writeInput !== undefined && view) {
826
+ throw new PolicyError(viewWrite(table))
827
+ }
502
828
  if (writeInput !== undefined) {
503
829
  setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
504
830
  }
@@ -512,18 +838,26 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
512
838
  if (version !== undefined && hasOwn(columnPolicies, version)) {
513
839
  throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
514
840
  }
515
- const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
841
+ const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
516
842
  const queueInput = ownEntry(policy, 'queue')
517
843
  const filesInput = ownEntry(policy, 'files')
844
+ // On a view, an empty insert or update list is refused too: it states a write the view never takes.
845
+ if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
846
+ throw new PolicyError(viewWrite(table))
847
+ }
518
848
  if (
519
849
  !writable
520
850
  && (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
521
- || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined)
851
+ || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
852
+ || actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
522
853
  ) {
523
- throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
854
+ throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
524
855
  }
525
856
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
526
857
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
858
+ const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
859
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
860
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
527
861
  const queue = queueInput === undefined
528
862
  ? undefined
529
863
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -551,7 +885,19 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
551
885
  columnWrites: freeze(columnWrites),
552
886
  dates,
553
887
  timestamps,
888
+ booleans,
889
+ json,
890
+ notNull,
554
891
  foreignKeys,
892
+ view,
893
+ confersInput: ownEntry(policy, 'confers'),
894
+ whenInput: ownEntry(policy, 'when'),
895
+ relationWhenInput: ownEntry(policy, 'relationWhen'),
896
+ revealsInput: ownEntry(policy, 'reveals'),
897
+ readThroughInput: ownEntry(policy, 'readThrough'),
898
+ writeThroughInput: ownEntry(policy, 'writeThrough'),
899
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
900
+ accessInput: ownEntry(policy, 'access'),
555
901
  }
556
902
  }
557
903
 
@@ -673,7 +1019,10 @@ function parseQueue(
673
1019
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
674
1020
  }
675
1021
 
676
- /** The column list's `date` (`dates`) or timestamp (`timestamps`) columns, each one of the table's. */
1022
+ /**
1023
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
1024
+ * (`notNull`) columns, each one of the table's.
1025
+ */
677
1026
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
678
1027
  if (input === undefined) {
679
1028
  return nameSet([])
@@ -704,6 +1053,24 @@ export function updatableBy(model: TableModel, action: string): NameSet {
704
1053
  return nameSet(columns)
705
1054
  }
706
1055
 
1056
+ /**
1057
+ * The columns any of `actions` updates in `model`, as one role holding them: the union of `updatableBy` over them.
1058
+ * One action's set is `updatableBy`'s own.
1059
+ */
1060
+ export function updatableByAny(model: TableModel, actions: readonly string[]): NameSet {
1061
+ if (actions.length === 1) {
1062
+ return updatableBy(model, actions[0] ?? '')
1063
+ }
1064
+ const columns: string[] = []
1065
+ for (let index = 0; index < actions.length; index++) {
1066
+ const names = namesOf(updatableBy(model, actions[index] ?? ''))
1067
+ for (let position = 0; position < names.length; position++) {
1068
+ columns[columns.length] = names[position] ?? ''
1069
+ }
1070
+ }
1071
+ return nameSet(columns)
1072
+ }
1073
+
707
1074
  /** Whether the table names `action`: one of its table actions, or a column's own write action. */
708
1075
  export function namesAction(model: TableModel, action: string): boolean {
709
1076
  const { read, insert, update, delete: remove } = model.actions
@@ -724,12 +1091,47 @@ export function namesAction(model: TableModel, action: string): boolean {
724
1091
  * one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
725
1092
  */
726
1093
  export function visibleFor(model: TableModel, action: string): readonly string[] {
1094
+ return visibleThrough(model, soleReach(action))
1095
+ }
1096
+
1097
+ /**
1098
+ * The actions whose reach one read answers: an `app` capability's held actions that admit the operation, each row
1099
+ * passing where one of them admits it (`conditionedAny`), and whether their `when` narrows the rows (`narrowed`), which
1100
+ * it does not in a table read with `'any'`.
1101
+ */
1102
+ export interface ReadReach {
1103
+ readonly actions: readonly string[]
1104
+ readonly narrowed: boolean
1105
+ }
1106
+
1107
+ /** The reach of a capability of one action, whose own condition narrows its rows. */
1108
+ export function soleReach(action: string): ReadReach {
1109
+ return freeze({ actions: freeze([action]), narrowed: true })
1110
+ }
1111
+
1112
+ /**
1113
+ * Whether every row a read of `reach` answers is a row `action` reads alone: it is one of the reaching actions, and either
1114
+ * no `when` of its own narrows it or it alone reaches the rows. A column of its own is shown only then, so several held
1115
+ * actions never put one action's column on another action's rows.
1116
+ */
1117
+ export function readsAsAction(model: TableModel, action: string, reach: ReadReach): boolean {
1118
+ if (!includes(reach.actions, action)) {
1119
+ return false
1120
+ }
1121
+ return !reach.narrowed || reach.actions.length === 1 || !hasOwn(model.when, action)
1122
+ }
1123
+
1124
+ /**
1125
+ * The columns a read of `reach` answers, the union of what each reaching action reads alone: every one that declares no
1126
+ * read action of its own, and one that does where that action reads every answered row (`readsAsAction`).
1127
+ */
1128
+ export function visibleThrough(model: TableModel, reach: ReadReach): readonly string[] {
727
1129
  const columns = namesOf(model.columns)
728
1130
  const visible: string[] = []
729
1131
  for (let index = 0; index < columns.length; index++) {
730
1132
  const name = columns[index] ?? ''
731
1133
  const declared = hasOwn(model.columnReads, name) ? model.columnReads[name] : undefined
732
- if (declared === undefined || declared === action) {
1134
+ if (declared === undefined || readsAsAction(model, declared, reach)) {
733
1135
  visible[visible.length] = name
734
1136
  }
735
1137
  }
@@ -848,6 +1250,10 @@ function parseContainer(
848
1250
  return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
849
1251
  }
850
1252
 
1253
+ function viewWrite(table: string): string {
1254
+ return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
1255
+ }
1256
+
851
1257
  function parseActions(
852
1258
  table: string,
853
1259
  scope: Readonly<Record<string, unknown>>,
@@ -869,7 +1275,13 @@ function parseActions(
869
1275
  }
870
1276
  return distinctActions(table, value, `actions.${field}`, action)
871
1277
  }
872
- const read = operation('read')
1278
+ const readAny = ownEntry(actions, 'read') === READ_ANY
1279
+ if (readAny && !hasOwn(scope, 'app')) {
1280
+ throw new PolicyError(
1281
+ `${table}: actions.read 'any' is for an application table; a dimension, child or reference table names its read actions`,
1282
+ )
1283
+ }
1284
+ const read = readAny ? freeze([]) : operation('read')
873
1285
  const records = hasOwn(scope, 'dimension') || hasOwn(scope, 'child')
874
1286
  const kind = hasOwn(scope, 'app') ? 'an application table' : 'a reference table'
875
1287
  const reach = (field: 'appRead' | 'appCount'): readonly string[] => {
@@ -900,7 +1312,7 @@ function parseActions(
900
1312
  throw new PolicyError(`${table}: actions.appRead and actions.appCount both name ${name}`)
901
1313
  }
902
1314
  }
903
- return freeze({ read, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
1315
+ return freeze({ read, readAny, insert: operation('insert'), update: operation('update'), delete: operation('delete'), appRead, appCount })
904
1316
  }
905
1317
 
906
1318
  /** A plain array of distinct actions of the vocabulary, at least one. */
@@ -973,6 +1385,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
973
1385
  if (stamp === undefined) {
974
1386
  continue
975
1387
  }
1388
+ // Nothing writes a view, so its key may be its parent column; a predicate still compares each.
1389
+ if (table.view) {
1390
+ if (inSet(table.json, stamp.column)) {
1391
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
1392
+ }
1393
+ continue
1394
+ }
976
1395
  for (let other = 0; other < index; other++) {
977
1396
  const earlier = stamps[other]
978
1397
  if (earlier !== undefined && earlier.column === stamp.column) {
@@ -987,6 +1406,9 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
987
1406
  if (hasOwn(table.columnWrites, stamp.column)) {
988
1407
  throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
989
1408
  }
1409
+ if (inSet(table.json, stamp.column)) {
1410
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
1411
+ }
990
1412
  }
991
1413
  }
992
1414
 
@@ -1012,7 +1434,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1012
1434
  }
1013
1435
 
1014
1436
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1015
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1437
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel, views: Readonly<Record<string, ViewColumns>>): TableModels {
1438
+ const containment = vocabulary.dimensions
1016
1439
  const byName: Record<string, ParsedTable> = {}
1017
1440
  const owners: Record<string, ParsedTable> = {}
1018
1441
  for (let index = 0; index < parsed.length; index++) {
@@ -1062,104 +1485,1357 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1062
1485
  return result
1063
1486
  }
1064
1487
 
1488
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1489
+ const linkedTable = (name: string): LinkedTable | undefined => {
1490
+ const target = ownEntry(byName, name)
1491
+ if (target === undefined) return undefined
1492
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, ...rest } = target
1493
+ return { ...rest, ...resolve(target, []) }
1494
+ }
1495
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1496
+ const source = ownEntry(byName, from)
1497
+ const target = ownEntry(byName, to)
1498
+ if (target?.scope.mode === 'reference') {
1499
+ return !backward
1500
+ }
1501
+ if (source === undefined || target === undefined) {
1502
+ return false
1503
+ }
1504
+ const into = resolve(target, [])
1505
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1506
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1507
+ return false
1508
+ }
1509
+ const scope = resolve(source, []).scope
1510
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1511
+ if (
1512
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1513
+ && into.scope.dimension === scope.container.dimension
1514
+ ) {
1515
+ return true
1516
+ }
1517
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1518
+ return true
1519
+ }
1520
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1521
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1522
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1523
+ return false
1524
+ }
1525
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1526
+ return true
1527
+ }
1528
+ const sources: Record<string, string> = {}
1529
+ const viewed: Record<string, string> = {}
1065
1530
  const models: Record<string, TableModel> = {}
1066
1531
  for (let index = 0; index < parsed.length; index++) {
1067
1532
  const table = parsed[index]
1068
1533
  if (table !== undefined) {
1069
1534
  const { scope, chain } = resolve(table, [])
1070
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1535
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, accessInput, ...rest } =
1536
+ table
1537
+ const linked = { ...rest, scope, chain }
1538
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1539
+ const owner = ownEntry(owners, dimension)
1540
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1541
+ }
1542
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1543
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1544
+ const declared = ownEntry(byName, container)?.readThroughInput
1545
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1546
+ const target = linkedTable(container)
1547
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1548
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1549
+ }
1550
+ const readThrough = parseWriteThrough(
1551
+ linked,
1552
+ parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath),
1553
+ writeThroughInput,
1554
+ vocabulary,
1555
+ )
1556
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1557
+ for (let position = 0; position < confers.length; position++) {
1558
+ const relation = confers[position]?.relation ?? ''
1559
+ const earlier = ownEntry(sources, relation)
1560
+ if (earlier !== undefined) {
1561
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1562
+ }
1563
+ setOwn(sources, relation, table.name)
1564
+ }
1565
+ const root = conditionRoot(linked, byName)
1566
+ const when = parseWhen(linked, root, whenInput, conditionTable, hopRule)
1567
+ const relationWhen = parseRelationWhen(linked, root, relationWhenInput, vocabulary, conditionTable, hopRule)
1568
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1569
+ const memberReveals = parseMemberReveals(linked, readThrough, memberRevealsInput, vocabulary, conditionTable, hopRule)
1570
+ const access = parseAccess(linked, accessInput, vocabulary, views)
1571
+ for (let position = 0; position < access.length; position++) {
1572
+ const relation = access[position]?.relation ?? ''
1573
+ if (!hasOwn(viewed, relation)) setOwn(viewed, relation, table.name)
1574
+ }
1575
+ setOwn(models, table.name, freeze({ ...linked, confers, when, relationWhen, reveals, readThrough, memberReveals, access }))
1576
+ }
1577
+ }
1578
+ checkRelationWhenReach(models, vocabulary)
1579
+ const relations = ownKeys(vocabulary.relations)
1580
+ for (let index = 0; index < relations.length; index++) {
1581
+ const relation = relations[index] ?? ''
1582
+ if (!hasOwn(sources, relation) && !hasOwn(viewed, relation)) {
1583
+ throw new PolicyError(
1584
+ `the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it, or name an access view for it`,
1585
+ )
1071
1586
  }
1072
1587
  }
1588
+ checkRevealSources(models, sources)
1073
1589
  return freeze(models)
1074
1590
  }
1075
1591
 
1076
- /** A table's scope with nothing left to derive, and its containment chain. */
1077
- interface Resolved {
1078
- readonly scope: ScopeModel
1079
- readonly chain: readonly Container[]
1592
+ /** A reveal is matched through the relation's source rows, so a relation that access views alone serve reveals nothing. */
1593
+ function checkRevealSources(models: Readonly<Record<string, TableModel>>, sources: Readonly<Record<string, string>>): void {
1594
+ const tables = ownKeys(models)
1595
+ for (let index = 0; index < tables.length; index++) {
1596
+ const model = ownEntry(models, tables[index] ?? '')
1597
+ const reveals = model?.reveals ?? []
1598
+ for (let position = 0; position < reveals.length; position++) {
1599
+ const relation = reveals[position]?.relation ?? ''
1600
+ if (model !== undefined && !hasOwn(sources, relation)) {
1601
+ throw new PolicyError(
1602
+ `${model.name}: reveals.${relation} is matched through the rows that confer it, and only access views serve it; declare confers.${relation}`,
1603
+ )
1604
+ }
1605
+ }
1606
+ }
1080
1607
  }
1081
1608
 
1082
- function resolveChain(
1083
- table: ParsedTable,
1084
- byName: Readonly<Record<string, ParsedTable>>,
1085
- owners: Readonly<Record<string, ParsedTable>>,
1086
- containment: Containment,
1087
- chainOf: (table: ParsedTable) => readonly Container[],
1088
- ): Resolved {
1089
- /**
1090
- * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
1091
- * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
1092
- */
1093
- const above = (dimension: string): readonly Container[] => {
1094
- const owner = ownEntry(owners, dimension)
1095
- if (owner !== undefined) {
1096
- return chainOf(owner)
1609
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
1610
+
1611
+ /** A view of the column list: its columns, and whether a policy makes it a table of the layer. */
1612
+ interface ViewColumns {
1613
+ readonly columns: NameSet
1614
+ readonly policy: boolean
1615
+ }
1616
+
1617
+ const ACCESS_FIELDS = nameSet(['view', 'row', 'principal', 'member'])
1618
+
1619
+ /**
1620
+ * `access`: relation → the view whose rows name the table's rows the relation reaches. The view is one the column list
1621
+ * marks, `row` and each binding are its columns, and at least one binding is stated, so the subquery never reads every
1622
+ * row: `principal` is compared to the caller, `member` to the nodes of the relation's dimension it holds the relation in.
1623
+ */
1624
+ function parseAccess(
1625
+ table: LinkedTable,
1626
+ input: unknown,
1627
+ vocabulary: VocabularyModel,
1628
+ views: Readonly<Record<string, ViewColumns>>,
1629
+ ): readonly AccessModel[] {
1630
+ if (input === undefined) {
1631
+ return freeze([])
1632
+ }
1633
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1634
+ throw new PolicyError(`${table.name}: only a dimension or child table, or a child view, takes access; its rows are what a relation reaches`)
1635
+ }
1636
+ const declared = plainRecord(input, `${table.name}: access`)
1637
+ const relations = ownKeys(declared)
1638
+ const parsed: AccessModel[] = []
1639
+ for (let index = 0; index < relations.length; index++) {
1640
+ const relation = relations[index] ?? ''
1641
+ const what = `${table.name}: access.${relation}`
1642
+ if (!hasOwn(vocabulary.relations, relation)) {
1643
+ throw new PolicyError(`${what} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`)
1097
1644
  }
1098
- const container = ownEntry(containment, dimension)?.container
1099
- return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
1100
- }
1101
- const scope = table.scope
1102
- if (scope.mode === 'dimension') {
1103
- const container = scope.container
1104
- if (container === undefined) {
1105
- return { scope, chain: freeze([]) }
1645
+ const entry = plainRecord(ownEntry(declared, relation), what)
1646
+ onlyFields(entry, ACCESS_FIELDS, what)
1647
+ const view = ownEntry(entry, 'view')
1648
+ const named = typeof view === 'string' ? ownEntry(views, view) : undefined
1649
+ if (typeof view !== 'string' || named === undefined) {
1650
+ throw new PolicyError(`${what}.view names ${String(view)}, which the column list does not mark as a view`)
1106
1651
  }
1107
- const owner = ownEntry(owners, container.dimension)
1108
- if (owner !== undefined) {
1109
- requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
1110
- requireCoveringKey(table, container, owner, chainOf(owner))
1652
+ // Read directly, the view would show the caller who else reaches which row.
1653
+ if (named.policy) {
1654
+ throw new PolicyError(`${what}.view names ${view}, which has a policy; an access view takes none, so only the relation's term reads it`)
1111
1655
  }
1112
- return { scope, chain: prepend(container, above(container.dimension)) }
1113
- }
1114
- if (scope.mode !== 'child') {
1115
- return { scope, chain: freeze([]) }
1116
- }
1117
- const parent = ownEntry(byName, scope.parent)
1118
- if (parent === undefined || parent.scope.mode !== 'dimension') {
1119
- throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
1120
- }
1121
- const parentChain = chainOf(parent)
1122
- const expected: string[] = []
1123
- for (let index = 0; index < parentChain.length; index++) {
1124
- expected[index] = parentChain[index]?.column ?? ''
1656
+ const columns = named.columns
1657
+ const viewColumn = (field: string, required: boolean): string | undefined => {
1658
+ const name = ownEntry(entry, field)
1659
+ if (name === undefined && !required) return undefined
1660
+ if (typeof name !== 'string' || !inSet(columns, name)) {
1661
+ throw new PolicyError(`${what}.${field} names ${String(name)}, which is not a column of ${view}`)
1662
+ }
1663
+ return name
1664
+ }
1665
+ const row = viewColumn('row', true) ?? ''
1666
+ const principal = viewColumn('principal', false)
1667
+ const member = viewColumn('member', false)
1668
+ if (principal === undefined && member === undefined) {
1669
+ throw new PolicyError(`${what} binds neither principal nor member: an access view is read for the caller, never whole`)
1670
+ }
1671
+ parsed[parsed.length] = freeze({ relation, dimension: ownEntry(vocabulary.relations, relation) ?? '', view, row, principal, member })
1125
1672
  }
1126
- const inherit = scope.inherit ?? freeze(expected)
1127
- const inherited = nameSet(inherit)
1128
- let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
1129
- for (let index = 0; index < expected.length; index++) {
1130
- matches = matches && inSet(inherited, expected[index])
1673
+ return freeze(parsed)
1674
+ }
1675
+
1676
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1677
+ function tableActionNames(table: LinkedTable): NameSet {
1678
+ const names: string[] = []
1679
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1680
+ for (let list = 0; list < lists.length; list++) {
1681
+ const actions = lists[list] ?? []
1682
+ for (let index = 0; index < actions.length; index++) {
1683
+ names[names.length] = actions[index] ?? ''
1684
+ }
1131
1685
  }
1132
- if (!matches) {
1133
- throw new PolicyError(
1134
- `${table.name}: must inherit exactly the containment columns of ${scope.parent} (${
1135
- expected.join(', ') || 'none'
1136
- }), so a composite foreign key keeps it in scope`,
1137
- )
1686
+ const reads = ownKeys(table.columnReads)
1687
+ for (let index = 0; index < reads.length; index++) {
1688
+ names[names.length] = ownEntry(table.columnReads, reads[index] ?? '') ?? ''
1138
1689
  }
1139
- const dimension = parent.scope.dimension
1140
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1141
- requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1142
- requireCoveringKey(table, link, parent, parentChain)
1143
- return {
1144
- scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }),
1145
- chain: prepend(link, parentChain),
1690
+ const writes = ownKeys(table.columnWrites)
1691
+ for (let index = 0; index < writes.length; index++) {
1692
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1146
1693
  }
1694
+ return nameSet(names)
1147
1695
  }
1148
1696
 
1149
- /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1150
- function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1151
- for (let index = 0; index < table.foreignKeys.length; index++) {
1152
- const foreignKey = table.foreignKeys[index]
1153
- if (foreignKey === undefined || foreignKey.table !== target) {
1154
- continue
1155
- }
1156
- for (let position = 0; position < foreignKey.columns.length; position++) {
1157
- if (foreignKey.columns[position] === column && foreignKey.references[position] === key) {
1158
- return true
1159
- }
1697
+ /** The actions that write a table: its insert, update and delete actions and its columns' own write actions. */
1698
+ function writeActionNames(table: LinkedTable): NameSet {
1699
+ const names: string[] = []
1700
+ const lists = [table.actions.insert, table.actions.update, table.actions.delete]
1701
+ for (let list = 0; list < lists.length; list++) {
1702
+ const actions = lists[list] ?? []
1703
+ for (let index = 0; index < actions.length; index++) {
1704
+ names[names.length] = actions[index] ?? ''
1160
1705
  }
1161
1706
  }
1162
- return false
1707
+ const writes = ownKeys(table.columnWrites)
1708
+ for (let index = 0; index < writes.length; index++) {
1709
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1710
+ }
1711
+ return nameSet(names)
1712
+ }
1713
+
1714
+ /**
1715
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1716
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1717
+ */
1718
+ function parseWhen(
1719
+ table: LinkedTable,
1720
+ root: ConditionTable,
1721
+ input: unknown,
1722
+ tables: (name: string) => ConditionTable | undefined,
1723
+ hops: HopRule,
1724
+ ): Readonly<Record<string, ConditionModel>> {
1725
+ if (input === undefined) {
1726
+ return freeze({})
1727
+ }
1728
+ if (table.scope.mode === 'reference') {
1729
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1730
+ }
1731
+ const declared = plainRecord(input, `${table.name}: when`)
1732
+ const named = tableActionNames(table)
1733
+ const actions = ownKeys(declared)
1734
+ const when: Record<string, ConditionModel> = {}
1735
+ for (let index = 0; index < actions.length; index++) {
1736
+ const action = actions[index] ?? ''
1737
+ if (!inSet(named, action)) {
1738
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1739
+ }
1740
+ if (table.actions.readAny && !inSet(writeActionNames(table), action)) {
1741
+ throw new PolicyError(
1742
+ `${table.name}: when.${action} narrows nothing: the table is read with 'any', and a when narrows only the writes of an action that inserts, updates or deletes`,
1743
+ )
1744
+ }
1745
+ const what = `${table.name}: when.${action}`
1746
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1747
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1748
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1749
+ if (problem !== undefined) {
1750
+ throw new PolicyError(`${what}: ${problem}`)
1751
+ }
1752
+ setOwn(when, action, condition)
1753
+ }
1754
+ return freeze(when)
1755
+ }
1756
+
1757
+ /**
1758
+ * `relationWhen`: relation → action → a condition on the rows the relation reaches for the action, parsed as `when` is
1759
+ * (the same root, hop rule and insert rule). The relation must be the vocabulary's and the action the table's; whether
1760
+ * the relation reaches the table at all is checked once every table is parsed (`checkRelationWhenReach`).
1761
+ */
1762
+ function parseRelationWhen(
1763
+ table: LinkedTable,
1764
+ root: ConditionTable,
1765
+ input: unknown,
1766
+ vocabulary: VocabularyModel,
1767
+ tables: (name: string) => ConditionTable | undefined,
1768
+ hops: HopRule,
1769
+ ): Readonly<Record<string, Readonly<Record<string, ConditionModel>>>> {
1770
+ if (input === undefined) {
1771
+ return freeze({})
1772
+ }
1773
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1774
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table takes no relationWhen; no relation reaches its rows`)
1775
+ }
1776
+ const declared = plainRecord(input, `${table.name}: relationWhen`)
1777
+ const relations = ownKeys(declared)
1778
+ const named = tableActionNames(table)
1779
+ const parsed: Record<string, Readonly<Record<string, ConditionModel>>> = {}
1780
+ for (let index = 0; index < relations.length; index++) {
1781
+ const relation = relations[index] ?? ''
1782
+ if (!hasOwn(vocabulary.relations, relation)) {
1783
+ throw new PolicyError(
1784
+ `${table.name}: relationWhen.${relation} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`,
1785
+ )
1786
+ }
1787
+ const perAction = plainRecord(ownEntry(declared, relation), `${table.name}: relationWhen.${relation}`)
1788
+ const actions = ownKeys(perAction)
1789
+ if (actions.length === 0) {
1790
+ throw new PolicyError(`${table.name}: relationWhen.${relation} names no action`)
1791
+ }
1792
+ const conditions: Record<string, ConditionModel> = {}
1793
+ for (let position = 0; position < actions.length; position++) {
1794
+ const action = actions[position] ?? ''
1795
+ const what = `${table.name}: relationWhen.${relation}.${action}`
1796
+ if (!inSet(named, action)) {
1797
+ throw new PolicyError(`${what} names an action the table does not name (${namesOf(named).join(', ')})`)
1798
+ }
1799
+ const condition = parseCondition(ownEntry(perAction, action), root, tables, what, hops)
1800
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1801
+ if (problem !== undefined) {
1802
+ throw new PolicyError(`${what}: ${problem}`)
1803
+ }
1804
+ setOwn(conditions, action, condition)
1805
+ }
1806
+ setOwn(parsed, relation, freeze(conditions))
1807
+ }
1808
+ return freeze(parsed)
1809
+ }
1810
+
1811
+ /**
1812
+ * Every `relationWhen` names a relation that reaches the table for its action: the relation's dimension is the table's
1813
+ * or on its chain, a secondary path reaches it, or a reveal of the relation for the action reveals a node the table
1814
+ * lies at. A child view is reached through its parent row, so its parent is what the relation must reach.
1815
+ */
1816
+ function checkRelationWhenReach(models: Readonly<Record<string, TableModel>>, vocabulary: VocabularyModel): void {
1817
+ const names = ownKeys(models)
1818
+ const reveals: RevealModel[] = []
1819
+ for (let index = 0; index < names.length; index++) {
1820
+ const model = ownEntry(models, names[index] ?? '')
1821
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
1822
+ const reveal = model.reveals[position]
1823
+ if (reveal !== undefined) reveals[reveals.length] = reveal
1824
+ }
1825
+ }
1826
+ for (let index = 0; index < names.length; index++) {
1827
+ const model = ownEntry(models, names[index] ?? '')
1828
+ if (model === undefined) continue
1829
+ const reached = model.view && model.scope.mode === 'child' ? ownEntry(models, model.scope.parent) ?? model : model
1830
+ const relations = ownKeys(model.relationWhen)
1831
+ for (let position = 0; position < relations.length; position++) {
1832
+ const relation = relations[position] ?? ''
1833
+ const dimension = ownEntry(vocabulary.relations, relation) ?? ''
1834
+ const actions = ownKeys(ownEntry(model.relationWhen, relation) ?? {})
1835
+ for (let next = 0; next < actions.length; next++) {
1836
+ const action = actions[next] ?? ''
1837
+ if (!relationReaches(reached, relation, dimension, action, reveals)) {
1838
+ throw new PolicyError(
1839
+ `${model.name}: relationWhen.${relation}.${action} names a relation that reaches no row of ${reached.name} for ${action}: neither its chain nor a secondary path holds ${dimension}, and no reveal of ${relation} for ${action} names a node it lies at`,
1840
+ )
1841
+ }
1842
+ }
1843
+ }
1844
+ }
1845
+ }
1846
+
1847
+ /** Whether `relation` of `dimension` reaches a row of `model` for `action`, as the relation terms of the store find one. */
1848
+ function relationReaches(model: TableModel, relation: string, dimension: string, action: string, reveals: readonly RevealModel[]): boolean {
1849
+ if (nodeColumnOf(model, dimension) !== undefined || model.access.some((access) => access.relation === relation)) {
1850
+ return true
1851
+ }
1852
+ for (let index = 0; index < model.readThrough.length; index++) {
1853
+ const path = model.readThrough[index]
1854
+ if (path === undefined) continue
1855
+ if (path.dimension === dimension) return true
1856
+ for (let link = 0; link < path.chain.length; link++) {
1857
+ if (path.chain[link]?.dimension === dimension) return true
1858
+ }
1859
+ }
1860
+ for (let index = 0; index < reveals.length; index++) {
1861
+ const reveal = reveals[index]
1862
+ if (
1863
+ reveal !== undefined && reveal.relation === relation && includes(reveal.actions, action) && nodeColumnOf(model, reveal.dimension) !== undefined
1864
+ ) {
1865
+ return true
1866
+ }
1867
+ }
1868
+ return false
1869
+ }
1870
+
1871
+ /**
1872
+ * The table a `when` of `table` starts at. A child view's parent column is a foreign key to its parent's key that no
1873
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
1874
+ */
1875
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
1876
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
1877
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
1878
+ return table
1879
+ }
1880
+ const foreignKeys: ForeignKey[] = []
1881
+ for (let index = 0; index < table.foreignKeys.length; index++) {
1882
+ const key = table.foreignKeys[index]
1883
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
1884
+ }
1885
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
1886
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
1887
+ }
1888
+
1889
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
1890
+ interface ResolvedOwner extends Resolved {
1891
+ readonly name: string
1892
+ }
1893
+
1894
+ /**
1895
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
1896
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
1897
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
1898
+ * nearest container's own path instead (`containerPath`).
1899
+ */
1900
+ function parseReadThrough(
1901
+ table: LinkedTable,
1902
+ input: unknown,
1903
+ vocabulary: VocabularyModel,
1904
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1905
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1906
+ ): readonly SecondaryPath[] {
1907
+ if (input === undefined) {
1908
+ return freeze([])
1909
+ }
1910
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1911
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
1912
+ }
1913
+ if (table.queue !== undefined) {
1914
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
1915
+ }
1916
+ const declared = plainRecord(input, `${table.name}: readThrough`)
1917
+ const dimensions = ownKeys(declared)
1918
+ const paths: SecondaryPath[] = []
1919
+ for (let index = 0; index < dimensions.length; index++) {
1920
+ const dimension = dimensions[index] ?? ''
1921
+ const what = `${table.name}: readThrough.${dimension}`
1922
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
1923
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
1924
+ }
1925
+ if (nodeColumnOf(table, dimension) !== undefined) {
1926
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
1927
+ }
1928
+ const column = ownEntry(declared, dimension)
1929
+ const segments = typeof column === 'string' ? splitPath(column) : []
1930
+ if (segments.length === 2) {
1931
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
1932
+ continue
1933
+ }
1934
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
1935
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
1936
+ }
1937
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
1938
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
1939
+ }
1940
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
1941
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
1942
+ }
1943
+ for (let position = 0; position < table.chain.length; position++) {
1944
+ if (table.chain[position]?.column === column) {
1945
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
1946
+ }
1947
+ }
1948
+ const owner = ownerOf(dimension)
1949
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
1950
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
1951
+ }
1952
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
1953
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
1954
+ if (!covered) {
1955
+ const columns: string[] = []
1956
+ const referenced: string[] = []
1957
+ for (let position = 0; position < pairs.length; position++) {
1958
+ columns[position] = pairs[position]?.[0] ?? ''
1959
+ referenced[position] = pairs[position]?.[1] ?? ''
1960
+ }
1961
+ throw new PolicyError(
1962
+ `${what}: ${column} and every ancestor ${table.name} shares with ${owner.name} must be one foreign key of exactly these columns, so the node lies in the row's own tenant; declare foreign key (${
1963
+ columns.join(', ')
1964
+ }) references ${owner.name} (${referenced.join(', ')})`,
1965
+ )
1966
+ }
1967
+ requireNotNullAncestors(what, table, pairs)
1968
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined, writes: freeze([]) })
1969
+ }
1970
+ return freeze(paths)
1971
+ }
1972
+
1973
+ /**
1974
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
1975
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
1976
+ * container's own path column, which no update of the container writes; so the read follows containment and the
1977
+ * container's path, and nothing the row's writer picks.
1978
+ */
1979
+ function throughContainer(
1980
+ table: LinkedTable,
1981
+ link: string,
1982
+ column: string,
1983
+ dimension: string,
1984
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1985
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1986
+ what: string,
1987
+ ): SecondaryPath {
1988
+ const nearest = table.chain[0]
1989
+ if (nearest === undefined || nearest.column !== link) {
1990
+ throw new PolicyError(
1991
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
1992
+ nearest === undefined ? '' : ` (${nearest.column})`
1993
+ }; a path through a container starts at the row's own container`,
1994
+ )
1995
+ }
1996
+ const container = ownerOf(nearest.dimension)
1997
+ if (container === undefined || container.scope.mode !== 'dimension') {
1998
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
1999
+ }
2000
+ const path = containerPath(container.name, dimension)
2001
+ if (path === undefined) {
2002
+ throw new PolicyError(
2003
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
2004
+ )
2005
+ }
2006
+ if (path.column !== column) {
2007
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
2008
+ }
2009
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }), writes: freeze([]) })
2010
+ }
2011
+
2012
+ /**
2013
+ * `writeThrough`: a dimension the table reads through → the actions a `Ref` held through that path holds. Each is an
2014
+ * action of the vocabulary: the table's own, or one a reveal matched through the path or a table below reaches the row
2015
+ * for. The path's column is the delegation: whoever inserts it must hold every listed action at the node it names, and
2016
+ * for a path through the container, whoever inserts the container's column (`pathWriters`).
2017
+ */
2018
+ function parseWriteThrough(
2019
+ table: LinkedTable,
2020
+ readThrough: readonly SecondaryPath[],
2021
+ input: unknown,
2022
+ vocabulary: VocabularyModel,
2023
+ ): readonly SecondaryPath[] {
2024
+ if (input === undefined) {
2025
+ return readThrough
2026
+ }
2027
+ const declared = plainRecord(input, `${table.name}: writeThrough`)
2028
+ const dimensions = ownKeys(declared)
2029
+ const writes: Record<string, readonly string[]> = {}
2030
+ for (let index = 0; index < dimensions.length; index++) {
2031
+ const dimension = dimensions[index] ?? ''
2032
+ const what = `${table.name}: writeThrough.${dimension}`
2033
+ let declaredPath = false
2034
+ for (let position = 0; position < readThrough.length; position++) {
2035
+ if (readThrough[position]?.dimension === dimension) declaredPath = true
2036
+ }
2037
+ if (!declaredPath) {
2038
+ throw new PolicyError(`${what}: ${table.name} reads no path to ${dimension}; declare readThrough.${dimension} first`)
2039
+ }
2040
+ const actions = parseList(ownEntry(declared, dimension), (action) => {
2041
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2042
+ throw new PolicyError(`${what} names ${String(action)}, which is not an action of the vocabulary`)
2043
+ }
2044
+ return action
2045
+ })
2046
+ if (actions === undefined) {
2047
+ throw new PolicyError(`${what} takes a plain array of the vocabulary's actions`)
2048
+ }
2049
+ const listed: string[] = []
2050
+ for (let position = 0; position < actions.length; position++) {
2051
+ const action = actions[position] ?? ''
2052
+ if (!includes(listed, action)) listed[listed.length] = action
2053
+ }
2054
+ if (listed.length === 0) {
2055
+ throw new PolicyError(`${what} names no action; leave the dimension out to hold nothing through the path`)
2056
+ }
2057
+ setOwn(writes, dimension, freeze(listed))
2058
+ }
2059
+ const paths: SecondaryPath[] = []
2060
+ for (let index = 0; index < readThrough.length; index++) {
2061
+ const path = readThrough[index]
2062
+ if (path === undefined) continue
2063
+ const listed = ownEntry(writes, path.dimension)
2064
+ paths[paths.length] = listed === undefined ? path : freeze({ ...path, writes: listed })
2065
+ }
2066
+ return freeze(paths)
2067
+ }
2068
+
2069
+ /**
2070
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
2071
+ * matches the row's key, or of a dimension the table reaches, so it matches that path's column; the ancestor is a link of the chain, whose column the layer stamps and a move rewrites, so the
2072
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
2073
+ */
2074
+ function parseReveals(
2075
+ table: LinkedTable,
2076
+ readThrough: readonly SecondaryPath[],
2077
+ input: unknown,
2078
+ vocabulary: VocabularyModel,
2079
+ tables: (name: string) => ConditionTable | undefined,
2080
+ hops: HopRule,
2081
+ ): readonly RevealModel[] {
2082
+ if (input === undefined) {
2083
+ return freeze([])
2084
+ }
2085
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2086
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
2087
+ }
2088
+ if (table.queue !== undefined) {
2089
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2090
+ }
2091
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2092
+ const key = table.scope.key
2093
+ const declared = plainRecord(input, `${table.name}: reveals`)
2094
+ const names = ownKeys(declared)
2095
+ const reveals: RevealModel[] = []
2096
+ for (let index = 0; index < names.length; index++) {
2097
+ const relation = names[index] ?? ''
2098
+ const what = `${table.name}: reveals.${relation}`
2099
+ const dimension = ownEntry(vocabulary.relations, relation)
2100
+ if (dimension === undefined) {
2101
+ throw new PolicyError(
2102
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
2103
+ )
2104
+ }
2105
+ const paths: SecondaryPath[] = []
2106
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
2107
+ const path = readThrough[position]
2108
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
2109
+ }
2110
+ if (dimension !== own && paths.length !== 1) {
2111
+ throw new PolicyError(
2112
+ paths.length === 0
2113
+ ? `${what}: ${relation} is of ${dimension}, which is neither ${table.name}'s own dimension nor one it reads through, or above one; a table reveals for a relation that reaches its rows`
2114
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
2115
+ )
2116
+ }
2117
+ const policy = plainRecord(ownEntry(declared, relation), what)
2118
+ onlyFields(policy, REVEALS_FIELDS, what)
2119
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2120
+ const path = paths[0]
2121
+ if (path?.via !== undefined) {
2122
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
2123
+ throw new PolicyError(
2124
+ `${what}: ${table.name} reads ${dimension} through its container ${path.via.table}, so a reveal matched through it reads too deep; reveal from ${path.via.table} instead`,
2125
+ )
2126
+ }
2127
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2128
+ throw new PolicyError(
2129
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a reveal through a secondary path reveals the nearest container only`,
2130
+ )
2131
+ }
2132
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2133
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
2134
+ }
2135
+ return freeze(reveals)
2136
+ }
2137
+
2138
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
2139
+ function parseRevealed(
2140
+ table: LinkedTable,
2141
+ policy: Readonly<Record<string, unknown>>,
2142
+ what: string,
2143
+ vocabulary: VocabularyModel,
2144
+ tables: (name: string) => ConditionTable | undefined,
2145
+ hops: HopRule,
2146
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
2147
+ const to = ownEntry(policy, 'to')
2148
+ let column: string | undefined
2149
+ for (let position = 0; position < table.chain.length; position++) {
2150
+ const link = table.chain[position]
2151
+ if (link !== undefined && link.dimension === to) column = link.column
2152
+ }
2153
+ if (typeof to !== 'string' || column === undefined) {
2154
+ const above: string[] = []
2155
+ for (let position = 0; position < table.chain.length; position++) {
2156
+ above[above.length] = table.chain[position]?.dimension ?? ''
2157
+ }
2158
+ throw new PolicyError(
2159
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
2160
+ )
2161
+ }
2162
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
2163
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2164
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
2165
+ }
2166
+ return action
2167
+ })
2168
+ if (actions === undefined) {
2169
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
2170
+ }
2171
+ const listed: string[] = []
2172
+ for (let position = 0; position < actions.length; position++) {
2173
+ const action = actions[position] ?? ''
2174
+ if (!includes(listed, action)) listed[listed.length] = action
2175
+ }
2176
+ if (listed.length === 0) {
2177
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
2178
+ }
2179
+ const whenInput = ownEntry(policy, 'when')
2180
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
2181
+ return { to, column, actions: freeze(listed), when }
2182
+ }
2183
+
2184
+ /**
2185
+ * `memberReveals`: the table's own dimension, or one it reads through, → the ancestor its rows reveal to a grant at the
2186
+ * node. By its own key only a dimension table reveals so: the layer generates the key, so no writer picks a node someone
2187
+ * already holds a grant at. Through a direct path the writer picks it, so an insertable table states `assign`, and the
2188
+ * row reveals its nearest container only, whose column no move of an ancestor rewrites. A queue table's rows move on
2189
+ * every claim.
2190
+ */
2191
+ function parseMemberReveals(
2192
+ table: LinkedTable,
2193
+ readThrough: readonly SecondaryPath[],
2194
+ input: unknown,
2195
+ vocabulary: VocabularyModel,
2196
+ tables: (name: string) => ConditionTable | undefined,
2197
+ hops: HopRule,
2198
+ ): readonly MemberRevealModel[] {
2199
+ if (input === undefined) {
2200
+ return freeze([])
2201
+ }
2202
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2203
+ throw new PolicyError(
2204
+ `${table.name}: a ${table.scope.mode} table reveals nothing to members; only a dimension or child table's rows name a node a grant is at`,
2205
+ )
2206
+ }
2207
+ if (table.queue !== undefined) {
2208
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2209
+ }
2210
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2211
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
2212
+ const names = ownKeys(declared)
2213
+ const reveals: MemberRevealModel[] = []
2214
+ for (let index = 0; index < names.length; index++) {
2215
+ const source = names[index] ?? ''
2216
+ const what = `${table.name}: memberReveals.${source}`
2217
+ let path: SecondaryPath | undefined
2218
+ for (let position = 0; source !== own && position < readThrough.length; position++) {
2219
+ if (readThrough[position]?.dimension === source) path = readThrough[position]
2220
+ }
2221
+ if (source !== own && path === undefined) {
2222
+ throw new PolicyError(
2223
+ `${what}: ${source} is neither the own dimension of ${table.name} (${
2224
+ own ?? 'none'
2225
+ }) nor one it reads through; a row reveals to a grant at its own node or at the node its path names`,
2226
+ )
2227
+ }
2228
+ const policy = plainRecord(ownEntry(declared, source), what)
2229
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
2230
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2231
+ if (path?.via !== undefined) {
2232
+ throw new PolicyError(
2233
+ `${what}: ${table.name} reads ${source} through its container ${path.via.table}; declare the member reveal on ${path.via.table}`,
2234
+ )
2235
+ }
2236
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2237
+ throw new PolicyError(
2238
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a member reveal through a path reveals the nearest container only`,
2239
+ )
2240
+ }
2241
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2242
+ const key = path === undefined ? table.scope.key : path.column
2243
+ reveals[reveals.length] = freeze({ source, table: table.name, key, path, assign, dimension: to, column, actions, when })
2244
+ }
2245
+ return freeze(reveals)
2246
+ }
2247
+
2248
+ /**
2249
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
2250
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
2251
+ */
2252
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
2253
+ if (path === undefined || table.actions.insert.length === 0) {
2254
+ if (input !== undefined) {
2255
+ throw new PolicyError(
2256
+ path === undefined
2257
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
2258
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
2259
+ )
2260
+ }
2261
+ return undefined
2262
+ }
2263
+ if (input === undefined) {
2264
+ throw new PolicyError(
2265
+ `${what}: inserting a row of ${table.name} (${
2266
+ table.actions.insert.join(', ')
2267
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
2268
+ )
2269
+ }
2270
+ const assign = plainRecord(input, `${what}.assign`)
2271
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
2272
+ const self = ownEntry(assign, 'self')
2273
+ if (self !== undefined && self !== true) {
2274
+ throw new PolicyError(`${what}.assign.self takes true`)
2275
+ }
2276
+ return freeze({ self: self === true })
2277
+ }
2278
+
2279
+ /**
2280
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
2281
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
2282
+ */
2283
+ export function delegates(model: TableModel): boolean {
2284
+ for (let index = 0; index < model.reveals.length; index++) {
2285
+ if (model.reveals[index]?.path !== undefined) return true
2286
+ }
2287
+ return model.confers.length > 0 || model.memberReveals.length > 0
2288
+ }
2289
+
2290
+ /**
2291
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
2292
+ * source, a path reveal or a path column that holds actions (`writeThrough`), whose writer the layer bounds; a
2293
+ * member-revealing table, whose key the layer generates so no write revives a node a stale grant still names; and the
2294
+ * tables a principal path or a relation's condition reads, whose columns decide whom a source row names and what it
2295
+ * confers.
2296
+ */
2297
+ export function accessTablesOf(models: TableModels): readonly string[] {
2298
+ const tables: string[] = []
2299
+ const names = ownKeys(models)
2300
+ for (let index = 0; index < names.length; index++) {
2301
+ const model = modelOf(models, names[index] ?? '')
2302
+ if (model !== undefined && (delegates(model) || pathWriters(models, model).length > 0)) {
2303
+ tables[tables.length] = model.name.toLowerCase()
2304
+ }
2305
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
2306
+ const source = model.confers[position]
2307
+ const path = source?.principalPath
2308
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
2309
+ if (source?.when !== undefined) {
2310
+ conditionReach(source.when, (table) => {
2311
+ tables[tables.length] = table.toLowerCase()
2312
+ })
2313
+ }
2314
+ }
2315
+ }
2316
+ return tables
2317
+ }
2318
+
2319
+ /** A path column whose insert hands out the listed actions at the node it names: the bound its writer is held to. */
2320
+ export interface PathWriter {
2321
+ readonly path: SecondaryPath
2322
+ /** The path's own `writes` and those of every table that reads the same dimension through this table's column. */
2323
+ readonly actions: readonly string[]
2324
+ }
2325
+
2326
+ /**
2327
+ * The columns of `model` whose insert hands out actions through a secondary path: its own paths that hold actions, and
2328
+ * its paths that a table below follows through it (`'<link>.<column>'`) with actions of its own. Such a table is written
2329
+ * only through the handles, so no write sets the column past the bound.
2330
+ */
2331
+ export function pathWriters(models: Readonly<Record<string, TableModel>>, model: TableModel): readonly PathWriter[] {
2332
+ const writers: PathWriter[] = []
2333
+ const names = ownKeys(models)
2334
+ for (let index = 0; index < model.readThrough.length; index++) {
2335
+ const path = model.readThrough[index]
2336
+ if (path === undefined || path.via !== undefined) continue
2337
+ const actions: string[] = []
2338
+ for (let position = 0; position < path.writes.length; position++) {
2339
+ const action = path.writes[position] ?? ''
2340
+ if (!includes(actions, action)) actions[actions.length] = action
2341
+ }
2342
+ for (let position = 0; position < names.length; position++) {
2343
+ const below = ownEntry(models, names[position] ?? '')
2344
+ for (let at = 0; below !== undefined && at < below.readThrough.length; at++) {
2345
+ const through = below.readThrough[at]
2346
+ if (through?.via?.table !== model.name || through.dimension !== path.dimension) continue
2347
+ for (let written = 0; written < through.writes.length; written++) {
2348
+ const action = through.writes[written] ?? ''
2349
+ if (!includes(actions, action)) actions[actions.length] = action
2350
+ }
2351
+ }
2352
+ }
2353
+ if (actions.length > 0) writers[writers.length] = freeze({ path, actions: freeze(actions) })
2354
+ }
2355
+ return freeze(writers)
2356
+ }
2357
+
2358
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
2359
+ for (let index = 0; index < chain.length; index++) {
2360
+ if (chain[index]?.dimension === dimension) return true
2361
+ }
2362
+ return false
2363
+ }
2364
+
2365
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
2366
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
2367
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
2368
+ return table.scope.key
2369
+ }
2370
+ for (let index = 0; index < table.chain.length; index++) {
2371
+ const link = table.chain[index]
2372
+ if (link?.dimension === dimension) {
2373
+ return link.column
2374
+ }
2375
+ }
2376
+ return undefined
2377
+ }
2378
+
2379
+ /**
2380
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
2381
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
2382
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
2383
+ * insert action bounds (`assign`).
2384
+ */
2385
+ function parseConfers(
2386
+ table: LinkedTable,
2387
+ input: unknown,
2388
+ relations: Readonly<Record<string, string>>,
2389
+ tables: (name: string) => ConditionTable | undefined,
2390
+ linked: (name: string) => LinkedTable | undefined,
2391
+ hops: HopRule,
2392
+ ): readonly RelationSource[] {
2393
+ if (input === undefined) {
2394
+ return freeze([])
2395
+ }
2396
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2397
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
2398
+ }
2399
+ if (table.view) {
2400
+ throw new PolicyError(
2401
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
2402
+ )
2403
+ }
2404
+ if (table.queue !== undefined) {
2405
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
2406
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
2407
+ }
2408
+ const declared = plainRecord(input, `${table.name}: confers`)
2409
+ const names = ownKeys(declared)
2410
+ const sources: RelationSource[] = []
2411
+ for (let index = 0; index < names.length; index++) {
2412
+ const relation = names[index] ?? ''
2413
+ const what = `${table.name}: confers.${relation}`
2414
+ const dimension = ownEntry(relations, relation)
2415
+ if (dimension === undefined) {
2416
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
2417
+ }
2418
+ const policy = plainRecord(ownEntry(declared, relation), what)
2419
+ onlyFields(policy, CONFERS_FIELDS, what)
2420
+ const column = (value: unknown, field: string): string => {
2421
+ if (!inSet(table.columns, value)) {
2422
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
2423
+ }
2424
+ return value
2425
+ }
2426
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
2427
+ const placed = nodeColumnOf(table, dimension)
2428
+ if (placed === undefined) {
2429
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
2430
+ }
2431
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
2432
+ if (!own && table.chain[0]?.column !== placed) {
2433
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
2434
+ throw new PolicyError(
2435
+ `${what}: ${dimension} is above ${table.name}'s own container, and a move of an ancestor rewrites ${placed}; a relation's node is the row's key or its own container or parent column`,
2436
+ )
2437
+ }
2438
+ const nodeInput = ownEntry(policy, 'node')
2439
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
2440
+ if (node !== placed) {
2441
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
2442
+ }
2443
+ const expiresInput = ownEntry(policy, 'expires')
2444
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
2445
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
2446
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
2447
+ }
2448
+ const whenInput = ownEntry(policy, 'when')
2449
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
2450
+ const fixed: string[] = [principal]
2451
+ if (expires !== undefined) fixed[fixed.length] = expires
2452
+ const read = when === undefined ? [] : conditionColumns(when)
2453
+ for (let position = 0; position < read.length; position++) {
2454
+ fixed[fixed.length] = read[position] ?? ''
2455
+ }
2456
+ for (let position = 0; position < fixed.length; position++) {
2457
+ const name = fixed[position] ?? ''
2458
+ if (name === table.version) {
2459
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
2460
+ }
2461
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
2462
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
2463
+ }
2464
+ }
2465
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
2466
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
2467
+ }
2468
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
2469
+ const assign = parseAssign(table, policy, expires, what)
2470
+ if (principal === table.createdBy && principalPath !== undefined) {
2471
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
2472
+ }
2473
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
2474
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
2475
+ throw new PolicyError(
2476
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
2477
+ )
2478
+ }
2479
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
2480
+ }
2481
+ return freeze(sources)
2482
+ }
2483
+
2484
+ /**
2485
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
2486
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
2487
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
2488
+ */
2489
+ function parseSourceWhen(
2490
+ table: LinkedTable,
2491
+ input: unknown,
2492
+ tables: (name: string) => ConditionTable | undefined,
2493
+ linked: (name: string) => LinkedTable | undefined,
2494
+ hops: HopRule,
2495
+ what: string,
2496
+ ): ConditionModel {
2497
+ const condition = parseCondition(input, table, tables, what, hops)
2498
+ const visit = (node: ConditionModel): void => {
2499
+ if (node.kind === 'not') {
2500
+ visit(node.term)
2501
+ } else if (node.kind === 'some') {
2502
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2503
+ throw new PolicyError(
2504
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2505
+ )
2506
+ } else if (node.kind === 'test') {
2507
+ const hop = node.hops[0]
2508
+ if (node.hops.length > 1) {
2509
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2510
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2511
+ }
2512
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2513
+ } else {
2514
+ for (let index = 0; index < node.terms.length; index++) {
2515
+ const term = node.terms[index]
2516
+ if (term !== undefined) visit(term)
2517
+ }
2518
+ }
2519
+ }
2520
+ visit(condition)
2521
+ return condition
2522
+ }
2523
+
2524
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2525
+ function farColumn(
2526
+ table: LinkedTable,
2527
+ hop: ConditionHop,
2528
+ held: string,
2529
+ linked: (name: string) => LinkedTable | undefined,
2530
+ what: string,
2531
+ ): void {
2532
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2533
+ const target = linked(hop.table)
2534
+ if (target === undefined) {
2535
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2536
+ }
2537
+ if (target.view) {
2538
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2539
+ }
2540
+ if (target.queue !== undefined) {
2541
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2542
+ }
2543
+ const scope = target.scope
2544
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2545
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2546
+ throw new PolicyError(
2547
+ `${what}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; a relation's condition reads a row whose key the layer generates`,
2548
+ )
2549
+ }
2550
+ if (scope.mode !== 'reference') {
2551
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2552
+ }
2553
+ if (held === target.version) {
2554
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2555
+ }
2556
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2557
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2558
+ }
2559
+ if (chainColumn(target, held)) {
2560
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2561
+ }
2562
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2563
+ }
2564
+
2565
+ /**
2566
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2567
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2568
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2569
+ */
2570
+ function parsePrincipal(
2571
+ table: LinkedTable,
2572
+ input: unknown,
2573
+ linked: (name: string) => LinkedTable | undefined,
2574
+ what: string,
2575
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2576
+ const field = `${what}.principal`
2577
+ if (typeof input !== 'string') {
2578
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2579
+ }
2580
+ const segments = splitPath(input)
2581
+ if (segments.length === 1) {
2582
+ if (!inSet(table.columns, input)) {
2583
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2584
+ }
2585
+ return { column: input, path: undefined }
2586
+ }
2587
+ if (segments.length !== 2) {
2588
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2589
+ }
2590
+ const column = segments[0] ?? ''
2591
+ const held = segments[1] ?? ''
2592
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2593
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2594
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2595
+ throw new PolicyError(
2596
+ `${field}: ${table.name}.${column} is a key, a containment, a version or a file column, which the layer stamps or a move rewrites; a principal path starts at a foreign key no update writes`,
2597
+ )
2598
+ }
2599
+ const hop = singleForeignKey(table, column, field)
2600
+ const target = linked(hop.table)
2601
+ if (target === undefined) {
2602
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2603
+ }
2604
+ if (target.view) {
2605
+ throw new PolicyError(`${field}: ${hop.table} is a view, whose rows change with every write to the tables it reads; a table holds the principal`)
2606
+ }
2607
+ if (target.queue !== undefined) {
2608
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2609
+ }
2610
+ const scope = target.scope
2611
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2612
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2613
+ }
2614
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2615
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2616
+ throw new PolicyError(
2617
+ `${field}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; the principal is held by a table whose key the layer generates`,
2618
+ )
2619
+ }
2620
+ if (scope.key !== hop.key) {
2621
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2622
+ }
2623
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2624
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2625
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2626
+ if (!inSet(target.columns, held)) {
2627
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2628
+ }
2629
+ if (held === target.version) {
2630
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2631
+ }
2632
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2633
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2634
+ }
2635
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2636
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2637
+ }
2638
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2639
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2640
+ }
2641
+
2642
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2643
+ for (let index = 0; index < table.chain.length; index++) {
2644
+ if (table.chain[index]?.column === column) return true
2645
+ }
2646
+ return false
2647
+ }
2648
+
2649
+ /**
2650
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2651
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2652
+ * the referenced table change whom every row names.
2653
+ */
2654
+ function refuseReferencing(
2655
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2656
+ column: string,
2657
+ field: string,
2658
+ role: string,
2659
+ hop: { readonly table: string; readonly key: string } | undefined,
2660
+ ): void {
2661
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2662
+ const key = table.foreignKeys[index]
2663
+ if (key === undefined) continue
2664
+ for (let position = 0; position < key.columns.length; position++) {
2665
+ if (key.columns[position] !== column) continue
2666
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2667
+ throw new PolicyError(
2668
+ `${field}: ${table.name}.${column} ${role} and is a column of a foreign key to ${key.table}, which an update there may rewrite; it references nothing else`,
2669
+ )
2670
+ }
2671
+ }
2672
+ }
2673
+
2674
+ function parseAssign(
2675
+ table: LinkedTable,
2676
+ policy: Readonly<Record<string, unknown>>,
2677
+ expires: string | undefined,
2678
+ what: string,
2679
+ ): RelationSource['assign'] {
2680
+ const input = ownEntry(policy, 'assign')
2681
+ if (table.actions.insert.length === 0) {
2682
+ if (input !== undefined) {
2683
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2684
+ }
2685
+ return undefined
2686
+ }
2687
+ if (input === undefined) {
2688
+ throw new PolicyError(
2689
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2690
+ )
2691
+ }
2692
+ const assign = plainRecord(input, `${what}.assign`)
2693
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2694
+ const maxDays = ownEntry(assign, 'maxDays')
2695
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2696
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2697
+ }
2698
+ if (maxDays !== undefined && expires === undefined) {
2699
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2700
+ }
2701
+ const self = ownEntry(assign, 'self')
2702
+ if (self !== undefined && self !== true) {
2703
+ throw new PolicyError(`${what}.assign.self takes true`)
2704
+ }
2705
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2706
+ }
2707
+
2708
+ /** The own columns a condition reads. */
2709
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2710
+ if (condition.kind === 'test') {
2711
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2712
+ }
2713
+ if (condition.kind === 'not') {
2714
+ return conditionColumns(condition.term)
2715
+ }
2716
+ if (condition.kind === 'some') {
2717
+ return [condition.hops[0]?.column ?? condition.key]
2718
+ }
2719
+ const columns: string[] = []
2720
+ for (let index = 0; index < condition.terms.length; index++) {
2721
+ const term = condition.terms[index]
2722
+ const inner = term === undefined ? [] : conditionColumns(term)
2723
+ for (let position = 0; position < inner.length; position++) {
2724
+ columns[columns.length] = inner[position] ?? ''
2725
+ }
2726
+ }
2727
+ return columns
2728
+ }
2729
+
2730
+ /** A table's scope with nothing left to derive, and its containment chain. */
2731
+ interface Resolved {
2732
+ readonly scope: ScopeModel
2733
+ readonly chain: readonly Container[]
2734
+ }
2735
+
2736
+ function resolveChain(
2737
+ table: ParsedTable,
2738
+ byName: Readonly<Record<string, ParsedTable>>,
2739
+ owners: Readonly<Record<string, ParsedTable>>,
2740
+ containment: Containment,
2741
+ chainOf: (table: ParsedTable) => readonly Container[],
2742
+ ): Resolved {
2743
+ /**
2744
+ * The links above `dimension`: the chain of the table that owns it, whose ancestors' columns a contained row carries
2745
+ * under the same names; past a dimension no table owns, the vocabulary's ancestry on the `<dimension>_id` convention.
2746
+ */
2747
+ const above = (dimension: string): readonly Container[] => {
2748
+ const owner = ownEntry(owners, dimension)
2749
+ if (owner !== undefined) {
2750
+ return chainOf(owner)
2751
+ }
2752
+ const container = ownEntry(containment, dimension)?.container
2753
+ return container === undefined ? freeze([]) : prepend({ dimension: container, column: `${container}_id` }, above(container))
2754
+ }
2755
+ const scope = table.scope
2756
+ if (scope.mode === 'dimension') {
2757
+ const container = scope.container
2758
+ if (container === undefined) {
2759
+ return { scope, chain: freeze([]) }
2760
+ }
2761
+ const owner = ownEntry(owners, container.dimension)
2762
+ if (owner !== undefined) {
2763
+ requireReference(table, container, owner, (column) => `scope.in: { column: '${column}' }`)
2764
+ requireCoveringKey(table, container, owner, chainOf(owner))
2765
+ }
2766
+ return { scope, chain: prepend(container, above(container.dimension)) }
2767
+ }
2768
+ if (scope.mode !== 'child') {
2769
+ return { scope, chain: freeze([]) }
2770
+ }
2771
+ const parent = ownEntry(byName, scope.parent)
2772
+ if (parent === undefined || parent.scope.mode !== 'dimension') {
2773
+ throw new PolicyError(`${table.name}: the parent ${scope.parent} must be a dimension table`)
2774
+ }
2775
+ const parentChain = chainOf(parent)
2776
+ const expected: string[] = []
2777
+ for (let index = 0; index < parentChain.length; index++) {
2778
+ expected[index] = parentChain[index]?.column ?? ''
2779
+ }
2780
+ const dimension = parent.scope.dimension
2781
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2782
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2783
+ if (table.view) {
2784
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2785
+ for (let index = 0; index < inherit.length; index++) {
2786
+ if (!includes(expected, inherit[index])) {
2787
+ throw new PolicyError(
2788
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2789
+ )
2790
+ }
2791
+ }
2792
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2793
+ }
2794
+ const inherit = scope.inherit ?? freeze(expected)
2795
+ const inherited = nameSet(inherit)
2796
+ let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
2797
+ for (let index = 0; index < expected.length; index++) {
2798
+ matches = matches && inSet(inherited, expected[index])
2799
+ }
2800
+ if (!matches) {
2801
+ throw new PolicyError(
2802
+ `${table.name}: must inherit exactly the containment columns of ${scope.parent} (${
2803
+ expected.join(', ') || 'none'
2804
+ }), so a composite foreign key keeps it in scope`,
2805
+ )
2806
+ }
2807
+ requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
2808
+ requireCoveringKey(table, link, parent, parentChain)
2809
+ return {
2810
+ scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }),
2811
+ chain: prepend(link, parentChain),
2812
+ }
2813
+ }
2814
+
2815
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2816
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2817
+ const found: string[] = []
2818
+ for (let index = 0; index < names.length; index++) {
2819
+ const name = names[index] ?? ''
2820
+ if (inSet(table.columns, name)) found[found.length] = name
2821
+ }
2822
+ return found
2823
+ }
2824
+
2825
+ /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
2826
+ function references(table: ParsedTable, column: string, target: string, key: string): boolean {
2827
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2828
+ const foreignKey = table.foreignKeys[index]
2829
+ if (foreignKey === undefined || foreignKey.table !== target) {
2830
+ continue
2831
+ }
2832
+ for (let position = 0; position < foreignKey.columns.length; position++) {
2833
+ if (foreignKey.columns[position] === column && foreignKey.references[position] === key) {
2834
+ return true
2835
+ }
2836
+ }
2837
+ }
2838
+ return false
1163
2839
  }
1164
2840
 
1165
2841
  /**
@@ -1225,6 +2901,53 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1225
2901
  )
1226
2902
  }
1227
2903
 
2904
+ /**
2905
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
2906
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
2907
+ */
2908
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
2909
+ const pairs: [string, string][] = [[column, key]]
2910
+ for (let index = 0; index < chain.length; index++) {
2911
+ const link = chain[index]
2912
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
2913
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
2914
+ }
2915
+ return pairs
2916
+ }
2917
+
2918
+ /**
2919
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
2920
+ * the key, and a row written raw with it null would reach another tenant's row.
2921
+ */
2922
+ function requireNotNullAncestors(
2923
+ what: string,
2924
+ table: { readonly name: string; readonly notNull: NameSet },
2925
+ pairs: readonly (readonly [string, string])[],
2926
+ ): void {
2927
+ const nullable: string[] = []
2928
+ for (let index = 1; index < pairs.length; index++) {
2929
+ const column = pairs[index]?.[0] ?? ''
2930
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
2931
+ }
2932
+ if (nullable.length > 0) {
2933
+ throw new PolicyError(
2934
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
2935
+ nullable.join(', ')
2936
+ } not null and run fabrika db codegen`,
2937
+ )
2938
+ }
2939
+ }
2940
+
2941
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
2942
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
2943
+ for (let index = 0; index < foreignKeys.length; index++) {
2944
+ const foreignKey = foreignKeys[index]
2945
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
2946
+ return true
2947
+ }
2948
+ }
2949
+ return false
2950
+ }
1228
2951
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1229
2952
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1230
2953
  for (let index = 0; index < pairs.length; index++) {
@@ -1277,12 +3000,21 @@ type ScopeOf<P, T> = PolicyOf<P, T> extends { readonly scope: infer S } ? S : ne
1277
3000
 
1278
3001
  export type Operation = 'read' | 'insert' | 'update' | 'delete'
1279
3002
 
1280
- /** The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none. */
3003
+ /**
3004
+ * The action, or the union of the actions, of operation `Op` on table `T`; `never` when the policy names none, and for
3005
+ * the read of a table read with `'any'` (`ReadsAny`).
3006
+ */
1281
3007
  export type ActionOf<P, T, Op extends Operation> = PolicyOf<P, T> extends { readonly actions: infer Acts }
1282
- ? Acts extends { readonly [K in Op]: infer A } ? A extends string ? A : A extends readonly (infer L extends string)[] ? L : never
3008
+ ? Acts extends { readonly [K in Op]: infer A } ? A extends typeof READ_ANY ? never
3009
+ : A extends string ? A
3010
+ : A extends readonly (infer L extends string)[] ? L
3011
+ : never
1283
3012
  : never
1284
3013
  : never
1285
3014
 
3015
+ /** Whether table `T` is read with `'any'`: by every `app` endpoint, job and webhook, whatever its action. */
3016
+ export type ReadsAny<P, T> = PolicyOf<P, T> extends { readonly actions: { readonly read: typeof READ_ANY } } ? true : false
3017
+
1286
3018
  export type DimensionOf<P, T> = ScopeOf<P, T> extends { readonly dimension: infer D extends string } ? D : never
1287
3019
  export type ContainerOf<P, T> = ScopeOf<P, T> extends { readonly in: { readonly dimension: infer D extends string } } ? D : never
1288
3020
  /** The dimension that lists and inserts of T are scoped by: its container, or for a top-level table its own. */