foldkit-entity 0.15.0 → 0.16.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 +8 -0
- package/dist/entity.d.ts +1 -1
- package/dist/entity.d.ts.map +1 -1
- package/dist/entity.js +1 -0
- package/dist/entity.js.map +1 -1
- package/dist/index.d.ts +24 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/invariant.js +1 -1
- package/dist/invariant.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -203,6 +203,14 @@ Object.keys(Blog.Post.members) // id, title, published, author, editor, comments
|
|
|
203
203
|
them, and `remote-drizzle`'s writer removes them where it deletes, on a store
|
|
204
204
|
without foreign keys too. `cascade` is the one action; `setNull` and
|
|
205
205
|
`restrict` are not declared yet (#348).
|
|
206
|
+
- Who may let a cascade take a row is said beside it. By default each row it
|
|
207
|
+
takes is held to its own `Delete` rule, for whoever deletes the row it
|
|
208
|
+
points at: a delete that would take a row they may not delete is refused
|
|
209
|
+
whole (Guard judges it, the writer holds it). `Relation.one(Post, {
|
|
210
|
+
onDelete: 'cascade', authorizedBy: 'parent' })` says whoever may delete the
|
|
211
|
+
post may take these rows with it, whoever wrote them: a post's author
|
|
212
|
+
removing everyone's likes of it. `authorizedBy` is said only beside
|
|
213
|
+
`onDelete`, and reads back as the relation's `authorizedBy`.
|
|
206
214
|
|
|
207
215
|
`Entity.relate` throws, and the types reject, a relation key that is already a
|
|
208
216
|
member, an owner that is not in the first argument, and a target that is not
|
package/dist/entity.d.ts
CHANGED
|
@@ -66,7 +66,7 @@ type Held<T> = T extends Option.Some<infer A> ? Present<A> : T extends Option.No
|
|
|
66
66
|
* schema's rule; the fit only guards against mapping the wrong member.
|
|
67
67
|
*/
|
|
68
68
|
type Fits<Input, Field> = [Present<Input>] extends [Field] ? true : [Held<Input>] extends [Field] ? true : false;
|
|
69
|
-
type MappingFor<Name extends string, Input, M> = M extends Unmapped ? M : M extends EntityField<infer Owner, any, any> | RelationInput<EntityRelation<infer Owner, any, any, any, any>> | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any> ? [Owner] extends [Name] ? M extends EntityField<any, any, infer S> ? Fits<Input, Schema.Schema.Type<S>> extends true ? M : 'the input value does not fit this field' : M extends RelationInput<infer R> ?
|
|
69
|
+
type MappingFor<Name extends string, Input, M> = M extends Unmapped ? M : M extends EntityField<infer Owner, any, any> | RelationInput<EntityRelation<infer Owner, any, any, any, any>> | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any> ? [Owner] extends [Name] ? M extends EntityField<any, any, infer S> ? Fits<Input, Schema.Schema.Type<S>> extends true ? M : 'the input value does not fit this field' : M extends RelationInput<infer R> ? Held<Input> extends RelationIds<R> ? M : 'the input value is not the id shape of this relation' : M extends NestedInput<infer R, infer I> ? R extends EntityRelation<any, any, infer Target, any, any> ? I extends EntityInput<infer Of, any, any> ? [Of['name']] extends [Target['name']] ? Present<Input> extends NestedValues<R, I> ? M : 'the input value is not the value of the nested input' : `the nested input is of ${Of['name']}, not ${Target['name']}` : never : never : never : `this member belongs to ${Owner}` : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped';
|
|
70
70
|
/** A key that names a field whose value it fits maps itself; every other key needs an entry. */
|
|
71
71
|
type SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = { [K in keyof Fields]: K extends keyof E['fields'] ? Fits<Schema.Schema.Type<Fields[K]>, Schema.Schema.Type<E['fields'][K]['schema']>> extends true ? K : never : never; }[keyof Fields];
|
|
72
72
|
/**
|
package/dist/entity.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity.d.ts","names":[],"sources":["../src/entity.ts"],"mappings":";;;;;;;;KA6DK,KAAK,UAAU,WAAW,aAAa,YAAY;WAEzC,sBAAsB,YAAY;;;KAG5C,WAAW,UAAU,WAAW,YAAY,mBAC9C,W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,cAC/C,YAAY,GAAG,QAAQ,aAAa,GAAG,QAAQ;;;;;;qBA8DrC,SACX,UAAU,iBACJ,aAAa,oBAAoB,uBAAqB,QAEpD,MAAC,MACA,qBACI,KAAK,eAAe,YAAY;;;;;;;;qBAoBlC,YAAa,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OAClF,YAAY,GAAG,QAAQ,UAAQ;WAClB,OAAO,SAAS;MACnC,UACD,WACA,YAAY,UACZ,gBAAgB,GAAG,YAAY,WAC/B,KAAK;;;;;;;qBAwBM,YAAa,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OAClF,YAAY,GAAG,QAAQ,UAAQ,OAC/B,SAAS,6BACf,QAAQ,OAAO,OAAO,KAAK"}
|
package/dist/entity.js
CHANGED
package/dist/entity.js.map
CHANGED
|
@@ -1 +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;CACpC,SAAQ,aAAY,iBAAiB,QAAQ,UAAU,QAAQ;AACjE,CAAC;AAEH,MAAM,oBACJ,QACA,UACA,aACe;CACf,MAAM,YAAY,QAChB,OAAO,OAAO,OAAO,QAAQ,GAAG,KAChC,QAAQ,UACR,SAAS,KAAK,MAAK,QAAO,CAAC,OAAO,OAAO,SAAS,MAAM,MAAO,GAAG,CAAC;CACrE,IAAI,CAAC,OAAO,OAAO,UAAU,MAAM,GAAG;EACpC,MAAM,SAAS,OAAO,KAAK,QAAQ,CAAC,CAAC,OAAO,QAAQ;EACpD,IAAI,OAAO,SAAS,GAClB,KACE,QACA,GAAG,OAAO,KAAK,IAAI,EAAE,GAAG,OAAO,WAAW,IAAI,eAAe,aAAa,mCAAmC,OAAO,WAAW,IAAI,OAAO,QAC5I;EACF,OAAO,OAAO,OAAO,QAAQ;CAC/B;CACA,MAAM,QAA8C,CAAC;CACrD,KAAK,MAAM,OAAO,SAAS,MAAM;EAC/B,MAAM,M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,CACX,CACF;CACA,OAAO,OAAO,MAAM,QAAQ;EAAE,GAAG;EAAM,GAAG,QAAQ;CAAK,CAAU;AACnE;;;;;;;AAQA,MAAa,aACX,OACA,UACwC;CACxC,MAAM,UAAiD,MAAM;CAE7D,MAAM,QAAQ,SACZ,SAAS,OACL,OACA,OAAO,SAAS,YAAY,QAAQ,OAClC,KAAK,KACL,OAAO,SAAS,WACd,OACA,KAAA;CACV,MAAM,UAAU,OAAO,QAAQ,OAAO,CAAC,CAAC,SAAS,CAAC,KAAK,YAAY;EACjE,IAAI,OAAO,SAAS,YAAY,OAAO,CAAC;EACxC,MAAM,UAAU,OAAO,SAAS,UAAU,OAAO,MAAM,OAAO,SAAS;EACvE,IAAI,EAAE,WAAW,QAAQ,OAAO,CAAC;EACjC,MAAM,OAAO,MAAM;EACnB,QAAQ,OAAO,MAAf;GACE,KAAK,SACH,OAAO,CAAC,CAAC,KAAK,IAAI,CAAU;GAC9B,KAAK,eAAe;IAClB,MAAM,UAAU,SACd,OAAO,SAAS,YAAY,SAAS,OACjC,UAAU,OAAO,OAAO,IAAyC,IACjE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,KAAK,iBAAiB;IACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;IAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;GAC1C;EACF;CACF,CAAC;CACD,OAAO,OAAO,YAAY,OAAO;AACnC"}
|
|
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 ? Held<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 authorizedBy: spec.authorizedBy,\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;CACpC,SAAQ,aAAY,iBAAiB,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YAAY,SAAS,OACjC,UAAU,OAAO,OAAO,IAAyC,IACjE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,KAAK,iBAAiB;IACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;IAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;GAC1C;EACF;CACF,CAAC;CACD,OAAO,OAAO,YAAY,OAAO;AACnC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -43,12 +43,21 @@ export type Cardinality = 'one' | 'many';
|
|
|
43
43
|
* with it, by the server in the write that deletes, and foreseen by a client.
|
|
44
44
|
*/
|
|
45
45
|
export type OnDelete = 'cascade';
|
|
46
|
+
/**
|
|
47
|
+
* Who may let a cascade take a row (#348). `child`, the default: the row's own
|
|
48
|
+
* `Delete` rule, judged for whoever deletes the row it points at, so a delete
|
|
49
|
+
* that would take a row they may not delete is refused whole. `parent`: whoever
|
|
50
|
+
* may delete the row it points at may take it too (a post's author removing
|
|
51
|
+
* the likes under it), declared on the relation so it is never a default.
|
|
52
|
+
*/
|
|
53
|
+
export type AuthorizedBy = 'child' | 'parent';
|
|
46
54
|
/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */
|
|
47
55
|
export interface RelationSpec<Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
|
|
48
56
|
readonly target: Target;
|
|
49
57
|
readonly cardinality: C;
|
|
50
58
|
readonly optional: Optional;
|
|
51
59
|
readonly onDelete: Option.Option<OnDelete>;
|
|
60
|
+
readonly authorizedBy: Option.Option<AuthorizedBy>;
|
|
52
61
|
}
|
|
53
62
|
/**
|
|
54
63
|
* A navigation edge as its owner sees it: one or many of `target`. How the edge
|
|
@@ -68,6 +77,8 @@ export interface EntityRelation<Name extends string, Key extends string, Target
|
|
|
68
77
|
* deleted; none for a `many`, and for a `one` declared with nothing.
|
|
69
78
|
*/
|
|
70
79
|
readonly onDelete: Option.Option<OnDelete>;
|
|
80
|
+
/** Who may let a cascade through it take this row: some exactly where `onDelete` is. */
|
|
81
|
+
readonly authorizedBy: Option.Option<AuthorizedBy>;
|
|
71
82
|
readonly metadata: Metadata;
|
|
72
83
|
}
|
|
73
84
|
type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>;
|
|
@@ -305,12 +316,21 @@ export interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.F
|
|
|
305
316
|
readonly schema: Schema.Struct<Fields>;
|
|
306
317
|
readonly members: Members;
|
|
307
318
|
}
|
|
308
|
-
/**
|
|
309
|
-
|
|
319
|
+
/**
|
|
320
|
+
* How a `one` relation is declared: whether it may point nowhere, and what a
|
|
321
|
+
* delete of its target does. `authorizedBy` is said only beside `onDelete`.
|
|
322
|
+
*/
|
|
323
|
+
export type OneOptions<Optional extends boolean> = {
|
|
310
324
|
readonly optional?: Optional;
|
|
325
|
+
} & ({
|
|
326
|
+
readonly onDelete?: undefined;
|
|
327
|
+
readonly authorizedBy?: undefined;
|
|
328
|
+
} | {
|
|
311
329
|
/** `cascade`: a row pointing here is deleted with the row it points at. */
|
|
312
|
-
readonly onDelete
|
|
313
|
-
|
|
330
|
+
readonly onDelete: OnDelete;
|
|
331
|
+
/** Whose `Delete` rule lets the cascade take this row: its own (`child`), or the parent's. */
|
|
332
|
+
readonly authorizedBy?: AuthorizedBy;
|
|
333
|
+
});
|
|
314
334
|
declare function one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>;
|
|
315
335
|
declare function one<Target extends AnyEntity, const Optional extends boolean>(target: Target, options: OneOptions<Optional> & {
|
|
316
336
|
readonly optional: Optional;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["ExprContext","EntityTypeId","EntitySet","AnyVariantUnion","NowExpr","ViewerExpr","ViewerPathExpr","SelectionTypeId","SelectionPageTypeId"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBA2BiB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT;;;;;;YAOA;;iBAGK,aACf,eAAe,WACf,UAAU,aACV;WAES,QAAQ;WACR,aAAa;WACb,UAAU;WACV,UAAU,OAAO,OAAO;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["ExprContext","EntityTypeId","EntitySet","AnyVariantUnion","NowExpr","ViewerExpr","ViewerPathExpr","SelectionTypeId","SelectionPageTypeId"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBA2BiB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT;;;;;;YAOA;;;;;;;;YASA;;iBAGK,aACf,eAAe,WACf,UAAU,aACV;WAES,QAAQ;WACR,aAAa;WACb,UAAU;WACV,UAAU,OAAO,OAAO;WACxB,cAAc,OAAO,OAAO;;;;;;;iBAQtB,eACf,qBACA,oBACA,eAAe,WACf,UAAU,aACV;WAES;WACA,OAAO,eAAe;WACtB,KAAK;;WAEL,cAAc;WACd,aAAa;WACb,UAAU;;;;;WAKV,UAAU,OAAO,OAAO;;WAExB,cAAc,OAAO,OAAO;WAC5B,UAAU;;KAGhB,cAAc,+BAA+B;;;;;;;;;;YAWtC,aAAa,KAAK;;;;;;EAM5B;aAAqB,SAAS,OAAO,OAAO;aAAmB,SAAS,OAAO,OAAO;;EACtF;aAAkB,UAAU;;EAC5B;aAAmB,UA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,OAAA;;cAGX,eAAa,OAAA,iBAAA,OAAA;KAEd,UAAU,KAAK,UAAU,qBAAqB,4BAA4B;qBAElE;;;;;;;;EAQX,OAAO,UAAU,OAAO,YAAU,QACxB,GAAC;aAEE,UAAU;aACV,UAAU;QAEpB,YAAY,GAAG,QAAQ;aAAuB;;;;;;;;;EAejD,QAAQ,UAAU,+BAA+B,4BAA0B,UAC/D,MACT,mBAAmB;aAAwB;aAAwB,UAAU;;;;;;;;;;;EAchF,SACE,UAAU,aACV,UAAU,eAAe,UAAU,YAAY,4BAA0B,UAE/D,GAAC;aACS,QAAQ;QAC3B,mBACM;aACI;aAAyB,UAAU;aAAY,QAAQ"}
|
package/dist/index.js
CHANGED
|
@@ -26,12 +26,16 @@ export * from "./evaluate.js";
|
|
|
26
26
|
const Derivation = Data.taggedEnum();
|
|
27
27
|
function one(target, options) {
|
|
28
28
|
const onDelete = options?.onDelete;
|
|
29
|
+
const authorizedBy = options?.authorizedBy;
|
|
29
30
|
if (onDelete !== void 0 && onDelete !== "cascade") throw new Error(`[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`);
|
|
31
|
+
if (authorizedBy !== void 0 && authorizedBy !== "child" && authorizedBy !== "parent") throw new Error(`[foldkit-entity] Relation.one(${target.name}): authorizedBy is 'child' or 'parent'; ${String(authorizedBy)} is not one`);
|
|
32
|
+
if (authorizedBy !== void 0 && onDelete === void 0) throw new Error(`[foldkit-entity] Relation.one(${target.name}): authorizedBy says who lets a cascade take the row, so it needs onDelete`);
|
|
30
33
|
return {
|
|
31
34
|
target,
|
|
32
35
|
cardinality: "one",
|
|
33
36
|
optional: options?.optional ?? false,
|
|
34
|
-
onDelete: Option.fromUndefinedOr(onDelete)
|
|
37
|
+
onDelete: Option.fromUndefinedOr(onDelete),
|
|
38
|
+
authorizedBy: onDelete === void 0 ? Option.none() : Option.some(authorizedBy ?? "child")
|
|
35
39
|
};
|
|
36
40
|
}
|
|
37
41
|
/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
|
|
@@ -55,7 +59,8 @@ const Relation = {
|
|
|
55
59
|
target,
|
|
56
60
|
cardinality: "many",
|
|
57
61
|
optional: false,
|
|
58
|
-
onDelete: Option.none()
|
|
62
|
+
onDelete: Option.none(),
|
|
63
|
+
authorizedBy: Option.none()
|
|
59
64
|
})
|
|
60
65
|
};
|
|
61
66
|
/** A count: never negative, never a fraction. */
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Data, Option, type Pipeable, Schema } from 'effect'\nimport type { Metadata } from 'foldkit-metadata'\nimport type { ExprContext, NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { HeldRow, HeldRows } from './held.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport type { EntitySet } from './sets.js'\n// The members of `Entity`, a namespace rather than an object so a page keeps only\n// those it calls (#378). Exported under the interface's name; `export * as`\n// would make each `Entity` type here a reference the declaration emitter refuses.\nimport * as EntityMembers from './entity.js'\nimport type { AnyVariantUnion } from './variants.js'\n\nexport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/**\n * What happens to a row when the row its `one` relation points at is deleted\n * (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted\n * with it, by the server in the write that deletes, and foreseen by a client.\n */\nexport type OnDelete = 'cascade'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n readonly onDelete: Option.Option<OnDelete>\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n /**\n * What happens to this row when the row a `one` relation points at is\n * deleted; none for a `many`, and for a `one` declared with nothing.\n */\n readonly onDelete: Option.Option<OnDelete>\n readonly metadata: Metadata\n}\n\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * What a derived member is. `Supplied` (`Derived.make`): an interpreter\n * supplies it, and nothing else can say what it is. `Count`\n * (`Derived.count`): how many rows point at this one through `relation`, a\n * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of\n * a row pointing here through `relation` whose `viewer` relation points at\n * whoever reads it, or none. A client predicts both from the rows it writes,\n * and a server compiles both from the relations' storage.\n */\nexport type Derivation = Data.TaggedEnum<{\n /**\n * `predict`: how a client foresees it for a row it writes; none, it waits\n * for the server. `forbids`: which write to the row its value refuses, so a\n * client holding it refuses that write where it is made.\n */\n Supplied: { readonly predict: Option.Option<Predict>; readonly forbids: Option.Option<Forbids> }\n Count: { readonly relation: OneRelation }\n Exists: { readonly relation: OneRelation; readonly viewer: OneRelation }\n}>\nexport const Derivation = Data.taggedEnum<Derivation>()\n\n/** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */\nexport interface Predicting {\n /** The Entity written, as the write declared it. */\n readonly entity: AnyEntity\n readonly row: HeldRow\n /** The holder's other rows, where a rule's path reads. */\n readonly rows: HeldRows\n /** The operation's context: who asks, and the write's time. */\n readonly context: ExprContext\n}\n\n/**\n * A supplied member foreseen: its value **encoded**, as the store holds it, or\n * none where the holder cannot know it, so nothing is shown before the answer.\n */\nexport type Predict = (predicting: Predicting) => Option.Option<unknown>\n\n/**\n * What a write does to a row it finds, as a supplied member's `forbids` is\n * asked: an update's members and the relations it points, or a delete.\n */\nexport interface WriteSurface {\n readonly kind: 'Update' | 'Delete'\n /** The members it sets, moves or computes, relations not among them. */\n readonly members: ReadonlyArray<string>\n /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly interaction: 'Link' | 'Unlink'\n }>\n}\n\n/**\n * Whether a supplied member's value, **encoded** as the store holds it,\n * refuses `surface`, with the reader's words for why when there are any; none\n * where it does not say so for certain. Only a definite refusal: a client\n * refuses the write unseen, and its server would refuse it too.\n */\nexport type Forbids = (\n value: unknown,\n surface: WriteSurface,\n) => Option.Option<{ readonly reason: Option.Option<string> }>\n\n/** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {\n readonly schema: S\n readonly derives: D\n}\n\n/** A value consumers may read that is not part of `entity.schema`, and what it derives. */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n D extends Derivation = Derivation,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly derives: D\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<\n Name,\n K,\n Derived[K]['schema'],\n Derived[K]['derives']\n >\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */\n readonly sets: Readonly<Record<string, EntitySet>>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/**\n * An Entity whose rows are one of several shapes (`Entity.defineVariants`).\n * `variants` is Effect's tagged union of them, read with its own `match`;\n * `fields` and `schema` are the stored row, which every case shares.\n */\nexport interface VariantEntity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n Union extends AnyVariantUnion = AnyVariantUnion,\n> extends Entity<Name, Fields, Relations, Derived> {\n readonly variants: Union\n}\n\nexport type AnyVariantEntity = VariantEntity<string, any, any, any, any>\n\n/** The keys of an Entity's `one` relations. */\ntype OneRelationKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/**\n * What a field holding `T` may be set to: the time where it holds a number,\n * the viewer's id where text, and what a path from the viewer reads where it\n * holds that.\n */\ntype ContextValueFor<T> =\n | (number extends T ? NowExpr<number> : never)\n | (T extends string ? ViewerExpr<T> : never)\n | ViewerPathExpr<T | null>\n\n/** The name of the Entity the `one` relation `K` points at. */\ntype TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<\n E['relations'][K]['target']\n>['name']\n\n/**\n * What `Entity.sets` takes, by member: a field the value of the write's\n * context it can hold, a `one` relation `Expr.viewer` of its target.\n */\nexport type EntitySets<E extends AnyEntity> = {\n readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<\n Schema.Schema.Type<E['fields'][K]['schema']>\n >\n} & {\n readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>\n}\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D, U>\n : Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\nexport type { InputMembers, WrittenAs, WrittenKey, WrittenSpec } from './entity.js'\nexport { EntityMembers as Entity }\n\n/** How a `one` relation is declared: whether it may point nowhere, and what a delete of its target does. */\nexport interface OneOptions<Optional extends boolean> {\n readonly optional?: Optional\n /** `cascade`: a row pointing here is deleted with the row it points at. */\n readonly onDelete?: OnDelete\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: OneOptions<Optional> & { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one<Target extends AnyEntity>(\n target: Target,\n options: OneOptions<false>,\n): RelationSpec<Target, 'one', false>\nfunction one(\n target: AnyEntity,\n options?: OneOptions<boolean>,\n): RelationSpec<AnyEntity, 'one', boolean> {\n const onDelete = options?.onDelete\n if (onDelete !== undefined && onDelete !== 'cascade')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`,\n )\n return {\n target,\n cardinality: 'one',\n optional: options?.optional ?? false,\n onDelete: Option.fromUndefinedOr(onDelete),\n }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n onDelete: Option.none(),\n }),\n}\n\n/** A count: never negative, never a fraction. */\nconst CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** The id of the row an exists found, as every Remote id is held: text, or none. */\nconst WitnessSchema = Schema.OptionFromNullOr(Schema.String)\n\ntype OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never\n\nexport const Derived = {\n /**\n * A member only an interpreter can compute, of type `schema`: it supplies the\n * value. `predict` says how a client foresees it for a row it writes (Guard's\n * `may`); without it the row reads as missing the member until the answer.\n * `forbids` says which write to the row its value refuses (Guard's `may`\n * again), so a client holding it refuses that write where it is made.\n */\n make: <S extends Schema.Constraint>(\n schema: S,\n options: {\n readonly predict?: Predict | undefined\n readonly forbids?: Forbids | undefined\n } = {},\n ): DerivedSpec<S, Extract<Derivation, { readonly _tag: 'Supplied' }>> => ({\n schema,\n derives: Derivation.Supplied({\n predict: Option.fromUndefinedOr(options.predict),\n forbids: Option.fromUndefinedOr(options.forbids),\n }),\n }),\n\n /**\n * How many rows point at this one through `relation`, a `one` relation of\n * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on\n * Post. Added after `Entity.relate`, which makes the relation. A server\n * compiles it from the relation's storage, and a client predicts it from\n * the rows a pending write inserts, deletes or points elsewhere.\n */\n count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(\n relation: R,\n ): DerivedSpec<typeof CountSchema, { readonly _tag: 'Count'; readonly relation: R }> => ({\n schema: CountSchema,\n derives: Derivation.Count({ relation }) as { readonly _tag: 'Count'; readonly relation: R },\n }),\n\n /**\n * Whether a row points at this one through `relation` and at whoever reads\n * it through `viewer`, another `one` relation of the same pointing Entity:\n * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`\n * on Post. Its value is that row's id as the store holds it, or none, so the\n * reader can take it back (`Write.delete` by that id). It depends on who\n * reads it: a server answers it for the principal it reads as, and a client\n * predicts it for the viewer it is told of.\n */\n exists: <\n R extends OneRelation,\n V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>,\n >(\n relation: R,\n options: { readonly viewer: V },\n ): DerivedSpec<\n typeof WitnessSchema,\n { readonly _tag: 'Exists'; readonly relation: R; readonly viewer: V }\n > => ({\n schema: WitnessSchema,\n derives: Derivation.Exists({ relation, viewer: options.viewer }) as {\n readonly _tag: 'Exists'\n readonly relation: R\n readonly viewer: V\n },\n }),\n}\n\nexport * from './expr.js'\nexport {\n contextValue,\n viewerIdOf,\n type ExprContext,\n type NowExpr,\n type ViewerExpr,\n type ViewerPathExpr,\n} from './context.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\nexport type {\n AnyVariantUnion,\n CheckCases,\n EntityVariants,\n StoredFields,\n VariantCases,\n VariantUnion,\n} from './variants.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport * from './held.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport type { ContextValue, EntitySet, SetOn } from './sets.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteKind,\n type WriteLink,\n type WriteSet,\n type ContextSet,\n type ContextRead,\n type ContextValues,\n} from './write.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,aAAa,KAAK,WAAuB;AA0UtD,SAAS,IACP,QACA,SACyC;CACzC,MAAM,WAAW,SAAS;CAC1B,IAAI,aAAa,KAAA,KAAa,aAAa,WACzC,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,4BAA4B,OAAO,QAAQ,EAAE,YAC5F;CACF,OAAO;EACL;EACA,aAAa;EACb,UAAU,SAAS,YAAY;EAC/B,UAAU,OAAO,gBAAgB,QAAQ;CAC3C;AACF;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;EACV,UAAU,OAAO,KAAK;CACxB;AACF;;AAGA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;;AAGxF,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,MAAM;AAI3D,MAAa,UAAU;;;;;;;;CAQrB,OACE,QACA,UAGI,CAAC,OACmE;EACxE;EACA,SAAS,WAAW,SAAS;GAC3B,SAAS,OAAO,gBAAgB,QAAQ,OAAO;GAC/C,SAAS,OAAO,gBAAgB,QAAQ,OAAO;EACjD,CAAC;CACH;;;;;;;;CASA,QACE,cACuF;EACvF,QAAQ;EACR,SAAS,WAAW,MAAM,EAAE,SAAS,CAAC;CACxC;;;;;;;;;;CAWA,SAIE,UACA,aAII;EACJ,QAAQ;EACR,SAAS,WAAW,OAAO;GAAE;GAAU,QAAQ,QAAQ;EAAO,CAAC;CAKjE;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Data, Option, type Pipeable, Schema } from 'effect'\nimport type { Metadata } from 'foldkit-metadata'\nimport type { ExprContext, NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { HeldRow, HeldRows } from './held.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport type { EntitySet } from './sets.js'\n// The members of `Entity`, a namespace rather than an object so a page keeps only\n// those it calls (#378). Exported under the interface's name; `export * as`\n// would make each `Entity` type here a reference the declaration emitter refuses.\nimport * as EntityMembers from './entity.js'\nimport type { AnyVariantUnion } from './variants.js'\n\nexport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/**\n * What happens to a row when the row its `one` relation points at is deleted\n * (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted\n * with it, by the server in the write that deletes, and foreseen by a client.\n */\nexport type OnDelete = 'cascade'\n\n/**\n * Who may let a cascade take a row (#348). `child`, the default: the row's own\n * `Delete` rule, judged for whoever deletes the row it points at, so a delete\n * that would take a row they may not delete is refused whole. `parent`: whoever\n * may delete the row it points at may take it too (a post's author removing\n * the likes under it), declared on the relation so it is never a default.\n */\nexport type AuthorizedBy = 'child' | 'parent'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n readonly onDelete: Option.Option<OnDelete>\n readonly authorizedBy: Option.Option<AuthorizedBy>\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n /**\n * What happens to this row when the row a `one` relation points at is\n * deleted; none for a `many`, and for a `one` declared with nothing.\n */\n readonly onDelete: Option.Option<OnDelete>\n /** Who may let a cascade through it take this row: some exactly where `onDelete` is. */\n readonly authorizedBy: Option.Option<AuthorizedBy>\n readonly metadata: Metadata\n}\n\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * What a derived member is. `Supplied` (`Derived.make`): an interpreter\n * supplies it, and nothing else can say what it is. `Count`\n * (`Derived.count`): how many rows point at this one through `relation`, a\n * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of\n * a row pointing here through `relation` whose `viewer` relation points at\n * whoever reads it, or none. A client predicts both from the rows it writes,\n * and a server compiles both from the relations' storage.\n */\nexport type Derivation = Data.TaggedEnum<{\n /**\n * `predict`: how a client foresees it for a row it writes; none, it waits\n * for the server. `forbids`: which write to the row its value refuses, so a\n * client holding it refuses that write where it is made.\n */\n Supplied: { readonly predict: Option.Option<Predict>; readonly forbids: Option.Option<Forbids> }\n Count: { readonly relation: OneRelation }\n Exists: { readonly relation: OneRelation; readonly viewer: OneRelation }\n}>\nexport const Derivation = Data.taggedEnum<Derivation>()\n\n/** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */\nexport interface Predicting {\n /** The Entity written, as the write declared it. */\n readonly entity: AnyEntity\n readonly row: HeldRow\n /** The holder's other rows, where a rule's path reads. */\n readonly rows: HeldRows\n /** The operation's context: who asks, and the write's time. */\n readonly context: ExprContext\n}\n\n/**\n * A supplied member foreseen: its value **encoded**, as the store holds it, or\n * none where the holder cannot know it, so nothing is shown before the answer.\n */\nexport type Predict = (predicting: Predicting) => Option.Option<unknown>\n\n/**\n * What a write does to a row it finds, as a supplied member's `forbids` is\n * asked: an update's members and the relations it points, or a delete.\n */\nexport interface WriteSurface {\n readonly kind: 'Update' | 'Delete'\n /** The members it sets, moves or computes, relations not among them. */\n readonly members: ReadonlyArray<string>\n /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly interaction: 'Link' | 'Unlink'\n }>\n}\n\n/**\n * Whether a supplied member's value, **encoded** as the store holds it,\n * refuses `surface`, with the reader's words for why when there are any; none\n * where it does not say so for certain. Only a definite refusal: a client\n * refuses the write unseen, and its server would refuse it too.\n */\nexport type Forbids = (\n value: unknown,\n surface: WriteSurface,\n) => Option.Option<{ readonly reason: Option.Option<string> }>\n\n/** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {\n readonly schema: S\n readonly derives: D\n}\n\n/** A value consumers may read that is not part of `entity.schema`, and what it derives. */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n D extends Derivation = Derivation,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly derives: D\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<\n Name,\n K,\n Derived[K]['schema'],\n Derived[K]['derives']\n >\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */\n readonly sets: Readonly<Record<string, EntitySet>>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/**\n * An Entity whose rows are one of several shapes (`Entity.defineVariants`).\n * `variants` is Effect's tagged union of them, read with its own `match`;\n * `fields` and `schema` are the stored row, which every case shares.\n */\nexport interface VariantEntity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n Union extends AnyVariantUnion = AnyVariantUnion,\n> extends Entity<Name, Fields, Relations, Derived> {\n readonly variants: Union\n}\n\nexport type AnyVariantEntity = VariantEntity<string, any, any, any, any>\n\n/** The keys of an Entity's `one` relations. */\ntype OneRelationKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/**\n * What a field holding `T` may be set to: the time where it holds a number,\n * the viewer's id where text, and what a path from the viewer reads where it\n * holds that.\n */\ntype ContextValueFor<T> =\n | (number extends T ? NowExpr<number> : never)\n | (T extends string ? ViewerExpr<T> : never)\n | ViewerPathExpr<T | null>\n\n/** The name of the Entity the `one` relation `K` points at. */\ntype TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<\n E['relations'][K]['target']\n>['name']\n\n/**\n * What `Entity.sets` takes, by member: a field the value of the write's\n * context it can hold, a `one` relation `Expr.viewer` of its target.\n */\nexport type EntitySets<E extends AnyEntity> = {\n readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<\n Schema.Schema.Type<E['fields'][K]['schema']>\n >\n} & {\n readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>\n}\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D, U>\n : Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\nexport type { InputMembers, WrittenAs, WrittenKey, WrittenSpec } from './entity.js'\nexport { EntityMembers as Entity }\n\n/**\n * How a `one` relation is declared: whether it may point nowhere, and what a\n * delete of its target does. `authorizedBy` is said only beside `onDelete`.\n */\nexport type OneOptions<Optional extends boolean> = {\n readonly optional?: Optional\n} & (\n | { readonly onDelete?: undefined; readonly authorizedBy?: undefined }\n | {\n /** `cascade`: a row pointing here is deleted with the row it points at. */\n readonly onDelete: OnDelete\n /** Whose `Delete` rule lets the cascade take this row: its own (`child`), or the parent's. */\n readonly authorizedBy?: AuthorizedBy\n }\n)\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: OneOptions<Optional> & { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one<Target extends AnyEntity>(\n target: Target,\n options: OneOptions<false>,\n): RelationSpec<Target, 'one', false>\nfunction one(\n target: AnyEntity,\n options?: OneOptions<boolean>,\n): RelationSpec<AnyEntity, 'one', boolean> {\n const onDelete = options?.onDelete\n const authorizedBy = options?.authorizedBy\n if (onDelete !== undefined && onDelete !== 'cascade')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`,\n )\n if (authorizedBy !== undefined && authorizedBy !== 'child' && authorizedBy !== 'parent')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): authorizedBy is 'child' or 'parent'; ${String(authorizedBy)} is not one`,\n )\n if (authorizedBy !== undefined && onDelete === undefined)\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): authorizedBy says who lets a cascade take the row, so it needs onDelete`,\n )\n return {\n target,\n cardinality: 'one',\n optional: options?.optional ?? false,\n onDelete: Option.fromUndefinedOr(onDelete),\n authorizedBy: onDelete === undefined ? Option.none() : Option.some(authorizedBy ?? 'child'),\n }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n onDelete: Option.none(),\n authorizedBy: Option.none(),\n }),\n}\n\n/** A count: never negative, never a fraction. */\nconst CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** The id of the row an exists found, as every Remote id is held: text, or none. */\nconst WitnessSchema = Schema.OptionFromNullOr(Schema.String)\n\ntype OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never\n\nexport const Derived = {\n /**\n * A member only an interpreter can compute, of type `schema`: it supplies the\n * value. `predict` says how a client foresees it for a row it writes (Guard's\n * `may`); without it the row reads as missing the member until the answer.\n * `forbids` says which write to the row its value refuses (Guard's `may`\n * again), so a client holding it refuses that write where it is made.\n */\n make: <S extends Schema.Constraint>(\n schema: S,\n options: {\n readonly predict?: Predict | undefined\n readonly forbids?: Forbids | undefined\n } = {},\n ): DerivedSpec<S, Extract<Derivation, { readonly _tag: 'Supplied' }>> => ({\n schema,\n derives: Derivation.Supplied({\n predict: Option.fromUndefinedOr(options.predict),\n forbids: Option.fromUndefinedOr(options.forbids),\n }),\n }),\n\n /**\n * How many rows point at this one through `relation`, a `one` relation of\n * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on\n * Post. Added after `Entity.relate`, which makes the relation. A server\n * compiles it from the relation's storage, and a client predicts it from\n * the rows a pending write inserts, deletes or points elsewhere.\n */\n count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(\n relation: R,\n ): DerivedSpec<typeof CountSchema, { readonly _tag: 'Count'; readonly relation: R }> => ({\n schema: CountSchema,\n derives: Derivation.Count({ relation }) as { readonly _tag: 'Count'; readonly relation: R },\n }),\n\n /**\n * Whether a row points at this one through `relation` and at whoever reads\n * it through `viewer`, another `one` relation of the same pointing Entity:\n * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`\n * on Post. Its value is that row's id as the store holds it, or none, so the\n * reader can take it back (`Write.delete` by that id). It depends on who\n * reads it: a server answers it for the principal it reads as, and a client\n * predicts it for the viewer it is told of.\n */\n exists: <\n R extends OneRelation,\n V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>,\n >(\n relation: R,\n options: { readonly viewer: V },\n ): DerivedSpec<\n typeof WitnessSchema,\n { readonly _tag: 'Exists'; readonly relation: R; readonly viewer: V }\n > => ({\n schema: WitnessSchema,\n derives: Derivation.Exists({ relation, viewer: options.viewer }) as {\n readonly _tag: 'Exists'\n readonly relation: R\n readonly viewer: V\n },\n }),\n}\n\nexport * from './expr.js'\nexport {\n contextValue,\n viewerIdOf,\n type ExprContext,\n type NowExpr,\n type ViewerExpr,\n type ViewerPathExpr,\n} from './context.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\nexport type {\n AnyVariantUnion,\n CheckCases,\n EntityVariants,\n StoredFields,\n VariantCases,\n VariantUnion,\n} from './variants.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport * from './held.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport type { ContextValue, EntitySet, SetOn } from './sets.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteKind,\n type WriteLink,\n type WriteSet,\n type ContextSet,\n type ContextRead,\n type ContextValues,\n} from './write.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,MAAa,aAAa,KAAK,WAAuB;AAmVtD,SAAS,IACP,QACA,SACyC;CACzC,MAAM,WAAW,SAAS;CAC1B,MAAM,eAAe,SAAS;CAC9B,IAAI,aAAa,KAAA,KAAa,aAAa,WACzC,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,4BAA4B,OAAO,QAAQ,EAAE,YAC5F;CACF,IAAI,iBAAiB,KAAA,KAAa,iBAAiB,WAAW,iBAAiB,UAC7E,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,0CAA0C,OAAO,YAAY,EAAE,YAC9G;CACF,IAAI,iBAAiB,KAAA,KAAa,aAAa,KAAA,GAC7C,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,2EAC/C;CACF,OAAO;EACL;EACA,aAAa;EACb,UAAU,SAAS,YAAY;EAC/B,UAAU,OAAO,gBAAgB,QAAQ;EACzC,cAAc,aAAa,KAAA,IAAY,OAAO,KAAK,IAAI,OAAO,KAAK,gBAAgB,OAAO;CAC5F;AACF;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;EACV,UAAU,OAAO,KAAK;EACtB,cAAc,OAAO,KAAK;CAC5B;AACF;;AAGA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;;AAGxF,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,MAAM;AAI3D,MAAa,UAAU;;;;;;;;CAQrB,OACE,QACA,UAGI,CAAC,OACmE;EACxE;EACA,SAAS,WAAW,SAAS;GAC3B,SAAS,OAAO,gBAAgB,QAAQ,OAAO;GAC/C,SAAS,OAAO,gBAAgB,QAAQ,OAAO;EACjD,CAAC;CACH;;;;;;;;CASA,QACE,cACuF;EACvF,QAAQ;EACR,SAAS,WAAW,MAAM,EAAE,SAAS,CAAC;CACxC;;;;;;;;;;CAWA,SAIE,UACA,aAII;EACJ,QAAQ;EACR,SAAS,WAAW,OAAO;GAAE;GAAU,QAAQ,QAAQ;EAAO,CAAC;CAKjE;AACF"}
|
package/dist/invariant.js
CHANGED
|
@@ -188,7 +188,7 @@ const judgeInput = (input, value, operators = Operators.kernel) => {
|
|
|
188
188
|
if (!Object.hasOwn(value, key)) continue;
|
|
189
189
|
if (member._tag === "RelationInput" && member.relation.cardinality === "one") {
|
|
190
190
|
const given = value[key];
|
|
191
|
-
const id = Option.isOption(given) ? Option.
|
|
191
|
+
const id = Option.isOption(given) ? Option.getOrUndefined(given) : given;
|
|
192
192
|
if (id === null || typeof id === "string") put(row, member.relation.key, id);
|
|
193
193
|
continue;
|
|
194
194
|
}
|
package/dist/invariant.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invariant.js","names":[],"sources":["../src/invariant.ts"],"sourcesContent":["/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`); each `one` relation is\n * there too, as the id it points at, so a judged row holds it as that id. What\n * it reads decides when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { Operators, type MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { remake, variantBases } from './descriptor.js'\nimport type {\n AnyEntity,\n EntityField,\n EntityIdentity,\n EntityInput,\n EntityMember,\n InputMember,\n} from './index.js'\nimport { storesNull, variantsOf } from './variants.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */\n readonly entity: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The members a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The members it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** The keys of an Entity's `one` relations: what a row holds as the id each points at. */\ntype LinkKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */\ntype LinkOf<\n E extends AnyEntity,\n K extends keyof E['relations'],\n> = E['relations'][K]['optional'] extends true ? string | null : string\n\n/**\n * Each field as the row before a write holds it, and each `one` relation as\n * the id it points at: what an invariant reads as `before`. Encoded, as the\n * store holds it and the judge reads it, so a literal is written so too (a\n * date as its ISO text).\n */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id and, once attached, that Entity's name, so a refusal is matched\n * against the declaration rather than a string spelled again\n * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique\n * only within an Entity, so the name is part of what a refusal names; reading\n * it before the declaration is attached throws.\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n readonly entity: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\n/** How an invariant is declared: what `build` returns over the rows, and what a failure says. */\ntype Build<E extends AnyEntity> = (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n}) => Predicate & Reads<E['name']>\n\ninterface Options<E extends AnyEntity> {\n readonly message: string\n readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>\n}\n\n/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */\nconst declareOn = <E extends AnyEntity>(\n entity: E,\n id: string,\n build: Build<E>,\n options: Options<E>,\n): Invariant => {\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const relations = entity.relations as Readonly<Record<string, EntityMember>>\n // A `one` relation reads as the id it points at; a `many` holds no one value.\n const links = Object.values(relations).flatMap(member =>\n member._tag === 'Relation' && member.cardinality === 'one' ? [member as OneRelation] : [],\n )\n const nexts = [\n ...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)] as const),\n ...links.map(link => [link.key, Expr.next(link)] as const),\n ]\n const after = Object.fromEntries(nexts) as unknown as AfterRow<E>\n // Before a write, each is what its `after` reads after it: the same operand, unmoved.\n const before = Object.fromEntries(\n nexts.map(([key, next]) => [key, next.field]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(entity, `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`)\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(entity, `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``)\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key) && !links.some(link => link.key === key))\n fail(entity, `\"${id}\"'s path names \"${key}\", neither a field nor a one relation`)\n }\n return Object.freeze({\n id,\n entity: entity.name,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n })\n}\n\n/**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: Build<E>,\n options: Options<E>,\n): DeclaredInvariant<E> => {\n let attached: string | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined && attached !== entity.name)\n fail(entity, `\"${id}\" is declared on ${attached} already: declare it again for this Entity`)\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n const held = declareOn(entity, id, build, options)\n attached = entity.name\n return remake(entity, {\n metadata: Metadata.combine([entity.metadata, Invariants.of(held)]),\n }) as E\n }\n return Object.defineProperties(declared, {\n id: { value: id, enumerable: true },\n entity: {\n enumerable: true,\n get: () => {\n if (attached === undefined) {\n throw new Error(\n `[foldkit-entity] Entity.invariant \"${id}\" names no Entity until it is attached to one`,\n )\n }\n return attached\n },\n },\n }) as DeclaredInvariant<E>\n}\n\nconst ofCases = new WeakMap<EntityIdentity<string>, ReadonlyArray<Invariant>>()\n\n/**\n * Each case's invariant of a variant Entity (`variant_Available`): a field\n * of its own is held, and one of another case is null. Built when first\n * read, so declaring variants reaches no expression code.\n */\nconst caseInvariants = (identity: EntityIdentity<string>): ReadonlyArray<Invariant> => {\n const base = variantBases.get(identity)\n if (base === undefined) return []\n const known = ofCases.get(identity)\n if (known !== undefined) return known\n const variants = Option.getOrThrow(variantsOf(identity))\n const { name } = base\n const separate = Object.keys(base.fields).filter(\n key => key !== '_tag' && variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key)),\n )\n const built = variants.tags.flatMap(tag => {\n const own = variants.cases[tag]!\n const reads = separate.filter(key => !Object.hasOwn(own, key) || !storesNull(own[key]!))\n if (reads.length === 0) return []\n const held = reads.filter(key => Object.hasOwn(own, key))\n const foreign = reads.filter(key => !Object.hasOwn(own, key))\n return [\n declareOn<AnyEntity>(\n base,\n `variant_${tag}`,\n ({ after }) => {\n const row = after as Readonly<Record<string, NextExpr<unknown>>>\n const checks = [\n ...held.map(key => Expr.isNotNull(row[key]!)),\n ...foreign.map(key => Expr.isNull(row[key]!)),\n ]\n return Expr.or(\n Expr.not(Expr.eq(row._tag!, tag)),\n Expr.and(checks[0]!, ...checks.slice(1)),\n )\n },\n {\n message: `A ${name} that is ${tag} ${[\n ...(held.length > 0 ? [`holds ${held.join(', ')}`] : []),\n ...(foreign.length > 0 ? [`holds none of ${foreign.join(', ')}`] : []),\n ].join(' and ')}`,\n path: reads,\n },\n ),\n ]\n })\n ofCases.set(identity, built)\n return built\n}\n\n/** The Entity's invariants, in the order they were declared. */\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> => {\n const cases = caseInvariants(entity.identity)\n const declared = Invariants.get(entity.metadata)\n return cases.length === 0 ? declared : [...cases, ...declared]\n}\n\n/** `Entity.judge` against invariants already read, such as those a database binding keeps. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it, and\n * each mapped to a `one` relation as the id it points at. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (!Object.hasOwn(value, key)) continue\n // A `one` relation's key holds the id it points at: the row holds that id, or null.\n if (member._tag === 'RelationInput' && member.relation.cardinality === 'one') {\n const given = value[key]\n const id = Option.isOption(given) ? Option.getOrNull(given) : given\n if (id === null || typeof id === 'string') put(row, member.relation.key, id)\n continue\n }\n if (member._tag !== 'Field') continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => put(row, member.key, encoded),\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it. Refused where it\n * is made when an invariant calls an operator `operators` does not run: such a\n * check would pass every value.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> => {\n const predicates = invariantsOf(entity).map(held => held.predicate)\n // The judge runs every operation an invariant reads; an operator alone can be missing.\n const missing = Expr.unsupported(predicates, {\n operations: dependenciesOf(...predicates).operations,\n operators: options.operators ?? Operators.kernel,\n })\n if (missing.length > 0) {\n throw new Error(\n `[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(', ')}, which the operator table does not run; pass one that does as \\`operators\\``,\n )\n }\n return Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n decoded[key],\n ),\n )\n }\n const judged = judge(entity, { after: row }, options.operators)\n if (judged._tag !== 'Invalid') return undefined\n return judged.failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n )\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,aAAa,SAAS,IAAe,6BAA6B;CAEtE,QAAO,WAAU,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;CACpC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAiBD,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAgB9E,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,MAAM,QAAQ,OAAO,OAAO,SAAS,CAAC,CAAC,SAAQ,WAC7C,OAAO,SAAS,cAAc,OAAO,gBAAgB,QAAQ,CAAC,MAAqB,IAAI,CAAC,CAC1F;CACA,MAAM,QAAQ,CACZ,GAAG,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,KAAK,KAAK,KAAK,CAAC,CAAU,GAChF,GAAG,MAAM,KAAI,SAAQ,CAAC,KAA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AM,QAAQ,EAAE,OAAO,IAAI,GAAG,QAAQ,SAAS;EAC9D,IAAI,OAAO,SAAS,WAAW,OAAO,KAAA;EACtC,OAAO,OAAO,SAAS,SAAS,YAC9B,QAAQ,KAAK,WAAW,IACpB,CAAC,QAAQ,OAAO,IAChB,QAAQ,KAAK,KAAI,SAAQ;GAAE,MAAM,CAAC,GAAG;GAAG,OAAO,QAAQ;EAAQ,EAAE,CACvE;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"invariant.js","names":[],"sources":["../src/invariant.ts"],"sourcesContent":["/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`); each `one` relation is\n * there too, as the id it points at, so a judged row holds it as that id. What\n * it reads decides when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { Operators, type MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { remake, variantBases } from './descriptor.js'\nimport type {\n AnyEntity,\n EntityField,\n EntityIdentity,\n EntityInput,\n EntityMember,\n InputMember,\n} from './index.js'\nimport { storesNull, variantsOf } from './variants.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */\n readonly entity: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The members a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The members it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** The keys of an Entity's `one` relations: what a row holds as the id each points at. */\ntype LinkKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */\ntype LinkOf<\n E extends AnyEntity,\n K extends keyof E['relations'],\n> = E['relations'][K]['optional'] extends true ? string | null : string\n\n/**\n * Each field as the row before a write holds it, and each `one` relation as\n * the id it points at: what an invariant reads as `before`. Encoded, as the\n * store holds it and the judge reads it, so a literal is written so too (a\n * date as its ISO text).\n */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id and, once attached, that Entity's name, so a refusal is matched\n * against the declaration rather than a string spelled again\n * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique\n * only within an Entity, so the name is part of what a refusal names; reading\n * it before the declaration is attached throws.\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n readonly entity: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\n/** How an invariant is declared: what `build` returns over the rows, and what a failure says. */\ntype Build<E extends AnyEntity> = (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n}) => Predicate & Reads<E['name']>\n\ninterface Options<E extends AnyEntity> {\n readonly message: string\n readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>\n}\n\n/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */\nconst declareOn = <E extends AnyEntity>(\n entity: E,\n id: string,\n build: Build<E>,\n options: Options<E>,\n): Invariant => {\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const relations = entity.relations as Readonly<Record<string, EntityMember>>\n // A `one` relation reads as the id it points at; a `many` holds no one value.\n const links = Object.values(relations).flatMap(member =>\n member._tag === 'Relation' && member.cardinality === 'one' ? [member as OneRelation] : [],\n )\n const nexts = [\n ...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)] as const),\n ...links.map(link => [link.key, Expr.next(link)] as const),\n ]\n const after = Object.fromEntries(nexts) as unknown as AfterRow<E>\n // Before a write, each is what its `after` reads after it: the same operand, unmoved.\n const before = Object.fromEntries(\n nexts.map(([key, next]) => [key, next.field]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(entity, `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`)\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(entity, `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``)\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key) && !links.some(link => link.key === key))\n fail(entity, `\"${id}\"'s path names \"${key}\", neither a field nor a one relation`)\n }\n return Object.freeze({\n id,\n entity: entity.name,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n })\n}\n\n/**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: Build<E>,\n options: Options<E>,\n): DeclaredInvariant<E> => {\n let attached: string | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined && attached !== entity.name)\n fail(entity, `\"${id}\" is declared on ${attached} already: declare it again for this Entity`)\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n const held = declareOn(entity, id, build, options)\n attached = entity.name\n return remake(entity, {\n metadata: Metadata.combine([entity.metadata, Invariants.of(held)]),\n }) as E\n }\n return Object.defineProperties(declared, {\n id: { value: id, enumerable: true },\n entity: {\n enumerable: true,\n get: () => {\n if (attached === undefined) {\n throw new Error(\n `[foldkit-entity] Entity.invariant \"${id}\" names no Entity until it is attached to one`,\n )\n }\n return attached\n },\n },\n }) as DeclaredInvariant<E>\n}\n\nconst ofCases = new WeakMap<EntityIdentity<string>, ReadonlyArray<Invariant>>()\n\n/**\n * Each case's invariant of a variant Entity (`variant_Available`): a field\n * of its own is held, and one of another case is null. Built when first\n * read, so declaring variants reaches no expression code.\n */\nconst caseInvariants = (identity: EntityIdentity<string>): ReadonlyArray<Invariant> => {\n const base = variantBases.get(identity)\n if (base === undefined) return []\n const known = ofCases.get(identity)\n if (known !== undefined) return known\n const variants = Option.getOrThrow(variantsOf(identity))\n const { name } = base\n const separate = Object.keys(base.fields).filter(\n key => key !== '_tag' && variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key)),\n )\n const built = variants.tags.flatMap(tag => {\n const own = variants.cases[tag]!\n const reads = separate.filter(key => !Object.hasOwn(own, key) || !storesNull(own[key]!))\n if (reads.length === 0) return []\n const held = reads.filter(key => Object.hasOwn(own, key))\n const foreign = reads.filter(key => !Object.hasOwn(own, key))\n return [\n declareOn<AnyEntity>(\n base,\n `variant_${tag}`,\n ({ after }) => {\n const row = after as Readonly<Record<string, NextExpr<unknown>>>\n const checks = [\n ...held.map(key => Expr.isNotNull(row[key]!)),\n ...foreign.map(key => Expr.isNull(row[key]!)),\n ]\n return Expr.or(\n Expr.not(Expr.eq(row._tag!, tag)),\n Expr.and(checks[0]!, ...checks.slice(1)),\n )\n },\n {\n message: `A ${name} that is ${tag} ${[\n ...(held.length > 0 ? [`holds ${held.join(', ')}`] : []),\n ...(foreign.length > 0 ? [`holds none of ${foreign.join(', ')}`] : []),\n ].join(' and ')}`,\n path: reads,\n },\n ),\n ]\n })\n ofCases.set(identity, built)\n return built\n}\n\n/** The Entity's invariants, in the order they were declared. */\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> => {\n const cases = caseInvariants(entity.identity)\n const declared = Invariants.get(entity.metadata)\n return cases.length === 0 ? declared : [...cases, ...declared]\n}\n\n/** `Entity.judge` against invariants already read, such as those a database binding keeps. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it, and\n * each mapped to a `one` relation as the id it points at. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (!Object.hasOwn(value, key)) continue\n // A `one` relation's key holds the id it points at: the row holds that id, or null.\n if (member._tag === 'RelationInput' && member.relation.cardinality === 'one') {\n const given = value[key]\n const id = Option.isOption(given) ? Option.getOrUndefined(given) : given\n if (id === null || typeof id === 'string') put(row, member.relation.key, id)\n continue\n }\n if (member._tag !== 'Field') continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => put(row, member.key, encoded),\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it. Refused where it\n * is made when an invariant calls an operator `operators` does not run: such a\n * check would pass every value.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> => {\n const predicates = invariantsOf(entity).map(held => held.predicate)\n // The judge runs every operation an invariant reads; an operator alone can be missing.\n const missing = Expr.unsupported(predicates, {\n operations: dependenciesOf(...predicates).operations,\n operators: options.operators ?? Operators.kernel,\n })\n if (missing.length > 0) {\n throw new Error(\n `[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(', ')}, which the operator table does not run; pass one that does as \\`operators\\``,\n )\n }\n return Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n decoded[key],\n ),\n )\n }\n const judged = judge(entity, { after: row }, options.operators)\n if (judged._tag !== 'Invalid') return undefined\n return judged.failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n )\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,aAAa,SAAS,IAAe,6BAA6B;CAEtE,QAAO,WAAU,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;CACpC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAiBD,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAgB9E,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,MAAM,QAAQ,OAAO,OAAO,SAAS,CAAC,CAAC,SAAQ,WAC7C,OAAO,SAAS,cAAc,OAAO,gBAAgB,QAAQ,CAAC,MAAqB,IAAI,CAAC,CAC1F;CACA,MAAM,QAAQ,CACZ,GAAG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