foldkit-entity 0.9.0 → 0.11.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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-5avJ3IkP.mjs","names":["key","Arr","fail"],"sources":["../src/shape.ts","../src/collation.ts","../src/expr.ts","../src/readFilter.ts","../src/words.ts","../src/evaluate.ts","../src/write.ts","../src/index.ts"],"sourcesContent":["import { SchemaAST } from 'effect'\n\nconst isNullish = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast)\n\nconst isText = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isString(ast) ||\n SchemaAST.isTemplateLiteral(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'string') ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText))\n\n/** What a schema's AST holds, read through Effect's own guards. */\nexport const SchemaShape = {\n /** True for the `null` and `undefined` members that make a schema optional. */\n isNullish,\n\n /**\n * The members of a schema with `null` and `undefined` set aside, so optional\n * text is still text; a schema that is not a union is its one member.\n */\n present: (ast: SchemaAST.AST): ReadonlyArray<SchemaAST.AST> =>\n SchemaAST.isUnion(ast) ? ast.types.filter(member => !isNullish(member)) : [ast],\n\n /** True when every value the schema admits is a string. */\n isText,\n}\n","/**\n * How text compares when a query orders by it, declared rather than left to\n * the backend. Left unsaid, SQLite compares bytes, Postgres follows the\n * database's locale and a JavaScript sort follows UTF-16 code units, so the\n * same body could order the same rows three ways. A declared collation is one\n * every interpreter that can honour it compiles to the same order, and one\n * that cannot refuses.\n *\n * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(\n * Collation.binary) })`), so most queries declare nothing; an order term may\n * override it (`Order.asc(field, { collation })`).\n */\nimport { Option } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport type Collation =\n /** By code point: SQLite `BINARY`, Postgres `COLLATE \"C\"`. */\n | { readonly _tag: 'Binary' }\n /** ASCII letters folded to lower case, then by code point: SQLite `NOCASE`, Postgres `lower(x COLLATE \"C\")`. */\n | { readonly _tag: 'AsciiFold' }\n /** The backend's collation by this name: ordered by the server, never by a client. */\n | { readonly _tag: 'Locale'; readonly locale: string }\n\nconst key = Metadata.key<Collation>('foldkit-entity/collation', {\n // The last collation attached wins: a later annotation refines an earlier one.\n merge: collations => collations.slice(-1),\n summarize: collation => collation._tag,\n})\n\n/** A collation name a backend can be told, and nothing that could be read as SQL. */\nconst localeName = /^[A-Za-z0-9_.@-]{1,64}$/\n\nexport const Collation = {\n binary: Object.freeze({ _tag: 'Binary' }) as Collation,\n asciiFold: Object.freeze({ _tag: 'AsciiFold' }) as Collation,\n locale: (locale: string): Collation => {\n if (!localeName.test(locale)) {\n throw new Error(`[foldkit-entity] Collation.locale: \"${locale}\" is not a collation name`)\n }\n return Object.freeze({ _tag: 'Locale', locale })\n },\n\n /** Member metadata: how a text field orders, wherever a query orders by it. */\n of: (collation: Collation): Metadata => key.of(collation),\n\n /** The collation a member's metadata declares, if any. */\n declared: (metadata: Metadata): Option.Option<Collation> =>\n Option.fromUndefinedOr(key.get(metadata)[0]),\n}\n","/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Array as Arr, Match, Option, Pipeable, Schema, SchemaAST } from 'effect'\nimport { Collation } from './collation.js'\nimport type { AnyEntity, EntityField, EntityIdentity } from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n /**\n * How it compares when ordered by, as the field declares (`Collation.of`).\n * An id is `binary` unless it says otherwise: its order need only be total\n * and agreed, and every order ends on it.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate =\n | EqPredicate\n | NullPredicate\n | ContainsPredicate\n | InPredicate\n | AndPredicate\n | OrPredicate\n | NotPredicate\n | ComparePredicate\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Whether a value is one of a list. The list is a scalar whose value is an\n * array: a literal, or an input (a principal's `projectIds`, a picker's\n * chosen ids). Read as SQL's `in`: a null value is unknown, and so is no\n * match against a list holding a null; an empty list matches nothing.\n */\nexport interface InPredicate {\n readonly _tag: 'In'\n readonly value: AnyExpr\n readonly among: AnyExpr\n}\n\n/**\n * Every operand holds. `Query.where`'s list is already a conjunction; this is\n * one inside something else, `or(and(a, b), c)`. Never empty, and never holding\n * another `and`: `Expr.and` flattens one into its parent.\n */\nexport interface AndPredicate {\n readonly _tag: 'And'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/** At least one operand holds. Never empty, and never holding another `or`. */\nexport interface OrPredicate {\n readonly _tag: 'Or'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/**\n * The operand does not hold. As SQL's `not`, an unknown stays unknown, so a row\n * whose operand is unknown (a null compared) is matched by neither the operand\n * nor its `not`.\n */\nexport interface NotPredicate {\n readonly _tag: 'Not'\n readonly operand: Predicate\n}\n\n/** Which way a comparison orders its two sides: `left < right` for `lt`. */\nexport type CompareOperator = 'lt' | 'lte' | 'gt' | 'gte'\n\n/**\n * One scalar orders before, or after, the other. A null on either side is\n * unknown. `collation` is how text compares, decided where the comparison is\n * written (see `Expr.lt`); none for values that order intrinsically, numbers.\n */\nexport interface ComparePredicate {\n readonly _tag: 'Compare'\n readonly operator: CompareOperator\n readonly left: AnyExpr\n readonly right: AnyExpr\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/** A field, a scalar already built from one, or a predicate used as a boolean. */\ntype Operand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\n/**\n * A field or scalar whose value is text, or absent text.\n *\n * `Expr.contains` is a case-insensitive **text** search that compiles to\n * `lower(column) like lower(?)`. Over a number that is nonsense which reaches\n * the database — SQLite coerces and answers something, Postgres raises — so\n * the operand is constrained here rather than discovered there.\n *\n * Null belongs in the type, because a nullable text column is a real and\n * documented case: a null contains nothing, not even the empty string, so its\n * rows drop out of a search that would otherwise match everything.\n *\n * Written as a **constraint on the type parameter** rather than as a check\n * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for\n * an unregistered descriptor). That idiom compares an already-resolved indexed\n * access; here the check would be a conditional over the type being inferred,\n * and inference falls back to the constraint — whose `Expr<any>` branch makes\n * the check vacuously true, so every operand passes. A constraint cannot be\n * defeated that way.\n */\nexport type TextOperand =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>>\n | Expr<string>\n | Expr<string | null>\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\n/**\n * Every node is frozen as it is made, so a query built from it stays the value\n * it was when `Query.where` checked it: nothing can swap a field or a literal\n * in afterwards. It also means no node can come to contain itself. A literal's\n * own payload is the caller's; the kernel compares scalars.\n */\nconst node = <T extends object>(value: T): T => Object.freeze(value)\n\nconst literal = <T>(value: T): LiteralExpr<T> => node({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> =>\n node({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n collation: Option.orElse(Collation.declared(field.metadata), () =>\n field.key === 'id' ? Option.some(Collation.binary) : Option.none(),\n ),\n })\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains', 'In', 'And', 'Or', 'Not', 'Compare'])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Literal' || tag === 'Input' || predicateTags.has(tag as string)) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/**\n * Every operation the kernel has. An interpreter declares which of them it\n * runs, and a body needing one it does not is refused rather than answered\n * wrongly — see `Query.unsupported`.\n */\nexport type Operation =\n 'eq' | 'isNull' | 'isNotNull' | 'contains' | 'in' | 'and' | 'or' | 'not' | 'compare'\n\n/** One field an expression reads: its Entity's name and key, and the identity that owns it. */\nexport interface FieldDependency {\n /** The owning Entity's name, for display; two Entities may share one. */\n readonly entity: string\n readonly key: string\n /** Which Entity it is. Two defined with the same name are two entries. */\n readonly owner: EntityIdentity<string>\n}\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field of each Entity identity. */\n readonly fields: ReadonlyArray<FieldDependency>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<Operation>\n}\n\n/**\n * What a query reads, with each field's role. A change to a `predicate` field\n * can move a row into or out of the result; a change to an `order` field can\n * move it within. A field in both is in both; `fields` is their union.\n */\nexport interface QueryDependencies extends Dependencies {\n readonly predicate: ReadonlyArray<FieldDependency>\n readonly order: ReadonlyArray<FieldDependency>\n}\n\n/**\n * A field or scalar whose value orders: a number, text, a date (which orders by\n * its encoded form), or one of those absent. A boolean does not order here.\n * A constraint on the type parameter, as `TextOperand` is, so inference cannot\n * fall back past it.\n */\nexport type OrderedOperand =\n | EntityField<\n string,\n string,\n Schema.Constraint & Schema.Codec<number | string | Date | null, any, any, any>\n >\n | Expr<number>\n | Expr<number | null>\n | Expr<string>\n | Expr<string | null>\n | Expr<Date>\n | Expr<Date | null>\n\n/** How values encoded by `ast` order: as numbers, as text, or not at all. */\nconst orderKindOf = (ast: SchemaAST.AST): 'number' | 'text' | 'none' => {\n if (SchemaAST.isNumber(ast)) return 'number'\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return 'text'\n if (SchemaAST.isLiteral(ast)) {\n if (typeof ast.literal === 'number') return 'number'\n if (typeof ast.literal === 'string') return 'text'\n return 'none'\n }\n if (SchemaAST.isUnion(ast)) {\n // A null orders nowhere, as every comparison of it is unknown.\n const kinds = new Set(ast.types.filter(member => !SchemaAST.isNull(member)).map(orderKindOf))\n const [only] = kinds\n return kinds.size === 1 && only !== undefined ? only : 'none'\n }\n return 'none'\n}\n\n/** How a literal orders; a null orders as anything, since comparing it is unknown. */\nconst literalKind = (value: unknown): 'number' | 'text' | 'none' | 'null' => {\n if (value === null) return 'null'\n if (typeof value === 'number') return 'number'\n if (typeof value === 'string') return 'text'\n return 'none'\n}\n\n/** How a side orders, read from its encoded form. */\nconst sideKind = (side: AnyExpr): 'number' | 'text' | 'none' | 'null' =>\n Match.value(side).pipe(\n Match.tagsExhaustive({\n Field: field => orderKindOf(Schema.toEncoded(field.schema).ast),\n Input: input => orderKindOf(Schema.toEncoded(input.schema).ast),\n Literal: ({ value }) => literalKind(value),\n }),\n )\n\n/**\n * How a comparison's text compares: the collation given, else the field's\n * declared one. Text orders differently by backend (SQLite's `BINARY`, the\n * Postgres database's locale, JavaScript's UTF-16 units), so it is compared\n * only under `binary` or `asciiFold`, which every interpreter here agrees on,\n * and only against a field, whose collation it is. Values that order\n * intrinsically, numbers, need none.\n */\nconst collationFor = (\n step: CompareOperator,\n left: AnyExpr,\n right: AnyExpr,\n given: Option.Option<Collation>,\n): Option.Option<Collation> => {\n const kinds = new Set([sideKind(left), sideKind(right)].filter(kind => kind !== 'null'))\n if (kinds.has('none') || kinds.size > 1) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`,\n )\n }\n if (!kinds.has('text')) return Option.none()\n const fields = [left, right].flatMap(side =>\n Match.value(side).pipe(\n Match.tag('Field', field => [field]),\n Match.orElse(() => []),\n ),\n )\n const [first] = fields\n if (first === undefined) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: text compared with no field, whose collation would say how it orders`,\n )\n }\n const named = fields.map(field => `${field.owner.name}.${field.key}`).join(' and ')\n const collations = Option.match(given, {\n onSome: collation => [collation],\n onNone: () =>\n fields.map(field =>\n Option.getOrElse(field.collation, () => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${field.owner.name}.${field.key} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`,\n )\n }),\n ),\n })\n const [collation] = collations\n if (collation === undefined || collations.some(each => each._tag !== collation._tag)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`,\n )\n }\n return Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.some(collation),\n AsciiFold: () => Option.some(collation),\n Locale: ({ locale }) => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} compares by the backend's \"${locale}\" collation, which only that backend has`,\n )\n },\n }),\n )\n}\n\n/** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */\nconst comparison =\n (operator: CompareOperator) =>\n <L extends OrderedOperand>(\n left: L,\n right: ValueOf<L> | Expr<ValueOf<L>>,\n options: { readonly collation?: Collation | undefined } = {},\n ): ComparePredicate => {\n const leftSide = toExpr<unknown>(left, operator)\n const rightSide = toExpr<unknown>(right, operator)\n return node({\n _tag: 'Compare',\n operator,\n left: leftSide,\n right: rightSide,\n collation: collationFor(\n operator,\n leftSide,\n rightSide,\n Option.fromUndefinedOr(options.collation),\n ),\n })\n }\n\n/** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */\nconst connected = (\n step: 'and' | 'or',\n kind: 'And' | 'Or',\n given: ReadonlyArray<unknown>,\n): Arr.NonEmptyReadonlyArray<Predicate> => {\n const operands = given.flatMap((operand): ReadonlyArray<Predicate> => {\n if (!isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`,\n )\n }\n return Match.value(operand).pipe(\n Match.tags({\n And: and => (kind === 'And' ? and.operands : [and]),\n Or: or => (kind === 'Or' ? or.operands : [or]),\n }),\n Match.orElse(() => [operand]),\n )\n })\n // Flattening copies a shared operand's list, so `or(x, x)` built thirty deep\n // would be 2^30 operands before the budget ever counts them.\n if (operands.length > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`,\n )\n }\n if (!Arr.isReadonlyArrayNonEmpty(operands)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: no operands, which would match ${step === 'and' ? 'every row' : 'no row'}; check a list is non-empty before spreading it`,\n )\n }\n return operands\n}\n\n/** `Expr.and` and `Expr.or`: one operand is that operand, and two or more are one node. */\ninterface Connective<Node extends Predicate> {\n <P extends Predicate>(only: P): P\n (first: Predicate, second: Predicate, ...rest: ReadonlyArray<Predicate>): Node\n (...operands: Arr.NonEmptyReadonlyArray<Predicate>): Predicate\n}\n\nconst connective =\n <Node extends AndPredicate | OrPredicate>(step: 'and' | 'or', kind: Node['_tag']) =>\n (...given: ReadonlyArray<Predicate>): Predicate => {\n const operands = connected(step, kind, given)\n return operands.length === 1 ? operands[0] : node({ _tag: kind, operands } as Node)\n }\n\nexport const Expr = {\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> =>\n node({ _tag: 'Input', key, schema }),\n\n /** One field of one Entity, as a scalar. */\n field: <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> => fieldExpr(field) as FieldExpr<Schema.Schema.Type<S>>,\n\n /**\n * Two scalars are the same value. A field or a plain value on either side is\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <L extends Operand<any>>(\n left: L,\n right: ValueOf<L> | Expr<ValueOf<L>> | (boolean extends ValueOf<L> ? Predicate : never),\n ): EqPredicate => node({ _tag: 'Eq', left: toOperand(left), right: toOperand(right as never) }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, since a query asks which of the two it means, and `is not null`\n * has no unknown for a `not` to keep.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNull'), present: false }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNotNull'), present: true }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.\n */\n contains: <L extends TextOperand>(value: L, search: string | Expr<string>): ContainsPredicate =>\n node({\n _tag: 'Contains',\n value: toExpr(value, 'contains'),\n search: toOperand(search as never),\n }),\n\n /**\n * Whether a value is one of `among`: a list written out, or an input whose\n * value is one. Each element is compared as `eq` compares.\n *\n * ```ts\n * Expr.in(Todo.fields.projectId, input.projectIds)\n * Expr.in(Todo.fields.status, ['open', 'blocked'])\n * ```\n *\n * As SQL's `in`: a null value is unknown, as is no match against a list\n * holding a null, and an empty list matches no row. A list written out is\n * copied, so changing the array afterwards does not change the query.\n */\n in: <L extends Operand<any>>(\n value: L,\n among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>,\n ): InPredicate =>\n node({\n _tag: 'In',\n value: toExpr(value, 'in'),\n among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, 'in'),\n }),\n\n /**\n * `left` orders before `right`. Numbers compare as numbers; text compares\n * under a collation, the one given or the field's declared one, which must be\n * `binary` or `asciiFold` (so every backend agrees), and text needs a field on\n * one side. A date compares by its encoded form: as text when it is stored as\n * an ISO string, so its field declares `Collation.binary`. A null on either\n * side is unknown, so the row is matched by neither this nor its `not`.\n *\n * ```ts\n * Expr.lt(fields.cents, 1000)\n * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))\n * ```\n */\n lt: comparison('lt'),\n /** `left` orders before `right`, or with it; see `Expr.lt`. */\n lte: comparison('lte'),\n /** `left` orders after `right`; see `Expr.lt`. */\n gt: comparison('gt'),\n /** `left` orders after `right`, or with it; see `Expr.lt`. */\n gte: comparison('gte'),\n\n /**\n * Every operand holds, as one predicate to place inside another: `where`'s\n * list is already a conjunction, so this is for `or(and(a, b), c)`.\n * Unknown as SQL's `and` is: false wins over unknown, which wins over true.\n * Needs an operand; a list built at run time is checked non-empty first\n * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.\n */\n and: connective<AndPredicate>('and', 'And') as Connective<AndPredicate>,\n\n /**\n * At least one operand holds:\n *\n * ```ts\n * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))\n * ```\n *\n * Unknown as SQL's `or` is: true wins over unknown, which wins over false.\n * Needs an operand, since an empty `or` would match no row.\n */\n or: connective<OrPredicate>('or', 'Or') as Connective<OrPredicate>,\n\n /**\n * The operand does not hold. **A null is matched by neither side**:\n * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since\n * `null = 'draft'` is unknown and so is its `not`, as in SQL. \"Everything\n * but drafts\" over a nullable column is\n * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.\n */\n not: (operand: Predicate): NotPredicate => {\n if (!isPredicate(operand)) {\n throw new Error(\n '[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first',\n )\n }\n return node({ _tag: 'Not', operand })\n },\n\n /**\n * A filter that applies only when its input is given: `or(isNull($x), …)`,\n * with the predicate built from the input as never null.\n *\n * ```ts\n * // Every product, or those of the chosen status.\n * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))\n * ```\n *\n * An interpreter that runs per request, as the Drizzle compiler does, decides\n * `isNull($x)` before writing SQL, so this compiles to `true`, which filters\n * nothing, or to the predicate alone.\n */\n whenGiven: <T>(\n input: InputExpr<T>,\n build: (given: InputExpr<NonNullable<T>>) => Predicate,\n ): Predicate =>\n // The predicate only decides a row when the input is not null: when it is,\n // `isNull` is true and so is the `or`. That is what the narrowed type says.\n Expr.or(Expr.isNull(input), build(input as unknown as InputExpr<NonNullable<T>>)),\n\n /** An expression as readable text; see `showExpr` for what it is and is not. */\n show: (node: Operandish): string => showExpr(node),\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly _tag: 'Term'\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n /**\n * Where rows without a value go, in the term's own direction. Databases\n * disagree when it is left unsaid (Postgres puts them last ascending, SQLite\n * first), so it is always said: last ascending and first descending unless\n * a term asks otherwise, which is Postgres's.\n */\n readonly nulls: 'first' | 'last'\n /**\n * How text compares, when the term orders text: the term's own, or its\n * field's. None leaves it to the backend, which a client cannot match.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/** What a term may say besides its operand. */\nexport interface TermOptions {\n readonly nulls?: 'first' | 'last' | undefined\n /** Overrides the field's declared collation for this term. */\n readonly collation?: Collation | undefined\n}\n\n/** A term, its nulls placed by `options` or by the direction's default. */\nconst term = (direction: 'asc' | 'desc', expr: AnyExpr, options: TermOptions = {}): OrderTerm =>\n node({\n _tag: 'Term',\n direction,\n expr,\n nulls: options.nulls ?? (direction === 'asc' ? 'last' : 'first'),\n collation: Option.orElse(Option.fromUndefinedOr(options.collation), () =>\n Match.value(expr).pipe(\n Match.tag('Field', field => field.collation),\n Match.orElse(() => Option.none<Collation>()),\n ),\n ),\n })\n\n/** How a list is sorted, as its input holds it: one of its named orders, which way, or none. */\nexport type ChosenSort<By extends string> = {\n readonly by: By\n readonly direction: 'asc' | 'desc'\n} | null\n\n/**\n * An ordering the input chooses: one of several named fields, which way, or\n * none. It is how a list sorts by what its reader picked, said in the body, so\n * the server and the client read one declaration of what each name means.\n */\nexport interface ChosenOrder {\n readonly _tag: 'Chosen'\n readonly sort: InputExpr<ChosenSort<string>>\n readonly choices: Readonly<Record<string, FieldExpr<unknown>>>\n}\n\n/** One entry of a body's ordering: fixed, or chosen by the input. */\nexport type Ordering = OrderTerm | ChosenOrder\n\nexport const Order = {\n /** Smallest first; rows without a value last, unless `nulls` says first. */\n asc: <E extends Operand<any>>(expr: E, options?: TermOptions): OrderTerm =>\n term('asc', toExpr(expr as never, 'asc'), options),\n /** Largest first; rows without a value first, unless `nulls` says last. */\n desc: <E extends Operand<any>>(expr: E, options?: TermOptions): OrderTerm =>\n term('desc', toExpr(expr as never, 'desc'), options),\n\n /**\n * The order the input names, among `choices`: every name the sort can hold\n * maps to a field, so a name left out is a type error here, not a query that\n * silently orders by nothing. A `null` sort chooses none, and the terms after\n * it decide.\n *\n * ```ts\n * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))\n * ```\n */\n chosen: <By extends string>(\n sort: InputExpr<ChosenSort<By>>,\n choices: { readonly [K in By]: Operand<any> },\n ): ChosenOrder => {\n const fields: Record<string, FieldExpr<unknown>> = Object.create(null)\n for (const [name, choice] of Object.entries<Operand<any>>(choices)) {\n const expr = toExpr(choice as never, 'chosen')\n if (expr._tag !== 'Field') {\n throw new Error(`[foldkit-entity] Order.chosen: \"${name}\" is not a field`)\n }\n fields[name] = expr\n }\n return node({\n _tag: 'Chosen',\n sort: sort as InputExpr<ChosenSort<string>>,\n choices: Object.freeze(fields),\n })\n },\n}\n\n/**\n * Whether a client can order rows the way the server does, for one input: the\n * answer `Query.placement` gives, and the reason when it cannot.\n */\nexport type Placement =\n { readonly _tag: 'Placeable' } | { readonly _tag: 'NotPlaceable'; readonly reason: string }\n\nconst placeable: Placement = Object.freeze({ _tag: 'Placeable' })\nconst notPlaceable = (reason: string): Placement => Object.freeze({ _tag: 'NotPlaceable', reason })\n\n/**\n * Whether values encoded by `ast` order the same everywhere: numbers and\n * booleans, never text. A null among them does too: where it goes is said on\n * every order term.\n */\nconst ordersIntrinsically = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal !== 'string') ||\n (SchemaAST.isUnion(ast) &&\n ast.types.every(member => SchemaAST.isNull(member) || ordersIntrinsically(member)))\n\n/** Why a term cannot be placed by a client, if it cannot. */\nconst unplaceable = (orderTerm: OrderTerm): Option.Option<string> =>\n Match.value(orderTerm.expr).pipe(\n Match.tag('Field', field =>\n Option.match(orderTerm.collation, {\n onNone: () =>\n ordersIntrinsically(Schema.toEncoded(field.schema).ast)\n ? Option.none()\n : Option.some(\n `it orders by ${field.owner.name}.${field.key}, text with no declared collation`,\n ),\n onSome: collation =>\n Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.none<string>(),\n AsciiFold: () => Option.none<string>(),\n Locale: ({ locale }) =>\n Option.some(\n `it orders ${field.owner.name}.${field.key} by the backend's \"${locale}\" collation`,\n ),\n }),\n ),\n }),\n ),\n Match.orElse(() => Option.some('it orders by something that is not a field')),\n )\n\n/** Each Entity's id tie-break, made once, so a resolved order reuses one term. */\nconst idTerms = new WeakMap<AnyEntity, OrderTerm>()\nconst idTermOf = (entity: AnyEntity): OrderTerm => {\n const known = idTerms.get(entity)\n if (known !== undefined) return known\n const id = entity.fields.id\n if (id === undefined) {\n throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`)\n }\n const tieBreak = term('asc', fieldExpr(id))\n idTerms.set(entity, tieBreak)\n return tieBreak\n}\n\n/** The fixed term a chosen order is for one input, or none for a `null` sort. */\nconst chosenTerms = (\n chosen: ChosenOrder,\n input: Readonly<Record<string, unknown>>,\n): ReadonlyArray<OrderTerm> => {\n const sort = input[chosen.sort.key]\n if (sort === null || sort === undefined) return []\n const picked =\n typeof sort === 'object' && 'by' in sort && typeof sort.by === 'string' ? sort.by : undefined\n const direction = typeof sort === 'object' && 'direction' in sort ? sort.direction : undefined\n if (\n picked === undefined ||\n !Object.hasOwn(chosen.choices, picked) ||\n (direction !== 'asc' && direction !== 'desc')\n ) {\n throw new Error(\n `[foldkit-entity] Order.chosen: $${chosen.sort.key} names no order it offers (${Object.keys(chosen.choices).join(', ')})`,\n )\n }\n return [term(direction, chosen.choices[picked]!)]\n}\n\n/** What a walk has found, and the nodes it has already been through. */\ninterface Found {\n readonly seen: Set<object>\n /** By owner identity, then key: two Entities sharing a name are two entries. */\n readonly fields: Map<symbol, Map<string, FieldDependency>>\n readonly order: Array<FieldDependency>\n readonly inputs: Set<string>\n readonly operations: Set<Operation>\n}\n\n/**\n * Visits each node once. A node can be shared by several paths (`eq(n, n)`),\n * and a walk that followed every path would take time exponential in the depth.\n */\nconst walk = (expr: AnyExpr | Predicate | Ordering, found: Found): void => {\n if (found.seen.has(expr)) return\n found.seen.add(expr)\n switch (expr._tag) {\n case 'Literal':\n return\n case 'Field': {\n const byKey = found.fields.get(expr.owner.token) ?? new Map<string, FieldDependency>()\n found.fields.set(expr.owner.token, byKey)\n if (!byKey.has(expr.key)) {\n const field = { entity: expr.owner.name, key: expr.key, owner: expr.owner }\n byKey.set(expr.key, field)\n found.order.push(field)\n }\n return\n }\n case 'Input':\n found.inputs.add(expr.key)\n return\n case 'Eq':\n found.operations.add('eq')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Null':\n found.operations.add(expr.present ? 'isNotNull' : 'isNull')\n walk(expr.operand, found)\n return\n case 'Contains':\n found.operations.add('contains')\n walk(expr.value, found)\n walk(expr.search, found)\n return\n case 'In':\n found.operations.add('in')\n walk(expr.value, found)\n walk(expr.among, found)\n return\n case 'And':\n found.operations.add('and')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Or':\n found.operations.add('or')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Not':\n found.operations.add('not')\n walk(expr.operand, found)\n return\n case 'Compare':\n found.operations.add('compare')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Term':\n walk(expr.expr, found)\n return\n case 'Chosen':\n walk(expr.sort, found)\n for (const choice of Object.values(expr.choices)) walk(choice, found)\n return\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>\n): Dependencies => {\n const found: Found = {\n seen: new Set(),\n fields: new Map(),\n order: [],\n inputs: new Set(),\n operations: new Set(),\n }\n for (const term of nodes) walk(term, found)\n return { fields: found.order, inputs: [...found.inputs], operations: [...found.operations] }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<Ordering>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/** Every field an expression reads, as the nodes themselves, each node visited once. */\nconst fieldsIn = function* (\n expr: AnyExpr | Predicate | Ordering,\n seen: Set<object>,\n): Generator<FieldExpr<unknown>> {\n if (seen.has(expr)) return\n seen.add(expr)\n switch (expr._tag) {\n case 'Field':\n yield expr\n return\n case 'Literal':\n case 'Input':\n return\n case 'Eq':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Null':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Contains':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.search, seen)\n return\n case 'In':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.among, seen)\n return\n case 'And':\n case 'Or':\n for (const operand of expr.operands) yield* fieldsIn(operand, seen)\n return\n case 'Not':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Compare':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Term':\n yield* fieldsIn(expr.expr, seen)\n return\n case 'Chosen':\n for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen)\n return\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n): void => {\n const seen = new Set<object>()\n for (const term of nodes) {\n for (const field of fieldsIn(term, seen)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\n/**\n * The most nodes a query's predicates may hold once every shared node is\n * counted on each path that reaches it. Interpreters read a predicate as a\n * tree: `evaluate` once per row, and the SQL compiler into text that repeats a\n * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is\n * thirty-one objects and a billion nodes of work. Real queries are tens.\n */\nexport const maxQueryNodes = 1_000\n\nconst childrenOf = (expr: AnyExpr | Predicate): ReadonlyArray<AnyExpr | Predicate> => {\n switch (expr._tag) {\n case 'Literal':\n case 'Field':\n case 'Input':\n return []\n case 'Eq':\n return [expr.left, expr.right]\n case 'Null':\n return [expr.operand]\n case 'Contains':\n return [expr.value, expr.search]\n case 'In':\n return [expr.value, expr.among]\n case 'And':\n case 'Or':\n return expr.operands\n case 'Not':\n return [expr.operand]\n case 'Compare':\n return [expr.left, expr.right]\n }\n}\n\n/** A node's size as a tree, each distinct node sized once. */\nconst expandedSize = (expr: AnyExpr | Predicate, sizes: Map<object, number>): number => {\n const known = sizes.get(expr)\n if (known !== undefined) return known\n // Capped, so a graph deep enough to overflow a number still compares as too big.\n const size = Math.min(\n maxQueryNodes + 1,\n childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1),\n )\n sizes.set(expr, size)\n return size\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<Ordering>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n (...predicates: ReadonlyArray<Predicate>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n const where = [...self.where, ...predicates]\n const sizes = new Map<object, number>()\n const size = where.reduce((sum, predicate) => sum + expandedSize(predicate, sizes), 0)\n if (size > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Query.where: the predicates expand to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`,\n )\n }\n return query(self.entity, where, self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n (...terms: ReadonlyArray<Ordering>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n return query(self.entity, self.where, [...self.orderBy, ...terms])\n },\n\n /**\n * The fixed terms this query orders by for one input: each chosen order\n * resolved to the field its input names, or to nothing for a `null` sort,\n * and the Entity's id last, ascending, unless the terms already read it. So\n * the order is total, and every interpreter breaks ties the same way: one\n * that broke them its own way would place rows a step apart from another.\n */\n orderFor: (\n self: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n ): ReadonlyArray<OrderTerm> => {\n const terms = self.orderBy.flatMap(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => [term],\n Chosen: chosen => chosenTerms(chosen, input),\n }),\n ),\n )\n const id = idTermOf(self.entity)\n // Every field an order reads is this Entity's: `orderBy` refuses another's.\n const endsOnId = terms.some(term => term.expr._tag === 'Field' && term.expr.key === 'id')\n return endsOnId ? terms : [...terms, id]\n },\n\n /**\n * Whether a client can order this query's rows exactly as the server does,\n * for one input: every term over a number or a boolean (a row may lack it), or over text with a\n * portable collation (`binary`, `asciiFold`). A body that names no order\n * leaves it to the server, and is never placeable.\n */\n placement: (self: AnyQuery, input: Readonly<Record<string, unknown>>): Placement => {\n if (self.orderBy.length === 0) {\n return notPlaceable(\"its order is the server's: the body names none\")\n }\n for (const orderTerm of Query.orderFor(self, input)) {\n const reason = unplaceable(orderTerm)\n if (Option.isSome(reason)) return notPlaceable(reason.value)\n }\n return placeable\n },\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses, with the fields also\n * split by role.\n */\n dependencies: (self: AnyQuery): QueryDependencies => ({\n ...dependenciesOf(...self.where, ...self.orderBy),\n predicate: dependenciesOf(...self.where).fields,\n order: dependenciesOf(...self.orderBy).fields,\n }),\n\n /**\n * The operations this query needs that `supported` does not list, in the\n * order the query uses them. Empty means an interpreter declaring\n * `supported` can answer it.\n *\n * An interpreter declares what it runs and refuses the rest, rather than\n * ignoring an operation it does not implement — which would answer a\n * different question and say nothing. The refusal is the interpreter's to\n * raise: this only says what is missing, because what to do about it differs\n * between one that compiles at registration and one that runs a body\n * directly.\n *\n * ```ts\n * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])\n * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)\n * ```\n */\n unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>): ReadonlyArray<Operation> => {\n const runs = new Set(supported)\n return Query.dependencies(self).operations.filter(operation => !runs.has(operation))\n },\n\n /**\n * The whole query as readable text, one clause per line:\n *\n * ```text\n * FROM Post\n * WHERE Post.slug = $slug\n * AND Post.published = true\n * ORDER BY Post.updatedAt DESC\n * ```\n *\n * For an explanation or a diagnostic, never for an interpreter — see\n * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather\n * than printing an empty one, so what is shown is what was written.\n */\n show: (self: AnyQuery): string =>\n [\n `FROM ${self.entity.name}`,\n // Among several, an `or` is parenthesised: `WHERE a or b` over `AND c`\n // would read as `a or (b and c)`.\n ...self.where.map(\n (predicate, index) =>\n `${index === 0 ? 'WHERE' : ' AND'} ${Match.value(predicate).pipe(\n Match.tag('Or', or => (self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or))),\n Match.orElse(each => Expr.show(each)),\n )}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,\n Chosen: chosen =>\n `$${chosen.sort.key} among (${Object.entries(chosen.choices)\n .map(([name, field]) => `${name}: ${Expr.show(field)}`)\n .join(', ')})`,\n }),\n ),\n )\n .join(', ')}`,\n ]),\n ].join('\\n'),\n}\n\n/**\n * An expression as readable text, in the IR's own terms.\n *\n * This is for a human — an explanation, a diagnostic, a test that wants to\n * assert on a whole predicate at once — and deliberately **not** for an\n * interpreter. It is close enough to SQL to read at a glance and unlike it\n * everywhere that matters: an input is `$slug` rather than a bound parameter,\n * `contains` is named rather than rendered as somebody's `like`, and no\n * dialect's escaping or collation is implied. What actually ran is whatever\n * that backend compiled, which is not this.\n *\n * A predicate standing where a value is wanted is parenthesised, because\n * `x is not null = $archived` reads as three operands and is two. A predicate\n * that *is* the whole expression is not: nothing encloses it.\n */\nconst showExpr = (node: AnyExpr | Predicate): string => {\n switch (node._tag) {\n case 'Literal':\n return JSON.stringify(node.value) ?? String(node.value)\n case 'Field':\n return `${node.owner.name}.${node.key}`\n case 'Input':\n return `$${node.key}`\n case 'Eq':\n return `${showOperand(node.left)} = ${showOperand(node.right)}`\n case 'Null':\n return `${showOperand(node.operand)} is ${node.present ? 'not null' : 'null'}`\n case 'Contains':\n return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`\n case 'In':\n return `${showOperand(node.value)} in ${showOperand(node.among)}`\n case 'And':\n return node.operands.map(showConnected).join(' and ')\n case 'Or':\n return node.operands.map(showConnected).join(' or ')\n case 'Not':\n return `not (${showExpr(node.operand)})`\n case 'Compare':\n return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`\n }\n}\n\nconst symbols: Readonly<Record<CompareOperator, string>> = {\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n}\n\n/** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */\nconst showConnected = (node: Predicate): string =>\n Match.value(node).pipe(\n Match.tags({ And: () => `(${showExpr(node)})`, Or: () => `(${showExpr(node)})` }),\n Match.orElse(() => showExpr(node)),\n )\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\n","/**\n * The members a server filters an Entity's rows by under a rule the client\n * does not run, such as an authorization rule. A client that places rows in\n * a list judges membership by the list's body; a change to one of these\n * members can move a row into or out of what the server lists, which only\n * the server can say. Declared by whoever owns the rule (`foldkit-guard`\n * attaches it), read by whoever places (`foldkit-remote`).\n */\nimport { Metadata } from 'foldkit-metadata'\n\nconst key = Metadata.key<ReadonlyArray<string>>('foldkit-entity/read-filter', {\n // Every rule attached filters rows, so their members add up.\n merge: lists => [[...new Set(lists.flat())]],\n summarize: members => members.join(', '),\n})\n\nexport const ReadFilter = {\n /** Entity metadata: the rows the server lists depend on these members. */\n of: (members: ReadonlyArray<string>): Metadata => key.of(members),\n\n /** The members an Entity's metadata names, every attachment's together. */\n members: (metadata: Metadata): ReadonlyArray<string> => key.get(metadata)[0] ?? [],\n}\n","import { Option, Schema } from 'effect'\n\n/** What a schema says of itself to a person: its `title` and `description`. */\nexport interface SchemaWords {\n readonly title: Option.Option<string>\n readonly description: Option.Option<string>\n}\n\nconst text = (value: unknown): Option.Option<string> =>\n typeof value === 'string' ? Option.some(value) : Option.none()\n\nexport const Words = {\n /**\n * A schema's words, as a label and its help text. Under Effect 4 a checked\n * schema resolves to its last check's annotations, which say what the check\n * expects and carry no `title`, so a title given before the check is read from\n * the schema's own annotations. Read words through this, never through\n * `Schema.resolveAnnotations` directly.\n */\n of: (schema: Schema.Top): SchemaWords => {\n const resolved = Schema.resolveAnnotations(schema) ?? {}\n const own = schema.ast.annotations ?? {}\n return {\n title: Option.orElse(text(resolved.title), () => text(own['title'])),\n description: Option.orElse(text(resolved.description), () => text(own['description'])),\n }\n },\n}\n","/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Match, Option } from 'effect'\nimport type { Collation } from './collation.js'\nimport { Query, dependenciesOf, isPredicate } from './expr.js'\nimport type { AnyExpr, AnyQuery, Operandish, Operation, OrderTerm, Predicate } from './expr.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\nconst valueOf = (node: AnyExpr, row: Row, input: Row): unknown => {\n switch (node._tag) {\n case 'Field':\n return row[node.key]\n case 'Literal':\n return node.value\n case 'Input':\n return input[node.key]\n }\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\n/**\n * Lowercases ASCII letters and leaves every other character as it is, which is\n * what SQLite's `lower` does without ICU and so what the compiled SQL folds to.\n * `toLowerCase` would fold `É` to `é` here and not there.\n */\nconst foldAscii = (text: string): string => text.replace(/[A-Z]+/g, upper => upper.toLowerCase())\n\nconst NUL = String.fromCharCode(0)\n\n/**\n * Whether `value` is text holding a NUL, which Postgres text cannot hold and\n * SQLite compares only up to: no two interpreters agree on it.\n */\nconst holdsNul = (value: unknown): boolean => typeof value === 'string' && value.includes(NUL)\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, row: Row, input: Row): unknown =>\n isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input)\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Truth): unknown => (truth === 'unknown' ? null : truth)\n\nconst holds = (node: Predicate, row: Row, input: Row): Truth => {\n switch (node._tag) {\n case 'Eq': {\n const left = sideOf(node.left, row, input)\n const right = sideOf(node.right, row, input)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n if (isNull(left) || isNull(right)) return 'unknown'\n if (holdsNul(left) || holdsNul(right)) {\n throw new QueryEvaluateError(\n 'an equality was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n return left === right\n }\n case 'Null':\n // The one comparison that is never unknown: asking whether a value is\n // absent always has an answer.\n return isNull(valueOf(node.operand, row, input)) !== node.present\n case 'Contains': {\n const value = valueOf(node.value, row, input)\n const search = sideOf(node.search, row, input)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n if (isNull(value) || isNull(search)) return 'unknown'\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Postgres text cannot hold NUL and SQLite's `like` stops at it, so no\n // two interpreters agree on such a value: refused rather than answered.\n if (holdsNul(value) || holdsNul(search)) {\n throw new QueryEvaluateError(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n // Case-insensitive for ASCII letters only, because that is what\n // `Expr.contains` documents and what the compiled SQL folds both sides to.\n return foldAscii(value).includes(foldAscii(search))\n }\n case 'In': {\n const among = valueOf(node.among, row, input)\n if (!Array.isArray(among)) {\n throw new QueryEvaluateError('a membership test was given a list that is not a list')\n }\n // SQL's `in`: an empty list is false whatever the value, then a null\n // value is unknown, a match is true, and no match against a list\n // holding a null is unknown, since that null might have been it.\n if (among.length === 0) return false\n const value = valueOf(node.value, row, input)\n if (holdsNul(value) || among.some(holdsNul)) {\n throw new QueryEvaluateError(\n 'a membership test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n if (isNull(value)) return 'unknown'\n if (among.some(each => each === value)) return true\n return among.some(isNull) ? 'unknown' : false\n }\n // Every operand is asked, with no short cut: SQL fixes no order, so one\n // that refuses its value (a NUL) refuses here whichever operand decided.\n case 'And': {\n const truths = node.operands.map(operand => holds(operand, row, input))\n if (truths.includes(false)) return false\n return truths.includes('unknown') ? 'unknown' : true\n }\n case 'Or': {\n const truths = node.operands.map(operand => holds(operand, row, input))\n if (truths.includes(true)) return true\n return truths.includes('unknown') ? 'unknown' : false\n }\n case 'Not': {\n const truth = holds(node.operand, row, input)\n return truth === 'unknown' ? 'unknown' : !truth\n }\n case 'Compare': {\n const left = valueOf(node.left, row, input)\n const right = valueOf(node.right, row, input)\n if (isNull(left) || isNull(right)) return 'unknown'\n if (holdsNul(left) || holdsNul(right)) {\n throw new QueryEvaluateError(\n 'a comparison was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n // Numbers with numbers and text with text, as `orderBy` compares them,\n // so a comparison and an ordering never disagree about what is first.\n const kind = typeof left\n if (kind !== typeof right || (kind !== 'number' && kind !== 'string')) {\n throw new QueryEvaluateError('a comparison was given values that do not order together')\n }\n const order = compare(left, right, node.collation)\n return Match.value(node.operator).pipe(\n Match.when('lt', () => order < 0),\n Match.when('lte', () => order <= 0),\n Match.when('gt', () => order > 0),\n Match.when('gte', () => order >= 0),\n Match.exhaustive,\n )\n }\n }\n}\n\n/** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */\nexport type PredicateTruth = Truth\n\n/** Whether a predicate reads a field, asked once per node: nodes are frozen. */\nconst readsAField = new WeakMap<Predicate, boolean>()\n\n/**\n * A predicate's truth from the input alone, when it reads no field; none when\n * it reads one. An interpreter that runs per request decides such a predicate\n * before it builds anything: `isNull($status)` is known before any row is.\n * Refuses what `evaluate` refuses (text holding a NUL).\n */\nexport const decided = (node: Predicate, input: Row): Option.Option<PredicateTruth> => {\n let reads = readsAField.get(node)\n if (reads === undefined) {\n reads = dependenciesOf(node).fields.length > 0\n readsAField.set(node, reads)\n }\n return reads ? Option.none() : Option.some(holds(node, {}, input))\n}\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (body: AnyQuery, row: Row, input: Row): boolean =>\n body.where.every(node => holds(node, row, input) === true)\n\n/** The kinds of value this interpreter orders by; every key of one term must share one. */\nconst comparable = new Set(['string', 'number', 'boolean'])\n\n/**\n * Text by code point, as SQLite's `BINARY` and Postgres's `\"C\"` compare it.\n * JavaScript's `<` compares UTF-16 code units, which puts a character past\n * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where\n * every byte-ordered backend puts it after.\n */\nconst byCodePoint = (left: string, right: string): number => {\n let i = 0\n let j = 0\n while (i < left.length && j < right.length) {\n const a = left.codePointAt(i)!\n const b = right.codePointAt(j)!\n if (a !== b) return a < b ? -1 : 1\n i += a > 0xffff ? 2 : 1\n j += b > 0xffff ? 2 : 1\n }\n return i < left.length ? 1 : j < right.length ? -1 : 0\n}\n\n/** Two keys of one term, text by its collation (code point when none is declared). */\nconst compare = (left: unknown, right: unknown, collation: Option.Option<Collation>): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n const fold = Option.exists(collation, declared => declared._tag === 'AsciiFold')\n return fold ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right)\n }\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n return (left as number) - (right as number)\n}\n\n/**\n * Refuses an ordering this interpreter will not answer for, before sorting, so\n * the refusal names the first offending row in row order rather than whichever\n * pair the engine's sort happened to compare first. Every term is checked over\n * every row: a key whose kind differs from the first present one's. A null key\n * is not refused; the term says where it goes.\n */\nconst checkOrder = (rows: ReadonlyArray<Row>, terms: ReadonlyArray<OrderTerm>, query: string) => {\n for (const term of terms) {\n if (term.expr._tag !== 'Field') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is not a field, which this interpreter cannot run yet`,\n )\n }\n if (Option.exists(term.collation, declared => declared._tag === 'Locale')) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders \"${term.expr.key}\" by a backend's locale collation, which only that backend has`,\n )\n }\n const key = term.expr.key\n let first: string | undefined\n for (const row of rows) {\n const value = row[key]\n if (isNull(value)) continue\n const kind = typeof value\n first ??= kind\n if (kind !== first || !comparable.has(kind)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${first} and ${kind})`,\n )\n }\n }\n }\n}\n\n/** Two rows by checked terms: negative when `left` sorts first. */\nconst byTerms = (terms: ReadonlyArray<OrderTerm>, left: Row, right: Row): number => {\n for (const term of terms) {\n const key = (term.expr as Extract<OrderTerm['expr'], { readonly _tag: 'Field' }>).key\n const absentLeft = isNull(left[key])\n const absentRight = isNull(right[key])\n // Where a row without a value goes is the term's to say, whichever the\n // direction; two such rows tie, for the next term.\n if (absentLeft || absentRight) {\n if (absentLeft && absentRight) continue\n return absentLeft === (term.nulls === 'first') ? -1 : 1\n }\n const sign = compare(left[key], right[key], term.collation)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n}\n\nconst ordered = (rows: ReadonlyArray<Row>, terms: ReadonlyArray<OrderTerm>, query: string) => {\n // One row, or none, is in order whatever its keys hold.\n if (terms.length === 0 || rows.length < 2) return [...rows]\n checkOrder(rows, terms, query)\n return [...rows].sort((left, right) => byTerms(terms, left, right))\n}\n\n/**\n * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),\n * as `evaluate` sorts: negative when it comes first. Refuses what `evaluate`\n * refuses, for these two rows: a term not over a field, a locale collation,\n * or keys of different kinds. For a client placing one row among others it\n * holds.\n */\nexport const compareRows = (\n terms: ReadonlyArray<OrderTerm>,\n left: Row,\n right: Row,\n query: string,\n): number => {\n checkOrder([left, right], terms, query)\n return byTerms(terms, left, right)\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = [\n 'eq',\n 'isNull',\n 'isNotNull',\n 'contains',\n 'in',\n 'and',\n 'or',\n 'not',\n 'compare',\n]\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (body: AnyQuery): void => {\n const missing = Query.unsupported(body, supported)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n): ReadonlyArray<Row> => {\n assertSupported(body)\n return ordered(\n rows.filter(row => matches(body, row, input)),\n Query.orderFor(body, input),\n body.entity.name,\n )\n}\n","/**\n * A write as a value: what an operation changes, declared over the input it\n * takes, so the changes can be known before it runs and its interpreters can\n * agree on what it means.\n *\n * A `Write` is built on `Entity.input`, which already says which input key is\n * which member of the Entity. `Write.update`, `Write.insert` and `Write.delete`\n * add what to do with them: the key that names the row, and optionally the key\n * holding the revision it was read at. Every other key mapped to a field is\n * set; a key mapped to `Entity.unmapped` is about the operation and is not\n * written.\n *\n * It is authority someone declared, never something derived from an Entity: an\n * Entity having a field does not mean anyone may set it.\n */\nimport { Option, Schema, SchemaAST } from 'effect'\nimport type {\n AnyEntity,\n EntityField,\n EntityInput,\n EntityRef,\n EntityRelation,\n InputMember,\n} from './index.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/** One input key the write sets, and the field it sets. */\nexport interface WriteSet {\n readonly key: string\n readonly field: AnyField\n}\n\n/** One input key the write points at another row with: a `one` relation, by the target's id. */\nexport interface WriteLink {\n readonly key: string\n readonly relation: OneRelation\n}\n\n/**\n * One row of an Entity, by id, from an operation's input: updated, inserted\n * with an id the client chose, or deleted.\n */\nexport interface Write<E extends AnyEntity, Fields extends Schema.Struct.Fields> {\n readonly _tag: 'Update' | 'Insert' | 'Delete'\n readonly input: EntityInput<E, Fields, any>\n /** The input key holding the row's id, and the Entity's `id` field it is. */\n readonly id: WriteSet & { readonly key: keyof Fields & string }\n /**\n * The input key holding the revision the row was read at, and its field, when\n * the write is refused for a row that moved on since.\n */\n readonly expect: (WriteSet & { readonly key: keyof Fields & string }) | undefined\n /** The keys it sets, in the input's order. */\n readonly sets: ReadonlyArray<WriteSet>\n /** The `one` relations it points elsewhere, in the input's order. */\n readonly links: ReadonlyArray<WriteLink>\n}\n\nexport type AnyWrite = Write<AnyEntity, any>\n\n/** One row's new values, in the store's wire shape: what a client patches and a server writes. */\nexport interface BoundWrite {\n readonly entity: string\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n /**\n * Each `one` relation it points, by the relation's key: the row it points at,\n * or none for an optional relation set to nothing. How a ref is carried (a\n * key on the wire, a foreign key in a table) is each interpreter's.\n */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n}\n\nconst fail = (input: EntityInput<AnyEntity, any, any>, message: string): never => {\n throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`)\n}\n\nconst membersOf = (\n input: EntityInput<AnyEntity, any, any>,\n): Readonly<Record<string, InputMember | undefined>> => input.members\n\n/** A field's value as the store holds it. A field's schema needs no service, so none is asked. */\nconst encoded = (field: AnyField, value: unknown): unknown =>\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(value)\n\n/**\n * A key's value as given, when it was: an absent key, and an `Option` that\n * holds nothing, give none, and a `Some` what it holds. What `Entity.input`\n * lets a key map itself to, a write can bind.\n */\nconst given = (value: unknown): Option.Option<unknown> => {\n if (value === undefined) return Option.none()\n return Option.isOption(value) ? value : Option.some(value)\n}\n\nconst fieldAt = (input: EntityInput<AnyEntity, any, any>, key: string, role: string): AnyField => {\n const member = membersOf(input)[key]\n if (member === undefined) return fail(input, `${role} \"${key}\" is not a key of the input`)\n if (member._tag !== 'Field') return fail(input, `${role} \"${key}\" is not mapped to a field`)\n return member\n}\n\n/**\n * What every kind shares: the key naming the row, the expected revision, and\n * what the other keys set or point. A kind adds its own checks.\n */\nconst declared = <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n kind: Write<E, Fields>['_tag'],\n input: EntityInput<E, Fields, any>,\n options: { readonly id: keyof Fields & string; readonly expect?: keyof Fields & string },\n): Write<E, Fields> => {\n const id = fieldAt(input, options.id, 'id')\n if (id.key !== 'id') fail(input, `id \"${options.id}\" is mapped to \"${id.key}\", not to \"id\"`)\n const idSchema = input.schema.fields[options.id] as unknown as Schema.Top\n const takes = Schema.is(Schema.toType(idSchema) as Schema.Codec<unknown>)\n if (SchemaAST.isOptional(idSchema.ast) || takes(undefined) || takes(Option.none()))\n fail(input, `id \"${options.id}\" may be absent, and a declared write names its row`)\n if (options.expect === options.id) fail(input, 'expect cannot be the id')\n const expect =\n options.expect === undefined\n ? undefined\n : Object.freeze({ key: options.expect, field: fieldAt(input, options.expect, 'expect') })\n const sets: Array<WriteSet> = []\n const links: Array<WriteLink> = []\n for (const [key, member] of Object.entries(membersOf(input))) {\n if (member === undefined || key === options.id || key === options.expect) continue\n switch (member._tag) {\n case 'Field':\n sets.push(Object.freeze({ key, field: member }))\n break\n case 'Unmapped':\n break\n case 'RelationInput':\n if (member.relation.cardinality !== 'one') {\n fail(input, `\"${key}\" is a many relation; a write points one relation at a time`)\n }\n links.push(Object.freeze({ key, relation: member.relation as OneRelation }))\n break\n case 'NestedInput':\n fail(input, `\"${key}\" writes a nested row; a write writes its own row only`)\n }\n }\n return Object.freeze({\n _tag: kind,\n input,\n id: Object.freeze({ key: options.id, field: id }),\n expect,\n sets: Object.freeze(sets),\n links: Object.freeze(links),\n })\n}\n\n/** An update or an insert that would write nothing is refused where it is declared. */\nconst settingSomething = <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n write: Write<E, Fields>,\n): Write<E, Fields> =>\n write.sets.length === 0 && write.links.length === 0\n ? fail(write.input, 'it sets no field')\n : write\n\nexport const Write = {\n /**\n * Sets, on the row whose id is the input's `id` key, every field the input\n * maps a key to. `expect` names the key holding the revision the row was\n * read at: an interpreter writes only a row still at that revision.\n *\n * ```ts\n * const EditPost = Write.update(EditPostInput, { id: 'id' })\n * ```\n *\n * A key mapped to a `one` relation (`Relation.input`) points the row at the\n * id it holds. Refused where it is written: an `id` that is not the Entity's\n * `id` field, a `many` relation or a nested key (not written by an update\n * yet), or nothing to set.\n */\n update: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: {\n readonly id: keyof Fields & string\n readonly expect?: keyof Fields & string\n },\n ): Write<E, Fields> => {\n return settingSomething(declared('Update', input, options))\n },\n\n /**\n * Inserts the row whose id is the input's `id` key, an id the client chose,\n * with every field and `one` relation the input maps a key to. An insert\n * expects no revision: there is no row to have read. A row already there\n * under that id (a retry) is left as it is.\n */\n insert: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: { readonly id: keyof Fields & string },\n ): Write<E, Fields> => {\n return settingSomething(declared('Insert', input, options))\n },\n\n /**\n * Deletes the row whose id is the input's `id` key, only while it is still at\n * the revision `expect` names, when it names one. It sets nothing, so a key\n * mapped to a member is refused where it is written. A row already gone (a\n * retry) is gone.\n */\n delete: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: {\n readonly id: keyof Fields & string\n readonly expect?: keyof Fields & string\n },\n ): Write<E, Fields> => {\n const write = declared('Delete', input, options)\n const named = [...write.sets, ...write.links][0]\n if (named !== undefined) fail(input, `a delete sets nothing, but \"${named.key}\" is mapped`)\n return write\n },\n\n /**\n * The revision this input says the row was read at, encoded, with its field:\n * what an interpreter writes only a row still at. None for a write that\n * expects none.\n */\n expected: <Fields extends Schema.Struct.Fields>(\n write: Write<AnyEntity, Fields>,\n value: Schema.Struct.Type<Fields>,\n ): Option.Option<{ readonly field: string; readonly revision: unknown }> =>\n Option.map(Option.fromUndefinedOr(write.expect), ({ key, field }) => ({\n field: field.key,\n revision: encoded(field, (value as Readonly<Record<string, unknown>>)[key]),\n })),\n\n /** The members any invocation may write: what a query reading none of them cannot be changed by. */\n writes: (write: AnyWrite): ReadonlyArray<AnyField | OneRelation> => [\n ...write.sets.map(set => set.field),\n ...write.links.map(link => link.relation),\n ],\n\n /**\n * The row this input writes and its new values, encoded as the store holds\n * them: the patch a client shows before the server answers. `keys`, when\n * given, narrows it to those input keys (what an author changed); the rest of\n * the input is still the whole, validated value.\n */\n bind: <Fields extends Schema.Struct.Fields>(\n write: Write<AnyEntity, Fields>,\n value: Schema.Struct.Type<Fields>,\n keys?: ReadonlyArray<string>,\n ): BoundWrite => {\n const input = value as Readonly<Record<string, unknown>>\n const wanted = keys === undefined ? undefined : new Set(keys)\n const asked = (key: string) => wanted === undefined || wanted.has(key)\n const values: Record<string, unknown> = {}\n for (const { key, field } of write.sets) {\n if (!asked(key)) continue\n // A key the input leaves out, or an `Option` holding nothing, writes nothing.\n Option.map(given(input[key]), held => {\n values[field.key] = encoded(field, held)\n })\n }\n const links: Record<string, Option.Option<EntityRef>> = {}\n for (const { key, relation } of write.links) {\n if (!asked(key)) continue\n const target = relation.target()\n links[relation.key] = Option.map(\n Option.flatMap(given(input[key]), Option.fromNullishOr),\n id => ({ entity: target.name, id: String(encoded(target.fields.id as AnyField, id)) }),\n )\n }\n return {\n entity: write.input.entity.name,\n id: String(encoded(write.id.field, input[write.id.key])),\n values,\n links,\n }\n },\n}\n","/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { type Option, Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport { SchemaShape } from './shape.js'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\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\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\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\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\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\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 ? | 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 ? 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> | 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 SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[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\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/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** 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/** 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 * Whether an input value fits a field. Only the value that is present has to\n * fit: an input may leave a key out (a partial update), send `null` to clear\n * it, or hold an `Option` (an id absent for something new), whose value fits as\n * it is (an `Option` field) or as what it holds. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Fits<Input, Field> = [Present<Input>] extends [Field]\n ? true\n : [Held<Input>] extends [Field]\n ? true\n : false\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Fits<Input, Schema.Schema.Type<S>> extends true\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Fits<Schema.Schema.Type<Fields[K]>, Schema.Schema.Type<E['fields'][K]['schema']>> extends true\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype 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/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\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\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\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\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n 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 relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\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 */\n 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 (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = 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 metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\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 */\n 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 = 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))\n 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: Schema.Struct(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 */\n 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 /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /** Attaches an interpreter's metadata to members, by key. */\n 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 annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) 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 */\n 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 (!(key in schema.fields))\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 given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\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 */\n fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(\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 (\n entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint> | undefined>\n >\n )[key] ?? 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 */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n > => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec 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 */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n switch (member._tag) {\n case 'Field':\n return [[key, read] as const]\n case 'NestedInput': {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? Entity.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\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n\nexport * from './expr.js'\nexport * from './collation.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport { Write, type AnyWrite, type BoundWrite, type WriteLink, type WriteSet } from './write.js'\n"],"mappings":";;;AAEA,MAAM,aAAa,QACjB,UAAU,OAAO,GAAG,KAAK,UAAU,YAAY,GAAG;AAEpD,MAAM,UAAU,QACd,UAAU,SAAS,GAAG,KACtB,UAAU,kBAAkB,GAAG,KAC9B,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YAAY,YACnD,UAAU,QAAQ,GAAG,KAAK,IAAI,MAAM,SAAS,KAAK,IAAI,MAAM,MAAM,MAAM;;AAG3E,MAAa,cAAc;;CAEzB;;;;;CAMA,UAAU,QACR,UAAU,QAAQ,GAAG,IAAI,IAAI,MAAM,QAAO,WAAU,CAAC,UAAU,MAAM,CAAC,IAAI,CAAC,GAAG;;CAGhF;AACF;;;;;;;;;;;;;;;ACFA,MAAMA,QAAM,SAAS,IAAe,4BAA4B;CAE9D,QAAO,eAAc,WAAW,MAAM,EAAE;CACxC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAGD,MAAM,aAAa;AAEnB,MAAa,YAAY;CACvB,QAAQ,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;CACxC,WAAW,OAAO,OAAO,EAAE,MAAM,YAAY,CAAC;CAC9C,SAAS,WAA8B;EACrC,IAAI,CAAC,WAAW,KAAK,MAAM,GACzB,MAAM,IAAI,MAAM,uCAAuC,OAAO,0BAA0B;EAE1F,OAAO,OAAO,OAAO;GAAE,MAAM;GAAU;EAAO,CAAC;CACjD;;CAGA,KAAK,cAAmCA,MAAI,GAAG,SAAS;;CAGxD,WAAW,aACT,OAAO,gBAAgB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