foldkit-entity 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +475 -227
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +10 -4
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/descriptor.d.ts +5 -1
  6. package/dist/descriptor.d.ts.map +1 -1
  7. package/dist/descriptor.js +6 -2
  8. package/dist/descriptor.js.map +1 -1
  9. package/dist/entity.d.ts +3 -2
  10. package/dist/entity.d.ts.map +1 -1
  11. package/dist/entity.js +5 -3
  12. package/dist/entity.js.map +1 -1
  13. package/dist/enumerate.d.ts +44 -0
  14. package/dist/enumerate.d.ts.map +1 -0
  15. package/dist/enumerate.js +128 -0
  16. package/dist/enumerate.js.map +1 -0
  17. package/dist/evaluate.d.ts +11 -5
  18. package/dist/evaluate.d.ts.map +1 -1
  19. package/dist/evaluate.js +27 -6
  20. package/dist/evaluate.js.map +1 -1
  21. package/dist/expr.d.ts +8 -2
  22. package/dist/expr.d.ts.map +1 -1
  23. package/dist/expr.js +19 -10
  24. package/dist/expr.js.map +1 -1
  25. package/dist/footprint.d.ts +120 -0
  26. package/dist/footprint.d.ts.map +1 -0
  27. package/dist/footprint.js +41 -0
  28. package/dist/footprint.js.map +1 -0
  29. package/dist/index.d.ts +8 -3
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +6 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/invariant.d.ts +41 -11
  34. package/dist/invariant.d.ts.map +1 -1
  35. package/dist/invariant.js +83 -38
  36. package/dist/invariant.js.map +1 -1
  37. package/dist/lawIds.d.ts +15 -0
  38. package/dist/lawIds.d.ts.map +1 -0
  39. package/dist/lawIds.js +13 -0
  40. package/dist/lawIds.js.map +1 -0
  41. package/dist/laws.d.ts +308 -0
  42. package/dist/laws.d.ts.map +1 -0
  43. package/dist/laws.js +566 -0
  44. package/dist/laws.js.map +1 -0
  45. package/dist/operators.d.ts +1 -1
  46. package/dist/refine.d.ts +64 -0
  47. package/dist/refine.d.ts.map +1 -0
  48. package/dist/refine.js +104 -0
  49. package/dist/refine.js.map +1 -0
  50. package/dist/rows.d.ts +15 -0
  51. package/dist/rows.d.ts.map +1 -0
  52. package/dist/rows.js +23 -0
  53. package/dist/rows.js.map +1 -0
  54. package/dist/uncollated.d.ts +10 -0
  55. package/dist/uncollated.d.ts.map +1 -0
  56. package/dist/uncollated.js +18 -0
  57. package/dist/uncollated.js.map +1 -0
  58. package/dist/write.d.ts +64 -6
  59. package/dist/write.d.ts.map +1 -1
  60. package/dist/write.js +88 -12
  61. package/dist/write.js.map +1 -1
  62. package/package.json +3 -3
@@ -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 { Match, 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 OnDelete,\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 pointInto(member.onDelete.value, member.target().identity, {\n relation: member as OneRelation,\n owner: entity,\n })\n return Object.freeze(related) as never\n}\n\n/** A `one` relation a delete acts through (it cascades, restricts or clears), and the Entity that owns it. */\nexport interface Cascade {\n readonly relation: OneRelation\n readonly owner: AnyEntity\n}\n\nconst pointing: Readonly<Record<OnDelete, WeakMap<EntityIdentity<string>, Array<Cascade>>>> = {\n cascade: new WeakMap(),\n restrict: new WeakMap(),\n setNull: new WeakMap(),\n}\nconst pointInto = (action: OnDelete, target: EntityIdentity<string>, edge: Cascade): void => {\n const known = pointing[action].get(target) ?? []\n known.push(edge)\n pointing[action].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 pointing.cascade.get(entity.identity) ?? []\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'restrict'` that\n * point at `entity`: a delete of one of its rows is refused while a row points\n * at it through one (#467).\n */\nexport const restricting = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.restrict.get(entity.identity) ?? []\n\n/**\n * The optional `one` relations, of any Entity, declared `onDelete: 'setNull'`\n * that point at `entity`: deleting one of its rows clears the link on each row\n * pointing at it through one, which stays (#467).\n */\nexport const clearing = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.setNull.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 = Match.value(member).pipe(\n Match.tag('Field', field => field),\n Match.tags({\n RelationInput: ({ relation }) => relation,\n NestedInput: ({ relation }) => relation,\n }),\n Match.tag('Unmapped', () => undefined),\n Match.orElse(() =>\n fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n ),\n ),\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 Match.valueTags(member, {\n Field: ({ key }) => [[key, true] as const],\n RelationInput: ({ relation }) => [[relation.key, true] as const],\n // What the nested input writes of the target, so its keys can be shown too.\n NestedInput: ({ relation, input: nested }) => [[relation.key, selectFor(nested)] as const],\n Unmapped: () => [],\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 = Match.valueTags(member, {\n Field: ({ key: field }) => field,\n RelationInput: ({ relation }) => relation.key,\n NestedInput: ({ relation }) => relation.key,\n })\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":";;;;;;;;;;;;;;;;;;;AA+UA,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;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ACd,OACA,KAAA;CACV,MAAM,UAAU,OAAO,QAAQ,OAAO,CAAC,CAAC,SAAS,CAAC,KAAK,YAAY;EACjE,IAAI,OAAO,SAAS,YAAY,OAAO,CAAC;EACxC,MAAM,UAAU,MAAM,UAAU,QAAQ;GACtC,QAAQ,EAAE,KAAK,YAAY;GAC3B,gBAAgB,EAAE,eAAe,SAAS;GAC1C,cAAc,EAAE,eAAe,SAAS;EAC1C,CAAC;EACD,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 { Match, 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 OnDelete,\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 { linkId } from './rows.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 pointInto(member.onDelete.value, member.target().identity, {\n relation: member as OneRelation,\n owner: entity,\n })\n return Object.freeze(related) as never\n}\n\n/** A `one` relation a delete acts through (it cascades, restricts or clears), and the Entity that owns it. */\nexport interface Cascade {\n readonly relation: OneRelation\n readonly owner: AnyEntity\n}\n\nconst pointing: Readonly<Record<OnDelete, WeakMap<EntityIdentity<string>, Array<Cascade>>>> = {\n cascade: new WeakMap(),\n restrict: new WeakMap(),\n setNull: new WeakMap(),\n}\nconst pointInto = (action: OnDelete, target: EntityIdentity<string>, edge: Cascade): void => {\n const known = pointing[action].get(target) ?? []\n known.push(edge)\n pointing[action].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 pointing.cascade.get(entity.identity) ?? []\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'restrict'` that\n * point at `entity`: a delete of one of its rows is refused while a row points\n * at it through one (#467).\n */\nexport const restricting = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.restrict.get(entity.identity) ?? []\n\n/**\n * The optional `one` relations, of any Entity, declared `onDelete: 'setNull'`\n * that point at `entity`: deleting one of its rows clears the link on each row\n * pointing at it through one, which stays (#467).\n */\nexport const clearing = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.setNull.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 = Match.value(member).pipe(\n Match.tag('Field', field => field),\n Match.tags({\n RelationInput: ({ relation }) => relation,\n NestedInput: ({ relation }) => relation,\n }),\n Match.tag('Unmapped', () => undefined),\n Match.orElse(() =>\n fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n ),\n ),\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 Match.valueTags(member, {\n Field: ({ key }) => [[key, true] as const],\n RelationInput: ({ relation }) => [[relation.key, true] as const],\n // What the nested input writes of the target, so its keys can be shown too.\n NestedInput: ({ relation, input: nested }) => [[relation.key, selectFor(nested)] as const],\n Unmapped: () => [],\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 const idOf = (held: unknown): unknown => Option.getOrUndefined(linkId(held))\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = Match.valueTags(member, {\n Field: ({ key: field }) => field,\n RelationInput: ({ relation }) => relation.key,\n NestedInput: ({ relation }) => relation.key,\n })\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 { inState, refine, states } from './refine.js'\nexport {\n check,\n invariant,\n invariantsOf as invariants,\n judge,\n judgeAgainst,\n judgeInput,\n judgedBy,\n readsBefore,\n rowFrom,\n type JudgeInputOptions,\n} from './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AAG,CAAU,IAAI,CAAC;GAC1C;EACF;CACF,CAAC;CACD,OAAO,OAAO,YAAY,OAAO;AACnC"}
@@ -0,0 +1,44 @@
1
+ import { Data, Option, Schema } from "effect";
2
+ import { Row } from "./evaluate.js";
3
+ import { MemoryOperators } from "./operators.js";
4
+ import { AnyWrite } from "./write.js";
5
+ /** The most rows (rows before, times inputs) one question is enumerated over. */
6
+ export declare const maxRows = 4096;
7
+ /**
8
+ * The values a stored form can hold, when they are few: a literal, a union of
9
+ * literals, a boolean, each with or without null. None for anything else.
10
+ */
11
+ export declare const finiteValues: (schema: Schema.Top) => Option.Option<ReadonlyArray<unknown>>;
12
+ /** One row a write can start from, an input it can be given, and the row it leaves. */
13
+ export interface Step {
14
+ readonly before: Row;
15
+ readonly input: Row;
16
+ readonly after: Row;
17
+ }
18
+ /** What enumerating a write comes to: every step, or why there is no list of them. */
19
+ export type Steps = Data.TaggedEnum<{
20
+ Steps: {
21
+ readonly steps: ReadonlyArray<Step>;
22
+ };
23
+ Undecided: {
24
+ readonly reason: string;
25
+ };
26
+ }>;
27
+ export declare const Steps: Data.TaggedEnum.Constructor<{
28
+ readonly _tag: "Steps";
29
+ readonly steps: ReadonlyArray<Step>;
30
+ } | {
31
+ readonly _tag: "Undecided";
32
+ readonly reason: string;
33
+ }>;
34
+ /**
35
+ * Every step `write` can take over the members `members` names (field keys of
36
+ * its Entity): each row before over them and the finite members its `when`
37
+ * reads, dropping a row the `when` definitely refuses, with each input value
38
+ * of the keys that set them. Rows are not filtered by the Entity's
39
+ * invariants: a row may be invalid before a write.
40
+ */
41
+ export declare const steps: (write: AnyWrite, members: ReadonlyArray<string>, options?: {
42
+ readonly operators?: MemoryOperators | undefined;
43
+ }) => Steps;
44
+ //# sourceMappingURL=enumerate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enumerate.d.ts","names":[],"sources":["../src/enumerate.ts"],"mappings":";;;;;qBAoBa;;;;;qBAMA,eAAY,QAAY,OAAO,QAAM,OAAO,OAAO;;iBAc/C;WACN,QAAQ;WACR,OAAO;WACP,OAAO;;;YAIN,QAAQ,KAAK;EACvB;aAAkB,OAAO,cAAc;;EACvC;aAAsB;;;qBAEX,OAAK,KAAA,WAAA;;WAHS,OAAA,cAAc;;;WACT;;;;;;;;;qBAuFnB,QAAK,OACT,UAAQ,SACN,uBAAqB;WACV,YAAY;MAC/B"}
@@ -0,0 +1,128 @@
1
+ import { Data, Match, Option, Schema, SchemaAST } from "effect";
2
+ import { own, put } from "./record.js";
3
+ import { heldRow } from "./rows.js";
4
+ import { Judge } from "./evaluate.js";
5
+ import { Query } from "./expr.js";
6
+ import { kernelOperators } from "./memoryTable.js";
7
+ // src/enumerate.ts
8
+ /**
9
+ * The enumerator `Laws.check` and a write's `becomes` share: every row a
10
+ * declared write can start from, over the finite members asked about, with the
11
+ * inputs it can be given and the row it leaves. No solver: a member that is not
12
+ * finite, or that the write changes otherwise than by setting it from its
13
+ * input, makes the question undecided, with the reason.
14
+ */
15
+ /** The most rows (rows before, times inputs) one question is enumerated over. */
16
+ const maxRows = 4096;
17
+ /**
18
+ * The values a stored form can hold, when they are few: a literal, a union of
19
+ * literals, a boolean, each with or without null. None for anything else.
20
+ */
21
+ const finiteValues = (schema) => valuesOf(Schema.toEncoded(schema).ast);
22
+ const valuesOf = (ast) => {
23
+ if (SchemaAST.isLiteral(ast)) return Option.some([ast.literal]);
24
+ if (SchemaAST.isNull(ast)) return Option.some([null]);
25
+ if (SchemaAST.isBoolean(ast)) return Option.some([true, false]);
26
+ if (SchemaAST.isUnion(ast)) return Option.map(Option.all(ast.types.map(valuesOf)), (each) => [...new Set(each.flat())]);
27
+ return Option.none();
28
+ };
29
+ const Steps = Data.taggedEnum();
30
+ const Change = Data.taggedEnum();
31
+ /** The values an input key gives a field, encoded as the field stores them: its own values when the input's are not few. */
32
+ const setValues = (write, key, field) => {
33
+ const schema = write.input.schema.fields[key];
34
+ const takes = Schema.is(Schema.toType(schema));
35
+ const optional = SchemaAST.isOptional(schema.ast) || takes(void 0) || takes(Option.none());
36
+ const encode = Schema.encodeUnknownOption(field.schema);
37
+ const fromInput = Option.map(valuesOf(Schema.toType(schema).ast), (values) => values.flatMap((value) => Option.toArray(encode(value))));
38
+ return Option.map(Option.orElse(fromInput, () => finiteValues(field.schema)), (values) => ({
39
+ values,
40
+ optional
41
+ }));
42
+ };
43
+ /** How `write` changes the member `key` of its row. */
44
+ const changeOf = (write, key) => {
45
+ const set = write.sets.find((each) => each.field.key === key);
46
+ if (set !== void 0) return Option.match(setValues(write, set.key, set.field), {
47
+ onNone: () => Change.Other({ reason: `${key} is set to any value its input holds` }),
48
+ onSome: ({ values, optional }) => Change.Set({
49
+ key: set.key,
50
+ values,
51
+ optional
52
+ })
53
+ });
54
+ if (write.increments.some((each) => each.field.key === key)) return Change.Other({ reason: `${key} is incremented` });
55
+ if (write.assignments.some((each) => each.field.key === key)) return Change.Other({ reason: `${key} is computed` });
56
+ if (write.links.some((each) => each.relation.key === key)) return Change.Other({ reason: `${key} is linked to another row` });
57
+ if (write.context.some((each) => each.member.key === key)) return Change.Other({ reason: `${key} is set by the write's context` });
58
+ if (write.expect?.field.key === key) return Change.Other({ reason: `${key} is the revision it expects, moved on where it lands` });
59
+ return Match.value(write).pipe(Match.tag("Insert", () => Change.Other({ reason: `${key} is not written by the insert, so the store decides it` })), Match.orElse(() => Change.Keep()));
60
+ };
61
+ /** Every combination of one value per key. */
62
+ const combinations = (choices) => choices.reduce((rows, [key, values]) => rows.flatMap((row) => values.map((value) => {
63
+ const next = { ...row };
64
+ put(next, key, value);
65
+ return next;
66
+ })), [{}]);
67
+ /** Absent from an input: the key the write is given nothing for. */
68
+ const absent = Symbol("absent");
69
+ /**
70
+ * Every step `write` can take over the members `members` names (field keys of
71
+ * its Entity): each row before over them and the finite members its `when`
72
+ * reads, dropping a row the `when` definitely refuses, with each input value
73
+ * of the keys that set them. Rows are not filtered by the Entity's
74
+ * invariants: a row may be invalid before a write.
75
+ */
76
+ const steps = (write, members, options = {}) => {
77
+ const entity = write.input.entity;
78
+ const fields = entity.fields;
79
+ const insert = write._tag === "Insert";
80
+ const changes = /* @__PURE__ */ new Map();
81
+ for (const key of members) {
82
+ if (own(fields, key) === void 0) return Steps.Undecided({ reason: `${key} is a link, not a field` });
83
+ const change = changeOf(write, key);
84
+ if (change._tag === "Other") return Steps.Undecided({ reason: change.reason });
85
+ changes.set(key, change);
86
+ }
87
+ const infinite = insert ? void 0 : members.find((key) => Option.isNone(finiteValues(own(fields, key).schema)));
88
+ if (infinite !== void 0) return Steps.Undecided({ reason: `${infinite} is not finite` });
89
+ const condition = Option.filter(write.when, () => !insert);
90
+ const read = Option.map(condition, (body) => Query.dependencies(body));
91
+ const whenKeys = Option.match(read, {
92
+ onNone: () => [],
93
+ onSome: (dependencies) => dependencies.predicate.map((field) => field.key).filter((key) => !changes.has(key) && Option.isSome(Option.flatMap(Option.fromUndefinedOr(own(fields, key)), (field) => finiteValues(field.schema))))
94
+ });
95
+ const beforeChoices = insert ? [] : [.../* @__PURE__ */ new Set([...changes.keys(), ...whenKeys])].map((key) => [key, Option.getOrThrow(finiteValues(own(fields, key).schema))]);
96
+ const setKeys = [...changes.values()].filter(Change.$is("Set"));
97
+ const inputChoices = [...new Map(setKeys.map((set) => [set.key, set])).values()].map((set) => [set.key, set.optional ? [...set.values, absent] : set.values]);
98
+ if ([...beforeChoices, ...inputChoices].reduce((product, [, values]) => product * values.length, 1) > 4096) return Steps.Undecided({ reason: `more than ${maxRows} rows` });
99
+ const operators = options.operators ?? kernelOperators;
100
+ const judged = Option.filter(Option.zipWith(condition, read, (body, dependencies) => ({
101
+ body,
102
+ dependencies
103
+ })), ({ dependencies }) => dependencies.inputs.every((key) => inputChoices.some(([given]) => given === key)) && !dependencies.operations.some((operation) => operation === "viewer" || operation === "now"));
104
+ const result = [];
105
+ for (const before of combinations(beforeChoices)) for (const given of combinations(inputChoices)) {
106
+ const input = {};
107
+ for (const [key, value] of Object.entries(given)) if (value !== absent) put(input, key, value);
108
+ if (Option.match(judged, {
109
+ onNone: () => false,
110
+ onSome: ({ body }) => {
111
+ const row = heldRow(entity, before);
112
+ const verdict = Judge.query(body, input, row, { operators });
113
+ return verdict._tag === "Known" && !verdict.truth;
114
+ }
115
+ })) continue;
116
+ const after = { ...before };
117
+ for (const [key, change] of changes) if (change._tag === "Set" && Object.hasOwn(input, change.key)) put(after, key, own(input, change.key));
118
+ result.push({
119
+ before: insert ? {} : before,
120
+ input,
121
+ after
122
+ });
123
+ }
124
+ return Steps.Steps({ steps: result });
125
+ };
126
+ export { Steps, finiteValues, maxRows, steps };
127
+
128
+ //# sourceMappingURL=enumerate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enumerate.js","names":[],"sources":["../src/enumerate.ts"],"sourcesContent":["/**\n * The enumerator `Laws.check` and a write's `becomes` share: every row a\n * declared write can start from, over the finite members asked about, with the\n * inputs it can be given and the row it leaves. No solver: a member that is not\n * finite, or that the write changes otherwise than by setting it from its\n * input, makes the question undecided, with the reason.\n */\nimport { Data, Match, Option, Schema, SchemaAST } from 'effect'\nimport { Judge, type Row } from './evaluate.js'\nimport { Query } from './expr.js'\nimport type { AnyEntity, EntityField } from './index.js'\nimport { kernelOperators } from './memoryTable.js'\nimport type { MemoryOperators } from './operators.js'\nimport { own, put } from './record.js'\nimport { heldRow } from './rows.js'\nimport type { AnyWrite } from './write.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** The most rows (rows before, times inputs) one question is enumerated over. */\nexport const maxRows = 4096\n\n/**\n * The values a stored form can hold, when they are few: a literal, a union of\n * literals, a boolean, each with or without null. None for anything else.\n */\nexport const finiteValues = (schema: Schema.Top): Option.Option<ReadonlyArray<unknown>> =>\n valuesOf(Schema.toEncoded(schema).ast)\n\nconst valuesOf = (ast: SchemaAST.AST): Option.Option<ReadonlyArray<unknown>> => {\n if (SchemaAST.isLiteral(ast)) return Option.some([ast.literal])\n if (SchemaAST.isNull(ast)) return Option.some([null])\n if (SchemaAST.isBoolean(ast)) return Option.some([true, false])\n if (SchemaAST.isUnion(ast)) {\n return Option.map(Option.all(ast.types.map(valuesOf)), each => [...new Set(each.flat())])\n }\n return Option.none()\n}\n\n/** One row a write can start from, an input it can be given, and the row it leaves. */\nexport interface Step {\n readonly before: Row\n readonly input: Row\n readonly after: Row\n}\n\n/** What enumerating a write comes to: every step, or why there is no list of them. */\nexport type Steps = Data.TaggedEnum<{\n Steps: { readonly steps: ReadonlyArray<Step> }\n Undecided: { readonly reason: string }\n}>\nexport const Steps = Data.taggedEnum<Steps>()\n\n/** How a write changes one member: leaves it, sets it to one of a few values, or otherwise. */\ntype Change = Data.TaggedEnum<{\n Keep: {}\n Set: { readonly key: string; readonly values: ReadonlyArray<unknown>; readonly optional: boolean }\n Other: { readonly reason: string }\n}>\nconst Change = Data.taggedEnum<Change>()\n\n/** The values an input key gives a field, encoded as the field stores them: its own values when the input's are not few. */\nconst setValues = (\n write: AnyWrite,\n key: string,\n field: AnyField,\n): Option.Option<{ readonly values: ReadonlyArray<unknown>; readonly optional: boolean }> => {\n const schema = write.input.schema.fields[key] as unknown as Schema.Top\n const takes = Schema.is(Schema.toType(schema) as Schema.Codec<unknown>)\n // A key that may be absent, or an `Option` holding nothing, writes nothing.\n const optional = SchemaAST.isOptional(schema.ast) || takes(undefined) || takes(Option.none())\n const encode = Schema.encodeUnknownOption(\n field.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const fromInput = Option.map(valuesOf(Schema.toType(schema).ast), values =>\n values.flatMap(value => Option.toArray(encode(value))),\n )\n return Option.map(\n Option.orElse(fromInput, () => finiteValues(field.schema as unknown as Schema.Top)),\n values => ({ values, optional }),\n )\n}\n\n/** How `write` changes the member `key` of its row. */\nconst changeOf = (write: AnyWrite, key: string): Change => {\n const set = write.sets.find(each => each.field.key === key)\n if (set !== undefined) {\n return Option.match(setValues(write, set.key, set.field), {\n onNone: () => Change.Other({ reason: `${key} is set to any value its input holds` }),\n onSome: ({ values, optional }) => Change.Set({ key: set.key, values, optional }),\n })\n }\n if (write.increments.some(each => each.field.key === key))\n return Change.Other({ reason: `${key} is incremented` })\n if (write.assignments.some(each => each.field.key === key))\n return Change.Other({ reason: `${key} is computed` })\n if (write.links.some(each => each.relation.key === key))\n return Change.Other({ reason: `${key} is linked to another row` })\n if (write.context.some(each => each.member.key === key))\n return Change.Other({ reason: `${key} is set by the write's context` })\n if (write.expect?.field.key === key)\n return Change.Other({ reason: `${key} is the revision it expects, moved on where it lands` })\n return Match.value(write).pipe(\n Match.tag('Insert', () =>\n Change.Other({ reason: `${key} is not written by the insert, so the store decides it` }),\n ),\n Match.orElse(() => Change.Keep()),\n )\n}\n\n/** Every combination of one value per key. */\nconst combinations = (\n choices: ReadonlyArray<readonly [string, ReadonlyArray<unknown>]>,\n): ReadonlyArray<Row> =>\n choices.reduce<ReadonlyArray<Row>>(\n (rows, [key, values]) =>\n rows.flatMap(row =>\n values.map(value => {\n const next: Record<string, unknown> = { ...row }\n put(next, key, value)\n return next\n }),\n ),\n [{}],\n )\n\n/** Absent from an input: the key the write is given nothing for. */\nconst absent: unique symbol = Symbol('absent')\n\n/**\n * Every step `write` can take over the members `members` names (field keys of\n * its Entity): each row before over them and the finite members its `when`\n * reads, dropping a row the `when` definitely refuses, with each input value\n * of the keys that set them. Rows are not filtered by the Entity's\n * invariants: a row may be invalid before a write.\n */\nexport const steps = (\n write: AnyWrite,\n members: ReadonlyArray<string>,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): Steps => {\n const entity: AnyEntity = write.input.entity\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const insert = write._tag === 'Insert'\n const changes = new Map<string, Change>()\n // How the write changes a member says more than that the member is not finite, so it is asked first.\n for (const key of members) {\n if (own(fields, key) === undefined)\n return Steps.Undecided({ reason: `${key} is a link, not a field` })\n const change = changeOf(write, key)\n if (change._tag === 'Other') return Steps.Undecided({ reason: change.reason })\n changes.set(key, change)\n }\n const infinite = insert\n ? undefined\n : members.find(key =>\n Option.isNone(finiteValues(own(fields, key)!.schema as unknown as Schema.Top)),\n )\n if (infinite !== undefined) return Steps.Undecided({ reason: `${infinite} is not finite` })\n // What the `when` reads joins the rows when it is finite, so a row it refuses is dropped.\n const condition = Option.filter(write.when, () => !insert)\n const read = Option.map(condition, body => Query.dependencies(body))\n const whenKeys = Option.match(read, {\n onNone: () => [],\n onSome: dependencies =>\n dependencies.predicate\n .map(field => field.key)\n .filter(\n key =>\n !changes.has(key) &&\n Option.isSome(\n Option.flatMap(Option.fromUndefinedOr(own(fields, key)), field =>\n finiteValues(field.schema as unknown as Schema.Top),\n ),\n ),\n ),\n })\n const beforeChoices = insert\n ? []\n : [...new Set([...changes.keys(), ...whenKeys])].map(\n key =>\n [\n key,\n Option.getOrThrow(finiteValues(own(fields, key)!.schema as unknown as Schema.Top)),\n ] as const,\n )\n const setKeys = [...changes.values()].filter(Change.$is('Set'))\n const inputChoices = [...new Map(setKeys.map(set => [set.key, set])).values()].map(\n set => [set.key, set.optional ? [...set.values, absent] : set.values] as const,\n )\n const size = [...beforeChoices, ...inputChoices].reduce(\n (product, [, values]) => product * values.length,\n 1,\n )\n if (size > maxRows) return Steps.Undecided({ reason: `more than ${maxRows} rows` })\n const operators = options.operators ?? kernelOperators\n // The `when` is judged only when what it reads is held: an input it reads that is\n // not enumerated, or the write's context, would read as nothing and refuse wrongly.\n const judged = Option.filter(\n Option.zipWith(condition, read, (body, dependencies) => ({ body, dependencies })),\n ({ dependencies }) =>\n dependencies.inputs.every(key => inputChoices.some(([given]) => given === key)) &&\n !dependencies.operations.some(operation => operation === 'viewer' || operation === 'now'),\n )\n const result: Array<Step> = []\n for (const before of combinations(beforeChoices)) {\n for (const given of combinations(inputChoices)) {\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(given)) if (value !== absent) put(input, key, value)\n const refused = Option.match(judged, {\n onNone: () => false,\n onSome: ({ body }) => {\n const row = heldRow(entity, before)\n const verdict = Judge.query(body, input, row, { operators })\n return verdict._tag === 'Known' && !verdict.truth\n },\n })\n if (refused) continue\n const after: Record<string, unknown> = { ...before }\n for (const [key, change] of changes) {\n if (change._tag === 'Set' && Object.hasOwn(input, change.key))\n put(after, key, own(input, change.key))\n }\n result.push({ before: insert ? {} : before, input, after })\n }\n }\n return Steps.Steps({ steps: result })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,UAAU;;;;;AAMvB,MAAa,gBAAgB,WAC3B,SAAS,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG;AAEvC,MAAM,YAAY,QAA8D;CAC9E,IAAI,UAAU,UAAU,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC,IAAI,OAAO,CAAC;CAC9D,IAAI,UAAU,OAAO,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC,IAAI,CAAC;CACpD,IAAI,UAAU,UAAU,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;CAC9D,IAAI,UAAU,QAAQ,GAAG,GACvB,OAAO,OAAO,IAAI,OAAO,IAAI,IAAI,MAAM,IAAI,QAAQ,CAAC,IAAG,SAAQ,CAAC,GAAG,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC;CAE1F,OAAO,OAAO,KAAK;AACrB;AAcA,MAAa,QAAQ,KAAK,WAAkB;AAQ5C,MAAM,SAAS,KAAK,WAAmB;;AAGvC,MAAM,aACJ,OACA,KACA,UAC2F;CAC3F,MAAM,SAAS,MAAM,MAAM,OAAO,OAAO;CACzC,MAAM,QAAQ,OAAO,GAAG,OAAO,OAAO,MAAM,CAA0B;CAEtE,MAAM,WAAW,UAAU,WAAW,OAAO,GAAG,KAAK,MAAM,KAAA,CAAS,KAAK,MAAM,OAAO,KAAK,CAAC;CAC5F,MAAM,SAAS,OAAO,oBACpB,MAAM,MACR;CACA,MAAM,YAAY,OAAO,IAAI,SAAS,OAAO,OAAO,MAAM,CAAC,CAAC,GAAG,IAAG,WAChE,OAAO,SAAQ,UAAS,OAAO,QAAQ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AAS,aAAa,YAAY,GAAG;EAC9C,MAAM,QAAiC,CAAC;EACxC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,GAAG,IAAI,UAAU,QAAQ,IAAI,OAAO,KAAK,KAAK;EAS7F,IARgB,OAAO,MAAM,QAAQ;GACnC,cAAc;GACd,SAAS,EAAE,WAAW;IACpB,MAAM,MAAM,QAAQ,QAAQ,MAAM;IAClC,MAAM,UAAU,MAAM,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,CAAC;IAC3D,OAAO,QAAQ,SAAS,WAAW,CAAC,QAAQ;GAC9C;EACF,CACU,GAAG;EACb,MAAM,QAAiC,EAAE,GAAG,OAAO;EACnD,KAAK,MAAM,CAAC,KAAK,WAAW,SAC1B,IAAI,OAAO,SAAS,SAAS,OAAO,OAAO,OAAO,OAAO,GAAG,GAC1D,IAAI,OAAO,KAAK,IAAI,OAAO,OAAO,GAAG,CAAC;EAE1C,OAAO,KAAK;GAAE,QAAQ,SAAS,CAAC,IAAI;GAAQ;GAAO;EAAM,CAAC;CAC5D;CAEF,OAAO,MAAM,MAAM,EAAE,OAAO,OAAO,CAAC;AACtC"}
@@ -1,6 +1,6 @@
1
1
  import { Option } from "effect";
2
- import { Collation } from "./collation.js";
3
2
  import { AnyQuery, Operandish, Operation, OperatorDescriptor, OperatorTable, OrderTerm, Predicate } from "./expr.js";
3
+ import { Collation } from "./collation.js";
4
4
  import { HeldRow, HeldRows, Pinned } from "./held.js";
5
5
  import { ExprContext, NowExpr, ViewerExpr } from "./context.js";
6
6
  import { MemoryOperators } from "./operators.js";
@@ -144,9 +144,9 @@ export declare const Judge: {
144
144
  * as `evaluate` sorts: negative when it comes first. A call among them runs
145
145
  * over each row with `input` and `operators` (the kernel's when not given).
146
146
  * Refuses what `evaluate` refuses, for these two rows: a term over neither a
147
- * field nor a call, a locale collation, keys of different kinds, or an
148
- * operator the table lacks. For a client placing one row among others it
149
- * holds.
147
+ * field nor a call, a locale collation, text with no declared collation, keys
148
+ * of different kinds, or an operator the table lacks. For a client placing
149
+ * one row among others it holds.
150
150
  */
151
151
  export declare const compareRows: (terms: ReadonlyArray<OrderTerm>, left: Row, right: Row, query: string, options?: {
152
152
  readonly input?: Row | undefined;
@@ -173,6 +173,10 @@ export declare const assertSupported: (body: AnyQuery, operators?: MemoryOperato
173
173
  * `input` holds the values this run was given, by the keys the body's
174
174
  * placeholders were built with — the same record the query would be called
175
175
  * with anywhere else.
176
+ *
177
+ * The order is part of the answer, so an order over text with no declared
178
+ * collation is refused (`Query.placement`'s reason): declare one on the field,
179
+ * or on the term.
176
180
  */
177
181
  export declare const evaluate: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>, options?: {
178
182
  readonly operators?: MemoryOperators | undefined;
@@ -193,7 +197,9 @@ export interface Evaluated {
193
197
  * What no single row causes still refuses the run: an operation or operator
194
198
  * the table lacks, an order by a locale collation, an input the body reads
195
199
  * holding a NUL (every row would refuse, and no row is the cause), and order
196
- * keys of different kinds across rows.
200
+ * keys of different kinds across rows. It judges membership, which no order
201
+ * decides, so an order over text with no declared collation does not refuse it:
202
+ * `matched` is then in code point order, which no other reader need follow.
197
203
  */
198
204
  export declare const evaluateEach: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>, options?: {
199
205
  readonly operators?: MemoryOperators | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"evaluate.d.ts","names":[],"sources":["../src/evaluate.ts"],"mappings":";;;;;;;YAkDY,MAAM,SAAS;qBAEd,2BAA2B;EACtC,YAAY;;;;;;;qBAWD,6BAA6B;WAC/B,UAAU;;WAEV;;EAET,YAAY,UAAU,oBAAoB,YAAW;;;;;;qBAyC1C,4BAA4B;EACvC,YAAY,MAAM,sBAAsB,kBAAkB;;;iBAyF3C;WACN,MAAM;WACN;;;;;;;qBAiIE,yBAAyB;EACpC,YAAY;;;;;;;qBA+GD,gBAAa,UACd,oBAAkB,QACpB,wBAAsB;WAEnB,WAAW,OAAO,OAAO;WACzB,WAA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OACP,KAAG,MACJ,cAAc,MAAI;WAEb,YAAY;;WAEZ,UAAU;MAEpB,cAAc;;iBAaA;WACN,SAAS,cAAc;WACvB,SAAS,cAAc;;;;;;;;;;;;;;;qBAgBrB,eAAY,MACjB,UAAQ,OACP,KAAG,MACJ,cAAc,MAAI;WAEb,YAAY;;WAEZ,UAAU;MAEpB"}
package/dist/evaluate.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { Match, Option, Schema, SchemaAST } from "effect";
2
2
  import { own } from "./record.js";
3
+ import { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from "./expr.js";
4
+ import { kernelOperators } from "./memoryTable.js";
3
5
  import { absurd } from "effect/Function";
4
6
  import { Collation } from "./collation.js";
5
- import { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from "./expr.js";
7
+ import { uncollatedText } from "./uncollated.js";
6
8
  import { Held } from "./held.js";
7
- import { kernelOperators } from "./memoryTable.js";
8
9
  import { contextValue } from "./context.js";
9
10
  // src/evaluate.ts
10
11
  /**
@@ -627,6 +628,18 @@ const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
627
628
  if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
628
629
  }
629
630
  });
631
+ /**
632
+ * Refuses an order over text with no declared collation: JavaScript would
633
+ * answer by code point where SQLite compares bytes and Postgres follows its
634
+ * locale. Asked wherever the answer depends on the order, and not of a
635
+ * membership judged alone (`evaluateEach`), which no order decides.
636
+ */
637
+ const checkCollated = (terms, query) => {
638
+ for (const term of terms) {
639
+ const uncollated = uncollatedText(term);
640
+ if (Option.isSome(uncollated)) throw new QueryEvaluateError(`query "${query}" cannot be ordered: ${uncollated.value}`);
641
+ }
642
+ };
630
643
  /** Two rows' keys by checked terms: negative when `left` sorts first. */
631
644
  const byTerms = (terms, left, right) => {
632
645
  for (const [index, term] of terms.entries()) {
@@ -643,6 +656,7 @@ const byTerms = (terms, left, right) => {
643
656
  };
644
657
  const ordered = (rows, terms, query, scope) => {
645
658
  if (terms.length === 0) return [...rows];
659
+ checkCollated(terms, query);
646
660
  const keyed = rows.map((row) => ({
647
661
  row,
648
662
  keys: keysOf(row, terms, scope)
@@ -655,9 +669,9 @@ const ordered = (rows, terms, query, scope) => {
655
669
  * as `evaluate` sorts: negative when it comes first. A call among them runs
656
670
  * over each row with `input` and `operators` (the kernel's when not given).
657
671
  * Refuses what `evaluate` refuses, for these two rows: a term over neither a
658
- * field nor a call, a locale collation, keys of different kinds, or an
659
- * operator the table lacks. For a client placing one row among others it
660
- * holds.
672
+ * field nor a call, a locale collation, text with no declared collation, keys
673
+ * of different kinds, or an operator the table lacks. For a client placing
674
+ * one row among others it holds.
661
675
  */
662
676
  const compareRows = (terms, left, right, query, options = {}) => {
663
677
  const scope = {
@@ -666,6 +680,7 @@ const compareRows = (terms, left, right, query, options = {}) => {
666
680
  context: options.context
667
681
  };
668
682
  const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
683
+ checkCollated(terms, query);
669
684
  checkOrder(keys, terms, query);
670
685
  return byTerms(terms, keys[0], keys[1]);
671
686
  };
@@ -704,6 +719,10 @@ const assertSupported = (body, operators = kernelOperators) => {
704
719
  * `input` holds the values this run was given, by the keys the body's
705
720
  * placeholders were built with — the same record the query would be called
706
721
  * with anywhere else.
722
+ *
723
+ * The order is part of the answer, so an order over text with no declared
724
+ * collation is refused (`Query.placement`'s reason): declare one on the field,
725
+ * or on the term.
707
726
  */
708
727
  const evaluate = (body, input, rows, options = {}) => {
709
728
  const operators = options.operators ?? kernelOperators;
@@ -724,7 +743,9 @@ const evaluate = (body, input, rows, options = {}) => {
724
743
  * What no single row causes still refuses the run: an operation or operator
725
744
  * the table lacks, an order by a locale collation, an input the body reads
726
745
  * holding a NUL (every row would refuse, and no row is the cause), and order
727
- * keys of different kinds across rows.
746
+ * keys of different kinds across rows. It judges membership, which no order
747
+ * decides, so an order over text with no declared collation does not refuse it:
748
+ * `matched` is then in code point order, which no other reader need follow.
728
749
  */
729
750
  const evaluateEach = (body, input, rows, options = {}) => {
730
751
  const operators = options.operators ?? kernelOperators;