@latticecms/core 0.0.0 → 0.1.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 (113) hide show
  1. package/README.md +1174 -2
  2. package/dist/access.d.ts +210 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +225 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +507 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +598 -0
  9. package/dist/build.js.map +1 -0
  10. package/dist/collection.d.ts +480 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +344 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +30 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +539 -0
  17. package/dist/crud.js.map +1 -0
  18. package/dist/describe.d.ts +89 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +119 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/errors.d.ts +179 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +146 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/family.d.ts +80 -0
  27. package/dist/family.d.ts.map +1 -0
  28. package/dist/family.js +231 -0
  29. package/dist/family.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +10 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/marker.d.ts +15 -0
  35. package/dist/marker.d.ts.map +1 -0
  36. package/dist/marker.js +28 -0
  37. package/dist/marker.js.map +1 -0
  38. package/dist/mask.d.ts +69 -0
  39. package/dist/mask.d.ts.map +1 -0
  40. package/dist/mask.js +255 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +32 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +73 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +143 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +128 -0
  49. package/dist/relations.js.map +1 -0
  50. package/dist/repo.d.ts +99 -0
  51. package/dist/repo.d.ts.map +1 -0
  52. package/dist/repo.js +83 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +61 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +145 -0
  57. package/dist/sort.js.map +1 -0
  58. package/dist/store/conformance.d.ts +15 -0
  59. package/dist/store/conformance.d.ts.map +1 -0
  60. package/dist/store/conformance.js +683 -0
  61. package/dist/store/conformance.js.map +1 -0
  62. package/dist/store/index.d.ts +9 -0
  63. package/dist/store/index.d.ts.map +1 -0
  64. package/dist/store/index.js +8 -0
  65. package/dist/store/index.js.map +1 -0
  66. package/dist/store.d.ts +113 -0
  67. package/dist/store.d.ts.map +1 -0
  68. package/dist/store.js +176 -0
  69. package/dist/store.js.map +1 -0
  70. package/dist/tenancy.d.ts +66 -0
  71. package/dist/tenancy.d.ts.map +1 -0
  72. package/dist/tenancy.js +69 -0
  73. package/dist/tenancy.js.map +1 -0
  74. package/dist/tracing.d.ts +12 -0
  75. package/dist/tracing.d.ts.map +1 -0
  76. package/dist/tracing.js +27 -0
  77. package/dist/tracing.js.map +1 -0
  78. package/dist/where.d.ts +95 -0
  79. package/dist/where.d.ts.map +1 -0
  80. package/dist/where.js +308 -0
  81. package/dist/where.js.map +1 -0
  82. package/package.json +79 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +76 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +91 -0
  87. package/skills/lattice/references/event-handler.md +88 -0
  88. package/skills/lattice/references/masking.md +72 -0
  89. package/skills/lattice/references/method.md +85 -0
  90. package/skills/lattice/references/override.md +77 -0
  91. package/skills/lattice/references/relations.md +90 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +429 -0
  95. package/src/build.ts +1722 -0
  96. package/src/collection.ts +1018 -0
  97. package/src/crud.ts +795 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +170 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +42 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +307 -0
  104. package/src/populate.ts +96 -0
  105. package/src/relations.ts +353 -0
  106. package/src/repo.ts +209 -0
  107. package/src/sort.ts +214 -0
  108. package/src/store/conformance.ts +1007 -0
  109. package/src/store/index.ts +16 -0
  110. package/src/store.ts +309 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
package/src/crud.ts ADDED
@@ -0,0 +1,795 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { z } from 'zod';
3
+ import { CallAccess } from './access.js';
4
+ import type {
5
+ Action,
6
+ AnyCollection,
7
+ AnyRelation,
8
+ ChangeArgs,
9
+ Data,
10
+ Document,
11
+ Events,
12
+ Operations,
13
+ } from './collection.js';
14
+ import { maxLinks } from './collection.js';
15
+ import { LatticeError, parse } from './errors.js';
16
+ import type { Family, FamilyContext } from './family.js';
17
+ import { linkFields, populateKeys, populateShape } from './populate.js';
18
+ import type { Referrers, RefField } from './relations.js';
19
+ import { findQuery, stamped, touched } from './repo.js';
20
+ import type { CollectionStore, StoredDoc } from './store.js';
21
+ import { tenantClause, withoutTenant } from './tenancy.js';
22
+ import { type AnyWhere, both } from './where.js';
23
+
24
+ type AnyShape = z.core.$ZodShape;
25
+
26
+ // The payload of each event. AnyCollection's event classes take any payload,
27
+ // so each one is checked against its schema type with `satisfies`.
28
+ type Payload<Name extends keyof Events<string, AnyShape>> = InstanceType<
29
+ Events<string, AnyShape>[Name]
30
+ >['payload'];
31
+
32
+ /** A use case as build() calls it. */
33
+ export type Executable<Ctx> = {
34
+ execute(ctx: Ctx, input: unknown): Promise<unknown>;
35
+ };
36
+
37
+ /**
38
+ * The app's event publisher, such as app-template's `DomainEventPublisher`.
39
+ * `publish` is a method signature, so its parameter is bivariant: a publisher
40
+ * typed by any catalog fits here. `.collection()` checks that it takes that
41
+ * collection's events.
42
+ */
43
+ export type EventPublisher = { publish(event: object): Promise<void> };
44
+
45
+ /** What one generated call works with. */
46
+ type Call = {
47
+ readonly store: CollectionStore;
48
+ readonly events: EventPublisher;
49
+ readonly collection: AnyCollection;
50
+ readonly ops: Operations<AnyShape>;
51
+ /** The access and tenant filter of this call, for every store call. */
52
+ readonly scope: AnyWhere | undefined;
53
+ readonly actorId: string;
54
+ /** The call's tenant on this collection: what create stamps and events carry. */
55
+ readonly tenantId: string | undefined;
56
+ /** Who refers to each collection, for onDelete. */
57
+ readonly referrers: Referrers;
58
+ /** The call's access, for the collections a read populates. */
59
+ readonly access: CallAccess;
60
+ /** Every collection, by slug: what a populated ref reads. */
61
+ readonly collections: ReadonlyMap<string, AnyCollection>;
62
+ };
63
+
64
+ /**
65
+ * 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
+ */
70
+ async function scopeOf(
71
+ ctx: FamilyContext<unknown>,
72
+ collection: AnyCollection,
73
+ action: Action,
74
+ ): Promise<AnyWhere | undefined> {
75
+ if (action === 'create') return undefined;
76
+ return (await ctx.access.scope(collection, action)).where;
77
+ }
78
+
79
+ /** `tenantId` for an event payload, on a tenanted collection only. */
80
+ function tenantPayload(call: Call): { tenantId?: string } {
81
+ return call.tenantId === undefined ? {} : { tenantId: call.tenantId };
82
+ }
83
+
84
+ function notFound(call: Call, id: string) {
85
+ return LatticeError.NOT_FOUND({ collection: call.collection.slug, id });
86
+ }
87
+
88
+ /** A stored doc as the collection's document type: it has its timestamps. */
89
+ function documentOf(
90
+ call: Pick<Call, 'collection'>,
91
+ doc: StoredDoc,
92
+ ): Document<AnyShape> {
93
+ const { createdAt, updatedAt } = doc;
94
+ if (typeof createdAt !== 'string' || typeof updatedAt !== 'string') {
95
+ throw new Error(
96
+ `Lattice: "${call.collection.slug}.${doc.id}" has no createdAt or updatedAt`,
97
+ );
98
+ }
99
+ return { ...doc, createdAt, updatedAt };
100
+ }
101
+
102
+ /** A document's own tenant, for a tenanted collection. */
103
+ function tenantOfDoc(
104
+ collection: AnyCollection,
105
+ doc: StoredDoc,
106
+ ): string | undefined {
107
+ const value =
108
+ collection.tenant === undefined ? undefined : doc[collection.tenant];
109
+ return typeof value === 'string' ? value : undefined;
110
+ }
111
+
112
+ /** A document of a collection, in a delete's plan. */
113
+ type Node = { readonly collection: AnyCollection; readonly doc: StoredDoc };
114
+
115
+ /** What a delete will do, decided before it writes anything. */
116
+ type Plan = {
117
+ /** Cascaded documents, in the order found: parents before children. */
118
+ readonly deletes: Node[];
119
+ /** Documents whose ref to a deleted one is cleared. */
120
+ readonly nullifies: (Node & {
121
+ readonly ref: RefField;
122
+ readonly id: string;
123
+ })[];
124
+ };
125
+
126
+ function keyOf(node: Node): string {
127
+ return JSON.stringify([node.collection.slug, node.doc.id]);
128
+ }
129
+
130
+ /** Every document of `collection` matching `where`, page by page. */
131
+ async function* every(
132
+ store: CollectionStore,
133
+ collection: string,
134
+ where: AnyWhere,
135
+ ): AsyncGenerator<StoredDoc> {
136
+ let after: string | undefined;
137
+ do {
138
+ const page = await store.find(
139
+ findQuery(collection, { where, sort: ['id'], limit: 100, after }),
140
+ );
141
+ yield* page.docs;
142
+ after = page.next ?? undefined;
143
+ } while (after !== undefined);
144
+ }
145
+
146
+ /**
147
+ * The onDelete plan of deleting `root`, through every ref to it, and to
148
+ * each cascaded document in turn. Restrict throws REFERENCED here, before
149
+ * anything is written. These are system steps: they skip access functions,
150
+ * but each carries the tenant of the document it starts from, so a row of
151
+ * another tenant that stores this id is neither counted nor touched. A
152
+ * global document's children are found across tenants.
153
+ */
154
+ async function planDelete(
155
+ store: CollectionStore,
156
+ referrers: Referrers,
157
+ root: Node,
158
+ ): Promise<Plan> {
159
+ const plan: Plan = { deletes: [], nullifies: [] };
160
+ const visited = new Set([keyOf(root)]);
161
+ const queue: Node[] = [root];
162
+ for (let node = queue.shift(); node !== undefined; node = queue.shift()) {
163
+ const { id } = node.doc;
164
+ const tenantId = tenantOfDoc(node.collection, node.doc);
165
+ for (const { collection, ref, relation } of referrers.get(
166
+ node.collection.slug,
167
+ ) ?? []) {
168
+ const where =
169
+ both(
170
+ { [ref.field]: ref.array ? { has: id } : { eq: id } },
171
+ tenantClause(collection, tenantId),
172
+ ) ?? {};
173
+ if (ref.onDelete === 'restrict') {
174
+ if ((await store.count(collection.slug, where)) > 0) {
175
+ throw LatticeError.REFERENCED({
176
+ collection: node.collection.slug,
177
+ id,
178
+ by: {
179
+ collection: collection.slug,
180
+ field: ref.field,
181
+ ...(relation === undefined ? {} : { relation }),
182
+ },
183
+ });
184
+ }
185
+ continue;
186
+ }
187
+ for await (const doc of every(store, collection.slug, where)) {
188
+ const child = { collection, doc };
189
+ if (ref.onDelete === 'nullify') {
190
+ plan.nullifies.push({ ...child, ref, id });
191
+ } else if (!visited.has(keyOf(child))) {
192
+ // A cycle meets a document already planned: stop there.
193
+ visited.add(keyOf(child));
194
+ plan.deletes.push(child);
195
+ queue.push(child);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ return plan;
201
+ }
202
+
203
+ /**
204
+ * Applies a plan in `store`, returning the events it owes. Clears refs
205
+ * first, then deletes the cascaded documents, the deepest first, so a
206
+ * store without transactions ends with the parent, deleted last by the
207
+ * caller.
208
+ */
209
+ async function applyPlan(
210
+ store: CollectionStore,
211
+ call: Pick<Call, 'actorId'>,
212
+ plan: Plan,
213
+ ): Promise<object[]> {
214
+ const events: object[] = [];
215
+ const deleted = new Set(plan.deletes.map(keyOf));
216
+ for (const { collection, doc, ref, id } of plan.nullifies) {
217
+ if (deleted.has(keyOf({ collection, doc }))) continue;
218
+ // Read again: an earlier step may have changed this document.
219
+ const current = await store.get(collection.slug, doc.id);
220
+ if (current === null) continue;
221
+ const value = current[ref.field];
222
+ const cleared = ref.array
223
+ ? Array.isArray(value)
224
+ ? value.filter((element) => element !== id)
225
+ : value
226
+ : ref.cleared;
227
+ const updated = await store.update(
228
+ collection.slug,
229
+ doc.id,
230
+ touched({ [ref.field]: cleared }),
231
+ );
232
+ if (updated === null) continue;
233
+ const tenantId = tenantOfDoc(collection, updated);
234
+ events.push(
235
+ new collection.events.updated({
236
+ doc: documentOf({ collection }, updated),
237
+ previous: documentOf({ collection }, current),
238
+ actorId: call.actorId,
239
+ ...(tenantId === undefined ? {} : { tenantId }),
240
+ } satisfies Payload<'updated'>),
241
+ );
242
+ }
243
+ for (const { collection, doc } of [...plan.deletes].reverse()) {
244
+ const removed = await store.remove(collection.slug, doc.id);
245
+ if (removed === null) continue;
246
+ const tenantId = tenantOfDoc(collection, removed);
247
+ events.push(
248
+ new collection.events.deleted({
249
+ doc: documentOf({ collection }, removed),
250
+ actorId: call.actorId,
251
+ ...(tenantId === undefined ? {} : { tenantId }),
252
+ } satisfies Payload<'deleted'>),
253
+ );
254
+ }
255
+ return events;
256
+ }
257
+
258
+ async function read(
259
+ call: Pick<Call, 'collection'>,
260
+ doc: StoredDoc,
261
+ ): Promise<Document<AnyShape>> {
262
+ const document = documentOf(call, doc);
263
+ const { afterRead } = call.collection;
264
+ return afterRead === undefined ? document : afterRead({ doc: document });
265
+ }
266
+
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
+ /** What populating a read works with. */
271
+ type Populating = Pick<Call, 'store' | 'access' | 'collections'>;
272
+
273
+ /** The ids a ref field holds: one, a list, or none. */
274
+ function idsIn(value: unknown): string[] {
275
+ return (Array.isArray(value) ? value : [value]).filter(
276
+ (id): id is string => typeof id === 'string',
277
+ );
278
+ }
279
+
280
+ /**
281
+ * The documents of `slug` among `ids` that the caller may read, by id: one
282
+ * getMany under the caller's read scope there, which carries the tenant,
283
+ * then each through its afterRead. A `false` read access withholds them
284
+ * all rather than failing the read that populates them.
285
+ */
286
+ async function readable(
287
+ call: Populating,
288
+ slug: string,
289
+ ids: readonly string[],
290
+ ): Promise<ReadonlyMap<string, Document<AnyShape>>> {
291
+ const collection = call.collections.get(slug);
292
+ if (collection === undefined) {
293
+ throw new Error(`Lattice: no collection "${slug}" to populate`);
294
+ }
295
+ const scope = await call.access.scope(collection, 'read').catch((error) => {
296
+ if (LatticeError.is(error) && error.code === 'FORBIDDEN') return null;
297
+ throw error;
298
+ });
299
+ if (scope === null) return new Map();
300
+ const stored = await call.store.getMany(slug, ids, scope.where);
301
+ return new Map(
302
+ await Promise.all(
303
+ stored.map(
304
+ async (doc): Promise<[string, Document<AnyShape>]> => [
305
+ doc.id,
306
+ await read({ collection }, doc),
307
+ ],
308
+ ),
309
+ ),
310
+ );
311
+ }
312
+
313
+ /**
314
+ * `docs` of `collection` with the ref fields in `keys` populated (0022).
315
+ * Ids are collected per target collection across all of `docs`, and each
316
+ * target is read once. A target the caller may not read, or one that no
317
+ * longer exists, is `{ id }`. A list of ids populates element-wise.
318
+ */
319
+ async function populated(
320
+ call: Populating,
321
+ collection: AnyCollection,
322
+ keys: readonly string[],
323
+ docs: readonly Document<AnyShape>[],
324
+ ): Promise<Document<AnyShape>[]> {
325
+ const refs = collection.refs.filter((ref) => keys.includes(ref.field));
326
+ if (refs.length === 0) return [...docs];
327
+ const wanted = new Map<string, Set<string>>();
328
+ for (const doc of docs) {
329
+ for (const ref of refs) {
330
+ const ids = wanted.get(ref.slug) ?? new Set();
331
+ for (const id of idsIn(doc[ref.field])) ids.add(id);
332
+ wanted.set(ref.slug, ids);
333
+ }
334
+ }
335
+ const found = new Map(
336
+ await Promise.all(
337
+ [...wanted].map(
338
+ async ([slug, ids]): Promise<
339
+ [string, ReadonlyMap<string, Document<AnyShape>>]
340
+ > => [slug, await readable(call, slug, [...ids])],
341
+ ),
342
+ ),
343
+ );
344
+ return docs.map((doc) => {
345
+ const next = { ...doc };
346
+ for (const ref of refs) {
347
+ const targets = found.get(ref.slug);
348
+ const swap = (id: unknown) =>
349
+ typeof id === 'string' ? (targets?.get(id) ?? { id }) : id;
350
+ const value = doc[ref.field];
351
+ next[ref.field] = Array.isArray(value) ? value.map(swap) : swap(value);
352
+ }
353
+ return next;
354
+ });
355
+ }
356
+
357
+ async function change(
358
+ call: Call,
359
+ args: ChangeArgs<AnyShape>,
360
+ ): Promise<Data<AnyShape>> {
361
+ const { beforeChange } = call.collection;
362
+ return beforeChange === undefined ? args.data : beforeChange(args);
363
+ }
364
+
365
+ /**
366
+ * Each operation's body. Each parses its own input: the family guard has
367
+ * rejected bad input, but hexok hands execute the raw value, so parsing here
368
+ * strips unknown keys and applies the create schema's defaults.
369
+ */
370
+ /*
371
+ * Each write publishes its event after the store write succeeds, so a failed
372
+ * write publishes nothing. A publish that fails reaches the caller although
373
+ * the write stays: the delivery gap architecture.md accepts until the outbox.
374
+ */
375
+ /**
376
+ * `document` with the `many()` relations in `keys` populated, as `get`
377
+ * does: each relation's links in one find on its join collection, inside
378
+ * the parent's tenant, then their targets in one getMany. `set` keeps a
379
+ * parent to at most 1000 links, so one find holds them all. The links run
380
+ * under the parent's read, as `list` does, which the get has passed.
381
+ */
382
+ async function withLinks(
383
+ call: Populating,
384
+ collection: AnyCollection,
385
+ keys: readonly string[],
386
+ parent: StoredDoc,
387
+ document: Document<AnyShape>,
388
+ ): Promise<Document<AnyShape>> {
389
+ const next = { ...document };
390
+ for (const [name, relation] of Object.entries(collection.relations)) {
391
+ if (!keys.includes(name)) continue;
392
+ const join = relation.through;
393
+ const where = both(
394
+ { [relation.parentField]: { eq: parent.id } },
395
+ tenantClause(join, tenantOfDoc(collection, parent)),
396
+ );
397
+ const { docs } = await call.store.find(
398
+ findQuery(join.slug, { where, limit: maxLinks }),
399
+ );
400
+ const targets = await readable(
401
+ call,
402
+ relation.target,
403
+ docs.flatMap((link) => idsIn(link[relation.targetField])),
404
+ );
405
+ const fields = linkFields(relation);
406
+ next[name] = docs.map((link) => {
407
+ const id = link[relation.targetField];
408
+ return {
409
+ ...Object.fromEntries(
410
+ fields
411
+ .filter((field) => link[field] !== undefined)
412
+ .map((field) => [field, link[field]]),
413
+ ),
414
+ doc: typeof id === 'string' ? (targets.get(id) ?? { id }) : id,
415
+ };
416
+ });
417
+ }
418
+ return next;
419
+ }
420
+
421
+ const operations: Record<
422
+ Action,
423
+ (call: Call, raw: unknown) => Promise<unknown>
424
+ > = {
425
+ async find(call, raw) {
426
+ const { where, sort, limit, after } = parse(call.ops.find.input, raw);
427
+ const { populate = [] } = parse(populateList, raw);
428
+ const page = await call.store.find(
429
+ findQuery(call.collection.slug, {
430
+ where: both(where, call.scope),
431
+ sort,
432
+ limit,
433
+ after,
434
+ }),
435
+ );
436
+ const docs = await Promise.all(page.docs.map((doc) => read(call, doc)));
437
+ return {
438
+ docs: await populated(call, call.collection, populate, docs),
439
+ next: page.next,
440
+ };
441
+ },
442
+
443
+ async count(call, raw) {
444
+ const { where } = parse(call.ops.count.input, raw);
445
+ return {
446
+ count: await call.store.count(
447
+ call.collection.slug,
448
+ both(where, call.scope),
449
+ ),
450
+ };
451
+ },
452
+
453
+ async get(call, raw) {
454
+ const { id } = parse(call.ops.get.input, raw);
455
+ const { populate = [] } = parse(populateList, raw);
456
+ const doc = await call.store.get(call.collection.slug, id, call.scope);
457
+ if (doc === null) throw notFound(call, id);
458
+ const [document] = await populated(call, call.collection, populate, [
459
+ await read(call, doc),
460
+ ]);
461
+ return document === undefined
462
+ ? document
463
+ : withLinks(call, call.collection, populate, doc, document);
464
+ },
465
+
466
+ async create(call, raw) {
467
+ const input = parse(call.ops.create.input, raw);
468
+ const data = await change(call, { data: input, operation: 'create' });
469
+ // Stamped after beforeChange, so a hook cannot pick the tenant.
470
+ const { tenant } = call.collection;
471
+ const doc = stamped(
472
+ tenant === undefined
473
+ ? data
474
+ : { ...withoutTenant(call.collection, data), [tenant]: call.tenantId },
475
+ );
476
+ await call.store.insert(call.collection.slug, doc);
477
+ await call.events.publish(
478
+ new call.collection.events.created({
479
+ doc,
480
+ actorId: call.actorId,
481
+ ...tenantPayload(call),
482
+ } satisfies Payload<'created'>),
483
+ );
484
+ return read(call, doc);
485
+ },
486
+
487
+ async update(call, raw) {
488
+ // The id schema types `id`; across all collections the patch schema is an
489
+ // index signature, which would type it unknown.
490
+ const { id } = parse(call.ops.get.input, raw);
491
+ const { id: _, ...patch } = parse(call.ops.update.input, raw);
492
+ const stored = await call.store.get(call.collection.slug, id, call.scope);
493
+ if (stored === null) throw notFound(call, id);
494
+ const previous = documentOf(call, stored);
495
+ // The tenant field is Lattice's, like the system fields: the schema does
496
+ // not have it, so leaving it in would read as a stored key to remove.
497
+ const { id: _id, createdAt, updatedAt, ...stamps } = previous;
498
+ const data = withoutTenant(call.collection, stamps);
499
+ // The merged document must pass the whole schema, as a create would, so
500
+ // an object-level refinement holds on update too. Parsing also drops
501
+ // stored keys the schema no longer has.
502
+ // A null on a field it clears removes the key (0035); a nullable field
503
+ // keeps its null as a value.
504
+ const { cleared } = call.ops.update;
505
+ const merged = parse(
506
+ call.ops.create.input,
507
+ Object.fromEntries(
508
+ Object.entries({ ...data, ...patch }).filter(
509
+ ([key, value]) => value !== null || !cleared.has(key),
510
+ ),
511
+ ),
512
+ );
513
+ // beforeChange sees the whole document after the change, as on create.
514
+ // A hook that returns the tenant field changes nothing: update never
515
+ // writes it.
516
+ const next = withoutTenant(
517
+ call.collection,
518
+ await change(call, { data: merged, operation: 'update', previous }),
519
+ );
520
+ // Only the fields that differ from the stored ones are written. A stored
521
+ // key that is gone from `next` (dropped by the schema or by the hook) is
522
+ // written as undefined, which the store removes.
523
+ const changes = Object.fromEntries(
524
+ Object.keys({ ...data, ...next })
525
+ .filter((key) => !isDeepStrictEqual(data[key], next[key]))
526
+ .map((key) => [key, next[key]]),
527
+ );
528
+ const updated = await call.store.update(
529
+ call.collection.slug,
530
+ id,
531
+ touched(changes),
532
+ call.scope,
533
+ );
534
+ if (updated === null) throw notFound(call, id);
535
+ await call.events.publish(
536
+ new call.collection.events.updated({
537
+ doc: documentOf(call, updated),
538
+ previous,
539
+ actorId: call.actorId,
540
+ ...tenantPayload(call),
541
+ } satisfies Payload<'updated'>),
542
+ );
543
+ return read(call, updated);
544
+ },
545
+
546
+ async delete(call, raw) {
547
+ const { id } = parse(call.ops.delete.input, raw);
548
+ const { slug } = call.collection;
549
+ // With refs to this collection, onDelete runs in one store transaction,
550
+ // and its events publish only after the commit (0028).
551
+ const { removed, owed } =
552
+ (call.referrers.get(slug) ?? []).length === 0
553
+ ? { removed: await call.store.remove(slug, id, call.scope), owed: [] }
554
+ : await call.store.transaction(async (store) => {
555
+ const doc = await store.get(slug, id, call.scope);
556
+ if (doc === null) throw notFound(call, id);
557
+ const plan = await planDelete(store, call.referrers, {
558
+ collection: call.collection,
559
+ doc,
560
+ });
561
+ const owed = await applyPlan(store, call, plan);
562
+ return { removed: await store.remove(slug, id, call.scope), owed };
563
+ });
564
+ if (removed === null) throw notFound(call, id);
565
+ for (const event of owed) await call.events.publish(event);
566
+ await call.events.publish(
567
+ new call.collection.events.deleted({
568
+ doc: documentOf(call, removed),
569
+ actorId: call.actorId,
570
+ ...tenantPayload(call),
571
+ } satisfies Payload<'deleted'>),
572
+ );
573
+ return read(call, removed);
574
+ },
575
+ };
576
+
577
+ /** The generated use case for one operation, in the app's family. */
578
+ export function generated<Actor>(
579
+ family: Family<Actor>,
580
+ store: CollectionStore,
581
+ events: EventPublisher,
582
+ collection: AnyCollection,
583
+ ops: Operations<AnyShape>,
584
+ action: Action,
585
+ referrers: Referrers,
586
+ 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;
596
+ 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;
606
+ },
607
+ ) {
608
+ super();
609
+ }
610
+
611
+ 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
+ );
626
+ }
627
+ }
628
+ return new Generated({ store, events });
629
+ }
630
+
631
+ /**
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.
636
+ */
637
+ export function generatedRelation<Actor>(
638
+ family: Family<Actor>,
639
+ store: CollectionStore,
640
+ events: EventPublisher,
641
+ collection: AnyCollection,
642
+ name: string,
643
+ relation: AnyRelation,
644
+ op: 'list' | 'set',
645
+ collections: ReadonlyMap<string, AnyCollection>,
646
+ ): Executable<FamilyContext<Actor>> {
647
+ const { input, output } = relation[op];
648
+ const join = relation.through;
649
+ const { parentField, targetField } = relation;
650
+ // The fields of a link, as `set` compares them.
651
+ const linkFields = Object.keys(join.schema.shape).filter(
652
+ (field) => field !== parentField,
653
+ );
654
+
655
+ /** The parent under the scope of `action`, or NOT_FOUND. */
656
+ async function parentOf(ctx: FamilyContext<Actor>, id: string) {
657
+ const scope = await ctx.access.scope(collection, `${name}.${op}`);
658
+ const parent = await store.get(collection.slug, id, scope.where);
659
+ if (parent === null) {
660
+ throw LatticeError.NOT_FOUND({ collection: collection.slug, id });
661
+ }
662
+ return parent;
663
+ }
664
+
665
+ /** The links of `id`, inside the parent's tenant. */
666
+ function linksOf(id: string, tenantId: string | undefined): AnyWhere {
667
+ return (
668
+ both({ [parentField]: { eq: id } }, tenantClause(join, tenantId)) ?? {}
669
+ );
670
+ }
671
+
672
+ async function list(ctx: FamilyContext<Actor>, raw: unknown) {
673
+ const { id, where, sort, limit, after, populate } = parse(
674
+ relation.list.input,
675
+ raw,
676
+ );
677
+ const parent = await parentOf(ctx, id);
678
+ const page = await store.find(
679
+ findQuery(join.slug, {
680
+ where: both(where, linksOf(id, tenantOfDoc(collection, parent))),
681
+ sort,
682
+ limit,
683
+ after,
684
+ }),
685
+ );
686
+ return {
687
+ docs: await populated(
688
+ { store, access: ctx.access, collections },
689
+ join,
690
+ populate ?? [],
691
+ page.docs.map((doc) => documentOf({ collection: join }, doc)),
692
+ ),
693
+ next: page.next,
694
+ };
695
+ }
696
+
697
+ async function set(ctx: FamilyContext<Actor>, raw: unknown) {
698
+ const { id, links } = parse(relation.set.input, raw);
699
+ const parent = await parentOf(ctx, id);
700
+ const tenantId = tenantOfDoc(collection, parent);
701
+ const actorId = family.actorId(ctx.actor);
702
+ const tenant = tenantId === undefined ? {} : { tenantId };
703
+ // The set replaces the links by diffing: an unchanged link keeps its id
704
+ // and createdAt, and each change owes its own event, after the commit.
705
+ const { docs, owed } = await store.transaction(async (tx) => {
706
+ const existing: StoredDoc[] = [];
707
+ for await (const doc of every(tx, join.slug, linksOf(id, tenantId))) {
708
+ existing.push(doc);
709
+ }
710
+ const byTarget = new Map(existing.map((doc) => [doc[targetField], doc]));
711
+ const wanted = new Set(links.map((link) => link[targetField]));
712
+ const owed: object[] = [];
713
+ for (const doc of existing) {
714
+ if (wanted.has(doc[targetField])) continue;
715
+ const removed = await tx.remove(join.slug, doc.id);
716
+ if (removed === null) continue;
717
+ owed.push(
718
+ new join.events.deleted({
719
+ doc: documentOf({ collection: join }, removed),
720
+ actorId,
721
+ ...tenant,
722
+ } satisfies Payload<'deleted'>),
723
+ );
724
+ }
725
+ const docs: StoredDoc[] = [];
726
+ for (const link of links) {
727
+ const previous = byTarget.get(link[targetField]);
728
+ if (previous === undefined) {
729
+ const doc = stamped({
730
+ ...link,
731
+ [parentField]: id,
732
+ ...(join.tenant === undefined || tenantId === undefined
733
+ ? {}
734
+ : { [join.tenant]: tenantId }),
735
+ });
736
+ await tx.insert(join.slug, doc);
737
+ owed.push(
738
+ new join.events.created({
739
+ doc: documentOf({ collection: join }, doc),
740
+ actorId,
741
+ ...tenant,
742
+ } satisfies Payload<'created'>),
743
+ );
744
+ docs.push(doc);
745
+ continue;
746
+ }
747
+ // A field the new link leaves out is written as undefined, which
748
+ // the store removes.
749
+ const changes = Object.fromEntries(
750
+ linkFields
751
+ .filter((field) => !isDeepStrictEqual(previous[field], link[field]))
752
+ .map((field) => [field, link[field]]),
753
+ );
754
+ if (Object.keys(changes).length === 0) {
755
+ docs.push(previous);
756
+ continue;
757
+ }
758
+ const updated = await tx.update(
759
+ join.slug,
760
+ previous.id,
761
+ touched(changes),
762
+ );
763
+ if (updated === null) throw notFoundIn(join, previous.id);
764
+ owed.push(
765
+ new join.events.updated({
766
+ doc: documentOf({ collection: join }, updated),
767
+ previous: documentOf({ collection: join }, previous),
768
+ actorId,
769
+ ...tenant,
770
+ } satisfies Payload<'updated'>),
771
+ );
772
+ docs.push(updated);
773
+ }
774
+ return { docs, owed };
775
+ });
776
+ for (const event of owed) await events.publish(event);
777
+ return { docs: docs.map((doc) => documentOf({ collection: join }, doc)) };
778
+ }
779
+
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();
791
+ }
792
+
793
+ function notFoundIn(collection: AnyCollection, id: string) {
794
+ return LatticeError.NOT_FOUND({ collection: collection.slug, id });
795
+ }