@effect-dynamodb/schema 1.39.0 → 1.41.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 (122) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +12 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +48 -7
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js +34 -16
  8. package/dist/DynamoModel.js.map +1 -1
  9. package/dist/DynamoSchema.d.ts +25 -0
  10. package/dist/DynamoSchema.d.ts.map +1 -1
  11. package/dist/DynamoSchema.js.map +1 -1
  12. package/dist/Entity.d.ts +66 -11
  13. package/dist/Entity.d.ts.map +1 -1
  14. package/dist/Entity.js +261 -34
  15. package/dist/Entity.js.map +1 -1
  16. package/dist/Errors.d.ts +61 -4
  17. package/dist/Errors.d.ts.map +1 -1
  18. package/dist/Errors.js +83 -6
  19. package/dist/Errors.js.map +1 -1
  20. package/dist/KeyComposer.d.ts +196 -5
  21. package/dist/KeyComposer.d.ts.map +1 -1
  22. package/dist/KeyComposer.js +490 -54
  23. package/dist/KeyComposer.js.map +1 -1
  24. package/dist/VectorIndex.d.ts.map +1 -1
  25. package/dist/VectorIndex.js +5 -4
  26. package/dist/VectorIndex.js.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/internal/AggregateEdges.d.ts +3 -3
  32. package/dist/internal/AggregateSchemas.d.ts +306 -14
  33. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  34. package/dist/internal/AggregateSchemas.js +733 -54
  35. package/dist/internal/AggregateSchemas.js.map +1 -1
  36. package/dist/internal/AggregateTypes.d.ts +396 -36
  37. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  38. package/dist/internal/CompositeCodec.d.ts +298 -8
  39. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  40. package/dist/internal/CompositeCodec.js +940 -34
  41. package/dist/internal/CompositeCodec.js.map +1 -1
  42. package/dist/internal/EffectInstances.d.ts +87 -0
  43. package/dist/internal/EffectInstances.d.ts.map +1 -0
  44. package/dist/internal/EffectInstances.js +662 -0
  45. package/dist/internal/EffectInstances.js.map +1 -0
  46. package/dist/internal/EntityPacked.d.ts.map +1 -1
  47. package/dist/internal/EntityPacked.js +5 -4
  48. package/dist/internal/EntityPacked.js.map +1 -1
  49. package/dist/internal/EntitySchemas.d.ts +239 -30
  50. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  51. package/dist/internal/EntitySchemas.js +1600 -197
  52. package/dist/internal/EntitySchemas.js.map +1 -1
  53. package/dist/internal/EntityTypes.d.ts +114 -25
  54. package/dist/internal/EntityTypes.d.ts.map +1 -1
  55. package/dist/internal/FailingAsBefore.d.ts +25 -0
  56. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  57. package/dist/internal/FailingAsBefore.js +42 -0
  58. package/dist/internal/FailingAsBefore.js.map +1 -0
  59. package/dist/internal/InstanceReads.d.ts +40 -0
  60. package/dist/internal/InstanceReads.d.ts.map +1 -0
  61. package/dist/internal/InstanceReads.js +183 -0
  62. package/dist/internal/InstanceReads.js.map +1 -0
  63. package/dist/internal/KeyReadings.d.ts +30 -0
  64. package/dist/internal/KeyReadings.d.ts.map +1 -0
  65. package/dist/internal/KeyReadings.js +99 -0
  66. package/dist/internal/KeyReadings.js.map +1 -0
  67. package/dist/internal/KeyText136.d.ts +4 -2
  68. package/dist/internal/KeyText136.d.ts.map +1 -1
  69. package/dist/internal/KeyText136.js +46 -13
  70. package/dist/internal/KeyText136.js.map +1 -1
  71. package/dist/internal/LostValues.d.ts +50 -0
  72. package/dist/internal/LostValues.d.ts.map +1 -0
  73. package/dist/internal/LostValues.js +465 -0
  74. package/dist/internal/LostValues.js.map +1 -0
  75. package/dist/internal/NumericKey.d.ts +21 -2
  76. package/dist/internal/NumericKey.d.ts.map +1 -1
  77. package/dist/internal/NumericKey.js +19 -1
  78. package/dist/internal/NumericKey.js.map +1 -1
  79. package/dist/internal/ObjectKeyText.d.ts +29 -0
  80. package/dist/internal/ObjectKeyText.d.ts.map +1 -0
  81. package/dist/internal/ObjectKeyText.js +50 -0
  82. package/dist/internal/ObjectKeyText.js.map +1 -0
  83. package/dist/internal/OwnNames.d.ts +205 -0
  84. package/dist/internal/OwnNames.d.ts.map +1 -0
  85. package/dist/internal/OwnNames.js +415 -0
  86. package/dist/internal/OwnNames.js.map +1 -0
  87. package/dist/internal/PackedCodec.d.ts +7 -1
  88. package/dist/internal/PackedCodec.d.ts.map +1 -1
  89. package/dist/internal/PackedCodec.js +83 -21
  90. package/dist/internal/PackedCodec.js.map +1 -1
  91. package/dist/internal/RestoredKeyText.d.ts +10 -0
  92. package/dist/internal/RestoredKeyText.d.ts.map +1 -0
  93. package/dist/internal/RestoredKeyText.js +50 -0
  94. package/dist/internal/RestoredKeyText.js.map +1 -0
  95. package/dist/internal/SchemaAccessors.d.ts +280 -1
  96. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  97. package/dist/internal/SchemaAccessors.js +1717 -1
  98. package/dist/internal/SchemaAccessors.js.map +1 -1
  99. package/dist/internal/SchemaIssue.d.ts +21 -0
  100. package/dist/internal/SchemaIssue.d.ts.map +1 -0
  101. package/dist/internal/SchemaIssue.js +34 -0
  102. package/dist/internal/SchemaIssue.js.map +1 -0
  103. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  104. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  105. package/dist/internal/SharedKeyAttribute.js +129 -13
  106. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  107. package/dist/internal/SparseKey.d.ts +46 -0
  108. package/dist/internal/SparseKey.d.ts.map +1 -0
  109. package/dist/internal/SparseKey.js +69 -0
  110. package/dist/internal/SparseKey.js.map +1 -0
  111. package/dist/internal/StoredForm.d.ts +139 -0
  112. package/dist/internal/StoredForm.d.ts.map +1 -0
  113. package/dist/internal/StoredForm.js +503 -0
  114. package/dist/internal/StoredForm.js.map +1 -0
  115. package/dist/internal/ZOrderCurve.d.ts.map +1 -1
  116. package/dist/internal/ZOrderCurve.js +2 -1
  117. package/dist/internal/ZOrderCurve.js.map +1 -1
  118. package/dist/internal/ZoneKeyText.d.ts +55 -0
  119. package/dist/internal/ZoneKeyText.d.ts.map +1 -0
  120. package/dist/internal/ZoneKeyText.js +264 -0
  121. package/dist/internal/ZoneKeyText.js.map +1 -0
  122. package/package.json +4 -4
@@ -32,8 +32,31 @@
32
32
  *
33
33
  * Not part of the public API.
34
34
  */
35
- import { Option, Schema, SchemaAST } from "effect";
36
- import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncoding, } from "./SchemaAccessors.js";
35
+ import { Equal, Option, Schema, SchemaAST } from "effect";
36
+ import { isProtoAbsent, substituteSchemaDeep } from "./EntitySchemas.js";
37
+ import { readingKeyInstances } from "./InstanceReads.js";
38
+ import { isStoredNaN, KeyValueError, STORED_NAN } from "./NumericKey.js";
39
+ import { given, keyEntries, ownValue, setOwn } from "./OwnNames.js";
40
+ import { getSchemaFields, hasEncodingTransformation, holdsPlainBigint, numericTypeWithStringEncoding, } from "./SchemaAccessors.js";
41
+ import { namesZone, zonesAsStored } from "./StoredForm.js";
42
+ /** The same encoded composite value: a scalar, or a `Date` of the same instant. */
43
+ const sameValue = (a, b) => Object.is(a, b) || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());
44
+ export { defaultObjectText, objectKeyRefusal } from "./ObjectKeyText.js";
45
+ /**
46
+ * The refusal of a composite's number its declared kind can't hold exactly (the
47
+ * `reason` {@link makeCompositeKeyForm} gives `onError`), `[EDD-9050]`. Thrown as
48
+ * a value key composition can't place (`KeyValueError`, as `NaN` is), so every
49
+ * path that takes the value fails with a `ValidationError`, nothing sent, rather
50
+ * than dying. `composite` names it: `Composite "n" on entity "E"`.
51
+ */
52
+ export const refuseInexact = (composite, value, reason) => {
53
+ throw new KeyValueError({
54
+ value,
55
+ reason,
56
+ message: `[EDD-9050] ${composite} has no key text: ${reason}, so a row storing it is one the ` +
57
+ `field can't read.`,
58
+ });
59
+ };
37
60
  /**
38
61
  * Build a `CompositeKeyForm` for a model/derived schema.
39
62
  *
@@ -43,7 +66,9 @@ import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncodi
43
66
  * already a wire-shaped string.
44
67
  * 2. **Numeric Type with string Encoded** — the rule's exception. Target is the
45
68
  * numeric Type value: keep a `number` / `bigint` as-is, otherwise `decode`
46
- * to reach it.
69
+ * to reach it. A `NaN` is handed on as `NumericKey.STORED_NAN`: the field
70
+ * stores it (`"NaN"`), which no other numeric field can, so with
71
+ * `escapeKeys` off it keeps the key text 1.36 gave it.
47
72
  * 3. **Anything else** — target is the Encoded value. A field with no encoding
48
73
  * transformation is identity by construction (a numeric one still coerced
49
74
  * to its declared kind, as in case 2) (`SchemaAST` documents
@@ -52,19 +77,46 @@ import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncodi
52
77
  * like `gte(t.status, "d")` on a `Schema.Literals` composite is deliberately
53
78
  * not a valid value and must not be rejected by a codec. Otherwise `encode`,
54
79
  * with `decode -> encode` as the fallback so an already-encoded value
55
- * round-trips to itself (`Entity.put`'s strategy).
80
+ * round-trips to itself (`Entity.put`'s strategy), and then, for a value
81
+ * neither takes, the same two from the numeric kind the Encoded side is
82
+ * stored as: a row read back holds a stored `bigint` as a number.
56
83
  *
57
- * `onError` fires when the value reaches neither target form — refuse loudly
58
- * rather than compose a key that silently matches nothing.
84
+ * A codec whose `encode` takes its own output (`x:` prepended,
85
+ * `Schema.StringFromBase64`, a number scaled) takes its stored text too, so
86
+ * `encode` alone can't tell the two sides apart. A value that is its own
87
+ * stored text (`encode(decode(value))` is the value) is that text, keyed as
88
+ * it is: `put` holds `"x:MiX"` for `"MiX"` and keys `x:mix`. Up to 1.39.0
89
+ * it was encoded once more, so `put` keyed `x:x:mix` (`text139` composes
90
+ * that, for `rekey`, and keeps an aggregate's keys, which only its own
91
+ * paths compose, from domain values). A domain value can be such a text as
92
+ * well (`"x:MiX"` itself): a path holding domain values encodes them first
93
+ * ({@link makeCompositeDomainKeyForm}), so the key form only ever sees
94
+ * stored text from it. A codec whose `encode` refuses its own output never
95
+ * reaches this: its stored text takes the `decode -> encode` fallback.
96
+ *
97
+ * `onError` fires when the value of an attribute a key is composed from
98
+ * reaches neither target form — refuse loudly rather than compose a key that
99
+ * silently matches nothing. `reason` says why, when it's a number its numeric
100
+ * kind can't hold exactly, which `onError` refuses with {@link refuseInexact}.
101
+ * `reads` names those attributes, when the records normalised hold others too
102
+ * (a whole row read back from DynamoDB): any other attribute's value is never
103
+ * key text, so one that reaches neither form is left as it is. Without `reads`,
104
+ * every attribute is one.
59
105
  */
60
- export const makeCompositeKeyForm = (source, onError) => {
106
+ export const makeCompositeKeyForm = (source, onError, options) => {
107
+ const keysStoredText = options?.text139 !== true;
61
108
  const fields = getSchemaFields(source);
62
109
  const cache = new Map();
110
+ const reads = options?.reads;
111
+ const refuse = (attr, value, reason) => reads === undefined || reads(attr) ? onError(attr, value, reason) : value;
112
+ /** `value` as `kind` holds it exactly, or refused (a row storing it is one `attr` can't read). */
113
+ const exactly = (attr, kind, value) => exactIn(kind, value) ??
114
+ refuse(attr, value, `${String(value)} is a value no ${kind} holds exactly`);
63
115
  const resolve = (attr) => {
64
116
  const cached = cache.get(attr);
65
117
  if (cached !== undefined)
66
118
  return cached;
67
- const field = fields?.[attr];
119
+ const field = declared(fields, attr);
68
120
  // Case 1.
69
121
  if (field === undefined) {
70
122
  cache.set(attr, null);
@@ -85,18 +137,17 @@ export const makeCompositeKeyForm = (source, onError) => {
85
137
  if (numericTypeWithStringEncoding(field)) {
86
138
  const wantsBigInt = SchemaAST.isBigInt(SchemaAST.toType(field.ast));
87
139
  const decode = Schema.decodeUnknownOption(codec);
140
+ const stored = (value) => storedNaNKeyForm(field, value);
88
141
  const fn = (value) => {
89
- if (typeof value === "bigint")
90
- return wantsBigInt ? value : Number(value);
91
- if (typeof value === "number") {
92
- if (!wantsBigInt)
93
- return value;
94
- return Number.isInteger(value) ? BigInt(value) : onError(attr, value);
142
+ if (isStoredNaN(value))
143
+ return value;
144
+ if (typeof value === "bigint" || typeof value === "number") {
145
+ return stored(exactly(attr, wantsBigInt ? "bigint" : "number", value));
95
146
  }
96
147
  const decoded = decode(value);
97
148
  if (Option.isSome(decoded))
98
- return decoded.value;
99
- return onError(attr, value);
149
+ return stored(decoded.value);
150
+ return refuse(attr, value);
100
151
  };
101
152
  cache.set(attr, fn);
102
153
  return fn;
@@ -106,19 +157,833 @@ export const makeCompositeKeyForm = (source, onError) => {
106
157
  // value unmarshalls as a number (and a `Schema.Number` past 2^53 as a
107
158
  // bigint), so a key re-derived from a stored row would compose at the
108
159
  // other kind's width.
160
+ // A union of kinds storing one numeric kind (`Union([String, BigInt])`) takes it the same way: a
161
+ // stored `N` can only have been that kind. One storing both is left: its value alone can't say.
162
+ // A number the kind can't hold exactly is refused, never rounded: a row holding one is one its
163
+ // field can't read (`rekey` reports it, and its sentinels stay where they are).
109
164
  if (!hasEncodingTransformation(field)) {
110
- const kind = keyFormValueKind(field);
111
- const fn = kind === "bigint"
112
- ? (value) => typeof value === "number" && Number.isInteger(value) ? BigInt(value) : value
113
- : kind === "number"
114
- ? (value) => (typeof value === "bigint" ? Number(value) : value)
115
- : null;
165
+ const declared = keyFormValueKind(field);
166
+ const kind = declared === "bigint" || declared === "number"
167
+ ? declared
168
+ : declared === undefined
169
+ ? onlyNumericKind(storedNumericKinds(field))
170
+ : undefined;
171
+ // A field encoding a zone to text inside it (a list of `TimeZoneNamedFromString`) is keyed by
172
+ // the value it stores, with each zone named as every key names one (`storedZoneText`).
173
+ const zoneText = storedZoneText(field);
174
+ const numeric = kind === undefined
175
+ ? undefined
176
+ : (value) => typeof value === "number" || typeof value === "bigint"
177
+ ? exactly(attr, kind, value)
178
+ : value;
179
+ const fn = zoneText === undefined
180
+ ? (numeric ?? null)
181
+ : (value) => {
182
+ const named = zoneText(value);
183
+ const keyed = named === undefined ? value : named;
184
+ return numeric === undefined ? keyed : numeric(keyed);
185
+ };
116
186
  cache.set(attr, fn);
117
187
  return fn;
118
188
  }
119
189
  // Case 3b — target is the Encoded side.
120
190
  const encode = Schema.encodeUnknownOption(codec);
121
191
  const decode = Schema.decodeUnknownOption(codec);
192
+ /** Is `value` its own stored text: what `encode` gives for what it decodes to? */
193
+ const isStoredText = (value) => {
194
+ const decoded = decode(value);
195
+ if (Option.isNone(decoded))
196
+ return false;
197
+ const reencoded = encode(decoded.value);
198
+ return Option.isSome(reencoded) && sameValue(reencoded.value, value);
199
+ };
200
+ // A zone's key text is its name as `storedZoneName` gives it, whichever Effect is installed:
201
+ // Effect's own string codecs encode the name a zone was made from on 4.1.3 (`Etc/UTC` where
202
+ // 4.1.2 encoded `UTC`), and the key encodes the zone 4.1.2 held (`zonesAsStored`). The stored
203
+ // attribute is the codec's, untouched.
204
+ const encodeNamed = (value) => encode(zonesAsStored(value));
205
+ const toEncoded = (value) => {
206
+ const direct = encodeNamed(value);
207
+ if (Option.isSome(direct)) {
208
+ // `encode` takes the value and changes it: a domain value, or, for a codec whose
209
+ // `encode` takes its own output, its stored text, which is its key text.
210
+ if (keysStoredText && !sameValue(direct.value, value) && isStoredText(value)) {
211
+ return Option.some(value);
212
+ }
213
+ return direct;
214
+ }
215
+ return Option.flatMap(decode(value), (decoded) => encodeNamed(decoded));
216
+ };
217
+ // The stored form, as case 3a takes it (`OptionFromNullOr(BigInt)`, a
218
+ // `BigInt` under a decoding default): asked only when the value as given
219
+ // reaches neither form. It is the value `put` handed this rule (the write
220
+ // path holds encoded records), so it takes the steps `put`'s value took.
221
+ const stored = storedNumericForm(field);
222
+ // A row read back holds a stored bigint beneath the field's step as a number
223
+ // (`Schema.Array(Schema.BigInt)` under a decoding default stores `[5n]`, which
224
+ // comes back `[5]`). A read lifts it back, so the value is taken as a read
225
+ // decodes it, and encoded again: asked last, of a value nothing else takes.
226
+ let readDecode;
227
+ const asRead = (value) => {
228
+ if (readDecode === undefined) {
229
+ readDecode = holdsPlainBigint(SchemaAST.toEncoded(field.ast)) ? readDecodeOf(field) : null;
230
+ }
231
+ return readDecode === null ? Option.none() : readDecode(value);
232
+ };
233
+ const fn = (value) => {
234
+ const given = toEncoded(value);
235
+ if (Option.isSome(given))
236
+ return given.value;
237
+ const lifted = stored?.(value);
238
+ if (lifted !== undefined) {
239
+ const fromStored = toEncoded(lifted);
240
+ if (Option.isSome(fromStored))
241
+ return fromStored.value;
242
+ }
243
+ const fromRead = Option.flatMap(asRead(value), (decoded) => encodeNamed(decoded));
244
+ if (Option.isSome(fromRead))
245
+ return fromRead.value;
246
+ return refuse(attr, value);
247
+ };
248
+ cache.set(attr, fn);
249
+ return fn;
250
+ };
251
+ // A value of a field storing a declaration may be one read back from a row, which the unmarshaller
252
+ // hands back as a plain map, list or set: it's taken as the field reads it first. Only for an
253
+ // attribute a key reads, when `reads` names them: no other is key text.
254
+ const readBacks = new Map();
255
+ const readBack = (attr) => {
256
+ if (!readBacks.has(attr)) {
257
+ const field = declared(fields, attr);
258
+ readBacks.set(attr, field === undefined ? undefined : storedFormOfDeclaration(field));
259
+ }
260
+ const fn = readBacks.get(attr);
261
+ return fn === undefined || reads === undefined || reads(attr) ? fn : undefined;
262
+ };
263
+ return (attr, value) => {
264
+ if (value === undefined || value === null)
265
+ return value;
266
+ const read = readBack(attr)?.(value);
267
+ const given = read === undefined ? value : read;
268
+ const fn = resolve(attr);
269
+ return fn === null ? given : fn(given);
270
+ };
271
+ };
272
+ /**
273
+ * Whether a schema's Encoded side holds a declaration anywhere (`Schema.Option`, `Schema.Result`,
274
+ * `Schema.ReadonlySet`, `Schema.Duration`, …): at its top, or in a member, property, element or
275
+ * suspension.
276
+ */
277
+ const holdsDeclaration = (ast, seen = new Set()) => {
278
+ if (seen.has(ast))
279
+ return false;
280
+ seen.add(ast);
281
+ if (SchemaAST.isDeclaration(ast))
282
+ return true;
283
+ if (SchemaAST.isSuspend(ast))
284
+ return holdsDeclaration(ast.thunk(), seen);
285
+ if (SchemaAST.isUnion(ast))
286
+ return ast.types.some((member) => holdsDeclaration(member, seen));
287
+ if (SchemaAST.isObjects(ast)) {
288
+ return (ast.propertySignatures.some((property) => holdsDeclaration(property.type, seen)) ||
289
+ ast.indexSignatures.some((index) => holdsDeclaration(index.type, seen)));
290
+ }
291
+ if (SchemaAST.isArrays(ast)) {
292
+ return [...ast.elements, ...ast.rest].some((element) => holdsDeclaration(element, seen));
293
+ }
294
+ return false;
295
+ };
296
+ /**
297
+ * A field's decode as an entity's read decodes a row's value (`legacyReads`): what the marshaller
298
+ * changed is taken back first, a stored bigint read back as a number lifted wherever it sits (in a
299
+ * list, a struct, a declaration's value), and each of Effect's look-alike declarations (a
300
+ * `Duration`, a zone, a date in an `Option`, ...) comes back as the instance a read hands back
301
+ * (`readingKeyInstances`), so a key composed again from the row is the text `put` composed for it.
302
+ */
303
+ const readDecodeOf = (field) => Schema.decodeUnknownOption(readingKeyInstances(substituteSchemaDeep(field, { legacyReads: true })));
304
+ /**
305
+ * The value a field storing a declaration ({@link holdsDeclaration}) stored, from what a read of it
306
+ * hands back: the value decoded through the field, as a read decodes it ({@link readDecodeOf}), and
307
+ * encoded again, as a write encodes it. A declaration's value goes to DynamoDB as a map, a list or a
308
+ * set, and comes back a plain one: `Option.some(5)` composes `some(5)`, and the map read back
309
+ * `[object Object]`, until the field decodes it to `Option.some(5)` again; `Option.some(5n)` comes
310
+ * back a map holding `5`, which a read lifts to `5n`. `undefined` for a field storing none, and from
311
+ * the function returned for a value that isn't an object or that the field doesn't decode, which is
312
+ * then taken as it is.
313
+ */
314
+ export const storedFormOfDeclaration = (field) => {
315
+ if (!holdsDeclaration(SchemaAST.toEncoded(field.ast)))
316
+ return undefined;
317
+ const codec = field;
318
+ const asRead = readDecodeOf(field);
319
+ const decode = Schema.decodeUnknownOption(codec);
320
+ const encode = Schema.encodeUnknownOption(codec);
321
+ return (value) => {
322
+ if (typeof value !== "object" || value === null)
323
+ return undefined;
324
+ const read = asRead(value);
325
+ const decoded = Option.isSome(read) ? read : decode(value);
326
+ const stored = Option.flatMap(decoded, (domain) => encode(domain));
327
+ return Option.isSome(stored) ? stored.value : undefined;
328
+ };
329
+ };
330
+ /**
331
+ * The value a field held when it was stored, from what the unmarshaller hands
332
+ * back for it. A field whose Encoded side is a `bigint` is stored as `N` and
333
+ * comes back as a number while it is a safe integer; one whose Encoded side is
334
+ * a number comes back as a `bigint` past 2^53. `undefined` when the field's
335
+ * Encoded side isn't one numeric kind, and from the function returned for a
336
+ * value already of that kind (or not a number at all).
337
+ */
338
+ export const storedNumericForm = (field) => liftToKind(storedNumericKinds(field));
339
+ /** The parse function of each declaration whose value can name a zone: a zone, a zoned date. */
340
+ const ZONE_RUNS = new Set([Schema.TimeZone, Schema.TimeZoneNamed, Schema.DateTimeZoned].map((schema) => schema.ast.run));
341
+ /** Whether a schema's Type side can hold a value naming a zone, wherever it sits. */
342
+ export const holdsZone = (ast, seen = new Set()) => {
343
+ if (seen.has(ast))
344
+ return false;
345
+ seen.add(ast);
346
+ if (SchemaAST.isDeclaration(ast)) {
347
+ return ZONE_RUNS.has(ast.run) || ast.typeParameters.some((type) => holdsZone(type, seen));
348
+ }
349
+ if (SchemaAST.isSuspend(ast))
350
+ return holdsZone(ast.thunk(), seen);
351
+ if (SchemaAST.isUnion(ast))
352
+ return ast.types.some((member) => holdsZone(member, seen));
353
+ if (SchemaAST.isObjects(ast)) {
354
+ return (ast.propertySignatures.some((property) => holdsZone(property.type, seen)) ||
355
+ ast.indexSignatures.some((index) => holdsZone(index.type, seen)));
356
+ }
357
+ if (SchemaAST.isArrays(ast)) {
358
+ return [...ast.elements, ...ast.rest].some((element) => holdsZone(element, seen));
359
+ }
360
+ return false;
361
+ };
362
+ /**
363
+ * Whether a schema encodes anywhere: at its top, or in a member, property, element, type parameter
364
+ * or suspension. `Schema.Array(Schema.TimeZoneNamedFromString)` has no encoding of its own, and its
365
+ * elements do.
366
+ */
367
+ const holdsEncoding = (ast, seen = new Set()) => {
368
+ if (seen.has(ast))
369
+ return false;
370
+ seen.add(ast);
371
+ if (ast.encoding !== undefined)
372
+ return true;
373
+ if (SchemaAST.isDeclaration(ast)) {
374
+ return ast.typeParameters.some((type) => holdsEncoding(type, seen));
375
+ }
376
+ if (SchemaAST.isSuspend(ast))
377
+ return holdsEncoding(ast.thunk(), seen);
378
+ if (SchemaAST.isUnion(ast))
379
+ return ast.types.some((member) => holdsEncoding(member, seen));
380
+ if (SchemaAST.isObjects(ast)) {
381
+ return (ast.propertySignatures.some((property) => holdsEncoding(property.type, seen)) ||
382
+ ast.indexSignatures.some((index) => holdsEncoding(index.type, seen)));
383
+ }
384
+ if (SchemaAST.isArrays(ast)) {
385
+ return [...ast.elements, ...ast.rest].some((element) => holdsEncoding(element, seen));
386
+ }
387
+ return false;
388
+ };
389
+ /**
390
+ * For a field encoding a zone, or a date zoned in one, to text (Effect's `TimeZoneNamedFromString`,
391
+ * `TimeZoneFromString`, `DateTimeZonedFromString`, or an application's own), at its top or anywhere
392
+ * in it (a list of them, an `Option` of one): the value it stores, or one read back, with each zone
393
+ * named as the key form names it (`zonesAsStored`). A key is composed from the value stored (case 3a,
394
+ * a list of them) or from the field's text (case 3b, which names it itself), a unique sentinel and a
395
+ * time-series event's sort key from the value stored, and Effect's codecs write the name a zone was
396
+ * made from on 4.1.3 (`Etc/UTC` where 4.1.2 wrote `UTC`), so these take this value instead, which is
397
+ * the same on both. `undefined` for any other field, and from the function returned for a value
398
+ * already so named, a value naming no zone, and one the field doesn't decode.
399
+ */
400
+ export const storedZoneText = (field) => {
401
+ if (!holdsEncoding(field.ast) || !holdsZone(SchemaAST.toType(field.ast)))
402
+ return undefined;
403
+ const codec = field;
404
+ const decode = Schema.decodeUnknownOption(codec);
405
+ const encode = Schema.encodeUnknownOption(codec);
406
+ return (value) => {
407
+ const decoded = decode(value);
408
+ if (Option.isNone(decoded) || !namesZone(decoded.value))
409
+ return undefined;
410
+ const stored = encode(zonesAsStored(decoded.value));
411
+ return Option.isSome(stored) && !sameValue(stored.value, value) ? stored.value : undefined;
412
+ };
413
+ };
414
+ /** {@link storedNumericForm}, from the kinds a field stores. */
415
+ const liftToKind = (kinds) => {
416
+ if (kinds.size !== 1)
417
+ return undefined;
418
+ if (kinds.has("bigint")) {
419
+ return (value) => typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : undefined;
420
+ }
421
+ return (value) => typeof value === "bigint" && Number.isSafeInteger(Number(value)) ? Number(value) : undefined;
422
+ };
423
+ /** The one numeric kind of `kinds`, when there's one. */
424
+ const onlyNumericKind = (kinds) => kinds.size === 1 ? [...kinds][0] : undefined;
425
+ /**
426
+ * `value` as `kind` holds it, exactly: a bigint as a number only within the safe range (a number
427
+ * can't be written past it, and DynamoDB hands one back as a bigint there), a number as a bigint
428
+ * only when it's an integer. `undefined` when `kind` can't hold it: a row storing that value is one
429
+ * a field of that kind can't read.
430
+ */
431
+ const exactIn = (kind, value) => kind === "bigint"
432
+ ? typeof value === "bigint"
433
+ ? value
434
+ : Number.isInteger(value)
435
+ ? BigInt(value)
436
+ : undefined
437
+ : typeof value === "number"
438
+ ? value
439
+ : Number.isSafeInteger(Number(value))
440
+ ? Number(value)
441
+ : undefined;
442
+ /**
443
+ * The numeric kinds a field's stored `N` can have been written from: those its Encoded side admits.
444
+ * `Schema.BigInt` and `Schema.Union([Schema.String, Schema.BigInt])` store only a `bigint`;
445
+ * `Schema.Union([Schema.Number, Schema.BigInt])` stores both, and so does an unknown value. Read back,
446
+ * a field storing one kind is that kind ({@link storedNumericForm}); a field storing both can't say
447
+ * which from the value alone, so no key is composed from one: declared, it's refused at load
448
+ * ({@link bothKindsKeyRefusal}), and a key whose kinds can't be read (`Schema.Unknown`, a declaration)
449
+ * refuses a value that reads back otherwise at write ({@link readsBackOtherwise}).
450
+ */
451
+ export const storedNumericKinds = (field) => numericKinds(field, true);
452
+ /**
453
+ * The numeric kinds a field's Encoded side declares: {@link storedNumericKinds} but for what
454
+ * `Schema.Unknown` and `Schema.Any` take, which declare no kind.
455
+ */
456
+ const numericKinds = (field, open) => {
457
+ const kinds = new Set();
458
+ const seen = new Set();
459
+ const walk = (ast) => {
460
+ if (SchemaAST.isSuspend(ast)) {
461
+ if (seen.has(ast))
462
+ return;
463
+ seen.add(ast);
464
+ walk(ast.thunk());
465
+ }
466
+ else if (SchemaAST.isNumber(ast))
467
+ kinds.add("number");
468
+ else if (SchemaAST.isBigInt(ast))
469
+ kinds.add("bigint");
470
+ else if (SchemaAST.isUnknown(ast) || SchemaAST.isAny(ast)) {
471
+ if (open) {
472
+ kinds.add("number");
473
+ kinds.add("bigint");
474
+ }
475
+ }
476
+ else if (SchemaAST.isLiteral(ast)) {
477
+ if (typeof ast.literal === "number")
478
+ kinds.add("number");
479
+ if (typeof ast.literal === "bigint")
480
+ kinds.add("bigint");
481
+ }
482
+ else if (SchemaAST.isEnum(ast)) {
483
+ for (const [, value] of ast.enums)
484
+ if (typeof value === "number")
485
+ kinds.add("number");
486
+ }
487
+ else if (SchemaAST.isUnion(ast)) {
488
+ for (const member of ast.types)
489
+ walk(member);
490
+ }
491
+ };
492
+ walk(SchemaAST.toEncoded(field.ast));
493
+ return kinds;
494
+ };
495
+ /**
496
+ * `[EDD-9128]`: a key composite declaring both numeric kinds, or `undefined` for one that doesn't.
497
+ * DynamoDB stores `5` and `5n` alike, as `{N:"5"}`, and a safe integer reads back as a `number`
498
+ * whichever was written, while the two compose different key text (16 digits, 38). So a key composed
499
+ * again from a row read back (`restore`, an update reading the item first, a delete releasing a
500
+ * unique constraint, `rekey`, an aggregate's `update` and `list`) wouldn't be the key `put` wrote,
501
+ * and the value can't say which kind it was. Refused at load wherever a value is composed into key
502
+ * text: a key, a unique constraint, a vector partition, a time-series `orderBy`. A field no key reads
503
+ * may store both. `Schema.Unknown` and `Schema.Any` declare no kind, and a key over one that holds
504
+ * strings works, so they're judged by value at write instead ({@link readsBackOtherwise}), as is a
505
+ * declaration and a transformation whose Encoded side is one of these.
506
+ */
507
+ export const bothKindsKeyRefusal = (owner, where, attr, field) => {
508
+ if (numericKinds(field, false).size < 2)
509
+ return undefined;
510
+ return new Error(`[EDD-9128] ${owner}: ${where} can't be composed from "${attr}", which stores both a number ` +
511
+ `and a bigint. DynamoDB stores 5 and 5n alike and reads a safe integer back as a number, ` +
512
+ `and the two compose different key text, so a key composed again from a stored row ` +
513
+ `wouldn't be the key the write composed. Declare the one kind it holds, such as ` +
514
+ `Schema.Number or Schema.BigInt.`);
515
+ };
516
+ /**
517
+ * Whether the numeric kinds a field stores can't be read off its schema: its Encoded side holds a
518
+ * `Schema.Unknown`, a `Schema.Any` or a declaration (`Schema.declare`), alone, in a union or behind a
519
+ * `Schema.suspend`. A transformation is judged by its Encoded side, so `Schema.Unknown` decoded to a
520
+ * `Schema.BigInt` is one.
521
+ */
522
+ const kindsUnreadable = (field) => {
523
+ const seen = new Set();
524
+ const walk = (ast) => {
525
+ if (SchemaAST.isSuspend(ast)) {
526
+ if (seen.has(ast))
527
+ return false;
528
+ seen.add(ast);
529
+ return walk(ast.thunk());
530
+ }
531
+ if (SchemaAST.isUnknown(ast) || SchemaAST.isAny(ast) || SchemaAST.isDeclaration(ast))
532
+ return true;
533
+ return SchemaAST.isUnion(ast) && ast.types.some(walk);
534
+ };
535
+ return walk(SchemaAST.toEncoded(field.ast));
536
+ };
537
+ /** Whether a schema transforms anywhere: at its top, or in a member, property, element or suspension. */
538
+ const transformsAnywhere = (ast, seen = new Set()) => {
539
+ if (seen.has(ast))
540
+ return false;
541
+ seen.add(ast);
542
+ if (ast.encoding !== undefined)
543
+ return true;
544
+ if (SchemaAST.isSuspend(ast))
545
+ return transformsAnywhere(ast.thunk(), seen);
546
+ if (SchemaAST.isUnion(ast))
547
+ return ast.types.some((member) => transformsAnywhere(member, seen));
548
+ if (SchemaAST.isObjects(ast)) {
549
+ return (ast.propertySignatures.some((property) => transformsAnywhere(property.type, seen)) ||
550
+ ast.indexSignatures.some((index) => transformsAnywhere(index.type, seen)));
551
+ }
552
+ if (SchemaAST.isArrays(ast)) {
553
+ return [...ast.elements, ...ast.rest].some((element) => transformsAnywhere(element, seen));
554
+ }
555
+ if (SchemaAST.isDeclaration(ast)) {
556
+ return ast.typeParameters.some((parameter) => transformsAnywhere(parameter, seen));
557
+ }
558
+ return false;
559
+ };
560
+ /**
561
+ * Whether a key composite's read-back can't be guaranteed at load, so a write judges each value it
562
+ * stores: a field whose numeric kinds can't be read off its schema (`Schema.Unknown`, `Schema.Any`, a
563
+ * declaration, alone or in a union), or one with a transformation anywhere on it. Only a field of
564
+ * known kinds with no transformation reads back as itself by construction: the marshaller's only
565
+ * changes to such a value (a safe-integer `bigint` read back as a number, a number past 2^53 as a
566
+ * `bigint`, `-0` as `0`) compose the same key text.
567
+ */
568
+ export const readBackUnsure = (field) => kindsUnreadable(field) || transformsAnywhere(field.ast);
569
+ /**
570
+ * The value a field stored, from what a read of it hands back, for composing a key from a row read
571
+ * back: `undefined` when it's that already. A field storing one numeric kind takes it
572
+ * ({@link storedNumericForm}). A field whose kinds can't be read off its schema ({@link
573
+ * kindsUnreadable}) is decoded through the field, as a read decodes it, and encoded again, as a write
574
+ * encodes it: `Schema.Unknown` decoded to a `Schema.BigInt` with `BigInt(n)` stored `5n`, which reads
575
+ * back as `5`, and decoding `5` gives `5n` again. A field storing a declaration takes an object the
576
+ * same way ({@link storedFormOfDeclaration}): `Option.some(5)` comes back a plain map. Only these
577
+ * are taken this way, the only values DynamoDB hands back otherwise, and for any other field nothing
578
+ * is.
579
+ */
580
+ export const storedFormOfRead = (field) => {
581
+ const lift = storedNumericForm(field);
582
+ const declared = storedFormOfDeclaration(field);
583
+ const numeric = lift ?? (kindsUnreadable(field) ? numericFormOfRead(field) : undefined);
584
+ if (declared === undefined)
585
+ return numeric;
586
+ return (value) => typeof value === "object" && value !== null ? declared(value) : numeric?.(value);
587
+ };
588
+ /** {@link storedFormOfRead} of a number or a bigint, for a field whose kinds can't be read off it. */
589
+ const numericFormOfRead = (field) => {
590
+ const codec = field;
591
+ const decode = Schema.decodeUnknownOption(codec);
592
+ const encode = Schema.encodeUnknownOption(codec);
593
+ return (value) => {
594
+ if (typeof value !== "number" && typeof value !== "bigint")
595
+ return undefined;
596
+ const stored = Option.flatMap(decode(value), (decoded) => encode(decoded));
597
+ return Option.isSome(stored) && !Object.is(stored.value, value) ? stored.value : undefined;
598
+ };
599
+ };
600
+ /**
601
+ * Whether two decoded values compose the same key text: the same value, or the same number (`-0` and
602
+ * `0` compose the same text).
603
+ */
604
+ const sameKeyValue = (a, b) => typeof a === typeof b &&
605
+ (Object.is(a, b) || (typeof a === "number" && a === b) || Equal.equals(a, b));
606
+ /**
607
+ * For a key composite whose read-back can't be guaranteed at load ({@link readBackUnsure}, of the
608
+ * field that reads it back or of the one a write encodes it with): what a value a write stores reads
609
+ * back as, when a key composed again from the row read back wouldn't be the key written. `"a
610
+ * number"` or `"a bigint"` for a value read back as the other kind, `"a value the field refuses"`,
611
+ * or the value it reads back as. `undefined` for a value that reads back as written.
612
+ *
613
+ * `asRead` is what DynamoDB hands back for a stored value, the marshaller and the unmarshaller run
614
+ * for real: a safe-integer `bigint` comes back as a `number`, and `-0` as `0`. A `number` past
615
+ * 2^53 the marshaller refuses, which the write's own marshalling reports (`EDD-9124`). A value that
616
+ * comes back as it went is never judged. One that doesn't is judged twice: each of `texts` composed
617
+ * from the value written and from the value read back must be the same text, and a value that isn't
618
+ * an object, read back and decoded through `field`, must be the value written decoded (when that
619
+ * decodes). An object is judged by its texts alone: `Option.some(5)` comes back a plain map, which
620
+ * the key form decodes to `Option.some(5)` again ({@link storedFormOfDeclaration}), so it composes
621
+ * the text written, while a struct holding a `bigint` reads back holding a number its field refuses,
622
+ * and composes the text written all the same. `Schema.Unknown` reads `5n` back as `5`, and a
623
+ * declaration of either kind does the same, so both are refused; `Schema.Unknown` decoded to a
624
+ * `Schema.BigInt` with `BigInt(n)` reads it back as `5n`, and is stored. A codec decoding `-0` and
625
+ * `0` to different values refuses `-0`. The judge itself is `undefined` for a field that reads back
626
+ * as itself by construction, which never needs asking.
627
+ */
628
+ export const readsBackOtherwise = (field, options) => {
629
+ if (!readBackUnsure(field) &&
630
+ (options.written === undefined || !readBackUnsure(options.written))) {
631
+ return undefined;
632
+ }
633
+ const decode = Schema.decodeUnknownOption(field);
634
+ // A read takes what DynamoDB hands back as the one numeric kind the field stores, when it stores
635
+ // one ({@link storedNumericForm}): `OptionFromNullOr(Schema.BigInt)` reads `5` as `5n`.
636
+ const lift = storedNumericForm(field);
637
+ const texts = options.texts ?? [];
638
+ return (stored) => {
639
+ // A string or a boolean comes back as it went.
640
+ if (typeof stored === "string" || typeof stored === "boolean")
641
+ return undefined;
642
+ let returned;
643
+ try {
644
+ returned = options.asRead(stored);
645
+ }
646
+ catch {
647
+ // A value the marshaller refuses is the write's own marshalling's to report.
648
+ return undefined;
649
+ }
650
+ if (Object.is(returned, stored))
651
+ return undefined;
652
+ const read = decode(lift?.(returned) ?? returned);
653
+ const written = decode(stored);
654
+ const textMoved = texts.some((text) => {
655
+ const at = text.written(stored);
656
+ return at !== undefined && text.read(returned) !== at;
657
+ });
658
+ // An object's key text is its texts' to judge: what each composes from the value read back is
659
+ // what a key composed again from the row holds.
660
+ const valueMoved = Option.isSome(written) &&
661
+ typeof written.value !== "object" &&
662
+ typeof written.value !== "function" &&
663
+ (Option.isNone(read) || !sameKeyValue(read.value, written.value));
664
+ if (!textMoved && !valueMoved)
665
+ return undefined;
666
+ return readBackAs(read, Option.isSome(written) ? written.value : stored);
667
+ };
668
+ };
669
+ /**
670
+ * What a value reads back as, in the words of {@link readsBackOtherwise}: `"a value the field
671
+ * refuses"` when the read fails, `"a number"` or `"a bigint"` for one of another kind than `was`, the
672
+ * value written, and otherwise the value read back.
673
+ */
674
+ export const readBackAs = (read, was) => {
675
+ if (Option.isNone(read))
676
+ return "a value the field refuses";
677
+ if (typeof read.value !== typeof was) {
678
+ return typeof read.value === "bigint"
679
+ ? "a bigint"
680
+ : typeof read.value === "number"
681
+ ? "a number"
682
+ : "something else";
683
+ }
684
+ return typeof read.value === "bigint"
685
+ ? `${read.value}n`
686
+ : typeof read.value === "number" || typeof read.value === "boolean"
687
+ ? String(read.value)
688
+ : typeof read.value === "string"
689
+ ? JSON.stringify(read.value)
690
+ : "something else";
691
+ };
692
+ /**
693
+ * The field a composite names by its dotted path (`nested.n`): the first segment a field of
694
+ * `fields`, each further one looked up through what holds it on the way — `Schema.optional`,
695
+ * `Schema.optionalKey`, `Schema.NullOr` or another union with `null` or `undefined`,
696
+ * `Schema.suspend`, and a `Schema.Class` — as the value holds it. A union of structs naming the
697
+ * segment in several members gives the union of their fields. `undefined` where a segment names
698
+ * nothing.
699
+ */
700
+ export const fieldAtPath = (fields, path) => followPath(fields, path, (ast) => ast);
701
+ /**
702
+ * {@link fieldAtPath} on the stored side: each segment looked up in what its holder is stored as, so
703
+ * a transformation of a value on the way (a struct decoded to another struct) is kept, and the field
704
+ * found is the one a row holds. `Schema.Struct({ n: Schema.Number })` decoded to a struct whose `n`
705
+ * is `Schema.Union([Schema.Number, Schema.BigInt])` stores a number at `nested.n`.
706
+ */
707
+ export const storedFieldAtPath = (fields, path) => followPath(fields, path, (ast) => SchemaAST.toEncoded(ast));
708
+ /**
709
+ * The field a model declares under `name`. Never a member every object
710
+ * inherits: an attribute named `toString` that the model doesn't declare (a
711
+ * version or timestamp attribute) is not a field. Nor one a derived struct holds
712
+ * as 1.40.0's didn't hold it (`isProtoAbsent`): its value is key text as given,
713
+ * as it was.
714
+ */
715
+ const declared = (fields, name) => {
716
+ const field = ownValue(fields, name);
717
+ return isProtoAbsent(field) ? undefined : field;
718
+ };
719
+ const followPath = (fields, path, side) => {
720
+ const [first, ...rest] = path.split(".");
721
+ const top = declared(fields, first);
722
+ if (top === undefined || rest.length === 0)
723
+ return top;
724
+ let at = [side(top.ast)];
725
+ for (const segment of rest) {
726
+ at = at.flatMap((ast) => propertyAt(ast, segment, new Set()));
727
+ if (at.length === 0)
728
+ return undefined;
729
+ }
730
+ return at.length === 1
731
+ ? Schema.make(at[0])
732
+ : Schema.Union(at.map((ast) => Schema.make(ast)));
733
+ };
734
+ const propertyAt = (ast, name, seen) => {
735
+ if (SchemaAST.isSuspend(ast)) {
736
+ if (seen.has(ast))
737
+ return [];
738
+ seen.add(ast);
739
+ return propertyAt(ast.thunk(), name, seen);
740
+ }
741
+ if (SchemaAST.isUnion(ast)) {
742
+ return ast.types.flatMap((member) => SchemaAST.isUndefined(member) || SchemaAST.isNull(member)
743
+ ? []
744
+ : propertyAt(member, name, seen));
745
+ }
746
+ if (SchemaAST.isObjects(ast)) {
747
+ const property = ast.propertySignatures.find((signature) => signature.name === name);
748
+ return property === undefined ? [] : [property.type];
749
+ }
750
+ // A class: a declaration of its struct, which is what it's stored as.
751
+ if (SchemaAST.isDeclaration(ast) &&
752
+ ast.typeParameters.length === 1 &&
753
+ SchemaAST.isObjects(SchemaAST.toEncoded(ast))) {
754
+ return propertyAt(ast.typeParameters[0], name, seen);
755
+ }
756
+ return [];
757
+ };
758
+ /**
759
+ * A number or bigint as the other kind, read from `stored`, the `N` its field stored, when there
760
+ * is one: a bigint past 2^53 keeps its digits, and a number that isn't an integer has no bigint.
761
+ * `undefined` for anything else.
762
+ */
763
+ export const otherNumericKind = (value, stored) => {
764
+ if (typeof value === "bigint")
765
+ return Number(stored ?? value);
766
+ if (typeof value !== "number")
767
+ return undefined;
768
+ const integer = stored !== undefined ? /^-?\d+$/.test(stored) : Number.isInteger(value);
769
+ return integer ? BigInt(stored ?? value) : undefined;
770
+ };
771
+ /** {@link KindTargets} over `texts`: sorted once, then each question is a binary search. */
772
+ export const kindTargets = (texts) => {
773
+ // Compared by UTF-16 code unit, as `<` and `startsWith` compare: the texts beginning with a
774
+ // prefix sort together, from the first one not below it.
775
+ const sorted = [...new Set(texts)].sort();
776
+ const from = (text) => {
777
+ let low = 0;
778
+ let high = sorted.length;
779
+ while (low < high) {
780
+ const middle = (low + high) >>> 1;
781
+ if (sorted[middle] < text)
782
+ low = middle + 1;
783
+ else
784
+ high = middle;
785
+ }
786
+ return sorted[low];
787
+ };
788
+ return {
789
+ has: (text) => from(text) === text,
790
+ hasPrefix: (prefix) => from(prefix)?.startsWith(prefix) ?? false,
791
+ };
792
+ };
793
+ /**
794
+ * The reading of `record` whose `compose` is `stored`, or one of the texts in `stored`: each of
795
+ * `fields` that holds a number or a bigint given as its own kind or as the other one ({@link
796
+ * otherNumericKind}, the other read from `digits`, the `N` the field stored). A field that stored
797
+ * both kinds (`Schema.Union([Schema.Number, Schema.BigInt])` before {@link bothKindsKeyRefusal},
798
+ * or a `Schema.Unknown`) composed each value's own kind's text, so `rekey` looks for a row stored
799
+ * under the other kind's. `compose` gives `undefined` for values with no text there.
800
+ *
801
+ * `compose` may give its text in segments, whose concatenation is the text (a key's partition and
802
+ * sort key halves): a value is looked for once in each segment, so a composite in both halves of a
803
+ * key is found in both. Each field is one decision, its kind, whichever segments it is in.
804
+ *
805
+ * `record` as it is comes first, and when its text is looked for nothing else is composed: that is
806
+ * a row under its current key, every row of a clean run. Otherwise each field is composed once as
807
+ * the other kind by itself, which shows where its value lies in each segment: the stretch where
808
+ * that segment and `record`'s differ. The readings are then walked stretch by stretch from the
809
+ * left, keeping those whose text so far begins a text looked for, a field's later stretches
810
+ * following its first, and one left whole at the end is composed to confirm it. That is one
811
+ * composition per field and one or two more, never one per combination, and no text is split on
812
+ * its delimiters. When two fields' stretches overlap in a segment, a composer that doesn't keep
813
+ * each value in a stretch of its own, each field is read as the other kind only alone.
814
+ */
815
+ export const kindReadingOf = (record, fields, digits, compose, stored) => {
816
+ const targets = typeof stored === "string"
817
+ ? { has: (text) => text === stored, hasPrefix: (prefix) => stored.startsWith(prefix) }
818
+ : stored;
819
+ const composed = (reading) => {
820
+ try {
821
+ const out = compose(reading);
822
+ return out === undefined ? undefined : typeof out === "string" ? [out] : out;
823
+ }
824
+ catch {
825
+ return undefined;
826
+ }
827
+ };
828
+ const asGiven = { record, asOther: new Set() };
829
+ const segments = composed(asGiven);
830
+ if (segments === undefined)
831
+ return undefined;
832
+ const base = segments.join("");
833
+ if (targets.has(base))
834
+ return asGiven;
835
+ const offsets = [];
836
+ let offset = 0;
837
+ for (const segment of segments) {
838
+ offsets.push(offset);
839
+ offset += segment.length;
840
+ }
841
+ const others = new Map();
842
+ const edits = [];
843
+ for (const field of new Set(fields)) {
844
+ const other = otherNumericKind(given(record, field), digits(field));
845
+ if (other === undefined)
846
+ continue;
847
+ const alone = { record: { ...record, [field]: other }, asOther: new Set([field]) };
848
+ const parts = composed(alone);
849
+ if (parts === undefined)
850
+ continue;
851
+ const text = parts.join("");
852
+ if (text === base)
853
+ continue;
854
+ if (targets.has(text))
855
+ return alone;
856
+ // Segments that don't line up can't be compared stretch by stretch: read alone only.
857
+ if (parts.length !== segments.length)
858
+ continue;
859
+ others.set(field, other);
860
+ for (let i = 0; i < segments.length; i++) {
861
+ const was = segments[i];
862
+ const now = parts[i];
863
+ if (was === now)
864
+ continue;
865
+ let start = 0;
866
+ while (start < was.length && start < now.length && was[start] === now[start])
867
+ start++;
868
+ let tail = 0;
869
+ while (tail < was.length - start &&
870
+ tail < now.length - start &&
871
+ was[was.length - 1 - tail] === now[now.length - 1 - tail]) {
872
+ tail++;
873
+ }
874
+ edits.push({
875
+ field,
876
+ other,
877
+ start: offsets[i] + start,
878
+ end: offsets[i] + was.length - tail,
879
+ text: now.slice(start, now.length - tail),
880
+ });
881
+ }
882
+ }
883
+ // Each field alone has been tried.
884
+ if (others.size < 2)
885
+ return undefined;
886
+ edits.sort((a, b) => a.start - b.start || a.end - b.end);
887
+ if (edits.some((edit, i) => i > 0 && edit.start <= edits[i - 1].start))
888
+ return undefined;
889
+ if (edits.some((edit, i) => i > 0 && edit.start < edits[i - 1].end))
890
+ return undefined;
891
+ // Where each field's last stretch is: a decision is followed until then.
892
+ const last = new Map();
893
+ for (let i = 0; i < edits.length; i++)
894
+ last.set(edits[i].field, i);
895
+ let walked = new Map([["", { text: "", decided: new Map() }]]);
896
+ let at = 0;
897
+ for (let i = 0; i < edits.length; i++) {
898
+ const edit = edits[i];
899
+ const next = new Map();
900
+ const between = base.slice(at, edit.start);
901
+ for (const { text, decided } of walked.values()) {
902
+ const made = decided.get(edit.field);
903
+ for (const asOther of made === undefined ? [false, true] : [made]) {
904
+ const sofar = `${text}${between}${asOther ? edit.text : base.slice(edit.start, edit.end)}`;
905
+ if (!targets.hasPrefix(sofar))
906
+ continue;
907
+ const now = new Map(decided).set(edit.field, asOther);
908
+ // Readings with one text so far differ only in decisions still to be followed.
909
+ const pending = [...now]
910
+ .filter(([field]) => last.get(field) > i)
911
+ .map(([field, flipped]) => `${field}:${flipped ? 1 : 0}`)
912
+ .join(",");
913
+ const key = `${sofar}\u0000${pending}`;
914
+ if (!next.has(key))
915
+ next.set(key, { text: sofar, decided: now });
916
+ }
917
+ }
918
+ if (next.size === 0)
919
+ return undefined;
920
+ walked = next;
921
+ at = edit.end;
922
+ }
923
+ const rest = base.slice(at);
924
+ for (const { text, decided } of walked.values()) {
925
+ const flipped = [...decided].filter(([, asOther]) => asOther).map(([field]) => field);
926
+ if (flipped.length < 2 || !targets.has(`${text}${rest}`))
927
+ continue;
928
+ const values = { ...record };
929
+ for (const field of flipped)
930
+ setOwn(values, field, others.get(field));
931
+ const reading = { record: values, asOther: new Set(flipped) };
932
+ const confirmed = composed(reading);
933
+ if (confirmed !== undefined && targets.has(confirmed.join("")))
934
+ return reading;
935
+ }
936
+ return undefined;
937
+ };
938
+ /**
939
+ * Build the function that puts a composite's DOMAIN value into the form
940
+ * `Entity.put` stores it in, before `makeCompositeKeyForm`'s normaliser composes
941
+ * a key from it — so a key composed from a caller's value is the key `put`
942
+ * wrote for it.
943
+ *
944
+ * `put` encodes its input (`encode`, else `decode -> encode`), then composes
945
+ * keys through the key-form normaliser, which keys that stored text as it is.
946
+ * For a codec that `encode` takes on its own output (`x:` prepended by
947
+ * `encode`, stripped by `decode`; a number scaled by `encode`), a caller's
948
+ * value is therefore encoded here first, once: the normaliser can't tell
949
+ * `"x:MiX"` given as a domain value from `"MiX"`'s stored text.
950
+ *
951
+ * A codec inside a wrapper (`Schema.optional(Schema.NumberFromString)`, a union
952
+ * of a codec and a literal) is encoded here too, as `put` encodes it. The
953
+ * normaliser takes such a field as it comes, so `put` keys its stored text
954
+ * (`id_5`), and a caller's `5` composed `id_0000000000000005`, a key `put` never
955
+ * writes.
956
+ *
957
+ * Every other composite is untouched here — an untransformed one, a numeric one
958
+ * stored as a string (the normaliser takes either side), and a codec whose
959
+ * `encode` refuses its own output compose the same key whichever form they come
960
+ * in.
961
+ *
962
+ * A value no step takes is passed through, for the normaliser to refuse.
963
+ */
964
+ export const makeCompositeStoredForm = (source) => {
965
+ const storedForm = compositeStoredForm(source);
966
+ return (record, required, optional) => toCompositeKeyRecord(storedForm, record, required, optional);
967
+ };
968
+ /** {@link makeCompositeStoredForm}, one attribute at a time. */
969
+ const compositeStoredForm = (source) => {
970
+ const fields = getSchemaFields(source);
971
+ const cache = new Map();
972
+ const resolve = (attr) => {
973
+ const cached = cache.get(attr);
974
+ if (cached !== undefined)
975
+ return cached;
976
+ const field = declared(fields, attr);
977
+ if (field === undefined ||
978
+ numericTypeWithStringEncoding(field) ||
979
+ // No transformation anywhere in it, a wrapper's included: stored as given.
980
+ SchemaAST.toEncoded(field.ast) === field.ast) {
981
+ cache.set(attr, null);
982
+ return null;
983
+ }
984
+ const codec = field;
985
+ const encode = Schema.encodeUnknownOption(codec);
986
+ const decode = Schema.decodeUnknownOption(codec);
122
987
  const fn = (value) => {
123
988
  const direct = encode(value);
124
989
  if (Option.isSome(direct))
@@ -129,7 +994,7 @@ export const makeCompositeKeyForm = (source, onError) => {
129
994
  if (Option.isSome(reencoded))
130
995
  return reencoded.value;
131
996
  }
132
- return onError(attr, value);
997
+ return value;
133
998
  };
134
999
  cache.set(attr, fn);
135
1000
  return fn;
@@ -142,19 +1007,36 @@ export const makeCompositeKeyForm = (source, onError) => {
142
1007
  };
143
1008
  };
144
1009
  /**
145
- * Apply a `CompositeKeyForm` across every entry of a record, so a whole key or
146
- * composite record can be normalised in one call.
1010
+ * The key form of a caller's DOMAIN value: {@link makeCompositeStoredForm}'s
1011
+ * stored form, then `makeCompositeKeyForm`'s key form — what `Entity.put`
1012
+ * composes for the value: encode a domain value once, then key that text.
1013
+ * Every path that composes a key from values a caller gives (an accessor's
1014
+ * composites, a `.where()` or `.within()` bound, a collection's or a vector
1015
+ * index's partition, a geo search's filter, a multi-item op's key, a
1016
+ * projection's row) composes through it, so it finds what `put` wrote. Except
1017
+ * for a domain value that is also its codec's stored text (`"x:MiX"`), it is
1018
+ * exactly the key form.
147
1019
  */
148
- export const toCompositeKeyRecord = (keyForm, record) => {
149
- const out = {};
150
- for (const [attr, value] of Object.entries(record)) {
151
- out[attr] = keyForm(attr, value);
152
- }
153
- return out;
1020
+ export const makeCompositeDomainKeyForm = (source, onError) => {
1021
+ const keyForm = makeCompositeKeyForm(source, onError);
1022
+ const storedForm = compositeStoredForm(source);
1023
+ return (attr, value) => keyForm(attr, storedForm(attr, value));
154
1024
  };
1025
+ /**
1026
+ * Apply a `CompositeKeyForm` across every entry of a record, so a whole key or
1027
+ * composite record can be normalised in one call. The result is a plain record
1028
+ * of own entries: the record's own enumerable entries, read as 1.40.0 read them
1029
+ * (`Object.entries`) and nothing else of the record, wherever they hold every
1030
+ * composite in `required` (the composites the key can't be composed without).
1031
+ * Only where they lack one, where 1.40.0 failed ("Missing composite
1032
+ * attribute"), is each composite of `required` and `optional` they lack read by
1033
+ * name (`keyEntries`): from a prototype, a class's getter or a proxy (#239),
1034
+ * never a function there. A record the library built holds its entries itself.
1035
+ */
1036
+ export const toCompositeKeyRecord = (keyForm, record, required = [], optional = []) => keyEntries(record, required, optional, keyForm);
155
1037
  /** Classify one composite attribute of a model/derived schema. */
156
1038
  export const compositeKeyFormKind = (source, attr) => {
157
- const field = getSchemaFields(source)?.[attr];
1039
+ const field = declared(getSchemaFields(source), attr);
158
1040
  if (field === undefined)
159
1041
  return "absent";
160
1042
  if (numericTypeWithStringEncoding(field))
@@ -163,7 +1045,11 @@ export const compositeKeyFormKind = (source, attr) => {
163
1045
  return "identity";
164
1046
  return "encoded";
165
1047
  };
166
- const astKeyFormValueKind = (ast) => {
1048
+ const astKeyFormValueKind = (ast, seen = new Set()) => {
1049
+ // A suspended schema is the schema it suspends (`Schema.suspend(() => Schema.BigInt)`).
1050
+ if (SchemaAST.isSuspend(ast)) {
1051
+ return seen.has(ast) ? undefined : astKeyFormValueKind(ast.thunk(), new Set([...seen, ast]));
1052
+ }
167
1053
  if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast))
168
1054
  return "string";
169
1055
  if (SchemaAST.isNumber(ast))
@@ -179,7 +1065,7 @@ const astKeyFormValueKind = (ast) => {
179
1065
  : SchemaAST.isUnion(ast)
180
1066
  ? ast.types
181
1067
  .filter((member) => !SchemaAST.isUndefined(member) && !SchemaAST.isNull(member))
182
- .map((member) => astKeyFormValueKind(member))
1068
+ .map((member) => astKeyFormValueKind(member, seen))
183
1069
  : [undefined];
184
1070
  const [first] = kinds;
185
1071
  return first !== undefined && kinds.every((kind) => kind === first) ? first : undefined;
@@ -195,6 +1081,26 @@ export const keyFormValueKind = (field) => {
195
1081
  }
196
1082
  return astKeyFormValueKind(SchemaAST.toEncoded(field.ast));
197
1083
  };
1084
+ /**
1085
+ * `value` in key form where it's the `NaN` of a number `field` stores as a string
1086
+ * (`Schema.NumberFromString`): `NumericKey.STORED_NAN`. The field stores it as `"NaN"`, so a row
1087
+ * can hold it, and with `escapeKeys` off it composes the text 1.36 gave it, as up to 1.39.0. A
1088
+ * `number`'s own `NaN`, which no row holds, has no key text. Any other value as it is. The one
1089
+ * place the two are told apart: the composite key form, and an aggregate's `many` edge sort key,
1090
+ * which is composed from the element's values.
1091
+ */
1092
+ export const storedNaNKeyForm = (field, value) => typeof value === "number" &&
1093
+ Number.isNaN(value) &&
1094
+ field !== undefined &&
1095
+ numericTypeWithStringEncoding(field) &&
1096
+ !SchemaAST.isBigInt(SchemaAST.toType(field.ast))
1097
+ ? STORED_NAN
1098
+ : value;
1099
+ /**
1100
+ * The JavaScript type of a key-form value, to compare with {@link keyFormValueKind}: `"number"` for
1101
+ * `NumericKey.STORED_NAN`, the `NaN` a number stored as a string hands on, as for any other number.
1102
+ */
1103
+ export const keyFormValueKindOf = (value) => isStoredNaN(value) ? "number" : typeof value;
198
1104
  /**
199
1105
  * The literal members a field's key form is limited to (a literal, a union of
200
1106
  * literals or an enum), or `undefined` when it isn't limited to literals.