foldkit-entity 0.15.0 → 0.17.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 +128 -17
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +20 -0
- package/dist/conformance/index.js.map +1 -1
- package/dist/conformance/operator.d.ts.map +1 -1
- package/dist/conformance/operator.js +13 -4
- package/dist/conformance/operator.js.map +1 -1
- package/dist/entity.d.ts +14 -2
- package/dist/entity.d.ts.map +1 -1
- package/dist/entity.js +41 -12
- package/dist/entity.js.map +1 -1
- package/dist/evaluate.d.ts +1 -1
- package/dist/evaluate.d.ts.map +1 -1
- package/dist/evaluate.js +22 -18
- package/dist/evaluate.js.map +1 -1
- package/dist/expr.d.ts +70 -20
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +67 -47
- package/dist/expr.js.map +1 -1
- package/dist/held.js +11 -3
- package/dist/held.js.map +1 -1
- package/dist/index.d.ts +38 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -3
- package/dist/index.js.map +1 -1
- package/dist/invariant.d.ts.map +1 -1
- package/dist/invariant.js +26 -20
- package/dist/invariant.js.map +1 -1
- package/dist/law.d.ts.map +1 -1
- package/dist/law.js +3 -9
- package/dist/law.js.map +1 -1
- package/dist/lawCore.d.ts +42 -0
- package/dist/lawCore.d.ts.map +1 -0
- package/dist/lawCore.js +12 -0
- package/dist/lawCore.js.map +1 -0
- package/dist/memoryTable.d.ts +11 -0
- package/dist/memoryTable.d.ts.map +1 -0
- package/dist/memoryTable.js +69 -0
- package/dist/memoryTable.js.map +1 -0
- package/dist/operators.d.ts.map +1 -1
- package/dist/operators.js +2 -66
- package/dist/operators.js.map +1 -1
- package/dist/sets.js.map +1 -1
- package/dist/write.d.ts +1 -1
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +40 -18
- package/dist/write.js.map +1 -1
- package/package.json +1 -1
package/dist/held.js
CHANGED
|
@@ -57,8 +57,11 @@ const rowsOf = (tables) => {
|
|
|
57
57
|
let missing = from.complete ? Option.none() : Option.some(`not every ${relation.owner.name} is held`);
|
|
58
58
|
for (const each of from.views) {
|
|
59
59
|
const link = each.field(relation.key);
|
|
60
|
-
if (link._tag === "Unheld")
|
|
61
|
-
|
|
60
|
+
if (link._tag === "Unheld") {
|
|
61
|
+
missing = Option.orElse(missing, () => Option.some(link.reason));
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (link.value === id) rows.push(each);
|
|
62
65
|
}
|
|
63
66
|
return {
|
|
64
67
|
rows,
|
|
@@ -144,7 +147,12 @@ const Held = {
|
|
|
144
147
|
of: held,
|
|
145
148
|
/** A value the holder does not have, and why. */
|
|
146
149
|
unheld,
|
|
147
|
-
match: (value, cases) =>
|
|
150
|
+
match: (value, cases) => {
|
|
151
|
+
switch (value._tag) {
|
|
152
|
+
case "Held": return cases.onHeld(value.value);
|
|
153
|
+
case "Unheld": return cases.onUnheld(value.reason);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
148
156
|
/** Rows held as plain records; see `HeldTable`. */
|
|
149
157
|
rows: rowsOf,
|
|
150
158
|
fromRefs,
|
package/dist/held.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"held.js","names":[],"sources":["../src/held.ts"],"sourcesContent":["/**\n * What a holder of rows has: the world `Judge` reads an `Expr` over.\n *\n * A server's database holds every row, so whatever an expression asks has an\n * answer there. A client holds what it was sent: some rows, some fields of\n * them, and none it may not see. `HeldRow` is how a holder says which, so an\n * interpreter can tell \"this field is null\" from \"I do not have this field\",\n * which a plain record cannot: both read as a missing key.\n */\nimport { Option } from 'effect'\nimport { relationsOf } from './descriptor.js'\nimport { Query, type AnyQuery, type OneRelation } from './expr.js'\nimport type { AnyEntity, EntityIdentity, EntityMember } from './index.js'\nimport { own, put } from './record.js'\n\n/** A value a holder has, or why it does not have it. */\nexport type Held<A> =\n | { readonly _tag: 'Held'; readonly value: A }\n | { readonly _tag: 'Unheld'; readonly reason: string }\n\n/** The rows pointing at one row through a relation, as far as a holder has them. */\nexport interface Pointing {\n readonly rows: ReadonlyArray<HeldRow>\n /**\n * Why a row pointing here may be missing from `rows`; none when it holds\n * every one whose fields hold the values `pinned` names.\n */\n readonly missing: Option.Option<string>\n}\n\n/**\n * The values an exists' filter fixes on the rows it counts, by field key (a\n * link as the id it points at): a row with another value in one of them is\n * not counted, so a holder holding every pointing row with these values holds\n * every one that counts (`Judge.pins`).\n */\nexport type Pinned = ReadonlyMap<string, unknown>\n\n/**\n * One row as a holder has it. Values are **encoded**, as a store keeps them\n * and as `evaluate` reads a row.\n */\nexport interface HeldRow {\n /** A field's value; unheld when the holder lacks it or may not see it. */\n readonly field: (key: string) => Held<unknown>\n /**\n * The row a `one` relation of this row points at: none for a null link, or\n * a row the reader may not see when the holder knows it holds every row it may.\n */\n readonly follow: (relation: OneRelation) => Held<Option.Option<HeldRow>>\n /**\n * The rows pointing at this one through `relation`, a `one` relation of\n * another Entity, for an exists whose filter fixes `pinned`.\n */\n readonly pointing: (relation: OneRelation, pinned: Pinned) => Pointing\n}\n\n/** One Entity's rows, as `Held.rows` takes them. */\nexport interface HeldTable {\n readonly entity: AnyEntity\n /**\n * Each row's values by key, encoded; a `one` relation's under its own key,\n * as the id of the row it points at or null. A key a row lacks is unheld.\n */\n readonly rows: ReadonlyArray<Readonly<Record<string, unknown>>>\n /**\n * Whether these are every row of the Entity the reader may see, so a row\n * not among them is known absent. True when not given.\n */\n readonly complete?: boolean | undefined\n /** Keys the reader may not see on any of these rows. */\n readonly hidden?: ReadonlyArray<string> | undefined\n}\n\n/** The rows `Held.rows` holds, by Entity. */\nexport interface HeldRows {\n /** The row of `entity` with this id, when it is held. */\n readonly row: (entity: AnyEntity, id: unknown) => Option.Option<HeldRow>\n /** Every held row of `entity`. */\n readonly rows: (entity: AnyEntity) => ReadonlyArray<HeldRow>\n /**\n * The row of `entity` with this id as the holder can say: none when it\n * knows there is no such row it may see, unheld when it cannot tell.\n */\n readonly find: (entity: AnyEntity, id: unknown) => Held<Option.Option<HeldRow>>\n}\n\nconst held = <A>(value: A): Held<A> => ({ _tag: 'Held', value })\nconst unheld = <A = never>(reason: string): Held<A> => ({ _tag: 'Unheld', reason })\n\n/**\n * Rows held as plain records: each table complete or not, with keys hidden.\n * What a test, a conformance check or a server that has the rows in hand\n * judges over.\n */\nconst rowsOf = (tables: ReadonlyArray<HeldTable>): HeldRows => {\n interface Table {\n readonly entity: AnyEntity\n readonly complete: boolean\n readonly hidden: ReadonlySet<string>\n readonly byId: ReadonlyMap<unknown, HeldRow>\n readonly views: ReadonlyArray<HeldRow>\n }\n const byToken = new Map<symbol, Table>()\n const tableOf = (identity: EntityIdentity<string>) =>\n Option.fromUndefinedOr(byToken.get(identity.token))\n const find = (target: AnyEntity, id: unknown): Held<Option.Option<HeldRow>> =>\n Option.match(tableOf(target.identity), {\n onNone: () => unheld(`no ${target.name} is held`),\n onSome: reached =>\n Option.match(Option.fromUndefinedOr(reached.byId.get(id)), {\n onSome: row => held(Option.some(row)),\n onNone: () =>\n reached.complete\n ? held(Option.none<HeldRow>())\n : unheld(`${target.name} ${String(id)} is not held`),\n }),\n })\n\n const view = (table: Table, record: Readonly<Record<string, unknown>>): HeldRow => {\n const read = (key: string): Held<unknown> =>\n table.hidden.has(key)\n ? unheld(`${table.entity.name}.${key} is hidden from this reader`)\n : Object.hasOwn(record, key)\n ? held(record[key])\n : unheld(`${table.entity.name}.${key} is not held`)\n return {\n field: read,\n follow: relation => {\n const link = read(relation.key)\n if (link._tag === 'Unheld') return link\n if (link.value === null || link.value === undefined) return held(Option.none())\n return find(relation.target(), link.value)\n },\n pointing: relation =>\n Option.match(tableOf(relation.owner), {\n onNone: () => ({\n rows: [],\n missing: Option.some(`no ${relation.owner.name} is held`),\n }),\n onSome: from => {\n const id = record.id\n const named = `${relation.owner.name}.${relation.key}`\n const rows: Array<HeldRow> = []\n let missing = from.complete\n ? Option.none<string>()\n : Option.some(`not every ${relation.owner.name} is held`)\n for (const each of from.views) {\n const link = each.field(relation.key)\n if (link._tag === 'Unheld') {\n missing = Option.orElse(missing, () => Option.some(link.reason))\n } else if (link.value === id) {\n rows.push(each)\n }\n }\n return { rows, missing: Option.map(missing, reason => `${named}: ${reason}`) }\n },\n }),\n }\n }\n\n for (const given of tables) {\n const views: Array<HeldRow> = []\n const byId = new Map<unknown, HeldRow>()\n const table: Table = {\n entity: given.entity,\n complete: given.complete ?? true,\n hidden: new Set(given.hidden ?? []),\n byId,\n views,\n }\n for (const record of given.rows) {\n const each = view(table, record)\n views.push(each)\n byId.set(record.id, each)\n }\n byToken.set(given.entity.identity.token, table)\n }\n\n return {\n row: (entity, id) =>\n Option.flatMap(tableOf(entity.identity), table => Option.fromUndefinedOr(table.byId.get(id))),\n rows: entity =>\n Option.match(tableOf(entity.identity), { onNone: () => [], onSome: table => table.views }),\n find,\n }\n}\n\nconst linksRead = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n\n/**\n * The links a query reads on its own row: each relation of its Entity it\n * reads (a body reads only a `one` relation as a value). A relation it reads\n * existed when it was built, so what it reads is known once.\n */\nconst linksOf = (query: AnyQuery): ReadonlyArray<string> => {\n const known = linksRead.get(query)\n if (known !== undefined) return known\n const relations: Readonly<Record<string, EntityMember>> = query.entity.relations\n const links = Query.dependencies(query)\n .fields.filter(\n field =>\n field.owner.token === query.entity.identity.token && Object.hasOwn(relations, field.key),\n )\n .map(field => field.key)\n linksRead.set(query, links)\n return links\n}\n\n/**\n * A row as a Source answers it and a Remote store keeps it, each `one`\n * relation as its ref key (`'User:ada'`), given as an interpreter reads it:\n * each link `query` reads as the id it points at. The row itself when the\n * query reads no link.\n */\nconst fromRefs = (\n query: AnyQuery,\n row: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> => {\n const links = linksOf(query)\n if (links.length === 0) return row\n const read: Record<string, unknown> = { ...row }\n for (const key of links) {\n const ref = own(row, key)\n if (ref !== null && ref !== undefined)\n put(read, key, idOfRef(ref, `${query.entity.name}.${key}`))\n }\n return read\n}\n\n/**\n * Whether `key` is a `one` relation of the Entity `owner` names: what a\n * ref-keyed holder reads as the id it points at on a row it knows only by\n * identity, as a row pointing through `HeldRow.pointing`'s relation is.\n */\nconst isLink = (owner: EntityIdentity<string>, key: string): boolean => {\n const member = own(relationsOf(owner), key)\n return member?._tag === 'Relation' && member.cardinality === 'one'\n}\n\n/** The id a ref key (`'User:ada'`) names, refusing what is none, as `where` holds it. */\nexport const idOfRef = (ref: unknown, where: string): string => {\n const separator = typeof ref === 'string' ? ref.indexOf(':') : -1\n if (separator === -1) {\n throw new Error(\n `[foldkit-entity] ${where} holds ${JSON.stringify(ref)}, which is no ref key (\"Entity:id\")`,\n )\n }\n return (ref as string).slice(separator + 1)\n}\n\nexport const Held = {\n /** A value the holder has. */\n of: held,\n /** A value the holder does not have, and why. */\n unheld,\n match: <A, B>(\n value: Held<A>,\n cases: { readonly onHeld: (value: A) => B; readonly onUnheld: (reason: string) => B },\n ): B => (value._tag === 'Held' ? cases.onHeld(value.value) : cases.onUnheld(value.reason)),\n /** Rows held as plain records; see `HeldTable`. */\n rows: rowsOf,\n fromRefs,\n isLink,\n}\n"],"mappings":";;;;;;;;;;;;;;AAuFA,MAAM,QAAW,WAAuB;CAAE,MAAM;CAAQ;AAAM;AAC9D,MAAM,UAAqB,YAA6B;CAAE,MAAM;CAAU;AAAO;;;;;;AAOjF,MAAM,UAAU,WAA+C;CAQ7D,MAAM,0BAAU,IAAI,IAAmB;CACvC,MAAM,WAAW,aACf,OAAO,gBAAgB,QAAQ,IAAI,SAAS,KAAK,CAAC;CACpD,MAAM,QAAQ,QAAmB,OAC/B,OAAO,MAAM,QAAQ,OAAO,QAAQ,GAAG;EACrC,cAAc,OAAO,MAAM,OAAO,KAAK,SAAS;EAChD,SAAQ,YACN,OAAO,MAAM,OAAO,gBAAgB,QAAQ,KAAK,IAAI,EAAE,CAAC,GAAG;GACzD,SAAQ,QAAO,KAAK,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MAAM,QAAQ,QAAQ,KAAK;CAC3B,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,OAAgC,EAAE,GAAG,IAAI;CAC/C,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,MAAM,IAAI,KAAK,GAAG;EACxB,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,IAAI,MAAM,KAAK,QAAQ,KAAK,GAAG,MAAM,OAAO,KAAK,GAAG,KAAK,CAAC;CAC9D;CACA,OAAO;AACT;;;;;;AAOA,MAAM,UAAU,OAA+B,QAAyB;CACtE,MAAM,SAAS,IAAI,YAAY,KAAK,GAAG,GAAG;CAC1C,OAAO,QAAQ,SAAS,cAAc,OAAO,gBAAgB;AAC/D;;AAGA,MAAa,WAAW,KAAc,UAA0B;CAC9D,MAAM,YAAY,OAAO,QAAQ,WAAW,IAAI,QAAQ,GAAG,IAAI;CAC/D,IAAI,cAAc,IAChB,MAAM,IAAI,MACR,oBAAoB,MAAM,SAAS,KAAK,UAAU,GAAG,EAAE,oCACzD;CAEF,OAAQ,IAAe,MAAM,YAAY,CAAC;AAC5C;AAEA,MAAa,OAAO;;CAElB,IAAI;;CAEJ;CACA,QACE,OACA,UACO,MAAM,SAAS,SAAS,MAAM,OAAO,MAAM,KAAK,IAAI,MAAM,SAAS,MAAM,MAAM;;CAExF,MAAM;CACN;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"held.js","names":[],"sources":["../src/held.ts"],"sourcesContent":["/**\n * What a holder of rows has: the world `Judge` reads an `Expr` over.\n *\n * A server's database holds every row, so whatever an expression asks has an\n * answer there. A client holds what it was sent: some rows, some fields of\n * them, and none it may not see. `HeldRow` is how a holder says which, so an\n * interpreter can tell \"this field is null\" from \"I do not have this field\",\n * which a plain record cannot: both read as a missing key.\n */\nimport { Option } from 'effect'\nimport { relationsOf } from './descriptor.js'\nimport { Query, type AnyQuery, type OneRelation } from './expr.js'\nimport type { AnyEntity, EntityIdentity, EntityMember } from './index.js'\nimport { own, put } from './record.js'\n\n/** A value a holder has, or why it does not have it. */\nexport type Held<A> =\n | { readonly _tag: 'Held'; readonly value: A }\n | { readonly _tag: 'Unheld'; readonly reason: string }\n\n/** The rows pointing at one row through a relation, as far as a holder has them. */\nexport interface Pointing {\n readonly rows: ReadonlyArray<HeldRow>\n /**\n * Why a row pointing here may be missing from `rows`; none when it holds\n * every one whose fields hold the values `pinned` names.\n */\n readonly missing: Option.Option<string>\n}\n\n/**\n * The values an exists' filter fixes on the rows it counts, by field key (a\n * link as the id it points at): a row with another value in one of them is\n * not counted, so a holder holding every pointing row with these values holds\n * every one that counts (`Judge.pins`).\n */\nexport type Pinned = ReadonlyMap<string, unknown>\n\n/**\n * One row as a holder has it. Values are **encoded**, as a store keeps them\n * and as `evaluate` reads a row.\n */\nexport interface HeldRow {\n /** A field's value; unheld when the holder lacks it or may not see it. */\n readonly field: (key: string) => Held<unknown>\n /**\n * The row a `one` relation of this row points at: none for a null link, or\n * a row the reader may not see when the holder knows it holds every row it may.\n */\n readonly follow: (relation: OneRelation) => Held<Option.Option<HeldRow>>\n /**\n * The rows pointing at this one through `relation`, a `one` relation of\n * another Entity, for an exists whose filter fixes `pinned`.\n */\n readonly pointing: (relation: OneRelation, pinned: Pinned) => Pointing\n}\n\n/** One Entity's rows, as `Held.rows` takes them. */\nexport interface HeldTable {\n readonly entity: AnyEntity\n /**\n * Each row's values by key, encoded; a `one` relation's under its own key,\n * as the id of the row it points at or null. A key a row lacks is unheld.\n */\n readonly rows: ReadonlyArray<Readonly<Record<string, unknown>>>\n /**\n * Whether these are every row of the Entity the reader may see, so a row\n * not among them is known absent. True when not given.\n */\n readonly complete?: boolean | undefined\n /** Keys the reader may not see on any of these rows. */\n readonly hidden?: ReadonlyArray<string> | undefined\n}\n\n/** The rows `Held.rows` holds, by Entity. */\nexport interface HeldRows {\n /** The row of `entity` with this id, when it is held. */\n readonly row: (entity: AnyEntity, id: unknown) => Option.Option<HeldRow>\n /** Every held row of `entity`. */\n readonly rows: (entity: AnyEntity) => ReadonlyArray<HeldRow>\n /**\n * The row of `entity` with this id as the holder can say: none when it\n * knows there is no such row it may see, unheld when it cannot tell.\n */\n readonly find: (entity: AnyEntity, id: unknown) => Held<Option.Option<HeldRow>>\n}\n\nconst held = <A>(value: A): Held<A> => ({ _tag: 'Held', value })\nconst unheld = <A = never>(reason: string): Held<A> => ({ _tag: 'Unheld', reason })\n\n/**\n * Rows held as plain records: each table complete or not, with keys hidden.\n * What a test, a conformance check or a server that has the rows in hand\n * judges over.\n */\nconst rowsOf = (tables: ReadonlyArray<HeldTable>): HeldRows => {\n interface Table {\n readonly entity: AnyEntity\n readonly complete: boolean\n readonly hidden: ReadonlySet<string>\n readonly byId: ReadonlyMap<unknown, HeldRow>\n readonly views: ReadonlyArray<HeldRow>\n }\n const byToken = new Map<symbol, Table>()\n const tableOf = (identity: EntityIdentity<string>) =>\n Option.fromUndefinedOr(byToken.get(identity.token))\n const find = (target: AnyEntity, id: unknown): Held<Option.Option<HeldRow>> =>\n Option.match(tableOf(target.identity), {\n onNone: () => unheld(`no ${target.name} is held`),\n onSome: reached =>\n Option.match(Option.fromUndefinedOr(reached.byId.get(id)), {\n onSome: row => held(Option.some(row)),\n onNone: () =>\n reached.complete\n ? held(Option.none<HeldRow>())\n : unheld(`${target.name} ${String(id)} is not held`),\n }),\n })\n\n const view = (table: Table, record: Readonly<Record<string, unknown>>): HeldRow => {\n const read = (key: string): Held<unknown> =>\n table.hidden.has(key)\n ? unheld(`${table.entity.name}.${key} is hidden from this reader`)\n : Object.hasOwn(record, key)\n ? held(record[key])\n : unheld(`${table.entity.name}.${key} is not held`)\n return {\n field: read,\n follow: relation => {\n const link = read(relation.key)\n if (link._tag === 'Unheld') return link\n if (link.value === null || link.value === undefined) return held(Option.none())\n return find(relation.target(), link.value)\n },\n pointing: relation =>\n Option.match(tableOf(relation.owner), {\n onNone: () => ({\n rows: [],\n missing: Option.some(`no ${relation.owner.name} is held`),\n }),\n onSome: from => {\n const id = record.id\n const named = `${relation.owner.name}.${relation.key}`\n const rows: Array<HeldRow> = []\n let missing = from.complete\n ? Option.none<string>()\n : Option.some(`not every ${relation.owner.name} is held`)\n for (const each of from.views) {\n const link = each.field(relation.key)\n if (link._tag === 'Unheld') {\n missing = Option.orElse(missing, () => Option.some(link.reason))\n continue\n }\n if (link.value === id) rows.push(each)\n }\n return { rows, missing: Option.map(missing, reason => `${named}: ${reason}`) }\n },\n }),\n }\n }\n\n for (const given of tables) {\n const views: Array<HeldRow> = []\n const byId = new Map<unknown, HeldRow>()\n const table: Table = {\n entity: given.entity,\n complete: given.complete ?? true,\n hidden: new Set(given.hidden ?? []),\n byId,\n views,\n }\n for (const record of given.rows) {\n const each = view(table, record)\n views.push(each)\n byId.set(record.id, each)\n }\n byToken.set(given.entity.identity.token, table)\n }\n\n return {\n row: (entity, id) =>\n Option.flatMap(tableOf(entity.identity), table => Option.fromUndefinedOr(table.byId.get(id))),\n rows: entity =>\n Option.match(tableOf(entity.identity), { onNone: () => [], onSome: table => table.views }),\n find,\n }\n}\n\nconst linksRead = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n\n/**\n * The links a query reads on its own row: each relation of its Entity it\n * reads (a body reads only a `one` relation as a value). A relation it reads\n * existed when it was built, so what it reads is known once.\n */\nconst linksOf = (query: AnyQuery): ReadonlyArray<string> => {\n const known = linksRead.get(query)\n if (known !== undefined) return known\n const relations: Readonly<Record<string, EntityMember>> = query.entity.relations\n const links = Query.dependencies(query)\n .fields.filter(\n field =>\n field.owner.token === query.entity.identity.token && Object.hasOwn(relations, field.key),\n )\n .map(field => field.key)\n linksRead.set(query, links)\n return links\n}\n\n/**\n * A row as a Source answers it and a Remote store keeps it, each `one`\n * relation as its ref key (`'User:ada'`), given as an interpreter reads it:\n * each link `query` reads as the id it points at. The row itself when the\n * query reads no link.\n */\nconst fromRefs = (\n query: AnyQuery,\n row: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> => {\n const links = linksOf(query)\n if (links.length === 0) return row\n const read: Record<string, unknown> = { ...row }\n for (const key of links) {\n const ref = own(row, key)\n if (ref !== null && ref !== undefined)\n put(read, key, idOfRef(ref, `${query.entity.name}.${key}`))\n }\n return read\n}\n\n/**\n * Whether `key` is a `one` relation of the Entity `owner` names: what a\n * ref-keyed holder reads as the id it points at on a row it knows only by\n * identity, as a row pointing through `HeldRow.pointing`'s relation is.\n */\nconst isLink = (owner: EntityIdentity<string>, key: string): boolean => {\n const member = own(relationsOf(owner), key)\n return member?._tag === 'Relation' && member.cardinality === 'one'\n}\n\n/** The id a ref key (`'User:ada'`) names, refusing what is none, as `where` holds it. */\nexport const idOfRef = (ref: unknown, where: string): string => {\n const separator = typeof ref === 'string' ? ref.indexOf(':') : -1\n if (separator === -1) {\n throw new Error(\n `[foldkit-entity] ${where} holds ${JSON.stringify(ref)}, which is no ref key (\"Entity:id\")`,\n )\n }\n return (ref as string).slice(separator + 1)\n}\n\nexport const Held = {\n /** A value the holder has. */\n of: held,\n /** A value the holder does not have, and why. */\n unheld,\n match: <A, B>(\n value: Held<A>,\n cases: { readonly onHeld: (value: A) => B; readonly onUnheld: (reason: string) => B },\n ): B => {\n switch (value._tag) {\n case 'Held':\n return cases.onHeld(value.value)\n case 'Unheld':\n return cases.onUnheld(value.reason)\n }\n },\n /** Rows held as plain records; see `HeldTable`. */\n rows: rowsOf,\n fromRefs,\n isLink,\n}\n"],"mappings":";;;;;;;;;;;;;;AAuFA,MAAM,QAAW,WAAuB;CAAE,MAAM;CAAQ;AAAM;AAC9D,MAAM,UAAqB,YAA6B;CAAE,MAAM;CAAU;AAAO;;;;;;AAOjF,MAAM,UAAU,WAA+C;CAQ7D,MAAM,0BAAU,IAAI,IAAmB;CACvC,MAAM,WAAW,aACf,OAAO,gBAAgB,QAAQ,IAAI,SAAS,KAAK,CAAC;CACpD,MAAM,QAAQ,QAAmB,OAC/B,OAAO,MAAM,QAAQ,OAAO,QAAQ,GAAG;EACrC,cAAc,OAAO,MAAM,OAAO,KAAK,S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3F,CAAC,CACA,KAAI,UAAS,MAAM,GAAG;CACzB,UAAU,IAAI,OAAO,KAAK;CAC1B,OAAO;AACT;;;;;;;AAQA,MAAM,YACJ,OACA,QACsC;CACtC,MAAM,QAAQ,QAAQ,KAAK;CAC3B,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,OAAgC,EAAE,GAAG,IAAI;CAC/C,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,MAAM,IAAI,KAAK,GAAG;EACxB,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,IAAI,MAAM,KAAK,QAAQ,KAAK,GAAG,MAAM,OAAO,KAAK,GAAG,KAAK,CAAC;CAC9D;CACA,OAAO;AACT;;;;;;AAOA,MAAM,UAAU,OAA+B,QAAyB;CACtE,MAAM,SAAS,IAAI,YAAY,KAAK,GAAG,GAAG;CAC1C,OAAO,QAAQ,SAAS,cAAc,OAAO,gBAAgB;AAC/D;;AAGA,MAAa,WAAW,KAAc,UAA0B;CAC9D,MAAM,YAAY,OAAO,QAAQ,WAAW,IAAI,QAAQ,GAAG,IAAI;CAC/D,IAAI,cAAc,IAChB,MAAM,IAAI,MACR,oBAAoB,MAAM,SAAS,KAAK,UAAU,GAAG,EAAE,oCACzD;CAEF,OAAQ,IAAe,MAAM,YAAY,CAAC;AAC5C;AAEA,MAAa,OAAO;;CAElB,IAAI;;CAEJ;CACA,QACE,OACA,UACM;EACN,QAAQ,MAAM,MAAd;GACE,KAAK,QACH,OAAO,MAAM,OAAO,MAAM,KAAK;GACjC,KAAK,UACH,OAAO,MAAM,SAAS,MAAM,MAAM;EACtC;CACF;;CAEA,MAAM;CACN;CACA;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -40,15 +40,27 @@ export type Cardinality = 'one' | 'many';
|
|
|
40
40
|
/**
|
|
41
41
|
* What happens to a row when the row its `one` relation points at is deleted
|
|
42
42
|
* (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted
|
|
43
|
-
* with it, by the server in the write that deletes, and foreseen by a client
|
|
43
|
+
* with it, by the server in the write that deletes, and foreseen by a client;
|
|
44
|
+
* `restrict`, the delete is refused while any row points there (#467), naming
|
|
45
|
+
* the relation and none of the rows; `setNull`, an optional link is cleared,
|
|
46
|
+
* an update of the row held to its own `Update` rules.
|
|
44
47
|
*/
|
|
45
|
-
export type OnDelete = 'cascade';
|
|
48
|
+
export type OnDelete = 'cascade' | 'restrict' | 'setNull';
|
|
49
|
+
/**
|
|
50
|
+
* Who may let a cascade take a row (#348). `child`, the default: the row's own
|
|
51
|
+
* `Delete` rule, judged for whoever deletes the row it points at, so a delete
|
|
52
|
+
* that would take a row they may not delete is refused whole. `parent`: whoever
|
|
53
|
+
* may delete the row it points at may take it too (a post's author removing
|
|
54
|
+
* the likes under it), declared on the relation so it is never a default.
|
|
55
|
+
*/
|
|
56
|
+
export type AuthorizedBy = 'child' | 'parent';
|
|
46
57
|
/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */
|
|
47
58
|
export interface RelationSpec<Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
|
|
48
59
|
readonly target: Target;
|
|
49
60
|
readonly cardinality: C;
|
|
50
61
|
readonly optional: Optional;
|
|
51
62
|
readonly onDelete: Option.Option<OnDelete>;
|
|
63
|
+
readonly authorizedBy: Option.Option<AuthorizedBy>;
|
|
52
64
|
}
|
|
53
65
|
/**
|
|
54
66
|
* A navigation edge as its owner sees it: one or many of `target`. How the edge
|
|
@@ -68,6 +80,8 @@ export interface EntityRelation<Name extends string, Key extends string, Target
|
|
|
68
80
|
* deleted; none for a `many`, and for a `one` declared with nothing.
|
|
69
81
|
*/
|
|
70
82
|
readonly onDelete: Option.Option<OnDelete>;
|
|
83
|
+
/** Who may let a cascade through it take this row: some exactly where `onDelete` is `cascade`. */
|
|
84
|
+
readonly authorizedBy: Option.Option<AuthorizedBy>;
|
|
71
85
|
readonly metadata: Metadata;
|
|
72
86
|
}
|
|
73
87
|
type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>;
|
|
@@ -305,12 +319,30 @@ export interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.F
|
|
|
305
319
|
readonly schema: Schema.Struct<Fields>;
|
|
306
320
|
readonly members: Members;
|
|
307
321
|
}
|
|
308
|
-
/**
|
|
309
|
-
|
|
322
|
+
/**
|
|
323
|
+
* How a `one` relation is declared: whether it may point nowhere, and what a
|
|
324
|
+
* delete of its target does. `authorizedBy` is said only beside `onDelete`.
|
|
325
|
+
*/
|
|
326
|
+
export type OneOptions<Optional extends boolean> = {
|
|
310
327
|
readonly optional?: Optional;
|
|
328
|
+
} & ({
|
|
329
|
+
readonly onDelete?: undefined;
|
|
330
|
+
readonly authorizedBy?: undefined;
|
|
331
|
+
} | {
|
|
311
332
|
/** `cascade`: a row pointing here is deleted with the row it points at. */
|
|
312
|
-
readonly onDelete
|
|
313
|
-
|
|
333
|
+
readonly onDelete: 'cascade';
|
|
334
|
+
/** Whose `Delete` rule lets the cascade take this row: its own (`child`), or the parent's. */
|
|
335
|
+
readonly authorizedBy?: AuthorizedBy;
|
|
336
|
+
} | {
|
|
337
|
+
/** `restrict`: the row it points at cannot be deleted while this row points there. */
|
|
338
|
+
readonly onDelete: 'restrict';
|
|
339
|
+
readonly authorizedBy?: undefined;
|
|
340
|
+
} | {
|
|
341
|
+
/** `setNull`: this row stays and points nowhere; only a link that may point nowhere can. */
|
|
342
|
+
readonly onDelete: 'setNull';
|
|
343
|
+
readonly optional: true;
|
|
344
|
+
readonly authorizedBy?: undefined;
|
|
345
|
+
});
|
|
314
346
|
declare function one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>;
|
|
315
347
|
declare function one<Target extends AnyEntity, const Optional extends boolean>(target: Target, options: OneOptions<Optional> & {
|
|
316
348
|
readonly optional: Optional;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["ExprContext","EntityTypeId","EntitySet","AnyVariantUnion","NowExpr","ViewerExpr","ViewerPathExpr","SelectionTypeId","SelectionPageTypeId"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBA2BiB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["ExprContext","EntityTypeId","EntitySet","AnyVariantUnion","NowExpr","ViewerExpr","ViewerPathExpr","SelectionTypeId","SelectionPageTypeId"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBA2BiB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT;;;;;;;;;YAUA;;;;;;;;YASA;;iBAGK,aACf,eAAe,WACf,UAAU,aACV;WAES,QAAQ;WACR,aAAa;WACb,UAAU;WACV,UAAU,OAAO,OAAO;WACxB,cAAc,OAAO,OAAO;;;;;;;iBAQtB,eACf,qBACA,oBACA,eAAe,WACf,UAAU,aACV;WAES;WACA,OAAO,eAAe;WACtB,KAAK;;WAEL,cAAc;WACd,aAAa;WACb,UAAU;;;;;WAKV,UAAU,OAAO,OAAO;;WAExB,cAAc,OAAO,OAAO;WAC5B,UAAU;;KAGhB,cAAc,+BAA+B;;;;;;;;;;YAWtC,aAAa,KAAK;;;;;;EAM5B;aAAqB,SAAS,OAAO,OAAO;aAAmB,SAAS,OAAO,OAAO;;EACtF;aAAkB,UAAU;;EAC5B;aAAmB,UAAU;aAAsB,QAAQ;;;qBAEhD,YAAU,KAAA,WAAA;;WAHO,UAAA;;;WACC,UAAA;WAA8B,QAAA;;;WAF7B,SAAA,OAAO,OAAO;WAA4B,SAAA,OAAO,OAAO;;;iBAOvE;;WA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B,GAAC;aAEE,UAAU;aACV,UAAU;QAEpB,YAAY,GAAG,QAAQ;aAAuB;;;;;;;;;EAejD,QAAQ,UAAU,+BAA+B,4BAA0B,UAC/D,MACT,mBAAmB;aAAwB;aAAwB,UAAU;;;;;;;;;;;EAchF,SACE,UAAU,aACV,UAAU,eAAe,UAAU,YAAY,4BAA0B,UAE/D,GAAC;aACS,QAAQ;QAC3B,mBACM;aACI;aAAyB,UAAU;aAAY,QAAQ"}
|
package/dist/index.js
CHANGED
|
@@ -26,12 +26,17 @@ export * from "./evaluate.js";
|
|
|
26
26
|
const Derivation = Data.taggedEnum();
|
|
27
27
|
function one(target, options) {
|
|
28
28
|
const onDelete = options?.onDelete;
|
|
29
|
-
|
|
29
|
+
const authorizedBy = options?.authorizedBy;
|
|
30
|
+
if (onDelete !== void 0 && onDelete !== "cascade" && onDelete !== "restrict" && onDelete !== "setNull") throw new Error(`[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade', 'restrict' or 'setNull'; ${String(onDelete)} is not one`);
|
|
31
|
+
if (onDelete === "setNull" && options?.optional !== true) throw new Error(`[foldkit-entity] Relation.one(${target.name}): onDelete: 'setNull' clears the link, so it needs optional: true`);
|
|
32
|
+
if (authorizedBy !== void 0 && authorizedBy !== "child" && authorizedBy !== "parent") throw new Error(`[foldkit-entity] Relation.one(${target.name}): authorizedBy is 'child' or 'parent'; ${String(authorizedBy)} is not one`);
|
|
33
|
+
if (authorizedBy !== void 0 && onDelete !== "cascade") throw new Error(`[foldkit-entity] Relation.one(${target.name}): authorizedBy says who lets a cascade take the row, so it needs onDelete: 'cascade'`);
|
|
30
34
|
return {
|
|
31
35
|
target,
|
|
32
36
|
cardinality: "one",
|
|
33
37
|
optional: options?.optional ?? false,
|
|
34
|
-
onDelete: Option.fromUndefinedOr(onDelete)
|
|
38
|
+
onDelete: Option.fromUndefinedOr(onDelete),
|
|
39
|
+
authorizedBy: onDelete === "cascade" ? Option.some(authorizedBy ?? "child") : Option.none()
|
|
35
40
|
};
|
|
36
41
|
}
|
|
37
42
|
/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
|
|
@@ -55,7 +60,8 @@ const Relation = {
|
|
|
55
60
|
target,
|
|
56
61
|
cardinality: "many",
|
|
57
62
|
optional: false,
|
|
58
|
-
onDelete: Option.none()
|
|
63
|
+
onDelete: Option.none(),
|
|
64
|
+
authorizedBy: Option.none()
|
|
59
65
|
})
|
|
60
66
|
};
|
|
61
67
|
/** A count: never negative, never a fraction. */
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Data, Option, type Pipeable, Schema } from 'effect'\nimport type { Metadata } from 'foldkit-metadata'\nimport type { ExprContext, NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { HeldRow, HeldRows } from './held.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport type { EntitySet } from './sets.js'\n// The members of `Entity`, a namespace rather than an object so a page keeps only\n// those it calls (#378). Exported under the interface's name; `export * as`\n// would make each `Entity` type here a reference the declaration emitter refuses.\nimport * as EntityMembers from './entity.js'\nimport type { AnyVariantUnion } from './variants.js'\n\nexport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/**\n * What happens to a row when the row its `one` relation points at is deleted\n * (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted\n * with it, by the server in the write that deletes, and foreseen by a client.\n */\nexport type OnDelete = 'cascade'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n readonly onDelete: Option.Option<OnDelete>\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n /**\n * What happens to this row when the row a `one` relation points at is\n * deleted; none for a `many`, and for a `one` declared with nothing.\n */\n readonly onDelete: Option.Option<OnDelete>\n readonly metadata: Metadata\n}\n\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * What a derived member is. `Supplied` (`Derived.make`): an interpreter\n * supplies it, and nothing else can say what it is. `Count`\n * (`Derived.count`): how many rows point at this one through `relation`, a\n * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of\n * a row pointing here through `relation` whose `viewer` relation points at\n * whoever reads it, or none. A client predicts both from the rows it writes,\n * and a server compiles both from the relations' storage.\n */\nexport type Derivation = Data.TaggedEnum<{\n /**\n * `predict`: how a client foresees it for a row it writes; none, it waits\n * for the server. `forbids`: which write to the row its value refuses, so a\n * client holding it refuses that write where it is made.\n */\n Supplied: { readonly predict: Option.Option<Predict>; readonly forbids: Option.Option<Forbids> }\n Count: { readonly relation: OneRelation }\n Exists: { readonly relation: OneRelation; readonly viewer: OneRelation }\n}>\nexport const Derivation = Data.taggedEnum<Derivation>()\n\n/** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */\nexport interface Predicting {\n /** The Entity written, as the write declared it. */\n readonly entity: AnyEntity\n readonly row: HeldRow\n /** The holder's other rows, where a rule's path reads. */\n readonly rows: HeldRows\n /** The operation's context: who asks, and the write's time. */\n readonly context: ExprContext\n}\n\n/**\n * A supplied member foreseen: its value **encoded**, as the store holds it, or\n * none where the holder cannot know it, so nothing is shown before the answer.\n */\nexport type Predict = (predicting: Predicting) => Option.Option<unknown>\n\n/**\n * What a write does to a row it finds, as a supplied member's `forbids` is\n * asked: an update's members and the relations it points, or a delete.\n */\nexport interface WriteSurface {\n readonly kind: 'Update' | 'Delete'\n /** The members it sets, moves or computes, relations not among them. */\n readonly members: ReadonlyArray<string>\n /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly interaction: 'Link' | 'Unlink'\n }>\n}\n\n/**\n * Whether a supplied member's value, **encoded** as the store holds it,\n * refuses `surface`, with the reader's words for why when there are any; none\n * where it does not say so for certain. Only a definite refusal: a client\n * refuses the write unseen, and its server would refuse it too.\n */\nexport type Forbids = (\n value: unknown,\n surface: WriteSurface,\n) => Option.Option<{ readonly reason: Option.Option<string> }>\n\n/** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {\n readonly schema: S\n readonly derives: D\n}\n\n/** A value consumers may read that is not part of `entity.schema`, and what it derives. */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n D extends Derivation = Derivation,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly derives: D\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<\n Name,\n K,\n Derived[K]['schema'],\n Derived[K]['derives']\n >\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */\n readonly sets: Readonly<Record<string, EntitySet>>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/**\n * An Entity whose rows are one of several shapes (`Entity.defineVariants`).\n * `variants` is Effect's tagged union of them, read with its own `match`;\n * `fields` and `schema` are the stored row, which every case shares.\n */\nexport interface VariantEntity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n Union extends AnyVariantUnion = AnyVariantUnion,\n> extends Entity<Name, Fields, Relations, Derived> {\n readonly variants: Union\n}\n\nexport type AnyVariantEntity = VariantEntity<string, any, any, any, any>\n\n/** The keys of an Entity's `one` relations. */\ntype OneRelationKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/**\n * What a field holding `T` may be set to: the time where it holds a number,\n * the viewer's id where text, and what a path from the viewer reads where it\n * holds that.\n */\ntype ContextValueFor<T> =\n | (number extends T ? NowExpr<number> : never)\n | (T extends string ? ViewerExpr<T> : never)\n | ViewerPathExpr<T | null>\n\n/** The name of the Entity the `one` relation `K` points at. */\ntype TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<\n E['relations'][K]['target']\n>['name']\n\n/**\n * What `Entity.sets` takes, by member: a field the value of the write's\n * context it can hold, a `one` relation `Expr.viewer` of its target.\n */\nexport type EntitySets<E extends AnyEntity> = {\n readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<\n Schema.Schema.Type<E['fields'][K]['schema']>\n >\n} & {\n readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>\n}\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D, U>\n : Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\nexport type { InputMembers, WrittenAs, WrittenKey, WrittenSpec } from './entity.js'\nexport { EntityMembers as Entity }\n\n/** How a `one` relation is declared: whether it may point nowhere, and what a delete of its target does. */\nexport interface OneOptions<Optional extends boolean> {\n readonly optional?: Optional\n /** `cascade`: a row pointing here is deleted with the row it points at. */\n readonly onDelete?: OnDelete\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: OneOptions<Optional> & { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one<Target extends AnyEntity>(\n target: Target,\n options: OneOptions<false>,\n): RelationSpec<Target, 'one', false>\nfunction one(\n target: AnyEntity,\n options?: OneOptions<boolean>,\n): RelationSpec<AnyEntity, 'one', boolean> {\n const onDelete = options?.onDelete\n if (onDelete !== undefined && onDelete !== 'cascade')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`,\n )\n return {\n target,\n cardinality: 'one',\n optional: options?.optional ?? false,\n onDelete: Option.fromUndefinedOr(onDelete),\n }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n onDelete: Option.none(),\n }),\n}\n\n/** A count: never negative, never a fraction. */\nconst CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** The id of the row an exists found, as every Remote id is held: text, or none. */\nconst WitnessSchema = Schema.OptionFromNullOr(Schema.String)\n\ntype OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never\n\nexport const Derived = {\n /**\n * A member only an interpreter can compute, of type `schema`: it supplies the\n * value. `predict` says how a client foresees it for a row it writes (Guard's\n * `may`); without it the row reads as missing the member until the answer.\n * `forbids` says which write to the row its value refuses (Guard's `may`\n * again), so a client holding it refuses that write where it is made.\n */\n make: <S extends Schema.Constraint>(\n schema: S,\n options: {\n readonly predict?: Predict | undefined\n readonly forbids?: Forbids | undefined\n } = {},\n ): DerivedSpec<S, Extract<Derivation, { readonly _tag: 'Supplied' }>> => ({\n schema,\n derives: Derivation.Supplied({\n predict: Option.fromUndefinedOr(options.predict),\n forbids: Option.fromUndefinedOr(options.forbids),\n }),\n }),\n\n /**\n * How many rows point at this one through `relation`, a `one` relation of\n * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on\n * Post. Added after `Entity.relate`, which makes the relation. A server\n * compiles it from the relation's storage, and a client predicts it from\n * the rows a pending write inserts, deletes or points elsewhere.\n */\n count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(\n relation: R,\n ): DerivedSpec<typeof CountSchema, { readonly _tag: 'Count'; readonly relation: R }> => ({\n schema: CountSchema,\n derives: Derivation.Count({ relation }) as { readonly _tag: 'Count'; readonly relation: R },\n }),\n\n /**\n * Whether a row points at this one through `relation` and at whoever reads\n * it through `viewer`, another `one` relation of the same pointing Entity:\n * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`\n * on Post. Its value is that row's id as the store holds it, or none, so the\n * reader can take it back (`Write.delete` by that id). It depends on who\n * reads it: a server answers it for the principal it reads as, and a client\n * predicts it for the viewer it is told of.\n */\n exists: <\n R extends OneRelation,\n V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>,\n >(\n relation: R,\n options: { readonly viewer: V },\n ): DerivedSpec<\n typeof WitnessSchema,\n { readonly _tag: 'Exists'; readonly relation: R; readonly viewer: V }\n > => ({\n schema: WitnessSchema,\n derives: Derivation.Exists({ relation, viewer: options.viewer }) as {\n readonly _tag: 'Exists'\n readonly relation: R\n readonly viewer: V\n },\n }),\n}\n\nexport * from './expr.js'\nexport {\n contextValue,\n viewerIdOf,\n type ExprContext,\n type NowExpr,\n type ViewerExpr,\n type ViewerPathExpr,\n} from './context.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\nexport type {\n AnyVariantUnion,\n CheckCases,\n EntityVariants,\n StoredFields,\n VariantCases,\n VariantUnion,\n} from './variants.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport * from './held.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport type { ContextValue, EntitySet, SetOn } from './sets.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteKind,\n type WriteLink,\n type WriteSet,\n type ContextSet,\n type ContextRead,\n type ContextValues,\n} from './write.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,aAAa,KAAK,WAAuB;AA0UtD,SAAS,IACP,QACA,SACyC;CACzC,MAAM,WAAW,SAAS;CAC1B,IAAI,aAAa,KAAA,KAAa,aAAa,WACzC,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,4BAA4B,OAAO,QAAQ,EAAE,YAC5F;CACF,OAAO;EACL;EACA,aAAa;EACb,UAAU,SAAS,YAAY;EAC/B,UAAU,OAAO,gBAAgB,QAAQ;CAC3C;AACF;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;EACV,UAAU,OAAO,KAAK;CACxB;AACF;;AAGA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;;AAGxF,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,MAAM;AAI3D,MAAa,UAAU;;;;;;;;CAQrB,OACE,QACA,UAGI,CAAC,OACmE;EACxE;EACA,SAAS,WAAW,SAAS;GAC3B,SAAS,OAAO,gBAAgB,QAAQ,OAAO;GAC/C,SAAS,OAAO,gBAAgB,QAAQ,OAAO;EACjD,CAAC;CACH;;;;;;;;CASA,QACE,cACuF;EACvF,QAAQ;EACR,SAAS,WAAW,MAAM,EAAE,SAAS,CAAC;CACxC;;;;;;;;;;CAWA,SAIE,UACA,aAII;EACJ,QAAQ;EACR,SAAS,WAAW,OAAO;GAAE;GAAU,QAAQ,QAAQ;EAAO,CAAC;CAKjE;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Data, Option, type Pipeable, Schema } from 'effect'\nimport type { Metadata } from 'foldkit-metadata'\nimport type { ExprContext, NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { HeldRow, HeldRows } from './held.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport type { EntitySet } from './sets.js'\n// The members of `Entity`, a namespace rather than an object so a page keeps only\n// those it calls (#378). Exported under the interface's name; `export * as`\n// would make each `Entity` type here a reference the declaration emitter refuses.\nimport * as EntityMembers from './entity.js'\nimport type { AnyVariantUnion } from './variants.js'\n\nexport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/**\n * What happens to a row when the row its `one` relation points at is deleted\n * (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted\n * with it, by the server in the write that deletes, and foreseen by a client;\n * `restrict`, the delete is refused while any row points there (#467), naming\n * the relation and none of the rows; `setNull`, an optional link is cleared,\n * an update of the row held to its own `Update` rules.\n */\nexport type OnDelete = 'cascade' | 'restrict' | 'setNull'\n\n/**\n * Who may let a cascade take a row (#348). `child`, the default: the row's own\n * `Delete` rule, judged for whoever deletes the row it points at, so a delete\n * that would take a row they may not delete is refused whole. `parent`: whoever\n * may delete the row it points at may take it too (a post's author removing\n * the likes under it), declared on the relation so it is never a default.\n */\nexport type AuthorizedBy = 'child' | 'parent'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n readonly onDelete: Option.Option<OnDelete>\n readonly authorizedBy: Option.Option<AuthorizedBy>\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n /**\n * What happens to this row when the row a `one` relation points at is\n * deleted; none for a `many`, and for a `one` declared with nothing.\n */\n readonly onDelete: Option.Option<OnDelete>\n /** Who may let a cascade through it take this row: some exactly where `onDelete` is `cascade`. */\n readonly authorizedBy: Option.Option<AuthorizedBy>\n readonly metadata: Metadata\n}\n\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * What a derived member is. `Supplied` (`Derived.make`): an interpreter\n * supplies it, and nothing else can say what it is. `Count`\n * (`Derived.count`): how many rows point at this one through `relation`, a\n * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of\n * a row pointing here through `relation` whose `viewer` relation points at\n * whoever reads it, or none. A client predicts both from the rows it writes,\n * and a server compiles both from the relations' storage.\n */\nexport type Derivation = Data.TaggedEnum<{\n /**\n * `predict`: how a client foresees it for a row it writes; none, it waits\n * for the server. `forbids`: which write to the row its value refuses, so a\n * client holding it refuses that write where it is made.\n */\n Supplied: { readonly predict: Option.Option<Predict>; readonly forbids: Option.Option<Forbids> }\n Count: { readonly relation: OneRelation }\n Exists: { readonly relation: OneRelation; readonly viewer: OneRelation }\n}>\nexport const Derivation = Data.taggedEnum<Derivation>()\n\n/** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */\nexport interface Predicting {\n /** The Entity written, as the write declared it. */\n readonly entity: AnyEntity\n readonly row: HeldRow\n /** The holder's other rows, where a rule's path reads. */\n readonly rows: HeldRows\n /** The operation's context: who asks, and the write's time. */\n readonly context: ExprContext\n}\n\n/**\n * A supplied member foreseen: its value **encoded**, as the store holds it, or\n * none where the holder cannot know it, so nothing is shown before the answer.\n */\nexport type Predict = (predicting: Predicting) => Option.Option<unknown>\n\n/**\n * What a write does to a row it finds, as a supplied member's `forbids` is\n * asked: an update's members and the relations it points, or a delete.\n */\nexport interface WriteSurface {\n readonly kind: 'Update' | 'Delete'\n /** The members it sets, moves or computes, relations not among them. */\n readonly members: ReadonlyArray<string>\n /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly interaction: 'Link' | 'Unlink'\n }>\n}\n\n/**\n * Whether a supplied member's value, **encoded** as the store holds it,\n * refuses `surface`, with the reader's words for why when there are any; none\n * where it does not say so for certain. Only a definite refusal: a client\n * refuses the write unseen, and its server would refuse it too.\n */\nexport type Forbids = (\n value: unknown,\n surface: WriteSurface,\n) => Option.Option<{ readonly reason: Option.Option<string> }>\n\n/** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {\n readonly schema: S\n readonly derives: D\n}\n\n/** A value consumers may read that is not part of `entity.schema`, and what it derives. */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n D extends Derivation = Derivation,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly derives: D\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<\n Name,\n K,\n Derived[K]['schema'],\n Derived[K]['derives']\n >\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */\n readonly sets: Readonly<Record<string, EntitySet>>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/**\n * An Entity whose rows are one of several shapes (`Entity.defineVariants`).\n * `variants` is Effect's tagged union of them, read with its own `match`;\n * `fields` and `schema` are the stored row, which every case shares.\n */\nexport interface VariantEntity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n Union extends AnyVariantUnion = AnyVariantUnion,\n> extends Entity<Name, Fields, Relations, Derived> {\n readonly variants: Union\n}\n\nexport type AnyVariantEntity = VariantEntity<string, any, any, any, any>\n\n/** The keys of an Entity's `one` relations. */\ntype OneRelationKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/**\n * What a field holding `T` may be set to: the time where it holds a number,\n * the viewer's id where text, and what a path from the viewer reads where it\n * holds that.\n */\ntype ContextValueFor<T> =\n | (number extends T ? NowExpr<number> : never)\n | (T extends string ? ViewerExpr<T> : never)\n | ViewerPathExpr<T | null>\n\n/** The name of the Entity the `one` relation `K` points at. */\ntype TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<\n E['relations'][K]['target']\n>['name']\n\n/**\n * What `Entity.sets` takes, by member: a field the value of the write's\n * context it can hold, a `one` relation `Expr.viewer` of its target.\n */\nexport type EntitySets<E extends AnyEntity> = {\n readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<\n Schema.Schema.Type<E['fields'][K]['schema']>\n >\n} & {\n readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>\n}\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D, U>\n : Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\nexport type { InputMembers, WrittenAs, WrittenKey, WrittenSpec } from './entity.js'\nexport { EntityMembers as Entity }\n\n/**\n * How a `one` relation is declared: whether it may point nowhere, and what a\n * delete of its target does. `authorizedBy` is said only beside `onDelete`.\n */\nexport type OneOptions<Optional extends boolean> = {\n readonly optional?: Optional\n} & (\n | { readonly onDelete?: undefined; readonly authorizedBy?: undefined }\n | {\n /** `cascade`: a row pointing here is deleted with the row it points at. */\n readonly onDelete: 'cascade'\n /** Whose `Delete` rule lets the cascade take this row: its own (`child`), or the parent's. */\n readonly authorizedBy?: AuthorizedBy\n }\n | {\n /** `restrict`: the row it points at cannot be deleted while this row points there. */\n readonly onDelete: 'restrict'\n readonly authorizedBy?: undefined\n }\n | {\n /** `setNull`: this row stays and points nowhere; only a link that may point nowhere can. */\n readonly onDelete: 'setNull'\n readonly optional: true\n readonly authorizedBy?: undefined\n }\n)\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: OneOptions<Optional> & { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one<Target extends AnyEntity>(\n target: Target,\n options: OneOptions<false>,\n): RelationSpec<Target, 'one', false>\nfunction one(\n target: AnyEntity,\n options?: OneOptions<boolean>,\n): RelationSpec<AnyEntity, 'one', boolean> {\n const onDelete = options?.onDelete\n const authorizedBy = options?.authorizedBy\n if (\n onDelete !== undefined &&\n onDelete !== 'cascade' &&\n onDelete !== 'restrict' &&\n onDelete !== 'setNull'\n )\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade', 'restrict' or 'setNull'; ${String(onDelete)} is not one`,\n )\n if (onDelete === 'setNull' && options?.optional !== true)\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete: 'setNull' clears the link, so it needs optional: true`,\n )\n if (authorizedBy !== undefined && authorizedBy !== 'child' && authorizedBy !== 'parent')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): authorizedBy is 'child' or 'parent'; ${String(authorizedBy)} is not one`,\n )\n if (authorizedBy !== undefined && onDelete !== 'cascade')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): authorizedBy says who lets a cascade take the row, so it needs onDelete: 'cascade'`,\n )\n return {\n target,\n cardinality: 'one',\n optional: options?.optional ?? false,\n onDelete: Option.fromUndefinedOr(onDelete),\n authorizedBy: onDelete === 'cascade' ? Option.some(authorizedBy ?? 'child') : Option.none(),\n }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n onDelete: Option.none(),\n authorizedBy: Option.none(),\n }),\n}\n\n/** A count: never negative, never a fraction. */\nconst CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** The id of the row an exists found, as every Remote id is held: text, or none. */\nconst WitnessSchema = Schema.OptionFromNullOr(Schema.String)\n\ntype OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never\n\nexport const Derived = {\n /**\n * A member only an interpreter can compute, of type `schema`: it supplies the\n * value. `predict` says how a client foresees it for a row it writes (Guard's\n * `may`); without it the row reads as missing the member until the answer.\n * `forbids` says which write to the row its value refuses (Guard's `may`\n * again), so a client holding it refuses that write where it is made.\n */\n make: <S extends Schema.Constraint>(\n schema: S,\n options: {\n readonly predict?: Predict | undefined\n readonly forbids?: Forbids | undefined\n } = {},\n ): DerivedSpec<S, Extract<Derivation, { readonly _tag: 'Supplied' }>> => ({\n schema,\n derives: Derivation.Supplied({\n predict: Option.fromUndefinedOr(options.predict),\n forbids: Option.fromUndefinedOr(options.forbids),\n }),\n }),\n\n /**\n * How many rows point at this one through `relation`, a `one` relation of\n * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on\n * Post. Added after `Entity.relate`, which makes the relation. A server\n * compiles it from the relation's storage, and a client predicts it from\n * the rows a pending write inserts, deletes or points elsewhere.\n */\n count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(\n relation: R,\n ): DerivedSpec<typeof CountSchema, { readonly _tag: 'Count'; readonly relation: R }> => ({\n schema: CountSchema,\n derives: Derivation.Count({ relation }) as { readonly _tag: 'Count'; readonly relation: R },\n }),\n\n /**\n * Whether a row points at this one through `relation` and at whoever reads\n * it through `viewer`, another `one` relation of the same pointing Entity:\n * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`\n * on Post. Its value is that row's id as the store holds it, or none, so the\n * reader can take it back (`Write.delete` by that id). It depends on who\n * reads it: a server answers it for the principal it reads as, and a client\n * predicts it for the viewer it is told of.\n */\n exists: <\n R extends OneRelation,\n V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>,\n >(\n relation: R,\n options: { readonly viewer: V },\n ): DerivedSpec<\n typeof WitnessSchema,\n { readonly _tag: 'Exists'; readonly relation: R; readonly viewer: V }\n > => ({\n schema: WitnessSchema,\n derives: Derivation.Exists({ relation, viewer: options.viewer }) as {\n readonly _tag: 'Exists'\n readonly relation: R\n readonly viewer: V\n },\n }),\n}\n\nexport * from './expr.js'\nexport {\n contextValue,\n viewerIdOf,\n type ExprContext,\n type NowExpr,\n type ViewerExpr,\n type ViewerPathExpr,\n} from './context.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\nexport type {\n AnyVariantUnion,\n CheckCases,\n EntityVariants,\n StoredFields,\n VariantCases,\n VariantUnion,\n} from './variants.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport * from './held.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport type { ContextValue, EntitySet, SetOn } from './sets.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteKind,\n type WriteLink,\n type WriteSet,\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;;CAQrB,OACE,QACA,UAGI,CAAC,OACmE;EACxE;EACA,SAAS,WAAW,SAAS;GAC3B,SAAS,OAAO,gBAAgB,QAAQ,OAAO;GAC/C,SAAS,OAAO,gBAAgB,QAAQ,OAAO;EACjD,CAAC;CACH;;;;;;;;CASA,QACE,cACuF;EACvF,QAAQ;EACR,SAAS,WAAW,MAAM,EAAE,SAAS,CAAC;CACxC;;;;;;;;;;CAWA,SAIE,UACA,aAII;EACJ,QAAQ;EACR,SAAS,WAAW,OAAO;GAAE;GAAU,QAAQ,QAAQ;EAAO,CAAC;CAKjE;AACF"}
|
package/dist/invariant.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invariant.d.ts","names":["MemoryOperators"],"sources":["../src/invariant.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"invariant.d.ts","names":["MemoryOperators"],"sources":["../src/invariant.ts"],"mappings":";;;;;;iBAiDiB;;WAEN;;WAEA;WACA,WAAW;;WAEX;;WAEA,MAAM;;WAEN,QAAQ;;WAER,OAAO;;;KAIb,SAAS,UAAU,gBACrB,WAAW,0BAA0B,eAAe,kCAAkC,mBACjF;;KAGH,OACH,UAAU,WACV,gBAAgB,kBACd,eAAe;;;;;;;YAQP,UAAU,UAAU,yBACpB,WAAW,uBAAuB,UAC1C,OAAO,MAAM,QAAQ,YAAY,iBAEjC,MAAM,4BACM,KAAK,SAAS,KAAK,UAAU,OAAO,GAAG,MAAM,MAAM;;YAGvD,SAAS,UAAU,yBACnB,WAAW,uBAAuB,SAC1C,OAAO,MAAM,QAAQ,YAAY,iBAEjC,MAAM,4BACM,KAAK,SAAS,KAAK,SAAS,OAAO,GAAG,MAAM,MAAM;;iBAGjD;WACN,OAAO;;WAEP,SAAS;;;YAUR;WACG;;WACA;WAA0B,UAAU,cAAc;;;;;;;WAMlD;WACA,QAAQ;WACR,WAAW;;;qBAIb,cAAW,MAAU;;;;;;;;;iBAUjB,kBAAkB,UAAU;GAC1C,QAAQ,IAAI;WACJ;WACA;;;KAQN,MAAM,UAAU,cAAc;WACxB,QAAQ,UAAU;WAClB,OAAO,SAAS;MACrB,YAAY,MAAM;UAEd,QAAQ,UAAU;WACjB;WACA,OAAO,qBAAqB,wBAAwB,SAAS;;;;;;;;;;;qBAiE3D,YAAa,UAAU,WAAS,YACjC,OACH,MAAM,IAAE,SACN,QAAQ,OAChB,kBAAkB;;qBAkFR,eAAY,QAAY,cAAY,cAAc;;qBAOlD,eAAY,YACX,cAAc,YAAU,QAC5B,QAAM,YACHA,sBACV;;;;;;;;qBAyCU,QAAK,QACR,WAAS,QACT,QAAM,YACHA,sBACV;;;;;;;;;qBAUU,aAAU,OACd,YAAY,sBAAoB,OAChC,SAAS,0BAAwB,YAC7BA,sBACV;;;;;;;;qBAsCU,QAAS,UAAU,WAAS,QAC/B,GAAC;WACW,YAAYA;MAC/B,UAAU,OAAO,OAAO,OAAO,KAAK"}
|
package/dist/invariant.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Option, Schema } from "effect";
|
|
1
|
+
import { Match, Option, Schema } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
3
|
import { put } from "./record.js";
|
|
4
4
|
import { storesNull, variantsOf } from "./variants.js";
|
|
5
5
|
import { remake, variantBases } from "./descriptor.js";
|
|
6
6
|
import { Expr, Query, dependenciesOf } from "./expr.js";
|
|
7
|
-
import {
|
|
7
|
+
import { kernelOperators } from "./memoryTable.js";
|
|
8
8
|
import { OperatorMissingError, truthOver } from "./evaluate.js";
|
|
9
9
|
// src/invariant.ts
|
|
10
10
|
/**
|
|
@@ -32,14 +32,17 @@ const Invariants = Metadata.key("foldkit-entity/invariants", {
|
|
|
32
32
|
});
|
|
33
33
|
/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
|
|
34
34
|
const readsBefore = (held) => held.before.length > 0;
|
|
35
|
-
const fail = (entity, message) => {
|
|
35
|
+
const fail$1 = (entity, message) => {
|
|
36
36
|
throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
|
|
37
37
|
};
|
|
38
38
|
/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */
|
|
39
39
|
const declareOn = (entity, id, build, options) => {
|
|
40
40
|
const fields = entity.fields;
|
|
41
41
|
const relations = entity.relations;
|
|
42
|
-
const links = Object.values(relations).flatMap((member) =>
|
|
42
|
+
const links = Object.values(relations).flatMap((member) => {
|
|
43
|
+
if (member._tag !== "Relation" || member.cardinality !== "one") return [];
|
|
44
|
+
return [member];
|
|
45
|
+
});
|
|
43
46
|
const nexts = [...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]), ...links.map((link) => [link.key, Expr.next(link)])];
|
|
44
47
|
const after = Object.fromEntries(nexts);
|
|
45
48
|
const predicate = build({
|
|
@@ -48,12 +51,12 @@ const declareOn = (entity, id, build, options) => {
|
|
|
48
51
|
});
|
|
49
52
|
const body = Query.from(entity).pipe(Query.where(predicate));
|
|
50
53
|
const dependencies = Query.dependencies(body);
|
|
51
|
-
if (dependencies.inputs.length > 0) fail(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
|
|
54
|
+
if (dependencies.inputs.length > 0) fail$1(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
|
|
52
55
|
const beforeReads = dependencies.predicate.map((field) => field.key);
|
|
53
56
|
const afterReads = dependencies.next.map((field) => field.key);
|
|
54
|
-
if (afterReads.length === 0) fail(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
|
|
57
|
+
if (afterReads.length === 0) fail$1(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
|
|
55
58
|
const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
|
|
56
|
-
for (const key of path) if (!Object.hasOwn(fields, key) && !links.some((link) => link.key === key)) fail(entity, `"${id}"'s path names "${key}", neither a field nor a one relation`);
|
|
59
|
+
for (const key of path) if (!Object.hasOwn(fields, key) && !links.some((link) => link.key === key)) fail$1(entity, `"${id}"'s path names "${key}", neither a field nor a one relation`);
|
|
57
60
|
return Object.freeze({
|
|
58
61
|
id,
|
|
59
62
|
entity: entity.name,
|
|
@@ -76,9 +79,9 @@ const declareOn = (entity, id, build, options) => {
|
|
|
76
79
|
const invariant = (id, build, options) => {
|
|
77
80
|
let attached;
|
|
78
81
|
const declared = (entity) => {
|
|
79
|
-
if (id.length === 0) fail(entity, "an invariant needs an id");
|
|
80
|
-
if (attached !== void 0 && attached !== entity.name) fail(entity, `"${id}" is declared on ${attached} already: declare it again for this Entity`);
|
|
81
|
-
if (invariantsOf(entity).some((held) => held.id === id)) fail(entity, `"${id}" is declared twice`);
|
|
82
|
+
if (id.length === 0) fail$1(entity, "an invariant needs an id");
|
|
83
|
+
if (attached !== void 0 && attached !== entity.name) fail$1(entity, `"${id}" is declared on ${attached} already: declare it again for this Entity`);
|
|
84
|
+
if (invariantsOf(entity).some((held) => held.id === id)) fail$1(entity, `"${id}" is declared twice`);
|
|
82
85
|
const held = declareOn(entity, id, build, options);
|
|
83
86
|
attached = entity.name;
|
|
84
87
|
return remake(entity, { metadata: Metadata.combine([entity.metadata, Invariants.of(held)]) });
|
|
@@ -136,7 +139,7 @@ const invariantsOf = (entity) => {
|
|
|
136
139
|
return cases.length === 0 ? declared : [...cases, ...declared];
|
|
137
140
|
};
|
|
138
141
|
/** `Entity.judge` against invariants already read, such as those a database binding keeps. */
|
|
139
|
-
const judgeAgainst = (invariants, change, operators =
|
|
142
|
+
const judgeAgainst = (invariants, change, operators = kernelOperators) => {
|
|
140
143
|
const missing = /* @__PURE__ */ new Set();
|
|
141
144
|
const unrun = /* @__PURE__ */ new Set();
|
|
142
145
|
const failures = [];
|
|
@@ -170,7 +173,7 @@ const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
|
|
|
170
173
|
* undecided, never valid. Without `before` (a create), transition invariants
|
|
171
174
|
* are not judged.
|
|
172
175
|
*/
|
|
173
|
-
const judge = (entity, change, operators =
|
|
176
|
+
const judge = (entity, change, operators = kernelOperators) => judgeAgainst(invariantsOf(entity), change, operators);
|
|
174
177
|
/**
|
|
175
178
|
* The row an input's value describes, judged under its Entity's state
|
|
176
179
|
* invariants: each key mapped to a field, encoded as the store holds it, and
|
|
@@ -179,7 +182,7 @@ const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(inv
|
|
|
179
182
|
* key left out) is undecided, so a partial input is never called valid on its
|
|
180
183
|
* account. It has no row before, so it judges no transition.
|
|
181
184
|
*/
|
|
182
|
-
const judgeInput = (input, value, operators =
|
|
185
|
+
const judgeInput = (input, value, operators = kernelOperators) => {
|
|
183
186
|
const invariants = invariantsOf(input.entity);
|
|
184
187
|
if (invariants.length === 0) return { _tag: "Valid" };
|
|
185
188
|
const members = input.members;
|
|
@@ -188,7 +191,7 @@ const judgeInput = (input, value, operators = Operators.kernel) => {
|
|
|
188
191
|
if (!Object.hasOwn(value, key)) continue;
|
|
189
192
|
if (member._tag === "RelationInput" && member.relation.cardinality === "one") {
|
|
190
193
|
const given = value[key];
|
|
191
|
-
const id = Option.isOption(given) ? Option.
|
|
194
|
+
const id = Option.isOption(given) ? Option.getOrUndefined(given) : given;
|
|
192
195
|
if (id === null || typeof id === "string") put(row, member.relation.key, id);
|
|
193
196
|
continue;
|
|
194
197
|
}
|
|
@@ -212,7 +215,7 @@ const check = (entity, options = {}) => {
|
|
|
212
215
|
const predicates = invariantsOf(entity).map((held) => held.predicate);
|
|
213
216
|
const missing = Expr.unsupported(predicates, {
|
|
214
217
|
operations: dependenciesOf(...predicates).operations,
|
|
215
|
-
operators: options.operators ??
|
|
218
|
+
operators: options.operators ?? kernelOperators
|
|
216
219
|
});
|
|
217
220
|
if (missing.length > 0) throw new Error(`[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(", ")}, which the operator table does not run; pass one that does as \`operators\``);
|
|
218
221
|
return Schema.makeFilter((value) => {
|
|
@@ -224,11 +227,14 @@ const check = (entity, options = {}) => {
|
|
|
224
227
|
put(row, key, Schema.encodeUnknownSync(field.schema)(decoded[key]));
|
|
225
228
|
}
|
|
226
229
|
const judged = judge(entity, { after: row }, options.operators);
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
230
|
+
return Match.valueTags(judged, {
|
|
231
|
+
Invalid: ({ failures }) => failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
|
|
232
|
+
path: [key],
|
|
233
|
+
issue: failure.message
|
|
234
|
+
}))),
|
|
235
|
+
Valid: () => void 0,
|
|
236
|
+
Undecided: () => void 0
|
|
237
|
+
});
|
|
232
238
|
});
|
|
233
239
|
};
|
|
234
240
|
export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, readsBefore };
|