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