foldkit-entity 0.14.0 → 0.15.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 +139 -5
- package/dist/collation.d.ts +33 -2
- package/dist/collation.d.ts.map +1 -0
- package/dist/conformance/index.d.ts +4 -4
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +5 -7
- package/dist/conformance/index.js.map +1 -1
- package/dist/conformance/operator.d.ts +1 -2
- package/dist/conformance/operator.d.ts.map +1 -1
- package/dist/conformance/operator.js +2 -6
- package/dist/conformance/operator.js.map +1 -1
- package/dist/conformance/relational.d.ts +17 -17
- package/dist/conformance/relational.d.ts.map +1 -1
- package/dist/conformance/relational.js +1 -3
- package/dist/conformance/relational.js.map +1 -1
- package/dist/conformance/variants.d.ts +47 -0
- package/dist/conformance/variants.d.ts.map +1 -0
- package/dist/conformance/variants.js +126 -0
- package/dist/conformance/variants.js.map +1 -0
- package/dist/context.d.ts +60 -2
- package/dist/context.d.ts.map +1 -0
- package/dist/descriptor.d.ts +33 -0
- package/dist/descriptor.d.ts.map +1 -0
- package/dist/descriptor.js +137 -0
- package/dist/descriptor.js.map +1 -0
- package/dist/entity.d.ts +231 -0
- package/dist/entity.d.ts.map +1 -0
- package/dist/entity.js +435 -0
- package/dist/entity.js.map +1 -0
- package/dist/evaluate.d.ts +204 -2
- package/dist/evaluate.d.ts.map +1 -0
- package/dist/evaluate.js +51 -7
- package/dist/evaluate.js.map +1 -1
- package/dist/expr.d.ts +915 -2
- package/dist/expr.d.ts.map +1 -0
- package/dist/expr.js +50 -10
- package/dist/expr.js.map +1 -1
- package/dist/held.d.ts +112 -2
- package/dist/held.d.ts.map +1 -0
- package/dist/held.js +13 -2
- package/dist/held.js.map +1 -1
- package/dist/ids.d.ts +8 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +8 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +380 -6
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +108 -12
- package/dist/index.js.map +1 -0
- package/dist/invariant.d.ts +123 -2
- package/dist/invariant.d.ts.map +1 -0
- package/dist/invariant.js +236 -1
- package/dist/invariant.js.map +1 -0
- package/dist/law.d.ts +264 -2
- package/dist/law.d.ts.map +1 -0
- package/dist/law.js +1 -1
- package/dist/operators.d.ts +170 -2
- package/dist/operators.d.ts.map +1 -0
- package/dist/operators.js +3 -3
- package/dist/readFilter.d.ts +8 -2
- package/dist/readFilter.d.ts.map +1 -0
- package/dist/sets.d.ts +18 -2
- package/dist/sets.d.ts.map +1 -0
- package/dist/sets.js +1 -1
- package/dist/shape.d.ts +23 -2
- package/dist/shape.d.ts.map +1 -0
- package/dist/tested.d.ts +8 -2
- package/dist/tested.d.ts.map +1 -0
- package/dist/text.d.ts +27 -2
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +1 -1
- package/dist/variants.d.ts +72 -0
- package/dist/variants.d.ts.map +1 -0
- package/dist/variants.js +76 -0
- package/dist/variants.js.map +1 -0
- package/dist/words.d.ts +17 -2
- package/dist/words.d.ts.map +1 -0
- package/dist/write.d.ts +312 -2
- package/dist/write.d.ts.map +1 -0
- package/dist/write.js +3 -3
- package/package.json +3 -3
- package/dist/collation-BB4YTIbY.d.ts +0 -34
- package/dist/collation-BB4YTIbY.d.ts.map +0 -1
- package/dist/index-48JeXG0A.d.ts +0 -2585
- package/dist/index-48JeXG0A.d.ts.map +0 -1
- package/dist/readFilter-CWMnFRVw.d.ts +0 -9
- package/dist/readFilter-CWMnFRVw.d.ts.map +0 -1
- package/dist/shape-LAowRf9f.d.ts +0 -23
- package/dist/shape-LAowRf9f.d.ts.map +0 -1
- package/dist/src-DKhUqLoC.js +0 -731
- package/dist/src-DKhUqLoC.js.map +0 -1
- package/dist/words-a4e9o-TK.d.ts +0 -18
- package/dist/words-a4e9o-TK.d.ts.map +0 -1
package/dist/entity.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
import { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from "./ids.js";
|
|
4
|
+
import { own, put } from "./record.js";
|
|
5
|
+
import { declareVariants, registerVariants, variantsOf as variantsOf$1 } from "./variants.js";
|
|
6
|
+
import { extend, make, mapValues, partsOf, remake, variantBases } from "./descriptor.js";
|
|
7
|
+
import { Derivation } from "./index.js";
|
|
8
|
+
import { checkedSet } from "./sets.js";
|
|
9
|
+
import { SchemaShape } from "./shape.js";
|
|
10
|
+
import { check, invariant, invariantsOf as invariants, judge, judgeAgainst, judgeInput, readsBefore } from "./invariant.js";
|
|
11
|
+
// src/entity.ts
|
|
12
|
+
/**
|
|
13
|
+
* The `Entity` namespace: declaring Entities, their relations and derived
|
|
14
|
+
* members, and Selections and inputs over them. An ES module rather than an
|
|
15
|
+
* object, so a page keeps only the members it calls: one that declares and
|
|
16
|
+
* reads Entities keeps none of the invariant judge or its expression
|
|
17
|
+
* evaluator (#378).
|
|
18
|
+
*/
|
|
19
|
+
/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
|
|
20
|
+
const idSchemaOf = (entity) => {
|
|
21
|
+
const id = entity.fields.id;
|
|
22
|
+
if (id === void 0 || id._tag !== "Field") return Schema.String;
|
|
23
|
+
const type = Schema.toType(id.schema);
|
|
24
|
+
return SchemaShape.isText(type.ast) ? type : Schema.String;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The schema a Selection of `entity` reads, given each selected member's
|
|
28
|
+
* schema by key: a Struct, or, for a variant Entity whose `_tag` is among
|
|
29
|
+
* them, its tagged union (each case keeps the selected fields it has, as it
|
|
30
|
+
* holds them). An interpreter that reads members its own way (Remote reads a
|
|
31
|
+
* relation as a ref) builds a Selection's value with it.
|
|
32
|
+
*
|
|
33
|
+
* A variant Entity's Selection: with `_tag`, a tagged union whose cases hold
|
|
34
|
+
* the selected fields they have, each as the case holds it, and every
|
|
35
|
+
* selected relation and derived member; without it, the stored row's Struct,
|
|
36
|
+
* refused when it selects a field only some cases have.
|
|
37
|
+
*/
|
|
38
|
+
const selectionSchema = (entity, selected) => Option.match(variantsOf$1(entity.identity), {
|
|
39
|
+
onNone: () => Schema.Struct(selected),
|
|
40
|
+
onSome: (variants) => variantSelection(entity, variants, selected)
|
|
41
|
+
});
|
|
42
|
+
const variantSelection = (entity, variants, selected) => {
|
|
43
|
+
const caseOnly = (key) => Object.hasOwn(entity.fields, key) && key !== "_tag" && variants.tags.some((tag) => !Object.hasOwn(variants.cases[tag], key));
|
|
44
|
+
if (!Object.hasOwn(selected, "_tag")) {
|
|
45
|
+
const untold = Object.keys(selected).filter(caseOnly);
|
|
46
|
+
if (untold.length > 0) fail(entity, `${untold.join(", ")} ${untold.length === 1 ? "is a field" : "are fields"} of some cases; select _tag with ${untold.length === 1 ? "it" : "them"}`);
|
|
47
|
+
return Schema.Struct(selected);
|
|
48
|
+
}
|
|
49
|
+
const cases = {};
|
|
50
|
+
for (const tag of variants.tags) {
|
|
51
|
+
const own = variants.cases[tag];
|
|
52
|
+
const fields = {};
|
|
53
|
+
for (const [key, schema] of Object.entries(selected)) {
|
|
54
|
+
if (key === "_tag") continue;
|
|
55
|
+
if (!Object.hasOwn(entity.fields, key)) put(fields, key, schema);
|
|
56
|
+
else if (Object.hasOwn(own, key)) put(fields, key, own[key]);
|
|
57
|
+
}
|
|
58
|
+
put(cases, tag, fields);
|
|
59
|
+
}
|
|
60
|
+
return Schema.TaggedUnion(cases);
|
|
61
|
+
};
|
|
62
|
+
const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
|
|
63
|
+
const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
|
|
64
|
+
/** For an input key that is about the operation rather than the Entity. */
|
|
65
|
+
const unmapped = Object.freeze({ _tag: "Unmapped" });
|
|
66
|
+
/** True when both descriptors are versions of one Entity. */
|
|
67
|
+
const isSameEntity = (left, right) => left.identity.token === right.identity.token;
|
|
68
|
+
const fail = (entity, message) => {
|
|
69
|
+
throw new Error(`Entity "${entity.name}": ${message}`);
|
|
70
|
+
};
|
|
71
|
+
const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
|
|
72
|
+
const kindName = {
|
|
73
|
+
Field: "field",
|
|
74
|
+
Relation: "relation",
|
|
75
|
+
Derived: "derived member"
|
|
76
|
+
};
|
|
77
|
+
const kindOf = (entity, key) => {
|
|
78
|
+
const member = entity.members[key];
|
|
79
|
+
return member && kindName[member._tag];
|
|
80
|
+
};
|
|
81
|
+
const assertFree = (entity, keys, adding) => {
|
|
82
|
+
for (const key of keys) {
|
|
83
|
+
const kind = kindOf(entity, key);
|
|
84
|
+
if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
/** Declares an Entity from its intrinsic fields. Each call is a new identity. */
|
|
88
|
+
const define = (name, schema) => {
|
|
89
|
+
const identity = Object.freeze({
|
|
90
|
+
name,
|
|
91
|
+
token: Symbol(name)
|
|
92
|
+
});
|
|
93
|
+
return make({
|
|
94
|
+
identity,
|
|
95
|
+
schema,
|
|
96
|
+
fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
|
|
97
|
+
_tag: "Field",
|
|
98
|
+
owner: identity,
|
|
99
|
+
key,
|
|
100
|
+
schema: fieldSchema,
|
|
101
|
+
metadata: Metadata.empty
|
|
102
|
+
})),
|
|
103
|
+
annotated: {},
|
|
104
|
+
metadata: Metadata.empty
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Declares an Entity whose rows are one of several shapes, each case's fields
|
|
109
|
+
* by its tag:
|
|
110
|
+
*
|
|
111
|
+
* ```ts
|
|
112
|
+
* const Domain = Entity.defineVariants('Domain', {
|
|
113
|
+
* Available: { ...DomainName.fields, ...DomainQuote.fields },
|
|
114
|
+
* Unconfirmed: DomainName.fields,
|
|
115
|
+
* })
|
|
116
|
+
* Domain.variants.match(row, { Available: ({ price }) => price, Unconfirmed: () => 0 })
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* A row is `Domain.variants`, Effect's tagged union of the cases. The stored
|
|
120
|
+
* row is `fields` and `schema`: `_tag`, the fields every case has, and each
|
|
121
|
+
* other field nullable, null on a row of another case. Each case with fields
|
|
122
|
+
* of its own gets an invariant saying so (`variant_Available`), which a
|
|
123
|
+
* database binding writes as a CHECK. A key in several cases is one stored
|
|
124
|
+
* field, so it is declared with one schema, spread into each case. Refused
|
|
125
|
+
* here: fewer than two cases, a case declaring `_tag`, an optional key.
|
|
126
|
+
*/
|
|
127
|
+
const defineVariants = (name, cases) => {
|
|
128
|
+
const { fields, variants } = declareVariants(name, cases);
|
|
129
|
+
const declared = define(name, Schema.Struct(fields));
|
|
130
|
+
registerVariants(declared.identity, declared.schema, variants);
|
|
131
|
+
const entity = remake(declared, {});
|
|
132
|
+
variantBases.set(entity.identity, entity);
|
|
133
|
+
return entity;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* An Entity's variants as an interpreter reads them: the union, each case's
|
|
137
|
+
* fields, and the codec from a stored row to its case. None for an Entity of
|
|
138
|
+
* one shape.
|
|
139
|
+
*/
|
|
140
|
+
const variantsOf = (entity) => variantsOf$1(entity.identity);
|
|
141
|
+
/**
|
|
142
|
+
* Declares the relations between a set of Entities in one step, and returns
|
|
143
|
+
* them related. One step, because Entities that point at each other cannot
|
|
144
|
+
* each be declared in terms of the other.
|
|
145
|
+
*/
|
|
146
|
+
const relate = (entities, relations) => {
|
|
147
|
+
const keyByToken = /* @__PURE__ */ new Map();
|
|
148
|
+
for (const [key, entity] of Object.entries(entities)) {
|
|
149
|
+
if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
|
|
150
|
+
const earlier = keyByToken.get(entity.identity.token);
|
|
151
|
+
if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
|
|
152
|
+
keyByToken.set(entity.identity.token, key);
|
|
153
|
+
}
|
|
154
|
+
const given = relations;
|
|
155
|
+
for (const owner of Object.keys(given)) if (!Object.hasOwn(entities, owner)) throw new Error(`Entity.relate: relations given for "${owner}", which is not being related`);
|
|
156
|
+
const related = {};
|
|
157
|
+
const additions = [];
|
|
158
|
+
for (const [ownerKey, entity] of Object.entries(entities)) {
|
|
159
|
+
const specs = own(given, ownerKey) ?? {};
|
|
160
|
+
assertFree(entity, Object.keys(specs), "relation");
|
|
161
|
+
const added = mapValues(specs, (spec, key) => {
|
|
162
|
+
const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
|
|
163
|
+
if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
|
|
164
|
+
return Object.freeze({
|
|
165
|
+
_tag: "Relation",
|
|
166
|
+
owner: entity.identity,
|
|
167
|
+
key,
|
|
168
|
+
target: () => related[targetKey],
|
|
169
|
+
cardinality: spec.cardinality,
|
|
170
|
+
optional: spec.optional,
|
|
171
|
+
onDelete: spec.onDelete,
|
|
172
|
+
metadata: Metadata.empty
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
additions.push([entity, added]);
|
|
176
|
+
put(related, ownerKey, entity);
|
|
177
|
+
}
|
|
178
|
+
for (const [entity, added] of additions) extend(entity, { relations: added });
|
|
179
|
+
for (const [entity, added] of additions) for (const member of Object.values(added)) if (member._tag === "Relation" && Option.isSome(member.onDelete)) cascadeInto(member.target().identity, {
|
|
180
|
+
relation: member,
|
|
181
|
+
owner: entity
|
|
182
|
+
});
|
|
183
|
+
return Object.freeze(related);
|
|
184
|
+
};
|
|
185
|
+
const cascades = /* @__PURE__ */ new WeakMap();
|
|
186
|
+
const cascadeInto = (target, cascade) => {
|
|
187
|
+
const known = cascades.get(target) ?? [];
|
|
188
|
+
known.push(cascade);
|
|
189
|
+
cascades.set(target, known);
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* The `one` relations, of any Entity, declared `onDelete: 'cascade'` that point
|
|
193
|
+
* at `entity`: deleting one of its rows deletes each row pointing at it through
|
|
194
|
+
* one, and so on from those. The owner is the Entity as it was related, whose
|
|
195
|
+
* members every descriptor of it shares.
|
|
196
|
+
*/
|
|
197
|
+
const cascading = (entity) => cascades.get(entity.identity) ?? [];
|
|
198
|
+
/**
|
|
199
|
+
* Selects members of an Entity and assembles the schema of the result. A
|
|
200
|
+
* relation selected with `true` yields an `EntityRef`; with a Selection of its
|
|
201
|
+
* target, that Selection's value. `many` yields an array, an optional `one`
|
|
202
|
+
* is nullable.
|
|
203
|
+
*/
|
|
204
|
+
const select = (entity, spec) => {
|
|
205
|
+
const members = entity.members;
|
|
206
|
+
const fields = mapValues(spec, (selected, key) => {
|
|
207
|
+
const member = own(members, key);
|
|
208
|
+
if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
|
|
209
|
+
if (member._tag !== "Relation") {
|
|
210
|
+
if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
|
|
211
|
+
return member.schema;
|
|
212
|
+
}
|
|
213
|
+
const target = member.target();
|
|
214
|
+
if (isSelectionPage(selected)) {
|
|
215
|
+
if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
|
|
216
|
+
if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
|
|
217
|
+
return Schema.Struct({
|
|
218
|
+
items: Schema.Array(selected.selection.schema),
|
|
219
|
+
hasNext: Schema.Boolean,
|
|
220
|
+
hasPrevious: Schema.Boolean
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
let item;
|
|
224
|
+
if (selected === true) item = Schema.Struct({
|
|
225
|
+
entity: Schema.Literal(target.name),
|
|
226
|
+
id: idSchemaOf(target)
|
|
227
|
+
});
|
|
228
|
+
else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
|
|
229
|
+
else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
|
|
230
|
+
return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
|
|
231
|
+
});
|
|
232
|
+
return Object.freeze({
|
|
233
|
+
[SelectionTypeId]: SelectionTypeId,
|
|
234
|
+
entity,
|
|
235
|
+
members: spec,
|
|
236
|
+
schema: selectionSchema(entity, fields)
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
/**
|
|
240
|
+
* A `many` relation read a page at a time, in place of its Selection:
|
|
241
|
+
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
|
|
242
|
+
* of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
|
|
243
|
+
*/
|
|
244
|
+
const page = (selection, window) => {
|
|
245
|
+
const sides = [window.first, window.last].filter((size) => size !== void 0);
|
|
246
|
+
if (sides.length !== 1 || !sides.every((size) => Number.isInteger(size) && size >= 0)) throw new Error(`Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`);
|
|
247
|
+
if (window.first !== void 0 && window.before !== void 0 || window.last !== void 0 && window.after !== void 0) throw new Error(`Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`);
|
|
248
|
+
return Object.freeze({
|
|
249
|
+
[SelectionPageTypeId]: SelectionPageTypeId,
|
|
250
|
+
selection,
|
|
251
|
+
window
|
|
252
|
+
});
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* Adds readable members that are not part of `entity.schema`. A
|
|
256
|
+
* `Derived.count` or `Derived.exists` must read rows pointing at this
|
|
257
|
+
* Entity: one over a relation to another is refused here, as is an exists
|
|
258
|
+
* whose viewer is not another `one` relation of the same pointing Entity.
|
|
259
|
+
*/
|
|
260
|
+
const derived = (specs) => (entity) => {
|
|
261
|
+
const members = entity.members;
|
|
262
|
+
const fresh = Object.fromEntries(Object.entries(specs).filter(([key, spec]) => {
|
|
263
|
+
const taken = own(members, key);
|
|
264
|
+
return !(taken?._tag === "Derived" && taken.schema === spec.schema && taken.derives === spec.derives);
|
|
265
|
+
}));
|
|
266
|
+
assertFree(entity, Object.keys(fresh), "derived member");
|
|
267
|
+
const added = mapValues(fresh, (spec, key) => {
|
|
268
|
+
const pointingHere = (relation, verb) => {
|
|
269
|
+
if (relation.cardinality !== "one") fail(entity, `"${key}" ${verb} "${relation.key}", a many relation; name a one relation that points here`);
|
|
270
|
+
if (!isSameEntity(relation.target(), entity)) fail(entity, `"${key}" ${verb} "${relation.owner.name}.${relation.key}", which points at ${relation.target().name}`);
|
|
271
|
+
};
|
|
272
|
+
Derivation.$match(spec.derives, {
|
|
273
|
+
Supplied: () => void 0,
|
|
274
|
+
Count: ({ relation }) => pointingHere(relation, "counts"),
|
|
275
|
+
Exists: ({ relation, viewer }) => {
|
|
276
|
+
pointingHere(relation, "reads");
|
|
277
|
+
if (viewer.owner.token !== relation.owner.token || viewer.key === relation.key) fail(entity, `"${key}"'s viewer "${viewer.owner.name}.${viewer.key}" must be another one relation of ${relation.owner.name}`);
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
return Object.freeze({
|
|
281
|
+
_tag: "Derived",
|
|
282
|
+
owner: entity.identity,
|
|
283
|
+
key,
|
|
284
|
+
schema: spec.schema,
|
|
285
|
+
derives: spec.derives,
|
|
286
|
+
metadata: Metadata.empty
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
extend(entity, { derived: added });
|
|
290
|
+
return entity;
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* Says which members take their value from the write's context, never its
|
|
294
|
+
* input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a
|
|
295
|
+
* field holding their id), and `Expr.now`, when (a field stored as a
|
|
296
|
+
* number). `on` says which writes set them: `'create'`, every insert, or
|
|
297
|
+
* `'write'`, every insert and every update.
|
|
298
|
+
*
|
|
299
|
+
* ```ts
|
|
300
|
+
* const Post = Blog.Post.pipe(
|
|
301
|
+
* Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),
|
|
302
|
+
* Entity.sets({ editedAt: Expr.now }, { on: 'write' }),
|
|
303
|
+
* )
|
|
304
|
+
* ```
|
|
305
|
+
*
|
|
306
|
+
* Every write of the Entity follows from it: a server writes the values and
|
|
307
|
+
* a client predicts them, and a write whose input sets one is refused where
|
|
308
|
+
* it is declared. Refused here: the id, a member set already, a `many`
|
|
309
|
+
* relation, a relation set to anything but the viewer of its target, and a
|
|
310
|
+
* field that cannot hold its value. Added after `Entity.relate` to set a
|
|
311
|
+
* relation.
|
|
312
|
+
*/
|
|
313
|
+
const sets = (values, options) => (entity) => {
|
|
314
|
+
const given = values;
|
|
315
|
+
const added = {};
|
|
316
|
+
for (const [key, value] of Object.entries(given)) {
|
|
317
|
+
if (value === void 0) continue;
|
|
318
|
+
put(added, key, checkedSet(entity, key, value, options.on));
|
|
319
|
+
}
|
|
320
|
+
extend(entity, { sets: added });
|
|
321
|
+
return entity;
|
|
322
|
+
};
|
|
323
|
+
/** Attaches an interpreter's metadata to the Entity itself. */
|
|
324
|
+
const annotate = (metadata) => (entity) => remake(entity, { metadata: Metadata.combine([entity.metadata, metadata]) });
|
|
325
|
+
/** Attaches an interpreter's metadata to members, by key. */
|
|
326
|
+
const annotateMembers = (metadata) => (entity) => {
|
|
327
|
+
const given = metadata;
|
|
328
|
+
for (const key of Object.keys(given)) if (kindOf(entity, key) === void 0) throw new Error(`Entity "${entity.name}": cannot annotate "${key}", it is not a member`);
|
|
329
|
+
const parts = partsOf.get(entity);
|
|
330
|
+
const fields = mapValues(entity.fields, (member, key) => {
|
|
331
|
+
const extra = own(given, key);
|
|
332
|
+
return extra === void 0 ? member : Object.freeze({
|
|
333
|
+
...member,
|
|
334
|
+
metadata: Metadata.combine([member.metadata, extra])
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
const annotated = { ...parts.annotated };
|
|
338
|
+
for (const [key, extra] of Object.entries(given)) {
|
|
339
|
+
if (extra === void 0 || Object.hasOwn(entity.fields, key)) continue;
|
|
340
|
+
const earlier = own(parts.annotated, key);
|
|
341
|
+
put(annotated, key, earlier === void 0 ? extra : Metadata.combine([earlier, extra]));
|
|
342
|
+
}
|
|
343
|
+
return remake(entity, {
|
|
344
|
+
fields,
|
|
345
|
+
annotated
|
|
346
|
+
});
|
|
347
|
+
};
|
|
348
|
+
/**
|
|
349
|
+
* Reads an operation's input schema against an Entity. A key that names a
|
|
350
|
+
* field maps to it; any other key is mapped explicitly, to a Field, to
|
|
351
|
+
* `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
|
|
352
|
+
* from a naming convention such as `authorId`.
|
|
353
|
+
*/
|
|
354
|
+
const input = (entity, schema, ...mapping) => {
|
|
355
|
+
const written = mapping[0] ?? {};
|
|
356
|
+
for (const key of Object.keys(written)) if (!Object.hasOwn(schema.fields, key)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
|
|
357
|
+
const named = (key, name) => {
|
|
358
|
+
const member = entity.members[name];
|
|
359
|
+
switch (member?._tag) {
|
|
360
|
+
case "Field": return member;
|
|
361
|
+
case "Relation": return Object.freeze({
|
|
362
|
+
_tag: "RelationInput",
|
|
363
|
+
relation: member
|
|
364
|
+
});
|
|
365
|
+
case "Derived":
|
|
366
|
+
case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
|
|
370
|
+
const fields = entity.fields;
|
|
371
|
+
const members = mapValues(schema.fields, (_, key) => {
|
|
372
|
+
const member = own(given, key) ?? own(fields, key) ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
|
|
373
|
+
const owned = member._tag === "Field" ? member : member._tag === "RelationInput" || member._tag === "NestedInput" ? member.relation : member._tag === "Unmapped" ? void 0 : fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`);
|
|
374
|
+
if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
|
|
375
|
+
if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
|
|
376
|
+
return member;
|
|
377
|
+
});
|
|
378
|
+
return Object.freeze({
|
|
379
|
+
entity,
|
|
380
|
+
schema,
|
|
381
|
+
members: Object.freeze(members)
|
|
382
|
+
});
|
|
383
|
+
};
|
|
384
|
+
/**
|
|
385
|
+
* The schemas of some of an Entity's fields, by key, to spread into an input's
|
|
386
|
+
* struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
|
|
387
|
+
* The input then keeps the field's own rules, and its keys map themselves.
|
|
388
|
+
*/
|
|
389
|
+
const fields = (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (own(entity.fields, key) ?? fail(entity, `"${key}" is not a field`)).schema]));
|
|
390
|
+
/**
|
|
391
|
+
* The Selection of every member an input writes, with each relation as refs:
|
|
392
|
+
* what an edit screen loads before it shows the input's current values.
|
|
393
|
+
* `also` names members to read beside them, each with `true` (what a lock
|
|
394
|
+
* reads). The Selection is typed as the input's alone: what it reads has
|
|
395
|
+
* those members, and these besides.
|
|
396
|
+
*/
|
|
397
|
+
const selectFor = (input, options = {}) => {
|
|
398
|
+
const members = input.members;
|
|
399
|
+
const spec = Object.fromEntries(Object.values(members).flatMap((member) => member._tag === "Field" ? [[member.key, true]] : member._tag === "RelationInput" ? [[member.relation.key, true]] : member._tag === "NestedInput" ? [[member.relation.key, selectFor(member.input)]] : []));
|
|
400
|
+
return select(input.entity, {
|
|
401
|
+
...spec,
|
|
402
|
+
...options.also
|
|
403
|
+
});
|
|
404
|
+
};
|
|
405
|
+
/**
|
|
406
|
+
* The input values that reproduce `value`, a value read through `selectFor`
|
|
407
|
+
* (or any Selection with those members): a field as it is, a relation as the
|
|
408
|
+
* id or ids of its refs. A key whose member `value` lacks is left out, as is
|
|
409
|
+
* an unmapped key, which the Entity knows nothing about.
|
|
410
|
+
*/
|
|
411
|
+
const valuesFor = (input, value) => {
|
|
412
|
+
const members = input.members;
|
|
413
|
+
const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
|
|
414
|
+
const entries = Object.entries(members).flatMap(([key, member]) => {
|
|
415
|
+
if (member._tag === "Unmapped") return [];
|
|
416
|
+
const written = member._tag === "Field" ? member.key : member.relation.key;
|
|
417
|
+
if (!(written in value)) return [];
|
|
418
|
+
const read = value[written];
|
|
419
|
+
switch (member._tag) {
|
|
420
|
+
case "Field": return [[key, read]];
|
|
421
|
+
case "NestedInput": {
|
|
422
|
+
const nested = (held) => typeof held === "object" && held !== null ? valuesFor(member.input, held) : null;
|
|
423
|
+
return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
|
|
424
|
+
}
|
|
425
|
+
case "RelationInput": {
|
|
426
|
+
const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
|
|
427
|
+
return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
return Object.fromEntries(entries);
|
|
432
|
+
};
|
|
433
|
+
export { annotate, annotateMembers, cascading, check, define, defineVariants, derived, fields, input, invariant, invariants, isEntity as is, judge, judgeAgainst, judgeInput, page, readsBefore, relate, isSameEntity as same, select, selectFor, selectionSchema, sets, unmapped, valuesFor, variantsOf };
|
|
434
|
+
|
|
435
|
+
//# sourceMappingURL=entity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entity.js","names":["variantsOfIdentity"],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * The `Entity` namespace: declaring Entities, their relations and derived\n * members, and Selections and inputs over them. An ES module rather than an\n * object, so a page keeps only the members it calls: one that declares and\n * reads Entities keeps none of the invariant judge or its expression\n * evaluator (#378).\n */\nimport { Option, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport { extend, make, mapValues, partsOf, remake, variantBases } from './descriptor.js'\nimport type { OneRelation } from './expr.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport {\n Derivation,\n type AnyEntity,\n type Cardinality,\n type DerivedSpec,\n type DerivedSpecs,\n type Entities,\n type Entity,\n type EntityDerived,\n type EntityField,\n type EntityIdentity,\n type EntityInput,\n type EntityMember,\n type EntityRelation,\n type EntitySets,\n type IdOf,\n type IdSchemaOf,\n type InputMember,\n type NestedInput,\n type PageWindow,\n type Related,\n type RelationInput,\n type RelationMap,\n type RelationSpec,\n type RelationSpecs,\n type Selection,\n type SelectionPage,\n type Unmapped,\n type VariantEntity,\n} from './index.js'\nimport { own, put } from './record.js'\nimport { checkedSet, type EntitySet, type SetOn } from './sets.js'\nimport { SchemaShape } from './shape.js'\nimport {\n declareVariants,\n registerVariants,\n variantsOf as variantsOfIdentity,\n type CheckCases,\n type EntityVariants,\n type StoredFields,\n type VariantCases,\n type VariantUnion,\n} from './variants.js'\n\n// What the signatures below check with. Not exported: a consumer's declaration\n// then writes out what one resolves to instead of naming a module the\n// package does not export.\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\n/** Unsatisfiable when a `Derived.count` or `Derived.exists` names a relation pointing at another Entity. */\ntype PointsHere<E extends AnyEntity, New extends DerivedSpecs> = {\n [K in keyof New]: New[K]['derives'] extends {\n readonly _tag: 'Count' | 'Exists'\n readonly relation: EntityRelation<any, any, infer Target, any, any>\n }\n ? [Target['name']] extends [E['name']]\n ? never\n : K\n : never\n}[keyof New] extends infer Wrong\n ? [Wrong] extends [never]\n ? unknown\n : { readonly countsRowsPointingAtAnotherEntity: Wrong }\n : never\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R, D & New, U>\n : E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\n/** A variant Entity's cases, by tag, as the field sets of its union (`_tag` among them); never for one shape. */\ntype CaseFieldSets<E> = E extends {\n readonly variants: {\n readonly cases: infer C extends Readonly<\n Record<string, { readonly fields: Schema.Struct.Fields }>\n >\n }\n}\n ? { readonly [T in keyof C & string]: C[T]['fields'] }\n : never\n\n/** Whether `K` is a field only some cases have, selected without `_tag` to say which case a row is. */\ntype CaseOnlyWithoutTag<E extends AnyEntity, K, Spec> = [CaseFieldSets<E>] extends [never]\n ? false\n : '_tag' extends keyof Spec\n ? false\n : K extends keyof E['fields']\n ? K extends keyof CaseFieldSets<E>[keyof CaseFieldSets<E>]\n ? false\n : true\n : false\n\n/** `true` for any member; a relation also takes a Selection of its target. */\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ?\n | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? CaseOnlyWithoutTag<E, K, Spec> extends true\n ? `\"${K & string}\" is a field of some cases of ${E['name']}; select _tag with it`\n : true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n | EntityField<any, any, infer S>\n | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>\n >\n : never\n\ntype FlatSelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\n/** What one case holds of a Selection: the selected fields it has, as it holds them, and every other member. */\ntype CaseSelectionFields<E extends AnyEntity, Spec, Fields> = {\n readonly [\n K in Exclude<keyof Spec & keyof E['members'], '_tag'> as K extends keyof E['fields']\n ? K extends keyof Fields\n ? K\n : never\n : K\n ]: K extends keyof Fields ? Fields[K] : SelectedSchema<E['members'][K], Spec[K]>\n}\n\n/**\n * A Selection's schema: a Struct, or, for a variant Entity whose `_tag` is\n * selected, a tagged union with a case per variant.\n */\ntype SelectionSchema<E extends AnyEntity, Spec> = [CaseFieldSets<E>] extends [never]\n ? FlatSelectionSchema<E, Spec>\n : '_tag' extends keyof Spec\n ? Schema.TaggedUnion<{\n readonly [T in keyof CaseFieldSets<E> & string]: Schema.TaggedStruct<\n T,\n CaseSelectionFields<E, Spec, CaseFieldSets<E>[T]>\n >\n }>\n : FlatSelectionSchema<E, Spec>\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<IdOf<Target>>\n : Optional extends true\n ? IdOf<Target> | null\n : IdOf<Target>\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\ntype Present<T> = Exclude<T, null | undefined>\n\n/** What an `Option` holds, else the value itself. */\ntype Held<T> =\n T extends Option.Some<infer A> ? Present<A> : T extends Option.None<any> ? never : Present<T>\n\n/**\n * Whether an input value fits a field. Only the value that is present has to\n * fit: an input may leave a key out (a partial update), send `null` to clear\n * it, or hold an `Option` (an id absent for something new), whose value fits as\n * it is (an `Option` field) or as what it holds. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Fits<Input, Field> = [Present<Input>] extends [Field]\n ? true\n : [Held<Input>] extends [Field]\n ? true\n : false\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Fits<Input, Schema.Schema.Type<S>> extends true\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Fits<Schema.Schema.Type<Fields[K]>, Schema.Schema.Type<E['fields'][K]['schema']>> extends true\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\n/** The member each key of an input writes, as `Entity.input` reads it from a mapping. */\nexport type InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Named<E, Mapping[K]>\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\n/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */\nconst idSchemaOf = (entity: AnyEntity): Schema.Top => {\n const fields: Readonly<Record<string, EntityMember | undefined>> = entity.fields\n const id = fields.id\n if (id === undefined || id._tag !== 'Field') return Schema.String\n const type = Schema.toType(id.schema as Schema.Top)\n return SchemaShape.isText(type.ast) ? type : Schema.String\n}\n\n/**\n * The schema a Selection of `entity` reads, given each selected member's\n * schema by key: a Struct, or, for a variant Entity whose `_tag` is among\n * them, its tagged union (each case keeps the selected fields it has, as it\n * holds them). An interpreter that reads members its own way (Remote reads a\n * relation as a ref) builds a Selection's value with it.\n *\n * A variant Entity's Selection: with `_tag`, a tagged union whose cases hold\n * the selected fields they have, each as the case holds it, and every\n * selected relation and derived member; without it, the stored row's Struct,\n * refused when it selects a field only some cases have.\n */\nexport const selectionSchema = (\n entity: AnyEntity,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top =>\n Option.match(variantsOfIdentity(entity.identity), {\n onNone: () => Schema.Struct(selected),\n onSome: variants => variantSelection(entity, variants, selected),\n })\n\nconst variantSelection = (\n entity: AnyEntity,\n variants: EntityVariants,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top => {\n const caseOnly = (key: string) =>\n Object.hasOwn(entity.fields, key) &&\n key !== '_tag' &&\n variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key))\n if (!Object.hasOwn(selected, '_tag')) {\n const untold = Object.keys(selected).filter(caseOnly)\n if (untold.length > 0)\n fail(\n entity,\n `${untold.join(', ')} ${untold.length === 1 ? 'is a field' : 'are fields'} of some cases; select _tag with ${untold.length === 1 ? 'it' : 'them'}`,\n )\n return Schema.Struct(selected)\n }\n const cases: Record<string, Schema.Struct.Fields> = {}\n for (const tag of variants.tags) {\n const own = variants.cases[tag]!\n const fields: Record<string, Schema.Constraint> = {}\n for (const [key, schema] of Object.entries(selected)) {\n if (key === '_tag') continue\n if (!Object.hasOwn(entity.fields, key)) put(fields, key, schema)\n else if (Object.hasOwn(own, key)) put(fields, key, own[key]!)\n }\n put(cases, tag, fields)\n }\n return Schema.TaggedUnion(cases)\n}\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** For an input key that is about the operation rather than the Entity. */\nexport const unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\n/** True when both descriptors are versions of one Entity. */\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\n/** Declares an Entity from its intrinsic fields. Each call is a new identity. */\nexport const define = <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n annotated: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n}\n\n/**\n * Declares an Entity whose rows are one of several shapes, each case's fields\n * by its tag:\n *\n * ```ts\n * const Domain = Entity.defineVariants('Domain', {\n * Available: { ...DomainName.fields, ...DomainQuote.fields },\n * Unconfirmed: DomainName.fields,\n * })\n * Domain.variants.match(row, { Available: ({ price }) => price, Unconfirmed: () => 0 })\n * ```\n *\n * A row is `Domain.variants`, Effect's tagged union of the cases. The stored\n * row is `fields` and `schema`: `_tag`, the fields every case has, and each\n * other field nullable, null on a row of another case. Each case with fields\n * of its own gets an invariant saying so (`variant_Available`), which a\n * database binding writes as a CHECK. A key in several cases is one stored\n * field, so it is declared with one schema, spread into each case. Refused\n * here: fewer than two cases, a case declaring `_tag`, an optional key.\n */\nexport const defineVariants = <const Name extends string, const Cases extends VariantCases>(\n name: Name,\n cases: Cases & CheckCases<Cases>,\n): VariantEntity<Name, StoredFields<Cases>, {}, {}, VariantUnion<Cases>> => {\n const { fields, variants } = declareVariants(name, cases)\n const declared = define(name, Schema.Struct(fields))\n registerVariants(declared.identity, declared.schema, variants)\n // Made again so the descriptor reads the variants just registered.\n const entity = remake(declared, {})\n // Each case's invariant is built from it when first read (`Entity.invariants`).\n variantBases.set(entity.identity, entity)\n return entity as never\n}\n\n/**\n * An Entity's variants as an interpreter reads them: the union, each case's\n * fields, and the codec from a stored row to its case. None for an Entity of\n * one shape.\n */\nexport const variantsOf = (entity: AnyEntity): Option.Option<EntityVariants> =>\n variantsOfIdentity(entity.identity)\n\n/**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\nexport const relate = <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!Object.hasOwn(entities, owner))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n // Every relation is checked before any is added, so a refused call adds none.\n const additions: Array<readonly [AnyEntity, Readonly<Record<string, EntityMember>>]> = []\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = own(given, ownerKey) ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n onDelete: spec.onDelete,\n metadata: Metadata.empty,\n })\n },\n )\n additions.push([entity, added])\n put(related, ownerKey, entity)\n }\n for (const [entity, added] of additions) extend(entity, { relations: added })\n // Once every relation is added, so each target is the one `relate` returns.\n for (const [entity, added] of additions)\n for (const member of Object.values(added))\n if (member._tag === 'Relation' && Option.isSome(member.onDelete))\n cascadeInto(member.target().identity, { relation: member as OneRelation, owner: entity })\n return Object.freeze(related) as never\n}\n\n/** A `one` relation a delete cascades through, and the Entity that owns it, whose rows go. */\nexport interface Cascade {\n readonly relation: OneRelation\n readonly owner: AnyEntity\n}\n\nconst cascades = new WeakMap<EntityIdentity<string>, Array<Cascade>>()\nconst cascadeInto = (target: EntityIdentity<string>, cascade: Cascade): void => {\n const known = cascades.get(target) ?? []\n known.push(cascade)\n cascades.set(target, known)\n}\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'cascade'` that point\n * at `entity`: deleting one of its rows deletes each row pointing at it through\n * one, and so on from those. The owner is the Entity as it was related, whose\n * members every descriptor of it shares.\n */\nexport const cascading = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n cascades.get(entity.identity) ?? []\n\n/**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\nexport const select = <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n): Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = own(members, key)\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: idSchemaOf(target) })\n else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: selectionSchema(entity, fields),\n }) as never\n}\n\n/**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page\n * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.\n */\nexport const page = <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n}\n\n/**\n * Adds readable members that are not part of `entity.schema`. A\n * `Derived.count` or `Derived.exists` must read rows pointing at this\n * Entity: one over a relation to another is refused here, as is an exists\n * whose viewer is not another `one` relation of the same pointing Entity.\n */\nexport const derived =\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New> & PointsHere<E, New>): WithDerived<E, New> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n // The very spec added again (`Guards.may` on a second view of the Entity) is the member it added.\n const fresh: DerivedSpecs = Object.fromEntries(\n Object.entries(specs).filter(([key, spec]) => {\n const taken = own(members, key)\n return !(\n taken?._tag === 'Derived' &&\n taken.schema === spec.schema &&\n taken.derives === spec.derives\n )\n }),\n )\n assertFree(entity, Object.keys(fresh), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(fresh, (spec, key) => {\n const pointingHere = (relation: OneRelation, verb: string): void => {\n if (relation.cardinality !== 'one')\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.key}\", a many relation; name a one relation that points here`,\n )\n if (!isSameEntity(relation.target(), entity))\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.owner.name}.${relation.key}\", which points at ${relation.target().name}`,\n )\n }\n Derivation.$match(spec.derives, {\n Supplied: () => undefined,\n Count: ({ relation }) => pointingHere(relation, 'counts'),\n Exists: ({ relation, viewer }) => {\n pointingHere(relation, 'reads')\n if (viewer.owner.token !== relation.owner.token || viewer.key === relation.key)\n fail(\n entity,\n `\"${key}\"'s viewer \"${viewer.owner.name}.${viewer.key}\" must be another one relation of ${relation.owner.name}`,\n )\n },\n })\n return Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n derives: spec.derives,\n metadata: Metadata.empty,\n })\n })\n extend(entity, { derived: added })\n return entity as never\n }\n\n/**\n * Says which members take their value from the write's context, never its\n * input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a\n * field holding their id), and `Expr.now`, when (a field stored as a\n * number). `on` says which writes set them: `'create'`, every insert, or\n * `'write'`, every insert and every update.\n *\n * ```ts\n * const Post = Blog.Post.pipe(\n * Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),\n * Entity.sets({ editedAt: Expr.now }, { on: 'write' }),\n * )\n * ```\n *\n * Every write of the Entity follows from it: a server writes the values and\n * a client predicts them, and a write whose input sets one is refused where\n * it is declared. Refused here: the id, a member set already, a `many`\n * relation, a relation set to anything but the viewer of its target, and a\n * field that cannot hold its value. Added after `Entity.relate` to set a\n * relation.\n */\nexport const sets =\n <E extends AnyEntity>(values: EntitySets<E>, options: { readonly on: SetOn }) =>\n (entity: E): E => {\n const given: Readonly<Record<string, unknown>> = values\n const added: Record<string, EntitySet> = {}\n for (const [key, value] of Object.entries(given)) {\n if (value === undefined) continue\n put(added, key, checkedSet(entity, key, value, options.on))\n }\n extend(entity, { sets: added })\n return entity\n }\n\n/** Attaches an interpreter's metadata to the Entity itself. */\nexport const annotate =\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n remake(entity, { metadata: Metadata.combine([entity.metadata, metadata]) }) as E\n\n/** Attaches an interpreter's metadata to members, by key. */\nexport const annotateMembers =\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const parts = partsOf.get(entity)!\n const fields = mapValues(entity.fields, (member: EntityMember, key) => {\n const extra = own(given, key)\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n // A relation or derived member is the Entity's own, so its metadata here is this descriptor's.\n const annotated: Record<string, Metadata> = { ...parts.annotated }\n for (const [key, extra] of Object.entries(given)) {\n if (extra === undefined || Object.hasOwn(entity.fields, key)) continue\n const earlier = own(parts.annotated, key)\n put(annotated, key, earlier === undefined ? extra : Metadata.combine([earlier, extra]))\n }\n return remake(entity, { fields, annotated }) as E\n }\n\n/**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\nexport const input = <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n>(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const written: Readonly<Record<string, InputMember | string | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(written))\n if (!Object.hasOwn(schema.fields, key))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n // A member named by its key: a Field as it is, a relation as its ids.\n const named = (key: string, name: string): InputMember => {\n const member = (entity.members as Readonly<Record<string, EntityMember | undefined>>)[name]\n switch (member?._tag) {\n case 'Field':\n return member\n case 'Relation':\n return Object.freeze({ _tag: 'RelationInput', relation: member })\n case 'Derived':\n case undefined:\n return fail(\n entity,\n `input key \"${key}\" is mapped to \"${name}\", which names no field or relation`,\n )\n }\n }\n const given: Readonly<Record<string, InputMember | undefined>> = mapValues(\n written,\n (member, key) => (typeof member === 'string' ? named(key, member) : member),\n )\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n own(given, key) ??\n own(fields, key) ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n}\n\n/**\n * The schemas of some of an Entity's fields, by key, to spread into an input's\n * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.\n * The input then keeps the field's own rules, and its keys map themselves.\n */\nexport const fields = <\n E extends AnyEntity,\n const Keys extends ReadonlyArray<keyof E['fields'] & string>,\n>(\n entity: E,\n ...keys: Keys\n): { readonly [K in Keys[number]]: E['fields'][K]['schema'] } =>\n Object.fromEntries(\n keys.map(key => [\n key,\n (\n own(\n entity.fields as Readonly<Record<string, EntityField<string, string, Schema.Constraint>>>,\n key,\n ) ?? fail(entity, `\"${key}\" is not a field`)\n ).schema,\n ]),\n ) as never\n\n/**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n * `also` names members to read beside them, each with `true` (what a lock\n * reads). The Selection is typed as the input's alone: what it reads has\n * those members, and these besides.\n */\nexport const selectFor = <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n options: { readonly also?: Readonly<Record<string, true>> | undefined } = {},\n): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, selectFor(member.input)]]\n : [],\n ),\n )\n return select(input.entity, { ...spec, ...options.also } as never) as never\n}\n\n/**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\nexport const valuesFor = <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n switch (member._tag) {\n case 'Field':\n return [[key, read] as const]\n case 'NestedInput': {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? valuesFor(member.input, held as Readonly<Record<string, unknown>>)\n : null\n return [[key, Array.isArray(read) ? read.map(nested) : nested(read)] as const]\n }\n case 'RelationInput': {\n const ids = Array.isArray(read) ? read.map(idOf) : idOf(read)\n // A relation read without its ids (a nested Selection that left `id` out) fills nothing.\n const known = Array.isArray(ids) ? !ids.includes(undefined) : ids !== undefined\n return known ? [[key, ids] as const] : []\n }\n }\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n}\n\nexport { isEntity as is, isSameEntity as same }\nexport {\n check,\n invariant,\n invariantsOf as invariants,\n judge,\n judgeAgainst,\n judgeInput,\n readsBefore,\n} from './invariant.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8UA,MAAM,cAAc,WAAkC;CAEpD,MAAM,KAD6D,OAAO,OACxD;CAClB,IAAI,OAAO,KAAA,KAAa,GAAG,SAAS,SAAS,OAAO,OAAO;CAC3D,MAAM,OAAO,OAAO,OAAO,GAAG,MAAoB;CAClD,OAAO,YAAY,OAAO,KAAK,GAAG,IAAI,OAAO,OAAO;AACtD;;;;;;;;;;;;;AAcA,MAAa,mBACX,QACA,aAEA,OAAO,MAAMA,aAAmB,OAAO,QAAQ,GAAG;CAChD,cAAc,OAAO,OAAO,QAAQ;CAC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