@latticecms/core 0.0.0 → 0.2.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 +1297 -2
  2. package/dist/access.d.ts +209 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +241 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +555 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +655 -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 +351 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +46 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +527 -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 +183 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +150 -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 +227 -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 +277 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +39 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +72 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +144 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +144 -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 +92 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +86 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +187 -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 +811 -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 +119 -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 +80 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +90 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +94 -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 +88 -0
  90. package/skills/lattice/references/override.md +160 -0
  91. package/skills/lattice/references/relations.md +91 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +449 -0
  95. package/src/build.ts +1888 -0
  96. package/src/collection.ts +1025 -0
  97. package/src/crud.ts +797 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +174 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +44 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +336 -0
  104. package/src/populate.ts +103 -0
  105. package/src/relations.ts +370 -0
  106. package/src/repo.ts +218 -0
  107. package/src/sort.ts +271 -0
  108. package/src/store/conformance.ts +1179 -0
  109. package/src/store/index.ts +22 -0
  110. package/src/store.ts +315 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
package/src/build.ts ADDED
@@ -0,0 +1,1888 @@
1
+ import type { Logger } from '@hexok/logger';
2
+ import {
3
+ INVALID_SPAN_CONTEXT,
4
+ context as otel,
5
+ SpanKind,
6
+ trace,
7
+ } from '@opentelemetry/api';
8
+ import {
9
+ type ContractProcedure,
10
+ type ContractRouterBrand,
11
+ type ErrorMap,
12
+ type Expansion,
13
+ type InferContractProcedure,
14
+ type InferExpandedOutput,
15
+ type InferSchemaInput,
16
+ type InferSchemaOutput,
17
+ isContractProcedure,
18
+ procedure,
19
+ router,
20
+ } from '@ts-pf/contract';
21
+ import type { DocsMeta } from '@ts-pf/docs';
22
+ import type { McpEffect } from '@ts-pf/mcp/meta';
23
+ import { isPFError, isUnexpectedError } from '@ts-pf/protocol';
24
+ import {
25
+ createImplementer,
26
+ type ImplementedProcedure,
27
+ type ImplementedRouter,
28
+ type MiddlewareFn,
29
+ } from '@ts-pf/server';
30
+ import { validate } from 'hexok';
31
+ import { z } from 'zod';
32
+ import {
33
+ type Access,
34
+ type AccessCheck,
35
+ type AccessFns,
36
+ type AccessMap,
37
+ type AccessReturns,
38
+ CallAccess,
39
+ CollectionAccess,
40
+ type FieldsMap,
41
+ familyContext,
42
+ } from './access.js';
43
+ import {
44
+ type Action,
45
+ type AnyCollection,
46
+ type AnyRelation,
47
+ type Operations,
48
+ operations,
49
+ } from './collection.js';
50
+ import {
51
+ type EventPublisher,
52
+ type Executable,
53
+ generatedUseCase,
54
+ operationBody,
55
+ relationBody,
56
+ } from './crud.js';
57
+ import { type EffectOf, generatedMeta, methodMeta } from './describe.js';
58
+ import {
59
+ declaredErrors,
60
+ type LatticeCode,
61
+ latticeCodes,
62
+ refusal,
63
+ toClientError,
64
+ } from './errors.js';
65
+ import {
66
+ type CallContext,
67
+ callerFields,
68
+ type Family,
69
+ type FamilyContext,
70
+ loggedByFamily,
71
+ } from './family.js';
72
+ import {
73
+ applyMask,
74
+ type MaskPlan,
75
+ maskedCollections,
76
+ maskPlan,
77
+ } from './mask.js';
78
+ import {
79
+ expansionOf,
80
+ populateInput,
81
+ populateKeys,
82
+ type Withheld,
83
+ } from './populate.js';
84
+ import { type CascadeFields, type RefSlugs, referrersOf } from './relations.js';
85
+ import { type ClientDoc, type Repo, repo } from './repo.js';
86
+ import type { CollectionStore } from './store.js';
87
+ import type { TenantField } from './tenancy.js';
88
+ import { failed, tracer } from './tracing.js';
89
+
90
+ const actions = [
91
+ 'find',
92
+ 'count',
93
+ 'get',
94
+ 'create',
95
+ 'update',
96
+ 'delete',
97
+ ] as const satisfies readonly Action[];
98
+
99
+ /** The effects `@ts-pf/mcp` knows, which a method's `effect` must be one of. */
100
+ const effects = ['read', 'write', 'destructive'] satisfies readonly McpEffect[];
101
+
102
+ /**
103
+ * Names a collection slug, a relation or a method cannot take: ts-pf
104
+ * `Implementer` keys, whose members they would shadow in the router.
105
+ */
106
+ export const reservedNames = [
107
+ '$context',
108
+ 'use',
109
+ 'useAfter',
110
+ 'middleware',
111
+ 'router',
112
+ ] as const;
113
+ type Reserved = (typeof reservedNames)[number];
114
+
115
+ type Ctor<I> = abstract new (...args: never[]) => I;
116
+
117
+ type Schemas = { readonly input: z.ZodType; readonly output: z.ZodType };
118
+
119
+ /**
120
+ * What a method's class says about itself, beside its schemas: one
121
+ * sentence on what it does, and whether it reads, writes or destroys. They
122
+ * become its procedure's `docs` and `mcp` meta (0033).
123
+ */
124
+ type MethodDescription = {
125
+ readonly summary: string;
126
+ readonly effect: McpEffect;
127
+ };
128
+
129
+ type MethodStatics = Schemas & MethodDescription;
130
+
131
+ /** An override as declared: a class, or one per operation of a relation. */
132
+ type AnyOverride = Ctor<unknown> | Readonly<Record<string, Ctor<unknown>>>;
133
+
134
+ /**
135
+ * A collection, its access functions, and the classes attached to it. A
136
+ * join collection a relation derived is an entry too, so its events, refs
137
+ * and indexes count, but it has no slice and no use cases.
138
+ */
139
+ type Entry = {
140
+ readonly collection: AnyCollection;
141
+ readonly access: AccessMap;
142
+ readonly fields: FieldsMap;
143
+ readonly methods: Readonly<Record<string, Ctor<unknown> & MethodStatics>>;
144
+ readonly overrides: Readonly<Record<string, AnyOverride>>;
145
+ readonly join: boolean;
146
+ };
147
+
148
+ /** The relation operations Lattice generates. */
149
+ const relationOps = ['list', 'set'] as const;
150
+ type RelationOp = (typeof relationOps)[number];
151
+
152
+ /** The entries a collection's relations add: their join collections. */
153
+ type JoinEntries<C extends AnyCollection> = {
154
+ [K in keyof C['relations'] as C['relations'][K]['through']['slug']]: {
155
+ collection: C['relations'][K]['through'];
156
+ methods: Record<never, never>;
157
+ overrides: Record<never, never>;
158
+ join: true;
159
+ };
160
+ };
161
+
162
+ /** The entries with a contract slice: all but join collections. */
163
+ type Sliced<E extends Entries> = {
164
+ [S in keyof E as E[S]['join'] extends true ? never : S]: E[S];
165
+ };
166
+
167
+ type Entries = Record<string, Entry>;
168
+
169
+ type Ops<Col extends AnyCollection> = Operations<
170
+ Col['schema']['shape'],
171
+ TenantField<Col>
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
+
191
+ /**
192
+ * What a client receives from operation `A` of `Col`: its documents as
193
+ * `clientOutput`, each maskable field optional.
194
+ */
195
+ type ClientOut<Col extends AnyCollection, A extends Action> = A extends 'count'
196
+ ? Ops<Col>['count']['output']
197
+ : A extends 'find'
198
+ ? z.ZodObject<{
199
+ docs: z.ZodArray<Col['clientOutput']>;
200
+ next: z.ZodNullable<z.ZodString>;
201
+ }>
202
+ : Col['clientOutput'];
203
+
204
+ /** The maskable fields of `Col`. */
205
+ type MaskableOf<Col extends AnyCollection> = Col['maskable'][number];
206
+
207
+ /**
208
+ * The `fields` option of `.collection()`: a read rule for each maskable
209
+ * field, given the actor, and required exactly when there is one.
210
+ */
211
+ type FieldsOption<Actor, Col extends AnyCollection> = [
212
+ MaskableOf<Col>,
213
+ ] extends [never]
214
+ ? { readonly fields?: never }
215
+ : {
216
+ readonly fields: {
217
+ readonly [K in MaskableOf<Col>]: {
218
+ readonly read: (args: {
219
+ readonly actor: Actor;
220
+ }) => boolean | Promise<boolean>;
221
+ };
222
+ };
223
+ };
224
+
225
+ /**
226
+ * What a class attached as method `N` of `Col` must be: its statics name
227
+ * `Col` and `<slug>.<N>`, say what it does and its effect, and `execute`
228
+ * takes and returns its own schemas' types. `execute` is a property here,
229
+ * not a method, so its input is checked contravariantly: a method signature
230
+ * is bivariant and would accept a narrower input.
231
+ */
232
+ type MethodCheck<C, Col extends AnyCollection, N, Ctx> = N extends
233
+ | Action
234
+ | 'read'
235
+ | Reserved
236
+ | keyof Col['relations']
237
+ | `${string}.${string}`
238
+ ? Ctor<unknown> &
239
+ MethodStatics & {
240
+ readonly '~error': `"${N & string}" is a generated operation, an access key, a relation, a ts-pf implementer key, or has a dot`;
241
+ }
242
+ : C extends {
243
+ readonly input: infer I extends z.ZodType;
244
+ readonly output: infer O extends z.ZodType;
245
+ }
246
+ ? C extends MethodDescription
247
+ ? Ctor<{
248
+ execute: (ctx: Ctx, input: z.output<I>) => Promise<z.output<O>>;
249
+ }> & {
250
+ readonly token: `${Col['slug']}.${N & string}`;
251
+ readonly collection: Col;
252
+ readonly input: I;
253
+ readonly output: O;
254
+ readonly summary: string;
255
+ readonly effect: McpEffect;
256
+ }
257
+ : Ctor<unknown> &
258
+ MethodStatics & {
259
+ readonly '~error': `method "${N & string}" needs a summary and an effect: what it does, and whether it reads, writes or is destructive`;
260
+ }
261
+ : Ctor<unknown> & MethodStatics;
262
+
263
+ /** What a class that replaces relation operation `Op` of `Col.R` must be. */
264
+ type RelationOverrideCheck<
265
+ Col extends AnyCollection,
266
+ R extends keyof Col['relations'],
267
+ Op extends RelationOp,
268
+ Ctx,
269
+ > = Ctor<{
270
+ execute: (
271
+ ctx: Ctx,
272
+ input: z.output<Col['relations'][R][Op]['input']>,
273
+ ) => Promise<z.output<Col['relations'][R][Op]['output']>>;
274
+ }> & {
275
+ readonly token: `${Col['slug']}.${R & string}.${Op}`;
276
+ readonly collection: Col;
277
+ };
278
+
279
+ /**
280
+ * An override keeps the summary and effect of the operation it replaces,
281
+ * because clients see the same procedure. A class `X` that declares either
282
+ * gains a key it lacks, so the error names the override.
283
+ */
284
+ type Undescribed<X, Name extends string> = X extends
285
+ | { readonly summary: unknown }
286
+ | { readonly effect: unknown }
287
+ ? {
288
+ readonly '~error': `override "${Name}" keeps the generated summary and effect; remove its summary and effect statics`;
289
+ }
290
+ : unknown;
291
+
292
+ /**
293
+ * What class `X`, replacing operation `A` of `Col`, must be. A relation's
294
+ * operations are replaced by name: `{ categories: { set: Class } }`.
295
+ */
296
+ type OverrideCheck<X, Col extends AnyCollection, A, Ctx> = A extends Action
297
+ ? Ctor<{
298
+ execute: (
299
+ ctx: Ctx,
300
+ input: z.output<Ops<Col>[A]['input']>,
301
+ ) => Promise<z.output<Ops<Col>[A]['output']>>;
302
+ }> & {
303
+ readonly token: `${Col['slug']}.${A}`;
304
+ readonly collection: Col;
305
+ } & Undescribed<X, A>
306
+ : A extends keyof Col['relations']
307
+ ? {
308
+ readonly [Op in RelationOp]?: RelationOverrideCheck<Col, A, Op, Ctx> &
309
+ Undescribed<
310
+ Op extends keyof X ? X[Op] : unknown,
311
+ `${A & string}.${Op}`
312
+ >;
313
+ }
314
+ : Ctor<unknown> & {
315
+ readonly '~error': `"${A & string}" is not a generated operation or a relation`;
316
+ };
317
+
318
+ // A rejected slug adds a key the collection lacks, so the error names it.
319
+ type SlugCheck<C extends AnyCollection, E extends Entries> = C extends {
320
+ readonly slug: Reserved;
321
+ }
322
+ ? { readonly '~error': `"${C['slug']}" is a ts-pf implementer key` }
323
+ : C['slug'] extends keyof E
324
+ ? { readonly '~error': `"${C['slug']}" is already a collection` }
325
+ : [keyof JoinEntries<C> & (keyof E | C['slug'])] extends [never]
326
+ ? unknown
327
+ : {
328
+ readonly '~error': `the join collection "${keyof JoinEntries<C> & (keyof E | C['slug']) & string}" is already a collection`;
329
+ };
330
+
331
+ // A tenanted collection needs a family with tenantOf. A rejected collection
332
+ // adds a key it lacks, so the error names it.
333
+ type TenantCheck<C extends AnyCollection, Tenanted extends boolean> = [
334
+ TenantField<C>,
335
+ ] extends [never]
336
+ ? unknown
337
+ : [Tenanted] extends [false]
338
+ ? {
339
+ readonly '~error': `"${C['slug']}" is tenanted, but the family has no tenantOf`;
340
+ }
341
+ : unknown;
342
+
343
+ // A cascade deletes children on Lattice's own path, so a collection that
344
+ // overrides delete, such as with a soft delete, would lose rows it keeps.
345
+ // A rejected collection adds a key its options lack, so the error names the
346
+ // field.
347
+ type CascadeOverrideCheck<C extends AnyCollection, O> = 'delete' extends keyof O
348
+ ? [CascadeFields<C['schema']['shape']>] extends [never]
349
+ ? unknown
350
+ : {
351
+ readonly '~error': `${C['slug']} overrides delete, so ${C['slug']}.${CascadeFields<C['schema']['shape']> & string} cannot cascade; use restrict or nullify`;
352
+ }
353
+ : unknown;
354
+
355
+ // Each event of `Col` that `P.publish` does not take, by token.
356
+ type Refused<Col extends AnyCollection, P extends EventPublisher> = {
357
+ [K in keyof Col['events']]: [Instance<Col['events'][K]>] extends [
358
+ Parameters<P['publish']>[0],
359
+ ]
360
+ ? never
361
+ : Instance<Col['events'][K]> extends { readonly token: infer T }
362
+ ? T
363
+ : never;
364
+ }[keyof Col['events']];
365
+
366
+ // Each event of every collection in `E` that `P.publish` does not take.
367
+ type RefusedBy<E extends Entries, P extends EventPublisher> = {
368
+ [S in keyof E]: Refused<E[S]['collection'], P>;
369
+ }[keyof E];
370
+
371
+ // Checked as a tuple, not through `P extends { publish(...) }`: publish is
372
+ // usually a method, and a method's parameter is bivariant, so a publisher of
373
+ // another catalog's events would pass. A rejected publisher adds a key it
374
+ // lacks, so the error names each token.
375
+ type EventsCheck<E extends Entries, P extends EventPublisher> = [
376
+ RefusedBy<E, P>,
377
+ ] extends [never]
378
+ ? unknown
379
+ : {
380
+ readonly '~error': `the events publisher does not take "${RefusedBy<E, P> & string}"`;
381
+ };
382
+
383
+ // A rejected map adds a key it lacks, so the error names the code.
384
+ type DeclaredCheck<D> = [keyof D & LatticeCode] extends [never]
385
+ ? unknown
386
+ : {
387
+ readonly '~error': `"${keyof D & LatticeCode & string}" is a Lattice error code`;
388
+ };
389
+
390
+ /** The errors every procedure declares: Lattice's, then the app's. */
391
+ type Declared<D extends ErrorMap> = typeof declaredErrors & D;
392
+
393
+ /**
394
+ * A procedure as ts-pf's `procedure.input(In).output(Out)` types it: a
395
+ * caller sends the input schema's input type, so a defaulted field is
396
+ * optional, and the handler receives its output type.
397
+ */
398
+ type Procedure<
399
+ In,
400
+ Out,
401
+ D extends ErrorMap,
402
+ Fx extends McpEffect,
403
+ > = ContractProcedure<
404
+ InferSchemaInput<In>,
405
+ InferSchemaOutput<Out>,
406
+ Declared<D>,
407
+ MetaOf<Fx>,
408
+ InferSchemaOutput<In>
409
+ >;
410
+
411
+ /**
412
+ * A procedure's meta: its summary and MCP effect, generated or from a
413
+ * method's statics. The effect is literal, so `@ts-pf/mcp`'s toolkit
414
+ * filters by it in types as the server does. Written out, not named, so an
415
+ * app's declarations name only what ts-pf exports (TS2883). The `lattice`
416
+ * key is runtime only: clients read it from the catalog, and no type needs
417
+ * it.
418
+ */
419
+ type MetaOf<Fx extends McpEffect> = {
420
+ readonly docs: DocsMeta;
421
+ readonly mcp: { readonly effect: Fx };
422
+ };
423
+
424
+ type Flat<T> = { [K in keyof T]: T[K] } & {};
425
+
426
+ /** The ref fields of `Col`, and the slug each refers to. */
427
+ type RefsOf<Col extends AnyCollection> = RefSlugs<Col['schema']['shape']>;
428
+
429
+ /** A read that populates: `get` takes refs and relations, `find` refs only. */
430
+ type PopulatingRead = 'get' | 'find';
431
+
432
+ /** The `many()` relations a read of `Col` may populate. */
433
+ type RelationsOf<
434
+ Col extends AnyCollection,
435
+ R extends PopulatingRead,
436
+ > = R extends 'get' ? keyof Col['relations'] : never;
437
+
438
+ /**
439
+ * What `populate` may name on read `R` of `Col`. A template literal, so an
440
+ * error prints the union rather than the alias.
441
+ */
442
+ type PopulateKey<
443
+ Col extends AnyCollection,
444
+ R extends PopulatingRead,
445
+ > = `${(keyof RefsOf<Col> | RelationsOf<Col, R>) & string}`;
446
+
447
+ /** A populated ref's document: the target's, or `Withheld`. */
448
+ type Target<E extends Entries, Slug> =
449
+ | (Slug extends keyof E ? ClientDoc<E[Slug]['collection']> : never)
450
+ | Withheld;
451
+
452
+ /** A ref field's expanded type, one target or a list. Null and undefined stay the field's own. */
453
+ type Swap<V, T> = V extends string
454
+ ? T
455
+ : V extends readonly string[]
456
+ ? T[]
457
+ : never;
458
+
459
+ /** A populated link of `Rel`: its fields and its target document. */
460
+ type Link<E extends Entries, Rel extends AnyRelation> = Flat<
461
+ Omit<
462
+ ClientDoc<Rel['through']>,
463
+ | 'id'
464
+ | 'createdAt'
465
+ | 'updatedAt'
466
+ | Rel['parentField']
467
+ | Rel['targetField']
468
+ | TenantField<Rel['through']>
469
+ > & { doc: Target<E, Rel['target']> }
470
+ >;
471
+
472
+ /** Each ref field of `Col`, populated. */
473
+ type ExpandedRefs<E extends Entries, Col extends AnyCollection> = {
474
+ [K in keyof RefsOf<Col>]: Swap<
475
+ ClientDoc<Col>[K & keyof ClientDoc<Col>],
476
+ Target<E, RefsOf<Col>[K]>
477
+ >;
478
+ };
479
+
480
+ /** Each relation read `R` of `Col` may populate, as its links. */
481
+ type ExpandedLinks<
482
+ E extends Entries,
483
+ Col extends AnyCollection,
484
+ R extends PopulatingRead,
485
+ > = {
486
+ [N in RelationsOf<Col, R>]: Link<E, Col['relations'][N]>[];
487
+ };
488
+
489
+ /** What `populate` gives on read `R` of `Col`: the expansion's `fields`. */
490
+ type Expanded<
491
+ E extends Entries,
492
+ Col extends AnyCollection,
493
+ R extends PopulatingRead,
494
+ > = Flat<ExpandedRefs<E, Col> & ExpandedLinks<E, Col, R>>;
495
+
496
+ /**
497
+ * `Col`'s document as read `R` sends it: each ref field plain or
498
+ * populated, and each relation only when populated.
499
+ */
500
+ type Wide<
501
+ E extends Entries,
502
+ Col extends AnyCollection,
503
+ R extends PopulatingRead,
504
+ > = Flat<
505
+ {
506
+ [K in keyof ClientDoc<Col>]: K extends keyof ExpandedRefs<E, Col>
507
+ ? ClientDoc<Col>[K] | ExpandedRefs<E, Col>[K]
508
+ : ClientDoc<Col>[K];
509
+ } & Partial<ExpandedLinks<E, Col, R>>
510
+ >;
511
+
512
+ /**
513
+ * A read of `Col`, as `contractOf` builds it: its output follows `populate`
514
+ * through ts-pf's expandable outputs (0022), at the root (`get`) or in
515
+ * `docs` (`find`, `list`). Plain when `Col` has no ref field.
516
+ */
517
+ type Read<
518
+ E extends Entries,
519
+ Col extends AnyCollection,
520
+ In,
521
+ R extends PopulatingRead,
522
+ D extends ErrorMap,
523
+ > = [PopulateKey<Col, R>] extends [never]
524
+ ? never
525
+ : ContractProcedure<
526
+ Flat<InferSchemaInput<In> & { populate?: PopulateKey<Col, R>[] }>,
527
+ R extends 'get'
528
+ ? Wide<E, Col, R>
529
+ : { docs: Wide<E, Col, R>[]; next: string | null },
530
+ Declared<D>,
531
+ MetaOf<EffectOf<R>>,
532
+ Flat<
533
+ InferSchemaOutput<In> & {
534
+ populate?: PopulateKey<Col, R>[] | undefined;
535
+ }
536
+ >,
537
+ Expansion<
538
+ 'populate',
539
+ R extends 'get' ? [] : ['docs'],
540
+ Expanded<E, Col, R>
541
+ >
542
+ >;
543
+
544
+ /** `Read`, or the plain procedure when there is nothing to populate. */
545
+ type ReadOr<
546
+ E extends Entries,
547
+ Col extends AnyCollection,
548
+ In,
549
+ Out,
550
+ R extends PopulatingRead,
551
+ D extends ErrorMap,
552
+ > = [Read<E, Col, In, R, D>] extends [never]
553
+ ? Procedure<In, Out, D, EffectOf<R>>
554
+ : Read<E, Col, In, R, D>;
555
+
556
+ /**
557
+ * Generated operation `A` of entry `S`. An overridden read is plain: the
558
+ * override serves it, and Lattice's population runs in the generated read.
559
+ */
560
+ type Operation<
561
+ E extends Entries,
562
+ S extends Entry,
563
+ A extends Action,
564
+ D extends ErrorMap,
565
+ > = A extends 'get' | 'find'
566
+ ? A extends keyof S['overrides']
567
+ ? Procedure<
568
+ Ops<S['collection']>[A]['input'],
569
+ ClientOut<S['collection'], A>,
570
+ D,
571
+ EffectOf<A>
572
+ >
573
+ : ReadOr<
574
+ E,
575
+ S['collection'],
576
+ Ops<S['collection']>[A]['input'],
577
+ ClientOut<S['collection'], A>,
578
+ A,
579
+ D
580
+ >
581
+ : Procedure<
582
+ Ops<S['collection']>[A]['input'],
583
+ ClientOut<S['collection'], A>,
584
+ D,
585
+ EffectOf<A>
586
+ >;
587
+
588
+ /** Operation `Op` of relation `R` of entry `S`. An overridden list is plain. */
589
+ type RelationOperation<
590
+ E extends Entries,
591
+ S extends Entry,
592
+ R extends keyof S['collection']['relations'],
593
+ Op extends RelationOp,
594
+ D extends ErrorMap,
595
+ > = Op extends 'list'
596
+ ? R extends keyof S['overrides']
597
+ ? 'list' extends keyof S['overrides'][R]
598
+ ? Procedure<
599
+ S['collection']['relations'][R]['list']['input'],
600
+ S['collection']['relations'][R]['list']['output'],
601
+ D,
602
+ EffectOf<'list'>
603
+ >
604
+ : RelationList<E, S, R, D>
605
+ : RelationList<E, S, R, D>
606
+ : Procedure<
607
+ S['collection']['relations'][R][Op]['input'],
608
+ S['collection']['relations'][R][Op]['output'],
609
+ D,
610
+ EffectOf<Op>
611
+ >;
612
+
613
+ type RelationList<
614
+ E extends Entries,
615
+ S extends Entry,
616
+ R extends keyof S['collection']['relations'],
617
+ D extends ErrorMap,
618
+ > = ReadOr<
619
+ E,
620
+ S['collection']['relations'][R]['through'],
621
+ S['collection']['relations'][R]['list']['input'],
622
+ S['collection']['relations'][R]['list']['output'],
623
+ 'find',
624
+ D
625
+ >;
626
+
627
+ /** One collection's contract slice: the generated operations plus its methods. */
628
+ type Slice<E extends Entries, S extends Entry, D extends ErrorMap> = {
629
+ [K in Action | (keyof S['methods'] & string)]: K extends Action
630
+ ? Operation<E, S, K, D>
631
+ : Procedure<
632
+ S['methods'][K]['input'],
633
+ S['methods'][K]['output'],
634
+ D,
635
+ S['methods'][K]['effect']
636
+ >;
637
+ } & {
638
+ [R in keyof S['collection']['relations']]: {
639
+ [Op in RelationOp]: RelationOperation<E, S, R, Op, D>;
640
+ };
641
+ };
642
+
643
+ /** Each ref whose slug is not a collection of `E`, as `slug.field → target`. */
644
+ type Unresolved<E extends Entries> = {
645
+ [S in keyof E]: {
646
+ [K in keyof RefSlugs<E[S]['collection']['schema']['shape']>]: RefSlugs<
647
+ E[S]['collection']['schema']['shape']
648
+ >[K] extends keyof E
649
+ ? never
650
+ : `${S & string}.${K & string} refers to "${RefSlugs<E[S]['collection']['schema']['shape']>[K] & string}"`;
651
+ }[keyof RefSlugs<E[S]['collection']['schema']['shape']>];
652
+ }[keyof E];
653
+
654
+ // Collections may be added in any order, so refs can point both ways: they
655
+ // are checked where the definition is used, on `contract` and `build()`. A
656
+ // rejected definition gains a key, so the error names each ref.
657
+ type SlugsCheck<E extends Entries> = [Unresolved<E>] extends [never]
658
+ ? unknown
659
+ : {
660
+ readonly '~error': `${Unresolved<E>}, which is not a collection of this framework`;
661
+ };
662
+
663
+ /** The generated ts-pf contract: one slice per collection. */
664
+ export type Contract<E extends Entries, D extends ErrorMap> = {
665
+ [S in keyof Sliced<E>]: Slice<E, E[S], D>;
666
+ } & ContractRouterBrand;
667
+
668
+ /** The contract as `.contract` gives it: with an `'~error'` key while a ref is unresolved. */
669
+ type CheckedContract<E extends Entries, D extends ErrorMap> = Contract<E, D> &
670
+ SlugsCheck<E>;
671
+
672
+ type Instance<C> = C extends Ctor<infer I> ? I : never;
673
+
674
+ /** The instance of a declared class, or of each relation operation's. */
675
+ type InstanceOf<V, Ctx> =
676
+ V extends Ctor<infer I>
677
+ ? I & Executable<Ctx>
678
+ : { [Op in keyof V]: Instance<V[Op]> & Executable<Ctx> };
679
+
680
+ type Instances<E extends Entries, Kind extends 'methods' | 'overrides', Ctx> = {
681
+ [S in keyof E as [keyof E[S][Kind]] extends [never] ? never : S]: {
682
+ [N in keyof E[S][Kind]]: InstanceOf<E[S][Kind][N], Ctx>;
683
+ };
684
+ };
685
+
686
+ /** Each collection's repo, by slug. */
687
+ type Repos<E extends Entries> = { [S in keyof E]: Repo<E[S]['collection']> };
688
+
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> };
741
+
742
+ /**
743
+ * One kind of instance `build()` takes: a factory that returns one instance
744
+ * per attached class, by slug and name. Required when a collection declared
745
+ * that kind.
746
+ */
747
+ type Factory<E extends Entries, Kind extends 'methods' | 'overrides', Ctx> = [
748
+ keyof Instances<E, Kind, Ctx>,
749
+ ] extends [never]
750
+ ? {
751
+ readonly [K in Kind]?: (
752
+ wiring: Wiring<E, Kind, Ctx>,
753
+ ) => Record<never, never>;
754
+ }
755
+ : {
756
+ readonly [K in Kind]: (
757
+ wiring: Wiring<E, Kind, Ctx>,
758
+ ) => Instances<E, Kind, Ctx>;
759
+ };
760
+
761
+ /** What `build()` takes: the ports, and the method and override instances. */
762
+ type BuildOptions<E extends Entries, P extends EventPublisher, Actor, Ctx> = {
763
+ /**
764
+ * Where every collection's documents live. A ref to a slug the definition
765
+ * lacks is reported here, because the store is what every ref needs.
766
+ */
767
+ readonly store: CollectionStore & SlugsCheck<E>;
768
+ /**
769
+ * Decides access instead of the functions given at `.collection()`, such
770
+ * as an adapter of another decision engine.
771
+ */
772
+ readonly access?: Access<Actor>;
773
+ /**
774
+ * The app's domain event publisher. Generated writes publish each
775
+ * collection's events through it. An app with no subscribers passes one
776
+ * that does nothing.
777
+ */
778
+ readonly events: P & EventsCheck<E, P>;
779
+ } & Factory<E, 'methods', Ctx> &
780
+ Factory<E, 'overrides', Ctx>;
781
+
782
+ /**
783
+ * A generated use case as a direct caller sees it. Its `execute` parses its
784
+ * own input, so it takes the schema's input type: defaulted fields may be
785
+ * left out.
786
+ */
787
+ type GeneratedUseCase<Col extends AnyCollection, A extends Action, Ctx> = {
788
+ execute(
789
+ ctx: Ctx,
790
+ input: z.input<Ops<Col>[A]['input']>,
791
+ ): Promise<z.output<Ops<Col>[A]['output']>>;
792
+ };
793
+
794
+ /** A generated relation operation as a direct caller sees it. */
795
+ type GeneratedRelationUseCase<
796
+ Schemas_ extends {
797
+ readonly input: z.core.$ZodType;
798
+ readonly output: z.core.$ZodType;
799
+ },
800
+ Ctx,
801
+ > = {
802
+ execute(
803
+ ctx: Ctx,
804
+ input: z.input<Schemas_['input']>,
805
+ ): Promise<z.output<Schemas_['output']>>;
806
+ };
807
+
808
+ /**
809
+ * A generated read as a direct caller sees it: its output follows
810
+ * `populate`, as a client's does.
811
+ */
812
+ // An interface, so a declaration file names it rather than spelling out
813
+ // ts-pf's ExpandResult, which @ts-pf/contract does not export.
814
+ export interface ReadUseCase<Proc, Ctx> {
815
+ execute<const P extends readonly ExpansionKeys<Proc>[] = readonly []>(
816
+ ctx: Ctx,
817
+ input: InferContractProcedure<Proc>['input'] & { readonly populate?: P },
818
+ ): Promise<InferExpandedOutput<Proc, P>>;
819
+ }
820
+
821
+ // ts-pf's InferExpansionKeys, which it does not export. The same type, so it
822
+ // satisfies InferExpandedOutput's constraint.
823
+ type ExpansionKeys<T> =
824
+ InferContractProcedure<T>['expand'] extends infer X extends Expansion
825
+ ? keyof X['fields'] & string
826
+ : never;
827
+
828
+ /** The use case of generated operation `A`: a populating read, or plain. */
829
+ type OperationUseCase<
830
+ E extends Entries,
831
+ S extends Entry,
832
+ A extends Action,
833
+ Ctx,
834
+ > = [InferContractProcedure<Operation<E, S, A, ErrorMap>>['expand']] extends [
835
+ never,
836
+ ]
837
+ ? GeneratedUseCase<S['collection'], A, Ctx>
838
+ : ReadUseCase<Operation<E, S, A, ErrorMap>, Ctx>;
839
+
840
+ /** The instances of one collection's relation operations. */
841
+ type RelationUseCases<E extends Entries, S extends Entry, Ctx> = {
842
+ [R in keyof S['collection']['relations']]: {
843
+ [Op in RelationOp]: R extends keyof S['overrides']
844
+ ? Op extends keyof S['overrides'][R]
845
+ ? Instance<S['overrides'][R][Op]>
846
+ : RelationUseCase<E, S, R, Op, Ctx>
847
+ : RelationUseCase<E, S, R, Op, Ctx>;
848
+ };
849
+ };
850
+
851
+ /** The generated use case of relation operation `Op`: list populates. */
852
+ type RelationUseCase<
853
+ E extends Entries,
854
+ S extends Entry,
855
+ R extends keyof S['collection']['relations'],
856
+ Op extends RelationOp,
857
+ Ctx,
858
+ > = Op extends 'list'
859
+ ? ReadUseCase<RelationList<E, S, R, ErrorMap>, Ctx>
860
+ : GeneratedRelationUseCase<S['collection']['relations'][R][Op], Ctx>;
861
+
862
+ /** The instance that serves each procedure: generated, override or method. */
863
+ type UseCases<E extends Entries, Ctx> = {
864
+ [S in keyof Sliced<E>]: {
865
+ [A in Action]: A extends keyof E[S]['overrides']
866
+ ? Instance<E[S]['overrides'][A]>
867
+ : OperationUseCase<E, E[S], A, Ctx>;
868
+ } & {
869
+ [N in keyof E[S]['methods']]: Instance<E[S]['methods'][N]>;
870
+ } & RelationUseCases<E, E[S], Ctx>;
871
+ };
872
+
873
+ /** What `build()` returns. */
874
+ type Built<E extends Entries, D extends ErrorMap, Actor> = {
875
+ readonly app: ImplementedRouter<Contract<E, D>, CallContext<Actor>>;
876
+ readonly useCases: UseCases<E, FamilyContext<Actor>>;
877
+ readonly repos: Repos<E>;
878
+ readonly onError: typeof unexpectedErrors;
879
+ /**
880
+ * Creates the indexes each collection declares, collection by collection
881
+ * in definition order, and never drops one. Await it after the store has
882
+ * started and before serving.
883
+ */
884
+ readonly ensure: () => Promise<void>;
885
+ /**
886
+ * The context for a direct `useCases.*.execute` call: the caller's, plus
887
+ * the call's access. Access answers are kept on it, so make one per call
888
+ * or per job.
889
+ */
890
+ readonly context: (base: CallContext<Actor>) => FamilyContext<Actor>;
891
+ };
892
+
893
+ /** Any procedure of the contract, a populated read's expansion included. */
894
+ type RuntimeProcedure = ContractProcedure<
895
+ unknown,
896
+ unknown,
897
+ ErrorMap,
898
+ Record<never, never>,
899
+ unknown,
900
+ Expansion
901
+ >;
902
+
903
+ /** A relation's node in a slice: its `list` and `set` procedures. */
904
+ type RuntimeRelation = Record<string, RuntimeProcedure>;
905
+
906
+ type RuntimeContract = Record<
907
+ string,
908
+ Record<string, RuntimeProcedure | RuntimeRelation>
909
+ >;
910
+
911
+ /** Whether a slice's node is a procedure, not a relation's node. */
912
+ function isProcedure(
913
+ node: RuntimeProcedure | RuntimeRelation,
914
+ ): node is RuntimeProcedure {
915
+ return isContractProcedure(node);
916
+ }
917
+
918
+ /** The app's client errors: its declared map, and the mapper that builds them. */
919
+ type AppErrors<D extends ErrorMap> = {
920
+ readonly declared: D;
921
+ /** Returns the error a client receives. ts-pf sends one it returns unchanged as INTERNAL. */
922
+ readonly map: (error: unknown) => unknown;
923
+ };
924
+
925
+ /** Instances by slug and name; a relation's by slug, relation and operation. */
926
+ type RuntimeInstances<Ctx> = Readonly<
927
+ Record<
928
+ string,
929
+ | Readonly<
930
+ Record<
931
+ string,
932
+ Executable<Ctx> | Readonly<Record<string, Executable<Ctx>>>
933
+ >
934
+ >
935
+ | undefined
936
+ >
937
+ >;
938
+
939
+ /**
940
+ * A factory as the implementation of `build()` reads it. A method
941
+ * signature, so its parameter compares bivariantly with the precise
942
+ * factory the overload states.
943
+ */
944
+ type FactoryFn<Actor, W> = {
945
+ factory(wiring: W): RuntimeInstances<FamilyContext<Actor>>;
946
+ }['factory'];
947
+
948
+ /** What the methods factory receives, as the implementation builds it. */
949
+ type RuntimeWiring = {
950
+ readonly repos: Readonly<Record<string, Repo<AnyCollection>>>;
951
+ };
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
+
960
+ /**
961
+ * An app's definition: its family, its error map and its collections, with
962
+ * the methods and overrides attached to them. It holds no ports, so its
963
+ * `contract` needs no store and no publisher. `build()` wires it.
964
+ */
965
+ export class Framework<
966
+ Actor,
967
+ D extends ErrorMap,
968
+ E extends Entries,
969
+ Tenanted extends boolean = boolean,
970
+ > {
971
+ #contract: CheckedContract<E, D> | undefined;
972
+
973
+ constructor(
974
+ private readonly family: Family<Actor, Tenanted>,
975
+ private readonly errors: AppErrors<ErrorMap>,
976
+ private readonly entries: readonly Entry[],
977
+ ) {}
978
+
979
+ /**
980
+ * Adds a collection, and the methods and overrides attached to it. Its slug
981
+ * becomes its contract slice.
982
+ */
983
+ collection<
984
+ C extends AnyCollection,
985
+ const R extends AccessReturns<R, C>,
986
+ M extends {
987
+ [N in keyof M]: MethodCheck<M[N], C, N, FamilyContext<Actor>>;
988
+ } = Record<never, never>,
989
+ O extends {
990
+ [A in keyof O]: OverrideCheck<O[A], C, A, FamilyContext<Actor>>;
991
+ } = Record<never, never>,
992
+ >(
993
+ collection: C & SlugCheck<C, E> & TenantCheck<C, Tenanted>,
994
+ options: {
995
+ /**
996
+ * Who may do what (0021): `read` (find and get), `create`, `update`,
997
+ * `delete`, and one per method. A missing function denies.
998
+ */
999
+ readonly access: AccessFns<Actor, R, C>;
1000
+ readonly methods?: M;
1001
+ readonly overrides?: O;
1002
+ } & FieldsOption<Actor, C> &
1003
+ AccessCheck<R, M, C> &
1004
+ CascadeOverrideCheck<C, O>,
1005
+ ): Framework<
1006
+ Actor,
1007
+ D,
1008
+ E &
1009
+ Record<
1010
+ C['slug'],
1011
+ { collection: C; methods: M; overrides: O; join: false }
1012
+ > &
1013
+ JoinEntries<C>,
1014
+ Tenanted
1015
+ > {
1016
+ const { slug } = collection;
1017
+ if (collection.tenant !== undefined && this.family.tenantOf === undefined) {
1018
+ throw new Error(
1019
+ `Lattice: "${slug}" is tenanted, but the family has no tenantOf`,
1020
+ );
1021
+ }
1022
+ if (reservedNames.some((key) => key === slug)) {
1023
+ throw new Error(`Lattice: "${slug}" is a ts-pf implementer key`);
1024
+ }
1025
+ if (this.entries.some((entry) => entry.collection.slug === slug)) {
1026
+ throw new Error(`Lattice: "${slug}" is already a collection`);
1027
+ }
1028
+ const relations = Object.entries(collection.relations);
1029
+ const joins = relations.map(([, relation]) => relation.through);
1030
+ for (const join of joins) {
1031
+ if (
1032
+ join.slug === slug ||
1033
+ this.entries.some((entry) => entry.collection.slug === join.slug) ||
1034
+ joins.filter((other) => other.slug === join.slug).length > 1
1035
+ ) {
1036
+ throw new Error(
1037
+ `Lattice: the join collection "${join.slug}" is already a collection`,
1038
+ );
1039
+ }
1040
+ }
1041
+ for (const [name] of relations) {
1042
+ if (reservedNames.some((key) => key === name)) {
1043
+ throw new Error(
1044
+ `Lattice: relation "${slug}.${name}" is a ts-pf implementer key`,
1045
+ );
1046
+ }
1047
+ }
1048
+ const methods: Entry['methods'] = options.methods ?? {};
1049
+ for (const name of Object.keys(methods)) {
1050
+ if (
1051
+ [...reservedNames, ...actions, 'read'].some((key) => key === name) ||
1052
+ relations.some(([relation]) => relation === name) ||
1053
+ name.includes('.')
1054
+ ) {
1055
+ throw new Error(`Lattice: "${slug}.${name}" cannot be a method name`);
1056
+ }
1057
+ // Its summary is the tool description MCP sends a model, and the
1058
+ // admin's label for the action. Its effect gives MCP its hints. A
1059
+ // JavaScript caller, or a widened class, reaches here unchecked.
1060
+ const summary = methods[name]?.summary;
1061
+ const effect: unknown = methods[name]?.effect;
1062
+ if (
1063
+ typeof summary !== 'string' ||
1064
+ summary.trim() === '' ||
1065
+ !effects.some((known) => known === effect)
1066
+ ) {
1067
+ throw new Error(
1068
+ `Lattice: method "${slug}.${name}" needs a summary and an effect: one sentence on what it does, and whether it is 'read', 'write' or 'destructive'`,
1069
+ );
1070
+ }
1071
+ }
1072
+ const overrides: Entry['overrides'] = options.overrides ?? {};
1073
+ for (const [action, override] of Object.entries(overrides)) {
1074
+ const classes: [string, Ctor<unknown>][] =
1075
+ typeof override === 'function'
1076
+ ? [[action, override]]
1077
+ : Object.entries(override).map(
1078
+ ([op, cls]): [string, Ctor<unknown>] => [`${action}.${op}`, cls],
1079
+ );
1080
+ for (const [name, cls] of classes) {
1081
+ if ('summary' in cls || 'effect' in cls) {
1082
+ throw new Error(
1083
+ `Lattice: override "${slug}.${name}" keeps the generated summary and effect; remove its summary and effect statics`,
1084
+ );
1085
+ }
1086
+ }
1087
+ }
1088
+ const fields: FieldsMap = options.fields ?? {};
1089
+ const given = Object.keys(fields);
1090
+ const { maskable } = collection;
1091
+ if (
1092
+ given.length !== maskable.length ||
1093
+ !maskable.every((field) => Object.hasOwn(fields, field))
1094
+ ) {
1095
+ throw new Error(
1096
+ `Lattice: ${slug} needs exactly one fields rule for each maskable field (${maskable.join(', ') || 'none'}); it has ${given.join(', ') || 'none'}`,
1097
+ );
1098
+ }
1099
+ const cascading = collection.refs.find((ref) => ref.onDelete === 'cascade');
1100
+ if (overrides.delete !== undefined && cascading !== undefined) {
1101
+ throw new Error(
1102
+ `Lattice: ${slug} overrides delete, so ${slug}.${cascading.field} cannot cascade; use restrict or nullify`,
1103
+ );
1104
+ }
1105
+ // A relation's list runs the parent's read, and its set the parent's
1106
+ // update (0028).
1107
+ const declared: AccessMap = options.access;
1108
+ const access: AccessMap = Object.fromEntries([
1109
+ ...Object.entries(declared),
1110
+ ...relations.flatMap(([name]): [string, AccessMap[string]][] => [
1111
+ ...(declared.read === undefined
1112
+ ? []
1113
+ : [
1114
+ [`${name}.list`, declared.read] satisfies [
1115
+ string,
1116
+ AccessMap[string],
1117
+ ],
1118
+ ]),
1119
+ ...(declared.update === undefined
1120
+ ? []
1121
+ : [
1122
+ [`${name}.set`, declared.update] satisfies [
1123
+ string,
1124
+ AccessMap[string],
1125
+ ],
1126
+ ]),
1127
+ ]),
1128
+ ]);
1129
+ for (const action of Object.keys(overrides)) {
1130
+ if (
1131
+ !actions.some((key) => key === action) &&
1132
+ !relations.some(([relation]) => relation === action)
1133
+ ) {
1134
+ throw new Error(
1135
+ `Lattice: "${slug}.${action}" is not a generated operation or a relation`,
1136
+ );
1137
+ }
1138
+ }
1139
+ return new Framework<
1140
+ Actor,
1141
+ D,
1142
+ E &
1143
+ Record<
1144
+ C['slug'],
1145
+ { collection: C; methods: M; overrides: O; join: false }
1146
+ > &
1147
+ JoinEntries<C>,
1148
+ Tenanted
1149
+ >(this.family, this.errors, [
1150
+ ...this.entries,
1151
+ { collection, access, fields, methods, overrides, join: false },
1152
+ ...joins.map((join) => ({
1153
+ collection: join,
1154
+ access: {},
1155
+ fields: {},
1156
+ methods: {},
1157
+ overrides: {},
1158
+ join: true,
1159
+ })),
1160
+ ]);
1161
+ }
1162
+
1163
+ /**
1164
+ * The ts-pf contract: one slice per collection. Built on first read and
1165
+ * the same object after, so clients and codegen import it with no ports.
1166
+ */
1167
+ get contract(): CheckedContract<E, D> {
1168
+ checkSlugs(this.entries);
1169
+ this.#contract ??= contractOf<E, D>(this.entries, this.errors.declared);
1170
+ return this.#contract;
1171
+ }
1172
+
1173
+ /**
1174
+ * Wires the definition to its ports: the implemented router, the use
1175
+ * cases, the repos, and the edge's `onError`. `methods` and `overrides`
1176
+ * build the declared instances from the repos. The overload states the
1177
+ * precise types; the implementation works on the runtime shape, which a
1178
+ * loop over collections cannot express as a mapped type.
1179
+ */
1180
+ build<P extends EventPublisher>(
1181
+ options: BuildOptions<E, P, Actor, FamilyContext<Actor>>,
1182
+ ): Built<E, D, Actor>;
1183
+ build(options: {
1184
+ readonly store: CollectionStore;
1185
+ readonly events: EventPublisher;
1186
+ readonly access?: Access<Actor>;
1187
+ readonly methods?: FactoryFn<Actor, RuntimeWiring>;
1188
+ readonly overrides?: FactoryFn<Actor, RuntimeOverrideWiring>;
1189
+ }): {
1190
+ readonly app: ImplementedRouter<unknown, CallContext<Actor>>;
1191
+ readonly useCases: Readonly<
1192
+ Record<string, Readonly<Record<string, unknown>>>
1193
+ >;
1194
+ readonly repos: RuntimeWiring['repos'];
1195
+ readonly onError: typeof unexpectedErrors;
1196
+ readonly ensure: () => Promise<void>;
1197
+ readonly context: (base: CallContext<Actor>) => FamilyContext<Actor>;
1198
+ } {
1199
+ checkSlugs(this.entries);
1200
+ const { store, events } = options;
1201
+ const referrers = referrersOf(
1202
+ this.entries.map((entry) => entry.collection),
1203
+ );
1204
+ const collections = new Map(
1205
+ this.entries.map(({ collection }) => [collection.slug, collection]),
1206
+ );
1207
+ const access =
1208
+ options.access ??
1209
+ new CollectionAccess(
1210
+ new Map(
1211
+ this.entries.map((entry) => [entry.collection.slug, entry.access]),
1212
+ ),
1213
+ new Map(
1214
+ this.entries.map((entry) => [entry.collection.slug, entry.fields]),
1215
+ ),
1216
+ );
1217
+ const context = (base: CallContext<Actor>): FamilyContext<Actor> =>
1218
+ familyContext(access, base, this.family);
1219
+ const repos = Object.fromEntries(
1220
+ this.entries.map(({ collection }) => [
1221
+ collection.slug,
1222
+ repo(store, collection),
1223
+ ]),
1224
+ );
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
+ });
1325
+ // Each operation and method's use case, and each relation operation's,
1326
+ // by slug: the procedures of a slice and its nested relation nodes.
1327
+ const operationUseCases: Record<
1328
+ string,
1329
+ Record<string, Executable<Ctx>>
1330
+ > = {};
1331
+ const relationUseCases: Record<
1332
+ string,
1333
+ Record<string, Record<string, Executable<Ctx>>>
1334
+ > = {};
1335
+ for (const { entry, ops, operationsOf, relations } of slices) {
1336
+ const { collection, methods } = entry;
1337
+ const { slug } = collection;
1338
+ const sliceUseCases: Record<string, Executable<Ctx>> = {};
1339
+ for (const { action, input, body, override } of operationsOf) {
1340
+ sliceUseCases[action] =
1341
+ override === undefined
1342
+ ? generatedUseCase(
1343
+ this.family,
1344
+ `${slug}.${action}`,
1345
+ { collection, input, output: ops[action].output },
1346
+ body,
1347
+ )
1348
+ : instanceOf(
1349
+ 'override',
1350
+ [slug, action],
1351
+ override,
1352
+ overrideInstances,
1353
+ );
1354
+ }
1355
+ for (const [name, method] of Object.entries(methods)) {
1356
+ sliceUseCases[name] = instanceOf(
1357
+ 'method',
1358
+ [slug, name],
1359
+ method,
1360
+ methodInstances,
1361
+ );
1362
+ }
1363
+ operationUseCases[slug] = sliceUseCases;
1364
+ const sliceRelations: Record<
1365
+ string,
1366
+ Record<string, Executable<Ctx>>
1367
+ > = {};
1368
+ for (const { name, relation, ops: relationOperations } of relations) {
1369
+ const opUseCases: Record<string, Executable<Ctx>> = {};
1370
+ for (const { op, body, override } of relationOperations) {
1371
+ opUseCases[op] =
1372
+ override === undefined
1373
+ ? generatedUseCase(
1374
+ this.family,
1375
+ `${slug}.${name}.${op}`,
1376
+ { collection, ...relation[op] },
1377
+ body,
1378
+ )
1379
+ : instanceOf(
1380
+ 'override',
1381
+ [slug, name, op],
1382
+ override,
1383
+ overrideInstances,
1384
+ );
1385
+ }
1386
+ sliceRelations[name] = opUseCases;
1387
+ }
1388
+ relationUseCases[slug] = sliceRelations;
1389
+ }
1390
+
1391
+ // One implementer per slice and per relation node, each typed by its own
1392
+ // procedures: ts-pf's types read a node that may be a procedure or a
1393
+ // router as a procedure. The root router places each procedure at its
1394
+ // path and checks the tree against the whole contract.
1395
+ const contract: RuntimeContract = this.contract;
1396
+ // Masking reads each output schema once, here. With no maskable field
1397
+ // in the app, nothing can be masked, so no schema needs reading.
1398
+ const masking = this.entries.some(
1399
+ ({ collection }) => collection.maskable.length > 0,
1400
+ );
1401
+ const maskOf = (
1402
+ path: readonly string[],
1403
+ procedure: RuntimeProcedure,
1404
+ ): Mask | undefined => {
1405
+ if (!masking) return undefined;
1406
+ const where = path.join('.');
1407
+ const { output } = procedure['~pf'];
1408
+ if (!(output instanceof z.core.$ZodType)) {
1409
+ throw new Error(
1410
+ `Lattice: the output of "${where}" is not a Zod schema, which Lattice cannot see through to mask a field`,
1411
+ );
1412
+ }
1413
+ const plan = maskPlan(output, where);
1414
+ if (plan === undefined) return undefined;
1415
+ return {
1416
+ plan,
1417
+ collections: [...maskedCollections(plan)].flatMap((slug) => {
1418
+ const found = collections.get(slug);
1419
+ return found === undefined ? [] : [found];
1420
+ }),
1421
+ };
1422
+ };
1423
+ type Implemented = ImplementedProcedure<
1424
+ RuntimeProcedure,
1425
+ CallContext<Actor>
1426
+ >;
1427
+ const tree: Record<
1428
+ string,
1429
+ Record<string, Implemented | Record<string, Implemented>>
1430
+ > = {};
1431
+ const implement = (
1432
+ path: readonly string[],
1433
+ procedures: Readonly<Record<string, RuntimeProcedure>>,
1434
+ useCasesOf: Readonly<Record<string, Executable<Ctx>>> | undefined,
1435
+ ): Record<string, Implemented> => {
1436
+ const impl = createImplementer(procedures).$context<CallContext<Actor>>();
1437
+ const node: Record<string, Implemented> = {};
1438
+ for (const [name, procedure] of Object.entries(procedures)) {
1439
+ const builder = impl[name];
1440
+ const useCase = useCasesOf?.[name];
1441
+ if (builder === undefined || useCase === undefined) {
1442
+ throw new Error(
1443
+ `Lattice: no procedure "${[...path, name].join('.')}"`,
1444
+ );
1445
+ }
1446
+ const mask = maskOf([...path, name], procedure);
1447
+ // A fresh context per call: a createLocalClient context object is
1448
+ // shared by every call, and access answers are kept on the context.
1449
+ // Every procedure's output is masked here, generated or not, so an
1450
+ // override or a method cannot skip it.
1451
+ node[name] = builder.handler(async ({ input, context: base }) => {
1452
+ const ctx = context(base);
1453
+ const output = await useCase.execute(ctx, input);
1454
+ return mask === undefined ? output : masked(mask, output, ctx);
1455
+ });
1456
+ }
1457
+ return node;
1458
+ };
1459
+ for (const [slug, slice] of Object.entries(contract)) {
1460
+ const procedures: Record<string, RuntimeProcedure> = {};
1461
+ const nodes: Record<string, Record<string, RuntimeProcedure>> = {};
1462
+ for (const [name, node] of Object.entries(slice)) {
1463
+ if (isProcedure(node)) procedures[name] = node;
1464
+ else nodes[name] = node;
1465
+ }
1466
+ const sliceTree: Record<
1467
+ string,
1468
+ Implemented | Record<string, Implemented>
1469
+ > = implement([slug], procedures, operationUseCases[slug]);
1470
+ for (const [name, node] of Object.entries(nodes)) {
1471
+ sliceTree[name] = implement(
1472
+ [slug, name],
1473
+ node,
1474
+ relationUseCases[slug]?.[name],
1475
+ );
1476
+ }
1477
+ tree[slug] = sliceTree;
1478
+ }
1479
+ const useCases = Object.fromEntries(
1480
+ Object.entries(operationUseCases).map(([slug, sliceUseCases]) => [
1481
+ slug,
1482
+ { ...sliceUseCases, ...relationUseCases[slug] },
1483
+ ]),
1484
+ );
1485
+ const errors = clientCalls(this.family, this.errors.map);
1486
+ return {
1487
+ app: rootRouter<CallContext<Actor>>(
1488
+ createImplementer(contract).$context<CallContext<Actor>>().use(errors),
1489
+ tree,
1490
+ ),
1491
+ useCases,
1492
+ repos,
1493
+ onError: unexpectedErrors,
1494
+ ensure: async () => {
1495
+ for (const { collection } of this.entries) {
1496
+ if (collection.indexes.length === 0) continue;
1497
+ await store.ensure(collection.slug, collection.indexes);
1498
+ }
1499
+ },
1500
+ context,
1501
+ };
1502
+ }
1503
+ }
1504
+
1505
+ /** Throws on a ref whose slug is not a collection of `entries`. */
1506
+ function checkSlugs(entries: readonly Entry[]): void {
1507
+ const slugs = new Set(entries.map((entry) => entry.collection.slug));
1508
+ for (const { collection } of entries) {
1509
+ for (const { field, slug } of collection.refs) {
1510
+ if (!slugs.has(slug)) {
1511
+ throw new Error(
1512
+ `Lattice: ${collection.slug}.${field} refers to "${slug}", which is not a collection of this framework`,
1513
+ );
1514
+ }
1515
+ }
1516
+ }
1517
+ }
1518
+
1519
+ /**
1520
+ * The contract of `entries`: Lattice's declared errors and the app's on
1521
+ * every procedure. The overload states its type; the implementation builds
1522
+ * it in a loop over collections, which a mapped type cannot express.
1523
+ */
1524
+ function contractOf<E extends Entries, D extends ErrorMap>(
1525
+ entries: readonly Entry[],
1526
+ declared: ErrorMap,
1527
+ ): CheckedContract<E, D>;
1528
+ function contractOf(
1529
+ entries: readonly Entry[],
1530
+ declared: ErrorMap,
1531
+ ): RuntimeContract {
1532
+ const call = procedure.errors({ ...declaredErrors, ...declared });
1533
+ // What a client receives of each collection's documents: each maskable
1534
+ // field optional. Where and sort stay on the stored output, so a caller
1535
+ // allowed to read a field can filter by it.
1536
+ const outputs = new Map(
1537
+ entries.map(({ collection }) => [collection.slug, collection.clientOutput]),
1538
+ );
1539
+ /** A page of `doc`s, as find and list return them. */
1540
+ const page = (doc: z.ZodObject) =>
1541
+ z.object({ docs: z.array(doc), next: z.string().nullable() });
1542
+ const slices: RuntimeContract = {};
1543
+ for (const { collection, methods, overrides, join } of entries) {
1544
+ if (join) continue;
1545
+ const slice: Record<string, RuntimeProcedure | RuntimeRelation> = {};
1546
+ const ops = operations(collection.schema, collection.output);
1547
+ const doc = collection.clientOutput;
1548
+ const { slug, label } = collection;
1549
+ for (const action of actions) {
1550
+ const output =
1551
+ action === 'count'
1552
+ ? ops.count.output
1553
+ : action === 'find'
1554
+ ? page(doc)
1555
+ : doc;
1556
+ slice[action] = call
1557
+ .meta(generatedMeta({ slug, label, op: action, populate: [] }))
1558
+ .input(ops[action].input)
1559
+ .output(output);
1560
+ }
1561
+ // A read's output follows its `populate` list, through ts-pf's
1562
+ // expandable outputs (0022): the output is the wide document.
1563
+ // An overridden read is plain: Lattice populates in the generated one.
1564
+ if (
1565
+ overrides.get === undefined &&
1566
+ populateKeys(collection, 'get').length > 0
1567
+ ) {
1568
+ const { fields, wide } = expansionOf(collection, outputs, 'get');
1569
+ slice.get = call
1570
+ .meta(
1571
+ generatedMeta({
1572
+ slug,
1573
+ label,
1574
+ op: 'get',
1575
+ populate: populateKeys(collection, 'get'),
1576
+ }),
1577
+ )
1578
+ .input(
1579
+ ops.get.input.extend(
1580
+ populateInput(populateKeys(collection, 'get')).shape,
1581
+ ),
1582
+ )
1583
+ .output(wide)
1584
+ .expand({ key: 'populate', fields });
1585
+ }
1586
+ if (
1587
+ overrides.find === undefined &&
1588
+ populateKeys(collection, 'find').length > 0
1589
+ ) {
1590
+ const { fields, wide } = expansionOf(collection, outputs, 'find');
1591
+ slice.find = call
1592
+ .meta(
1593
+ generatedMeta({
1594
+ slug,
1595
+ label,
1596
+ op: 'find',
1597
+ populate: populateKeys(collection, 'find'),
1598
+ }),
1599
+ )
1600
+ .input(
1601
+ ops.find.input.extend(
1602
+ populateInput(populateKeys(collection, 'find')).shape,
1603
+ ),
1604
+ )
1605
+ .output(page(wide))
1606
+ .expand({ key: 'populate', at: ['docs'], fields });
1607
+ }
1608
+ for (const [name, method] of Object.entries(methods)) {
1609
+ const { summary, effect } = method;
1610
+ slice[name] = call
1611
+ .meta(methodMeta({ slug, label, name, summary, effect }))
1612
+ .input(method.input)
1613
+ .output(method.output);
1614
+ }
1615
+ for (const [name, relation] of Object.entries(collection.relations)) {
1616
+ const declared = overrides[name];
1617
+ const { fields, wide } = expansionOf(relation.through, outputs, 'find');
1618
+ const listed =
1619
+ typeof declared === 'object' && declared.list !== undefined;
1620
+ const list = call.meta(
1621
+ generatedMeta({
1622
+ slug,
1623
+ label,
1624
+ op: 'list',
1625
+ relation: name,
1626
+ target: relation.target,
1627
+ populate: listed ? [] : Object.keys(fields),
1628
+ }),
1629
+ );
1630
+ slice[name] = {
1631
+ list: listed
1632
+ ? list.input(relation.list.input).output(relation.list.output)
1633
+ : list
1634
+ .input(relation.list.input)
1635
+ .output(page(wide))
1636
+ .expand({ key: 'populate', at: ['docs'], fields }),
1637
+ set: call
1638
+ .meta(
1639
+ generatedMeta({
1640
+ slug,
1641
+ label,
1642
+ op: 'set',
1643
+ relation: name,
1644
+ target: relation.target,
1645
+ populate: [],
1646
+ }),
1647
+ )
1648
+ .input(relation.set.input)
1649
+ .output(relation.set.output),
1650
+ };
1651
+ }
1652
+ slices[collection.slug] = slice;
1653
+ }
1654
+ return router(slices);
1655
+ }
1656
+
1657
+ /**
1658
+ * The edge's `onError`, such as `FetchHandler`'s: it logs each unexpected
1659
+ * error (ts-pf's `isUnexpectedError`) that no family logged as a failure. A
1660
+ * throw inside `execute` reaches the edge unchanged, and the family has
1661
+ * logged it once already. Logged here: a throw the family never saw, such as
1662
+ * the context factory's or ts-pf's output check, and a refusal the app's
1663
+ * map keeps from clients, which the family logged only at info. Typed
1664
+ * structurally, so core needs no `@ts-pf/server-http`: it fits
1665
+ * `FetchHandlerOnError`, which also passes the request.
1666
+ */
1667
+ function unexpectedErrors(logger: Logger): (error: unknown) => void {
1668
+ return (error) => {
1669
+ if (!isUnexpectedError(error) || loggedByFamily(error) === 'failed') {
1670
+ return;
1671
+ }
1672
+ if (error instanceof Error) logger.error(error);
1673
+ else logger.error('Unexpected error', { thrown: error });
1674
+ };
1675
+ }
1676
+
1677
+ /**
1678
+ * The instance passed to `build()` for one declared class. The type check is
1679
+ * structural, so it accepts a different class with the same members;
1680
+ * `instanceof` catches that here.
1681
+ */
1682
+ function instanceOf<Ctx>(
1683
+ kind: 'method' | 'override',
1684
+ path: readonly [string, string] | readonly [string, string, string],
1685
+ declared: Ctor<unknown>,
1686
+ instances: RuntimeInstances<Ctx> | undefined,
1687
+ ): Executable<Ctx> {
1688
+ const [slug, name, op] = path;
1689
+ const found = instances?.[slug]?.[name];
1690
+ // A relation's instances are one more level down, by operation.
1691
+ const instance =
1692
+ op === undefined || found === undefined || isExecutable(found)
1693
+ ? found
1694
+ : found[op];
1695
+ const at = path.join('.');
1696
+ if (instance === undefined || !isExecutable(instance)) {
1697
+ throw new Error(`Lattice: no instance for ${kind} "${at}"`);
1698
+ }
1699
+ if (!(instance instanceof declared)) {
1700
+ throw new Error(
1701
+ `Lattice: "${at}" instance is not an instance of ${declared.name}`,
1702
+ );
1703
+ }
1704
+ return instance;
1705
+ }
1706
+
1707
+ /**
1708
+ * Whether a value is an implementer node, which has `router()`. The
1709
+ * predicate claims that `router()` returns the implemented router, as its
1710
+ * signature in ts-pf says, but checks only that `router` is a function.
1711
+ * The claim is not left unguarded: ts-pf's `router()` checks the tree
1712
+ * against the whole contract at runtime, and throws on a missing or extra
1713
+ * implementation (build.test.ts proves it). The predicate goes with
1714
+ * `rootRouter()`.
1715
+ */
1716
+ function hasRouter<Ctx>(
1717
+ value: object,
1718
+ ): value is { router(tree: object): ImplementedRouter<unknown, Ctx> } {
1719
+ return 'router' in value && typeof value.router === 'function';
1720
+ }
1721
+
1722
+ /**
1723
+ * The finished root router. The runtime contract's slice node is
1724
+ * `RuntimeProcedure | RuntimeRelation`, and ts-pf (1.0) types a node that
1725
+ * may be a procedure as one: `IsContractProcedure` of the union is true, so
1726
+ * `RouterImplCheck` wants an implemented procedure where a relation's
1727
+ * router sits. The root implementer's `router()` is therefore called
1728
+ * through its runtime shape, and its result typed by `hasRouter`. At
1729
+ * runtime ts-pf still checks the tree against the whole contract, sets each
1730
+ * procedure's path and adds the root middleware. This function and
1731
+ * `hasRouter` go when ts-pf ships a `RouterImplCheck` that decides a mixed
1732
+ * node by the implementation's node, or a public guard for an implemented
1733
+ * router. Exported for its test only; it is not in index.ts.
1734
+ */
1735
+ export function rootRouter<Ctx>(
1736
+ implementer: object,
1737
+ tree: object,
1738
+ ): ImplementedRouter<unknown, Ctx> {
1739
+ if (!hasRouter<Ctx>(implementer)) {
1740
+ throw new Error('Lattice: the ts-pf implementer has no router()');
1741
+ }
1742
+ return implementer.router(tree);
1743
+ }
1744
+
1745
+ /** Whether an instance entry is a use case, not a relation's map of them. */
1746
+ function isExecutable<Ctx>(
1747
+ value: Executable<Ctx> | Readonly<Record<string, Executable<Ctx>>>,
1748
+ ): value is Executable<Ctx> {
1749
+ return 'execute' in value && typeof value.execute === 'function';
1750
+ }
1751
+
1752
+ /**
1753
+ * The middleware on every procedure, and the only one, so the outermost.
1754
+ *
1755
+ * - It traces the call: one span per procedure, active while the procedure
1756
+ * runs, so the use case's span and the store's spans nest under it. Its
1757
+ * outcome is what the client receives.
1758
+ * - It replaces a thrown error with the one the client receives
1759
+ * (`toClientError`).
1760
+ * - It logs each refusal no family logged, once, at info: a guard's, and
1761
+ * ts-pf's own input check, which runs after `.use()` middleware. An error
1762
+ * sent as INTERNAL is the edge's `onError` to log.
1763
+ *
1764
+ * One middleware, because the span and the log both read the error the
1765
+ * client receives.
1766
+ */
1767
+ function clientCalls<Actor>(
1768
+ family: Family<Actor>,
1769
+ map: (error: unknown) => unknown,
1770
+ ): MiddlewareFn<CallContext<Actor>> {
1771
+ return async ({ context, next, path }) => {
1772
+ const span = tracer.startSpan(path.join('/'), { kind: SpanKind.SERVER });
1773
+ // A real span, sampled or not, is made active, so the use case's span
1774
+ // and the store's nest under it and share its sampling. The no-op API's
1775
+ // span has no context to pass on, so without an SDK the call makes none.
1776
+ const recording = span.isRecording();
1777
+ // By identity: the no-op span carries the API's one invalid context.
1778
+ const active = span.spanContext() !== INVALID_SPAN_CONTEXT;
1779
+ if (recording) {
1780
+ span.setAttributes({
1781
+ 'rpc.system': 'ts-pf',
1782
+ 'rpc.service': path[0] ?? '',
1783
+ 'rpc.method': path.slice(1).join('/'),
1784
+ });
1785
+ }
1786
+ try {
1787
+ const output = await (active
1788
+ ? otel.with(trace.setSpan(otel.active(), span), next)
1789
+ : next());
1790
+ if (recording) span.setAttribute('lattice.outcome', 'ok');
1791
+ return output;
1792
+ } catch (error) {
1793
+ const sent = toClientError(error, map);
1794
+ if (!isPFError(sent) || sent.code === 'INTERNAL') {
1795
+ failed(span, error);
1796
+ throw sent;
1797
+ }
1798
+ // A refusal is the caller's, not a failure: the status stays UNSET.
1799
+ if (recording) {
1800
+ span.setAttributes({
1801
+ 'lattice.outcome': 'refused',
1802
+ 'lattice.code': sent.code,
1803
+ });
1804
+ }
1805
+ if (loggedByFamily(error) === undefined) {
1806
+ const [collection, action] = path;
1807
+ // The guards may not have checked the actor yet.
1808
+ const actor = validate(family.actor, context.actor);
1809
+ context.logger.info(path.join('.'), {
1810
+ collection,
1811
+ action,
1812
+ ...(actor.ok ? callerFields(family, actor.value) : {}),
1813
+ outcome: 'refused',
1814
+ ...(refusal(error) ?? { code: sent.code }),
1815
+ });
1816
+ }
1817
+ throw sent;
1818
+ } finally {
1819
+ span.end();
1820
+ }
1821
+ };
1822
+ }
1823
+
1824
+ /**
1825
+ * Starts an app's definition: the family every generated and hand-written
1826
+ * use case extends, and the app's client errors. It takes no ports;
1827
+ * `build()` does.
1828
+ */
1829
+ export function framework<
1830
+ Actor,
1831
+ Tenanted extends boolean,
1832
+ D extends ErrorMap = Record<never, never>,
1833
+ >(options: {
1834
+ family: Family<Actor, Tenanted>;
1835
+ /**
1836
+ * The app's client errors, such as app-template's `clientErrors` and
1837
+ * `toRpcError`. Every procedure declares them next to Lattice's codes. An
1838
+ * app with no domain errors leaves this out.
1839
+ */
1840
+ errors?: {
1841
+ readonly declared: D & DeclaredCheck<D>;
1842
+ readonly map: (error: unknown) => unknown;
1843
+ };
1844
+ }): Framework<Actor, D, Record<never, never>, Tenanted> {
1845
+ const errors = options.errors ?? { declared: {}, map: (error) => error };
1846
+ for (const code of Object.keys(errors.declared)) {
1847
+ if (latticeCodes.includes(code)) {
1848
+ throw new Error(`Lattice: "${code}" is a Lattice error code`);
1849
+ }
1850
+ }
1851
+ return new Framework<Actor, D, Record<never, never>, Tenanted>(
1852
+ options.family,
1853
+ errors,
1854
+ [],
1855
+ );
1856
+ }
1857
+
1858
+ /** A procedure's mask: where its output holds maskable fields, and whose. */
1859
+ type Mask = {
1860
+ readonly plan: MaskPlan;
1861
+ readonly collections: readonly AnyCollection[];
1862
+ };
1863
+
1864
+ /**
1865
+ * `output` without the fields the caller's rules withhold, asked once per
1866
+ * call per collection. A field of a collection outside the app is withheld.
1867
+ */
1868
+ async function masked(
1869
+ mask: Mask,
1870
+ output: unknown,
1871
+ ctx: { readonly access: CallAccess },
1872
+ ): Promise<unknown> {
1873
+ const withheld = new Map(
1874
+ await Promise.all(
1875
+ mask.collections.map(
1876
+ async (collection): Promise<[string, ReadonlySet<string>]> => [
1877
+ collection.slug,
1878
+ await CallAccess.withheld(ctx.access, collection),
1879
+ ],
1880
+ ),
1881
+ ),
1882
+ );
1883
+ return applyMask(
1884
+ mask.plan,
1885
+ output,
1886
+ ({ collection, field }) => withheld.get(collection)?.has(field) ?? true,
1887
+ );
1888
+ }