@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.50

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 (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. package/types/src/vocabulary-tables.d.ts +169 -22
package/src/store.ts CHANGED
@@ -1,6 +1,36 @@
1
1
  import { uuidv7 } from '@fabrika/platform'
2
- import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
2
+ import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
3
3
  import { admissions } from './admissions'
4
+ import {
5
+ accessReach,
6
+ type AccessRelation,
7
+ activeRow,
8
+ conditioned,
9
+ conditionedAny,
10
+ everyPath,
11
+ gateTerms,
12
+ heldThrough,
13
+ holdsBesides,
14
+ isIn,
15
+ knownRelation,
16
+ type LayerRelation,
17
+ type MemberReveals,
18
+ memberTerms,
19
+ namesPrincipal,
20
+ noPath,
21
+ type PathRule,
22
+ pathTerms,
23
+ refScope,
24
+ relationCondition,
25
+ relationGate,
26
+ relationSource,
27
+ type RelationSources,
28
+ relationTerms,
29
+ revealedNodes,
30
+ type SplitReach,
31
+ throughPath,
32
+ viewScope,
33
+ } from './authority'
4
34
  import {
5
35
  defineValue,
6
36
  freeze,
@@ -25,21 +55,28 @@ import {
25
55
  type AppGrant,
26
56
  type CapabilityAuthority,
27
57
  type CapabilityGrant,
58
+ type ContainerGrant,
28
59
  describeGrant,
29
60
  MAX_WITHIN_VALUES,
30
61
  type Ref,
31
62
  type RefGrant,
63
+ type RelationHold,
32
64
  type Within,
33
65
  type WithinGrant,
34
66
  } from './capability'
67
+ import { conditionNode, subquery } from './condition-nodes'
68
+ import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
35
69
  import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
36
70
  import {
71
+ type ComparableColumn,
72
+ comparableColumnOf,
37
73
  type Compare,
38
74
  type Condition,
39
75
  type Contains,
40
76
  finishSelect,
41
77
  isPrimitive,
42
78
  type JoinShape,
79
+ type JoinState,
43
80
  type NoColumns,
44
81
  type Primitive,
45
82
  type ScopedSelect,
@@ -51,9 +88,10 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
51
88
  import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
52
89
  import { fileReference } from './file-references'
53
90
  import { webhookTables } from './framework-tables'
54
- import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
91
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
55
92
  import { fencedTransaction, jobLeases } from './job-leases'
56
93
  import { jobWakes, leaseProjection } from './job-wakes'
94
+ import { jsonInput } from './json'
57
95
  import { linksPredicate, type LinkValue, linkValues } from './links'
58
96
  import {
59
97
  acknowledgement,
@@ -74,7 +112,10 @@ import {
74
112
  scopedWhere,
75
113
  selectNode,
76
114
  updateNode,
115
+ valueList,
116
+ valuesNode,
77
117
  } from './nodes'
118
+ import { notifications } from './notifications'
78
119
  import { dataAccess } from './orm'
79
120
  import {
80
121
  type Acknowledgement,
@@ -82,28 +123,41 @@ import {
82
123
  type ChildTableName,
83
124
  type Container,
84
125
  type ContainerOf,
126
+ delegates,
85
127
  type DimensionOf,
86
128
  type DimensionTableName,
87
129
  includes,
88
130
  type InsertValues,
89
131
  type JoinableChildren,
90
132
  type ListDimensionOf,
133
+ type MemberRevealModel,
91
134
  modelOf,
92
135
  type MoveAcknowledgement,
93
136
  namesAction,
137
+ nodeColumnOf,
94
138
  type Operation,
95
139
  type ParentOf,
140
+ type PathWriter,
141
+ pathWriters,
96
142
  type PolicyRow,
143
+ type ReadReach,
144
+ type RevealModel,
145
+ type SecondaryPath,
97
146
  type TableModel,
98
147
  type TableModels,
99
148
  tableModels,
100
149
  type Tables,
150
+ updatableBy,
151
+ updatableByAny,
101
152
  updateActions,
102
153
  type UpdateValues,
103
154
  type VersionArguments,
104
155
  visibleFor,
156
+ visibleThrough,
105
157
  } from './policy'
158
+ import { pushSubscriptions } from './push-subscriptions'
106
159
  import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
160
+ import { requestReceipts } from './request-receipts'
107
161
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
108
162
  import { storedFiles, storedFilesMetadata } from './stored-files'
109
163
  import { type TablePolicies, tablePolicies } from './tables'
@@ -136,6 +190,36 @@ export interface TableContext {
136
190
  /** The model of each child a select may join, by its table name. */
137
191
  readonly children: Readonly<Record<string, TableModel>>
138
192
  readonly connection: Connection
193
+ /** Every relation of the layer with its source table: what a relation term of any table reads. */
194
+ readonly relations: RelationSources
195
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
196
+ readonly members: MemberReveals
197
+ /** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
198
+ readonly subqueries: Readonly<Record<string, readonly string[]>>
199
+ /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
200
+ readonly through: ViewParent | undefined
201
+ /** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
202
+ readonly writers: readonly PathBound[]
203
+ }
204
+
205
+ /** A path column an insert writes under its bound, and the table that owns the dimension it names. */
206
+ export interface PathBound extends PathWriter {
207
+ readonly owner: TableModel
208
+ }
209
+
210
+ /** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
211
+ export interface ViewParent extends ViewParentLink {
212
+ readonly context: TableContext
213
+ }
214
+
215
+ /** A child view's access views, as the guard admits them on its statements: its key in each view's row column. */
216
+ function viewAccessLinks(model: TableModel, key: string): readonly ViewAccessLink[] {
217
+ const links: ViewAccessLink[] = []
218
+ for (let index = 0; index < model.access.length; index++) {
219
+ const access = model.access[index]
220
+ if (access !== undefined) links[links.length] = freeze({ key, view: access.view, row: access.row })
221
+ }
222
+ return freeze(links)
139
223
  }
140
224
 
141
225
  /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
@@ -145,7 +229,7 @@ export function dialectOf(context: TableContext): SqlDialect {
145
229
 
146
230
  /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
147
231
  export function rowColumnsOf(model: TableModel): RowColumns {
148
- return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans }
232
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json }
149
233
  }
150
234
 
151
235
  /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
@@ -296,13 +380,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
296
380
  return grant
297
381
  }
298
382
 
299
- /** The chain links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. */
383
+ /**
384
+ * The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
385
+ * table's own dimension counts, so its containers lie above a `Within` of it.
386
+ */
300
387
  function linksAbove(model: TableModel, dimension: string): readonly Container[] {
301
- for (let index = 0; index < model.chain.length; index++) {
302
- if (model.chain[index]?.dimension === dimension) {
388
+ const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
389
+ for (let index = 0; index < links.length; index++) {
390
+ if (links[index]?.dimension === dimension) {
303
391
  const above: Container[] = []
304
- for (let position = index + 1; position < model.chain.length; position++) {
305
- const link = model.chain[position]
392
+ for (let position = index + 1; position < links.length; position++) {
393
+ const link = links[position]
306
394
  if (link !== undefined) {
307
395
  above[above.length] = link
308
396
  }
@@ -380,6 +468,9 @@ function withinCount(grant: WithinGrant): number {
380
468
  for (let index = 0; index < grant.contained.length; index++) {
381
469
  count += grant.contained[index]?.values.length ?? 0
382
470
  }
471
+ for (let index = 0; index < grant.revealing.length; index++) {
472
+ count += grant.revealing[index]?.values.length ?? 0
473
+ }
383
474
  return count
384
475
  }
385
476
 
@@ -388,9 +479,11 @@ function withinCount(grant: WithinGrant): number {
388
479
  * the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
389
480
  * answers `[]` without a query.
390
481
  */
391
- function withinPredicate(model: TableModel, column: string, grant: WithinGrant): OperationNode | undefined {
482
+ function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
483
+ const model = context.model
484
+ const now = new Date()
392
485
  if (grant.values === 'all') {
393
- return everything()
486
+ return conditioned(model, grant.action, 'all', now)
394
487
  }
395
488
  const above = linksAbove(model, grant.dimension)
396
489
  const predicates: OperationNode[] = []
@@ -424,7 +517,80 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
424
517
  if (count > MAX_WITHIN_VALUES) {
425
518
  throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
426
519
  }
427
- return predicates.length === 0 ? undefined : anyOf(predicates)
520
+ addRelationTerms(context, grant, operation === 'read', predicates, now)
521
+ if (operation === 'read') addMemberTerms(context, grant, predicates, now)
522
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
523
+ }
524
+
525
+ /** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
526
+ function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
527
+ const terms = memberTerms(context.members, context.model, grant, now)
528
+ for (let index = 0; index < terms.length; index++) {
529
+ const term = terms[index]
530
+ if (term !== undefined) predicates[predicates.length] = term
531
+ }
532
+ }
533
+
534
+ /** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
535
+ function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
536
+ for (let index = 0; index < grant.relations.length; index++) {
537
+ const hold = grant.relations[index]
538
+ if (hold === undefined) continue
539
+ const terms = relationTerms(
540
+ context.relations,
541
+ context.model,
542
+ hold,
543
+ grant.principal,
544
+ grant.action,
545
+ now,
546
+ reads ? everyPath : noPath,
547
+ )
548
+ for (let position = 0; position < terms.length; position++) {
549
+ const term = terms[position]
550
+ if (term !== undefined) predicates[predicates.length] = term
551
+ }
552
+ }
553
+ }
554
+
555
+ /**
556
+ * The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
557
+ * `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
558
+ * (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
559
+ * Within's lies at no node the column holds, so it reaches no row here.
560
+ */
561
+ function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
562
+ const model = context.model
563
+ const now = new Date()
564
+ if (grant.values === 'all') {
565
+ return conditioned(model, grant.action, 'all', now)
566
+ }
567
+ if (withinCount(grant) > MAX_WITHIN_VALUES) {
568
+ throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
569
+ }
570
+ const predicates: OperationNode[] = []
571
+ for (let index = 0; index < paths.length; index++) {
572
+ const path = paths[index]
573
+ if (path === undefined) continue
574
+ if (grant.values.length > 0) {
575
+ const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
576
+ if (own !== undefined) predicates[predicates.length] = own
577
+ }
578
+ for (let position = 0; position < grant.containers.length; position++) {
579
+ const container = grant.containers[position]
580
+ if (container === undefined || container.values.length === 0) continue
581
+ const above = throughPath(model.name, path, container.dimension, valueList(container.values))
582
+ if (above === undefined) {
583
+ throw new CapabilityError(
584
+ 'unenforceable',
585
+ `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
586
+ )
587
+ }
588
+ predicates[predicates.length] = above
589
+ }
590
+ }
591
+ addRelationTerms(context, grant, true, predicates, now)
592
+ addMemberTerms(context, grant, predicates, now)
593
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
428
594
  }
429
595
 
430
596
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
@@ -440,23 +606,126 @@ export function selfLinks(model: TableModel): readonly Container[] {
440
606
  return links
441
607
  }
442
608
 
443
- /** This object, over the whole chain the Ref carries. */
444
- export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
609
+ /** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
610
+ export function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode {
445
611
  const scope = dimensionScope(context.model)
446
612
  const grant = refGrant(context, capability, scope.dimension, operation)
447
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
613
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
448
614
  }
449
615
 
450
616
  /** Rows of a dimension table within the scope values of its list dimension. */
451
617
  export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
452
618
  const scope = dimensionScope(context.model)
453
619
  const grant = withinGrant(context, capability, listDimension(scope), operation)
454
- return withinPredicate(context.model, scope.container?.column ?? scope.key, grant)
620
+ return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
621
+ }
622
+
623
+ /**
624
+ * Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
625
+ * of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
626
+ */
627
+ export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
628
+ const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
629
+ const through = context.through
630
+ if (through !== undefined) {
631
+ const parent = through.context
632
+ const now = new Date()
633
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
634
+ const reached = narrowed.length === 0
635
+ ? refScope(parent, parent.model, selfLinks(parent.model), grant, now)
636
+ : splitRefReach(context.model, parent, grant, narrowed, now)
637
+ return viewScope(context.model, through, grant.action, reached, now, row)
638
+ }
639
+ return refScope(context, context.model, context.model.chain, grant, new Date(), row)
640
+ }
641
+
642
+ /** Of `holds`, the relations a child view's `relationWhen` narrows for `action`: each reads the parent through a part of its own. */
643
+ function viewNarrowed(view: TableModel, holds: readonly RelationHold[], action: string): readonly string[] {
644
+ const narrowed: string[] = []
645
+ for (let index = 0; index < holds.length; index++) {
646
+ const relation = holds[index]?.relation ?? ''
647
+ if (relationCondition(view, relation, action) !== undefined && !includes(narrowed, relation)) narrowed[narrowed.length] = relation
648
+ }
649
+ return narrowed
650
+ }
651
+
652
+ /**
653
+ * A Ref's reach of a view's parent, split by the relations the view narrows: the chain with the terms of its other
654
+ * relations, member reveals and paths, and the chain with each narrowed relation's own terms. A part that reaches no
655
+ * parent row adds nothing; none left is unenforceable, never unconditioned.
656
+ */
657
+ function splitRefReach(view: TableModel, parent: TableContext, grant: RefGrant, narrowed: readonly string[], now: Date): SplitReach {
658
+ const model = parent.model
659
+ const chain = linksPredicate(model.name, linkValues(model.name, selfLinks(model), grant))
660
+ const paths = heldThrough(grant.action)
661
+ const others = holdsBesides(grant.relations, narrowed)
662
+ const rest: RefGrant = { ...grant, relations: others }
663
+ const restTerms = others.length === 0 && rest.revealing.length === 0 && rest.paths.length === 0 ? [] : gateTerms(parent, model, rest, now, paths)
664
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
665
+ for (let index = 0; index < grant.relations.length; index++) {
666
+ const hold = grant.relations[index]
667
+ const condition = hold === undefined || !includes(narrowed, hold.relation) ? undefined : relationCondition(view, hold.relation, grant.action)
668
+ const terms = hold === undefined || condition === undefined
669
+ ? []
670
+ : relationTerms(parent.relations, model, hold, grant.principal, grant.action, now, paths)
671
+ if (condition !== undefined && terms.length > 0) relations[relations.length] = { reached: allOf([chain, anyOf(terms)]), condition }
672
+ }
673
+ if (restTerms.length === 0 && relations.length === 0) {
674
+ throw new CapabilityError(
675
+ 'unenforceable',
676
+ `the Ref of ${grant.dimension} is held through relations, member reveals or secondary paths, none of which reaches a row of ${model.name} for ${grant.action}`,
677
+ )
678
+ }
679
+ return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
455
680
  }
456
681
 
457
- /** Rows of a child table that belong to the parent object the Ref names, over the whole chain. */
458
- export function parentPredicate(context: TableContext, grant: RefGrant): OperationNode {
459
- return linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
682
+ /**
683
+ * A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
684
+ * those whose parent row exists. A relation the view narrows (`relationWhen`) reaches the parent through a part of its
685
+ * own, ANDed with the view's condition. The view's own access views list rows beside them. Undefined where nothing is
686
+ * reached: the empty `Within`.
687
+ */
688
+ function throughParent(
689
+ context: TableContext,
690
+ through: ViewParent,
691
+ grant: WithinGrant,
692
+ reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
693
+ ): OperationNode | undefined {
694
+ const now = new Date()
695
+ if (grant.values === 'all') {
696
+ return viewScope(context.model, through, grant.action, 'all', now)
697
+ }
698
+ const own: OperationNode[] = []
699
+ for (let index = 0; index < grant.relations.length; index++) {
700
+ const hold = grant.relations[index]
701
+ const terms = hold === undefined ? [] : accessReach(context.model, hold, grant.principal, grant.action, now)
702
+ for (let position = 0; position < terms.length; position++) {
703
+ const term = terms[position]
704
+ if (term !== undefined) own[own.length] = term
705
+ }
706
+ }
707
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
708
+ if (narrowed.length === 0) {
709
+ const reached = reach(through.context, grant)
710
+ return reached === undefined && own.length === 0 ? undefined : viewScope(context.model, through, grant.action, reached, now, undefined, own)
711
+ }
712
+ const rest = reach(through.context, { ...grant, relations: holdsBesides(grant.relations, narrowed) })
713
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
714
+ for (let index = 0; index < grant.relations.length; index++) {
715
+ const hold = grant.relations[index]
716
+ const condition = hold === undefined || !includes(narrowed, hold.relation)
717
+ ? undefined
718
+ : relationCondition(context.model, hold.relation, grant.action)
719
+ const alone: WithinGrant | undefined = hold === undefined
720
+ ? undefined
721
+ : { ...grant, values: [], containers: [], contained: [], revealing: [], relations: [hold] }
722
+ const reached = condition === undefined || alone === undefined ? undefined : reach(through.context, alone)
723
+ if (condition !== undefined && reached !== undefined) relations[relations.length] = { reached, condition }
724
+ }
725
+ if (rest === undefined && relations.length === 0 && own.length === 0) {
726
+ return undefined
727
+ }
728
+ return viewScope(context.model, through, grant.action, { rest, relations }, now, undefined, own)
460
729
  }
461
730
 
462
731
  export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
@@ -470,29 +739,38 @@ export function childListPredicate(context: TableContext, capability: unknown, o
470
739
  throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
471
740
  }
472
741
  checkGrant(context, grant, listDimension(scope.parent), operation)
473
- return withinPredicate(context.model, scope.parent.container?.column ?? scope.column, grant)
742
+ if (context.through !== undefined) {
743
+ const column = scope.parent.container?.column ?? scope.parent.key
744
+ return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
745
+ }
746
+ return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
474
747
  }
475
748
 
476
749
  /**
477
- * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
478
- * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
750
+ * Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
751
+ * chain or a secondary path; a child view through its parent's.
479
752
  */
480
- export function reachColumn(model: TableModel, dimension: string): string | undefined {
481
- if (model.scope.mode === 'dimension' && model.scope.container === undefined && model.scope.dimension === dimension) {
482
- return model.scope.key
483
- }
484
- for (let index = 0; index < model.chain.length; index++) {
485
- const link = model.chain[index]
486
- if (link?.dimension === dimension) {
487
- return link.column
753
+ export function reachedBy(context: TableContext, dimension: string): boolean {
754
+ const model = context.through?.context.model ?? context.model
755
+ return nodeColumnOf(model, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
756
+ }
757
+
758
+ /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
759
+ export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
760
+ const paths: SecondaryPath[] = []
761
+ for (let index = 0; index < model.readThrough.length; index++) {
762
+ const path = model.readThrough[index]
763
+ if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
764
+ paths[paths.length] = path
488
765
  }
489
766
  }
490
- return undefined
767
+ return paths
491
768
  }
492
769
 
493
770
  /**
494
771
  * Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
495
- * `org` through their stamped `org_id`, as under one of `project` through `project_id`.
772
+ * `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
773
+ * table reaches through a secondary path, through that path's column.
496
774
  */
497
775
  export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
498
776
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
@@ -501,14 +779,25 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
501
779
  throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
502
780
  }
503
781
  checkAction(context, 'read', grant.action)
504
- const column = reachColumn(context.model, grant.dimension)
505
- if (column === undefined) {
782
+ if (!reachedBy(context, grant.dimension)) {
506
783
  throw new CapabilityError(
507
784
  'out_of_reach',
508
- `a Within of ${grant.dimension} does not reach ${table}: its containment chain does not hold ${grant.dimension}`,
785
+ `a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
509
786
  )
510
787
  }
511
- return withinPredicate(context.model, column, grant)
788
+ if (context.through !== undefined) {
789
+ return throughParent(context, context.through, grant, withinReach)
790
+ }
791
+ return withinReach(context, grant)
792
+ }
793
+
794
+ /** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
795
+ function withinReach(context: TableContext, grant: WithinGrant): OperationNode | undefined {
796
+ const column = nodeColumnOf(context.model, grant.dimension)
797
+ if (column !== undefined) {
798
+ return withinPredicate(context, column, grant, 'read')
799
+ }
800
+ return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
512
801
  }
513
802
 
514
803
  /**
@@ -527,7 +816,8 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
527
816
  throw new CapabilityError('table_kind', `a scoped site writes no application table: ${statement} needs the capability of an app endpoint`)
528
817
  }
529
818
  const actions = model.actions[use]
530
- if (includes(actions, grant.action)) {
819
+ const held = grantActions(grant)
820
+ if (admitted(held, actions).length > 0) {
531
821
  return
532
822
  }
533
823
  const columnWrites: string[] = []
@@ -539,11 +829,39 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
539
829
  if (actions.length === 0 && columnWrites.length === 0) {
540
830
  throw new CapabilityError('undeclared_operation', `${statement}: its policy declares no ${use} action`)
541
831
  }
542
- if (!includes(columnWrites, grant.action)) {
832
+ if (admitted(held, columnWrites).length === 0) {
543
833
  const needs = actions.length === 0 ? [] : [`its ${use} action ${actions.join(' or ')}`]
544
834
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
545
- throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
835
+ throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${held.join(', ')}`)
836
+ }
837
+ }
838
+
839
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
840
+ export function grantActions(grant: CapabilityGrant): readonly string[] {
841
+ return grant.kind === 'app' ? grant.actions : [grant.action]
842
+ }
843
+
844
+ /** The actions of `held` that `allowed` lists: those that allow an operation, as any one of them does. */
845
+ function admitted(held: readonly string[], allowed: readonly string[]): string[] {
846
+ const found: string[] = []
847
+ for (let index = 0; index < held.length; index++) {
848
+ const action = held[index]
849
+ if (action !== undefined && includes(allowed, action)) {
850
+ found[found.length] = action
851
+ }
852
+ }
853
+ return found
854
+ }
855
+
856
+ /** The first of `actions` the table narrows with a `when`: a fragment, which renders column tests only, cannot hold it. */
857
+ function heldCondition(model: TableModel, actions: readonly string[]): string | undefined {
858
+ for (let index = 0; index < actions.length; index++) {
859
+ const action = actions[index]
860
+ if (action !== undefined && hasOwn(model.when, action)) {
861
+ return action
862
+ }
546
863
  }
864
+ return undefined
547
865
  }
548
866
 
549
867
  /**
@@ -565,8 +883,29 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
565
883
  if (use !== 'read') {
566
884
  checkWriteTarget(context, grant, use)
567
885
  }
886
+ // The fragment renders column tests only; a relation's, a member reveal's or a path's subquery, or an action's condition, would be left out.
887
+ const held = grant.kind !== 'app'
888
+ && (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
889
+ // An `'any'` read is unconditioned: a `when` keyed by the action narrows only its writes.
890
+ const readsEvery = grant.kind === 'app' && use === 'read' && readsAny(context, grant)
891
+ const conditionedBy = readsEvery ? undefined : heldCondition(model, grantActions(grant))
892
+ if (held || conditionedBy !== undefined) {
893
+ throw new CapabilityError(
894
+ 'unenforceable',
895
+ `ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${
896
+ conditionedBy ?? grantActions(grant).join(', ')
897
+ } on ${model.name}: read it through ctx.db`,
898
+ )
899
+ }
900
+ // Nor the subquery through the parent row, which alone places a child view's rows.
901
+ if (grant.kind !== 'app' && context.through !== undefined) {
902
+ throw new CapabilityError(
903
+ 'unenforceable',
904
+ `ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
905
+ )
906
+ }
568
907
  if (grant.kind === 'app') {
569
- if (use === 'read') {
908
+ if (use === 'read' && !readsEvery) {
570
909
  // The action is held as a global grant, so its scope is every row of a table it reaches.
571
910
  checkAppReach(context, grant)
572
911
  }
@@ -608,7 +947,7 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
608
947
  }
609
948
  return [tests]
610
949
  }
611
- const column = reachColumn(model, grant.dimension)
950
+ const column = nodeColumnOf(model, grant.dimension)
612
951
  if (column === undefined) {
613
952
  throw new CapabilityError(
614
953
  'out_of_reach',
@@ -690,32 +1029,63 @@ export function updatingRef(context: TableContext, capability: unknown, dimensio
690
1029
  */
691
1030
  export type AppReach = 'rows' | 'counts'
692
1031
 
693
- /** Refuses an `app` capability whose action does not reach `reach` of a dimension or child table. */
694
- function checkRecordReach(context: TableContext, grant: AppGrant, reach: AppReach): void {
1032
+ /**
1033
+ * The actions of an `app` capability that reach `reach` of a dimension or child table, at least one: its read action and
1034
+ * its `appRead`, and for `counts` its `appCount` too. Refuses a capability none of whose actions does.
1035
+ */
1036
+ function recordReach(context: TableContext, grant: AppGrant, reach: AppReach): readonly string[] {
695
1037
  const model = context.model
696
1038
  const { appRead, appCount } = model.actions
697
1039
  const read = model.actions.read.join(' or ')
698
- if (
699
- includes(model.actions.read, grant.action) || includes(appRead, grant.action) || (reach === 'counts' && includes(appCount, grant.action))
700
- ) {
701
- return
1040
+ const reaching = admitted(grant.actions, model.actions.read)
1041
+ const reads = admitted(grant.actions, appRead)
1042
+ for (let index = 0; index < reads.length; index++) {
1043
+ reaching[reaching.length] = reads[index] ?? ''
702
1044
  }
703
- if (includes(appCount, grant.action)) {
1045
+ const counts = admitted(grant.actions, appCount)
1046
+ if (reach === 'counts') {
1047
+ for (let index = 0; index < counts.length; index++) {
1048
+ reaching[reaching.length] = counts[index] ?? ''
1049
+ }
1050
+ }
1051
+ if (reaching.length > 0) {
1052
+ return reaching
1053
+ }
1054
+ const held = grant.actions.join(', ')
1055
+ if (counts.length > 0) {
704
1056
  throw new CapabilityError(
705
1057
  'wrong_action',
706
- `an app capability of ${grant.action} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
1058
+ `an app capability of ${held} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
707
1059
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
708
1060
  }`,
709
1061
  )
710
1062
  }
711
1063
  throw new CapabilityError(
712
1064
  'wrong_action',
713
- `an app capability of ${grant.action} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
1065
+ `an app capability of ${held} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
714
1066
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
715
1067
  } only`,
716
1068
  )
717
1069
  }
718
1070
 
1071
+ /** The actions of an `app` capability the application table names; refuses a capability none of whose actions it names. */
1072
+ function namedActions(model: TableModel, grant: AppGrant): readonly string[] {
1073
+ const named: string[] = []
1074
+ for (let index = 0; index < grant.actions.length; index++) {
1075
+ const action = grant.actions[index]
1076
+ if (action !== undefined && namesAction(model, action)) {
1077
+ named[named.length] = action
1078
+ }
1079
+ }
1080
+ if (named.length === 0) {
1081
+ throw new CapabilityError(
1082
+ 'wrong_action',
1083
+ `an app capability of ${grant.actions.join(', ')} does not reach ${model.name}: ${model.name} does not name the action`,
1084
+ )
1085
+ }
1086
+ return named
1087
+ }
1088
+
719
1089
  /**
720
1090
  * Refuses a table `ctx.db.app` does not list for the capability (`applicationTables` in `orm.ts`): it lists an
721
1091
  * application table under any action the table names, and the rows of a dimension or child table under its read
@@ -725,12 +1095,7 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
725
1095
  const model = context.model
726
1096
  const mode = model.scope.mode
727
1097
  if (mode === 'app') {
728
- if (!namesAction(model, grant.action)) {
729
- throw new CapabilityError(
730
- 'wrong_action',
731
- `an app capability of ${grant.action} does not reach ${model.name}: ${model.name} does not name the action`,
732
- )
733
- }
1098
+ namedActions(model, grant)
734
1099
  return
735
1100
  }
736
1101
  if (mode !== 'dimension' && mode !== 'child') {
@@ -739,14 +1104,20 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
739
1104
  `an app capability does not reach ${model.name}: ctx.db.app lists application, dimension and child tables only`,
740
1105
  )
741
1106
  }
742
- checkRecordReach(context, grant, 'rows')
1107
+ recordReach(context, grant, 'rows')
1108
+ }
1109
+
1110
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
1111
+ export interface AppRead {
1112
+ readonly predicate: OperationNode
1113
+ readonly reach: ReadReach
743
1114
  }
744
1115
 
745
1116
  /**
746
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
747
- * reaches `reach` (`checkRecordReach`).
1117
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
1118
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
748
1119
  */
749
- export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1120
+ export function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead {
750
1121
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
751
1122
  const model = context.model
752
1123
  if (grant.kind !== 'app') {
@@ -758,8 +1129,13 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
758
1129
  if (model.scope.mode !== 'dimension' && model.scope.mode !== 'child') {
759
1130
  throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
760
1131
  }
761
- checkRecordReach(context, grant, reach)
762
- return everything()
1132
+ const actions = recordReach(context, grant, reach)
1133
+ return { predicate: conditionedAny(model, actions, 'all', new Date()), reach: freeze({ actions, narrowed: true }) }
1134
+ }
1135
+
1136
+ /** `appRecordRead`'s rows. */
1137
+ export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1138
+ return appRecordRead(context, capability, reach).predicate
763
1139
  }
764
1140
 
765
1141
  /** An `app` capability addresses a row by its key, and writes, only in an application table. */
@@ -773,10 +1149,11 @@ function checkApplicationTable(context: TableContext, operation: Operation): voi
773
1149
  }
774
1150
 
775
1151
  /**
776
- * The capability of an `app` endpoint for `operation` on `table`: its action is that operation's. An application table
777
- * is written with it, and a dimension or child table read with it.
1152
+ * The capability of an `app` endpoint for `operation` on `table`, and its actions that are that operation's, at least
1153
+ * one. An application table is written with it, and a dimension or child
1154
+ * table read with it.
778
1155
  */
779
- function appGrant(context: TableContext, capability: unknown, operation: Operation): AppGrant {
1156
+ function appGrant(context: TableContext, capability: unknown, operation: Operation): AppOperation {
780
1157
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
781
1158
  const table = context.model.name
782
1159
  if (grant.kind !== 'app') {
@@ -785,22 +1162,82 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
785
1162
  if (operation !== 'read') {
786
1163
  checkApplicationTable(context, operation)
787
1164
  }
1165
+ if (operation === 'read' && readsAny(context, grant)) {
1166
+ return { grant, actions: grant.actions, narrowed: false }
1167
+ }
788
1168
  checkAppReach(context, grant)
789
- checkAction(context, operation, grant.action)
790
- return grant
1169
+ return { grant, actions: operationActions(context, operation, grant), narrowed: true }
1170
+ }
1171
+
1172
+ /**
1173
+ * An `app` capability and those of its actions that allow one operation: every one it holds for a read of a table read
1174
+ * with `'any'`, which no `when` narrows.
1175
+ */
1176
+ interface AppOperation extends ReadReach {
1177
+ readonly grant: AppGrant
1178
+ }
1179
+
1180
+ /** The actions of `grant` that allow `operation` on the table, at least one; `checkAction` over a set. */
1181
+ function operationActions(context: TableContext, operation: Operation, grant: AppGrant): readonly string[] {
1182
+ const actions = requiredActions(context, operation)
1183
+ const allowing = admitted(grant.actions, actions)
1184
+ if (allowing.length === 0) {
1185
+ throw new CapabilityError(
1186
+ 'wrong_action',
1187
+ `${operation} on ${context.model.name} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`,
1188
+ )
1189
+ }
1190
+ return allowing
1191
+ }
1192
+
1193
+ /**
1194
+ * Whether `grant` reads `context`'s table because it is read with `'any'`: every `app` grant but a public procedure's,
1195
+ * which is refused there. The read is unconditioned: a `when` of the grant's action narrows only its writes.
1196
+ */
1197
+ function readsAny(context: TableContext, grant: AppGrant): boolean {
1198
+ const model = context.model
1199
+ if (model.scope.mode !== 'app' || !model.actions.readAny) {
1200
+ return false
1201
+ }
1202
+ if (grant.public) {
1203
+ throw new CapabilityError(
1204
+ 'wrong_capability',
1205
+ `a public procedure does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1206
+ )
1207
+ }
1208
+ return true
1209
+ }
1210
+
1211
+ /**
1212
+ * The rows `held`, the read actions of an `app` capability, read of `context`'s table within `branch`: narrowed by their
1213
+ * conditions, any one admitting a row, unless the table is read with `'any'`.
1214
+ */
1215
+ function appReadPredicate(context: TableContext, held: AppOperation, branch: OperationNode | 'all'): OperationNode {
1216
+ if (context.model.scope.mode === 'app' && context.model.actions.readAny) {
1217
+ return branch === 'all' ? ValueNode.createImmediate(true) : branch
1218
+ }
1219
+ return conditionedAny(context.model, held.actions, branch, new Date())
1220
+ }
1221
+
1222
+ /**
1223
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
1224
+ * `'any'`, and the reach whose columns it answers.
1225
+ */
1226
+ export function appListRead(context: TableContext, capability: unknown): AppRead {
1227
+ const held = appGrant(context, capability, 'read')
1228
+ return { predicate: appReadPredicate(context, held, 'all'), reach: freeze({ actions: held.actions, narrowed: held.narrowed }) }
791
1229
  }
792
1230
 
793
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
1231
+ /** `appListRead`'s rows. */
794
1232
  export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
795
- appGrant(context, capability, 'read')
796
- return everything()
1233
+ return appListRead(context, capability).predicate
797
1234
  }
798
1235
 
799
1236
  /**
800
1237
  * Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
801
1238
  * or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
802
1239
  */
803
- export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
1240
+ export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
804
1241
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
805
1242
  const model = context.model
806
1243
  if (model.scope.mode !== 'app') {
@@ -809,6 +1246,12 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
809
1246
  if (grant.kind === 'app') {
810
1247
  throw new CapabilityError('wrong_capability', `a read of ${model.name} from a scoped site needs a Ref or a Within, got ${describeGrant(grant)}`)
811
1248
  }
1249
+ if (model.actions.readAny) {
1250
+ throw new CapabilityError(
1251
+ 'wrong_capability',
1252
+ `a scoped site does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1253
+ )
1254
+ }
812
1255
  const read = requiredActions(context, 'read')
813
1256
  if (!includes(read, grant.action)) {
814
1257
  throw new CapabilityError(
@@ -816,14 +1259,15 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
816
1259
  `a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
817
1260
  )
818
1261
  }
819
- return everything()
1262
+ return conditioned(model, grant.action, branch, new Date())
820
1263
  }
821
1264
 
822
1265
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
823
1266
  export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
824
1267
  checkApplicationTable(context, operation)
825
- appGrant(context, capability, operation)
826
- return appKeyPredicate(context.model, key)
1268
+ const held = appGrant(context, capability, operation)
1269
+ const row = appKeyPredicate(context.model, key)
1270
+ return operation === 'read' ? appReadPredicate(context, held, row) : conditionedAny(context.model, held.actions, row, new Date())
827
1271
  }
828
1272
 
829
1273
  /**
@@ -833,14 +1277,20 @@ export function appRowPredicate(context: TableContext, capability: unknown, key:
833
1277
  export function claimScope(
834
1278
  context: TableContext,
835
1279
  capability: unknown,
836
- ): { readonly grant: AppGrant | WithinGrant; readonly scope: OperationNode | undefined } {
1280
+ ): { readonly grant: AppGrant | WithinGrant; readonly action: string; readonly scope: OperationNode | undefined } {
837
1281
  const model = context.model
838
1282
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
839
1283
  if (model.queue === undefined) {
840
1284
  throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
841
1285
  }
842
1286
  if (grant.kind === 'app') {
843
- return { grant: appGrant(context, capability, 'update'), scope: everything() }
1287
+ const [action, ...more] = grant.actions
1288
+ // A claimed row's `row.ref` is finished under one action; only a job claims, and its `ctx.app(action)` holds one.
1289
+ if (more.length > 0) {
1290
+ throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a capability of one action, got one of ${grant.actions.join(', ')}`)
1291
+ }
1292
+ appGrant(context, capability, 'update')
1293
+ return { grant, action, scope: conditioned(model, action, 'all', new Date()) }
844
1294
  }
845
1295
  if (grant.kind !== 'within') {
846
1296
  throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
@@ -849,14 +1299,14 @@ export function claimScope(
849
1299
  throw new CapabilityError('table_kind', `${model.name} is an application table: claim it through ctx.db.app`)
850
1300
  }
851
1301
  checkAction(context, 'update', grant.action)
852
- const column = reachColumn(model, grant.dimension)
1302
+ const column = nodeColumnOf(model, grant.dimension)
853
1303
  if (column === undefined) {
854
1304
  throw new CapabilityError(
855
1305
  'out_of_reach',
856
1306
  `a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
857
1307
  )
858
1308
  }
859
- return { grant, scope: withinPredicate(model, column, grant) }
1309
+ return { grant, action: grant.action, scope: withinPredicate(context, column, grant, 'update') }
860
1310
  }
861
1311
 
862
1312
  /**
@@ -879,7 +1329,17 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
879
1329
  }
880
1330
  terms[terms.length] = equals(model.name, link.column, value)
881
1331
  }
882
- return allOf(terms)
1332
+ return conditioned(model, grant.action, allOf(terms), new Date())
1333
+ }
1334
+
1335
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
1336
+ export function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1337
+ return conditionedAny(model, actions, appKeyPredicate(model, key), new Date())
1338
+ }
1339
+
1340
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
1341
+ export function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1342
+ return model.actions.readAny ? appKeyPredicate(model, key) : appKeyScope(model, actions, key)
883
1343
  }
884
1344
 
885
1345
  /** The row of an application table `key` names. */
@@ -891,10 +1351,10 @@ export function appKeyPredicate(model: TableModel, key: unknown): OperationNode
891
1351
  }
892
1352
 
893
1353
  /**
894
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
895
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
1354
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
1355
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
896
1356
  */
897
- export function updatingApp(context: TableContext, capability: unknown): AppGrant {
1357
+ export function updatingApp(context: TableContext, capability: unknown): readonly string[] {
898
1358
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
899
1359
  const table = context.model.name
900
1360
  if (grant.kind !== 'app') {
@@ -905,12 +1365,63 @@ export function updatingApp(context: TableContext, capability: unknown): AppGran
905
1365
  if (actions.length === 0) {
906
1366
  throw new CapabilityError('undeclared_operation', `${table} allows no update; its policy declares no update action`)
907
1367
  }
908
- for (let index = 0; index < actions.length; index++) {
909
- if (actions[index] === grant.action) {
910
- return grant
1368
+ const updating = admitted(grant.actions, actions)
1369
+ if (updating.length === 0) {
1370
+ throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`)
1371
+ }
1372
+ return updating
1373
+ }
1374
+
1375
+ /**
1376
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
1377
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
1378
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
1379
+ */
1380
+ export function appUpdate(
1381
+ context: TableContext,
1382
+ capability: unknown,
1383
+ key: unknown,
1384
+ values: unknown,
1385
+ ): { readonly scope: OperationNode; readonly changes: Map<string, Primitive | null> } {
1386
+ const model = context.model
1387
+ const updating = updatingApp(context, capability)
1388
+ const writable = updatableByAny(model, updating)
1389
+ const changes = readValues(values, writable, 'update', model)
1390
+ // `readValues` took only columns of `writable`, so those of them `changes` sets are every column it sets.
1391
+ const columns = namesOf(writable)
1392
+ const written: string[] = []
1393
+ for (let index = 0; index < columns.length; index++) {
1394
+ const name = columns[index] ?? ''
1395
+ if (changes.has(name)) {
1396
+ written[written.length] = name
911
1397
  }
912
1398
  }
913
- throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.action}`)
1399
+ const covering: string[] = []
1400
+ for (let index = 0; index < updating.length; index++) {
1401
+ const action = updating[index]
1402
+ if (action !== undefined && writesEvery(updatableBy(model, action), written)) {
1403
+ covering[covering.length] = action
1404
+ }
1405
+ }
1406
+ if (covering.length === 0) {
1407
+ throw new CapabilityError(
1408
+ 'wrong_action',
1409
+ `no action of ${updating.join(', ')} updates every column of this update of ${model.name} (${
1410
+ written.join(', ')
1411
+ }): update the columns of each action apart`,
1412
+ )
1413
+ }
1414
+ return { scope: appKeyScope(model, covering, key), changes }
1415
+ }
1416
+
1417
+ /** Whether `columns` holds each of `written`. */
1418
+ function writesEvery(columns: NameSet, written: readonly string[]): boolean {
1419
+ for (let index = 0; index < written.length; index++) {
1420
+ if (!inSet(columns, written[index])) {
1421
+ return false
1422
+ }
1423
+ }
1424
+ return true
914
1425
  }
915
1426
 
916
1427
  export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
@@ -919,11 +1430,22 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
919
1430
  throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
920
1431
  }
921
1432
  const grant = refGrant(context, parent, scope.parent.dimension, operation)
922
- return allOf([equals(context.model.name, scope.key, key), parentPredicate(context, grant)])
1433
+ return parentPredicate(context, grant, key)
923
1434
  }
924
1435
 
925
1436
  export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
926
- return { root, table: context.model.name, joins: root === 'SelectQueryNode' ? context.joins : {}, scope }
1437
+ // Every store write reaches its statement through here: a view's rows are its tables', never written (ADR-0072).
1438
+ if (context.model.view && root !== 'SelectQueryNode') {
1439
+ throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
1440
+ }
1441
+ return {
1442
+ root,
1443
+ table: context.model.name,
1444
+ joins: root === 'SelectQueryNode' ? context.joins : {},
1445
+ scope,
1446
+ subqueries: context.subqueries,
1447
+ through: context.through,
1448
+ }
927
1449
  }
928
1450
 
929
1451
  /**
@@ -949,9 +1471,29 @@ export function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Ses
949
1471
  return fence === null ? session.transaction(work) : fencedTransaction(session, fence, work)
950
1472
  }
951
1473
 
952
- /** The action a capability holds, which its operation's checks already admitted. */
1474
+ /**
1475
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
1476
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
1477
+ */
953
1478
  export function heldAction(context: TableContext, capability: unknown): string {
954
- return runtimeOf(context.connection).capabilities.resolve(capability).action
1479
+ const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1480
+ if (grant.kind !== 'app') {
1481
+ return grant.action
1482
+ }
1483
+ const [action, ...more] = grant.actions
1484
+ if (more.length > 0) {
1485
+ throw new CapabilityError(
1486
+ 'wrong_capability',
1487
+ `this read takes a capability of one action, got one of ${grant.actions.join(', ')}: read through ctx.db.app`,
1488
+ )
1489
+ }
1490
+ return action
1491
+ }
1492
+
1493
+ /** The one action a capability holds, or `undefined` for an `anyOf` endpoint's `app` capability that holds several. */
1494
+ function soleAction(context: TableContext, capability: unknown): string | undefined {
1495
+ const actions = grantActions(runtimeOf(context.connection).capabilities.resolve(capability))
1496
+ return actions.length === 1 ? actions[0] : undefined
955
1497
  }
956
1498
 
957
1499
  function storeRunner(context: TableContext): Runner {
@@ -1003,6 +1545,10 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1003
1545
  copied.set(key, fileValue(model, key, value))
1004
1546
  continue
1005
1547
  }
1548
+ if (inSet(model.json, key)) {
1549
+ copied.set(key, value === null ? null : jsonInput(value, `${table}.${key}`))
1550
+ continue
1551
+ }
1006
1552
  if (value !== null && !isPrimitive(value)) {
1007
1553
  throw new QueryRefusedError('invalid_argument', `${table}.${key} takes a plain value (string, number, bigint, boolean, Date or null)`)
1008
1554
  }
@@ -1052,28 +1598,61 @@ async function selectRows<S>(
1052
1598
  context: TableContext,
1053
1599
  scope: OperationNode | undefined,
1054
1600
  state: SelectState,
1055
- action: string,
1601
+ action: string | undefined,
1056
1602
  visible: readonly string[] = context.model.visible,
1057
1603
  ): Promise<S[]> {
1058
1604
  const run = storeRunner(context)
1605
+ const now = new Date()
1606
+ const joins: JoinState[] = []
1059
1607
  for (let index = 0; index < state.joins.length; index++) {
1060
1608
  const join = state.joins[index]
1061
- if (join !== undefined && !includes(join.join.readActions, action)) {
1609
+ if (join === undefined) continue
1610
+ if (action === undefined) {
1611
+ throw new CapabilityError('wrong_capability', `joining ${join.join.shape.table} takes a capability of one action, whose condition narrows it`)
1612
+ }
1613
+ if (!includes(join.join.readActions, action)) {
1062
1614
  throw new CapabilityError(
1063
1615
  'wrong_action',
1064
1616
  `joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
1065
1617
  )
1066
1618
  }
1619
+ joins[joins.length] = heldJoin(context, join, action, now)
1067
1620
  }
1068
1621
  if (scope === undefined) {
1069
1622
  return []
1070
1623
  }
1071
1624
  const dialect = dialectOf(context)
1072
- const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
1625
+ const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
1073
1626
  const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
1074
1627
  return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
1075
1628
  }
1076
1629
 
1630
+ /**
1631
+ * `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
1632
+ * subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
1633
+ */
1634
+ function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
1635
+ const child = ownEntry(context.children, join.join.shape.table)
1636
+ if (child === undefined) {
1637
+ throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
1638
+ }
1639
+ const condition = ownEntry(child.when, action)
1640
+ if (condition === undefined) {
1641
+ return join
1642
+ }
1643
+ let reads = false
1644
+ conditionReach(condition, () => {
1645
+ reads = true
1646
+ })
1647
+ if (reads) {
1648
+ throw new CapabilityError(
1649
+ 'unenforceable',
1650
+ `joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
1651
+ )
1652
+ }
1653
+ return { ...join, condition: conditionNode(child.name, condition, now) }
1654
+ }
1655
+
1077
1656
  /** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
1078
1657
  function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1079
1658
  const own = rowColumnsOf(context.model)
@@ -1100,19 +1679,20 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1100
1679
  days: joined((columns) => columns.days),
1101
1680
  timestamps: joined((columns) => columns.timestamps),
1102
1681
  booleans: joined((columns) => columns.booleans),
1682
+ json: joined((columns) => columns.json),
1103
1683
  }
1104
1684
  }
1105
1685
 
1106
1686
  /**
1107
1687
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
1108
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
1688
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
1109
1689
  */
1110
1690
  export async function selectOne<O>(
1111
1691
  context: TableContext,
1112
1692
  run: Runner,
1113
1693
  scope: OperationNode,
1114
1694
  visible = context.model.visible,
1115
- action?: string,
1695
+ reach?: ReadReach,
1116
1696
  ): Promise<O> {
1117
1697
  const start = startSelect(context.shape)
1118
1698
  const state = finishSelect(start, start)
@@ -1124,8 +1704,8 @@ export async function selectOne<O>(
1124
1704
  if (row === undefined) {
1125
1705
  throw new NotFoundError(`${context.model.name} not found`)
1126
1706
  }
1127
- if (action !== undefined) {
1128
- await answerFiles(context.model, run.files, session, [row], action)
1707
+ if (reach !== undefined) {
1708
+ await answerFiles(context.model, run.files, session, [row], reach)
1129
1709
  }
1130
1710
  return row
1131
1711
  }
@@ -1195,29 +1775,55 @@ export function keyOf(model: TableModel): string {
1195
1775
  * Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
1196
1776
  * Ref minted before its object moved would insert into, or move rows into, the object's new container.
1197
1777
  */
1198
- async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
1778
+ async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<void> {
1779
+ if (!(await destinationHeld(transaction, context, grant, paths))) {
1780
+ throw context.destination === undefined
1781
+ ? new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
1782
+ : new NotFoundError(`${context.destination.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1783
+ }
1784
+ }
1785
+
1786
+ /** Whether the destination still lies where `grant`'s chain says and still holds it, locked `for share` (`lockDestination`). */
1787
+ async function destinationHeld(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
1199
1788
  const owner = context.destination
1200
1789
  if (owner === undefined) {
1201
- return
1790
+ // No table owns the destination, so a Ref held through relations or member reveals is checked on the rows that hold it.
1791
+ return grant.relations.length === 0 && grant.revealing.length === 0 ? true : await holdingRowLocked(transaction, context, grant)
1202
1792
  }
1203
- const scope = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1793
+ const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1794
+ // A Ref held through a relation or a member reveal inserts only while a row of it still holds the destination.
1795
+ const gate = relationGate(context, owner, grant, new Date(), paths ?? heldThrough(grant.action))
1796
+ const scope = gate === undefined ? chain : allOf([chain, gate])
1204
1797
  const node = lockNode(owner.name, keyOf(owner), scope)
1205
- const rows = await transaction.run(node, { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, lock: 'share' })
1206
- if (rows.length === 0) {
1207
- throw new NotFoundError(`${owner.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1208
- }
1798
+ const rows = await transaction.run(node, {
1799
+ root: 'SelectQueryNode',
1800
+ table: owner.name,
1801
+ joins: {},
1802
+ scope,
1803
+ lock: 'share',
1804
+ subqueries: context.subqueries,
1805
+ })
1806
+ return rows.length > 0
1209
1807
  }
1210
1808
 
1809
+ /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
1211
1810
  export async function insertRow<O>(
1212
1811
  context: TableContext,
1213
1812
  run: Runner,
1214
1813
  given: ReadonlyMap<string, Primitive | null>,
1215
- destination: RefGrant | undefined,
1814
+ prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
1216
1815
  ): Promise<O> {
1217
1816
  const values = boundValues(context, given)
1218
1817
  return run.write(async (transaction) => {
1219
- if (destination !== undefined) {
1220
- await lockDestination(transaction, context, destination)
1818
+ if (prepared?.destination !== undefined) {
1819
+ await lockDestination(transaction, context, prepared.destination)
1820
+ }
1821
+ const before = await narrowedHolds(transaction, context, prepared)
1822
+ if (prepared !== undefined) {
1823
+ await checkPrincipalAssign(transaction, context, prepared.writer, given)
1824
+ await checkRevealAssign(transaction, context, prepared.writer, given)
1825
+ await checkMemberRevealAssign(transaction, context, prepared.writer, given)
1826
+ await checkPathWriters(transaction, context, prepared.writer, given)
1221
1827
  }
1222
1828
  const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
1223
1829
  if (row === undefined) {
@@ -1225,6 +1831,8 @@ export async function insertRow<O>(
1225
1831
  }
1226
1832
  checkVersion(context, row)
1227
1833
  await referenceInserted(context, run, transaction, values)
1834
+ await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
1835
+ await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
1228
1836
  return row
1229
1837
  })
1230
1838
  }
@@ -1238,18 +1846,20 @@ export interface OnConflict {
1238
1846
  readonly mode: 'nothing' | 'update'
1239
1847
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
1240
1848
  readonly updates: ReadonlyMap<string, Primitive | null>
1849
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
1850
+ readonly actions: readonly string[]
1241
1851
  }
1242
1852
 
1243
1853
  const CONFLICT_FIELDS = nameSet(['columns', 'do'])
1244
1854
 
1245
1855
  /**
1246
1856
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
1247
- * also needs the capability's action to be one of the table's update actions.
1857
+ * also needs one of the capability's `actions` to be one of the table's update actions.
1248
1858
  */
1249
1859
  export function onConflictOf(
1250
1860
  context: TableContext,
1251
1861
  options: unknown,
1252
- action: string,
1862
+ actions: readonly string[],
1253
1863
  given: ReadonlyMap<string, Primitive | null>,
1254
1864
  ): OnConflict | undefined {
1255
1865
  if (options === undefined) {
@@ -1266,6 +1876,10 @@ export function onConflictOf(
1266
1876
  if (!inSet(model.columns, name)) {
1267
1877
  throw new QueryRefusedError('on_conflict', `onConflict names ${String(name)}, which is not a column of ${model.name}`)
1268
1878
  }
1879
+ if (inSet(model.json, name)) {
1880
+ // jsonb compares by value and SQLite's text by spelling: the two dialects would disagree about a conflict.
1881
+ throw new QueryRefusedError('on_conflict', `onConflict names ${name}, a JSON column of ${model.name}, which the data layer never compares`)
1882
+ }
1269
1883
  return name
1270
1884
  })
1271
1885
  if (columns === undefined || columns.length === 0) {
@@ -1276,13 +1890,14 @@ export function onConflictOf(
1276
1890
  throw new QueryRefusedError('on_conflict', "onConflict.do takes 'nothing' or 'update'")
1277
1891
  }
1278
1892
  const updates = new Map<string, Primitive | null>()
1893
+ const updating = admitted(actions, model.actions.update)
1279
1894
  if (mode === 'update') {
1280
- if (!includes(model.actions.update, action)) {
1895
+ if (updating.length === 0) {
1281
1896
  throw new CapabilityError(
1282
1897
  'wrong_action',
1283
1898
  `an insert of ${model.name} that updates on a conflict also needs its update action ${
1284
1899
  model.actions.update.join(' or ') || '(none)'
1285
- }; the capability holds ${action}`,
1900
+ }; the capability holds ${actions.join(', ')}`,
1286
1901
  )
1287
1902
  }
1288
1903
  const columns = namesOf(model.update)
@@ -1294,7 +1909,7 @@ export function onConflictOf(
1294
1909
  }
1295
1910
  }
1296
1911
  }
1297
- return freeze({ columns: freeze(columns), mode, updates })
1912
+ return freeze({ columns: freeze(columns), mode, updates, actions: freeze(updating) })
1298
1913
  }
1299
1914
 
1300
1915
  /** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
@@ -1349,8 +1964,8 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
1349
1964
 
1350
1965
  /**
1351
1966
  * `insert … on conflict (columns) do nothing`, and for `update` the conflicting row's update in the same transaction,
1352
- * within the insert's own containment. A row deleted between the two is inserted on the second try; a conflicting row
1353
- * the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1967
+ * within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
1968
+ * inserted on the second try; a conflicting row the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1354
1969
  * false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
1355
1970
  */
1356
1971
  async function insertOnConflict(
@@ -1372,7 +1987,7 @@ async function insertOnConflict(
1372
1987
  }
1373
1988
  matches[matches.length] = equals(model.name, name, value)
1374
1989
  }
1375
- const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
1990
+ const scope = conflict.mode === 'update' ? conditionedAny(model, conflict.actions, insertedScope(context, values), new Date()) : undefined
1376
1991
  for (let attempt = 0; attempt < 2; attempt++) {
1377
1992
  const node = insertNode(model.name, values, answer(context), conflict.columns)
1378
1993
  const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
@@ -1453,7 +2068,7 @@ export async function updateRow<O>(
1453
2068
  target: Addressed,
1454
2069
  given: ReadonlyMap<string, Primitive | null>,
1455
2070
  expectedVersion: OperationNode | undefined,
1456
- destination?: RefGrant,
2071
+ moved?: MovedRow,
1457
2072
  ): Promise<O> {
1458
2073
  const { name: table, version } = context.model
1459
2074
  const changes = boundValues(context, given)
@@ -1463,19 +2078,42 @@ export async function updateRow<O>(
1463
2078
  ? acknowledgementNode(table, keyOf(context.model), version, where)
1464
2079
  : updateNode(table, changes, version, where, answer(context))
1465
2080
  return run.write(async (transaction) => {
1466
- if (destination !== undefined) {
1467
- await lockDestination(transaction, context, destination)
2081
+ // A move follows containment, so a path never holds its destination.
2082
+ if (moved !== undefined) {
2083
+ await lockDestination(transaction, context, moved.destination, noPath)
1468
2084
  }
2085
+ const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
1469
2086
  const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
1470
2087
  if (row !== undefined) {
1471
2088
  checkVersion(context, row)
1472
2089
  await referenceUpdated(context, run, transaction, changes, row)
2090
+ if (moved !== undefined) {
2091
+ await judgeInserted(transaction, context, moved.judged, rowKey(context, row))
2092
+ await judgeNarrowed(transaction, context, moved, before, rowKey(context, row))
2093
+ }
1473
2094
  return row
1474
2095
  }
1475
2096
  return missingOrChanged(context, transaction, target, expectedVersion)
1476
2097
  })
1477
2098
  }
1478
2099
 
2100
+ /**
2101
+ * A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
2102
+ * after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
2103
+ * `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
2104
+ */
2105
+ export interface MovedRow {
2106
+ readonly destination: RefGrant
2107
+ readonly judged: JudgedInsert | undefined
2108
+ readonly narrowed: readonly NarrowedInsert[]
2109
+ }
2110
+
2111
+ /** The key `row`, a write's acknowledgement, answers; `undefined` when it answers none as text. */
2112
+ function rowKey(context: TableContext, row: unknown): string | undefined {
2113
+ const value: unknown = typeof row === 'object' && row !== null ? ownDescriptor(row, keyOf(context.model))?.value : undefined
2114
+ return typeof value === 'string' ? value : undefined
2115
+ }
2116
+
1479
2117
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
1480
2118
  export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
1481
2119
  const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
@@ -1491,11 +2129,11 @@ type Columns<Row> = keyof Row & string
1491
2129
  type NumericColumn<Row> = { [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never }[Columns<Row>]
1492
2130
 
1493
2131
  export interface AggregateSpec<Row> {
1494
- readonly groupBy?: readonly Columns<Row>[]
2132
+ readonly groupBy?: readonly ComparableColumn<Row>[]
1495
2133
  readonly count?: boolean
1496
2134
  readonly sum?: readonly NumericColumn<Row>[]
1497
- readonly min?: readonly Columns<Row>[]
1498
- readonly max?: readonly Columns<Row>[]
2135
+ readonly min?: readonly ComparableColumn<Row>[]
2136
+ readonly max?: readonly ComparableColumn<Row>[]
1499
2137
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>
1500
2138
  }
1501
2139
 
@@ -1532,7 +2170,7 @@ function aggregateColumns(table: string, shape: TableShape, spec: AggregateInput
1532
2170
  if (!inSet(shape.visible, name)) {
1533
2171
  throw new QueryRefusedError('unknown_column', `${String(name)} is not a column of ${table} (columns: ${namesOf(shape.visible).join(', ')})`)
1534
2172
  }
1535
- return name
2173
+ return comparableColumnOf(shape, name, 'aggregates')
1536
2174
  })
1537
2175
  if (names === undefined) {
1538
2176
  throw new QueryRefusedError('invalid_argument', `aggregate ${field} takes a plain array of column names`)
@@ -1586,6 +2224,7 @@ export async function aggregateRows<Row, O>(
1586
2224
  days: aggregated(own.days, columns),
1587
2225
  timestamps: aggregated(own.timestamps, columns),
1588
2226
  booleans: aggregated(own.booleans, columns),
2227
+ json: nameSet([]),
1589
2228
  }, rows)
1590
2229
  return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
1591
2230
  }
@@ -1641,8 +2280,25 @@ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]
1641
2280
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
1642
2281
  export interface PreparedInsert {
1643
2282
  readonly row: Map<string, Primitive | null>
2283
+ /** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
2284
+ readonly writer: string
1644
2285
  readonly destination: RefGrant | undefined
1645
2286
  readonly conflict: OnConflict | undefined
2287
+ /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
2288
+ readonly judged: JudgedInsert | undefined
2289
+ /** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
2290
+ readonly narrowed: readonly NarrowedInsert[]
2291
+ }
2292
+
2293
+ export interface JudgedInsert {
2294
+ readonly action: string
2295
+ readonly condition: ConditionModel
2296
+ }
2297
+
2298
+ /** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
2299
+ export interface NarrowedInsert {
2300
+ readonly relation: string
2301
+ readonly condition: ConditionModel
1646
2302
  }
1647
2303
 
1648
2304
  /**
@@ -1653,25 +2309,66 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
1653
2309
  const scope = dimensionScope(context.model)
1654
2310
  const grant = refGrant(context, target, listDimension(scope), 'insert')
1655
2311
  const row = readValues(values, context.model.insert, 'insert', context.model)
1656
- const conflict = onConflictOf(context, options, grant.action, row)
2312
+ const conflict = onConflictOf(context, options, [grant.action], row)
1657
2313
  if (scope.container === undefined) {
1658
2314
  // The object does not exist yet; this only refuses a chain the table has no column for.
1659
2315
  linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
1660
2316
  stampInsert(context, grant, row, scope.key, grant.id)
1661
- return { row, destination: undefined, conflict }
2317
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2318
+ // No destination to check again after the write, so a condition with a path holds nothing here.
2319
+ narrowedDestination(context, grant, row, false)
2320
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
1662
2321
  }
1663
2322
  stampInsert(context, grant, row, scope.key, uuidv7())
1664
2323
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1665
- return { row, destination: grant, conflict }
2324
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2325
+ const held = narrowedDestination(context, grant, row, true)
2326
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1666
2327
  }
1667
2328
 
1668
2329
  /** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
1669
2330
  export function prepareApplicationInsert(context: TableContext, capability: unknown, values: unknown, options?: unknown): PreparedInsert {
1670
- const grant = appGrant(context, capability, 'insert')
2331
+ const { grant, actions } = appGrant(context, capability, 'insert')
2332
+ // Every insert action writes the table's one insert list, so each held one writes all of `values`: only their conditions differ.
1671
2333
  const row = readValues(values, context.model.insert, 'insert', context.model)
1672
- const conflict = onConflictOf(context, options, grant.action, row)
2334
+ // Only an insert action that also updates may update on a conflict: never one action's insert with another's update.
2335
+ const declared = onConflictOf(context, options, actions, row)
1673
2336
  stampInsert(context, grant, row, keyOf(context.model), uuidv7())
1674
- return { row, destination: undefined, conflict }
2337
+ const conflict = declared?.mode === 'update' ? upsertingActions(context.model, declared, row) : declared
2338
+ const judged = checkInserted(context, conflict?.mode === 'update' ? conflict.actions : actions, grant.principal, row)
2339
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
2340
+ }
2341
+
2342
+ /**
2343
+ * An upsert under several actions that each insert and update: only those whose own condition admits the inserted row
2344
+ * may update the conflicting one, so the update runs under an action whose insert alone was allowed. A condition that
2345
+ * follows a path is judged only in the transaction, after the update chose its actions, so several such are refused.
2346
+ */
2347
+ function upsertingActions(model: TableModel, conflict: OnConflict, row: ReadonlyMap<string, Primitive | null>): OnConflict {
2348
+ if (conflict.actions.length < 2) {
2349
+ return conflict
2350
+ }
2351
+ const now = new Date()
2352
+ const admitting: string[] = []
2353
+ for (let index = 0; index < conflict.actions.length; index++) {
2354
+ const action = conflict.actions[index] ?? ''
2355
+ const condition = ownEntry(model.when, action)
2356
+ if (condition !== undefined && readPaths(condition).length > 0) {
2357
+ throw new CapabilityError(
2358
+ 'unenforceable',
2359
+ `an insert into ${model.name} that updates on a conflict under ${
2360
+ conflict.actions.join(', ')
2361
+ } would pair a condition that follows a path with another action's: upsert from an endpoint of one of them`,
2362
+ )
2363
+ }
2364
+ if (condition === undefined || rowSatisfies(condition, row, now)) {
2365
+ admitting[admitting.length] = action
2366
+ }
2367
+ }
2368
+ // None admits the row: keep them all, and the insert's own check refuses it.
2369
+ return admitting.length === 0
2370
+ ? conflict
2371
+ : freeze({ columns: conflict.columns, mode: conflict.mode, updates: conflict.updates, actions: freeze(admitting) })
1675
2372
  }
1676
2373
 
1677
2374
  /** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
@@ -1679,52 +2376,574 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
1679
2376
  const scope = childScope(context)
1680
2377
  const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
1681
2378
  const row = readValues(values, context.model.insert, 'insert', context.model)
1682
- const conflict = onConflictOf(context, options, grant.action, row)
2379
+ const conflict = onConflictOf(context, options, [grant.action], row)
1683
2380
  stampInsert(context, grant, row, scope.key, uuidv7())
1684
2381
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1685
- return { row, destination: grant, conflict }
2382
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2383
+ const held = narrowedDestination(context, grant, row, true)
2384
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1686
2385
  }
1687
2386
 
1688
- /** Writes each chain column the destination `Ref` settles into an insert's row. */
1689
- function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
1690
- for (let index = 0; index < values.length; index++) {
1691
- const entry = values[index]
1692
- if (entry !== undefined) {
1693
- row.set(entry.link.column, entry.value)
2387
+ const DAY_MS = 86_400_000
2388
+
2389
+ /**
2390
+ * An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
2391
+ * its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
2392
+ * ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
2393
+ * that follows a path is answered for the transaction to judge.
2394
+ */
2395
+ function checkInserted(
2396
+ context: TableContext,
2397
+ actions: readonly string[],
2398
+ principal: string,
2399
+ row: ReadonlyMap<string, Primitive | null>,
2400
+ ): JudgedInsert | undefined {
2401
+ const model = context.model
2402
+ const now = new Date()
2403
+ const judged = insertCondition(model, actions, row, now)
2404
+ for (let index = 0; index < model.confers.length; index++) {
2405
+ const source = model.confers[index]
2406
+ if (source === undefined) {
2407
+ continue
2408
+ }
2409
+ const assign = source.assign
2410
+ if (assign === undefined) {
2411
+ throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
2412
+ }
2413
+ // A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
2414
+ if (!assign.self && source.principalPath === undefined && row.get(source.principal) === principal) {
2415
+ throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
2416
+ }
2417
+ if (assign.maxDays !== undefined && source.expires !== undefined) {
2418
+ const value = row.get(source.expires)
2419
+ const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
2420
+ if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
2421
+ throw new ConflictError(
2422
+ `a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
2423
+ )
2424
+ }
1694
2425
  }
1695
2426
  }
2427
+ return judged
1696
2428
  }
1697
2429
 
1698
- /** A prepared insert, with its conflict handling when the caller named one. */
1699
- export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
1700
- const conflict = prepared.conflict
1701
- if (conflict === undefined) {
1702
- return insertRow(context, run, prepared.row, prepared.destination)
1703
- }
1704
- return run.write(async (transaction) => {
1705
- if (prepared.destination !== undefined) {
1706
- await lockDestination(transaction, context, prepared.destination)
2430
+ /**
2431
+ * The insert actions' condition on the row, as one role holding `actions` is narrowed: a row any of them admits passes,
2432
+ * and one without a condition admits every row. A pathless condition is judged here; one that follows a path is
2433
+ * answered for the transaction to judge, which holds one such condition only, so several are refused.
2434
+ */
2435
+ function insertCondition(
2436
+ model: TableModel,
2437
+ actions: readonly string[],
2438
+ row: ReadonlyMap<string, Primitive | null>,
2439
+ now: Date,
2440
+ ): JudgedInsert | undefined {
2441
+ const pathed: JudgedInsert[] = []
2442
+ for (let index = 0; index < actions.length; index++) {
2443
+ const action = actions[index]
2444
+ if (action === undefined) continue
2445
+ const condition = ownEntry(model.when, action)
2446
+ if (condition === undefined) {
2447
+ return undefined
1707
2448
  }
1708
- return insertOnConflict(context, run, transaction, prepared.row, conflict)
1709
- })
1710
- }
1711
-
2449
+ if (readPaths(condition).length > 0) {
2450
+ pathed[pathed.length] = { action, condition }
2451
+ } else if (rowSatisfies(condition, row, now)) {
2452
+ return undefined
2453
+ }
2454
+ }
2455
+ const [only, ...more] = pathed
2456
+ if (only === undefined) {
2457
+ throw new ConflictError(`the row is outside what ${actions.join(' or ')} inserts into ${model.name}`)
2458
+ }
2459
+ if (more.length > 0) {
2460
+ throw new CapabilityError(
2461
+ 'unenforceable',
2462
+ `an insert into ${model.name} under ${
2463
+ actions.join(', ')
2464
+ } would be judged by several conditions that follow paths: insert from an endpoint of one of them`,
2465
+ )
2466
+ }
2467
+ return only
2468
+ }
2469
+
2470
+ /**
2471
+ * The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
2472
+ * and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
2473
+ * the transaction to judge (`judgeNarrowed`), or, without a destination to check again (`defer` false), held to fail. A Ref held by nothing else then is refused (409): the relation's membership
2474
+ * is never judged on the written row, so the row never counts towards its own insert.
2475
+ */
2476
+ function narrowedDestination(
2477
+ context: TableContext,
2478
+ grant: RefGrant,
2479
+ row: ReadonlyMap<string, Primitive | null>,
2480
+ defer: boolean,
2481
+ ): { readonly destination: RefGrant; readonly narrowed: readonly NarrowedInsert[] } {
2482
+ const now = new Date()
2483
+ const kept: RelationHold[] = []
2484
+ const narrowed: NarrowedInsert[] = []
2485
+ for (let index = 0; index < grant.relations.length; index++) {
2486
+ const hold = grant.relations[index]
2487
+ if (hold === undefined) continue
2488
+ const relation = hold.relation
2489
+ const condition = relationCondition(context.model, relation, grant.action)
2490
+ const pathed = condition !== undefined && readPaths(condition).length > 0
2491
+ if (condition !== undefined && pathed && defer && !judgesRelation(narrowed, relation)) {
2492
+ narrowed[narrowed.length] = { relation, condition }
2493
+ }
2494
+ if (condition === undefined || (pathed ? defer : rowSatisfies(condition, row, now))) {
2495
+ kept[kept.length] = hold
2496
+ }
2497
+ }
2498
+ if (kept.length === grant.relations.length) {
2499
+ return { destination: grant, narrowed }
2500
+ }
2501
+ if (kept.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2502
+ throw new ConflictError(`the row is outside what ${grant.action} inserts into ${context.model.name} through its relations`)
2503
+ }
2504
+ return { destination: { ...grant, relations: kept }, narrowed }
2505
+ }
2506
+
2507
+ /** Whether `narrowed` already judges `relation`: two holds of one relation are judged once. */
2508
+ function judgesRelation(narrowed: readonly NarrowedInsert[], relation: string): boolean {
2509
+ for (let index = 0; index < narrowed.length; index++) {
2510
+ if (narrowed[index]?.relation === relation) return true
2511
+ }
2512
+ return false
2513
+ }
2514
+
2515
+ /**
2516
+ * What held an insert's destination before the write, apart from the relations narrowed by a path: the rest of the
2517
+ * `Ref`, and, with several such relations, each of them alone. Decided before the row exists, so it never counts it.
2518
+ */
2519
+ interface NarrowedHolds {
2520
+ readonly rest: boolean
2521
+ readonly alone: readonly string[]
2522
+ }
2523
+
2524
+ /** `NarrowedHolds` of a prepared insert, locked `for share` in its transaction before the write; `undefined` with nothing narrowed. */
2525
+ async function narrowedHolds(
2526
+ transaction: Session,
2527
+ context: TableContext,
2528
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2529
+ paths?: PathRule,
2530
+ ): Promise<NarrowedHolds | undefined> {
2531
+ const destination = prepared?.destination
2532
+ if (prepared === undefined || destination === undefined || prepared.narrowed.length === 0) {
2533
+ return undefined
2534
+ }
2535
+ const relations: string[] = []
2536
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2537
+ const entry = prepared.narrowed[index]
2538
+ if (entry !== undefined) relations[relations.length] = entry.relation
2539
+ }
2540
+ const rest = await heldBy(transaction, context, { ...destination, relations: holdsBesides(destination.relations, relations) }, paths)
2541
+ const alone: string[] = []
2542
+ // One narrowed relation that passes leaves the destination as `lockDestination` found it; only with several may it be another's.
2543
+ for (let index = 0; relations.length > 1 && index < relations.length; index++) {
2544
+ const relation = relations[index] ?? ''
2545
+ const holds: RelationHold[] = []
2546
+ for (let position = 0; position < destination.relations.length; position++) {
2547
+ const hold = destination.relations[position]
2548
+ if (hold !== undefined && hold.relation === relation) holds[holds.length] = hold
2549
+ }
2550
+ if (await heldBy(transaction, context, { ...destination, relations: holds, revealing: [], paths: [] }, paths)) alone[alone.length] = relation
2551
+ }
2552
+ return { rest, alone }
2553
+ }
2554
+
2555
+ /** Whether `grant` holds the destination: with no part left, never. */
2556
+ async function heldBy(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
2557
+ if (grant.relations.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2558
+ return false
2559
+ }
2560
+ return await destinationHeld(transaction, context, grant, paths)
2561
+ }
2562
+
2563
+ /**
2564
+ * The destination's relations whose condition for the insert follows a path, judged on the row just written as
2565
+ * `judgeInserted` judges `when`. When the row fails one, the insert stands only on what held the destination before the
2566
+ * write without it (`before`): the rest of the `Ref`, or a narrowed relation the row meets that held it alone. Otherwise
2567
+ * the transaction fails with a 409.
2568
+ */
2569
+ async function judgeNarrowed(
2570
+ transaction: Session,
2571
+ context: TableContext,
2572
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2573
+ before: NarrowedHolds | undefined,
2574
+ key: Primitive | null | undefined,
2575
+ ): Promise<void> {
2576
+ const destination = prepared?.destination
2577
+ if (prepared === undefined || destination === undefined || before === undefined) {
2578
+ return
2579
+ }
2580
+ let failed = false
2581
+ let held = before.rest
2582
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2583
+ const entry = prepared.narrowed[index]
2584
+ if (entry === undefined) continue
2585
+ if (!(await rowMeets(transaction, context, destination.action, entry.condition, key))) {
2586
+ failed = true
2587
+ } else if (includes(before.alone, entry.relation)) {
2588
+ held = true
2589
+ }
2590
+ }
2591
+ if (failed && !held) {
2592
+ transaction.fail()
2593
+ throw new ConflictError(`the row is outside what ${destination.action} inserts into ${context.model.name} through its relations`)
2594
+ }
2595
+ }
2596
+
2597
+ /**
2598
+ * An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
2599
+ * held the row's foreign keys, so a path reads only the rows they name in the row's tenant. Every row each read path
2600
+ * reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
2601
+ * before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
2602
+ * so it commits nothing even when the handler catches the refusal.
2603
+ */
2604
+ async function judgeInserted(
2605
+ transaction: Session,
2606
+ context: TableContext,
2607
+ judged: JudgedInsert | undefined,
2608
+ key: Primitive | null | undefined,
2609
+ ): Promise<void> {
2610
+ if (judged === undefined) {
2611
+ return
2612
+ }
2613
+ if (!(await rowMeets(transaction, context, judged.action, judged.condition, key))) {
2614
+ transaction.fail()
2615
+ throw new ConflictError(`the row is outside what ${judged.action} inserts into ${context.model.name}`)
2616
+ }
2617
+ }
2618
+
2619
+ /**
2620
+ * Whether the row just written meets `condition`, in the insert's transaction: every row each of its paths reaches is
2621
+ * locked `FOR SHARE` first, then the condition is judged as a read of the row judges it.
2622
+ */
2623
+ async function rowMeets(
2624
+ transaction: Session,
2625
+ context: TableContext,
2626
+ action: string,
2627
+ condition: ConditionModel,
2628
+ key: Primitive | null | undefined,
2629
+ ): Promise<boolean> {
2630
+ const model = context.model
2631
+ if (key === undefined || key === null) {
2632
+ throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
2633
+ }
2634
+ const paths = readPaths(condition)
2635
+ for (let index = 0; index < paths.length; index++) {
2636
+ const steps = paths[index] ?? []
2637
+ // The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
2638
+ let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
2639
+ const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
2640
+ for (let position = 0; position < steps.length; position++) {
2641
+ const step = steps[position]
2642
+ if (step === undefined) continue
2643
+ const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
2644
+ await transaction.run(lockNode(step.table, step.to, scope), {
2645
+ root: 'SelectQueryNode',
2646
+ table: step.table,
2647
+ joins: {},
2648
+ scope,
2649
+ lock: 'share',
2650
+ subqueries: withColumns(context.subqueries, walked),
2651
+ })
2652
+ const next = steps[position + 1]
2653
+ if (next !== undefined) {
2654
+ reached = subquery(step.table, next.from, scope)
2655
+ walked[step.table] = [...(walked[step.table] ?? []), next.from]
2656
+ }
2657
+ }
2658
+ }
2659
+ const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
2660
+ const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
2661
+ root: 'SelectQueryNode',
2662
+ table: model.name,
2663
+ joins: {},
2664
+ scope,
2665
+ subqueries: context.subqueries,
2666
+ })
2667
+ return rows.length > 0
2668
+ }
2669
+
2670
+ /** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
2671
+ function withColumns(
2672
+ admitted: Readonly<Record<string, readonly string[]>>,
2673
+ more: Readonly<Record<string, readonly string[]>>,
2674
+ ): Readonly<Record<string, readonly string[]>> {
2675
+ const merged: Record<string, readonly string[]> = { ...admitted }
2676
+ const tables = ownKeys(more)
2677
+ for (let index = 0; index < tables.length; index++) {
2678
+ const table = tables[index] ?? ''
2679
+ setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
2680
+ }
2681
+ return merged
2682
+ }
2683
+
2684
+ /** Writes each chain column the destination `Ref` settles into an insert's row. */
2685
+ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
2686
+ for (let index = 0; index < values.length; index++) {
2687
+ const entry = values[index]
2688
+ if (entry !== undefined) {
2689
+ row.set(entry.link.column, entry.value)
2690
+ }
2691
+ }
2692
+ }
2693
+
2694
+ /** A prepared insert, with its conflict handling when the caller named one. */
2695
+ export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
2696
+ const conflict = prepared.conflict
2697
+ if (conflict === undefined) {
2698
+ return insertRow(context, run, prepared.row, prepared)
2699
+ }
2700
+ return run.write(async (transaction) => {
2701
+ if (prepared.destination !== undefined) {
2702
+ await lockDestination(transaction, context, prepared.destination)
2703
+ }
2704
+ const before = await narrowedHolds(transaction, context, prepared)
2705
+ await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
2706
+ await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
2707
+ await checkMemberRevealAssign(transaction, context, prepared.writer, prepared.row)
2708
+ await checkPathWriters(transaction, context, prepared.writer, prepared.row)
2709
+ const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
2710
+ // A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
2711
+ if (written['inserted'] === true) {
2712
+ await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
2713
+ await judgeNarrowed(transaction, context, prepared, before, prepared.row.get(keyOf(context.model)))
2714
+ }
2715
+ return written
2716
+ })
2717
+ }
2718
+
2719
+ /**
2720
+ * A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
2721
+ * row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
2722
+ * stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
2723
+ */
2724
+ async function checkPrincipalAssign(
2725
+ transaction: Session,
2726
+ context: TableContext,
2727
+ writer: string,
2728
+ row: ReadonlyMap<string, Primitive | null>,
2729
+ ): Promise<void> {
2730
+ const model = context.model
2731
+ for (let index = 0; index < model.confers.length; index++) {
2732
+ const source = model.confers[index]
2733
+ const path = source?.principalPath
2734
+ const value = source === undefined ? undefined : row.get(source.principal)
2735
+ if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
2736
+ continue
2737
+ }
2738
+ const keyed = equals(path.table, path.key, value)
2739
+ await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
2740
+ const named = allOf([keyed, equals(path.table, path.column, writer)])
2741
+ const rows = await transaction.run(locateNode(path.table, [path.key], named), {
2742
+ root: 'SelectQueryNode',
2743
+ table: path.table,
2744
+ joins: {},
2745
+ scope: named,
2746
+ })
2747
+ if (rows.length > 0) {
2748
+ throw new ConflictError(
2749
+ `a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
2750
+ )
2751
+ }
2752
+ }
2753
+ }
2754
+
2755
+ /**
2756
+ * An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
2757
+ * insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
2758
+ * the relation is at. One guarded select per such reveal, in the insert's transaction.
2759
+ */
2760
+ async function checkRevealAssign(
2761
+ transaction: Session,
2762
+ context: TableContext,
2763
+ writer: string,
2764
+ row: ReadonlyMap<string, Primitive | null>,
2765
+ ): Promise<void> {
2766
+ const model = context.model
2767
+ const now = new Date()
2768
+ for (let index = 0; index < model.reveals.length; index++) {
2769
+ const reveal = model.reveals[index]
2770
+ const path = reveal?.path
2771
+ const value = path === undefined ? undefined : row.get(path.column)
2772
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
2773
+ const source = relationSource(context.relations, reveal.relation)
2774
+ const tests: OperationNode[] = []
2775
+ const rest: OperationNode[] = [...activeRow(source, now)]
2776
+ if (source.dimension === path.dimension) {
2777
+ tests[tests.length] = equals(source.table, source.node, value)
2778
+ } else {
2779
+ const link = linkOf(path.chain, source.dimension)
2780
+ if (link === undefined) continue
2781
+ const above = subquery(path.table, link.column, equals(path.table, path.key, value))
2782
+ rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
2783
+ }
2784
+ // The principal test comes last: an equality, or a path's membership after the node's equality.
2785
+ tests[tests.length] = namesPrincipal(source, writer)
2786
+ const address = allOf(tests)
2787
+ const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
2788
+ const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
2789
+ root: 'SelectQueryNode',
2790
+ table: source.table,
2791
+ joins: {},
2792
+ scope,
2793
+ subqueries: context.subqueries,
2794
+ })
2795
+ if (rows.length > 0) {
2796
+ throw new ConflictError(
2797
+ `a row of ${model.name} names in ${path.column} a node where its writer holds ${reveal.relation}, which the reveal's assign.self does not allow`,
2798
+ )
2799
+ }
2800
+ }
2801
+ }
2802
+
2803
+ /**
2804
+ * An inserted row whose path column a member reveal matches through, under the reveal's `assign`: without `self`, the
2805
+ * insert is refused while its writer holds a grant the reveal counts (one of its actions, at the node itself) at the
2806
+ * node the column names. The grants are the request's own; the database compares them with the node's key, so every
2807
+ * spelling of a key it reads as one (a `uuid`) is that node. Work with no request caller has none to judge, and is
2808
+ * refused.
2809
+ */
2810
+ async function checkMemberRevealAssign(
2811
+ transaction: Session,
2812
+ context: TableContext,
2813
+ writer: string,
2814
+ row: ReadonlyMap<string, Primitive | null>,
2815
+ ): Promise<void> {
2816
+ const model = context.model
2817
+ const authority = runtimeOf(context.connection).capabilities
2818
+ for (let index = 0; index < model.memberReveals.length; index++) {
2819
+ const reveal = model.memberReveals[index]
2820
+ const path = reveal?.path
2821
+ const value = path === undefined ? undefined : row.get(path.column)
2822
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || value === undefined || value === null) {
2823
+ continue
2824
+ }
2825
+ for (let position = 0; position < reveal.actions.length; position++) {
2826
+ const action = reveal.actions[position] ?? ''
2827
+ const standing = authority.standing?.(path.dimension, action)
2828
+ if (standing === undefined || standing.principal !== writer) {
2829
+ throw new ConflictError(
2830
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} its member reveal reveals to, and its writer's grants cannot be judged under assign without self: work with no request caller`,
2831
+ )
2832
+ }
2833
+ if (standing.values === 'all' || standing.values.length === 0) continue
2834
+ const scope = AndNode.create(equals(path.table, path.key, value), inList(path.table, path.key, standing.values))
2835
+ const rows = await transaction.run(locateNode(path.table, [path.key], scope), {
2836
+ root: 'SelectQueryNode',
2837
+ table: path.table,
2838
+ joins: {},
2839
+ scope,
2840
+ })
2841
+ if (rows.length > 0) {
2842
+ throw new ConflictError(
2843
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer holds a grant the member reveal counts, which the reveal's assign.self does not allow`,
2844
+ )
2845
+ }
2846
+ }
2847
+ }
2848
+ }
2849
+
2850
+ /**
2851
+ * An inserted row's path column that hands out actions (`writeThrough`): its writer must hold every one of them at the
2852
+ * node the column names, as a grant there or above it, a relation row naming it there (of a relation no `relationWhen`
2853
+ * narrows for the action), or a revealing row. The node's
2854
+ * row is locked `FOR SHARE` first, so it stays where it lies until the commit, and so is each row the writer holds it
2855
+ * through; IAM grants are the request's own. Judged before the insert, so the inserted row never counts. A writer
2856
+ * outside the bound, or work with no caller, is a 409 and nothing is written.
2857
+ */
2858
+ async function checkPathWriters(
2859
+ transaction: Session,
2860
+ context: TableContext,
2861
+ writer: string,
2862
+ row: ReadonlyMap<string, Primitive | null>,
2863
+ ): Promise<void> {
2864
+ const model = context.model
2865
+ const authority = runtimeOf(context.connection).capabilities
2866
+ for (let index = 0; index < context.writers.length; index++) {
2867
+ const bound = context.writers[index]
2868
+ const value = bound === undefined ? undefined : row.get(bound.path.column)
2869
+ if (bound === undefined || value === undefined || value === null) continue
2870
+ const { path, owner } = bound
2871
+ const refused = (action: string) =>
2872
+ new ConflictError(
2873
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer does not hold ${action}, which the path hands out (writeThrough)`,
2874
+ )
2875
+ const keyed = equals(owner.name, keyOf(owner), value)
2876
+ const locked = await transaction.run(lockNode(owner.name, keyOf(owner), keyed), {
2877
+ root: 'SelectQueryNode',
2878
+ table: owner.name,
2879
+ joins: {},
2880
+ scope: keyed,
2881
+ lock: 'share',
2882
+ })
2883
+ const chain = locked.length === 0 ? null : await chainOf(owner, transaction, String(value))
2884
+ for (let position = 0; position < bound.actions.length; position++) {
2885
+ const action = bound.actions[position] ?? ''
2886
+ const standing = authority.standing?.(path.dimension, action)
2887
+ if (chain === null || standing === undefined || standing.principal !== writer) throw refused(action)
2888
+ if (holdsByGrant(standing, String(value), chain)) continue
2889
+ const holding: RefGrant = {
2890
+ kind: 'ref',
2891
+ dimension: path.dimension,
2892
+ action,
2893
+ principal: writer,
2894
+ id: String(value),
2895
+ chain,
2896
+ relations: unnarrowed(context.relations, standing.relations, action),
2897
+ revealing: standing.revealing,
2898
+ paths: [],
2899
+ }
2900
+ if (!(await holdingRowLocked(transaction, context, holding))) throw refused(action)
2901
+ }
2902
+ }
2903
+ }
2904
+
2905
+ /**
2906
+ * Of `relations`, those no table's `relationWhen` narrows for `action`: a relation that holds the action on some rows only
2907
+ * does not bound a writer who hands it out at a node.
2908
+ */
2909
+ function unnarrowed(relations: RelationSources, held: readonly RelationHold[], action: string): readonly RelationHold[] {
2910
+ const kept: RelationHold[] = []
2911
+ for (let index = 0; index < held.length; index++) {
2912
+ const hold = held[index]
2913
+ if (hold !== undefined && !includes(knownRelation(relations, hold.relation).narrowed, action)) kept[kept.length] = hold
2914
+ }
2915
+ return kept
2916
+ }
2917
+
2918
+ /** Whether `standing`'s grants hold its action at `node`: everywhere, there, or at a container `chain` places it in. */
2919
+ function holdsByGrant(standing: WithinGrant, node: string, chain: ReadonlyMap<string, string>): boolean {
2920
+ if (standing.values === 'all' || includes(standing.values, node)) {
2921
+ return true
2922
+ }
2923
+ for (let index = 0; index < standing.containers.length; index++) {
2924
+ const container = standing.containers[index]
2925
+ const at = container === undefined ? undefined : chain.get(container.dimension)
2926
+ if (container !== undefined && at !== undefined && includes(container.values, at)) return true
2927
+ }
2928
+ return false
2929
+ }
2930
+
1712
2931
  /** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
1713
2932
  export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
1714
2933
  const prepared = prepareDimensionInsert(context, target, values)
1715
- return insertRow(context, run, prepared.row, prepared.destination)
2934
+ return insertRow(context, run, prepared.row, prepared)
1716
2935
  }
1717
2936
 
1718
2937
  /** An application table's insert, for an `app` capability of its insert action. */
1719
2938
  export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
1720
2939
  const prepared = prepareApplicationInsert(context, capability, values)
1721
- return insertRow(context, run, prepared.row, prepared.destination)
2940
+ return insertRow(context, run, prepared.row, prepared)
1722
2941
  }
1723
2942
 
1724
2943
  /** `ChildTable.insert` over a capability nobody type-checked. */
1725
2944
  export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
1726
2945
  const prepared = prepareChildInsert(context, parent, values)
1727
- return insertRow(context, run, prepared.row, prepared.destination)
2946
+ return insertRow(context, run, prepared.row, prepared)
1728
2947
  }
1729
2948
 
1730
2949
  type ReadAction<P, T> = ActionOf<P, T, 'read'>
@@ -1784,7 +3003,9 @@ export class DimensionTable<DB, P, T extends string> {
1784
3003
  /**
1785
3004
  * Moves the object to another container: the delete action at the source, the insert action at the target,
1786
3005
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
1787
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
3006
+ * through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
3007
+ * condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
3008
+ * Answers the acknowledgement and the new chain.
1788
3009
  */
1789
3010
  async move(
1790
3011
  ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
@@ -1795,8 +3016,21 @@ export class DimensionTable<DB, P, T extends string> {
1795
3016
  if (container === undefined) {
1796
3017
  throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
1797
3018
  }
1798
- const scope = objectPredicate(context, ref, 'delete')
3019
+ if (delegates(context.model)) {
3020
+ throw new CapabilityError(
3021
+ 'table_kind',
3022
+ `${context.model.name} hands out access, so a row is never moved: insert a new one`,
3023
+ )
3024
+ }
3025
+ // A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
1799
3026
  const target = refGrant(context, to, container.dimension, 'insert')
3027
+ if (refGrant(context, ref, dimensionScope(context.model).dimension, 'delete').paths.length > 0 || target.paths.length > 0) {
3028
+ throw new CapabilityError(
3029
+ 'unenforceable',
3030
+ `a Ref held through a secondary path never moves a row of ${context.model.name}: a move follows containment`,
3031
+ )
3032
+ }
3033
+ const scope = objectPredicate(context, ref, 'delete', noPath)
1800
3034
  const values = linkValues(context.model.name, context.model.chain, target)
1801
3035
  const changes = new Map<string, Primitive | null>()
1802
3036
  stampChain(changes, values)
@@ -1807,7 +3041,16 @@ export class DimensionTable<DB, P, T extends string> {
1807
3041
  setOwn(chain, entry.link.dimension, entry.value)
1808
3042
  }
1809
3043
  }
1810
- const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, target)
3044
+ const condition = ownEntry(context.model.when, target.action)
3045
+ const narrowed: NarrowedInsert[] = []
3046
+ for (let index = 0; index < target.relations.length; index++) {
3047
+ const relation = target.relations[index]?.relation ?? ''
3048
+ const narrowing = relationCondition(context.model, relation, target.action)
3049
+ if (narrowing !== undefined && !judgesRelation(narrowed, relation)) narrowed[narrowed.length] = { relation, condition: narrowing }
3050
+ }
3051
+ const judged = condition === undefined ? undefined : { action: target.action, condition }
3052
+ const moved: MovedRow = { destination: target, judged, narrowed }
3053
+ const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, moved)
1811
3054
  return { ...acknowledged, chain }
1812
3055
  }
1813
3056
 
@@ -1910,7 +3153,7 @@ function probeRunner(context: TableContext): { readonly run: Runner; readonly he
1910
3153
  }
1911
3154
 
1912
3155
  /**
1913
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
3156
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
1914
3157
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
1915
3158
  * `key`, a dimension row by its capability alone.
1916
3159
  */
@@ -1938,15 +3181,19 @@ function probeOf(context: TableContext): TableProbe {
1938
3181
  }
1939
3182
  return objectPredicate(context, capability, operation)
1940
3183
  }
3184
+ const app = (capability: unknown): boolean => runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app'
1941
3185
  // An `app` capability reads every row through ctx.db.app: its rows with appRead, its counts with appCount too.
1942
3186
  const list = (capability: unknown, reach: AppReach): OperationNode | undefined => {
1943
- if (runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app') {
3187
+ if (app(capability)) {
1944
3188
  return appRecordPredicate(context, capability, reach)
1945
3189
  }
1946
3190
  return child ? childListPredicate(context, capability, 'read') : dimensionListPredicate(context, capability, 'read')
1947
3191
  }
1948
- // A capability reads the columns of its own action, as ctx.db does.
1949
- const visible = (capability: unknown): readonly string[] => visibleFor(context.model, heldAction(context, capability))
3192
+ // A capability reads the columns of its own action, as ctx.db does; an `app` one those its reaching actions read alone.
3193
+ const visible = (capability: unknown): readonly string[] =>
3194
+ app(capability)
3195
+ ? visibleThrough(context.model, appRecordRead(context, capability, 'rows').reach)
3196
+ : visibleFor(context.model, heldAction(context, capability))
1950
3197
  const { run, held } = probeRunner(context)
1951
3198
  return freeze({
1952
3199
  mode: child ? 'child' : 'dimension',
@@ -1957,12 +3204,12 @@ function probeOf(context: TableContext): TableProbe {
1957
3204
  context,
1958
3205
  list(capability, 'rows'),
1959
3206
  finishSelect(start, start),
1960
- heldAction(context, capability),
3207
+ soleAction(context, capability),
1961
3208
  visible(capability),
1962
3209
  )
1963
3210
  },
1964
3211
  group: async (capability: unknown, columns: readonly string[]) =>
1965
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(
3212
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(
1966
3213
  context,
1967
3214
  run,
1968
3215
  list(capability, 'rows'),
@@ -2018,8 +3265,7 @@ function appProbeOf(context: TableContext): TableProbe {
2018
3265
  mode: 'app',
2019
3266
  get: async (capability: unknown, key?: string) => {
2020
3267
  if (scoped(capability)) {
2021
- scopedApplicationRead(context, capability)
2022
- return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
3268
+ return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
2023
3269
  }
2024
3270
  return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
2025
3271
  },
@@ -2029,12 +3275,12 @@ function appProbeOf(context: TableContext): TableProbe {
2029
3275
  context,
2030
3276
  every(capability),
2031
3277
  finishSelect(start, start),
2032
- heldAction(context, capability),
3278
+ soleAction(context, capability),
2033
3279
  )
2034
3280
  },
2035
3281
  count,
2036
3282
  group: async (capability: unknown, columns: readonly string[]) =>
2037
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
3283
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
2038
3284
  groupBy: columns,
2039
3285
  count: true,
2040
3286
  }),
@@ -2068,11 +3314,11 @@ function destinationOf(models: TableModels, model: TableModel, parent: TableMode
2068
3314
 
2069
3315
  /** What a select or an aggregate of a capability that reads `visible` may name: those columns, and no join. */
2070
3316
  export function actionShape(model: TableModel, visible: readonly string[]): TableShape {
2071
- return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates })
3317
+ return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates, json: model.json })
2072
3318
  }
2073
3319
 
2074
3320
  function shapeOf(model: TableModel, joinable: Readonly<Record<string, JoinShape>>): TableShape {
2075
- return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates })
3321
+ return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates, json: model.json })
2076
3322
  }
2077
3323
 
2078
3324
  function joinShapes(models: TableModels, parent: TableModel): Readonly<Record<string, JoinShape>> {
@@ -2120,6 +3366,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
2120
3366
  export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2121
3367
  const models = tableModels(tables)
2122
3368
  const connection: Connection = { runtime: undefined }
3369
+ const layer = layerReach(models)
3370
+ const { relations, members, subqueries } = layer
2123
3371
 
2124
3372
  function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
2125
3373
  const model = typeof table === 'string' ? modelOf(models, table) : undefined
@@ -2131,6 +3379,15 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2131
3379
 
2132
3380
  function contextOf(model: TableModel): TableContext {
2133
3381
  const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
3382
+ const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
3383
+ ? freeze({
3384
+ column: model.scope.column,
3385
+ table: parent.name,
3386
+ key: parent.scope.key,
3387
+ access: viewAccessLinks(model, model.scope.key),
3388
+ context: contextOf(freeze({ ...parent, when: freeze({}), relationWhen: freeze({}) })),
3389
+ })
3390
+ : undefined
2134
3391
  const joinable = joinShapes(models, model)
2135
3392
  const joins: Record<string, readonly ForeignKeyPair[]> = {}
2136
3393
  const children = ownKeys(joinable)
@@ -2149,6 +3406,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2149
3406
  }
2150
3407
  }
2151
3408
  const shape = shapeOf(model, joinable)
3409
+ const writers: PathBound[] = []
3410
+ const declared = pathWriters(models, model)
3411
+ for (let index = 0; index < declared.length; index++) {
3412
+ const writer = declared[index]
3413
+ const owner = writer === undefined ? undefined : modelOf(models, writer.path.table)
3414
+ if (writer !== undefined && owner !== undefined) writers[writers.length] = freeze({ ...writer, owner })
3415
+ }
2152
3416
  return freeze({
2153
3417
  model,
2154
3418
  parent,
@@ -2157,6 +3421,11 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2157
3421
  joins: freeze(joins),
2158
3422
  children: freeze(childModels),
2159
3423
  connection,
3424
+ relations,
3425
+ members,
3426
+ subqueries,
3427
+ through,
3428
+ writers: freeze(writers),
2160
3429
  })
2161
3430
  }
2162
3431
 
@@ -2186,6 +3455,20 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2186
3455
  connection.runtime = bound
2187
3456
  return freeze({
2188
3457
  locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
3458
+ relates: async (relation: string, node: string, principal: string) =>
3459
+ relationHolds(models, relations, subqueries, bound, relation, node, principal),
3460
+ reveals: async (relation: string, dimension: string, node: string, principal: string, action: string) =>
3461
+ revealHolds(relations, subqueries, bound, relation, dimension, node, principal, action),
3462
+ holdsThrough: async (
3463
+ dimension: string,
3464
+ id: string,
3465
+ action: string,
3466
+ principal: string,
3467
+ relations: readonly RelationHold[],
3468
+ paths: readonly ContainerGrant[],
3469
+ ) => heldThroughPaths(models, layer, bound, dimension, id, action, principal, relations, paths),
3470
+ revealsToMembers: async (revealing: string, values: readonly string[], dimension: string, node: string, action: string) =>
3471
+ membersRevealed(members, subqueries, bound, revealing, values, dimension, node, action),
2189
3472
  release() {
2190
3473
  if (connection.runtime === bound) {
2191
3474
  connection.runtime = undefined
@@ -2199,6 +3482,9 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2199
3482
  wakes: jobWakes(() => runtimeOf(connection)),
2200
3483
  admissions: admissions(() => runtimeOf(connection)),
2201
3484
  files: storedFiles(() => runtimeOf(connection)),
3485
+ receipts: requestReceipts(),
3486
+ push: pushSubscriptions(),
3487
+ notifications: notifications(),
2202
3488
  }),
2203
3489
  data: dataAccess({
2204
3490
  models,
@@ -2218,6 +3504,150 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2218
3504
  return database
2219
3505
  }
2220
3506
 
3507
+ /**
3508
+ * Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
3509
+ * node column, a condition path's target by its key), which the guard admits and nothing else.
3510
+ */
3511
+ function layerReach(
3512
+ models: TableModels,
3513
+ ): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
3514
+ const relations: Record<string, LayerRelation | AccessRelation> = {}
3515
+ const members: Record<string, MemberRevealModel[]> = {}
3516
+ const selected: Record<string, string[]> = {}
3517
+ const select = (table: string, column: string): void => {
3518
+ const columns = ownEntry(selected, table) ?? []
3519
+ if (!includes(columns, column)) columns[columns.length] = column
3520
+ setOwn(selected, table, columns)
3521
+ }
3522
+ const names = ownKeys(models)
3523
+ const reveals: Record<string, RevealModel[]> = {}
3524
+ const narrowed: Record<string, string[]> = {}
3525
+ for (let index = 0; index < names.length; index++) {
3526
+ const model = modelOf(models, names[index] ?? '')
3527
+ const conditioned = model === undefined ? [] : ownKeys(model.relationWhen)
3528
+ for (let position = 0; model !== undefined && position < conditioned.length; position++) {
3529
+ const relation = conditioned[position] ?? ''
3530
+ const conditions = ownEntry(model.relationWhen, relation) ?? {}
3531
+ const actions = ownKeys(conditions)
3532
+ const listed = ownEntry(narrowed, relation) ?? []
3533
+ for (let next = 0; next < actions.length; next++) {
3534
+ const action = actions[next] ?? ''
3535
+ if (!includes(listed, action)) listed[listed.length] = action
3536
+ const condition = ownEntry(conditions, action)
3537
+ if (condition !== undefined) addReach(condition, select)
3538
+ }
3539
+ setOwn(narrowed, relation, listed)
3540
+ }
3541
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
3542
+ const reveal = model.reveals[position]
3543
+ if (reveal === undefined) continue
3544
+ const listed = ownEntry(reveals, reveal.relation) ?? []
3545
+ listed[listed.length] = reveal
3546
+ setOwn(reveals, reveal.relation, listed)
3547
+ select(reveal.table, reveal.column)
3548
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3549
+ }
3550
+ for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
3551
+ const reveal = model.memberReveals[position]
3552
+ if (reveal === undefined) continue
3553
+ const listed = ownEntry(members, reveal.source) ?? []
3554
+ listed[listed.length] = reveal
3555
+ setOwn(members, reveal.source, listed)
3556
+ select(reveal.table, reveal.column)
3557
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3558
+ }
3559
+ }
3560
+ for (let index = 0; index < names.length; index++) {
3561
+ const model = modelOf(models, names[index] ?? '')
3562
+ if (model === undefined) continue
3563
+ for (let position = 0; position < model.confers.length; position++) {
3564
+ const source = model.confers[position]
3565
+ if (source === undefined) continue
3566
+ const revealed = ownEntry(reveals, source.relation) ?? []
3567
+ const placed: Record<string, Readonly<Record<string, string>>> = {}
3568
+ setOwn(placed, model.name, placementOf(model))
3569
+ for (let next = 0; next < revealed.length; next++) {
3570
+ const table = revealed[next]?.table ?? ''
3571
+ const at = modelOf(models, table)
3572
+ if (at !== undefined) setOwn(placed, table, placementOf(at))
3573
+ }
3574
+ setOwn(
3575
+ relations,
3576
+ source.relation,
3577
+ freeze({
3578
+ ...source,
3579
+ kind: 'source',
3580
+ reveals: freeze(revealed),
3581
+ narrowed: freeze(ownEntry(narrowed, source.relation) ?? []),
3582
+ placed: freeze(placed),
3583
+ }),
3584
+ )
3585
+ select(source.table, source.node)
3586
+ if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
3587
+ if (source.when !== undefined) addReach(source.when, select)
3588
+ }
3589
+ for (let position = 0; position < model.access.length; position++) {
3590
+ const access = model.access[position]
3591
+ if (access === undefined) continue
3592
+ select(access.view, access.row)
3593
+ }
3594
+ for (let position = 0; position < model.readThrough.length; position++) {
3595
+ const path = model.readThrough[position]
3596
+ if (path === undefined) continue
3597
+ select(path.table, path.key)
3598
+ if (path.via !== undefined) select(path.via.table, path.via.key)
3599
+ for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
3600
+ }
3601
+ const actions = ownKeys(model.when)
3602
+ for (let position = 0; position < actions.length; position++) {
3603
+ const condition = ownEntry(model.when, actions[position] ?? '')
3604
+ if (condition !== undefined) addReach(condition, select)
3605
+ }
3606
+ }
3607
+ // A relation no table confers is served by the access views alone; a table that confers it adds them to its source.
3608
+ for (let index = 0; index < names.length; index++) {
3609
+ const model = modelOf(models, names[index] ?? '')
3610
+ for (let position = 0; model !== undefined && position < model.access.length; position++) {
3611
+ const access = model.access[position]
3612
+ if (access === undefined || ownEntry(relations, access.relation) !== undefined) continue
3613
+ const relation = access.relation
3614
+ setOwn(
3615
+ relations,
3616
+ relation,
3617
+ freeze({ kind: 'access', relation, dimension: access.dimension, narrowed: freeze(ownEntry(narrowed, relation) ?? []) }),
3618
+ )
3619
+ }
3620
+ }
3621
+ const subqueries: Record<string, readonly string[]> = {}
3622
+ const tablesRead = ownKeys(selected)
3623
+ for (let index = 0; index < tablesRead.length; index++) {
3624
+ const table = tablesRead[index] ?? ''
3625
+ setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
3626
+ }
3627
+ const revealing: Record<string, readonly MemberRevealModel[]> = {}
3628
+ const sources = ownKeys(members)
3629
+ for (let index = 0; index < sources.length; index++) {
3630
+ const source = sources[index] ?? ''
3631
+ setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
3632
+ }
3633
+ return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
3634
+ }
3635
+
3636
+ /** `model`'s column for each dimension a row of it lies at: its key at its own dimension, then each link of its chain. */
3637
+ function placementOf(model: TableModel): Readonly<Record<string, string>> {
3638
+ const placed: Record<string, string> = {}
3639
+ if (model.scope.mode === 'dimension') setOwn(placed, model.scope.dimension, model.scope.key)
3640
+ for (let index = 0; index < model.chain.length; index++) {
3641
+ const link = model.chain[index]
3642
+ if (link !== undefined && ownEntry(placed, link.dimension) === undefined) setOwn(placed, link.dimension, link.column)
3643
+ }
3644
+ return freeze(placed)
3645
+ }
3646
+
3647
+ function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
3648
+ conditionReach(condition, select)
3649
+ }
3650
+
2221
3651
  /** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
2222
3652
  function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
2223
3653
  const side = frameworkSideOf(database)
@@ -2260,6 +3690,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
2260
3690
  return undefined
2261
3691
  }
2262
3692
 
3693
+ /**
3694
+ * Whether an access view of `relation` lists `node` for `principal`: a guarded select of the row of the table that owns
3695
+ * the relation's dimension, by its key, under the access term. Only a principal-bound view answers; one bound to a
3696
+ * member node lists nothing for a hold anywhere, which is all `relates` asks about.
3697
+ */
3698
+ async function accessHolds(
3699
+ models: TableModels,
3700
+ subqueries: Readonly<Record<string, readonly string[]>>,
3701
+ runtime: DataLayerRuntime,
3702
+ relation: string,
3703
+ dimension: string,
3704
+ node: string,
3705
+ principal: string,
3706
+ ): Promise<boolean> {
3707
+ const names = ownKeys(models)
3708
+ for (let index = 0; index < names.length; index++) {
3709
+ const model = modelOf(models, names[index] ?? '')
3710
+ if (model === undefined || model.scope.mode !== 'dimension' || model.scope.dimension !== dimension) continue
3711
+ const terms = relationTerms(
3712
+ { [relation]: freeze({ kind: 'access', relation, dimension, narrowed: freeze([]) }) },
3713
+ model,
3714
+ { relation, inside: null },
3715
+ principal,
3716
+ '',
3717
+ new Date(),
3718
+ noPath,
3719
+ )
3720
+ if (terms.length === 0) continue
3721
+ const scope = AndNode.create(equals(model.name, keyOf(model), node), anyOf(terms))
3722
+ const context: GuardContext = { root: 'SelectQueryNode', table: model.name, joins: {}, scope, subqueries }
3723
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(model.name, [keyOf(model)], scope), context)
3724
+ if (rows.length > 0) return true
3725
+ }
3726
+ return false
3727
+ }
3728
+
2263
3729
  /** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
2264
3730
  function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2265
3731
  const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
@@ -2269,6 +3735,298 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2269
3735
  return owner
2270
3736
  }
2271
3737
 
3738
+ /** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
3739
+ async function relationHolds(
3740
+ models: TableModels,
3741
+ relations: RelationSources,
3742
+ subqueries: Readonly<Record<string, readonly string[]>>,
3743
+ runtime: DataLayerRuntime,
3744
+ relation: string,
3745
+ node: string,
3746
+ principal: string,
3747
+ ): Promise<boolean> {
3748
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3749
+ throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
3750
+ }
3751
+ const known = knownRelation(relations, relation)
3752
+ if (known.kind === 'access') {
3753
+ return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
3754
+ }
3755
+ const source = relationSource(relations, relation)
3756
+ const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
3757
+ const active = activeRow(source, new Date())
3758
+ const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
3759
+ const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
3760
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
3761
+ // A relation with a source table may also name access views: the same term answers through them.
3762
+ return rows.length > 0 || accessHolds(models, subqueries, runtime, relation, source.dimension, node, principal)
3763
+ }
3764
+
3765
+ /**
3766
+ * Locks the first row that holds `grant`'s action for its principal at its object or a container on its chain, if any:
3767
+ * a source row naming it there, a row the relation reaches that reveals that node, or a row at a node the Ref's
3768
+ * revealing grants name that reveals it to its members.
3769
+ */
3770
+ async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
3771
+ const now = new Date()
3772
+ const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
3773
+ const candidates: { table: string; column: string; scope: OperationNode }[] = []
3774
+ for (let index = 0; index < grant.revealing.length; index++) {
3775
+ const revealing = grant.revealing[index]
3776
+ const reveals = revealing === undefined ? [] : ownEntry(context.members, revealing.dimension) ?? []
3777
+ for (let position = 0; revealing !== undefined && position < reveals.length; position++) {
3778
+ const reveal = reveals[position]
3779
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3780
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3781
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3782
+ if (reveal === undefined || revealed === undefined || revealing.values.length === 0) continue
3783
+ candidates[candidates.length] = { table: reveal.table, column: reveal.key, scope: memberAddress(reveal, revealing.values, revealed, now) }
3784
+ }
3785
+ }
3786
+ for (let index = 0; index < grant.relations.length; index++) {
3787
+ const hold = grant.relations[index]
3788
+ // An access view's base rows are not the data layer's to lock (ADR-0076): such a hold holds no destination here.
3789
+ if (hold === undefined || knownRelation(context.relations, hold.relation).kind === 'access') continue
3790
+ const source = relationSource(context.relations, hold.relation)
3791
+ const node = nodeOf(source.dimension)
3792
+ const sourceInside = insideRow(source, source.table, hold)
3793
+ if (node !== undefined && sourceInside !== null) {
3794
+ const parts = [equals(source.table, source.node, node), namesPrincipal(source, grant.principal)]
3795
+ if (sourceInside !== undefined) parts[parts.length] = sourceInside
3796
+ const address = allOf(parts)
3797
+ const active = activeRow(source, now)
3798
+ candidates[candidates.length] = {
3799
+ table: source.table,
3800
+ column: source.node,
3801
+ scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
3802
+ }
3803
+ }
3804
+ for (let position = 0; position < source.reveals.length; position++) {
3805
+ const reveal = source.reveals[position]
3806
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3807
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3808
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3809
+ const revealInside = reveal === undefined ? null : insideRow(source, reveal.table, hold)
3810
+ if (reveal !== undefined && revealed !== undefined && revealInside !== null) {
3811
+ const address = revealAddress(source, reveal, revealed, grant.principal, now)
3812
+ candidates[candidates.length] = {
3813
+ table: reveal.table,
3814
+ column: reveal.column,
3815
+ scope: revealInside === undefined ? address : allOf([address, revealInside]),
3816
+ }
3817
+ }
3818
+ }
3819
+ }
3820
+ for (let position = 0; position < candidates.length; position++) {
3821
+ const candidate = candidates[position]
3822
+ if (candidate === undefined) continue
3823
+ const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
3824
+ root: 'SelectQueryNode',
3825
+ table: candidate.table,
3826
+ joins: {},
3827
+ scope: candidate.scope,
3828
+ lock: 'share',
3829
+ subqueries: context.subqueries,
3830
+ })
3831
+ if (rows.length > 0) return true
3832
+ }
3833
+ return false
3834
+ }
3835
+
3836
+ /**
3837
+ * What a row of `table` (the relation's source or a reveal's table) must meet to hold under `hold`: nothing
3838
+ * (`undefined`) for a hold anywhere, its column for the hold's dimension among the hold's values for one inside a node,
3839
+ * and null when it has no such column, so it is not inside and holds nothing.
3840
+ */
3841
+ function insideRow(source: LayerRelation, table: string, hold: RelationHold): OperationNode | undefined | null {
3842
+ if (hold.inside === null) {
3843
+ return undefined
3844
+ }
3845
+ const placed = ownEntry(source.placed, table)
3846
+ const column = placed === undefined ? undefined : ownEntry(placed, hold.inside.dimension)
3847
+ return column === undefined || hold.inside.values.length === 0 ? null : isIn(table, column, valueList(hold.inside.values))
3848
+ }
3849
+
3850
+ /** `R.<ancestor> = $node and (R.<key> in (values) and <when>)`: a row at a node `values` name that reveals `node` now. */
3851
+ function memberAddress(reveal: MemberRevealModel, values: readonly string[], node: string, now: Date): OperationNode {
3852
+ const named = inList(reveal.table, reveal.key, values)
3853
+ const held = reveal.when === undefined ? named : allOf([named, conditionNode(reveal.table, reveal.when, now)])
3854
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(held))
3855
+ }
3856
+
3857
+ /** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
3858
+ function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
3859
+ const revealed = BinaryOperationNode.create(
3860
+ column(reveal.table, reveal.column),
3861
+ OperatorNode.create('in'),
3862
+ revealedNodes(source, reveal, principal, now),
3863
+ )
3864
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
3865
+ }
3866
+
3867
+ /** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
3868
+ async function revealHolds(
3869
+ relations: RelationSources,
3870
+ subqueries: Readonly<Record<string, readonly string[]>>,
3871
+ runtime: DataLayerRuntime,
3872
+ relation: string,
3873
+ dimension: string,
3874
+ node: string,
3875
+ principal: string,
3876
+ action: string,
3877
+ ): Promise<boolean> {
3878
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3879
+ throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
3880
+ }
3881
+ const source = relationSource(relations, relation)
3882
+ for (let index = 0; index < source.reveals.length; index++) {
3883
+ const reveal = source.reveals[index]
3884
+ // A reveal matched through a secondary path holds a Ref's action only where the path holds it (`writeThrough`).
3885
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3886
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3887
+ const address = revealAddress(source, reveal, node, principal, new Date())
3888
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
3889
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
3890
+ if (rows.length > 0) return true
3891
+ }
3892
+ return false
3893
+ }
3894
+
3895
+ /**
3896
+ * Of `values`, nodes of `revealing` at which the caller holds `action`, the ones whose row reveals `node` of `dimension`
3897
+ * for it now: one guarded select per member reveal of `revealing` to `dimension` that lists `action`.
3898
+ */
3899
+ async function membersRevealed(
3900
+ members: MemberReveals,
3901
+ subqueries: Readonly<Record<string, readonly string[]>>,
3902
+ runtime: DataLayerRuntime,
3903
+ revealing: string,
3904
+ values: readonly string[],
3905
+ dimension: string,
3906
+ node: string,
3907
+ action: string,
3908
+ ): Promise<readonly string[]> {
3909
+ if (typeof node !== 'string' || node.length === 0 || !isArray(values) || values.length > MAX_WITHIN_VALUES) {
3910
+ throw new QueryRefusedError('row_address', `a node ${revealing} reveals is addressed by its node and at most ${MAX_WITHIN_VALUES} grants`)
3911
+ }
3912
+ for (let index = 0; index < values.length; index++) {
3913
+ if (typeof values[index] !== 'string' || values[index] === '') {
3914
+ throw new QueryRefusedError('row_address', `a grant at ${revealing} names its node, a non-empty string`)
3915
+ }
3916
+ }
3917
+ const reveals = ownEntry(members, revealing) ?? []
3918
+ const found: string[] = []
3919
+ for (let index = 0; values.length > 0 && index < reveals.length; index++) {
3920
+ const reveal = reveals[index]
3921
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3922
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3923
+ const scope = memberAddress(reveal, values, node, new Date())
3924
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope, subqueries }
3925
+ // Grouped, not limited: through a path many rows name one grant's node, and every grant matched is carried.
3926
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(valuesNode(reveal.table, reveal.key, scope), context)
3927
+ for (let position = 0; position < rows.length; position++) {
3928
+ const key = ownEntry(rows[position] ?? {}, reveal.key)
3929
+ if (typeof key === 'string' && !includes(found, key)) found[found.length] = key
3930
+ }
3931
+ }
3932
+ return freeze(found)
3933
+ }
3934
+
3935
+ /**
3936
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
3937
+ * through a relation row, a reveal or a secondary path that holds the action for a `Ref` (`writeThrough`): one guarded
3938
+ * select per candidate. What `on` and `in` mint a `Ref` held through a path with, and through a relation held inside a
3939
+ * node: the statement compares the object's column for the node's dimension with the held values, and the relation
3940
+ * comes back held inside the node that column stores, so every spelling the database equates is one node.
3941
+ */
3942
+ async function heldThroughPaths(
3943
+ models: TableModels,
3944
+ layer: ReturnType<typeof layerReach>,
3945
+ runtime: DataLayerRuntime,
3946
+ dimension: string,
3947
+ id: string,
3948
+ action: string,
3949
+ principal: string,
3950
+ relations: readonly RelationHold[],
3951
+ paths: readonly ContainerGrant[],
3952
+ ): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }> {
3953
+ const owner = locatedOwner(models, dimension)
3954
+ if (typeof id !== 'string' || id.length === 0 || typeof principal !== 'string' || principal.length === 0 || typeof action !== 'string') {
3955
+ throw new QueryRefusedError('row_address', `a ${dimension} held through a path is addressed by its key, the principal and the action`)
3956
+ }
3957
+ let count = 0
3958
+ const grantOf = (grant: unknown, what: string): ContainerGrant => {
3959
+ const at: unknown = typeof grant === 'object' && grant !== null ? ownDescriptor(grant, 'dimension')?.value : undefined
3960
+ const values = typeof grant === 'object' && grant !== null
3961
+ ? parseList(ownDescriptor(grant, 'values')?.value, (value) => {
3962
+ if (typeof value !== 'string' || value === '') throw new QueryRefusedError('row_address', 'a grant names its node, a non-empty string')
3963
+ return value
3964
+ })
3965
+ : undefined
3966
+ if (typeof at !== 'string' || values === undefined) {
3967
+ throw new QueryRefusedError('row_address', `${what} names its dimension and its nodes`)
3968
+ }
3969
+ count += values.length
3970
+ return freeze({ dimension: at, values: freeze(values) })
3971
+ }
3972
+ const named = parseList(relations, (hold): RelationHold => {
3973
+ const relation: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'relation')?.value : undefined
3974
+ const inside: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'inside')?.value : undefined
3975
+ if (typeof relation !== 'string') throw new QueryRefusedError('row_address', 'a relation is named by its name')
3976
+ return freeze({ relation, inside: inside === null ? null : grantOf(inside, 'a relation held inside a node') })
3977
+ })
3978
+ const grants = parseList(paths, (grant): ContainerGrant => grantOf(grant, 'a grant of a path'))
3979
+ if (named === undefined || grants === undefined) {
3980
+ throw new QueryRefusedError('row_address', 'the candidates of a path are plain arrays')
3981
+ }
3982
+ if (count > MAX_WITHIN_VALUES) {
3983
+ throw new QueryRefusedError('row_address', `the grants of a path carry at most ${MAX_WITHIN_VALUES} nodes`)
3984
+ }
3985
+ const now = new Date()
3986
+ const session = sessionOf(runtime)
3987
+ const reached = async (
3988
+ terms: readonly OperationNode[],
3989
+ column: string,
3990
+ inside?: readonly string[],
3991
+ ): Promise<Readonly<Record<string, unknown>> | undefined> => {
3992
+ if (terms.length === 0) return undefined
3993
+ const found = AndNode.create(equals(owner.name, keyOf(owner), id), anyOf(terms))
3994
+ // A member-bound access term is not narrowed to the node (ADR-0076): the object's own column is, as the database compares it.
3995
+ const scope = inside === undefined ? found : AndNode.create(found, ParensNode.create(isIn(owner.name, column, valueList(inside))))
3996
+ const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, subqueries: layer.subqueries }
3997
+ const columns = column === keyOf(owner) ? [column] : [keyOf(owner), column]
3998
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
3999
+ return row
4000
+ }
4001
+ const held: RelationHold[] = []
4002
+ for (let index = 0; index < named.length; index++) {
4003
+ const hold = named[index]
4004
+ if (hold === undefined) continue
4005
+ const column = hold.inside === null ? keyOf(owner) : nodeColumnOf(owner, hold.inside.dimension)
4006
+ const row = column === undefined
4007
+ ? undefined
4008
+ : await reached(relationTerms(layer.relations, owner, hold, principal, action, now, heldThrough(action)), column, hold.inside?.values)
4009
+ if (row === undefined || column === undefined) continue
4010
+ if (hold.inside === null) {
4011
+ held[held.length] = hold
4012
+ continue
4013
+ }
4014
+ const node = ownEntry(row, column)
4015
+ if (typeof node !== 'string') {
4016
+ throw new PolicyError(`${owner.name}.${column} came back as ${typeof node}; a containment column holds its scope value as text`)
4017
+ }
4018
+ held[held.length] = freeze({ relation: hold.relation, inside: freeze({ dimension: hold.inside.dimension, values: freeze([node]) }) })
4019
+ }
4020
+ const through: ContainerGrant[] = []
4021
+ for (let index = 0; index < grants.length; index++) {
4022
+ const grant = grants[index]
4023
+ if (grant !== undefined && (await reached(pathTerms(owner, [grant], heldThrough(action)), keyOf(owner))) !== undefined) {
4024
+ through[through.length] = grant
4025
+ }
4026
+ }
4027
+ return freeze({ relations: freeze(held), paths: freeze(through) })
4028
+ }
4029
+
2272
4030
  /** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
2273
4031
  async function locateObject(
2274
4032
  models: TableModels,
@@ -2281,6 +4039,11 @@ async function locateObject(
2281
4039
  if (typeof id !== 'string' || id.length === 0) {
2282
4040
  throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
2283
4041
  }
4042
+ return chainOf(owner, using ?? sessionOf(runtime), id)
4043
+ }
4044
+
4045
+ /** The containers of `owner`'s row keyed `id`, by dimension, read in `session`; `null` for no such row. */
4046
+ async function chainOf(owner: TableModel, session: Session, id: string): Promise<ReadonlyMap<string, string> | null> {
2284
4047
  const key = keyOf(owner)
2285
4048
  const scope = equals(owner.name, key, id)
2286
4049
  const columns: string[] = [key]
@@ -2288,7 +4051,7 @@ async function locateObject(
2288
4051
  columns[columns.length] = owner.chain[index]?.column ?? ''
2289
4052
  }
2290
4053
  const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
2291
- const [row] = await (using ?? sessionOf(runtime)).run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
4054
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
2292
4055
  if (row === undefined) {
2293
4056
  return null
2294
4057
  }