foldkit-entity 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +582 -240
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +30 -4
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/conformance/operator.d.ts.map +1 -1
  6. package/dist/conformance/operator.js +13 -4
  7. package/dist/conformance/operator.js.map +1 -1
  8. package/dist/descriptor.d.ts +5 -1
  9. package/dist/descriptor.d.ts.map +1 -1
  10. package/dist/descriptor.js +6 -2
  11. package/dist/descriptor.js.map +1 -1
  12. package/dist/entity.d.ts +16 -3
  13. package/dist/entity.d.ts.map +1 -1
  14. package/dist/entity.js +44 -14
  15. package/dist/entity.js.map +1 -1
  16. package/dist/enumerate.d.ts +44 -0
  17. package/dist/enumerate.d.ts.map +1 -0
  18. package/dist/enumerate.js +128 -0
  19. package/dist/enumerate.js.map +1 -0
  20. package/dist/evaluate.d.ts +12 -6
  21. package/dist/evaluate.d.ts.map +1 -1
  22. package/dist/evaluate.js +48 -23
  23. package/dist/evaluate.js.map +1 -1
  24. package/dist/expr.d.ts +78 -22
  25. package/dist/expr.d.ts.map +1 -1
  26. package/dist/expr.js +86 -57
  27. package/dist/expr.js.map +1 -1
  28. package/dist/footprint.d.ts +120 -0
  29. package/dist/footprint.d.ts.map +1 -0
  30. package/dist/footprint.js +41 -0
  31. package/dist/footprint.js.map +1 -0
  32. package/dist/held.js +11 -3
  33. package/dist/held.js.map +1 -1
  34. package/dist/index.d.ts +24 -7
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -6
  37. package/dist/index.js.map +1 -1
  38. package/dist/invariant.d.ts +41 -11
  39. package/dist/invariant.d.ts.map +1 -1
  40. package/dist/invariant.js +102 -51
  41. package/dist/invariant.js.map +1 -1
  42. package/dist/law.d.ts.map +1 -1
  43. package/dist/law.js +3 -9
  44. package/dist/law.js.map +1 -1
  45. package/dist/lawCore.d.ts +42 -0
  46. package/dist/lawCore.d.ts.map +1 -0
  47. package/dist/lawCore.js +12 -0
  48. package/dist/lawCore.js.map +1 -0
  49. package/dist/lawIds.d.ts +15 -0
  50. package/dist/lawIds.d.ts.map +1 -0
  51. package/dist/lawIds.js +13 -0
  52. package/dist/lawIds.js.map +1 -0
  53. package/dist/laws.d.ts +308 -0
  54. package/dist/laws.d.ts.map +1 -0
  55. package/dist/laws.js +566 -0
  56. package/dist/laws.js.map +1 -0
  57. package/dist/memoryTable.d.ts +11 -0
  58. package/dist/memoryTable.d.ts.map +1 -0
  59. package/dist/memoryTable.js +69 -0
  60. package/dist/memoryTable.js.map +1 -0
  61. package/dist/operators.d.ts +1 -1
  62. package/dist/operators.d.ts.map +1 -1
  63. package/dist/operators.js +2 -66
  64. package/dist/operators.js.map +1 -1
  65. package/dist/refine.d.ts +64 -0
  66. package/dist/refine.d.ts.map +1 -0
  67. package/dist/refine.js +104 -0
  68. package/dist/refine.js.map +1 -0
  69. package/dist/rows.d.ts +15 -0
  70. package/dist/rows.d.ts.map +1 -0
  71. package/dist/rows.js +23 -0
  72. package/dist/rows.js.map +1 -0
  73. package/dist/sets.js.map +1 -1
  74. package/dist/uncollated.d.ts +10 -0
  75. package/dist/uncollated.d.ts.map +1 -0
  76. package/dist/uncollated.js +18 -0
  77. package/dist/uncollated.js.map +1 -0
  78. package/dist/write.d.ts +65 -7
  79. package/dist/write.d.ts.map +1 -1
  80. package/dist/write.js +128 -30
  81. package/dist/write.js.map +1 -1
  82. package/package.json +3 -3
package/dist/expr.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
+ import { EntityTypeId } from "./ids.js";
2
3
  import { own, put } from "./record.js";
3
4
  import { variantsOf } from "./variants.js";
4
5
  import { SchemaShape } from "./shape.js";
5
6
  import { absurd } from "effect/Function";
6
7
  import { Collation } from "./collation.js";
8
+ import { uncollatedText } from "./uncollated.js";
7
9
  import { now, viewer } from "./context.js";
8
- import { Law } from "./law.js";
10
+ import { Laws, lawKind } from "./lawCore.js";
9
11
  // src/expr.ts
10
12
  /**
11
13
  * `Expr` — a query's scalar computations as typed values.
@@ -204,16 +206,20 @@ const collationFor = (step, left, right, given) => {
204
206
  }));
205
207
  };
206
208
  /** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */
207
- const comparison = (operator) => (left, right, options = {}) => {
208
- const leftSide = toExpr(left, operator);
209
- const rightSide = toExpr(right, operator);
210
- return node({
211
- _tag: "Compare",
212
- operator,
213
- left: leftSide,
214
- right: rightSide,
215
- collation: collationFor(operator, leftSide, rightSide, Option.fromUndefinedOr(options.collation))
216
- });
209
+ const comparison = (operator) => {
210
+ const compare = (left, right, options = {}) => {
211
+ const leftSide = toExpr(left, operator);
212
+ const rightSide = toExpr(right, operator);
213
+ return node({
214
+ _tag: "Compare",
215
+ operator,
216
+ left: leftSide,
217
+ right: rightSide,
218
+ collation: collationFor(operator, leftSide, rightSide, Option.fromUndefinedOr(options.collation))
219
+ });
220
+ };
221
+ const step = (right, options) => (left) => compare(left, right, options);
222
+ return Object.assign(compare, { step });
217
223
  };
218
224
  /** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */
219
225
  const connected = (step, kind, given) => {
@@ -261,11 +267,11 @@ const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
261
267
  * whose text keeps none.
262
268
  */
263
269
  const lawProblem = (law, input, output, collation) => {
264
- const name = Law.describe(law).kind;
270
+ const name = lawKind(law);
265
271
  const binary = () => input.length === 2 ? Option.none() : Option.some(`${name} is a law of an operator of two arguments, and this one takes ${input.length}`);
266
272
  const decodes = (value, schema, what) => Schema.is(Schema.toEncoded(schema))(value) ? Option.none() : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`);
267
273
  const sides = (value, side) => Option.orElse(binary(), () => Option.orElse(side === "right" ? Option.none() : decodes(value, input[0], "left witness"), () => side === "left" ? Option.none() : decodes(value, input[1], "right witness")));
268
- return Law.$match(law, {
274
+ return Laws.$match(law, {
269
275
  Associative: binary,
270
276
  Commutative: binary,
271
277
  Idempotent: binary,
@@ -352,10 +358,13 @@ const callCollation = (id, rule, args) => {
352
358
  const fail = (what) => {
353
359
  throw new Error(`[foldkit-entity] ${id}: ${what}`);
354
360
  };
355
- const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
356
- arg,
357
- collation: collationOf(arg)
358
- }]);
361
+ const voters = args.flatMap((arg) => {
362
+ if (isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text") return [];
363
+ return [{
364
+ arg,
365
+ collation: collationOf(arg)
366
+ }];
367
+ });
359
368
  const collations = voters.flatMap(({ arg, collation }) => Option.match(collation, {
360
369
  onSome: (each) => [each],
361
370
  onNone: () => rule === "required" ? fail(`${showExpr(arg)} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`) : []
@@ -440,20 +449,24 @@ const makeOperator = (id, options) => {
440
449
  collation: carried
441
450
  });
442
451
  };
443
- return Object.freeze(Object.assign(call, { descriptor }));
452
+ const step = (...rest) => (self) => call(self, ...rest);
453
+ return Object.freeze(Object.assign(call, {
454
+ step,
455
+ descriptor
456
+ }));
444
457
  };
445
458
  /** Each defined call replaced by its expansion, deeply; built once per node. */
446
459
  const expandedCache = /* @__PURE__ */ new WeakMap();
447
460
  const expandedScalar = (scalar) => {
448
461
  const known = expandedCache.get(scalar);
449
462
  if (known !== void 0) return known;
450
- const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
463
+ const result = Match.value(scalar).pipe(Match.tag("Call", (call) => Option.match(call.expansion, {
451
464
  onSome: expandedScalar,
452
465
  onNone: () => node({
453
- ...scalar,
454
- args: scalar.args.map(expandedSide)
466
+ ...call,
467
+ args: call.args.map(expandedSide)
455
468
  })
456
- }) : scalar;
469
+ })), Match.orElse((other) => other));
457
470
  expandedCache.set(scalar, result);
458
471
  return result;
459
472
  };
@@ -627,6 +640,28 @@ const nextOf = ((member) => node({
627
640
  _tag: "Next",
628
641
  field: toOperand(member)
629
642
  }));
643
+ const eqCall = (left, right) => node({
644
+ _tag: "Eq",
645
+ left: toOperand(left),
646
+ right: toOperand(right)
647
+ });
648
+ const eq = Object.assign(eqCall, { step: ((right) => (left) => eqCall(left, right)) });
649
+ const containsCall = (value, search) => {
650
+ const operand = toOperand(search);
651
+ if (operand._tag !== "Literal" && operand._tag !== "Input") throw new Error(`[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`);
652
+ return node({
653
+ _tag: "Contains",
654
+ value: toExpr(value, "contains"),
655
+ search: operand
656
+ });
657
+ };
658
+ const contains = Object.assign(containsCall, { step: ((search) => (value) => containsCall(value, search)) });
659
+ const inCall = (value, among) => node({
660
+ _tag: "In",
661
+ value: toExpr(value, "in"),
662
+ among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
663
+ });
664
+ const inAmong = Object.assign(inCall, { step: ((among) => (value) => inCall(value, among)) });
630
665
  const Expr = {
631
666
  /**
632
667
  * An operator, defined by what a call of it means: `definedAs` builds that
@@ -790,11 +825,7 @@ const Expr = {
790
825
  * Expr.eq(Post.fields.status, 'active')
791
826
  * ```
792
827
  */
793
- eq: (left, right) => node({
794
- _tag: "Eq",
795
- left: toOperand(left),
796
- right: toOperand(right)
797
- }),
828
+ eq,
798
829
  /**
799
830
  * Whether a field holds no value. Its opposite is `isNotNull`; both are the
800
831
  * one node, since a query asks which of the two it means, and `is not null`
@@ -827,15 +858,7 @@ const Expr = {
827
858
  * nullable column that should match everything on an empty search says so:
828
859
  * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
829
860
  */
830
- contains: (value, search) => {
831
- const operand = toOperand(search);
832
- if (operand._tag !== "Literal" && operand._tag !== "Input") throw new Error(`[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`);
833
- return node({
834
- _tag: "Contains",
835
- value: toExpr(value, "contains"),
836
- search: operand
837
- });
838
- },
861
+ contains,
839
862
  /**
840
863
  * Whether a value is one of `among`: a list written out, or an input whose
841
864
  * value is one. Each element is compared as `eq` compares.
@@ -849,11 +872,7 @@ const Expr = {
849
872
  * holding a null, and an empty list matches no row. A list written out is
850
873
  * copied, so changing the array afterwards does not change the query.
851
874
  */
852
- in: (value, among) => node({
853
- _tag: "In",
854
- value: toExpr(value, "in"),
855
- among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
856
- }),
875
+ in: inAmong,
857
876
  /**
858
877
  * `left` orders before `right`. Numbers compare as numbers; text compares
859
878
  * under a collation, the one given or the field's declared one, which must be
@@ -936,11 +955,11 @@ const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side,
936
955
  * A scalar rewritten: a call's arguments and expansion each, so a field read
937
956
  * under it is rewritten as one read directly is; anything else by `rewrite`.
938
957
  */
939
- const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
940
- ...scalar,
941
- args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
942
- expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
943
- }) : rewrite(scalar);
958
+ const substitutedScalar = (scalar, rewrite) => Match.value(scalar).pipe(Match.tag("Call", (call) => node({
959
+ ...call,
960
+ args: Object.freeze(call.args.map((arg) => substitutedSide(arg, rewrite))),
961
+ expansion: Option.map(call.expansion, (expansion) => substitutedScalar(expansion, rewrite))
962
+ })), Match.orElse((other) => rewrite(other)));
944
963
  const substituted = (predicate, rewrite) => {
945
964
  switch (predicate._tag) {
946
965
  case "Eq": return node({
@@ -1076,18 +1095,12 @@ const notPlaceable = (reason) => Object.freeze({
1076
1095
  _tag: "NotPlaceable",
1077
1096
  reason
1078
1097
  });
1079
- /**
1080
- * Whether values encoded by `ast` order the same everywhere: numbers and
1081
- * booleans, never text. A null among them does too: where it goes is said on
1082
- * every order term.
1083
- */
1084
- const ordersIntrinsically = (ast) => SchemaAST.isNumber(ast) || SchemaAST.isBoolean(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal !== "string" || SchemaAST.isUnion(ast) && ast.types.every((member) => SchemaAST.isNull(member) || ordersIntrinsically(member));
1085
1098
  /** Why a term cannot be placed by a client running `operators`, if it cannot. */
1086
1099
  const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
1087
1100
  const missing = missingFrom(dependenciesOf(call).operators, operators);
1088
1101
  return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
1089
1102
  }), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
1090
- onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
1103
+ onNone: () => uncollatedText(orderTerm),
1091
1104
  onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
1092
1105
  Binary: () => Option.none(),
1093
1106
  AsciiFold: () => Option.none(),
@@ -1343,7 +1356,10 @@ const fieldsIn = function* (expr, seen) {
1343
1356
  */
1344
1357
  const checkOwnership = (step, what, entity, nodes) => {
1345
1358
  const seen = /* @__PURE__ */ new Set();
1346
- for (const term of nodes) for (const field of fieldsIn(term, seen)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
1359
+ for (const term of nodes) for (const field of fieldsIn(term, seen)) if (field.owner.token !== entity.identity.token) {
1360
+ const namesake = field.owner.name === entity.name ? `: the field belongs to another Entity defined with that name, and two definitions are two Entities` : "";
1361
+ throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}${namesake}`);
1362
+ }
1347
1363
  };
1348
1364
  /**
1349
1365
  * The most nodes a query's predicates may hold once every shared node is
@@ -1412,8 +1428,11 @@ const checkSize = (step, where, orderBy) => {
1412
1428
  if ([...where, ...terms].reduce((sum, each) => sum + expandedSize(each, sizes), 0) > 1e3) throw new Error(`[foldkit-entity] Query.${step}: the query expands to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`);
1413
1429
  };
1414
1430
  const Query = {
1415
- /** Every row of an Entity: the query each transformation narrows. */
1416
- from: (entity) => query(entity, [], []),
1431
+ /**
1432
+ * Every row of an Entity, the query each transformation narrows; or every
1433
+ * row in a state of one (`Query.from(Draft)`), its predicate in `where`.
1434
+ */
1435
+ from: (source) => isRefinement(source) ? query(source.entity, [source.predicate], []) : query(source, [], []),
1417
1436
  /**
1418
1437
  * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
1419
1438
  * second never replaces the first — so a fragment can be written once and
@@ -1549,6 +1568,8 @@ const Query = {
1549
1568
  * that *is* the whole expression is not: nothing encloses it.
1550
1569
  */
1551
1570
  const showExpr = (node) => {
1571
+ const name = names.get(node);
1572
+ if (name !== void 0) return name;
1552
1573
  switch (node._tag) {
1553
1574
  case "Literal": return JSON.stringify(node.value) ?? String(node.value);
1554
1575
  case "Field": return `${node.owner.name}.${node.key}`;
@@ -1586,6 +1607,14 @@ const showExpr = (node) => {
1586
1607
  }
1587
1608
  }
1588
1609
  };
1610
+ /** Whether `Query.from` was given a state of an Entity rather than an Entity. */
1611
+ const isRefinement = (source) => !(EntityTypeId in source);
1612
+ /** The names `Expr.show` prints a refinement's predicates by (`Product.Draft`), in place of their body. */
1613
+ const names = /* @__PURE__ */ new WeakMap();
1614
+ /** Prints `node` as `name`: what `Entity.refine` names its predicates. */
1615
+ const nameNode = (node, name) => {
1616
+ names.set(node, name);
1617
+ };
1589
1618
  /**
1590
1619
  * Where an exists starts on the judged row: the relation its path follows
1591
1620
  * first, or, asked of the row itself, its id, which the pointing rows hold.
@@ -1625,6 +1654,6 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
1625
1654
  Or: () => `(${showExpr(node)})`
1626
1655
  }), Match.orElse(() => showExpr(node)));
1627
1656
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
1628
- export { Expr, Order, Query, dependenciesOf, isPredicate, maxPathLength, maxQueryNodes, missingName, noOperators };
1657
+ export { Expr, Order, Query, dependenciesOf, isPredicate, maxPathLength, maxQueryNodes, missingName, nameNode, noOperators };
1629
1658
 
1630
1659
  //# sourceMappingURL=expr.js.map