@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/dist/build.js ADDED
@@ -0,0 +1,655 @@
1
+ import { INVALID_SPAN_CONTEXT, context as otel, SpanKind, trace, } from '@opentelemetry/api';
2
+ import { isContractProcedure, procedure, router, } from '@ts-pf/contract';
3
+ import { isPFError, isUnexpectedError } from '@ts-pf/protocol';
4
+ import { createImplementer, } from '@ts-pf/server';
5
+ import { validate } from 'hexok';
6
+ import { z } from 'zod';
7
+ import { CallAccess, CollectionAccess, familyContext, } from './access.js';
8
+ import { operations, } from './collection.js';
9
+ import { generatedUseCase, operationBody, relationBody, } from './crud.js';
10
+ import { generatedMeta, methodMeta } from './describe.js';
11
+ import { declaredErrors, latticeCodes, refusal, toClientError, } from './errors.js';
12
+ import { callerFields, loggedByFamily, } from './family.js';
13
+ import { applyMask, maskedCollections, maskPlan, } from './mask.js';
14
+ import { expansionOf, populateInput, populateKeys, } from './populate.js';
15
+ import { referrersOf } from './relations.js';
16
+ import { repo } from './repo.js';
17
+ import { failed, tracer } from './tracing.js';
18
+ const actions = [
19
+ 'find',
20
+ 'count',
21
+ 'get',
22
+ 'create',
23
+ 'update',
24
+ 'delete',
25
+ ];
26
+ /** The effects `@ts-pf/mcp` knows, which a method's `effect` must be one of. */
27
+ const effects = ['read', 'write', 'destructive'];
28
+ /**
29
+ * Names a collection slug, a relation or a method cannot take: ts-pf
30
+ * `Implementer` keys, whose members they would shadow in the router.
31
+ */
32
+ export const reservedNames = [
33
+ '$context',
34
+ 'use',
35
+ 'useAfter',
36
+ 'middleware',
37
+ 'router',
38
+ ];
39
+ /** The relation operations Lattice generates. */
40
+ const relationOps = ['list', 'set'];
41
+ /** Whether a slice's node is a procedure, not a relation's node. */
42
+ function isProcedure(node) {
43
+ return isContractProcedure(node);
44
+ }
45
+ /**
46
+ * An app's definition: its family, its error map and its collections, with
47
+ * the methods and overrides attached to them. It holds no ports, so its
48
+ * `contract` needs no store and no publisher. `build()` wires it.
49
+ */
50
+ export class Framework {
51
+ family;
52
+ errors;
53
+ entries;
54
+ #contract;
55
+ constructor(family, errors, entries) {
56
+ this.family = family;
57
+ this.errors = errors;
58
+ this.entries = entries;
59
+ }
60
+ /**
61
+ * Adds a collection, and the methods and overrides attached to it. Its slug
62
+ * becomes its contract slice.
63
+ */
64
+ collection(collection, options) {
65
+ const { slug } = collection;
66
+ if (collection.tenant !== undefined && this.family.tenantOf === undefined) {
67
+ throw new Error(`Lattice: "${slug}" is tenanted, but the family has no tenantOf`);
68
+ }
69
+ if (reservedNames.some((key) => key === slug)) {
70
+ throw new Error(`Lattice: "${slug}" is a ts-pf implementer key`);
71
+ }
72
+ if (this.entries.some((entry) => entry.collection.slug === slug)) {
73
+ throw new Error(`Lattice: "${slug}" is already a collection`);
74
+ }
75
+ const relations = Object.entries(collection.relations);
76
+ const joins = relations.map(([, relation]) => relation.through);
77
+ for (const join of joins) {
78
+ if (join.slug === slug ||
79
+ this.entries.some((entry) => entry.collection.slug === join.slug) ||
80
+ joins.filter((other) => other.slug === join.slug).length > 1) {
81
+ throw new Error(`Lattice: the join collection "${join.slug}" is already a collection`);
82
+ }
83
+ }
84
+ for (const [name] of relations) {
85
+ if (reservedNames.some((key) => key === name)) {
86
+ throw new Error(`Lattice: relation "${slug}.${name}" is a ts-pf implementer key`);
87
+ }
88
+ }
89
+ const methods = options.methods ?? {};
90
+ for (const name of Object.keys(methods)) {
91
+ if ([...reservedNames, ...actions, 'read'].some((key) => key === name) ||
92
+ relations.some(([relation]) => relation === name) ||
93
+ name.includes('.')) {
94
+ throw new Error(`Lattice: "${slug}.${name}" cannot be a method name`);
95
+ }
96
+ // Its summary is the tool description MCP sends a model, and the
97
+ // admin's label for the action. Its effect gives MCP its hints. A
98
+ // JavaScript caller, or a widened class, reaches here unchecked.
99
+ const summary = methods[name]?.summary;
100
+ const effect = methods[name]?.effect;
101
+ if (typeof summary !== 'string' ||
102
+ summary.trim() === '' ||
103
+ !effects.some((known) => known === effect)) {
104
+ throw new Error(`Lattice: method "${slug}.${name}" needs a summary and an effect: one sentence on what it does, and whether it is 'read', 'write' or 'destructive'`);
105
+ }
106
+ }
107
+ const overrides = options.overrides ?? {};
108
+ for (const [action, override] of Object.entries(overrides)) {
109
+ const classes = typeof override === 'function'
110
+ ? [[action, override]]
111
+ : Object.entries(override).map(([op, cls]) => [`${action}.${op}`, cls]);
112
+ for (const [name, cls] of classes) {
113
+ if ('summary' in cls || 'effect' in cls) {
114
+ throw new Error(`Lattice: override "${slug}.${name}" keeps the generated summary and effect; remove its summary and effect statics`);
115
+ }
116
+ }
117
+ }
118
+ const fields = options.fields ?? {};
119
+ const given = Object.keys(fields);
120
+ const { maskable } = collection;
121
+ if (given.length !== maskable.length ||
122
+ !maskable.every((field) => Object.hasOwn(fields, field))) {
123
+ throw new Error(`Lattice: ${slug} needs exactly one fields rule for each maskable field (${maskable.join(', ') || 'none'}); it has ${given.join(', ') || 'none'}`);
124
+ }
125
+ const cascading = collection.refs.find((ref) => ref.onDelete === 'cascade');
126
+ if (overrides.delete !== undefined && cascading !== undefined) {
127
+ throw new Error(`Lattice: ${slug} overrides delete, so ${slug}.${cascading.field} cannot cascade; use restrict or nullify`);
128
+ }
129
+ // A relation's list runs the parent's read, and its set the parent's
130
+ // update (0028).
131
+ const declared = options.access;
132
+ const access = Object.fromEntries([
133
+ ...Object.entries(declared),
134
+ ...relations.flatMap(([name]) => [
135
+ ...(declared.read === undefined
136
+ ? []
137
+ : [
138
+ [`${name}.list`, declared.read],
139
+ ]),
140
+ ...(declared.update === undefined
141
+ ? []
142
+ : [
143
+ [`${name}.set`, declared.update],
144
+ ]),
145
+ ]),
146
+ ]);
147
+ for (const action of Object.keys(overrides)) {
148
+ if (!actions.some((key) => key === action) &&
149
+ !relations.some(([relation]) => relation === action)) {
150
+ throw new Error(`Lattice: "${slug}.${action}" is not a generated operation or a relation`);
151
+ }
152
+ }
153
+ return new Framework(this.family, this.errors, [
154
+ ...this.entries,
155
+ { collection, access, fields, methods, overrides, join: false },
156
+ ...joins.map((join) => ({
157
+ collection: join,
158
+ access: {},
159
+ fields: {},
160
+ methods: {},
161
+ overrides: {},
162
+ join: true,
163
+ })),
164
+ ]);
165
+ }
166
+ /**
167
+ * The ts-pf contract: one slice per collection. Built on first read and
168
+ * the same object after, so clients and codegen import it with no ports.
169
+ */
170
+ get contract() {
171
+ checkSlugs(this.entries);
172
+ this.#contract ??= contractOf(this.entries, this.errors.declared);
173
+ return this.#contract;
174
+ }
175
+ build(options) {
176
+ checkSlugs(this.entries);
177
+ const { store, events } = options;
178
+ const referrers = referrersOf(this.entries.map((entry) => entry.collection));
179
+ const collections = new Map(this.entries.map(({ collection }) => [collection.slug, collection]));
180
+ const access = options.access ??
181
+ new CollectionAccess(new Map(this.entries.map((entry) => [entry.collection.slug, entry.access])), new Map(this.entries.map((entry) => [entry.collection.slug, entry.fields])));
182
+ const context = (base) => familyContext(access, base, this.family);
183
+ const repos = Object.fromEntries(this.entries.map(({ collection }) => [
184
+ collection.slug,
185
+ repo(store, collection),
186
+ ]));
187
+ // Every generated operation, with its body and the class that overrides
188
+ // it, if any: a generated use case runs the body, and an override may
189
+ // call it as `generated` (0036). Whether an operation is overridden is
190
+ // decided here, once, for both.
191
+ const slices = this.entries.flatMap((entry) => {
192
+ if (entry.join)
193
+ return [];
194
+ const { collection, overrides } = entry;
195
+ const ops = operations(collection.schema, collection.output);
196
+ const operationsOf = actions.map((action) => {
197
+ // A read takes `populate`: one schema, for its input and its body.
198
+ const populate = populateInput(action === 'get' || action === 'find'
199
+ ? populateKeys(collection, action)
200
+ : []);
201
+ const declared = overrides[action];
202
+ return {
203
+ action,
204
+ input: ops[action].input.extend(populate.shape),
205
+ body: operationBody(this.family, store, events, collection, ops, action, populate, referrers, collections),
206
+ override: typeof declared === 'function' ? declared : undefined,
207
+ };
208
+ });
209
+ const relations = Object.entries(collection.relations).map(([name, relation]) => {
210
+ const declared = overrides[name];
211
+ const opOverrides = declared === undefined || typeof declared === 'function'
212
+ ? {}
213
+ : declared;
214
+ return {
215
+ name,
216
+ relation,
217
+ ops: relationOps.map((op) => ({
218
+ op,
219
+ body: relationBody(this.family, store, events, collection, name, relation, op, collections),
220
+ override: opOverrides[op],
221
+ })),
222
+ };
223
+ });
224
+ return [{ entry, ops, operationsOf, relations }];
225
+ });
226
+ // Only the overridden operations' bodies: what each override may call.
227
+ const generatedBodies = Object.fromEntries(slices.flatMap(({ entry, operationsOf, relations }) => {
228
+ const declared = {
229
+ ...Object.fromEntries(operationsOf
230
+ .filter(({ override }) => override !== undefined)
231
+ .map(({ action, body }) => [action, body])),
232
+ ...Object.fromEntries(relations.flatMap(({ name, ops }) => {
233
+ const overridden = ops.filter(({ override }) => override !== undefined);
234
+ return overridden.length === 0
235
+ ? []
236
+ : [
237
+ [
238
+ name,
239
+ Object.fromEntries(overridden.map(({ op, body }) => [op, body])),
240
+ ],
241
+ ];
242
+ })),
243
+ };
244
+ return Object.keys(declared).length === 0
245
+ ? []
246
+ : [[entry.collection.slug, declared]];
247
+ }));
248
+ const methodInstances = options.methods?.({ repos });
249
+ const overrideInstances = options.overrides?.({
250
+ repos,
251
+ generated: generatedBodies,
252
+ });
253
+ // Each operation and method's use case, and each relation operation's,
254
+ // by slug: the procedures of a slice and its nested relation nodes.
255
+ const operationUseCases = {};
256
+ const relationUseCases = {};
257
+ for (const { entry, ops, operationsOf, relations } of slices) {
258
+ const { collection, methods } = entry;
259
+ const { slug } = collection;
260
+ const sliceUseCases = {};
261
+ for (const { action, input, body, override } of operationsOf) {
262
+ sliceUseCases[action] =
263
+ override === undefined
264
+ ? generatedUseCase(this.family, `${slug}.${action}`, { collection, input, output: ops[action].output }, body)
265
+ : instanceOf('override', [slug, action], override, overrideInstances);
266
+ }
267
+ for (const [name, method] of Object.entries(methods)) {
268
+ sliceUseCases[name] = instanceOf('method', [slug, name], method, methodInstances);
269
+ }
270
+ operationUseCases[slug] = sliceUseCases;
271
+ const sliceRelations = {};
272
+ for (const { name, relation, ops: relationOperations } of relations) {
273
+ const opUseCases = {};
274
+ for (const { op, body, override } of relationOperations) {
275
+ opUseCases[op] =
276
+ override === undefined
277
+ ? generatedUseCase(this.family, `${slug}.${name}.${op}`, { collection, ...relation[op] }, body)
278
+ : instanceOf('override', [slug, name, op], override, overrideInstances);
279
+ }
280
+ sliceRelations[name] = opUseCases;
281
+ }
282
+ relationUseCases[slug] = sliceRelations;
283
+ }
284
+ // One implementer per slice and per relation node, each typed by its own
285
+ // procedures: ts-pf's types read a node that may be a procedure or a
286
+ // router as a procedure. The root router places each procedure at its
287
+ // path and checks the tree against the whole contract.
288
+ const contract = this.contract;
289
+ // Masking reads each output schema once, here. With no maskable field
290
+ // in the app, nothing can be masked, so no schema needs reading.
291
+ const masking = this.entries.some(({ collection }) => collection.maskable.length > 0);
292
+ const maskOf = (path, procedure) => {
293
+ if (!masking)
294
+ return undefined;
295
+ const where = path.join('.');
296
+ const { output } = procedure['~pf'];
297
+ if (!(output instanceof z.core.$ZodType)) {
298
+ throw new Error(`Lattice: the output of "${where}" is not a Zod schema, which Lattice cannot see through to mask a field`);
299
+ }
300
+ const plan = maskPlan(output, where);
301
+ if (plan === undefined)
302
+ return undefined;
303
+ return {
304
+ plan,
305
+ collections: [...maskedCollections(plan)].flatMap((slug) => {
306
+ const found = collections.get(slug);
307
+ return found === undefined ? [] : [found];
308
+ }),
309
+ };
310
+ };
311
+ const tree = {};
312
+ const implement = (path, procedures, useCasesOf) => {
313
+ const impl = createImplementer(procedures).$context();
314
+ const node = {};
315
+ for (const [name, procedure] of Object.entries(procedures)) {
316
+ const builder = impl[name];
317
+ const useCase = useCasesOf?.[name];
318
+ if (builder === undefined || useCase === undefined) {
319
+ throw new Error(`Lattice: no procedure "${[...path, name].join('.')}"`);
320
+ }
321
+ const mask = maskOf([...path, name], procedure);
322
+ // A fresh context per call: a createLocalClient context object is
323
+ // shared by every call, and access answers are kept on the context.
324
+ // Every procedure's output is masked here, generated or not, so an
325
+ // override or a method cannot skip it.
326
+ node[name] = builder.handler(async ({ input, context: base }) => {
327
+ const ctx = context(base);
328
+ const output = await useCase.execute(ctx, input);
329
+ return mask === undefined ? output : masked(mask, output, ctx);
330
+ });
331
+ }
332
+ return node;
333
+ };
334
+ for (const [slug, slice] of Object.entries(contract)) {
335
+ const procedures = {};
336
+ const nodes = {};
337
+ for (const [name, node] of Object.entries(slice)) {
338
+ if (isProcedure(node))
339
+ procedures[name] = node;
340
+ else
341
+ nodes[name] = node;
342
+ }
343
+ const sliceTree = implement([slug], procedures, operationUseCases[slug]);
344
+ for (const [name, node] of Object.entries(nodes)) {
345
+ sliceTree[name] = implement([slug, name], node, relationUseCases[slug]?.[name]);
346
+ }
347
+ tree[slug] = sliceTree;
348
+ }
349
+ const useCases = Object.fromEntries(Object.entries(operationUseCases).map(([slug, sliceUseCases]) => [
350
+ slug,
351
+ { ...sliceUseCases, ...relationUseCases[slug] },
352
+ ]));
353
+ const errors = clientCalls(this.family, this.errors.map);
354
+ return {
355
+ app: rootRouter(createImplementer(contract).$context().use(errors), tree),
356
+ useCases,
357
+ repos,
358
+ onError: unexpectedErrors,
359
+ ensure: async () => {
360
+ for (const { collection } of this.entries) {
361
+ if (collection.indexes.length === 0)
362
+ continue;
363
+ await store.ensure(collection.slug, collection.indexes);
364
+ }
365
+ },
366
+ context,
367
+ };
368
+ }
369
+ }
370
+ /** Throws on a ref whose slug is not a collection of `entries`. */
371
+ function checkSlugs(entries) {
372
+ const slugs = new Set(entries.map((entry) => entry.collection.slug));
373
+ for (const { collection } of entries) {
374
+ for (const { field, slug } of collection.refs) {
375
+ if (!slugs.has(slug)) {
376
+ throw new Error(`Lattice: ${collection.slug}.${field} refers to "${slug}", which is not a collection of this framework`);
377
+ }
378
+ }
379
+ }
380
+ }
381
+ function contractOf(entries, declared) {
382
+ const call = procedure.errors({ ...declaredErrors, ...declared });
383
+ // What a client receives of each collection's documents: each maskable
384
+ // field optional. Where and sort stay on the stored output, so a caller
385
+ // allowed to read a field can filter by it.
386
+ const outputs = new Map(entries.map(({ collection }) => [collection.slug, collection.clientOutput]));
387
+ /** A page of `doc`s, as find and list return them. */
388
+ const page = (doc) => z.object({ docs: z.array(doc), next: z.string().nullable() });
389
+ const slices = {};
390
+ for (const { collection, methods, overrides, join } of entries) {
391
+ if (join)
392
+ continue;
393
+ const slice = {};
394
+ const ops = operations(collection.schema, collection.output);
395
+ const doc = collection.clientOutput;
396
+ const { slug, label } = collection;
397
+ for (const action of actions) {
398
+ const output = action === 'count'
399
+ ? ops.count.output
400
+ : action === 'find'
401
+ ? page(doc)
402
+ : doc;
403
+ slice[action] = call
404
+ .meta(generatedMeta({ slug, label, op: action, populate: [] }))
405
+ .input(ops[action].input)
406
+ .output(output);
407
+ }
408
+ // A read's output follows its `populate` list, through ts-pf's
409
+ // expandable outputs (0022): the output is the wide document.
410
+ // An overridden read is plain: Lattice populates in the generated one.
411
+ if (overrides.get === undefined &&
412
+ populateKeys(collection, 'get').length > 0) {
413
+ const { fields, wide } = expansionOf(collection, outputs, 'get');
414
+ slice.get = call
415
+ .meta(generatedMeta({
416
+ slug,
417
+ label,
418
+ op: 'get',
419
+ populate: populateKeys(collection, 'get'),
420
+ }))
421
+ .input(ops.get.input.extend(populateInput(populateKeys(collection, 'get')).shape))
422
+ .output(wide)
423
+ .expand({ key: 'populate', fields });
424
+ }
425
+ if (overrides.find === undefined &&
426
+ populateKeys(collection, 'find').length > 0) {
427
+ const { fields, wide } = expansionOf(collection, outputs, 'find');
428
+ slice.find = call
429
+ .meta(generatedMeta({
430
+ slug,
431
+ label,
432
+ op: 'find',
433
+ populate: populateKeys(collection, 'find'),
434
+ }))
435
+ .input(ops.find.input.extend(populateInput(populateKeys(collection, 'find')).shape))
436
+ .output(page(wide))
437
+ .expand({ key: 'populate', at: ['docs'], fields });
438
+ }
439
+ for (const [name, method] of Object.entries(methods)) {
440
+ const { summary, effect } = method;
441
+ slice[name] = call
442
+ .meta(methodMeta({ slug, label, name, summary, effect }))
443
+ .input(method.input)
444
+ .output(method.output);
445
+ }
446
+ for (const [name, relation] of Object.entries(collection.relations)) {
447
+ const declared = overrides[name];
448
+ const { fields, wide } = expansionOf(relation.through, outputs, 'find');
449
+ const listed = typeof declared === 'object' && declared.list !== undefined;
450
+ const list = call.meta(generatedMeta({
451
+ slug,
452
+ label,
453
+ op: 'list',
454
+ relation: name,
455
+ target: relation.target,
456
+ populate: listed ? [] : Object.keys(fields),
457
+ }));
458
+ slice[name] = {
459
+ list: listed
460
+ ? list.input(relation.list.input).output(relation.list.output)
461
+ : list
462
+ .input(relation.list.input)
463
+ .output(page(wide))
464
+ .expand({ key: 'populate', at: ['docs'], fields }),
465
+ set: call
466
+ .meta(generatedMeta({
467
+ slug,
468
+ label,
469
+ op: 'set',
470
+ relation: name,
471
+ target: relation.target,
472
+ populate: [],
473
+ }))
474
+ .input(relation.set.input)
475
+ .output(relation.set.output),
476
+ };
477
+ }
478
+ slices[collection.slug] = slice;
479
+ }
480
+ return router(slices);
481
+ }
482
+ /**
483
+ * The edge's `onError`, such as `FetchHandler`'s: it logs each unexpected
484
+ * error (ts-pf's `isUnexpectedError`) that no family logged as a failure. A
485
+ * throw inside `execute` reaches the edge unchanged, and the family has
486
+ * logged it once already. Logged here: a throw the family never saw, such as
487
+ * the context factory's or ts-pf's output check, and a refusal the app's
488
+ * map keeps from clients, which the family logged only at info. Typed
489
+ * structurally, so core needs no `@ts-pf/server-http`: it fits
490
+ * `FetchHandlerOnError`, which also passes the request.
491
+ */
492
+ function unexpectedErrors(logger) {
493
+ return (error) => {
494
+ if (!isUnexpectedError(error) || loggedByFamily(error) === 'failed') {
495
+ return;
496
+ }
497
+ if (error instanceof Error)
498
+ logger.error(error);
499
+ else
500
+ logger.error('Unexpected error', { thrown: error });
501
+ };
502
+ }
503
+ /**
504
+ * The instance passed to `build()` for one declared class. The type check is
505
+ * structural, so it accepts a different class with the same members;
506
+ * `instanceof` catches that here.
507
+ */
508
+ function instanceOf(kind, path, declared, instances) {
509
+ const [slug, name, op] = path;
510
+ const found = instances?.[slug]?.[name];
511
+ // A relation's instances are one more level down, by operation.
512
+ const instance = op === undefined || found === undefined || isExecutable(found)
513
+ ? found
514
+ : found[op];
515
+ const at = path.join('.');
516
+ if (instance === undefined || !isExecutable(instance)) {
517
+ throw new Error(`Lattice: no instance for ${kind} "${at}"`);
518
+ }
519
+ if (!(instance instanceof declared)) {
520
+ throw new Error(`Lattice: "${at}" instance is not an instance of ${declared.name}`);
521
+ }
522
+ return instance;
523
+ }
524
+ /**
525
+ * Whether a value is an implementer node, which has `router()`. The
526
+ * predicate claims that `router()` returns the implemented router, as its
527
+ * signature in ts-pf says, but checks only that `router` is a function.
528
+ * The claim is not left unguarded: ts-pf's `router()` checks the tree
529
+ * against the whole contract at runtime, and throws on a missing or extra
530
+ * implementation (build.test.ts proves it). The predicate goes with
531
+ * `rootRouter()`.
532
+ */
533
+ function hasRouter(value) {
534
+ return 'router' in value && typeof value.router === 'function';
535
+ }
536
+ /**
537
+ * The finished root router. The runtime contract's slice node is
538
+ * `RuntimeProcedure | RuntimeRelation`, and ts-pf (1.0) types a node that
539
+ * may be a procedure as one: `IsContractProcedure` of the union is true, so
540
+ * `RouterImplCheck` wants an implemented procedure where a relation's
541
+ * router sits. The root implementer's `router()` is therefore called
542
+ * through its runtime shape, and its result typed by `hasRouter`. At
543
+ * runtime ts-pf still checks the tree against the whole contract, sets each
544
+ * procedure's path and adds the root middleware. This function and
545
+ * `hasRouter` go when ts-pf ships a `RouterImplCheck` that decides a mixed
546
+ * node by the implementation's node, or a public guard for an implemented
547
+ * router. Exported for its test only; it is not in index.ts.
548
+ */
549
+ export function rootRouter(implementer, tree) {
550
+ if (!hasRouter(implementer)) {
551
+ throw new Error('Lattice: the ts-pf implementer has no router()');
552
+ }
553
+ return implementer.router(tree);
554
+ }
555
+ /** Whether an instance entry is a use case, not a relation's map of them. */
556
+ function isExecutable(value) {
557
+ return 'execute' in value && typeof value.execute === 'function';
558
+ }
559
+ /**
560
+ * The middleware on every procedure, and the only one, so the outermost.
561
+ *
562
+ * - It traces the call: one span per procedure, active while the procedure
563
+ * runs, so the use case's span and the store's spans nest under it. Its
564
+ * outcome is what the client receives.
565
+ * - It replaces a thrown error with the one the client receives
566
+ * (`toClientError`).
567
+ * - It logs each refusal no family logged, once, at info: a guard's, and
568
+ * ts-pf's own input check, which runs after `.use()` middleware. An error
569
+ * sent as INTERNAL is the edge's `onError` to log.
570
+ *
571
+ * One middleware, because the span and the log both read the error the
572
+ * client receives.
573
+ */
574
+ function clientCalls(family, map) {
575
+ return async ({ context, next, path }) => {
576
+ const span = tracer.startSpan(path.join('/'), { kind: SpanKind.SERVER });
577
+ // A real span, sampled or not, is made active, so the use case's span
578
+ // and the store's nest under it and share its sampling. The no-op API's
579
+ // span has no context to pass on, so without an SDK the call makes none.
580
+ const recording = span.isRecording();
581
+ // By identity: the no-op span carries the API's one invalid context.
582
+ const active = span.spanContext() !== INVALID_SPAN_CONTEXT;
583
+ if (recording) {
584
+ span.setAttributes({
585
+ 'rpc.system': 'ts-pf',
586
+ 'rpc.service': path[0] ?? '',
587
+ 'rpc.method': path.slice(1).join('/'),
588
+ });
589
+ }
590
+ try {
591
+ const output = await (active
592
+ ? otel.with(trace.setSpan(otel.active(), span), next)
593
+ : next());
594
+ if (recording)
595
+ span.setAttribute('lattice.outcome', 'ok');
596
+ return output;
597
+ }
598
+ catch (error) {
599
+ const sent = toClientError(error, map);
600
+ if (!isPFError(sent) || sent.code === 'INTERNAL') {
601
+ failed(span, error);
602
+ throw sent;
603
+ }
604
+ // A refusal is the caller's, not a failure: the status stays UNSET.
605
+ if (recording) {
606
+ span.setAttributes({
607
+ 'lattice.outcome': 'refused',
608
+ 'lattice.code': sent.code,
609
+ });
610
+ }
611
+ if (loggedByFamily(error) === undefined) {
612
+ const [collection, action] = path;
613
+ // The guards may not have checked the actor yet.
614
+ const actor = validate(family.actor, context.actor);
615
+ context.logger.info(path.join('.'), {
616
+ collection,
617
+ action,
618
+ ...(actor.ok ? callerFields(family, actor.value) : {}),
619
+ outcome: 'refused',
620
+ ...(refusal(error) ?? { code: sent.code }),
621
+ });
622
+ }
623
+ throw sent;
624
+ }
625
+ finally {
626
+ span.end();
627
+ }
628
+ };
629
+ }
630
+ /**
631
+ * Starts an app's definition: the family every generated and hand-written
632
+ * use case extends, and the app's client errors. It takes no ports;
633
+ * `build()` does.
634
+ */
635
+ export function framework(options) {
636
+ const errors = options.errors ?? { declared: {}, map: (error) => error };
637
+ for (const code of Object.keys(errors.declared)) {
638
+ if (latticeCodes.includes(code)) {
639
+ throw new Error(`Lattice: "${code}" is a Lattice error code`);
640
+ }
641
+ }
642
+ return new Framework(options.family, errors, []);
643
+ }
644
+ /**
645
+ * `output` without the fields the caller's rules withhold, asked once per
646
+ * call per collection. A field of a collection outside the app is withheld.
647
+ */
648
+ async function masked(mask, output, ctx) {
649
+ const withheld = new Map(await Promise.all(mask.collections.map(async (collection) => [
650
+ collection.slug,
651
+ await CallAccess.withheld(ctx.access, collection),
652
+ ])));
653
+ return applyMask(mask.plan, output, ({ collection, field }) => withheld.get(collection)?.has(field) ?? true);
654
+ }
655
+ //# sourceMappingURL=build.js.map