foldkit-entity 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -417,7 +417,14 @@ placeholder instead of a branch around it.
417
417
 
418
418
  `dependenciesOf(...)` says which fields and inputs an expression reads and which
419
419
  operations it uses, so a planner knows what it needs and an interpreter can
420
- refuse a query it cannot run.
420
+ refuse a query it cannot run. Each field names its `owner`, the Entity's
421
+ identity, as well as the Entity's name, so two Entities defined with the same
422
+ name are two entries.
423
+
424
+ Every node is frozen as it is built, so a query is the value it was when
425
+ `Query.where` checked it: nothing can swap a field or a literal in afterwards.
426
+ A node may be shared, `Expr.eq(n, n)`, and every walk over one visits each
427
+ node once, so a deeply shared predicate costs its size, not its paths.
421
428
 
422
429
  ### Asking a question that depends on an input, without branching on it
423
430
 
@@ -443,7 +450,10 @@ flipped, so nothing has to negate a predicate to get the other.
443
450
  **`contains` is case-insensitive**, which is what a search means — and which
444
451
  has to be said, not left to the interpreter: SQLite's `like` ignores case and
445
452
  Postgres's does not, so a body that left it open would mean two things. Folding
446
- is ASCII-only, since that is what `lower` does in SQLite without ICU.
453
+ is ASCII-only, since that is what `lower` does in SQLite without ICU: `É` does
454
+ not match `é`, though each matches itself. Text holding a NUL character is
455
+ refused by every interpreter here, since Postgres text cannot hold one and
456
+ SQLite's `like` stops at it.
447
457
 
448
458
  **It searches text, and the operand is constrained to text.** `contains` over a
449
459
  number would compile to `lower(rank) like …`, which SQLite coerces into an
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/conformance/index.ts"],"mappings":";;;;qBA4Ca,SAAO;;;;;;;;;;;;;;;iBAmBH;WACN;WACA;WACA;WACA;;WAEA;YACC;;qBAGC,MAAM,cAAc;iBAQhB;;WAEN;WACA,MAAM;;;;;;;WAON,OAAO,SAAS;;WAEhB,UAAU;;qBAUR,OAAO,cAAc"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/conformance/index.ts"],"mappings":";;;;qBA4Ca,SAAO;;;;;;;;;;;;;;;iBAmBH;WACN;WACA;WACA;WACA;;WAEA;YACC;;qBAGC,MAAM,cAAc;iBAQhB;;WAEN;WACA,MAAM;;;;;;;WAON,OAAO,SAAS;;WAEhB,UAAU;;qBAWR,OAAO,cAAc"}
@@ -89,6 +89,7 @@ const rows = [
89
89
  const from = Query.from(Subject);
90
90
  const byId = Query.orderBy(Order.asc(Subject.fields.id));
91
91
  const label = Expr.input("label", Schema.String);
92
+ const text = Expr.input("text", Schema.String);
92
93
  const tag = Expr.input("tag", Schema.String);
93
94
  const present = Expr.input("present", Schema.Boolean);
94
95
  const at = Expr.input("at", Timestamp);
@@ -220,6 +221,30 @@ const cases = [
220
221
  "e"
221
222
  ]
222
223
  },
224
+ {
225
+ what: "contains folds ASCII letters only: an accented capital does not match its lowercase",
226
+ body: from.pipe(Query.where(Expr.contains(text, label)), byId),
227
+ input: {
228
+ text: "Élan",
229
+ label: "é"
230
+ },
231
+ expected: []
232
+ },
233
+ {
234
+ what: "contains still matches a non-ASCII letter written the same way",
235
+ body: from.pipe(Query.where(Expr.contains(text, label)), byId),
236
+ input: {
237
+ text: "Élan",
238
+ label: "Él"
239
+ },
240
+ expected: [
241
+ "a",
242
+ "b",
243
+ "c",
244
+ "d",
245
+ "e"
246
+ ]
247
+ },
223
248
  {
224
249
  what: "contains with a null search is unknown for every row",
225
250
  body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/conformance/index.ts"],"sourcesContent":["/**\n * The conformance suite for a query body: what\n * [data-query-DESIGN §6.0.1](../../../docs/design/data-query-DESIGN.md) says\n * each operator means, as cases an interpreter can be run against.\n *\n * Exported rather than kept in this repository's tests, because the interpreter\n * most worth checking against it is one written elsewhere: run every case\n * through yours and compare the ids, in order, against `expected`.\n *\n * §18 names portable-kernel conformance as what the reference interpreter is\n * for. This is that, extracted: one set of cases, run against every interpreter\n * rather than each interpreter having its own tests that happen to agree.\n * `foldkit-remote-server` runs them over rows in memory;\n * `foldkit-remote-drizzle` compiles them to SQL and runs them against a real\n * SQLite. A body that means two things fails in whichever is wrong.\n *\n * The cases are chosen to make interpreters *disagree*, which is the only kind\n * that tests anything. A fixture whose values are all lowercase cannot tell a\n * case-sensitive `contains` from a case-insensitive one — that is not a\n * hypothetical, it is how `contains` reached a released package meaning three\n * different things.\n */\nimport { Schema, SchemaGetter } from 'effect'\nimport { Entity, Expr, Order, Query, type AnyQuery } from '../index.js'\n\n/**\n * A `Date` on the way in, an ISO string on the wire — the one fixture whose\n * **encoded form differs from its decoded form**.\n *\n * Every other column here encodes to itself, which is why the suite could not\n * previously see an interpreter comparing a decoded value against an encoded\n * row. That is not a hypothetical bug: a store holds wire values and decodes at\n * read, while a `QueryRef`'s input and a body's literals are written in domain\n * terms, so anything that runs a body over stored rows has to reconcile the two\n * and nothing was checking that it did.\n */\nconst Timestamp = Schema.Date.pipe(\n Schema.encodeTo(Schema.String, {\n decode: SchemaGetter.transform((iso: string) => new Date(iso)),\n encode: SchemaGetter.transform((at: Date) => at.toISOString()),\n }),\n)\n\n/** The one Entity every case reads, with a column of each kind that matters. */\nexport const Subject = Entity.define(\n 'Subject',\n Schema.Struct({\n id: Schema.String,\n /** Mixed case on purpose: a case-blind `contains` must be caught. */\n label: Schema.String,\n rank: Schema.Number,\n /** Nullable on purpose: three-valued logic has to be exercised. */\n tag: Schema.String,\n /** Encoded and decoded forms differ on purpose: see `Timestamp`. */\n at: Timestamp,\n }),\n)\n\n/**\n * How a row looks to an interpreter reading values, and to SQL as a table. The\n * index signature is what lets one be read by key without a cast, which is how\n * an interpreter over plain rows reads one.\n */\nexport interface ConformanceRow {\n readonly id: string\n readonly label: string\n readonly rank: number\n readonly tag: string | null\n /** The **encoded** form: what a store holds and an interpreter compares. */\n readonly at: string\n readonly [key: string]: unknown\n}\n\nexport const rows: ReadonlyArray<ConformanceRow> = [\n { id: 'a', label: 'Intro', rank: 2, tag: null, at: '2026-01-01T00:00:00.000Z' },\n { id: 'b', label: 'intro to sql', rank: 1, tag: 'x', at: '2026-01-02T00:00:00.000Z' },\n { id: 'c', label: 'Other', rank: 3, tag: null, at: '2026-01-02T00:00:00.000Z' },\n { id: 'd', label: '100% cotton', rank: 3, tag: 'x', at: '2026-01-03T00:00:00.000Z' },\n { id: 'e', label: 'snake_case', rank: 4, tag: 'y', at: '2026-01-04T00:00:00.000Z' },\n]\n\nexport interface ConformanceCase {\n /** What the case pins, as a sentence an interpreter fails by name. */\n readonly what: string\n readonly body: AnyQuery\n /**\n * The inputs, **encoded** — the space a store's rows are in, not the domain\n * space the body's types describe. For every column but `at` the two are the\n * same value, which is exactly why this has to be said rather than inferred\n * from the fixtures.\n */\n readonly input: Readonly<Record<string, unknown>>\n /** The ids the body matches, in the order it asks for. */\n readonly expected: ReadonlyArray<string>\n}\n\nconst from = Query.from(Subject)\nconst byId = Query.orderBy(Order.asc(Subject.fields.id))\nconst label = Expr.input('label', Schema.String)\nconst tag = Expr.input('tag', Schema.String)\nconst present = Expr.input('present', Schema.Boolean)\nconst at = Expr.input('at', Timestamp)\n\nexport const cases: ReadonlyArray<ConformanceCase> = [\n // ---- eq ------------------------------------------------------------------\n {\n what: 'eq matches a field against a literal',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.rank, 3)), byId),\n input: {},\n expected: ['c', 'd'],\n },\n {\n what: 'eq matches a field against the value the request supplies',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.label, label)), byId),\n input: { label: 'Other' },\n expected: ['c'],\n },\n {\n what: 'eq is exact: a value that differs only by case does not match',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.label, label)), byId),\n input: { label: 'other' },\n expected: [],\n },\n {\n what: 'eq against null matches nothing, not even the rows that are null',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.tag, tag)), byId),\n input: { tag: null },\n expected: [],\n },\n {\n what: 'eq against a value skips the rows whose column is null',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.tag, 'x')), byId),\n input: {},\n expected: ['b', 'd'],\n },\n\n // ---- isNull / isNotNull --------------------------------------------------\n {\n what: 'isNull finds exactly the rows with no value',\n body: from.pipe(Query.where(Expr.isNull(Subject.fields.tag)), byId),\n input: {},\n expected: ['a', 'c'],\n },\n {\n what: 'isNotNull finds exactly the rest',\n body: from.pipe(Query.where(Expr.isNotNull(Subject.fields.tag)), byId),\n input: {},\n expected: ['b', 'd', 'e'],\n },\n {\n what: 'a predicate compared to a true input is that predicate',\n body: from.pipe(Query.where(Expr.eq(Expr.isNotNull(Subject.fields.tag), present)), byId),\n input: { present: true },\n expected: ['b', 'd', 'e'],\n },\n {\n what: 'a predicate compared to a false input is its negation',\n body: from.pipe(Query.where(Expr.eq(Expr.isNotNull(Subject.fields.tag), present)), byId),\n input: { present: false },\n expected: ['a', 'c'],\n },\n ...[true, false].map(value => ({\n what: `a ${value} input compared to a predicate works in reverse order`,\n body: from.pipe(Query.where(Expr.eq(present, Expr.isNotNull(Subject.fields.tag))), byId),\n input: { present: value },\n expected: value ? ['b', 'd', 'e'] : ['a', 'c'],\n })),\n ...[true, false].map(value => ({\n what: `an unknown equality compared to ${value} stays unknown`,\n body: from.pipe(Query.where(Expr.eq(Expr.eq(Subject.fields.tag, tag), present)), byId),\n input: { tag: null, present: value },\n expected: [],\n })),\n\n // ---- contains ------------------------------------------------------------\n {\n what: 'contains ignores case, which is stated rather than left to the backend',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: 'INTRO' },\n expected: ['a', 'b'],\n },\n {\n what: 'contains matches anywhere in the value, not only at the start',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: 'to sql' },\n expected: ['b'],\n },\n {\n what: 'containing the empty string is everything',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '' },\n expected: ['a', 'b', 'c', 'd', 'e'],\n },\n {\n what: 'a percent is searched for literally, not as a wildcard',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '%' },\n expected: ['d'],\n },\n {\n what: 'an underscore is searched for literally, not as a single-character wildcard',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '_' },\n expected: ['e'],\n },\n {\n what: 'contains over a null column drops those rows, so it is not the same as no filter',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.tag, label)), byId),\n input: { label: '' },\n expected: ['b', 'd', 'e'],\n },\n {\n what: 'contains with a null search is unknown for every row',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: null },\n expected: [],\n },\n {\n what: 'an unknown containment compared to false stays unknown',\n body: from.pipe(Query.where(Expr.eq(Expr.contains(Subject.fields.label, label), false)), byId),\n input: { label: null },\n expected: [],\n },\n\n // ---- conjunction, which is the list rather than an operator ---------------\n {\n what: 'two predicates conjoin: every one must hold',\n body: from.pipe(\n Query.where(Expr.eq(Subject.fields.rank, 3), Expr.isNotNull(Subject.fields.tag)),\n byId,\n ),\n input: {},\n expected: ['d'],\n },\n {\n what: 'no predicate at all is every row',\n body: from.pipe(byId),\n input: {},\n expected: ['a', 'b', 'c', 'd', 'e'],\n },\n\n // ---- encoded values ------------------------------------------------------\n // The body's types say `Date`; a store's rows and a request's inputs are ISO\n // strings. An interpreter compares in the **encoded** space, and these are the\n // cases that say so — for every other column the two spaces hold the same\n // value, so nothing here could previously tell them apart.\n //\n // What happens when a caller passes a *decoded* value is deliberately not a\n // case, because the interpreters do not agree: the reference one matches\n // nothing, SQLite raises `datatype mismatch`, and a local engine does\n // whatever its own comparison does. `cases` are what interpreters must agree\n // about. The consequence is pinned in `packages/entity/test/encoding.test.ts`\n // instead, and it is the one that matters: **a runtime error cannot be relied\n // on to catch the mistake**, because one of the three answers is an empty\n // result that reads exactly like a correct one.\n {\n what: 'an input whose encoded form differs from its decoded one matches on the encoded one',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.at, at)), byId),\n input: { at: '2026-01-02T00:00:00.000Z' },\n expected: ['b', 'c'],\n },\n {\n what: 'a literal is encoded too, or it has the same problem as an input',\n body: from.pipe(\n Query.where(Expr.eq(Subject.fields.at, '2026-01-03T00:00:00.000Z' as never)),\n byId,\n ),\n input: {},\n expected: ['d'],\n },\n\n // ---- ordering ------------------------------------------------------------\n {\n what: 'orders ascending by a number',\n body: from.pipe(Query.orderBy(Order.asc(Subject.fields.rank), Order.asc(Subject.fields.id))),\n input: {},\n expected: ['b', 'a', 'c', 'd', 'e'],\n },\n {\n what: 'orders descending, and a later term breaks the tie',\n body: from.pipe(Query.orderBy(Order.desc(Subject.fields.rank), Order.asc(Subject.fields.id))),\n input: {},\n expected: ['e', 'c', 'd', 'a', 'b'],\n },\n // Ordering by text is deliberately not here. How text compares is the\n // backend's — SQLite by code point, TanStack by locale, Postgres by whatever\n // the database was created with — and §6.0.1 puts it outside the conformant\n // subset rather than pretending one of them is the rule. A case asserting an\n // order would only pin whichever engine was written first.\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,YAAY,OAAO,KAAK,KAC5B,OAAO,SAAS,OAAO,QAAQ;CAC7B,QAAQ,aAAa,WAAW,QAAgB,IAAI,KAAK,GAAG,CAAC;CAC7D,QAAQ,aAAa,WAAW,OAAa,GAAG,YAAY,CAAC;AAC/D,CAAC,CACH;;AAGA,MAAa,UAAU,OAAO,OAC5B,WACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,OAAO,OAAO;CACd,MAAM,OAAO;;CAEb,KAAK,OAAO;;CAEZ,IAAI;AACN,CAAC,CACH;AAiBA,MAAa,OAAsC;CACjD;EAAE,IAAI;EAAK,OAAO;EAAS,MAAM;EAAG,KAAK;EAAM,IAAI;CAA2B;CAC9E;EAAE,IAAI;EAAK,OAAO;EAAgB,MAAM;EAAG,KAAK;EAAK,IAAI;CAA2B;CACpF;EAAE,IAAI;EA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AI,QAAQ,OAAO,EAAE,CAAC,CAAC;EAC5F,OAAO,CAAC;EACR,UAAU;GAAC;GAAK;GAAK;GAAK;GAAK;EAAG;CACpC;AAMF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/conformance/index.ts"],"sourcesContent":["/**\n * The conformance suite for a query body: what\n * [data-query-DESIGN §6.0.1](../../../docs/design/data-query-DESIGN.md) says\n * each operator means, as cases an interpreter can be run against.\n *\n * Exported rather than kept in this repository's tests, because the interpreter\n * most worth checking against it is one written elsewhere: run every case\n * through yours and compare the ids, in order, against `expected`.\n *\n * §18 names portable-kernel conformance as what the reference interpreter is\n * for. This is that, extracted: one set of cases, run against every interpreter\n * rather than each interpreter having its own tests that happen to agree.\n * `foldkit-remote-server` runs them over rows in memory;\n * `foldkit-remote-drizzle` compiles them to SQL and runs them against a real\n * SQLite. A body that means two things fails in whichever is wrong.\n *\n * The cases are chosen to make interpreters *disagree*, which is the only kind\n * that tests anything. A fixture whose values are all lowercase cannot tell a\n * case-sensitive `contains` from a case-insensitive one — that is not a\n * hypothetical, it is how `contains` reached a released package meaning three\n * different things.\n */\nimport { Schema, SchemaGetter } from 'effect'\nimport { Entity, Expr, Order, Query, type AnyQuery } from '../index.js'\n\n/**\n * A `Date` on the way in, an ISO string on the wire — the one fixture whose\n * **encoded form differs from its decoded form**.\n *\n * Every other column here encodes to itself, which is why the suite could not\n * previously see an interpreter comparing a decoded value against an encoded\n * row. That is not a hypothetical bug: a store holds wire values and decodes at\n * read, while a `QueryRef`'s input and a body's literals are written in domain\n * terms, so anything that runs a body over stored rows has to reconcile the two\n * and nothing was checking that it did.\n */\nconst Timestamp = Schema.Date.pipe(\n Schema.encodeTo(Schema.String, {\n decode: SchemaGetter.transform((iso: string) => new Date(iso)),\n encode: SchemaGetter.transform((at: Date) => at.toISOString()),\n }),\n)\n\n/** The one Entity every case reads, with a column of each kind that matters. */\nexport const Subject = Entity.define(\n 'Subject',\n Schema.Struct({\n id: Schema.String,\n /** Mixed case on purpose: a case-blind `contains` must be caught. */\n label: Schema.String,\n rank: Schema.Number,\n /** Nullable on purpose: three-valued logic has to be exercised. */\n tag: Schema.String,\n /** Encoded and decoded forms differ on purpose: see `Timestamp`. */\n at: Timestamp,\n }),\n)\n\n/**\n * How a row looks to an interpreter reading values, and to SQL as a table. The\n * index signature is what lets one be read by key without a cast, which is how\n * an interpreter over plain rows reads one.\n */\nexport interface ConformanceRow {\n readonly id: string\n readonly label: string\n readonly rank: number\n readonly tag: string | null\n /** The **encoded** form: what a store holds and an interpreter compares. */\n readonly at: string\n readonly [key: string]: unknown\n}\n\nexport const rows: ReadonlyArray<ConformanceRow> = [\n { id: 'a', label: 'Intro', rank: 2, tag: null, at: '2026-01-01T00:00:00.000Z' },\n { id: 'b', label: 'intro to sql', rank: 1, tag: 'x', at: '2026-01-02T00:00:00.000Z' },\n { id: 'c', label: 'Other', rank: 3, tag: null, at: '2026-01-02T00:00:00.000Z' },\n { id: 'd', label: '100% cotton', rank: 3, tag: 'x', at: '2026-01-03T00:00:00.000Z' },\n { id: 'e', label: 'snake_case', rank: 4, tag: 'y', at: '2026-01-04T00:00:00.000Z' },\n]\n\nexport interface ConformanceCase {\n /** What the case pins, as a sentence an interpreter fails by name. */\n readonly what: string\n readonly body: AnyQuery\n /**\n * The inputs, **encoded** — the space a store's rows are in, not the domain\n * space the body's types describe. For every column but `at` the two are the\n * same value, which is exactly why this has to be said rather than inferred\n * from the fixtures.\n */\n readonly input: Readonly<Record<string, unknown>>\n /** The ids the body matches, in the order it asks for. */\n readonly expected: ReadonlyArray<string>\n}\n\nconst from = Query.from(Subject)\nconst byId = Query.orderBy(Order.asc(Subject.fields.id))\nconst label = Expr.input('label', Schema.String)\nconst text = Expr.input('text', Schema.String)\nconst tag = Expr.input('tag', Schema.String)\nconst present = Expr.input('present', Schema.Boolean)\nconst at = Expr.input('at', Timestamp)\n\nexport const cases: ReadonlyArray<ConformanceCase> = [\n // ---- eq ------------------------------------------------------------------\n {\n what: 'eq matches a field against a literal',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.rank, 3)), byId),\n input: {},\n expected: ['c', 'd'],\n },\n {\n what: 'eq matches a field against the value the request supplies',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.label, label)), byId),\n input: { label: 'Other' },\n expected: ['c'],\n },\n {\n what: 'eq is exact: a value that differs only by case does not match',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.label, label)), byId),\n input: { label: 'other' },\n expected: [],\n },\n {\n what: 'eq against null matches nothing, not even the rows that are null',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.tag, tag)), byId),\n input: { tag: null },\n expected: [],\n },\n {\n what: 'eq against a value skips the rows whose column is null',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.tag, 'x')), byId),\n input: {},\n expected: ['b', 'd'],\n },\n\n // ---- isNull / isNotNull --------------------------------------------------\n {\n what: 'isNull finds exactly the rows with no value',\n body: from.pipe(Query.where(Expr.isNull(Subject.fields.tag)), byId),\n input: {},\n expected: ['a', 'c'],\n },\n {\n what: 'isNotNull finds exactly the rest',\n body: from.pipe(Query.where(Expr.isNotNull(Subject.fields.tag)), byId),\n input: {},\n expected: ['b', 'd', 'e'],\n },\n {\n what: 'a predicate compared to a true input is that predicate',\n body: from.pipe(Query.where(Expr.eq(Expr.isNotNull(Subject.fields.tag), present)), byId),\n input: { present: true },\n expected: ['b', 'd', 'e'],\n },\n {\n what: 'a predicate compared to a false input is its negation',\n body: from.pipe(Query.where(Expr.eq(Expr.isNotNull(Subject.fields.tag), present)), byId),\n input: { present: false },\n expected: ['a', 'c'],\n },\n ...[true, false].map(value => ({\n what: `a ${value} input compared to a predicate works in reverse order`,\n body: from.pipe(Query.where(Expr.eq(present, Expr.isNotNull(Subject.fields.tag))), byId),\n input: { present: value },\n expected: value ? ['b', 'd', 'e'] : ['a', 'c'],\n })),\n ...[true, false].map(value => ({\n what: `an unknown equality compared to ${value} stays unknown`,\n body: from.pipe(Query.where(Expr.eq(Expr.eq(Subject.fields.tag, tag), present)), byId),\n input: { tag: null, present: value },\n expected: [],\n })),\n\n // ---- contains ------------------------------------------------------------\n {\n what: 'contains ignores case, which is stated rather than left to the backend',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: 'INTRO' },\n expected: ['a', 'b'],\n },\n {\n what: 'contains matches anywhere in the value, not only at the start',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: 'to sql' },\n expected: ['b'],\n },\n {\n what: 'containing the empty string is everything',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '' },\n expected: ['a', 'b', 'c', 'd', 'e'],\n },\n {\n what: 'a percent is searched for literally, not as a wildcard',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '%' },\n expected: ['d'],\n },\n {\n what: 'an underscore is searched for literally, not as a single-character wildcard',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: '_' },\n expected: ['e'],\n },\n {\n what: 'contains over a null column drops those rows, so it is not the same as no filter',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.tag, label)), byId),\n input: { label: '' },\n expected: ['b', 'd', 'e'],\n },\n // The text searched is an input here so the fixture rows stay ASCII: each\n // case asks the same of every row, so it matches all of them or none.\n {\n what: 'contains folds ASCII letters only: an accented capital does not match its lowercase',\n body: from.pipe(Query.where(Expr.contains(text, label)), byId),\n input: { text: 'Élan', label: 'é' },\n expected: [],\n },\n {\n what: 'contains still matches a non-ASCII letter written the same way',\n body: from.pipe(Query.where(Expr.contains(text, label)), byId),\n input: { text: 'Élan', label: 'Él' },\n expected: ['a', 'b', 'c', 'd', 'e'],\n },\n {\n what: 'contains with a null search is unknown for every row',\n body: from.pipe(Query.where(Expr.contains(Subject.fields.label, label)), byId),\n input: { label: null },\n expected: [],\n },\n {\n what: 'an unknown containment compared to false stays unknown',\n body: from.pipe(Query.where(Expr.eq(Expr.contains(Subject.fields.label, label), false)), byId),\n input: { label: null },\n expected: [],\n },\n\n // ---- conjunction, which is the list rather than an operator ---------------\n {\n what: 'two predicates conjoin: every one must hold',\n body: from.pipe(\n Query.where(Expr.eq(Subject.fields.rank, 3), Expr.isNotNull(Subject.fields.tag)),\n byId,\n ),\n input: {},\n expected: ['d'],\n },\n {\n what: 'no predicate at all is every row',\n body: from.pipe(byId),\n input: {},\n expected: ['a', 'b', 'c', 'd', 'e'],\n },\n\n // ---- encoded values ------------------------------------------------------\n // The body's types say `Date`; a store's rows and a request's inputs are ISO\n // strings. An interpreter compares in the **encoded** space, and these are the\n // cases that say so — for every other column the two spaces hold the same\n // value, so nothing here could previously tell them apart.\n //\n // What happens when a caller passes a *decoded* value is deliberately not a\n // case, because the interpreters do not agree: the reference one matches\n // nothing, SQLite raises `datatype mismatch`, and a local engine does\n // whatever its own comparison does. `cases` are what interpreters must agree\n // about. The consequence is pinned in `packages/entity/test/encoding.test.ts`\n // instead, and it is the one that matters: **a runtime error cannot be relied\n // on to catch the mistake**, because one of the three answers is an empty\n // result that reads exactly like a correct one.\n {\n what: 'an input whose encoded form differs from its decoded one matches on the encoded one',\n body: from.pipe(Query.where(Expr.eq(Subject.fields.at, at)), byId),\n input: { at: '2026-01-02T00:00:00.000Z' },\n expected: ['b', 'c'],\n },\n {\n what: 'a literal is encoded too, or it has the same problem as an input',\n body: from.pipe(\n Query.where(Expr.eq(Subject.fields.at, '2026-01-03T00:00:00.000Z' as never)),\n byId,\n ),\n input: {},\n expected: ['d'],\n },\n\n // ---- ordering ------------------------------------------------------------\n {\n what: 'orders ascending by a number',\n body: from.pipe(Query.orderBy(Order.asc(Subject.fields.rank), Order.asc(Subject.fields.id))),\n input: {},\n expected: ['b', 'a', 'c', 'd', 'e'],\n },\n {\n what: 'orders descending, and a later term breaks the tie',\n body: from.pipe(Query.orderBy(Order.desc(Subject.fields.rank), Order.asc(Subject.fields.id))),\n input: {},\n expected: ['e', 'c', 'd', 'a', 'b'],\n },\n // Ordering by text is deliberately not here. How text compares is the\n // backend's — SQLite by code point, TanStack by locale, Postgres by whatever\n // the database was created with — and §6.0.1 puts it outside the conformant\n // subset rather than pretending one of them is the rule. A case asserting an\n // order would only pin whichever engine was written first.\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,YAAY,OAAO,KAAK,KAC5B,OAAO,SAAS,OAAO,QAAQ;CAC7B,QAAQ,aAAa,WAAW,QAAgB,IAAI,KAAK,GAAG,CAAC;CAC7D,QAAQ,aAAa,WAAW,OAAa,GAAG,YAAY,CAAC;AAC/D,CAAC,CACH;;AAGA,MAAa,UAAU,OAAO,OAC5B,WACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,OAAO,OAAO;CACd,MAAM,OAAO;;CAEb,KAAK,OAAO;;CAEZ,IAAI;AACN,CAAC,CACH;AAiBA,MAAa,OAAsC;CACjD;EAAE,IAAI;EAAK,OAAO;EAAS,MAAM;EAAG,KAAK;EAAM,IAAI;CAA2B;CAC9E;EAAE,IAAI;EAAK,OAAO;EAAgB,MAAM;EAAG,KAAK;EAAK,IAAI;CAA2B;CACpF;EAAE,IAAI;EAAK,OAAO;EAAS,MAAM;EAAG,KAAK;EAAM,IAAI;CAA2B;CAC9E;EAAE,IAAI;EAAK,OAAO;EAAe,MAAM;EAAG,KAAK;EAAK,IAAI;CAA2B;CACnF;EAAE,IAAI;EAAK,OAAO;EAAc,MAAM;EAAG,KAAK;EAAK,IAAI;CAA2B;AACpF;AAiBA,MAAM,OAAO,MAAM,KAAK,OAAO;AAC/B,MAAM,OAAO,MAAM,QAAQ,MAAM,IAAI,QAAQ,OAAO,EAAE,CAAC;AACvD,MAAM,QAAQ,KAAK,MAAM,SAAS,OAAO,MAAM;AAC/C,MAAM,OAAO,KAAK,MAAM,QAAQ,OAAO,MAAM;AAC7C,MAAM,MAAM,KAAK,MAAM,OAAO,OAAO,MAAM;AAC3C,MAAM,UAAU,KAAK,MAAM,WAAW,OAAO,O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C;AAMF"}
package/dist/index.d.mts CHANGED
@@ -106,13 +106,18 @@ export declare const isPredicate: (value: unknown) => value is Predicate;
106
106
  * wrongly — see `Query.unsupported`.
107
107
  */
108
108
  export type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains';
109
+ /** One field an expression reads: its Entity's name and key, and the identity that owns it. */
110
+ export interface FieldDependency {
111
+ /** The owning Entity's name, for display; two Entities may share one. */
112
+ readonly entity: string;
113
+ readonly key: string;
114
+ /** Which Entity it is. Two defined with the same name are two entries. */
115
+ readonly owner: EntityIdentity<string>;
116
+ }
109
117
  /** Which fields and inputs an expression reads, and which operations it uses. */
110
118
  export interface Dependencies {
111
- /** One entry per distinct field, as `Entity.key`. */
112
- readonly fields: ReadonlyArray<{
113
- readonly entity: string;
114
- readonly key: string;
115
- }>;
119
+ /** One entry per distinct field of each Entity identity. */
120
+ readonly fields: ReadonlyArray<FieldDependency>;
116
121
  /** One entry per distinct input key. */
117
122
  readonly inputs: ReadonlyArray<string>;
118
123
  /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/expr.ts","../src/words.ts","../src/shape.ts","../src/evaluate.ts","../src/index.ts"],"mappings":";;;;iBAiBiB,YAAY;WAClB;WACA,OAAO;;;;;;iBAOD,UAAU;WAChB;WACA,OAAO;WACP;WACA,QAAQ,OAAO,MAAM;;;;;;;;iBASf,UAAU;WAChB;WACA;WACA,QAAQ,OAAO,MAAM;;;YAIpB,KAAK,KAAK,YAAY,KAAK,UAAU,KAAK,UAAU;;YAGpD,UAAU;;;;;;;;;YAUV,YAAY,cAAc,gBAAgB;;iBAGrC;WACN;WACA,MAAM;WACN,OAAO;;;;;;;iBAQD;WACN;WACA,SAAS;WACT;;;;;;;iBAQM;WACN;WACA,OAAO;WACP,QAAQ;;;;;;;;YASP,aAAa,UAAU;;KAG9B,QAAQ,KAAK,4BAA4B,OAAO,cAAc,KAAK,KAAK;;YAGjE,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OACJ,MACN,YAAY,GAAG;EAEX,OAAA,eAAe,WAAS,QAAU,WAAS,aAAa;;qBAOpD;EACJ,OAAA,UAAU,OAAO,YAAU,QAAU,MAAI,YAAY"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/expr.ts","../src/words.ts","../src/shape.ts","../src/evaluate.ts","../src/index.ts"],"mappings":";;;;iBAiBiB,YAAY;WAClB;WACA,OAAO;;;;;;iBAOD,UAAU;WAChB;WACA,OAAO;WACP;WACA,QAAQ,OAAO,MAAM;;;;;;;;iBASf,UAAU;WAChB;WACA;WACA,QAAQ,OAAO,MAAM;;;YAIpB,KAAK,KAAK,YAAY,KAAK,UAAU,KAAK,UAAU;;YAGpD,UAAU;;;;;;;;;YAUV,YAAY,cAAc,gBAAgB;;iBAGrC;WACN;WACA,MAAM;WACN,OAAO;;;;;;;iBAQD;WACN;WACA,SAAS;WACT;;;;;;;iBAQM;WACN;WACA,OAAO;WACP,QAAQ;;;;;;;;YASP,aAAa,UAAU;;KAG9B,QAAQ,KAAK,4BAA4B,OAAO,cAAc,KAAK,KAAK;;YAGjE,QAAQ,KAClB,UAAU,kCAAkC,KACxC,OAAO,OAAO,KAAK,KACnB,UAAU,sBAER,UAAU,WAAW,KACnB;;;;;;;;;;;;;;;;;;;;;YAuBE,cACR,4BAA4B,OAAO,aAAa,OAAO,uCACvD,eACA;;qBAgCS,cAAe,mBAAiB,SAAS;;;;;;YAkC1C;;iBAGK;;WAEN;WACA;;WAEA,OAAO;;;iBAID;;WAEN,QAAQ,cAAc;;WAEtB,QAAQ;;WAER,YAAY,cAAc;;qBAGxB;;EApEI,UAAA,GAAC,OAAS,MAAI,YAAY;;;;;EA4EjC,QAAA,GAAC,aAAa,QAAU,OAAO,MAAM,gBAAc,UAAU;;EAI7D,QAAA,qBAAqB,oBAAoB,UAAU,OAAO,YAAU,OACnE,YAAY,MAAM,KAAK,OAC7B,UAAU,OAAO,OAAO,KAAK;;;;;;;;;;EAW3B,KAAA,UAAU,c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a,GAAG,QAAQ;;;;;;;;EAiEzC,SAAA,UAAU,iBAAiB,aAAa,oBAAoB,uBAAqB,QAChF,MAAC,MACA,qBACI,KAAK,eAAe,YAAY;;;;;EAkBnC,YAAA,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OACpE,YAAY,GAAG,QAAQ,aAC7B,UACD,WACA,YAAY,UACZ,gBAAgB,GAAG,YAAY,WAC/B,KAAK;;;;;;;EAwBK,YAAA,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OACpE,YAAY,GAAG,QAAQ,UAAQ,OAC/B,SAAS,6BACf,QAAQ,OAAO,OAAO,KAAK;EAtXP,KAAA,mBAAU,SAAS;;EAPhB,OAAA,MAAA,WAAS,OAAS;;iBAwarC,IAAI,eAAe,WAAW,QAAQ,SAAS,aAAa;iBAC5D,IAAI,eAAe,iBAAiB,0BAC3C,QAAQ,QACR;WAAoB,UAAU;IAC7B,aAAa,eAAe;;qBASlB;;;EAIH,QAAA,UAAU,yCAAuC,UAAY,MAAI,cAAc;;;;;EAO9E,SAAA,UAAU,yCAAyC,UAAU,4BAA0B,UACpF,GAAC,OACJ,MACN,YAAY,GAAG;EAEX,OAAA,eAAe,WAAS,QAAU,WAAS,aAAa;;qBAOpD;EACJ,OAAA,UAAU,OAAO,YAAU,QAAU,MAAI,YAAY"}
package/dist/index.mjs CHANGED
@@ -37,11 +37,18 @@ const tagOf = (value) => typeof value === "object" && value !== null && "_tag" i
37
37
  * idempotent on its own output. Nothing needs to tell them apart, which is
38
38
  * better than telling them apart by which extra member happens to be present.
39
39
  */
40
- const literal = (value) => ({
40
+ /**
41
+ * Every node is frozen as it is made, so a query built from it stays the value
42
+ * it was when `Query.where` checked it: nothing can swap a field or a literal
43
+ * in afterwards. It also means no node can come to contain itself. A literal's
44
+ * own payload is the caller's; the kernel compares scalars.
45
+ */
46
+ const node = (value) => Object.freeze(value);
47
+ const literal = (value) => node({
41
48
  _tag: "Literal",
42
49
  value
43
50
  });
44
- const fieldExpr = (field) => ({
51
+ const fieldExpr = (field) => node({
45
52
  _tag: "Field",
46
53
  owner: field.owner,
47
54
  key: field.key,
@@ -77,7 +84,7 @@ const Expr = {
77
84
  * A value the query is given when it runs. A definition builds these from its
78
85
  * `Input` schema; written by hand only when constructing a body directly.
79
86
  */
80
- input: (key, schema) => ({
87
+ input: (key, schema) => node({
81
88
  _tag: "Input",
82
89
  key,
83
90
  schema
@@ -93,7 +100,7 @@ const Expr = {
93
100
  * Expr.eq(Post.fields.status, 'active')
94
101
  * ```
95
102
  */
96
- eq: (left, right) => ({
103
+ eq: (left, right) => node({
97
104
  _tag: "Eq",
98
105
  left: toOperand(left),
99
106
  right: toOperand(right)
@@ -103,13 +110,13 @@ const Expr = {
103
110
  * one node, because a query asks which of the two it means and nothing here
104
111
  * can negate a predicate.
105
112
  */
106
- isNull: (operand) => ({
113
+ isNull: (operand) => node({
107
114
  _tag: "Null",
108
115
  operand: toExpr(operand, "isNull"),
109
116
  present: false
110
117
  }),
111
118
  /** Whether a field holds a value. */
112
- isNotNull: (operand) => ({
119
+ isNotNull: (operand) => node({
113
120
  _tag: "Null",
114
121
  operand: toExpr(operand, "isNotNull"),
115
122
  present: true
@@ -131,7 +138,7 @@ const Expr = {
131
138
  * `Expr.or` does not exist yet, so for now such a column needs its own
132
139
  * predicate or a native escape hatch.
133
140
  */
134
- contains: (value, search) => ({
141
+ contains: (value, search) => node({
135
142
  _tag: "Contains",
136
143
  value: toExpr(value, "contains"),
137
144
  search: toOperand(search)
@@ -140,40 +147,54 @@ const Expr = {
140
147
  show: (node) => showExpr(node)
141
148
  };
142
149
  const Order = {
143
- asc: (expr) => ({
150
+ asc: (expr) => node({
144
151
  direction: "asc",
145
152
  expr: toExpr(expr, "asc")
146
153
  }),
147
- desc: (expr) => ({
154
+ desc: (expr) => node({
148
155
  direction: "desc",
149
156
  expr: toExpr(expr, "desc")
150
157
  })
151
158
  };
152
- const walk = (node, fields, inputs, operations) => {
153
- switch (node._tag) {
159
+ /**
160
+ * Visits each node once. A node can be shared by several paths (`eq(n, n)`),
161
+ * and a walk that followed every path would take time exponential in the depth.
162
+ */
163
+ const walk = (expr, found) => {
164
+ if (found.seen.has(expr)) return;
165
+ found.seen.add(expr);
166
+ switch (expr._tag) {
154
167
  case "Literal": return;
155
- case "Field":
156
- fields.set(`${node.owner.name}.${node.key}`, {
157
- entity: node.owner.name,
158
- key: node.key
159
- });
168
+ case "Field": {
169
+ const byKey = found.fields.get(expr.owner.token) ?? /* @__PURE__ */ new Map();
170
+ found.fields.set(expr.owner.token, byKey);
171
+ if (!byKey.has(expr.key)) {
172
+ const field = {
173
+ entity: expr.owner.name,
174
+ key: expr.key,
175
+ owner: expr.owner
176
+ };
177
+ byKey.set(expr.key, field);
178
+ found.order.push(field);
179
+ }
160
180
  return;
181
+ }
161
182
  case "Input":
162
- inputs.add(node.key);
183
+ found.inputs.add(expr.key);
163
184
  return;
164
185
  case "Eq":
165
- operations.add("eq");
166
- walk(node.left, fields, inputs, operations);
167
- walk(node.right, fields, inputs, operations);
186
+ found.operations.add("eq");
187
+ walk(expr.left, found);
188
+ walk(expr.right, found);
168
189
  return;
169
190
  case "Null":
170
- operations.add(node.present ? "isNotNull" : "isNull");
171
- walk(node.operand, fields, inputs, operations);
191
+ found.operations.add(expr.present ? "isNotNull" : "isNull");
192
+ walk(expr.operand, found);
172
193
  return;
173
194
  case "Contains":
174
- operations.add("contains");
175
- walk(node.value, fields, inputs, operations);
176
- walk(node.search, fields, inputs, operations);
195
+ found.operations.add("contains");
196
+ walk(expr.value, found);
197
+ walk(expr.search, found);
177
198
  return;
178
199
  }
179
200
  };
@@ -183,34 +204,40 @@ const walk = (node, fields, inputs, operations) => {
183
204
  * order first seen, so the answer is stable enough to assert on.
184
205
  */
185
206
  const dependenciesOf = (...nodes) => {
186
- const fields = /* @__PURE__ */ new Map();
187
- const inputs = /* @__PURE__ */ new Set();
188
- const operations = /* @__PURE__ */ new Set();
189
- for (const node of nodes) walk("direction" in node ? node.expr : node, fields, inputs, operations);
207
+ const found = {
208
+ seen: /* @__PURE__ */ new Set(),
209
+ fields: /* @__PURE__ */ new Map(),
210
+ order: [],
211
+ inputs: /* @__PURE__ */ new Set(),
212
+ operations: /* @__PURE__ */ new Set()
213
+ };
214
+ for (const term of nodes) walk("direction" in term ? term.expr : term, found);
190
215
  return {
191
- fields: [...fields.values()],
192
- inputs: [...inputs],
193
- operations: [...operations]
216
+ fields: found.order,
217
+ inputs: [...found.inputs],
218
+ operations: [...found.operations]
194
219
  };
195
220
  };
196
- /** Every field an expression reads, as the nodes themselves. */
197
- const fieldsIn = function* (node) {
198
- switch (node._tag) {
221
+ /** Every field an expression reads, as the nodes themselves, each node visited once. */
222
+ const fieldsIn = function* (expr, seen) {
223
+ if (seen.has(expr)) return;
224
+ seen.add(expr);
225
+ switch (expr._tag) {
199
226
  case "Field":
200
- yield node;
227
+ yield expr;
201
228
  return;
202
229
  case "Literal":
203
230
  case "Input": return;
204
231
  case "Eq":
205
- yield* fieldsIn(node.left);
206
- yield* fieldsIn(node.right);
232
+ yield* fieldsIn(expr.left, seen);
233
+ yield* fieldsIn(expr.right, seen);
207
234
  return;
208
235
  case "Null":
209
- yield* fieldsIn(node.operand);
236
+ yield* fieldsIn(expr.operand, seen);
210
237
  return;
211
238
  case "Contains":
212
- yield* fieldsIn(node.value);
213
- yield* fieldsIn(node.search);
239
+ yield* fieldsIn(expr.value, seen);
240
+ yield* fieldsIn(expr.search, seen);
214
241
  return;
215
242
  }
216
243
  };
@@ -221,7 +248,8 @@ const fieldsIn = function* (node) {
221
248
  * two Entities defined with the same name are two Entities.
222
249
  */
223
250
  const checkOwnership = (step, what, entity, nodes) => {
224
- for (const node of nodes) for (const field of fieldsIn("direction" in node ? node.expr : node)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
251
+ const seen = /* @__PURE__ */ new Set();
252
+ for (const term of nodes) for (const field of fieldsIn("direction" in term ? term.expr : term, seen)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
225
253
  };
226
254
  const QueryProto = {
227
255
  _tag: "Query",
@@ -393,6 +421,13 @@ const valueOf = (node, row, input) => {
393
421
  }
394
422
  };
395
423
  const isNull = (value) => value === null || value === void 0;
424
+ /**
425
+ * Lowercases ASCII letters and leaves every other character as it is, which is
426
+ * what SQLite's `lower` does without ICU and so what the compiled SQL folds to.
427
+ * `toLowerCase` would fold `É` to `é` here and not there.
428
+ */
429
+ const foldAscii = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
430
+ const NUL = String.fromCharCode(0);
396
431
  /** A predicate used as a value is its own truth; anything else is its value. */
397
432
  const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
398
433
  /**
@@ -414,27 +449,51 @@ const holds = (node, row, input) => {
414
449
  const search = sideOf(node.search, row, input);
415
450
  if (isNull(value) || isNull(search)) return "unknown";
416
451
  if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
417
- return value.toLowerCase().includes(search.toLowerCase());
452
+ if (value.includes(NUL) || search.includes(NUL)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
453
+ return foldAscii(value).includes(foldAscii(search));
418
454
  }
419
455
  }
420
456
  };
421
457
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
422
458
  const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
423
- const compare = (left, right, query) => {
459
+ /** The kinds of value this interpreter orders by; every key of one term must share one. */
460
+ const comparable = /* @__PURE__ */ new Set([
461
+ "string",
462
+ "number",
463
+ "boolean"
464
+ ]);
465
+ const compare = (left, right) => {
424
466
  if (typeof left === "string" && typeof right === "string") return left < right ? -1 : left > right ? 1 : 0;
425
- if (typeof left === "number" && typeof right === "number") return left - right;
426
467
  if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
427
- throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`);
468
+ return left - right;
469
+ };
470
+ /**
471
+ * Refuses an ordering this interpreter will not answer for, before sorting, so
472
+ * the refusal names the first offending row in row order rather than whichever
473
+ * pair the engine's sort happened to compare first. Every term is checked over
474
+ * every row: a null key, or a key whose kind differs from the first row's.
475
+ */
476
+ const checkOrder = (rows, terms, query) => {
477
+ for (const term of terms) {
478
+ if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
479
+ const key = term.expr.key;
480
+ let first;
481
+ for (const row of rows) {
482
+ const value = row[key];
483
+ if (isNull(value)) throw new QueryEvaluateError(`query "${query}" orders by "${key}", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`);
484
+ const kind = typeof value;
485
+ first ??= kind;
486
+ if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
487
+ }
488
+ }
428
489
  };
429
490
  const ordered = (rows, terms, query) => {
430
- if (terms.length === 0) return [...rows];
491
+ if (terms.length === 0 || rows.length < 2) return [...rows];
492
+ checkOrder(rows, terms, query);
431
493
  return [...rows].sort((left, right) => {
432
494
  for (const term of terms) {
433
- if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
434
- const a = left[term.expr.key];
435
- const b = right[term.expr.key];
436
- if (isNull(a) || isNull(b)) throw new QueryEvaluateError(`query "${query}" orders by "${term.expr.key}", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`);
437
- const sign = compare(a, b, query);
495
+ const key = term.expr.key;
496
+ const sign = compare(left[key], right[key]);
438
497
  if (sign !== 0) return term.direction === "asc" ? sign : -sign;
439
498
  }
440
499
  return 0;
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/shape.ts","../src/expr.ts","../src/words.ts","../src/evaluate.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 * `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 { Pipeable, Schema } from 'effect'\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\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 = EqPredicate | NullPredicate | ContainsPredicate\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 * 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 */\nconst literal = <T>(value: T): LiteralExpr<T> => ({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> => ({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n})\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains'])\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 = 'eq' | 'isNull' | 'isNotNull' | 'contains'\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field, as `Entity.key`. */\n readonly fields: ReadonlyArray<{ readonly entity: string; readonly key: string }>\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\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 _tag: 'Input',\n key,\n schema,\n }),\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 => ({\n _tag: 'Eq',\n left: toOperand(left),\n right: toOperand(right as never),\n }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, because a query asks which of the two it means and nothing here\n * can negate a predicate.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNull'),\n present: false,\n }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNotNull'),\n present: true,\n }),\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` does not exist yet, so for now such a column needs its own\n * predicate or a native escape hatch.\n */\n contains: <L extends TextOperand>(\n value: L,\n search: string | Expr<string>,\n ): ContainsPredicate => ({\n _tag: 'Contains',\n value: toExpr(value, 'contains'),\n search: toOperand(search as never),\n }),\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 direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n}\n\nexport const Order = {\n asc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'asc',\n expr: toExpr(expr as never, 'asc'),\n }),\n desc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'desc',\n expr: toExpr(expr as never, 'desc'),\n }),\n}\n\nconst walk = (\n node: AnyExpr | Predicate,\n fields: Map<string, { readonly entity: string; readonly key: string }>,\n inputs: Set<string>,\n operations: Set<Operation>,\n): void => {\n switch (node._tag) {\n case 'Literal':\n return\n case 'Field':\n fields.set(`${node.owner.name}.${node.key}`, { entity: node.owner.name, key: node.key })\n return\n case 'Input':\n inputs.add(node.key)\n return\n case 'Eq':\n operations.add('eq')\n walk(node.left, fields, inputs, operations)\n walk(node.right, fields, inputs, operations)\n return\n case 'Null':\n operations.add(node.present ? 'isNotNull' : 'isNull')\n walk(node.operand, fields, inputs, operations)\n return\n case 'Contains':\n operations.add('contains')\n walk(node.value, fields, inputs, operations)\n walk(node.search, fields, inputs, operations)\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 | OrderTerm>\n): Dependencies => {\n const fields = new Map<string, { readonly entity: string; readonly key: string }>()\n const inputs = new Set<string>()\n const operations = new Set<Operation>()\n for (const node of nodes) {\n walk('direction' in node ? node.expr : node, fields, inputs, operations)\n }\n return { fields: [...fields.values()], inputs: [...inputs], operations: [...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<OrderTerm>\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. */\nconst fieldsIn = function* (node: AnyExpr | Predicate): Generator<FieldExpr<unknown>> {\n switch (node._tag) {\n case 'Field':\n yield node\n return\n case 'Literal':\n case 'Input':\n return\n case 'Eq':\n yield* fieldsIn(node.left)\n yield* fieldsIn(node.right)\n return\n case 'Null':\n yield* fieldsIn(node.operand)\n return\n case 'Contains':\n yield* fieldsIn(node.value)\n yield* fieldsIn(node.search)\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 | OrderTerm>,\n): void => {\n for (const node of nodes) {\n for (const field of fieldsIn('direction' in node ? node.expr : node)) {\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\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<OrderTerm>,\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 return query(self.entity, [...self.where, ...predicates], 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<OrderTerm>) =>\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 * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses.\n */\n dependencies: (self: AnyQuery): Dependencies => dependenciesOf(...self.where, ...self.orderBy),\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 ...self.where.map(\n (predicate, index) => `${index === 0 ? 'WHERE' : ' AND'} ${Expr.show(predicate)}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`)\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 }\n}\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\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 { Query, 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/** 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 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 // Case-insensitive, because that is what `Expr.contains` means and what\n // the compiled SQL folds both sides to. Plain `includes` would be\n // case-sensitive here and case-insensitive under SQLite's `like`, which\n // is a body meaning two things.\n return value.toLowerCase().includes(search.toLowerCase())\n }\n }\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\nconst compare = (left: unknown, right: unknown, query: string): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\n }\n if (typeof left === 'number' && typeof right === 'number') return left - right\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`,\n )\n}\n\nconst ordered = (rows: ReadonlyArray<Row>, terms: ReadonlyArray<OrderTerm>, query: string) => {\n if (terms.length === 0) return [...rows]\n return [...rows].sort((left, right) => {\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 const a = left[term.expr.key]\n const b = right[term.expr.key]\n if (isNull(a) || isNull(b)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by \"${term.expr.key}\", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`,\n )\n }\n const sign = compare(a, b, query)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n })\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> = ['eq', 'isNull', 'isNotNull', 'contains']\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 body.orderBy,\n body.entity.name,\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 { 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\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\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 ? Present<Input> extends Schema.Schema.Type<S>\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 ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\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 './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'\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;;;;;;;;;;;;;;;;AC+GA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;;AAQhF,MAAM,WAAc,WAA8B;CAAE,MAAM;CAAW;AAAM;AAE3E,MAAM,aAAa,WAA+E;CAChG,MAAM;CACN,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"],"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 * `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 { Pipeable, Schema } from 'effect'\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\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 = EqPredicate | NullPredicate | ContainsPredicate\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 * 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 })\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains'])\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 = 'eq' | 'isNull' | 'isNotNull' | 'contains'\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\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, because a query asks which of the two it means and nothing here\n * can negate a predicate.\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` does not exist yet, so for now such a column needs its own\n * predicate or a native escape hatch.\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 /** 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 direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n}\n\nexport const Order = {\n asc: <E extends Operand<any>>(expr: E): OrderTerm =>\n node({ direction: 'asc', expr: toExpr(expr as never, 'asc') }),\n desc: <E extends Operand<any>>(expr: E): OrderTerm =>\n node({ direction: 'desc', expr: toExpr(expr as never, 'desc') }),\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, 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 }\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 | OrderTerm>\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('direction' in term ? term.expr : 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<OrderTerm>\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,\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 }\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 | OrderTerm>,\n): void => {\n const seen = new Set<object>()\n for (const term of nodes) {\n for (const field of fieldsIn('direction' in term ? term.expr : 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\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<OrderTerm>,\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 return query(self.entity, [...self.where, ...predicates], 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<OrderTerm>) =>\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 * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses.\n */\n dependencies: (self: AnyQuery): Dependencies => dependenciesOf(...self.where, ...self.orderBy),\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 ...self.where.map(\n (predicate, index) => `${index === 0 ? 'WHERE' : ' AND'} ${Expr.show(predicate)}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`)\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 }\n}\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\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 { Query, 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/** 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 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 (value.includes(NUL) || search.includes(NUL)) {\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 }\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\nconst compare = (left: unknown, right: unknown): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\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 null key, or a key whose kind differs from the first row's.\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 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)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by \"${key}\", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`,\n )\n }\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\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) => {\n for (const term of terms) {\n const key = (term.expr as Extract<OrderTerm['expr'], { readonly _tag: 'Field' }>).key\n const sign = compare(left[key], right[key])\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n })\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> = ['eq', 'isNull', 'isNotNull', 'contains']\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 body.orderBy,\n body.entity.name,\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 { 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\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\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 ? Present<Input> extends Schema.Schema.Type<S>\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 ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\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 './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'\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;;;;;;;;;;;;;;;;AC+GA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;;;;;;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,WAAW,QAAQ,OAAO,CAAC;GACjC,MAAM,OAAO,MAAM;GACnB,QAAQ,OAAO,MAAf;IACE,KAAK,SACH,OAAO,CAAC,CAAC,KAAK,IAAI,CAAU;IAC9B,KAAK,eAAe;KAClB,MAAM,UAAU,SACd,OAAO,SAAS,YAAY,SAAS,OACjC,OAAO,UAAU,OAAO,OAAO,IAAyC,IACxE;KACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;IAC/E;IACA,KAAK,iBAAiB;KACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;KAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;IAC1C;GACF;EACF,CAAC;EACD,OAAO,OAAO,YAAY,OAAO;CACnC;CAEA,IAAI;;CAGJ,MAAM;AACR;AAOA,SAAS,IACP,QACA,SACyC;CACzC,OAAO;EAAE;EAAQ,aAAa;EAAO,UAAU,SAAS,YAAY;CAAM;AAC5E;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;CACZ;AACF;AAEA,MAAa,UAAU,EACrB,OAAoC,YAA+B,EAAE,OAAO,GAC9E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-entity",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Domain structure for Foldkit Plus: an Entity's fields, relations, and derived members as typed values, and Selections of them.",
5
5
  "keywords": [
6
6
  "foldkit",