@latticecms/core 0.1.0 → 0.3.0

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 (83) hide show
  1. package/README.md +183 -60
  2. package/dist/access.d.ts +2 -3
  3. package/dist/access.d.ts.map +1 -1
  4. package/dist/access.js +21 -5
  5. package/dist/access.js.map +1 -1
  6. package/dist/build.d.ts +52 -4
  7. package/dist/build.d.ts.map +1 -1
  8. package/dist/build.js +78 -21
  9. package/dist/build.js.map +1 -1
  10. package/dist/collection.d.ts.map +1 -1
  11. package/dist/collection.js +12 -5
  12. package/dist/collection.js.map +1 -1
  13. package/dist/crud.d.ts +24 -8
  14. package/dist/crud.d.ts.map +1 -1
  15. package/dist/crud.js +47 -59
  16. package/dist/crud.js.map +1 -1
  17. package/dist/errors.d.ts +5 -1
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +5 -1
  20. package/dist/errors.js.map +1 -1
  21. package/dist/family.js +15 -19
  22. package/dist/family.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/mask.d.ts +11 -11
  27. package/dist/mask.d.ts.map +1 -1
  28. package/dist/mask.js +24 -2
  29. package/dist/mask.js.map +1 -1
  30. package/dist/populate.d.ts +9 -2
  31. package/dist/populate.d.ts.map +1 -1
  32. package/dist/populate.js +3 -4
  33. package/dist/populate.js.map +1 -1
  34. package/dist/relations.d.ts +2 -1
  35. package/dist/relations.d.ts.map +1 -1
  36. package/dist/relations.js +18 -2
  37. package/dist/relations.js.map +1 -1
  38. package/dist/repo.d.ts +1 -1
  39. package/dist/repo.d.ts.map +1 -1
  40. package/dist/repo.js +15 -6
  41. package/dist/repo.js.map +1 -1
  42. package/dist/sort.d.ts +32 -7
  43. package/dist/sort.d.ts.map +1 -1
  44. package/dist/sort.js +66 -24
  45. package/dist/sort.js.map +1 -1
  46. package/dist/store/conformance.d.ts.map +1 -1
  47. package/dist/store/conformance.js +146 -5
  48. package/dist/store/conformance.js.map +1 -1
  49. package/dist/store/index.d.ts +1 -1
  50. package/dist/store/index.d.ts.map +1 -1
  51. package/dist/store/index.js +1 -1
  52. package/dist/store/index.js.map +1 -1
  53. package/dist/store.d.ts +6 -0
  54. package/dist/store.d.ts.map +1 -1
  55. package/dist/store.js +1 -1
  56. package/dist/store.js.map +1 -1
  57. package/dist/where.d.ts +3 -1
  58. package/dist/where.d.ts.map +1 -1
  59. package/dist/where.js +31 -5
  60. package/dist/where.js.map +1 -1
  61. package/package.json +12 -11
  62. package/skills/lattice/SKILL.md +2 -2
  63. package/skills/lattice/references/access.md +19 -5
  64. package/skills/lattice/references/collection.md +4 -1
  65. package/skills/lattice/references/method.md +3 -0
  66. package/skills/lattice/references/override.md +89 -6
  67. package/skills/lattice/references/relations.md +3 -2
  68. package/src/access.ts +24 -4
  69. package/src/build.ts +214 -48
  70. package/src/collection.ts +12 -5
  71. package/src/crud.ts +74 -72
  72. package/src/errors.ts +5 -1
  73. package/src/family.ts +21 -21
  74. package/src/index.ts +2 -0
  75. package/src/mask.ts +31 -2
  76. package/src/populate.ts +11 -4
  77. package/src/relations.ts +19 -2
  78. package/src/repo.ts +16 -7
  79. package/src/sort.ts +92 -35
  80. package/src/store/conformance.ts +193 -4
  81. package/src/store/index.ts +7 -1
  82. package/src/store.ts +7 -1
  83. package/src/where.ts +36 -9
package/src/build.ts CHANGED
@@ -50,8 +50,9 @@ import {
50
50
  import {
51
51
  type EventPublisher,
52
52
  type Executable,
53
- generated,
54
- generatedRelation,
53
+ generatedUseCase,
54
+ operationBody,
55
+ relationBody,
55
56
  } from './crud.js';
56
57
  import { type EffectOf, generatedMeta, methodMeta } from './describe.js';
57
58
  import {
@@ -76,8 +77,8 @@ import {
76
77
  } from './mask.js';
77
78
  import {
78
79
  expansionOf,
80
+ populateInput,
79
81
  populateKeys,
80
- populateShape,
81
82
  type Withheld,
82
83
  } from './populate.js';
83
84
  import { type CascadeFields, type RefSlugs, referrersOf } from './relations.js';
@@ -170,6 +171,23 @@ type Ops<Col extends AnyCollection> = Operations<
170
171
  TenantField<Col>
171
172
  >;
172
173
 
174
+ /**
175
+ * What a collection's create takes: its input schema's input type, so a
176
+ * defaulted field may be left out. An override of create declares it.
177
+ */
178
+ export type CreateInput<C extends AnyCollection> = z.input<
179
+ Ops<C>['create']['input']
180
+ >;
181
+
182
+ /**
183
+ * What a collection's update takes: the `id`, and each field to change. It
184
+ * applies no defaults, and `null` clears an optional field with no default.
185
+ * An override of update declares it.
186
+ */
187
+ export type UpdateInput<C extends AnyCollection> = z.input<
188
+ Ops<C>['update']['input']
189
+ >;
190
+
173
191
  /**
174
192
  * What a client receives from operation `A` of `Col`: its documents as
175
193
  * `clientOutput`, each maskable field optional.
@@ -668,8 +686,58 @@ type Instances<E extends Entries, Kind extends 'methods' | 'overrides', Ctx> = {
668
686
  /** Each collection's repo, by slug. */
669
687
  type Repos<E extends Entries> = { [S in keyof E]: Repo<E[S]['collection']> };
670
688
 
671
- /** What an instance factory receives: what exists before the use cases. */
672
- type Wiring<E extends Entries> = { readonly repos: Repos<E> };
689
+ /**
690
+ * A generated operation's body, as an override calls it: the operation
691
+ * without the family's guards, logging and spans, which the override's own
692
+ * use case has run (0036). Typed as a direct caller sees the generated use
693
+ * case.
694
+ */
695
+ type GeneratedBody<
696
+ Schemas_ extends {
697
+ readonly input: z.core.$ZodType;
698
+ readonly output: z.core.$ZodType;
699
+ },
700
+ Ctx,
701
+ > = (
702
+ ctx: Ctx,
703
+ input: z.input<Schemas_['input']>,
704
+ ) => Promise<z.output<Schemas_['output']>>;
705
+
706
+ /**
707
+ * The body of each operation the app overrides, by slug, and of each
708
+ * overridden relation operation by relation name: what an override may
709
+ * call. An operation that is not overridden is not here, so no override
710
+ * reaches another operation's body.
711
+ *
712
+ * The variances are stated, because measuring them instantiates every
713
+ * operation's input and output for a marker `E`, which cost an app over a
714
+ * million instantiations. `Ctx` appears only in parameters, so it is `in`.
715
+ * `E` decides the keys, the inputs and the outputs, so it is invariant: do
716
+ * not loosen it.
717
+ */
718
+ type Generated<in out E extends Entries, in Ctx> = {
719
+ [S in keyof E as [keyof E[S]['overrides']] extends [never] ? never : S]: {
720
+ [A in keyof E[S]['overrides'] & Action]: GeneratedBody<
721
+ Ops<E[S]['collection']>[A],
722
+ Ctx
723
+ >;
724
+ } & {
725
+ [R in keyof E[S]['overrides'] & keyof E[S]['collection']['relations']]: {
726
+ [Op in keyof E[S]['overrides'][R] & RelationOp]: GeneratedBody<
727
+ E[S]['collection']['relations'][R][Op],
728
+ Ctx
729
+ >;
730
+ };
731
+ };
732
+ };
733
+
734
+ /**
735
+ * What an instance factory receives: what exists before the use cases. The
736
+ * overrides factory also receives the generated operations it may call.
737
+ */
738
+ type Wiring<E extends Entries, Kind, Ctx> = Kind extends 'overrides'
739
+ ? { readonly repos: Repos<E>; readonly generated: Generated<E, Ctx> }
740
+ : { readonly repos: Repos<E> };
673
741
 
674
742
  /**
675
743
  * One kind of instance `build()` takes: a factory that returns one instance
@@ -679,9 +747,15 @@ type Wiring<E extends Entries> = { readonly repos: Repos<E> };
679
747
  type Factory<E extends Entries, Kind extends 'methods' | 'overrides', Ctx> = [
680
748
  keyof Instances<E, Kind, Ctx>,
681
749
  ] extends [never]
682
- ? { readonly [K in Kind]?: (wiring: Wiring<E>) => Record<never, never> }
750
+ ? {
751
+ readonly [K in Kind]?: (
752
+ wiring: Wiring<E, Kind, Ctx>,
753
+ ) => Record<never, never>;
754
+ }
683
755
  : {
684
- readonly [K in Kind]: (wiring: Wiring<E>) => Instances<E, Kind, Ctx>;
756
+ readonly [K in Kind]: (
757
+ wiring: Wiring<E, Kind, Ctx>,
758
+ ) => Instances<E, Kind, Ctx>;
685
759
  };
686
760
 
687
761
  /** What `build()` takes: the ports, and the method and override instances. */
@@ -867,14 +941,22 @@ type RuntimeInstances<Ctx> = Readonly<
867
941
  * signature, so its parameter compares bivariantly with the precise
868
942
  * factory the overload states.
869
943
  */
870
- type FactoryFn<Actor> = {
871
- factory(wiring: RuntimeWiring): RuntimeInstances<FamilyContext<Actor>>;
944
+ type FactoryFn<Actor, W> = {
945
+ factory(wiring: W): RuntimeInstances<FamilyContext<Actor>>;
872
946
  }['factory'];
873
947
 
948
+ /** What the methods factory receives, as the implementation builds it. */
874
949
  type RuntimeWiring = {
875
950
  readonly repos: Readonly<Record<string, Repo<AnyCollection>>>;
876
951
  };
877
952
 
953
+ /** What the overrides factory receives: also each overridden body. */
954
+ type RuntimeOverrideWiring = RuntimeWiring & {
955
+ readonly generated: Readonly<
956
+ Record<string, Readonly<Record<string, unknown>>>
957
+ >;
958
+ };
959
+
878
960
  /**
879
961
  * An app's definition: its family, its error map and its collections, with
880
962
  * the methods and overrides attached to them. It holds no ports, so its
@@ -1102,8 +1184,8 @@ export class Framework<
1102
1184
  readonly store: CollectionStore;
1103
1185
  readonly events: EventPublisher;
1104
1186
  readonly access?: Access<Actor>;
1105
- readonly methods?: FactoryFn<Actor>;
1106
- readonly overrides?: FactoryFn<Actor>;
1187
+ readonly methods?: FactoryFn<Actor, RuntimeWiring>;
1188
+ readonly overrides?: FactoryFn<Actor, RuntimeOverrideWiring>;
1107
1189
  }): {
1108
1190
  readonly app: ImplementedRouter<unknown, CallContext<Actor>>;
1109
1191
  readonly useCases: Readonly<
@@ -1140,9 +1222,106 @@ export class Framework<
1140
1222
  repo(store, collection),
1141
1223
  ]),
1142
1224
  );
1143
- const methodInstances = options.methods?.({ repos });
1144
- const overrideInstances = options.overrides?.({ repos });
1145
1225
  type Ctx = FamilyContext<Actor>;
1226
+ // Every generated operation, with its body and the class that overrides
1227
+ // it, if any: a generated use case runs the body, and an override may
1228
+ // call it as `generated` (0036). Whether an operation is overridden is
1229
+ // decided here, once, for both.
1230
+ const slices = this.entries.flatMap((entry) => {
1231
+ if (entry.join) return [];
1232
+ const { collection, overrides } = entry;
1233
+ const ops = operations(collection.schema, collection.output);
1234
+ const operationsOf = actions.map((action) => {
1235
+ // A read takes `populate`: one schema, for its input and its body.
1236
+ const populate = populateInput(
1237
+ action === 'get' || action === 'find'
1238
+ ? populateKeys(collection, action)
1239
+ : [],
1240
+ );
1241
+ const declared = overrides[action];
1242
+ return {
1243
+ action,
1244
+ input: ops[action].input.extend(populate.shape),
1245
+ body: operationBody(
1246
+ this.family,
1247
+ store,
1248
+ events,
1249
+ collection,
1250
+ ops,
1251
+ action,
1252
+ populate,
1253
+ referrers,
1254
+ collections,
1255
+ ),
1256
+ override: typeof declared === 'function' ? declared : undefined,
1257
+ };
1258
+ });
1259
+ const relations = Object.entries(collection.relations).map(
1260
+ ([name, relation]) => {
1261
+ const declared = overrides[name];
1262
+ const opOverrides =
1263
+ declared === undefined || typeof declared === 'function'
1264
+ ? {}
1265
+ : declared;
1266
+ return {
1267
+ name,
1268
+ relation,
1269
+ ops: relationOps.map((op) => ({
1270
+ op,
1271
+ body: relationBody(
1272
+ this.family,
1273
+ store,
1274
+ events,
1275
+ collection,
1276
+ name,
1277
+ relation,
1278
+ op,
1279
+ collections,
1280
+ ),
1281
+ override: opOverrides[op],
1282
+ })),
1283
+ };
1284
+ },
1285
+ );
1286
+ return [{ entry, ops, operationsOf, relations }];
1287
+ });
1288
+ // Only the overridden operations' bodies: what each override may call.
1289
+ const generatedBodies = Object.fromEntries(
1290
+ slices.flatMap(({ entry, operationsOf, relations }) => {
1291
+ const declared = {
1292
+ ...Object.fromEntries(
1293
+ operationsOf
1294
+ .filter(({ override }) => override !== undefined)
1295
+ .map(({ action, body }) => [action, body]),
1296
+ ),
1297
+ ...Object.fromEntries(
1298
+ relations.flatMap(({ name, ops }) => {
1299
+ const overridden = ops.filter(
1300
+ ({ override }) => override !== undefined,
1301
+ );
1302
+ return overridden.length === 0
1303
+ ? []
1304
+ : [
1305
+ [
1306
+ name,
1307
+ Object.fromEntries(
1308
+ overridden.map(({ op, body }) => [op, body]),
1309
+ ),
1310
+ ],
1311
+ ];
1312
+ }),
1313
+ ),
1314
+ };
1315
+ return Object.keys(declared).length === 0
1316
+ ? []
1317
+ : [[entry.collection.slug, declared]];
1318
+ }),
1319
+ );
1320
+ const methodInstances = options.methods?.({ repos });
1321
+ const overrideInstances = options.overrides?.({
1322
+ repos,
1323
+ generated: generatedBodies,
1324
+ });
1146
1325
  // Each operation and method's use case, and each relation operation's,
1147
1326
  // by slug: the procedures of a slice and its nested relation nodes.
1148
1327
  const operationUseCases: Record<
@@ -1153,30 +1332,24 @@ export class Framework<
1153
1332
  string,
1154
1333
  Record<string, Record<string, Executable<Ctx>>>
1155
1334
  > = {};
1156
- for (const { collection, methods, overrides, join } of this.entries) {
1157
- if (join) continue;
1335
+ for (const { entry, ops, operationsOf, relations } of slices) {
1336
+ const { collection, methods } = entry;
1158
1337
  const { slug } = collection;
1159
1338
  const sliceUseCases: Record<string, Executable<Ctx>> = {};
1160
- const ops = operations(collection.schema, collection.output);
1161
- for (const action of actions) {
1162
- const declared = overrides[action];
1339
+ for (const { action, input, body, override } of operationsOf) {
1163
1340
  sliceUseCases[action] =
1164
- typeof declared === 'function'
1165
- ? instanceOf(
1341
+ override === undefined
1342
+ ? generatedUseCase(
1343
+ this.family,
1344
+ `${slug}.${action}`,
1345
+ { collection, input, output: ops[action].output },
1346
+ body,
1347
+ )
1348
+ : instanceOf(
1166
1349
  'override',
1167
1350
  [slug, action],
1168
- declared,
1351
+ override,
1169
1352
  overrideInstances,
1170
- )
1171
- : generated(
1172
- this.family,
1173
- store,
1174
- events,
1175
- collection,
1176
- ops,
1177
- action,
1178
- referrers,
1179
- collections,
1180
1353
  );
1181
1354
  }
1182
1355
  for (const [name, method] of Object.entries(methods)) {
@@ -1192,25 +1365,16 @@ export class Framework<
1192
1365
  string,
1193
1366
  Record<string, Executable<Ctx>>
1194
1367
  > = {};
1195
- for (const [name, relation] of Object.entries(collection.relations)) {
1196
- const declared = overrides[name];
1368
+ for (const { name, relation, ops: relationOperations } of relations) {
1197
1369
  const opUseCases: Record<string, Executable<Ctx>> = {};
1198
- for (const op of relationOps) {
1199
- const override =
1200
- declared === undefined || typeof declared === 'function'
1201
- ? undefined
1202
- : declared[op];
1370
+ for (const { op, body, override } of relationOperations) {
1203
1371
  opUseCases[op] =
1204
1372
  override === undefined
1205
- ? generatedRelation(
1373
+ ? generatedUseCase(
1206
1374
  this.family,
1207
- store,
1208
- events,
1209
- collection,
1210
- name,
1211
- relation,
1212
- op,
1213
- collections,
1375
+ `${slug}.${name}.${op}`,
1376
+ { collection, ...relation[op] },
1377
+ body,
1214
1378
  )
1215
1379
  : instanceOf(
1216
1380
  'override',
@@ -1412,7 +1576,9 @@ function contractOf(
1412
1576
  }),
1413
1577
  )
1414
1578
  .input(
1415
- ops.get.input.extend(populateShape(populateKeys(collection, 'get'))),
1579
+ ops.get.input.extend(
1580
+ populateInput(populateKeys(collection, 'get')).shape,
1581
+ ),
1416
1582
  )
1417
1583
  .output(wide)
1418
1584
  .expand({ key: 'populate', fields });
@@ -1433,7 +1599,7 @@ function contractOf(
1433
1599
  )
1434
1600
  .input(
1435
1601
  ops.find.input.extend(
1436
- populateShape(populateKeys(collection, 'find')),
1602
+ populateInput(populateKeys(collection, 'find')).shape,
1437
1603
  ),
1438
1604
  )
1439
1605
  .output(page(wide))
package/src/collection.ts CHANGED
@@ -126,8 +126,15 @@ type Output<
126
126
  z.core.$strip
127
127
  >;
128
128
 
129
+ /**
130
+ * The stored document's schema: the schema's fields plus the system and
131
+ * tenant fields. Built from the shape, so an output never carries the
132
+ * schema's object-level refinements: they check input, and Zod 4 refuses to
133
+ * overwrite a key of a refined object, which a populated read and a masked
134
+ * field both do.
135
+ */
129
136
  function outputOf<Shape extends z.core.$ZodShape, Tenant extends string>(
130
- schema: Schema<Shape>,
137
+ shape: Shape,
131
138
  tenant: Tenant | undefined,
132
139
  ): Output<Shape, Tenant> {
133
140
  // Typed, so `extend` infers `Stamped<Tenant>` itself: an anonymous spread
@@ -136,7 +143,7 @@ function outputOf<Shape extends z.core.$ZodShape, Tenant extends string>(
136
143
  ...systemShape,
137
144
  ...tenantShapes(tenant).field,
138
145
  };
139
- return schema.extend(stamped);
146
+ return z.object(shape).extend(stamped);
140
147
  }
141
148
 
142
149
  /**
@@ -188,13 +195,13 @@ function outputsOf(
188
195
  maskable: readonly string[],
189
196
  ): { readonly output: z.ZodObject; readonly clientOutput: z.ZodObject } {
190
197
  if (maskable.length === 0) {
191
- const output = outputOf(schema, tenant);
198
+ const output = outputOf(schema.shape, tenant);
192
199
  return { output, clientOutput: output };
193
200
  }
194
201
  const { stored, client } = maskShapes(slug, schema.shape, maskable);
195
202
  return {
196
- output: outputOf(schema.extend(stored), tenant),
197
- clientOutput: outputOf(schema.extend(client), tenant),
203
+ output: outputOf({ ...schema.shape, ...stored }, tenant),
204
+ clientOutput: outputOf({ ...schema.shape, ...client }, tenant),
198
205
  };
199
206
  }
200
207
 
package/src/crud.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
- import { z } from 'zod';
2
+ import type { z } from 'zod';
3
3
  import { CallAccess } from './access.js';
4
4
  import type {
5
5
  Action,
@@ -14,7 +14,8 @@ import type {
14
14
  import { maxLinks } from './collection.js';
15
15
  import { LatticeError, parse } from './errors.js';
16
16
  import type { Family, FamilyContext } from './family.js';
17
- import { linkFields, populateKeys, populateShape } from './populate.js';
17
+ import { refuseWithheld } from './mask.js';
18
+ import { linkFields, type PopulateInput } from './populate.js';
18
19
  import type { Referrers, RefField } from './relations.js';
19
20
  import { findQuery, stamped, touched } from './repo.js';
20
21
  import type { CollectionStore, StoredDoc } from './store.js';
@@ -50,6 +51,8 @@ type Call = {
50
51
  readonly ops: Operations<AnyShape>;
51
52
  /** The access and tenant filter of this call, for every store call. */
52
53
  readonly scope: AnyWhere | undefined;
54
+ /** What a read's `populate` may name: the schema of that one field. */
55
+ readonly populate: PopulateInput;
53
56
  readonly actorId: string;
54
57
  /** The call's tenant on this collection: what create stamps and events carry. */
55
58
  readonly tenantId: string | undefined;
@@ -63,9 +66,9 @@ type Call = {
63
66
 
64
67
  /**
65
68
  * The filter that limits what a call may see and change (0005): the call's
66
- * access scope. The family's access guard has already asked, so this reads
67
- * its kept answer. Create has no row to filter, and its answer is not kept,
68
- * so it does not ask again.
69
+ * access scope. Asked here, so a body called from another operation's
70
+ * override is still checked (0036); after the family's guard, it reads the
71
+ * kept answer. Create has no row to filter: its body asks with its data.
69
72
  */
70
73
  async function scopeOf(
71
74
  ctx: FamilyContext<unknown>,
@@ -130,7 +133,7 @@ function keyOf(node: Node): string {
130
133
  /** Every document of `collection` matching `where`, page by page. */
131
134
  async function* every(
132
135
  store: CollectionStore,
133
- collection: string,
136
+ collection: AnyCollection,
134
137
  where: AnyWhere,
135
138
  ): AsyncGenerator<StoredDoc> {
136
139
  let after: string | undefined;
@@ -184,7 +187,7 @@ async function planDelete(
184
187
  }
185
188
  continue;
186
189
  }
187
- for await (const doc of every(store, collection.slug, where)) {
190
+ for await (const doc of every(store, collection, where)) {
188
191
  const child = { collection, doc };
189
192
  if (ref.onDelete === 'nullify') {
190
193
  plan.nullifies.push({ ...child, ref, id });
@@ -264,9 +267,6 @@ async function read(
264
267
  return afterRead === undefined ? document : afterRead({ doc: document });
265
268
  }
266
269
 
267
- /** A read's `populate` list. The family guard has checked each key. */
268
- const populateList = z.object({ populate: z.array(z.string()).optional() });
269
-
270
270
  /** What populating a read works with. */
271
271
  type Populating = Pick<Call, 'store' | 'access' | 'collections'>;
272
272
 
@@ -395,7 +395,7 @@ async function withLinks(
395
395
  tenantClause(join, tenantOfDoc(collection, parent)),
396
396
  );
397
397
  const { docs } = await call.store.find(
398
- findQuery(join.slug, { where, limit: maxLinks }),
398
+ findQuery(join, { where, limit: maxLinks }),
399
399
  );
400
400
  const targets = await readable(
401
401
  call,
@@ -424,9 +424,10 @@ const operations: Record<
424
424
  > = {
425
425
  async find(call, raw) {
426
426
  const { where, sort, limit, after } = parse(call.ops.find.input, raw);
427
- const { populate = [] } = parse(populateList, raw);
427
+ await refuseWithheld(call.access, call.collection, 'find', raw);
428
+ const { populate = [] } = parse(call.populate, raw);
428
429
  const page = await call.store.find(
429
- findQuery(call.collection.slug, {
430
+ findQuery(call.collection, {
430
431
  where: both(where, call.scope),
431
432
  sort,
432
433
  limit,
@@ -442,6 +443,7 @@ const operations: Record<
442
443
 
443
444
  async count(call, raw) {
444
445
  const { where } = parse(call.ops.count.input, raw);
446
+ await refuseWithheld(call.access, call.collection, 'count', raw);
445
447
  return {
446
448
  count: await call.store.count(
447
449
  call.collection.slug,
@@ -452,7 +454,7 @@ const operations: Record<
452
454
 
453
455
  async get(call, raw) {
454
456
  const { id } = parse(call.ops.get.input, raw);
455
- const { populate = [] } = parse(populateList, raw);
457
+ const { populate = [] } = parse(call.populate, raw);
456
458
  const doc = await call.store.get(call.collection.slug, id, call.scope);
457
459
  if (doc === null) throw notFound(call, id);
458
460
  const [document] = await populated(call, call.collection, populate, [
@@ -465,6 +467,9 @@ const operations: Record<
465
467
 
466
468
  async create(call, raw) {
467
469
  const input = parse(call.ops.create.input, raw);
470
+ // Create has no scope to filter by, so its access is asked here, with
471
+ // the data it will write.
472
+ await call.access.scope(call.collection, 'create', input);
468
473
  const data = await change(call, { data: input, operation: 'create' });
469
474
  // Stamped after beforeChange, so a hook cannot pick the tenant.
470
475
  const { tenant } = call.collection;
@@ -489,6 +494,7 @@ const operations: Record<
489
494
  // index signature, which would type it unknown.
490
495
  const { id } = parse(call.ops.get.input, raw);
491
496
  const { id: _, ...patch } = parse(call.ops.update.input, raw);
497
+ await refuseWithheld(call.access, call.collection, 'update', patch);
492
498
  const stored = await call.store.get(call.collection.slug, id, call.scope);
493
499
  if (stored === null) throw notFound(call, id);
494
500
  const previous = documentOf(call, stored);
@@ -574,67 +580,74 @@ const operations: Record<
574
580
  },
575
581
  };
576
582
 
577
- /** The generated use case for one operation, in the app's family. */
578
- export function generated<Actor>(
583
+ /**
584
+ * What one generated operation does, from parsing its input to its events:
585
+ * the body its use case runs, and what an override's `generated` calls
586
+ * (0036). It runs no guards, logging or spans; the calling use case has.
587
+ */
588
+ export type Body<Ctx> = (ctx: Ctx, input: unknown) => Promise<unknown>;
589
+
590
+ /** The body of one generated operation. */
591
+ export function operationBody<Actor>(
579
592
  family: Family<Actor>,
580
593
  store: CollectionStore,
581
594
  events: EventPublisher,
582
595
  collection: AnyCollection,
583
596
  ops: Operations<AnyShape>,
584
597
  action: Action,
598
+ populate: PopulateInput,
585
599
  referrers: Referrers,
586
600
  collections: ReadonlyMap<string, AnyCollection>,
587
- ): Executable<FamilyContext<Actor>> {
588
- const { output } = ops[action];
589
- // A read's input takes `populate`, so the family guard checks its keys.
590
- const input =
591
- action === 'get' || action === 'find'
592
- ? ops[action].input.extend(
593
- populateShape(populateKeys(collection, action)),
594
- )
595
- : ops[action].input;
601
+ ): Body<FamilyContext<Actor>> {
596
602
  const run = operations[action];
597
- class Generated extends family(`${collection.slug}.${action}`, {
598
- collection,
599
- input,
600
- output,
601
- }) {
602
- constructor(
603
- private readonly deps: {
604
- store: CollectionStore;
605
- events: EventPublisher;
603
+ return async (ctx, raw) =>
604
+ run(
605
+ {
606
+ store,
607
+ events,
608
+ collection,
609
+ ops,
610
+ scope: await scopeOf(ctx, collection, action),
611
+ populate,
612
+ actorId: family.actorId(ctx.actor),
613
+ tenantId: CallAccess.stampOf(ctx.access, collection),
614
+ referrers,
615
+ access: ctx.access,
616
+ collections,
606
617
  },
607
- ) {
608
- super();
609
- }
618
+ raw,
619
+ );
620
+ }
610
621
 
622
+ /**
623
+ * A generated use case, an operation's or a relation operation's, in the
624
+ * app's family: its guards, logging and span around `body`.
625
+ */
626
+ export function generatedUseCase<Actor>(
627
+ family: Family<Actor>,
628
+ token: string,
629
+ spec: {
630
+ readonly collection: AnyCollection;
631
+ readonly input: z.core.$ZodType;
632
+ readonly output: z.core.$ZodType;
633
+ },
634
+ body: Body<FamilyContext<Actor>>,
635
+ ): Executable<FamilyContext<Actor>> {
636
+ class Generated extends family(token, spec) {
611
637
  async execute(ctx: FamilyContext<Actor>, raw: unknown): Promise<unknown> {
612
- return run(
613
- {
614
- ...this.deps,
615
- collection,
616
- ops,
617
- scope: await scopeOf(ctx, collection, action),
618
- actorId: family.actorId(ctx.actor),
619
- tenantId: CallAccess.stampOf(ctx.access, collection),
620
- referrers,
621
- access: ctx.access,
622
- collections,
623
- },
624
- raw,
625
- );
638
+ return body(ctx, raw);
626
639
  }
627
640
  }
628
- return new Generated({ store, events });
641
+ return new Generated();
629
642
  }
630
643
 
631
644
  /**
632
- * A generated relation operation of `collection`: `<slug>.<name>.list` or
633
- * `.set`, in the app's family. `list` runs the parent's read and `set` its
634
- * update (0028): each first gets the parent under that scope, so a parent
635
- * outside it is NOT_FOUND.
645
+ * The body of a relation operation of `collection`: `<slug>.<name>.list` or
646
+ * `.set`. `list` runs the parent's read and `set` its update (0028): each
647
+ * first gets the parent under that scope, so a parent outside it is
648
+ * NOT_FOUND.
636
649
  */
637
- export function generatedRelation<Actor>(
650
+ export function relationBody<Actor>(
638
651
  family: Family<Actor>,
639
652
  store: CollectionStore,
640
653
  events: EventPublisher,
@@ -643,8 +656,7 @@ export function generatedRelation<Actor>(
643
656
  relation: AnyRelation,
644
657
  op: 'list' | 'set',
645
658
  collections: ReadonlyMap<string, AnyCollection>,
646
- ): Executable<FamilyContext<Actor>> {
647
- const { input, output } = relation[op];
659
+ ): Body<FamilyContext<Actor>> {
648
660
  const join = relation.through;
649
661
  const { parentField, targetField } = relation;
650
662
  // The fields of a link, as `set` compares them.
@@ -676,7 +688,7 @@ export function generatedRelation<Actor>(
676
688
  );
677
689
  const parent = await parentOf(ctx, id);
678
690
  const page = await store.find(
679
- findQuery(join.slug, {
691
+ findQuery(join, {
680
692
  where: both(where, linksOf(id, tenantOfDoc(collection, parent))),
681
693
  sort,
682
694
  limit,
@@ -704,7 +716,7 @@ export function generatedRelation<Actor>(
704
716
  // and createdAt, and each change owes its own event, after the commit.
705
717
  const { docs, owed } = await store.transaction(async (tx) => {
706
718
  const existing: StoredDoc[] = [];
707
- for await (const doc of every(tx, join.slug, linksOf(id, tenantId))) {
719
+ for await (const doc of every(tx, join, linksOf(id, tenantId))) {
708
720
  existing.push(doc);
709
721
  }
710
722
  const byTarget = new Map(existing.map((doc) => [doc[targetField], doc]));
@@ -777,17 +789,7 @@ export function generatedRelation<Actor>(
777
789
  return { docs: docs.map((doc) => documentOf({ collection: join }, doc)) };
778
790
  }
779
791
 
780
- const run = op === 'list' ? list : set;
781
- class GeneratedRelation extends family(`${collection.slug}.${name}.${op}`, {
782
- collection,
783
- input,
784
- output,
785
- }) {
786
- async execute(ctx: FamilyContext<Actor>, raw: unknown): Promise<unknown> {
787
- return run(ctx, raw);
788
- }
789
- }
790
- return new GeneratedRelation();
792
+ return op === 'list' ? list : set;
791
793
  }
792
794
 
793
795
  function notFoundIn(collection: AnyCollection, id: string) {