foldkit-entity 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,5 @@
1
1
  import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
2
  import { Metadata } from "foldkit-metadata";
3
- //#region src/shape.ts
4
- const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
5
- const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
6
- /** What a schema's AST holds, read through Effect's own guards. */
7
- const SchemaShape = {
8
- /** True for the `null` and `undefined` members that make a schema optional. */
9
- isNullish,
10
- /**
11
- * The members of a schema with `null` and `undefined` set aside, so optional
12
- * text is still text; a schema that is not a union is its one member.
13
- */
14
- present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
15
- /** True when every value the schema admits is a string. */
16
- isText
17
- };
18
- //#endregion
19
3
  //#region src/collation.ts
20
4
  /**
21
5
  * How text compares when a query orders by it, declared rather than left to
@@ -109,7 +93,7 @@ const isPredicate = (value) => predicateTags.has(tagOf(value));
109
93
  const toOperand = (value) => {
110
94
  const tag = tagOf(value);
111
95
  if (tag === "Field") return fieldExpr(value);
112
- if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
96
+ if (tag === "Literal" || tag === "Input" || tag === "Next" || predicateTags.has(tag)) return value;
113
97
  return literal(value);
114
98
  };
115
99
  /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
@@ -144,6 +128,7 @@ const literalKind = (value) => {
144
128
  /** How a side orders, read from its encoded form. */
145
129
  const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
146
130
  Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
131
+ Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
147
132
  Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
148
133
  Literal: ({ value }) => literalKind(value)
149
134
  }));
@@ -159,7 +144,7 @@ const collationFor = (step, left, right, given) => {
159
144
  const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
160
145
  if (kinds.has("none") || kinds.size > 1) throw new Error(`[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`);
161
146
  if (!kinds.has("text")) return Option.none();
162
- const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.orElse(() => [])));
147
+ const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.tag("Next", (next) => [next.field]), Match.orElse(() => [])));
163
148
  const [first] = fields;
164
149
  if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, whose collation would say how it orders`);
165
150
  const named = fields.map((field) => `${field.owner.name}.${field.key}`).join(" and ");
@@ -223,6 +208,14 @@ const Expr = {
223
208
  key,
224
209
  schema
225
210
  }),
211
+ /**
212
+ * A field as the row a write would leave holds it: what `Entity.invariant`'s
213
+ * builder hands out as `after`.
214
+ */
215
+ next: (field) => node({
216
+ _tag: "Next",
217
+ field: fieldExpr(field)
218
+ }),
226
219
  /** One field of one Entity, as a scalar. */
227
220
  field: (field) => fieldExpr(field),
228
221
  /**
@@ -363,7 +356,52 @@ const Expr = {
363
356
  */
364
357
  whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
365
358
  /** An expression as readable text; see `showExpr` for what it is and is not. */
366
- show: (node) => showExpr(node)
359
+ show: (node) => showExpr(node),
360
+ /**
361
+ * The predicate with each field after a write (`Next`) that `values` names,
362
+ * by key, read as that value: how an invariant is judged where the
363
+ * write's new values are known. A field it does not name stays `Next`, for
364
+ * the interpreter to read as the row after holds it.
365
+ */
366
+ substituteNext: (predicate, values) => substituted(predicate, (operand) => Match.value(operand).pipe(Match.tag("Next", ({ field }) => Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand), Match.orElse(() => operand)))
367
+ };
368
+ const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : rewrite(side);
369
+ const substituted = (predicate, rewrite) => {
370
+ switch (predicate._tag) {
371
+ case "Eq": return node({
372
+ ...predicate,
373
+ left: substitutedSide(predicate.left, rewrite),
374
+ right: substitutedSide(predicate.right, rewrite)
375
+ });
376
+ case "Null": return node({
377
+ ...predicate,
378
+ operand: rewrite(predicate.operand)
379
+ });
380
+ case "Contains": return node({
381
+ ...predicate,
382
+ value: rewrite(predicate.value),
383
+ search: substitutedSide(predicate.search, rewrite)
384
+ });
385
+ case "In": return node({
386
+ ...predicate,
387
+ value: rewrite(predicate.value),
388
+ among: rewrite(predicate.among)
389
+ });
390
+ case "And":
391
+ case "Or": return node({
392
+ ...predicate,
393
+ operands: Array$1.map(predicate.operands, (operand) => substituted(operand, rewrite))
394
+ });
395
+ case "Not": return node({
396
+ ...predicate,
397
+ operand: substituted(predicate.operand, rewrite)
398
+ });
399
+ case "Compare": return node({
400
+ ...predicate,
401
+ left: rewrite(predicate.left),
402
+ right: rewrite(predicate.right)
403
+ });
404
+ }
367
405
  };
368
406
  /** A term, its nulls placed by `options` or by the direction's default. */
369
407
  const term = (direction, expr, options = {}) => node({
@@ -468,6 +506,22 @@ const walk = (expr, found) => {
468
506
  case "Input":
469
507
  found.inputs.add(expr.key);
470
508
  return;
509
+ case "Next": {
510
+ found.operations.add("next");
511
+ const { field } = expr;
512
+ const byKey = found.next.get(field.owner.token) ?? /* @__PURE__ */ new Map();
513
+ found.next.set(field.owner.token, byKey);
514
+ if (!byKey.has(field.key)) {
515
+ const read = {
516
+ entity: field.owner.name,
517
+ key: field.key,
518
+ owner: field.owner
519
+ };
520
+ byKey.set(field.key, read);
521
+ found.nextOrder.push(read);
522
+ }
523
+ return;
524
+ }
471
525
  case "Eq":
472
526
  found.operations.add("eq");
473
527
  walk(expr.left, found);
@@ -524,11 +578,14 @@ const dependenciesOf = (...nodes) => {
524
578
  fields: /* @__PURE__ */ new Map(),
525
579
  order: [],
526
580
  inputs: /* @__PURE__ */ new Set(),
581
+ next: /* @__PURE__ */ new Map(),
582
+ nextOrder: [],
527
583
  operations: /* @__PURE__ */ new Set()
528
584
  };
529
585
  for (const term of nodes) walk(term, found);
530
586
  return {
531
587
  fields: found.order,
588
+ next: found.nextOrder,
532
589
  inputs: [...found.inputs],
533
590
  operations: [...found.operations]
534
591
  };
@@ -541,6 +598,9 @@ const fieldsIn = function* (expr, seen) {
541
598
  case "Field":
542
599
  yield expr;
543
600
  return;
601
+ case "Next":
602
+ yield expr.field;
603
+ return;
544
604
  case "Literal":
545
605
  case "Input": return;
546
606
  case "Eq":
@@ -599,7 +659,8 @@ const childrenOf = (expr) => {
599
659
  switch (expr._tag) {
600
660
  case "Literal":
601
661
  case "Field":
602
- case "Input": return [];
662
+ case "Input":
663
+ case "Next": return [];
603
664
  case "Eq": return [expr.left, expr.right];
604
665
  case "Null": return [expr.operand];
605
666
  case "Contains": return [expr.value, expr.search];
@@ -763,6 +824,7 @@ const showExpr = (node) => {
763
824
  case "Literal": return JSON.stringify(node.value) ?? String(node.value);
764
825
  case "Field": return `${node.owner.name}.${node.key}`;
765
826
  case "Input": return `$${node.key}`;
827
+ case "Next": return `next ${node.field.owner.name}.${node.field.key}`;
766
828
  case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
767
829
  case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
768
830
  case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
@@ -786,45 +848,6 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
786
848
  }), Match.orElse(() => showExpr(node)));
787
849
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
788
850
  //#endregion
789
- //#region src/readFilter.ts
790
- /**
791
- * The members a server filters an Entity's rows by under a rule the client
792
- * does not run, such as an authorization rule. A client that places rows in
793
- * a list judges membership by the list's body; a change to one of these
794
- * members can move a row into or out of what the server lists, which only
795
- * the server can say. Declared by whoever owns the rule (`foldkit-guard`
796
- * attaches it), read by whoever places (`foldkit-remote`).
797
- */
798
- const key = Metadata.key("foldkit-entity/read-filter", {
799
- merge: (lists) => [[...new Set(lists.flat())]],
800
- summarize: (members) => members.join(", ")
801
- });
802
- const ReadFilter = {
803
- /** Entity metadata: the rows the server lists depend on these members. */
804
- of: (members) => key.of(members),
805
- /** The members an Entity's metadata names, every attachment's together. */
806
- members: (metadata) => key.get(metadata)[0] ?? []
807
- };
808
- //#endregion
809
- //#region src/words.ts
810
- const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
811
- const Words = {
812
- /**
813
- * A schema's words, as a label and its help text. Under Effect 4 a checked
814
- * schema resolves to its last check's annotations, which say what the check
815
- * expects and carry no `title`, so a title given before the check is read from
816
- * the schema's own annotations. Read words through this, never through
817
- * `Schema.resolveAnnotations` directly.
818
- */
819
- of: (schema) => {
820
- const resolved = Schema.resolveAnnotations(schema) ?? {};
821
- const own = schema.ast.annotations ?? {};
822
- return {
823
- title: Option.orElse(text(resolved.title), () => text(own["title"])),
824
- description: Option.orElse(text(resolved.description), () => text(own["description"]))
825
- };
826
- } };
827
- //#endregion
828
851
  //#region src/evaluate.ts
829
852
  /**
830
853
  * The reference interpreter: a query body run over rows already in memory.
@@ -856,11 +879,12 @@ var QueryEvaluateError = class extends Error {
856
879
  this.name = "QueryEvaluateError";
857
880
  }
858
881
  };
859
- const valueOf = (node, row, input) => {
882
+ const valueOf = (node, scope) => {
860
883
  switch (node._tag) {
861
- case "Field": return row[node.key];
884
+ case "Field": return scope.row[node.key];
885
+ case "Next": return scope.next[node.field.key];
862
886
  case "Literal": return node.value;
863
- case "Input": return input[node.key];
887
+ case "Input": return scope.input[node.key];
864
888
  }
865
889
  };
866
890
  const isNull = (value) => value === null || value === void 0;
@@ -877,57 +901,57 @@ const NUL = String.fromCharCode(0);
877
901
  */
878
902
  const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
879
903
  /** A predicate used as a value is its own truth; anything else is its value. */
880
- const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
904
+ const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
881
905
  /**
882
906
  * A predicate compared as a value. SQL's unknown is null there too, so an
883
907
  * unknown compared to anything stays unknown rather than becoming false.
884
908
  */
885
909
  const truthValue = (truth) => truth === "unknown" ? null : truth;
886
- const holds = (node, row, input) => {
910
+ const holds = (node, scope) => {
887
911
  switch (node._tag) {
888
912
  case "Eq": {
889
- const left = sideOf(node.left, row, input);
890
- const right = sideOf(node.right, row, input);
913
+ const left = sideOf(node.left, scope);
914
+ const right = sideOf(node.right, scope);
891
915
  if (isNull(left) || isNull(right)) return "unknown";
892
916
  if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("an equality was given text holding a NUL character, which SQL text cannot hold portably");
893
917
  return left === right;
894
918
  }
895
- case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
919
+ case "Null": return isNull(valueOf(node.operand, scope)) !== node.present;
896
920
  case "Contains": {
897
- const value = valueOf(node.value, row, input);
898
- const search = sideOf(node.search, row, input);
921
+ const value = valueOf(node.value, scope);
922
+ const search = sideOf(node.search, scope);
899
923
  if (isNull(value) || isNull(search)) return "unknown";
900
924
  if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
901
925
  if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
902
926
  return foldAscii(value).includes(foldAscii(search));
903
927
  }
904
928
  case "In": {
905
- const among = valueOf(node.among, row, input);
929
+ const among = valueOf(node.among, scope);
906
930
  if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
907
931
  if (among.length === 0) return false;
908
- const value = valueOf(node.value, row, input);
932
+ const value = valueOf(node.value, scope);
909
933
  if (holdsNul(value) || among.some(holdsNul)) throw new QueryEvaluateError("a membership test was given text holding a NUL character, which SQL text cannot hold portably");
910
934
  if (isNull(value)) return "unknown";
911
935
  if (among.some((each) => each === value)) return true;
912
936
  return among.some(isNull) ? "unknown" : false;
913
937
  }
914
938
  case "And": {
915
- const truths = node.operands.map((operand) => holds(operand, row, input));
939
+ const truths = node.operands.map((operand) => holds(operand, scope));
916
940
  if (truths.includes(false)) return false;
917
941
  return truths.includes("unknown") ? "unknown" : true;
918
942
  }
919
943
  case "Or": {
920
- const truths = node.operands.map((operand) => holds(operand, row, input));
944
+ const truths = node.operands.map((operand) => holds(operand, scope));
921
945
  if (truths.includes(true)) return true;
922
946
  return truths.includes("unknown") ? "unknown" : false;
923
947
  }
924
948
  case "Not": {
925
- const truth = holds(node.operand, row, input);
949
+ const truth = holds(node.operand, scope);
926
950
  return truth === "unknown" ? "unknown" : !truth;
927
951
  }
928
952
  case "Compare": {
929
- const left = valueOf(node.left, row, input);
930
- const right = valueOf(node.right, row, input);
953
+ const left = valueOf(node.left, scope);
954
+ const right = valueOf(node.right, scope);
931
955
  if (isNull(left) || isNull(right)) return "unknown";
932
956
  if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
933
957
  const kind = typeof left;
@@ -948,13 +972,28 @@ const readsAField = /* @__PURE__ */ new WeakMap();
948
972
  const decided = (node, input) => {
949
973
  let reads = readsAField.get(node);
950
974
  if (reads === void 0) {
951
- reads = dependenciesOf(node).fields.length > 0;
975
+ const read = dependenciesOf(node);
976
+ reads = read.fields.length + read.next.length > 0;
952
977
  readsAField.set(node, reads);
953
978
  }
954
- return reads ? Option.none() : Option.some(holds(node, {}, input));
979
+ return reads ? Option.none() : Option.some(holds(node, {
980
+ row: {},
981
+ input,
982
+ next: {}
983
+ }));
955
984
  };
985
+ /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
986
+ const truthOver = (node, row, input = {}, next = {}) => holds(node, {
987
+ row,
988
+ input,
989
+ next
990
+ });
956
991
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
957
- const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
992
+ const matches = (body, row, input) => body.where.every((node) => holds(node, {
993
+ row,
994
+ input,
995
+ next: {}
996
+ }) === true);
958
997
  /** The kinds of value this interpreter orders by; every key of one term must share one. */
959
998
  const comparable = /* @__PURE__ */ new Set([
960
999
  "string",
@@ -1077,6 +1116,190 @@ const evaluate = (body, input, rows) => {
1077
1116
  return ordered(rows.filter((row) => matches(body, row, input)), Query.orderFor(body, input), body.entity.name);
1078
1117
  };
1079
1118
  //#endregion
1119
+ //#region src/invariant.ts
1120
+ /**
1121
+ * Invariants: what every stored row of an Entity must hold, and what every
1122
+ * change of one must, declared once on the Entity through its metadata and read
1123
+ * from there by each interpreter: the reference judge here, a Schema check, a
1124
+ * form, a server's writer.
1125
+ *
1126
+ * One is built over the row before a write (`before`, each field as `Expr.field`) and
1127
+ * the row after it (`after`, each field as `Expr.next`). What it reads decides
1128
+ * when it is judged:
1129
+ *
1130
+ * ```text
1131
+ * reads `after` only -> a state invariant: every create and update, a CHECK constraint
1132
+ * reads `before` too -> a transition invariant: every update, which has a row before
1133
+ * ```
1134
+ *
1135
+ * It reads no input and no principal. Who may write is a guard's; whether a
1136
+ * write applies now is its `when`'s.
1137
+ */
1138
+ const Invariants = Metadata.key("foldkit-entity/invariants", {
1139
+ merge: (values) => [...new Set(values)],
1140
+ summarize: (invariant) => invariant.id
1141
+ });
1142
+ /** Whether an invariant reads the row before, and so is judged only where there is one. */
1143
+ const readsBefore = (held) => held.before.length > 0;
1144
+ const fail$2 = (entity, message) => {
1145
+ throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
1146
+ };
1147
+ const invariant = (id, build, options) => Object.assign((entity) => {
1148
+ if (id.length === 0) fail$2(entity, "an invariant needs an id");
1149
+ if (invariantsOf(entity).some((held) => held.id === id)) fail$2(entity, `"${id}" is declared twice`);
1150
+ const fields = entity.fields;
1151
+ const after = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]));
1152
+ const predicate = build({
1153
+ before: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)])),
1154
+ after
1155
+ });
1156
+ const body = Query.from(entity).pipe(Query.where(predicate));
1157
+ const dependencies = Query.dependencies(body);
1158
+ if (dependencies.inputs.length > 0) fail$2(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
1159
+ const beforeReads = dependencies.predicate.map((field) => field.key);
1160
+ const afterReads = dependencies.next.map((field) => field.key);
1161
+ if (afterReads.length === 0) fail$2(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
1162
+ const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
1163
+ for (const key of path) if (!Object.hasOwn(fields, key)) fail$2(entity, `"${id}"'s path names "${key}", not a field`);
1164
+ return entity.pipe(Entity.annotate(Invariants.of(Object.freeze({
1165
+ id,
1166
+ predicate,
1167
+ message: options.message,
1168
+ path: Object.freeze([...path]),
1169
+ before: Object.freeze(beforeReads),
1170
+ after: Object.freeze(afterReads)
1171
+ }))));
1172
+ }, { id });
1173
+ const invariantsOf = (entity) => Invariants.get(entity.metadata);
1174
+ /** `judge` with the invariants given, as a binding that keeps them holds them. */
1175
+ const judgeAgainst = (invariants, change) => {
1176
+ const missing = /* @__PURE__ */ new Set();
1177
+ const failures = [];
1178
+ const { after, before } = change;
1179
+ for (const held of invariants) {
1180
+ if (readsBefore(held) && before === void 0) continue;
1181
+ const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
1182
+ if (absent.length > 0) absent.forEach((key) => missing.add(key));
1183
+ else if (truthOver(held.predicate, before ?? {}, {}, after) !== true) failures.push(held);
1184
+ }
1185
+ if (failures.length > 0) return {
1186
+ _tag: "Invalid",
1187
+ failures
1188
+ };
1189
+ if (missing.size > 0) return {
1190
+ _tag: "Undecided",
1191
+ fields: [...missing]
1192
+ };
1193
+ return { _tag: "Valid" };
1194
+ };
1195
+ /**
1196
+ * A row, or a change, under every invariant (each row as the store holds it,
1197
+ * encoded): valid only when each is true. SQL's unknown, from a null, fails
1198
+ * one, as a `WHERE` drops the row; a field a row does not have leaves it
1199
+ * undecided, never valid. Without `before` (a create), transition invariants
1200
+ * are not judged.
1201
+ */
1202
+ const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
1203
+ /**
1204
+ * The row an input's value describes, judged under its Entity's state
1205
+ * invariants: each key mapped to a field, encoded as the store holds it. An
1206
+ * invariant over a field the input does not set (an `Option` holding nothing, a
1207
+ * key left out) is undecided, so a partial input is never called valid on its
1208
+ * account. It has no row before, so it judges no transition.
1209
+ */
1210
+ const judgeInput = (input, value) => {
1211
+ const invariants = invariantsOf(input.entity);
1212
+ if (invariants.length === 0) return { _tag: "Valid" };
1213
+ const members = input.members;
1214
+ const row = {};
1215
+ for (const [key, member] of Object.entries(members)) {
1216
+ if (member._tag !== "Field" || !Object.hasOwn(value, key)) continue;
1217
+ const encode = Schema.encodeUnknownOption(member.schema);
1218
+ const given = value[key];
1219
+ const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
1220
+ const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
1221
+ Option.map(Option.flatMap(held, () => stored), (encoded) => {
1222
+ row[member.key] = encoded;
1223
+ });
1224
+ }
1225
+ return judgeAgainst(invariants, { after: row });
1226
+ };
1227
+ /**
1228
+ * The Entity's state invariants as an Effect Schema check over its row type:
1229
+ * each failure at its path, with its message. The value is encoded first,
1230
+ * field by field, so it is judged as the store would hold it.
1231
+ */
1232
+ const check = (entity) => Schema.makeFilter((value) => {
1233
+ const fields = entity.fields;
1234
+ const decoded = value;
1235
+ const row = {};
1236
+ for (const [key, field] of Object.entries(fields)) {
1237
+ if (!Object.hasOwn(decoded, key)) continue;
1238
+ row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
1239
+ }
1240
+ const judged = judge(entity, { after: row });
1241
+ if (judged._tag !== "Invalid") return void 0;
1242
+ return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
1243
+ path: [key],
1244
+ issue: failure.message
1245
+ })));
1246
+ });
1247
+ //#endregion
1248
+ //#region src/shape.ts
1249
+ const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
1250
+ const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
1251
+ /** What a schema's AST holds, read through Effect's own guards. */
1252
+ const SchemaShape = {
1253
+ /** True for the `null` and `undefined` members that make a schema optional. */
1254
+ isNullish,
1255
+ /**
1256
+ * The members of a schema with `null` and `undefined` set aside, so optional
1257
+ * text is still text; a schema that is not a union is its one member.
1258
+ */
1259
+ present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
1260
+ /** True when every value the schema admits is a string. */
1261
+ isText
1262
+ };
1263
+ //#endregion
1264
+ //#region src/readFilter.ts
1265
+ /**
1266
+ * The members a server filters an Entity's rows by under a rule the client
1267
+ * does not run, such as an authorization rule. A client that places rows in
1268
+ * a list judges membership by the list's body; a change to one of these
1269
+ * members can move a row into or out of what the server lists, which only
1270
+ * the server can say. Declared by whoever owns the rule (`foldkit-guard`
1271
+ * attaches it), read by whoever places (`foldkit-remote`).
1272
+ */
1273
+ const key = Metadata.key("foldkit-entity/read-filter", {
1274
+ merge: (lists) => [[...new Set(lists.flat())]],
1275
+ summarize: (members) => members.join(", ")
1276
+ });
1277
+ const ReadFilter = {
1278
+ /** Entity metadata: the rows the server lists depend on these members. */
1279
+ of: (members) => key.of(members),
1280
+ /** The members an Entity's metadata names, every attachment's together. */
1281
+ members: (metadata) => key.get(metadata)[0] ?? []
1282
+ };
1283
+ //#endregion
1284
+ //#region src/words.ts
1285
+ const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
1286
+ const Words = {
1287
+ /**
1288
+ * A schema's words, as a label and its help text. Under Effect 4 a checked
1289
+ * schema resolves to its last check's annotations, which say what the check
1290
+ * expects and carry no `title`, so a title given before the check is read from
1291
+ * the schema's own annotations. Read words through this, never through
1292
+ * `Schema.resolveAnnotations` directly.
1293
+ */
1294
+ of: (schema) => {
1295
+ const resolved = Schema.resolveAnnotations(schema) ?? {};
1296
+ const own = schema.ast.annotations ?? {};
1297
+ return {
1298
+ title: Option.orElse(text(resolved.title), () => text(own["title"])),
1299
+ description: Option.orElse(text(resolved.description), () => text(own["description"]))
1300
+ };
1301
+ } };
1302
+ //#endregion
1080
1303
  //#region src/write.ts
1081
1304
  /**
1082
1305
  * A write as a value: what an operation changes, declared over the input it
@@ -1093,6 +1316,13 @@ const evaluate = (body, input, rows) => {
1093
1316
  * It is authority someone declared, never something derived from an Entity: an
1094
1317
  * Entity having a field does not mean anyone may set it.
1095
1318
  */
1319
+ const update = (input, options) => settingSomething(declared("Update", input, options));
1320
+ const remove = (input, options) => {
1321
+ const write = declared("Delete", input, options);
1322
+ const named = [...write.sets, ...write.links][0];
1323
+ if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
1324
+ return write;
1325
+ };
1096
1326
  const fail$1 = (input, message) => {
1097
1327
  throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
1098
1328
  };
@@ -1151,6 +1381,15 @@ const declared = (kind, input, options) => {
1151
1381
  case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
1152
1382
  }
1153
1383
  }
1384
+ const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
1385
+ const placeholders = Object.create(null);
1386
+ for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
1387
+ return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
1388
+ });
1389
+ const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
1390
+ expect,
1391
+ sets
1392
+ })]);
1154
1393
  return Object.freeze({
1155
1394
  _tag: kind,
1156
1395
  input,
@@ -1159,12 +1398,38 @@ const declared = (kind, input, options) => {
1159
1398
  field: id
1160
1399
  }),
1161
1400
  expect,
1401
+ when,
1162
1402
  sets: Object.freeze(sets),
1403
+ increments: Object.freeze(increments),
1163
1404
  links: Object.freeze(links)
1164
1405
  });
1165
1406
  };
1407
+ /** Whether a value's stored form is a plain number. */
1408
+ const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
1409
+ /**
1410
+ * One increment, checked: a field of the Entity stored as a number, written
1411
+ * by nothing else, moved by an unmapped input key whose value is a number.
1412
+ */
1413
+ const incrementOf = (input, fieldKey, key, declared) => {
1414
+ const fields = input.entity.fields;
1415
+ const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
1416
+ if (field === void 0) return fail$1(input, `increments "${fieldKey}", which is not a field`);
1417
+ if (fieldKey === "id") return fail$1(input, "increments the id");
1418
+ if (declared.expect?.field.key === fieldKey) return fail$1(input, `increments "${fieldKey}", the revision it expects`);
1419
+ if (declared.sets.some((set) => set.field.key === fieldKey)) return fail$1(input, `increments "${fieldKey}", which a key also sets`);
1420
+ if (!storedAsNumber(field.schema)) return fail$1(input, `increments "${fieldKey}", which is not stored as a number`);
1421
+ const member = membersOf(input)[key];
1422
+ if (member === void 0) return fail$1(input, `"${key}" is not a key of the input`);
1423
+ if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
1424
+ const amount = input.schema.fields[key];
1425
+ if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
1426
+ return Object.freeze({
1427
+ key,
1428
+ field
1429
+ });
1430
+ };
1166
1431
  /** An update or an insert that would write nothing is refused where it is declared. */
1167
- const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 ? fail$1(write.input, "it sets no field") : write;
1432
+ const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 ? fail$1(write.input, "it sets no field") : write;
1168
1433
  const Write = {
1169
1434
  /**
1170
1435
  * Sets, on the row whose id is the input's `id` key, every field the input
@@ -1179,10 +1444,12 @@ const Write = {
1179
1444
  * id it holds. Refused where it is written: an `id` that is not the Entity's
1180
1445
  * `id` field, a `many` relation or a nested key (not written by an update
1181
1446
  * yet), or nothing to set.
1447
+ *
1448
+ * `when` is what the row must hold for the update to land, checked where it
1449
+ * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
1450
+ * does not hold of is refused as unmet.
1182
1451
  */
1183
- update: (input, options) => {
1184
- return settingSomething(declared("Update", input, options));
1185
- },
1452
+ update,
1186
1453
  /**
1187
1454
  * Inserts the row whose id is the input's `id` key, an id the client chose,
1188
1455
  * with every field and `one` relation the input maps a key to. An insert
@@ -1196,14 +1463,9 @@ const Write = {
1196
1463
  * Deletes the row whose id is the input's `id` key, only while it is still at
1197
1464
  * the revision `expect` names, when it names one. It sets nothing, so a key
1198
1465
  * mapped to a member is refused where it is written. A row already gone (a
1199
- * retry) is gone.
1466
+ * retry) is gone. `when`, as an update's, is what the row must hold.
1200
1467
  */
1201
- delete: (input, options) => {
1202
- const write = declared("Delete", input, options);
1203
- const named = [...write.sets, ...write.links][0];
1204
- if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
1205
- return write;
1206
- },
1468
+ delete: remove,
1207
1469
  /**
1208
1470
  * The revision this input says the row was read at, encoded, with its field:
1209
1471
  * what an interpreter writes only a row still at. None for a write that
@@ -1214,7 +1476,24 @@ const Write = {
1214
1476
  revision: encoded(field, value[key])
1215
1477
  })),
1216
1478
  /** The members any invocation may write: what a query reading none of them cannot be changed by. */
1217
- writes: (write) => [...write.sets.map((set) => set.field), ...write.links.map((link) => link.relation)],
1479
+ writes: (write) => [
1480
+ ...write.sets.map((set) => set.field),
1481
+ ...write.increments.map((increment) => increment.field),
1482
+ ...write.links.map((link) => link.relation)
1483
+ ],
1484
+ /**
1485
+ * The fields a write reads from the row it writes: those its `when` reads,
1486
+ * each it increments, and the revision it expects. What an interpreter
1487
+ * must read, and what a startup check judges it could disclose.
1488
+ */
1489
+ reads: (write) => {
1490
+ const fields = /* @__PURE__ */ new Map();
1491
+ const add = (field) => fields.set(field.key, field);
1492
+ Option.map(write.when, (body) => Query.dependencies(body).predicate.forEach((field) => add(field)));
1493
+ write.increments.forEach((increment) => add(increment.field));
1494
+ if (write.expect !== void 0) add(write.expect.field);
1495
+ return [...fields.values()];
1496
+ },
1218
1497
  /**
1219
1498
  * The row this input writes and its new values, encoded as the store holds
1220
1499
  * them: the patch a client shows before the server answers. `keys`, when
@@ -1241,11 +1520,20 @@ const Write = {
1241
1520
  id: String(encoded(target.fields.id, id))
1242
1521
  }));
1243
1522
  }
1523
+ const increments = {};
1524
+ for (const { key, field } of write.increments) {
1525
+ if (!asked(key)) continue;
1526
+ const schema = write.input.schema.fields[key];
1527
+ Option.map(given(input[key]), (held) => {
1528
+ increments[field.key] = Schema.encodeUnknownSync(schema)(held);
1529
+ });
1530
+ }
1244
1531
  return {
1245
1532
  entity: write.input.entity.name,
1246
1533
  id: String(encoded(write.id.field, input[write.id.key])),
1247
1534
  values,
1248
- links
1535
+ links,
1536
+ increments
1249
1537
  };
1250
1538
  }
1251
1539
  };
@@ -1454,6 +1742,36 @@ const Entity = {
1454
1742
  ...entity,
1455
1743
  metadata: Metadata.combine([entity.metadata, metadata])
1456
1744
  }),
1745
+ /**
1746
+ * Declares what every stored row, or every change of one, must hold:
1747
+ * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
1748
+ * Expr.lte(after.reserved, after.quantity), { message })` over the row a
1749
+ * write leaves, or with `before` too over the change an update makes.
1750
+ * Refused where it is declared: an id declared twice, a predicate over another
1751
+ * Entity, one reading an input or nothing of `after` (that is a `when`), a path
1752
+ * naming no field.
1753
+ */
1754
+ invariant,
1755
+ /** The Entity's invariants, in the order they were declared. */
1756
+ invariants: invariantsOf,
1757
+ /**
1758
+ * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
1759
+ * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
1760
+ * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
1761
+ * one reads that a row lacks.
1762
+ */
1763
+ judge,
1764
+ /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
1765
+ readsBefore,
1766
+ /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
1767
+ judgeAgainst,
1768
+ /**
1769
+ * The row an `Entity.input`'s value describes, judged: what a form can say
1770
+ * before the server does. Undecided for an invariant over a field it leaves unset.
1771
+ */
1772
+ judgeInput,
1773
+ /** The state invariants as a Schema check over the row type, each failure at its path. */
1774
+ check,
1457
1775
  /** Attaches an interpreter's metadata to members, by key. */
1458
1776
  annotateMembers: (metadata) => (entity) => {
1459
1777
  const given = metadata;
@@ -1589,6 +1907,6 @@ const Relation = {
1589
1907
  };
1590
1908
  const Derived = { make: (schema) => ({ schema }) };
1591
1909
  //#endregion
1592
- export { SchemaShape as C, Collation as S, Order as _, SelectionPageTypeId as a, isPredicate as b, QueryEvaluateError as c, decided as d, evaluate as f, Expr as g, ReadFilter as h, Relation as i, assertSupported as l, Words as m, Entity as n, SelectionTypeId as o, supported as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, Query as v, maxQueryNodes as x, dependenciesOf as y };
1910
+ export { maxQueryNodes as C, isPredicate as S, truthOver as _, SelectionPageTypeId as a, Query as b, Words as c, QueryEvaluateError as d, assertSupported as f, supported as g, evaluate as h, Relation as i, ReadFilter as l, decided as m, Entity as n, SelectionTypeId as o, compareRows as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, Expr as v, Collation as w, dependenciesOf as x, Order as y };
1593
1911
 
1594
- //# sourceMappingURL=src-Iz7806gm.mjs.map
1912
+ //# sourceMappingURL=src-DwKdHZDu.mjs.map