@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
@@ -7,8 +7,13 @@
7
7
  */
8
8
  import { DateTime } from "effect";
9
9
  import { applyCasing, composeClusteredSortKey, composeCollectionKey, composeIsolatedSortKey, composeKey, KEY_DELIMITER, } from "./DynamoSchema.js";
10
- import { encodeBigInt, encodeNumber } from "./internal/NumericKey.js";
10
+ import { encodeBigInt, encodeNumber, isStoredNaN, KeyValueError } from "./internal/NumericKey.js";
11
+ import { judgeObjectKeyText } from "./internal/ObjectKeyText.js";
12
+ // A record composed from may be a caller's key or query composites: a composite's value is read as
13
+ // a caller's payload is (`given`), so a member every object inherits is no value (#239).
14
+ import { given, PROTO_ENTRY, setOwn } from "./internal/OwnNames.js";
11
15
  import { MAX_SHARD_COUNT, ShardSourceError, shardMarker, shardOf } from "./internal/Shards.js";
16
+ import { zonesAsStored } from "./internal/StoredForm.js";
12
17
  import { concatBytes, interleave, prefixSegment, toBytes, } from "./internal/ZOrderCurve.js";
13
18
  import { declareDimension } from "./internal/ZOrderDimension.js";
14
19
  /** Is this sort key half a Z-order one? */
@@ -177,7 +182,7 @@ const normalizeZOrderHalf = (config, sk) => {
177
182
  * Returns: ["t-1", "a@b.com"]
178
183
  */
179
184
  export const extractComposites = (composite, record) => composite.map((attr) => {
180
- const value = record[attr];
185
+ const value = given(record, attr);
181
186
  if (value === undefined || value === null) {
182
187
  throw new Error(`Missing composite attribute "${attr}" in record`);
183
188
  }
@@ -191,7 +196,7 @@ export const extractComposites = (composite, record) => composite.map((attr) =>
191
196
  export const tryExtractComposites = (composite, record) => {
192
197
  const values = [];
193
198
  for (const attr of composite) {
194
- const value = record[attr];
199
+ const value = given(record, attr);
195
200
  if (value === undefined || value === null)
196
201
  return undefined;
197
202
  values.push(serializeValue(value));
@@ -206,6 +211,8 @@ const serializeWith = (value, number, bigint) => {
206
211
  return number(value);
207
212
  if (typeof value === "bigint")
208
213
  return bigint(value);
214
+ if (isStoredNaN(value))
215
+ return number(Number.NaN);
209
216
  if (typeof value === "boolean")
210
217
  return value ? "true" : "false";
211
218
  // DateTime types → ISO string (Zoned normalized to UTC for sort order)
@@ -215,7 +222,29 @@ const serializeWith = (value, number, bigint) => {
215
222
  // Native Date
216
223
  if (value instanceof Date)
217
224
  return value.toISOString();
218
- return String(value);
225
+ // A named zone's text names it as 4.1.2 did, whichever Effect is installed
226
+ return String(zonesAsStored(value));
227
+ };
228
+ /**
229
+ * Whether `value` has key text of its own ({@link serializeValue}): a string, a number, a bigint, a
230
+ * boolean, a `DateTime` or a `Date`. Any other value's text is its `String` form, which says nothing
231
+ * exact about the value: a map read back from a row gives `[object Object]`, where the instance it
232
+ * was stored from gave its own `toString`. Two such texts compared say nothing either way. A map
233
+ * read back from a marshalled `DateTime` carries its type id but isn't one (#133): not exact.
234
+ */
235
+ export const hasExactText = (value) => {
236
+ if (typeof value === "string" ||
237
+ typeof value === "number" ||
238
+ typeof value === "bigint" ||
239
+ typeof value === "boolean" ||
240
+ isStoredNaN(value) ||
241
+ value instanceof Date) {
242
+ return true;
243
+ }
244
+ if (typeof value !== "object" || value === null || !DateTime.isDateTime(value))
245
+ return false;
246
+ const proto = Object.getPrototypeOf(value);
247
+ return proto !== Object.prototype && proto !== null;
219
248
  };
220
249
  /**
221
250
  * Serialize a value for a composite key under `escapeKeys: true`. {@link compositeText} is the
@@ -243,10 +272,24 @@ export const serializeValue = (value) => serializeWith(value, encodeNumber, enco
243
272
  * `00000000000002.5`). Never throws: `NaN` is `0000000000000NaN`.
244
273
  */
245
274
  export const serializeValue136 = (value) => serializeWith(value, (n) => String(n).padStart(16, "0"), (n) => String(n).padStart(38, "0"));
246
- /** A composite value's serialized text under the schema's setting, before casing and escaping. */
247
- export const compositeText = (schema, value) => schema.escapeKeys === true || schema.numericKeyText === true
248
- ? serializeValue(value)
249
- : serializeValue136(value);
275
+ /**
276
+ * A composite value's serialized text under the schema's setting, before casing and escaping. A
277
+ * `number`'s `NaN` has no place in key order under any setting, and no stored form: `[EDD-9096]`.
278
+ * With `escapeKeys` off every other value keeps the text 1.36 gave it. That includes the `NaN` of a
279
+ * number its field stores as a string (`NumericKey.STORED_NAN`, which the composite key form hands
280
+ * on for a `Schema.NumberFromString`): a row holds it under `0000000000000NaN`, as 1.39.0 wrote
281
+ * it, and is read, updated and deleted by that key. With `escapeKeys` on it's refused like any
282
+ * `NaN`. {@link DynamoSchema.DynamoSchema.text136} composes 1.36's text for a `number`'s `NaN` too,
283
+ * for `rekey` to find a row stored under it.
284
+ */
285
+ export const compositeText = (schema, value) => {
286
+ if (schema.escapeKeys === true || schema.numericKeyText === true)
287
+ return serializeValue(value);
288
+ if (schema.text136 !== true && typeof value === "number" && Number.isNaN(value)) {
289
+ return serializeValue(value);
290
+ }
291
+ return serializeValue136(value);
292
+ };
250
293
  /** The highest code point a key composite's text escapes: `%`. */
251
294
  const ESCAPED_MAX = 0x25;
252
295
  /**
@@ -301,13 +344,29 @@ export const serializeSortKeyValue = (value, casing) => escapeKeyText(serializeV
301
344
  export const keyText = (schema, text, casing) => (schema.escapeKeys === true ? escapeKeyText(text, casing) : applyCasing(text, casing));
302
345
  /** A composite value's text in a key: {@link compositeText}, then {@link keyText}. */
303
346
  export const keyValueText = (schema, value, casing) => keyText(schema, compositeText(schema, value), casing);
304
- /** {@link extractComposites} under the schema's setting, each value's {@link keyValueText}. */
305
- export const extractKeyComposites = (schema, index, composite, record) => composite.map((attr) => {
306
- const value = record[attr];
347
+ /**
348
+ * {@link compositeText} of `attr`'s `value` where a key is composed: `key` is the definition whose
349
+ * key it is and `half` its half. Under a write's own schema (`objectKeys`) an object composing
350
+ * `[object Object]` is refused here (#242, `EDD-9162`), so only a key actually composed refuses: an
351
+ * index a write leaves out (sparse, a half skipped) never composes its composites.
352
+ */
353
+ export const siteCompositeText = (schema, value, attr, key, half) => {
354
+ const text = compositeText(schema, value);
355
+ if (schema.objectKeys !== undefined) {
356
+ judgeObjectKeyText(schema, value, text, () => ({ attr, value, key, half }));
357
+ }
358
+ return text;
359
+ };
360
+ /**
361
+ * {@link extractComposites} under the schema's setting, each value's {@link keyValueText}. `half`
362
+ * says which half of `index` they're composed into, for {@link siteCompositeText}.
363
+ */
364
+ export const extractKeyComposites = (schema, index, composite, record, half) => composite.map((attr) => {
365
+ const value = given(record, attr);
307
366
  if (value === undefined || value === null) {
308
367
  throw new Error(`Missing composite attribute "${attr}" in record`);
309
368
  }
310
- return keyValueText(schema, value, index.casing ?? schema.casing);
369
+ return keyText(schema, siteCompositeText(schema, value, attr, index, half), index.casing ?? schema.casing);
311
370
  });
312
371
  /**
313
372
  * Compose a partition key for an entity index.
@@ -316,7 +375,7 @@ export const extractKeyComposites = (schema, index, composite, record) => compos
316
375
  * For collection indexes: `$schema#v<version>#collectionName#attr1#attr2`
317
376
  */
318
377
  export const composePk = (schema, entityType, index, record) => {
319
- const composites = extractKeyComposites(schema, index, index.pk.composite, record);
378
+ const composites = extractKeyComposites(schema, index, index.pk.composite, record, "pk");
320
379
  return composePkText(schema, entityType, index, composites, index.pk.composite, composedShardMarker(entityType, index, record));
321
380
  };
322
381
  /**
@@ -347,7 +406,7 @@ const composedShardMarker = (entityType, index, record) => {
347
406
  if (shards === undefined)
348
407
  return undefined;
349
408
  const source = boundShardSource(index, shards);
350
- const absent = source.filter((attr) => record[attr] === undefined || record[attr] === null);
409
+ const absent = source.filter((attr) => given(record, attr) === undefined || given(record, attr) === null);
351
410
  if (absent.length > 0) {
352
411
  throw new ShardSourceError({
353
412
  message: `[EDD-9100] Entity "${entityType}": index "${index.index}" is sharded, and its partition ` +
@@ -356,7 +415,7 @@ const composedShardMarker = (entityType, index, record) => {
356
415
  `Include ${absent.length === 1 ? "it" : "them"} in the write.`,
357
416
  });
358
417
  }
359
- return shardMarker(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count));
418
+ return shardMarker(shards.count, shardOf(source.map((attr) => serializeValue(given(record, attr))), shards.count));
360
419
  };
361
420
  /**
362
421
  * `index` as its unsharded layout: what a `previous: 1` migration reads, and the
@@ -379,7 +438,7 @@ export const composeStoredPk = (schema, entityType, index, record) => {
379
438
  return undefined;
380
439
  const shards = index.shards;
381
440
  if (shards !== undefined &&
382
- !boundShardSource(index, shards).every((attr) => hasValue(record[attr]))) {
441
+ !boundShardSource(index, shards).every((attr) => hasValue(given(record, attr)))) {
383
442
  return undefined;
384
443
  }
385
444
  return outcome.length === index.pk.composite.length
@@ -432,12 +491,12 @@ const pinsShardSource = (index, source, record) => {
432
491
  const pins = new Set(index.pk.composite);
433
492
  if (!isZOrderHalf(index.sk)) {
434
493
  for (const attr of index.sk.composite) {
435
- if (!hasValue(record[attr]))
494
+ if (!hasValue(given(record, attr)))
436
495
  break;
437
496
  pins.add(attr);
438
497
  }
439
498
  }
440
- return source.every((attr) => pins.has(attr) && hasValue(record[attr]));
499
+ return source.every((attr) => pins.has(attr) && hasValue(given(record, attr)));
441
500
  };
442
501
  /**
443
502
  * The partitions a query of `index` reads for the pinned composites in `record`,
@@ -461,7 +520,7 @@ options) => {
461
520
  const pruned = options?.prune !== false && pinsShardSource(index, source, record);
462
521
  const current = pruned
463
522
  ? [
464
- partition(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count)),
523
+ partition(shards.count, shardOf(source.map((attr) => serializeValue(given(record, attr))), shards.count)),
465
524
  ]
466
525
  : layout(shards.count);
467
526
  const unsharded = shards.previous === 1
@@ -492,7 +551,7 @@ options) => {
492
551
  */
493
552
  export const composeSk = (schema, entityType, entityVersion, index, record) => {
494
553
  assertStringHalf(index, "composeSk");
495
- const composites = extractKeyComposites(schema, index, index.sk.composite, record);
554
+ const composites = extractKeyComposites(schema, index, index.sk.composite, record, "sk");
496
555
  const names = [...index.sk.composite];
497
556
  const collection = index.collection;
498
557
  const collectionType = index.type ?? "isolated";
@@ -547,14 +606,14 @@ export const composeZOrderSk = (schema, index, record) => {
547
606
  }
548
607
  const casing = effectiveCasing(schema, index);
549
608
  const segments = prefix.map((part) => {
550
- const value = record[part.field];
609
+ const value = given(record, part.field);
551
610
  if (value === undefined || value === null) {
552
611
  throw new Error(`Missing composite attribute "${part.field}" in record`);
553
612
  }
554
- return prefixSegment(keyValueText(schema, value, casing), part.hash);
613
+ return prefixSegment(keyText(schema, siteCompositeText(schema, value, part.field, index, "sk"), casing), part.hash);
555
614
  });
556
615
  const levels = layout.dimensions.map((dim) => {
557
- const value = record[dim.field];
616
+ const value = given(record, dim.field);
558
617
  if (value === undefined || value === null) {
559
618
  throw new Error(`Missing composite attribute "${dim.field}" in record`);
560
619
  }
@@ -580,13 +639,32 @@ export const composeHistoryItemSegment = (schema, entityType, entityVersion, pri
580
639
  const bare = composeSk(schema, entityType, entityVersion, { ...primary, sk: { ...primary.sk, composite: [] } }, {});
581
640
  return liveSk.startsWith(`${bare}#`) ? liveSk.slice(bare.length + 1) : undefined;
582
641
  };
642
+ /**
643
+ * The attribute an index's `half` is stored under, for a write giving it a value. One named
644
+ * `__proto__` (an index whose composites a row may lack, so its definition loads) is refused
645
+ * (`[EDD-9165]`, a `KeyValueError`): the AWS SDK's marshaller drops it, and its unmarshaller drops
646
+ * one an update stored. A write that gives it no value (the index left out, or its half removed)
647
+ * is as it was.
648
+ */
649
+ const keyAttribute = (index, half) => {
650
+ const field = index[half].field;
651
+ if (field !== "__proto__")
652
+ return field;
653
+ const which = half === "pk" ? "partition" : "sort";
654
+ const named = index.index === undefined ? "the table" : `index "${index.index}"`;
655
+ throw new KeyValueError({
656
+ value: field,
657
+ reason: PROTO_ENTRY,
658
+ message: `The ${which} key attribute of ${named}: ${PROTO_ENTRY} [EDD-9165]`,
659
+ });
660
+ };
583
661
  /**
584
662
  * Compose all key attributes for a single index.
585
663
  * Returns a record mapping field names to composed key values.
586
664
  */
587
665
  export const composeIndexKeys = (schema, entityType, entityVersion, index, record) => ({
588
- [index.pk.field]: composePk(schema, entityType, index, record),
589
- [index.sk.field]: composeSkValue(schema, entityType, entityVersion, index, record),
666
+ [keyAttribute(index, "pk")]: composePk(schema, entityType, index, record),
667
+ [keyAttribute(index, "sk")]: composeSkValue(schema, entityType, entityVersion, index, record),
590
668
  });
591
669
  /**
592
670
  * Non-throwing variant of composeIndexKeys. Returns undefined if any composite
@@ -598,11 +676,30 @@ export const composeIndexKeys = (schema, entityType, entityVersion, index, recor
598
676
  * as text first — a Z-order half's `composite` lists its dimension fields.
599
677
  */
600
678
  export const tryComposeIndexKeys = (schema, entityType, entityVersion, index, record) => {
601
- const present = (composite) => composite.every((attr) => record[attr] !== undefined && record[attr] !== null);
679
+ const present = (composite) => composite.every((attr) => given(record, attr) !== undefined && given(record, attr) !== null);
602
680
  if (!present(index.pk.composite) || !present(index.sk.composite))
603
681
  return undefined;
604
682
  return composeIndexKeys(schema, entityType, entityVersion, index, record);
605
683
  };
684
+ /**
685
+ * The halves of a secondary index `record` holds every value of, for a write that leaves what it
686
+ * doesn't name as it's stored (an upsert). A half missing a value is left out, never truncated; a
687
+ * sharded index's partition half also needs what it hashes.
688
+ */
689
+ export const composeKnownHalves = (schema, entityType, entityVersion, index, record) => {
690
+ const shardSource = index.shards === undefined ? [] : boundShardSource(index, index.shards);
691
+ const complete = (composite) => composite.every((attr) => hasValue(given(record, attr)));
692
+ return {
693
+ ...(complete([...index.pk.composite, ...shardSource])
694
+ ? { [keyAttribute(index, "pk")]: composePk(schema, entityType, index, record) }
695
+ : {}),
696
+ ...(complete(index.sk.composite)
697
+ ? {
698
+ [keyAttribute(index, "sk")]: composeSkValue(schema, entityType, entityVersion, index, record),
699
+ }
700
+ : {}),
701
+ };
702
+ };
606
703
  /**
607
704
  * Compose keys for all indexes of an entity.
608
705
  * Returns a flat record of all key field -> value mappings.
@@ -634,7 +731,7 @@ export const composeAllKeys = (schema, entityType, entityVersion, indexes, recor
634
731
  */
635
732
  const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
636
733
  const slice = index.pk.composite.slice(0, stopBefore);
637
- return composePkText(schema, entityType, index, extractKeyComposites(schema, index, slice, record), slice, composedShardMarker(entityType, index, record));
734
+ return composePkText(schema, entityType, index, extractKeyComposites(schema, index, slice, record, "pk"), slice, composedShardMarker(entityType, index, record));
638
735
  };
639
736
  /**
640
737
  * Compose a sort key from the leading prefix `[sk_0, ..., sk_(stopBefore-1)]`
@@ -652,7 +749,7 @@ const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
652
749
  export const composeSkPrefixUpTo = (schema, entityType, entityVersion, index, record, stopBefore) => {
653
750
  assertStringHalf(index, "composeSkPrefixUpTo");
654
751
  const slice = index.sk.composite.slice(0, stopBefore);
655
- const composites = extractKeyComposites(schema, index, slice, record);
752
+ const composites = extractKeyComposites(schema, index, slice, record, "sk");
656
753
  const collection = index.collection;
657
754
  const collectionType = index.type ?? "isolated";
658
755
  if (collection !== undefined) {
@@ -710,7 +807,7 @@ const classifyHalf = (composites, record, policy, halfHasRemoved) => {
710
807
  }
711
808
  let leadingLen = 0;
712
809
  while (leadingLen < composites.length) {
713
- const v = record[composites[leadingLen]];
810
+ const v = given(record, composites[leadingLen]);
714
811
  if (v === undefined || v === null)
715
812
  break;
716
813
  leadingLen++;
@@ -722,7 +819,7 @@ const classifyHalf = (composites, record, policy, halfHasRemoved) => {
722
819
  // Some absent. Check for hole (a present composite after the absent run).
723
820
  let hasHole = false;
724
821
  for (let j = leadingLen + 1; j < composites.length; j++) {
725
- const v = record[composites[j]];
822
+ const v = given(record, composites[j]);
726
823
  if (v !== undefined && v !== null) {
727
824
  hasHole = true;
728
825
  break;
@@ -750,20 +847,164 @@ const classifyHalf = (composites, record, policy, halfHasRemoved) => {
750
847
  * - otherwise noop (`'preserve'`: the stored address may go stale).
751
848
  */
752
849
  const classifyZOrderHalf = (fields, record, policy, halfHasRemoved) => {
753
- if (fields.every((field) => record[field] !== undefined && record[field] !== null))
850
+ if (fields.every((field) => given(record, field) !== undefined && given(record, field) !== null))
754
851
  return "set";
755
852
  if (policy === "sparse" || halfHasRemoved)
756
853
  return "drop";
757
854
  return "noop";
758
855
  };
759
856
  const hasValue = (value) => value !== undefined && value !== null;
857
+ const FINE = { kind: "fine" };
858
+ const sameKeyValue = (a, b) => {
859
+ if (typeof a === "string" || typeof b === "string")
860
+ return a === b;
861
+ return a.length === b.length && a.every((byte, i) => byte === b[i]);
862
+ };
863
+ /** Is `stored` a leading run of `composites`' text, under any form? */
864
+ const isLeadingRun = (judging, index, half, composites, record, stored) => {
865
+ if (typeof stored !== "string")
866
+ return false;
867
+ for (const form of judging.forms) {
868
+ for (let length = 0; length < composites.length; length++) {
869
+ try {
870
+ const text = half === "pk"
871
+ ? composePkPrefixUpTo(form.pk, judging.entityType, index, record, length)
872
+ : composeSkPrefixUpTo(form.sk, judging.entityType, judging.entityVersion, index, record, length);
873
+ if (text === stored)
874
+ return true;
875
+ }
876
+ catch {
877
+ // No text under this form: `NaN` under `escapeKeys: true`.
878
+ }
879
+ }
880
+ }
881
+ return false;
882
+ };
883
+ /**
884
+ * Whether `stored` differs from what `record` composes only in the text of `attr`, the composite
885
+ * whose key may lag. An update that can't compose a half holding it leaves the key, so this is what
886
+ * a healthy row looks like, and comparing the whole key would rewrite it on every run after any
887
+ * write. Everything around the segment has to match exactly, and the segment has to be one segment.
888
+ * A Z-order address has no segments to read apart, so any address it holds will do.
889
+ */
890
+ const differsOnlyInLaggingText = (judging, index, half, composites, record, stored, attr) => {
891
+ if (half === "sk" && isZOrderHalf(index.sk))
892
+ return true;
893
+ if (typeof stored !== "string")
894
+ return false;
895
+ const { schema, entityType, entityVersion } = judging;
896
+ const blank = { ...record, [attr]: "" };
897
+ const position = composites.indexOf(attr) + 1;
898
+ const head = half === "pk"
899
+ ? composePkPrefixUpTo(schema, entityType, index, blank, position)
900
+ : composeSkPrefixUpTo(schema, entityType, entityVersion, index, blank, position);
901
+ const whole = half === "pk"
902
+ ? composePk(schema, entityType, index, blank)
903
+ : composeSkValue(schema, entityType, entityVersion, index, blank);
904
+ if (typeof whole !== "string")
905
+ return false;
906
+ const tail = whole.slice(head.length);
907
+ if (stored.length <= head.length + tail.length)
908
+ return false;
909
+ if (!stored.startsWith(head) || !stored.endsWith(tail))
910
+ return false;
911
+ return !stored.slice(head.length, stored.length - tail.length).includes("#");
912
+ };
913
+ /**
914
+ * Judge one half of a stored row's index against what its values compose, for `rekey`'s report and
915
+ * `repairIndexKeys` (`rekey-repair.md`). Reads nothing and writes nothing. `stored` is what the
916
+ * half's attribute holds as read; `record` is the row's key form.
917
+ *
918
+ * A half with every composite on the row should hold what a `put` of them writes: the same
919
+ * composers, so a Z-order half is all or nothing and compares bytes, and a value within one
920
+ * quantization level is no difference. A half with one missing is the update path's business: under
921
+ * `preserve` it's left whatever it holds, which is what the policy promises; under `sparse` it holds
922
+ * what the structural rule composes (a trailing composite absent is a truncation, shape 3), or
923
+ * nothing. A half with no key whose index a `put` wouldn't have written whole has nothing missing.
924
+ *
925
+ * A half holding `updatedAt` is compared without that composite's text, so a key that only lags
926
+ * stays `fine` and a key that holds anything else is rewritten once, from the row's value, and is
927
+ * `fine` from then on, whatever later writes do to `updatedAt`.
928
+ *
929
+ * Not judged, so `fine`: values that compose no key (`NaN`, a Z-order value a dimension can't place,
930
+ * a shard it can't compute), which a `put` refuses too; and a sharded partition key that's stored,
931
+ * since `rekey` already rewrites or reports those.
932
+ */
933
+ export const judgeIndexHalf = (judging, index, half, stored, record) => {
934
+ const { schema, entityType, entityVersion, primaryComposites, stamped, lagTolerated } = judging;
935
+ const composites = half === "pk" ? index.pk.composite : index.sk.composite;
936
+ if (half === "pk" && index.shards !== undefined && stored !== undefined)
937
+ return FINE;
938
+ const shardSource = index.shards === undefined ? [] : boundShardSource(index, index.shards);
939
+ const policy = resolveIndexPolicy(index.indexPolicy)[half];
940
+ try {
941
+ if (composites.every((attr) => hasValue(given(record, attr)))) {
942
+ const full = half === "pk"
943
+ ? composePk(schema, entityType, index, record)
944
+ : composeSkValue(schema, entityType, entityVersion, index, record);
945
+ if (stored !== undefined) {
946
+ if (sameKeyValue(stored, full))
947
+ return FINE;
948
+ if (lagTolerated !== null &&
949
+ composites.includes(lagTolerated) &&
950
+ differsOnlyInLaggingText(judging, index, half, composites, record, stored, lagTolerated)) {
951
+ return FINE;
952
+ }
953
+ return {
954
+ kind: "set",
955
+ drift: isLeadingRun(judging, index, half, composites, record, stored)
956
+ ? "truncated"
957
+ : "lagging",
958
+ value: full,
959
+ };
960
+ }
961
+ // `put` writes an index whole or not at all.
962
+ const wholeIndex = [...index.pk.composite, ...index.sk.composite, ...shardSource].every((attr) => hasValue(given(record, attr)));
963
+ if (!wholeIndex)
964
+ return FINE;
965
+ const outsidePrimary = new Set(composites.filter((attr) => !primaryComposites.has(attr) && !stamped.has(attr)));
966
+ if (policy === "sparse" && outsidePrimary.size >= 2)
967
+ return { kind: "ambiguous" };
968
+ return { kind: "set", drift: "missing", value: full };
969
+ }
970
+ if (policy === "preserve" || stored === undefined)
971
+ return FINE;
972
+ if (half === "sk" && isZOrderHalf(index.sk))
973
+ return { kind: "remove" };
974
+ const outcome = classifyHalf(composites, record, "sparse", false);
975
+ if (outcome.kind !== "set")
976
+ return { kind: "remove" };
977
+ const truncated = half === "pk"
978
+ ? composePkPrefixUpTo(schema, entityType, index, record, outcome.length)
979
+ : composeSkPrefixUpTo(schema, entityType, entityVersion, index, record, outcome.length);
980
+ return sameKeyValue(stored, truncated)
981
+ ? FINE
982
+ : { kind: "set", drift: "lagging", value: truncated };
983
+ }
984
+ catch {
985
+ return FINE;
986
+ }
987
+ };
760
988
  /**
761
989
  * The per-half gate's question for a half with composites: does this writer name
762
990
  * none of them, while the half can't be recomposed from what it knows? Then the
763
991
  * half belongs to some other writer, and its stored key stays as it is.
764
992
  */
765
- const writerLeavesHalf = (composites, updatePayload, keyRecord) => composites.every((attr) => !(attr in updatePayload)) &&
766
- composites.some((attr) => !hasValue(keyRecord[attr]));
993
+ const writerLeavesHalf = (composites, updatePayload, keyRecord) => composites.every((attr) => !Object.hasOwn(updatePayload, attr)) &&
994
+ composites.some((attr) => !hasValue(given(keyRecord, attr)));
995
+ /**
996
+ * Whether a write leaves a half holding a value it stamps itself (`DESIGN.md` §7, "Composites the
997
+ * library stamps"). Every update stamps it, so the stamp says nothing about who owns the half, and
998
+ * asking the skip-predicate would make every unrelated update "touch" it: under `sparse` that drops
999
+ * the row, the bug #183 stopped. Only the half's other composites count. All of them known: the
1000
+ * half moves with the write. One unknown: the key lags until a write can compose it, under either
1001
+ * policy. A composite the writer explicitly clears isn't left: that's the structural rule's.
1002
+ */
1003
+ const writerLeavesStampedHalf = (composites, stamped, updatePayload, keyRecord) => {
1004
+ const others = composites.filter((attr) => !Object.hasOwn(stamped, attr));
1005
+ return (others.some((attr) => !hasValue(given(updatePayload, attr)) && !hasValue(given(keyRecord, attr))) &&
1006
+ others.every((attr) => !Object.hasOwn(updatePayload, attr) || hasValue(given(updatePayload, attr))));
1007
+ };
767
1008
  /**
768
1009
  * The PK half's outcome on a sharded index, from what {@link classifyHalf} says
769
1010
  * of its composites and what the update did to the shard source (design §5). On
@@ -783,8 +1024,8 @@ const shardedPkOutcome = (entityType, index, outcome, update) => {
783
1024
  const refuse = () => {
784
1025
  if (update.onMissing === "keep")
785
1026
  return { kind: "noop" };
786
- const absent = boundShardSource(index, shards).filter((attr) => !hasValue(merged[attr]));
787
- const missing = absent.length > 0 ? absent : pkComposites.filter((a) => !hasValue(merged[a]));
1027
+ const absent = boundShardSource(index, shards).filter((attr) => !hasValue(given(merged, attr)));
1028
+ const missing = absent.length > 0 ? absent : pkComposites.filter((a) => !hasValue(given(merged, a)));
788
1029
  throw new ShardSourceError({
789
1030
  message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
790
1031
  `sharded by, and its partition key can't be composed without ` +
@@ -796,12 +1037,12 @@ const shardedPkOutcome = (entityType, index, outcome, update) => {
796
1037
  return { kind: "drop" };
797
1038
  if (outcome.kind === "drop") {
798
1039
  const pkExplicitlyGone = update.pkHasRemoved ||
799
- pkComposites.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
1040
+ pkComposites.some((attr) => Object.hasOwn(updatePayload, attr) && !hasValue(given(updatePayload, attr)));
800
1041
  return update.byTouched && !pkExplicitlyGone ? refuse() : outcome;
801
1042
  }
802
1043
  if (outcome.kind === "noop")
803
1044
  return update.byTouched ? refuse() : outcome;
804
- if (boundShardSource(index, shards).every((attr) => hasValue(merged[attr]))) {
1045
+ if (boundShardSource(index, shards).every((attr) => hasValue(given(merged, attr)))) {
805
1046
  // The shard follows `by`, and the sort key would stay at the old value: no pin
806
1047
  // could reach the row, since each searches the shard its own value hashes to and
807
1048
  // only the old value's text is stored. The update may name the value the row
@@ -809,7 +1050,7 @@ const shardedPkOutcome = (entityType, index, outcome, update) => {
809
1050
  if (update.byTouched && update.skKept) {
810
1051
  if (update.onMissing === "keep")
811
1052
  return { kind: "noop" };
812
- const missing = index.sk.composite.filter((attr) => !hasValue(merged[attr]));
1053
+ const missing = index.sk.composite.filter((attr) => !hasValue(given(merged, attr)));
813
1054
  throw new ShardSourceError({
814
1055
  message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
815
1056
  `sharded by, and its sort key can't be composed without ` +
@@ -825,7 +1066,7 @@ const shardedPkOutcome = (entityType, index, outcome, update) => {
825
1066
  return { kind: "drop" };
826
1067
  // The source is incomplete: an update changing the partition or part of `by`
827
1068
  // can't compute the shard; any other leaves the stored key alone.
828
- return update.byTouched || pkComposites.some((attr) => hasValue(updatePayload[attr]))
1069
+ return update.byTouched || pkComposites.some((attr) => hasValue(given(updatePayload, attr)))
829
1070
  ? refuse()
830
1071
  : { kind: "noop" };
831
1072
  };
@@ -904,6 +1145,10 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
904
1145
  const sets = {};
905
1146
  const removes = [];
906
1147
  const removedSet = options?.removedSet;
1148
+ const stamped = options?.stamped;
1149
+ const leavesHalf = (composites) => stamped !== undefined && composites.some((attr) => Object.hasOwn(stamped, attr))
1150
+ ? writerLeavesStampedHalf(composites, stamped, updatePayload, keyRecord)
1151
+ : writerLeavesHalf(composites, updatePayload, keyRecord);
907
1152
  for (const [indexName, index] of Object.entries(indexes)) {
908
1153
  if (indexName === "primary")
909
1154
  continue;
@@ -938,19 +1183,17 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
938
1183
  // touches it: the shard follows its value. Its presence in `keyRecord` is no
939
1184
  // evidence of a change. The retain path's holds the whole item.
940
1185
  const by = index.shards?.by ?? [];
941
- const byTouched = by.some((attr) => hasValue(updatePayload[attr]));
942
- const byCleared = by.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
1186
+ const byTouched = by.some((attr) => hasValue(given(updatePayload, attr)));
1187
+ const byCleared = by.some((attr) => Object.hasOwn(updatePayload, attr) && !hasValue(given(updatePayload, attr)));
943
1188
  const byRemoved = removedSet !== undefined && by.some((attr) => removedSet.has(attr));
944
1189
  // An empty PK half is a constant prefix, unless `by` makes its marker vary.
945
1190
  const skipPk = (pkComposites.length > 0
946
- ? !pkHasRemoved && writerLeavesHalf(pkComposites, updatePayload, keyRecord)
947
- : by.length > 0 && by.some((attr) => !hasValue(keyRecord[attr]))) &&
1191
+ ? !pkHasRemoved && leavesHalf(pkComposites)
1192
+ : by.length > 0 && by.some((attr) => !hasValue(given(keyRecord, attr)))) &&
948
1193
  !byTouched &&
949
1194
  !byCleared &&
950
1195
  !byRemoved;
951
- const skipSk = skComposites.length > 0 &&
952
- !skHasRemoved &&
953
- writerLeavesHalf(skComposites, updatePayload, keyRecord);
1196
+ const skipSk = skComposites.length > 0 && !skHasRemoved && leavesHalf(skComposites);
954
1197
  if (skipPk && skipSk)
955
1198
  continue;
956
1199
  // Build merged record for value extraction. Two-way classification: any
@@ -965,13 +1208,14 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
965
1208
  delete merged[k];
966
1209
  continue;
967
1210
  }
968
- merged[k] = v;
1211
+ setOwn(merged, k, v);
969
1212
  }
970
1213
  if (removedSet !== undefined) {
971
1214
  for (const attr of removedSet) {
972
1215
  delete merged[attr];
973
1216
  }
974
1217
  }
1218
+ Object.assign(merged, stamped);
975
1219
  const policy = resolveIndexPolicy(index.indexPolicy);
976
1220
  // A Z-order half is never a `by` source, so only a text half can disagree.
977
1221
  const skKept = !skipSk &&
@@ -993,7 +1237,7 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
993
1237
  removes.push(index.pk.field);
994
1238
  }
995
1239
  else if (pkOutcome.kind === "set") {
996
- sets[index.pk.field] =
1240
+ sets[keyAttribute(index, "pk")] =
997
1241
  pkOutcome.length === pkComposites.length
998
1242
  ? composePk(schema, entityType, index, merged)
999
1243
  : composePkPrefixUpTo(schema, entityType, index, merged, pkOutcome.length);
@@ -1007,7 +1251,7 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
1007
1251
  if (outcome === "drop")
1008
1252
  removes.push(index.sk.field);
1009
1253
  else if (outcome === "set")
1010
- sets[index.sk.field] = composeZOrderSk(schema, index, merged);
1254
+ sets[keyAttribute(index, "sk")] = composeZOrderSk(schema, index, merged);
1011
1255
  }
1012
1256
  else if (!skipSk) {
1013
1257
  const skOutcome = classifyHalf(skComposites, merged, policy.sk, skHasRemoved);
@@ -1015,7 +1259,7 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
1015
1259
  removes.push(index.sk.field);
1016
1260
  }
1017
1261
  else if (skOutcome.kind === "set") {
1018
- sets[index.sk.field] =
1262
+ sets[keyAttribute(index, "sk")] =
1019
1263
  skOutcome.length === skComposites.length
1020
1264
  ? composeSk(schema, entityType, entityVersion, index, merged)
1021
1265
  : composeSkPrefixUpTo(schema, entityType, entityVersion, index, merged, skOutcome.length);
@@ -1067,7 +1311,7 @@ export const tryComposeVectorPartition = (schema, entityType, index, record) =>
1067
1311
  * sparse-index outcome.
1068
1312
  */
1069
1313
  export const composeVectorPartition = (schema, entityType, index, record) => {
1070
- const composites = extractKeyComposites(schema, index, index.partition, record);
1314
+ const composites = extractKeyComposites(schema, index, index.partition, record, "pk");
1071
1315
  return composeKey(schema, entityType, composites, {
1072
1316
  casing: index.casing,
1073
1317
  names: [...index.partition],
@@ -1081,7 +1325,7 @@ const availableSkCount = (index, record) => {
1081
1325
  assertStringHalf(index, "availableSkCount");
1082
1326
  let n = 0;
1083
1327
  for (const attr of index.sk.composite) {
1084
- const value = record[attr];
1328
+ const value = given(record, attr);
1085
1329
  if (value === undefined || value === null)
1086
1330
  break;
1087
1331
  n++;
@@ -1133,6 +1377,192 @@ export const composeSortKeyBeginsWith = (schema, entityType, entityVersion, inde
1133
1377
  * a composite's label, and no label reaches U+FFFF.
1134
1378
  */
1135
1379
  export const SORT_KEY_MAX = "\uFFFF";
1380
+ /**
1381
+ * @internal The key spaces of an index's partition and sort keys ({@link KeySpace}), as {@link composePk} and
1382
+ * {@link composeSk} write them. Each walked composite's value is composed as U+FFFF, which no
1383
+ * casing or escaping changes and no label holds, and the text is cut there. The walk goes on past a
1384
+ * composite whose values `valuesOf` says can't hold the delimiter: its value ends where the next
1385
+ * label starts. It stops at the first that can (`"open"`): a partition key's values aren't
1386
+ * escaped, so text after one can always match another key's. Without `valuesOf`, at the first
1387
+ * composite. A composite limited to `values` is their key text under the schema's setting, or
1388
+ * with `everyForm` under every setting a row can have been written under (`escapeKeys` on, off,
1389
+ * and the 1.37 numeric text): the fixed text is the same under all of them. With `walkOpen` the
1390
+ * walk goes on past a composite that can hold the delimiter too, its value any text (`any`), so
1391
+ * the space is exactly the keys the composer writes for values of those kinds, to the end of the
1392
+ * key.
1393
+ */
1394
+ export const composeKeySpace = (schema, entityType, entityVersion, index, valuesOf = () => "open", options) => {
1395
+ const casing = index.casing ?? schema.casing;
1396
+ const forms = options?.everyForm === true
1397
+ ? [
1398
+ { ...schema, escapeKeys: true },
1399
+ { ...schema, escapeKeys: false },
1400
+ { ...schema, escapeKeys: false, numericKeyText: true },
1401
+ ]
1402
+ : [schema];
1403
+ const valueText = (values) => {
1404
+ if (values === "text")
1405
+ return { kind: "text" };
1406
+ if (values === "number")
1407
+ return { kind: "number" };
1408
+ if (values === "date" || values === "zonedDate") {
1409
+ return { kind: "date", zoned: values === "zonedDate" };
1410
+ }
1411
+ const texts = new Set();
1412
+ for (const value of values.values) {
1413
+ for (const form of forms) {
1414
+ try {
1415
+ // The composer cases the whole key again, which leaves cased text as it is.
1416
+ texts.add(applyCasing(keyValueText(form, value, casing), casing));
1417
+ }
1418
+ catch {
1419
+ // A value no key can hold (`NaN`) is no key's.
1420
+ }
1421
+ }
1422
+ }
1423
+ return { kind: "oneOf", texts: [...texts] };
1424
+ };
1425
+ const half = (composite, compose) => {
1426
+ const walked = [];
1427
+ const values = [];
1428
+ let open = false;
1429
+ for (const name of composite) {
1430
+ walked.push(name);
1431
+ const of = valuesOf(name);
1432
+ if (of === "open" && options?.walkOpen === true) {
1433
+ values.push({ kind: "any" });
1434
+ continue;
1435
+ }
1436
+ if (of === "open") {
1437
+ open = true;
1438
+ break;
1439
+ }
1440
+ values.push(valueText(of));
1441
+ }
1442
+ if (walked.length === 0)
1443
+ return { text: compose([], {}), after: [], values: [], open: false };
1444
+ const record = Object.create(null);
1445
+ for (const name of walked)
1446
+ record[name] = SORT_KEY_MAX;
1447
+ const [text = "", ...rest] = compose(walked, record).split(SORT_KEY_MAX);
1448
+ // The text after an open value isn't the key's: anything follows it.
1449
+ return { text, after: open ? rest.slice(0, -1) : rest, values, open };
1450
+ };
1451
+ return {
1452
+ pk: half(index.pk.composite, (composite, record) => composePk(schema, entityType, { ...index, pk: { ...index.pk, composite: [...composite] } }, record)),
1453
+ sk: half(index.sk.composite, (composite, record) => composeSk(schema, entityType, entityVersion, { ...index, sk: { ...index.sk, composite: [...composite] } }, record)),
1454
+ };
1455
+ };
1456
+ const ANY_CHARACTER = { chars: "", negated: true };
1457
+ const NOT_DELIMITER = { chars: KEY_DELIMITER, negated: true };
1458
+ /** The first character of a number's or a bigint's key text, under any setting. */
1459
+ const NUMBER_FIRST = { chars: "0123456789-:;", negated: false };
1460
+ /** Any other character of it: `NumericKey`'s, and 1.36's (`1e+21`, `Infinity`), in any casing. */
1461
+ const NUMBER_REST = { chars: "0123456789-+.:;)*eEiInNfFtTyY", negated: false };
1462
+ /** The first character of a date's ISO text: its year's first digit, or the sign of a wide year. */
1463
+ const DATE_FIRST = { chars: "0123456789+-", negated: false };
1464
+ /** Any other character of an instant's ISO text (`+275760-09-13T00:00:00.000Z`), in any casing. */
1465
+ const DATE_REST = { chars: "0123456789-+:.TtZz", negated: false };
1466
+ /** Whether some character is in both. */
1467
+ const classesMeet = (a, b) => {
1468
+ if (a.negated && b.negated)
1469
+ return true;
1470
+ if (!a.negated && !b.negated)
1471
+ return [...a.chars].some((char) => b.chars.includes(char));
1472
+ const [set, not] = a.negated ? [b, a] : [a, b];
1473
+ return [...set.chars].some((char) => !not.chars.includes(char));
1474
+ };
1475
+ /**
1476
+ * The keys of a {@link KeySpace} as an automaton: `edges[state]` are the moves on one character,
1477
+ * `empty[state]` those on none. It starts at state 0 and accepts at `accept`.
1478
+ */
1479
+ const keyAutomaton = (space) => {
1480
+ const edges = [];
1481
+ const empty = [];
1482
+ const state = () => {
1483
+ edges.push([]);
1484
+ empty.push([]);
1485
+ return edges.length - 1;
1486
+ };
1487
+ let at = state();
1488
+ /** The characters of `text`, one by one, from `from`: the state after them. */
1489
+ const spell = (from, text) => {
1490
+ let to = from;
1491
+ for (const char of text) {
1492
+ const next = state();
1493
+ edges[to].push([{ chars: char, negated: false }, next]);
1494
+ to = next;
1495
+ }
1496
+ return to;
1497
+ };
1498
+ at = spell(at, space.text);
1499
+ space.after.forEach((text, i) => {
1500
+ const value = space.values?.[i] ?? { kind: "text" };
1501
+ const end = state();
1502
+ if (value.kind === "text" || value.kind === "any") {
1503
+ const loop = state();
1504
+ empty[at].push(loop);
1505
+ edges[loop].push([value.kind === "any" ? ANY_CHARACTER : NOT_DELIMITER, loop]);
1506
+ empty[loop].push(end);
1507
+ }
1508
+ else if (value.kind === "number") {
1509
+ const digits = state();
1510
+ edges[at].push([NUMBER_FIRST, digits]);
1511
+ edges[digits].push([NUMBER_REST, digits]);
1512
+ empty[digits].push(end);
1513
+ }
1514
+ else if (value.kind === "date") {
1515
+ const rest = state();
1516
+ edges[at].push([DATE_FIRST, rest]);
1517
+ edges[rest].push([value.zoned ? NOT_DELIMITER : DATE_REST, rest]);
1518
+ empty[rest].push(end);
1519
+ }
1520
+ else {
1521
+ for (const option of value.texts)
1522
+ empty[spell(at, option)].push(end);
1523
+ }
1524
+ at = spell(end, text);
1525
+ });
1526
+ if (space.open)
1527
+ edges[at].push([ANY_CHARACTER, at]);
1528
+ return { edges, empty, accept: at };
1529
+ };
1530
+ /**
1531
+ * @internal Whether a key of one {@link KeySpace} can be a key of the other. Each is literal text
1532
+ * with values between, each value what its {@link KeyValueText} allows, and an open space ends in
1533
+ * any text at all. The two are read character against character, together, until both can end.
1534
+ */
1535
+ export const keySpacesMeet = (a, b) => {
1536
+ const x = keyAutomaton(a);
1537
+ const y = keyAutomaton(b);
1538
+ const width = y.edges.length;
1539
+ const seen = new Set();
1540
+ const queue = [];
1541
+ const visit = (i, j) => {
1542
+ const key = i * width + j;
1543
+ if (seen.has(key))
1544
+ return;
1545
+ seen.add(key);
1546
+ queue.push([i, j]);
1547
+ };
1548
+ visit(0, 0);
1549
+ for (let k = 0; k < queue.length; k++) {
1550
+ const [i, j] = queue[k];
1551
+ if (i === x.accept && j === y.accept)
1552
+ return true;
1553
+ for (const to of x.empty[i])
1554
+ visit(to, j);
1555
+ for (const to of y.empty[j])
1556
+ visit(i, to);
1557
+ for (const [left, toLeft] of x.edges[i]) {
1558
+ for (const [right, toRight] of y.edges[j]) {
1559
+ if (classesMeet(left, right))
1560
+ visit(toLeft, toRight);
1561
+ }
1562
+ }
1563
+ }
1564
+ return false;
1565
+ };
1136
1566
  /**
1137
1567
  * The condition selecting a complete sort key prefix on a secondary index, with
1138
1568
  * `escapeKeys: true`: the key itself, where the structural rule truncates a row whose
@@ -1204,7 +1634,7 @@ export const composeSortKeyPrefix = (schema, entityType, entityVersion, index, r
1204
1634
  const available = [];
1205
1635
  const names = [];
1206
1636
  for (const attr of index.sk.composite) {
1207
- const value = record[attr];
1637
+ const value = given(record, attr);
1208
1638
  if (value === undefined || value === null)
1209
1639
  break;
1210
1640
  available.push(keyValueText(schema, value, casing));
@@ -1249,8 +1679,14 @@ export const composeEventSk = (first, ...rest) => {
1249
1679
  return `${first}#${applyCasing(EVENT_SK_INFIX, casing)}#${escapeKeyText(serializeValue(rest[0]), casing)}`;
1250
1680
  }
1251
1681
  const casing = (rest[2] ?? first.casing);
1252
- return `${rest[0]}#${applyCasing(EVENT_SK_INFIX, casing)}#${keyValueText(first, rest[1], casing)}`;
1682
+ const text = keyText(first, siteCompositeText(first, rest[1], undefined, EVENT_SORT_KEY, "sk"), casing);
1683
+ return `${rest[0]}#${applyCasing(EVENT_SK_INFIX, casing)}#${text}`;
1253
1684
  };
1685
+ /**
1686
+ * The `key` of the site {@link composeEventSk} composes a time-series event's `orderBy` value at
1687
+ * (`DynamoSchema.ObjectKeySite`), which names no attribute.
1688
+ */
1689
+ export const EVENT_SORT_KEY = "timeSeries.orderBy";
1254
1690
  /**
1255
1691
  * The value of the `orderBy` attribute an event's sort key holds: its key form with numeric key
1256
1692
  * text, its encoded value (a `NumberFromString` `"10"` as the string `10`) with `escapeKeys` off,