effect-dynamodb 1.36.1 → 1.38.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 (87) hide show
  1. package/README.md +1 -1
  2. package/dist/Aggregate.d.ts +29 -17
  3. package/dist/Aggregate.d.ts.map +1 -1
  4. package/dist/Aggregate.js +795 -173
  5. package/dist/Aggregate.js.map +1 -1
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +196 -77
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +11 -2
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/Collections.d.ts +15 -6
  13. package/dist/Collections.d.ts.map +1 -1
  14. package/dist/Collections.js +2 -1
  15. package/dist/Collections.js.map +1 -1
  16. package/dist/DynamoClient.d.ts +122 -14
  17. package/dist/DynamoClient.d.ts.map +1 -1
  18. package/dist/DynamoClient.js +1151 -146
  19. package/dist/DynamoClient.js.map +1 -1
  20. package/dist/Entity.d.ts +126 -51
  21. package/dist/Entity.d.ts.map +1 -1
  22. package/dist/Entity.js +3491 -556
  23. package/dist/Entity.js.map +1 -1
  24. package/dist/EventStore.d.ts +12 -11
  25. package/dist/EventStore.d.ts.map +1 -1
  26. package/dist/EventStore.js +618 -55
  27. package/dist/EventStore.js.map +1 -1
  28. package/dist/Query.d.ts +311 -25
  29. package/dist/Query.d.ts.map +1 -1
  30. package/dist/Query.js +1159 -103
  31. package/dist/Query.js.map +1 -1
  32. package/dist/Table.d.ts +172 -3
  33. package/dist/Table.d.ts.map +1 -1
  34. package/dist/Table.js +85 -4
  35. package/dist/Table.js.map +1 -1
  36. package/dist/Transaction.d.ts +18 -2
  37. package/dist/Transaction.d.ts.map +1 -1
  38. package/dist/Transaction.js +62 -8
  39. package/dist/Transaction.js.map +1 -1
  40. package/dist/index.d.ts +6 -3
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/internal/BoundQuery.d.ts +226 -32
  45. package/dist/internal/BoundQuery.d.ts.map +1 -1
  46. package/dist/internal/BoundQuery.js +96 -18
  47. package/dist/internal/BoundQuery.js.map +1 -1
  48. package/dist/internal/Capacity.d.ts +8 -0
  49. package/dist/internal/Capacity.d.ts.map +1 -1
  50. package/dist/internal/Capacity.js +24 -4
  51. package/dist/internal/Capacity.js.map +1 -1
  52. package/dist/internal/Cursor.d.ts +90 -0
  53. package/dist/internal/Cursor.d.ts.map +1 -0
  54. package/dist/internal/Cursor.js +179 -0
  55. package/dist/internal/Cursor.js.map +1 -0
  56. package/dist/internal/ExpressionLimits.d.ts +18 -2
  57. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  58. package/dist/internal/ExpressionLimits.js +35 -2
  59. package/dist/internal/ExpressionLimits.js.map +1 -1
  60. package/dist/internal/ProjectionEngine.d.ts +16 -0
  61. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  62. package/dist/internal/ProjectionEngine.js +242 -46
  63. package/dist/internal/ProjectionEngine.js.map +1 -1
  64. package/dist/internal/RangePlanner.d.ts +394 -0
  65. package/dist/internal/RangePlanner.d.ts.map +1 -0
  66. package/dist/internal/RangePlanner.js +1296 -0
  67. package/dist/internal/RangePlanner.js.map +1 -0
  68. package/dist/internal/Rekey.d.ts +78 -0
  69. package/dist/internal/Rekey.d.ts.map +1 -0
  70. package/dist/internal/Rekey.js +323 -0
  71. package/dist/internal/Rekey.js.map +1 -0
  72. package/dist/internal/TransactPlan.d.ts +8 -1
  73. package/dist/internal/TransactPlan.d.ts.map +1 -1
  74. package/dist/internal/TransactPlan.js +9 -2
  75. package/dist/internal/TransactPlan.js.map +1 -1
  76. package/dist/internal/TransactWriteOps.d.ts +10 -7
  77. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  78. package/dist/internal/TransactWriteOps.js +82 -6
  79. package/dist/internal/TransactWriteOps.js.map +1 -1
  80. package/dist/internal/TransactableOps.d.ts +33 -2
  81. package/dist/internal/TransactableOps.d.ts.map +1 -1
  82. package/dist/internal/TransactableOps.js +55 -6
  83. package/dist/internal/TransactableOps.js.map +1 -1
  84. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  85. package/dist/internal/WriteDiagnosis.js +10 -7
  86. package/dist/internal/WriteDiagnosis.js.map +1 -1
  87. package/package.json +5 -5
@@ -12,19 +12,25 @@ import { Compression, make as makeCompressionRegistry, } from "@effect-dynamodb/
12
12
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
13
13
  import { Embedder } from "@effect-dynamodb/schema/Embedder.js";
14
14
  import { DynamoError, DynamoValidationError, InternalServerError, isAwsInternalServerError, isAwsResourceNotFound, isAwsThrottling, isAwsValidationError, ResourceNotFoundError, ThrottlingError, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
15
- import { compositeKeyFormKind, makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
15
+ import { compositeKeyFormKind, keyFormValueKind, makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
16
16
  import { makeDefaultCrypto } from "@effect-dynamodb/schema/internal/DefaultCrypto.js";
17
+ import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
18
+ import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
19
+ import * as ZOrderCurve from "@effect-dynamodb/schema/internal/ZOrderCurve.js";
17
20
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
18
- import { Config, Context, Crypto, Duration, Effect, Layer, Option, } from "effect";
21
+ import { Config, Context, DateTime, Duration, Effect, Layer, Option, SchemaAST, } from "effect";
22
+ import { SecureRandom } from "effect/crypto";
19
23
  import { bind as aggregateBind } from "./Aggregate.js";
20
24
  import { bind as entityBind, fromDefinition as entityFromDefinition } from "./Entity.js";
21
25
  import { BoundQueryImpl, collectionNaming, entityNaming, } from "./internal/BoundQuery.js";
22
26
  import { makeBoundVectorQuery, } from "./internal/BoundVectorQuery.js";
23
27
  import * as Capacity from "./internal/Capacity.js";
24
28
  import { redactCredentialRefusal } from "./internal/CredentialRefusal.js";
25
- import { createConditionOps } from "./internal/Expr.js";
29
+ import { createConditionOps, ExprTag } from "./internal/Expr.js";
26
30
  import { codecRequirements, collectionPackedQueryOptions, entityPackedQueryOptions, unregisteredCodecError, } from "./internal/Packed.js";
27
31
  import { createPathBuilder } from "./internal/PathBuilder.js";
32
+ import { canonicalJson, compareUtf8, compositePlanner, keyJustBelow, zorderPlanner, } from "./internal/RangePlanner.js";
33
+ import * as Rekey from "./internal/Rekey.js";
28
34
  import { diagnoseFailure, explainDiagnosis, withCause, } from "./internal/WriteDiagnosis.js";
29
35
  import * as Query from "./Query.js";
30
36
  import { mergeVectorIndexes, definition as tableDefinition, toVectorIndexSpec } from "./Table.js";
@@ -37,6 +43,942 @@ import { mergeVectorIndexes, definition as tableDefinition, toVectorIndexSpec }
37
43
  * character DynamoDB key composition emits for the following segment.
38
44
  */
39
45
  const SK_MAX_SENTINEL = "￿";
46
+ /**
47
+ * A composite value's key text as key composition writes it: serialized,
48
+ * cased and escaped (`KeyComposer.serializeSortKeyValue`), so it sorts as the
49
+ * cased value does.
50
+ */
51
+ const valueText = (casing, keyForm) => KeyComposer.serializeSortKeyValue(keyForm, casing);
52
+ /** A sort key composite's segment as key composition writes it: `<name>_<value>`, cased. */
53
+ export const compositeSegment = (casing, field, keyForm) => `${DynamoSchema.applyCasing(field, casing)}_${valueText(casing, keyForm)}`;
54
+ /** `bound` with each operand mapped — into its key form, say. */
55
+ const mapBound = (bound, f) => {
56
+ if ("eq" in bound)
57
+ return { eq: f(bound.eq) };
58
+ if ("lt" in bound)
59
+ return { lt: f(bound.lt) };
60
+ if ("lte" in bound)
61
+ return { lte: f(bound.lte) };
62
+ if ("gt" in bound)
63
+ return { gt: f(bound.gt) };
64
+ if ("gte" in bound)
65
+ return { gte: f(bound.gte) };
66
+ if ("between" in bound)
67
+ return { between: [f(bound.between[0]), f(bound.between[1])] };
68
+ return { beginsWith: f(bound.beginsWith) };
69
+ };
70
+ /**
71
+ * Does a composite's value satisfy `bound`, compared as key text (§11)? Key
72
+ * forms. Escaped key text sorts as the cased value, so this is the order the
73
+ * key condition reads in.
74
+ */
75
+ const boundHolds = (casing, bound, keyForm) => {
76
+ const text = valueText(casing, keyForm);
77
+ const against = (operand) => compareUtf8(text, valueText(casing, operand));
78
+ if ("eq" in bound)
79
+ return against(bound.eq) === 0;
80
+ if ("lt" in bound)
81
+ return against(bound.lt) < 0;
82
+ if ("lte" in bound)
83
+ return against(bound.lte) <= 0;
84
+ if ("gt" in bound)
85
+ return against(bound.gt) > 0;
86
+ if ("gte" in bound)
87
+ return against(bound.gte) >= 0;
88
+ if ("between" in bound)
89
+ return against(bound.between[0]) >= 0 && against(bound.between[1]) <= 0;
90
+ // A number has no text prefix: `beginsWith` on a numeric composite is `eq`.
91
+ const operand = bound.beginsWith;
92
+ return typeof operand === "number" || typeof operand === "bigint"
93
+ ? against(operand) === 0
94
+ : text.startsWith(valueText(casing, operand));
95
+ };
96
+ /**
97
+ * @internal Compose a bound on sort key composite `field` into a key condition, the
98
+ * same way `put` composes the stored key: `prefixText` — the key text of
99
+ * every composite before `field`, ending with the delimiter — then
100
+ * `<name>_<value>`. Operands are already in key form.
101
+ *
102
+ * A stored SK is `$schema#v1#entity#<name>_<cased value>#...`; comparing a
103
+ * raw operand against that is meaningless (issue #101 — `gte` matched the
104
+ * whole partition because `"1-009" < "ballkey_…"`, while `begins_with` /
105
+ * `between` matched nothing). So the operand is placed in the *position* of
106
+ * the composite it targets and composed like the key, with `serializeValue`,
107
+ * the `<name>_` prefix, the casing and the escaping.
108
+ *
109
+ * The condition is exact: a composite's key text is escaped
110
+ * (`KeyComposer.sortKeyText`), so it sorts as its value, and the delimiter
111
+ * that follows it sorts below every character it holds — a value's subtree
112
+ * (`v#…`) sorts after `v` itself and before every greater value (`v%20x`,
113
+ * `v0`), whatever characters the values hold (#171).
114
+ *
115
+ * `clampToPrefix` keeps a one-sided bound inside `prefixText`: DynamoDB allows
116
+ * one sort key condition, so once leading composites are pinned the open end
117
+ * is clamped and the condition becomes a `BETWEEN`. A strict `lt` on the last
118
+ * composite then ends at the greatest key text below the bound
119
+ * (`keyJustBelow`), BETWEEN being inclusive.
120
+ *
121
+ * Shared by `.where()` and `.within()` (#171), so the two can't drift.
122
+ */
123
+ export const composeRangeUnder = (index, prefixText, field, bound, options) => {
124
+ // A missing operand composes the prefix alone, without its delimiter — as
125
+ // `composeSortKeyPrefix` stops at the first missing composite.
126
+ const compose = (value) => value === undefined || value === null
127
+ ? prefixText.slice(0, -1)
128
+ : `${prefixText}${compositeSegment(index.casing, field, value)}`;
129
+ /**
130
+ * `begins_with` operand matching exactly the keys whose composite equals
131
+ * `value`: it stops on a segment boundary rather than leaking into sibling
132
+ * values (`status_done` vs `status_done_archived`, #115).
133
+ */
134
+ const subtreeBeginsWith = (value) => `${compose(value)}${DynamoSchema.KEY_DELIMITER}`;
135
+ /**
136
+ * A bound sorting strictly above every key whose composite is `value`, and
137
+ * strictly below the first key of any greater value.
138
+ *
139
+ * The delimiter here is UNCONDITIONAL, including on the last composite:
140
+ * `compose(v)￿` alone would sort below `compose(v + "0")`, which is a
141
+ * strictly greater value that must stay inside a `gt`. `compose(v)#￿` sits
142
+ * above `compose(v)` and below every longer value because `#` is lower than
143
+ * every character a composite's escaped text holds.
144
+ */
145
+ const aboveSubtree = (value) => `${compose(value)}${DynamoSchema.KEY_DELIMITER}${SK_MAX_SENTINEL}`;
146
+ /** Inclusive upper bound covering the whole subtree of `value`. */
147
+ const upper = (value) => (index.isLast ? compose(value) : aboveSubtree(value));
148
+ // `beginsWith` / `between` / `eq` carry the prefix in BOTH operands, so they
149
+ // never escape it.
150
+ if ("beginsWith" in bound) {
151
+ // A number has no text prefix: its key text is not its digits (`-3` is
152
+ // `-9999999999999996:`), and an integer's text prefixes its fractions'
153
+ // (3 of 3.14). `beginsWith` on a numeric composite is `eq` — what it
154
+ // amounted to up to 1.36 for non-negative integers, whose key text was
155
+ // fixed-width.
156
+ const operand = bound.beginsWith;
157
+ if (typeof operand === "number" || typeof operand === "bigint") {
158
+ return composeRangeUnder(index, prefixText, field, { eq: operand }, options);
159
+ }
160
+ return { beginsWith: compose(operand) };
161
+ }
162
+ if ("eq" in bound) {
163
+ return index.isLast ? { eq: compose(bound.eq) } : { beginsWith: subtreeBeginsWith(bound.eq) };
164
+ }
165
+ if ("between" in bound) {
166
+ return { between: [compose(bound.between[0]), upper(bound.between[1])] };
167
+ }
168
+ // One-sided operators are open on the other side, which is exactly right
169
+ // when nothing is clamped: the open end runs to the edge of the partition.
170
+ if (!options.clampToPrefix) {
171
+ if ("lt" in bound)
172
+ return { lt: compose(bound.lt) };
173
+ if ("lte" in bound)
174
+ return { lte: upper(bound.lte) };
175
+ // `>` is already exclusive of the composed value, so only a non-terminal
176
+ // target needs the subtree pushed past.
177
+ if ("gt" in bound)
178
+ return { gt: index.isLast ? compose(bound.gt) : aboveSubtree(bound.gt) };
179
+ return { gte: compose(bound.gte) };
180
+ }
181
+ const prefixMax = `${prefixText}${SK_MAX_SENTINEL}`;
182
+ if ("gte" in bound)
183
+ return { between: [compose(bound.gte), prefixMax] };
184
+ if ("gt" in bound)
185
+ return { between: [aboveSubtree(bound.gt), prefixMax] };
186
+ if ("lte" in bound)
187
+ return { between: [prefixText, upper(bound.lte)] };
188
+ // `lt`. On a non-terminal composite no stored key can equal the composed
189
+ // bound (trailing composites always follow), so BETWEEN's inclusive high end
190
+ // is harmless. On the LAST composite the bound IS a storable key: the high
191
+ // end is the greatest key text below it (`EDD-9046` refused this bound up to
192
+ // 1.36).
193
+ const below = compose(bound.lt);
194
+ return { between: [prefixText, index.isLast ? keyJustBelow(below) : below] };
195
+ };
196
+ /**
197
+ * @internal A `.within()` bound on composite `field` — its lower and / or upper end —
198
+ * composed under `prefixText` as {@link composeRangeUnder} composes each,
199
+ * clamped to it: one `BETWEEN` of the lower end's start and the upper end's
200
+ * end, or the one end given. `undefined` when no value satisfies both ends
201
+ * (`{ gt: 3, lte: 3 }`, `{ gte: "b", lt: "a" }`), judged on the ends' key
202
+ * text, which sorts as their values: nothing need be read, and the composed
203
+ * ends could be reversed, which DynamoDB refuses.
204
+ */
205
+ export const composeIntervalUnder = (index, prefixText, field, lower, upper) => {
206
+ const under = (bound) => composeRangeUnder(index, prefixText, field, bound, { clampToPrefix: true });
207
+ if (lower === undefined || upper === undefined) {
208
+ const one = lower ?? upper;
209
+ if (one === undefined)
210
+ throw new Error("[internal] A .within() range bound has no end.");
211
+ return under(one);
212
+ }
213
+ const operand = (bound) => valueText(index.casing, Object.values(bound)[0]);
214
+ const order = compareUtf8(operand(lower), operand(upper));
215
+ if (order > 0 || (order === 0 && ("gt" in lower || "lt" in upper)))
216
+ return undefined;
217
+ return { between: [under(lower).between[0], under(upper).between[1]] };
218
+ };
219
+ /** A composed sort key condition as a planned key range: only the forms a clamped bound composes. */
220
+ const keyRangeOf = (condition, exact) => {
221
+ if ("eq" in condition)
222
+ return { lower: condition.eq, upper: condition.eq, exact };
223
+ if ("between" in condition) {
224
+ return { lower: condition.between[0], upper: condition.between[1], exact };
225
+ }
226
+ if ("beginsWith" in condition) {
227
+ return { lower: undefined, upper: undefined, beginsWith: condition.beginsWith, exact };
228
+ }
229
+ throw new Error("[internal] .within() composed an unclamped sort key condition.");
230
+ };
231
+ const BOUND_OPERATORS = new Set(["eq", "between", "gt", "gte", "lt", "lte"]);
232
+ /**
233
+ * How a row check reads a composite's key form from a raw row (§11): its
234
+ * stored attribute — for a ref-derived `${ref}Id`, the referenced identifier
235
+ * inside the stored ref, which is the value the key was composed from —
236
+ * through the accessor's encoder for a numeric field stored as a string, so a
237
+ * stored `"950000"` reads as `950000`. `undefined` when the row lacks it.
238
+ */
239
+ const storedKeyForm = (args, field) => {
240
+ const resolve = args.entityLike._resolveDbName ?? ((name) => name);
241
+ const ref = args.entityLike._resolvedRefs?.find((r) => r.idFieldName === field);
242
+ const attribute = resolve(ref?.fieldName ?? field);
243
+ const schema = getSchemaFields(args.encoderSource)?.[field];
244
+ const wantsBigInt = schema !== undefined && SchemaAST.isBigInt(SchemaAST.toType(schema.ast));
245
+ const typeNumeric = compositeKeyFormKind(args.encoderSource, field) === "type-numeric";
246
+ return {
247
+ attribute,
248
+ read: (row) => {
249
+ const value = ref === undefined ? row[attribute] : row[attribute]?.M?.[ref.identifierField];
250
+ if (value === undefined)
251
+ return undefined;
252
+ const stored = value.S ?? value.N;
253
+ if (typeNumeric && stored !== undefined)
254
+ return args.compositeKeyForm(field, stored);
255
+ if (value.S !== undefined)
256
+ return value.S;
257
+ if (value.N !== undefined)
258
+ return wantsBigInt ? BigInt(value.N) : Number(value.N);
259
+ if (value.BOOL !== undefined)
260
+ return value.BOOL;
261
+ return undefined;
262
+ },
263
+ };
264
+ };
265
+ /**
266
+ * A composite's per-row check (§11): its key form read from the raw row
267
+ * ({@link storedKeyForm}), and `holds` asked of it; a row without it fails.
268
+ */
269
+ const compositeCheck = (args, field, holds) => {
270
+ const stored = storedKeyForm(args, field);
271
+ return {
272
+ field,
273
+ attribute: stored.attribute,
274
+ accepts: (row) => {
275
+ const keyForm = stored.read(row);
276
+ return keyForm !== undefined && holds(keyForm);
277
+ },
278
+ };
279
+ };
280
+ /** Field checks as one row check, every one of them passing; `undefined` for none. */
281
+ const combineRowChecks = (checks) => checks.length === 0
282
+ ? undefined
283
+ : {
284
+ fields: checks.map((check) => check.field),
285
+ reads: [...new Set(checks.map((check) => check.attribute))],
286
+ accepts: (row) => checks.every((check) => check.accepts(row)),
287
+ };
288
+ /**
289
+ * Plan `.within(bounds)` on a composite sort key accessor (design §7.1):
290
+ *
291
+ * - eq bounds right after the accessor's pins extend the prefix, like pins;
292
+ * - a range bound on the next composite (or nothing else bounded) is the `key`
293
+ * plan — one key condition, composed as `.where()` composes it;
294
+ * - otherwise the unbounded composites in between are the skip tuple:
295
+ * `skip-scan` when the tuple parse is sound (§7.3), else `filter`.
296
+ *
297
+ * Every bound the key condition can't express is checked per row (§11).
298
+ * Misuse from untyped code throws `[EDD-9093]`; a value that doesn't reach
299
+ * key form throws `[EDD-9050]` (the accessor's own encoder). `{}` plans
300
+ * nothing: the query is returned as it is.
301
+ */
302
+ const planCompositeWithin = (args) => {
303
+ const { entityLike, accessor, indexDef, compositeKeyForm, pinnedKeyForm } = args;
304
+ const sk = indexDef.sk.composite;
305
+ const n = sk.length;
306
+ const p = sk.findIndex((attr) => pinnedKeyForm[attr] === undefined);
307
+ const pinnedCount = p === -1 ? n : p;
308
+ const refuse = (why) => {
309
+ throw new Error(`[EDD-9093] .within() on index "${accessor}" of entity "${entityLike.entityType}": ${why}`);
310
+ };
311
+ if (typeof args.bounds !== "object" || args.bounds === null || Array.isArray(args.bounds)) {
312
+ return refuse("pass an object of bounds keyed by sort key composite.");
313
+ }
314
+ const open = sk.slice(pinnedCount);
315
+ const fields = getSchemaFields(args.encoderSource);
316
+ /** The ref a `${ref}Id` composite is derived from: the item stores the ref, not the id. */
317
+ const refOf = (field) => entityLike._resolvedRefs?.find((ref) => ref.idFieldName === field);
318
+ /** The kind of value a composite's key form is, when its schema says (EDD-9093's type check). */
319
+ const kindOf = (field) => {
320
+ const schema = fields?.[field];
321
+ return schema === undefined ? undefined : keyFormValueKind(schema);
322
+ };
323
+ // -- validate and normalise (EDD-9093) --
324
+ const bounds = new Map();
325
+ for (const [field, raw] of Object.entries(args.bounds)) {
326
+ if (raw === undefined)
327
+ continue;
328
+ const i = sk.indexOf(field);
329
+ if (i === -1) {
330
+ return refuse(indexDef.pk.composite.includes(field)
331
+ ? `"${field}" is a partition key composite: give it to the accessor.`
332
+ : `"${field}" is not a sort key composite of the index. Bound one of: ${open.join(", ")}.`);
333
+ }
334
+ if (i < pinnedCount) {
335
+ return refuse(`"${field}" is already pinned by the accessor, so it can't also be bounded. Drop it ` +
336
+ `from the accessor call to bound it here.`);
337
+ }
338
+ if (refOf(field) === undefined &&
339
+ compositeKeyFormKind(args.encoderSource, field) === "absent") {
340
+ return refuse(`"${field}" is not stored on the item, so its bound can't be checked per row. Give ` +
341
+ `it to the accessor, or bound it with .where().`);
342
+ }
343
+ const shape = raw;
344
+ const operators = typeof raw === "object" && raw !== null && !Array.isArray(raw)
345
+ ? Object.keys(shape).filter((key) => shape[key] !== undefined)
346
+ : [];
347
+ const between = shape?.between;
348
+ const wellFormed = operators.length > 0 &&
349
+ operators.every((key) => BOUND_OPERATORS.has(key)) &&
350
+ (operators.includes("eq") || operators.includes("between") ? operators.length === 1 : true) &&
351
+ !(operators.includes("gt") && operators.includes("gte")) &&
352
+ !(operators.includes("lt") && operators.includes("lte")) &&
353
+ (between === undefined || (Array.isArray(between) && between.length === 2));
354
+ if (!wellFormed) {
355
+ return refuse(`the bound on "${field}" is not one of { eq }, { between: [low, high] }, or ` +
356
+ `{ gt | gte } and / or { lt | lte }.`);
357
+ }
358
+ const expected = kindOf(field);
359
+ const keyForm = (value) => {
360
+ const converted = compositeKeyForm(field, value);
361
+ if (expected !== undefined && typeof converted !== expected) {
362
+ return refuse(`the bound on "${field}" is ${JSON.stringify(String(value))} (${typeof value}), but ` +
363
+ `the composite's key form is a ${expected}.`);
364
+ }
365
+ return converted;
366
+ };
367
+ if (operators.includes("eq")) {
368
+ bounds.set(i, { _tag: "eq", value: keyForm(shape.eq) });
369
+ continue;
370
+ }
371
+ const [low, high] = between ?? [];
372
+ bounds.set(i, {
373
+ _tag: "range",
374
+ lower: between !== undefined
375
+ ? { gte: keyForm(low) }
376
+ : "gt" in shape && shape.gt !== undefined
377
+ ? { gt: keyForm(shape.gt) }
378
+ : "gte" in shape && shape.gte !== undefined
379
+ ? { gte: keyForm(shape.gte) }
380
+ : undefined,
381
+ upper: between !== undefined
382
+ ? { lte: keyForm(high) }
383
+ : "lt" in shape && shape.lt !== undefined
384
+ ? { lt: keyForm(shape.lt) }
385
+ : "lte" in shape && shape.lte !== undefined
386
+ ? { lte: keyForm(shape.lte) }
387
+ : undefined,
388
+ });
389
+ }
390
+ if (bounds.size === 0)
391
+ return args.query;
392
+ // -- composition --
393
+ const casing = KeyComposer.effectiveCasing(entityLike._schema, indexDef);
394
+ const segment = (i, keyForm) => compositeSegment(casing, sk[i], keyForm);
395
+ const label = (i) => `${DynamoSchema.applyCasing(sk[i], casing)}_`;
396
+ /**
397
+ * Bound `i` composed under `prefixText`, clamped to it; `undefined` when no
398
+ * value satisfies it (`{ gt: 3, lte: 3 }`).
399
+ */
400
+ const composeBound = (prefixText, i) => {
401
+ const bound = bounds.get(i);
402
+ const index = { casing, isLast: i === n - 1 };
403
+ return bound._tag === "eq"
404
+ ? composeRangeUnder(index, prefixText, sk[i], { eq: bound.value }, { clampToPrefix: true })
405
+ : composeIntervalUnder(index, prefixText, sk[i], bound.lower, bound.upper);
406
+ };
407
+ /** Does bound `i` hold for a composite value (key form), compared as key text? */
408
+ const holds = (i, keyForm) => {
409
+ const bound = bounds.get(i);
410
+ if (bound._tag === "eq")
411
+ return boundHolds(casing, { eq: bound.value }, keyForm);
412
+ return ((bound.lower === undefined || boundHolds(casing, bound.lower, keyForm)) &&
413
+ (bound.upper === undefined || boundHolds(casing, bound.upper, keyForm)));
414
+ };
415
+ /**
416
+ * The key condition under `prefixText` from composite `from`: eq bounds
417
+ * extend the prefix, then one range bound (or the prefix alone). Returns
418
+ * the composites left to the row check.
419
+ */
420
+ const keyCondition = (prefixText, from) => {
421
+ let q = prefixText;
422
+ let i = from;
423
+ while (i < n) {
424
+ const bound = bounds.get(i);
425
+ if (bound === undefined)
426
+ break;
427
+ if (bound._tag === "eq" && i < n - 1) {
428
+ q = `${q}${segment(i, bound.value)}${DynamoSchema.KEY_DELIMITER}`;
429
+ i++;
430
+ continue;
431
+ }
432
+ return {
433
+ condition: composeBound(q, i),
434
+ checked: [...bounds.keys()].filter((j) => j > i),
435
+ };
436
+ }
437
+ return { condition: { beginsWith: q }, checked: [...bounds.keys()].filter((j) => j >= i) };
438
+ };
439
+ /**
440
+ * Bounds checked on the raw row (§11): each composite's key text is
441
+ * composed from the stored attribute — `serializeValue`, casing and
442
+ * escaping, the composer's own path — and compared with the bound's key
443
+ * text ({@link boundHolds}). Key text sorts as the value, so a row passes
444
+ * exactly when the key condition would have admitted it, and the skip and
445
+ * filter plans agree on every row. A ref-derived composite (`${ref}Id`) is
446
+ * read from the stored ref: the referenced identifier inside its map, which
447
+ * is the value the key was composed from.
448
+ */
449
+ const rowCheckFor = (indices) => combineRowChecks([...indices]
450
+ .sort((a, b) => a - b)
451
+ .map((i) => compositeCheck(args, sk[i], (keyForm) => holds(i, keyForm))));
452
+ // -- plan choice (§7.1) --
453
+ const prefix0 = KeyComposer.composeSortKeyBeginsWith(entityLike._schema, entityLike.entityType, 1, indexDef, pinnedKeyForm);
454
+ let k = pinnedCount;
455
+ let P = prefix0;
456
+ while (k < n - 1 && bounds.get(k)?._tag === "eq") {
457
+ P = `${P}${segment(k, bounds.get(k).value)}${DynamoSchema.KEY_DELIMITER}`;
458
+ k++;
459
+ }
460
+ let t = k;
461
+ while (t < n && !bounds.has(t))
462
+ t++;
463
+ const tupled = t < n && t > k;
464
+ const tupleFields = sk.slice(k, t);
465
+ const fingerprint = {
466
+ index: indexDef.index ?? "primary",
467
+ entityType: entityLike.entityType,
468
+ pk: args.pkValue,
469
+ prefix: prefix0,
470
+ bounds: [...bounds.entries()]
471
+ .sort(([a], [b]) => a - b)
472
+ .map(([i, bound]) => bound._tag === "eq"
473
+ ? [sk[i], "eq", segment(i, bound.value)]
474
+ : [
475
+ sk[i],
476
+ bound.lower === undefined ? null : Object.keys(bound.lower)[0],
477
+ bound.lower === undefined ? null : segment(i, Object.values(bound.lower)[0]),
478
+ bound.upper === undefined ? null : Object.keys(bound.upper)[0],
479
+ bound.upper === undefined ? null : segment(i, Object.values(bound.upper)[0]),
480
+ ]),
481
+ };
482
+ const inner = tupled ? keyCondition("", t) : keyCondition(prefix0, pinnedCount);
483
+ const innerRowCheck = rowCheckFor(inner.checked);
484
+ // No value satisfies some bound (`{ gt: 3, lte: 3 }`): nothing to read,
485
+ // whatever the prefix it is composed under.
486
+ const empty = [...bounds.keys()].some((i) => composeBound(prefix0, i) === undefined);
487
+ const space = tupled
488
+ ? {
489
+ _tag: "string",
490
+ prefix: P,
491
+ labels: tupleFields.map((_, j) => label(k + j)),
492
+ next: label(t),
493
+ fields: tupleFields,
494
+ }
495
+ : { _tag: "none" };
496
+ // Any tuple composite parses soundly from the key text: escaped values
497
+ // hold no delimiter (§7.3). History rows don't parse as tuples.
498
+ const ineligible = tupled && indexDef.index === undefined && entityLike._liveRows?.() !== undefined
499
+ ? "history rows on the primary index"
500
+ : undefined;
501
+ return Query.plan(args.query, {
502
+ planner: compositePlanner({
503
+ entityType: entityLike.entityType,
504
+ index: indexDef.index ?? "primary",
505
+ pkField: indexDef.pk.field,
506
+ pkValue: args.pkValue,
507
+ skField: indexDef.sk.field,
508
+ fingerprint,
509
+ space,
510
+ inner: {
511
+ _tag: "single",
512
+ conditionFor: (tuple) => {
513
+ const { condition } = tupled
514
+ ? keyCondition(tuple ?? P, t)
515
+ : keyCondition(prefix0, pinnedCount);
516
+ // An empty plan reads nothing, so it never asks for its range.
517
+ if (condition === undefined)
518
+ throw new Error("[internal] An empty plan has no range.");
519
+ return keyRangeOf(condition, innerRowCheck === undefined);
520
+ },
521
+ rowCheck: innerRowCheck,
522
+ empty,
523
+ },
524
+ filterPlan: {
525
+ prefix: P,
526
+ rowCheck: rowCheckFor([...bounds.keys()].filter((i) => i >= k)),
527
+ },
528
+ ineligible,
529
+ }),
530
+ maxSkips: args.options?.maxSkips,
531
+ });
532
+ };
533
+ /** What a Z-order dimension bound may name: a composite's operators, and `in` (literals). */
534
+ const DIMENSION_OPERATORS = new Set([...BOUND_OPERATORS, "in"]);
535
+ /** The most operands DynamoDB's `IN` takes. */
536
+ const MAX_IN_OPERANDS = 100;
537
+ /** How many Z-order range plans an accessor keeps (§5.4). */
538
+ const ZORDER_PLAN_CACHE = 64;
539
+ /**
540
+ * An accessor's LRU of Z-order range plans. A plan is a pure function of the
541
+ * layout (the accessor's), the box and the cap, so a miss only recomputes —
542
+ * no cursor depends on what is cached.
543
+ */
544
+ const makeZOrderPlans = (layout) => {
545
+ const cache = new Map();
546
+ return (box, maxRanges, refineFactor) => {
547
+ const key = canonicalJson({ box, maxRanges, refineFactor });
548
+ const hit = cache.get(key);
549
+ if (hit !== undefined) {
550
+ cache.delete(key);
551
+ cache.set(key, hit);
552
+ return hit;
553
+ }
554
+ const planned = ZOrderCurve.plan(layout, box, maxRanges, refineFactor);
555
+ cache.set(key, planned);
556
+ if (cache.size > ZORDER_PLAN_CACHE)
557
+ cache.delete(cache.keys().next().value);
558
+ return planned;
559
+ };
560
+ };
561
+ /** A plain object of bound operators (not a value: a `Date` and a `DateTime` are values). */
562
+ const isBoundShape = (u) => typeof u === "object" &&
563
+ u !== null &&
564
+ !Array.isArray(u) &&
565
+ !(u instanceof Date) &&
566
+ !DateTime.isDateTime(u);
567
+ /** The ends of a range bound (`eq` as both, inclusive). */
568
+ const boundEnds = (bound) => {
569
+ if ("eq" in bound && bound.eq !== undefined) {
570
+ return { lower: { value: bound.eq, strict: false }, upper: { value: bound.eq, strict: false } };
571
+ }
572
+ const between = bound.between;
573
+ if (between !== undefined) {
574
+ return {
575
+ lower: { value: between[0], strict: false },
576
+ upper: { value: between[1], strict: false },
577
+ };
578
+ }
579
+ return {
580
+ lower: bound.gt !== undefined
581
+ ? { value: bound.gt, strict: true }
582
+ : bound.gte !== undefined
583
+ ? { value: bound.gte, strict: false }
584
+ : undefined,
585
+ upper: bound.lt !== undefined
586
+ ? { value: bound.lt, strict: true }
587
+ : bound.lte !== undefined
588
+ ? { value: bound.lte, strict: false }
589
+ : undefined,
590
+ };
591
+ };
592
+ /** Numbers and bigints in numeric order (`bigint` against `bigint` exactly). */
593
+ const compareNumeric = (a, b) => {
594
+ if (typeof a === "bigint" && typeof b === "bigint")
595
+ return a < b ? -1 : a > b ? 1 : 0;
596
+ const x = Number(a);
597
+ const y = Number(b);
598
+ return x < y ? -1 : x > y ? 1 : 0;
599
+ };
600
+ /** Does `value` lie between the ends, as `compare` orders them? */
601
+ const withinEnds = (value, lower, upper, compare) => {
602
+ if (lower !== undefined) {
603
+ const order = compare(value, lower.value);
604
+ if (Number.isNaN(order) || order < 0 || (order === 0 && lower.strict))
605
+ return false;
606
+ }
607
+ if (upper !== undefined) {
608
+ const order = compare(value, upper.value);
609
+ if (Number.isNaN(order) || order > 0 || (order === 0 && upper.strict))
610
+ return false;
611
+ }
612
+ return true;
613
+ };
614
+ /**
615
+ * Plan `.within(bounds)` on a Z-order accessor (design §3.3, §5, §7.5, §11):
616
+ *
617
+ * - each dimension bound is put into key form through the accessor's encoder
618
+ * and quantized into the box (an inverted bound is the empty box: nothing
619
+ * is sent);
620
+ * - the given leading prefix composites are the key prefix `P`; from the first
621
+ * one left out, the prefix composites are a binary skip tuple, any given
622
+ * later one checked as each probed key is parsed;
623
+ * - the exact bounds are a `FilterExpression` on the stored attributes where
624
+ * DynamoDB's comparison agrees with the dimension's order, and a row check
625
+ * where it doesn't (numbers stored as strings, zoned dates, a `literals`
626
+ * selection too large for `IN`) and for hashed prefix values (collisions).
627
+ *
628
+ * Throws `[EDD-9093]` for misuse from untyped code, `[EDD-9050]` for a value
629
+ * that doesn't reach key form and `[EDD-9092]` for one no level holds — at
630
+ * `.within()`, so every terminal (and `explain`) has a valid box. `{}` plans
631
+ * nothing: the query is returned as it is.
632
+ */
633
+ const planZOrderWithin = (args) => {
634
+ const { entityLike, accessor, indexDef, compositeKeyForm } = args;
635
+ const refuse = (why) => {
636
+ throw new Error(`[EDD-9093] .within() on index "${accessor}" of entity "${entityLike.entityType}": ${why}`);
637
+ };
638
+ if (!KeyComposer.isZOrderHalf(indexDef.sk) || indexDef.sk.zorderHalf.layout === undefined) {
639
+ throw new Error("[internal] A Z-order .within() reached a sort key that isn't bound.");
640
+ }
641
+ const { prefix } = indexDef.sk.zorderHalf;
642
+ const layout = indexDef.sk.zorderHalf.layout;
643
+ if (!isBoundShape(args.bounds)) {
644
+ return refuse("pass an object of bounds keyed by dimension or prefix composite.");
645
+ }
646
+ const dimensions = layout.dimensions;
647
+ const named = [...prefix.map((part) => part.field), ...dimensions.map((dim) => dim.field)];
648
+ const fields = getSchemaFields(args.encoderSource);
649
+ /** `value` in the field's key form: `[EDD-9050]` from the encoder, `[EDD-9093]` for the wrong type. */
650
+ const keyForm = (field, value) => {
651
+ const converted = compositeKeyForm(field, value);
652
+ const schema = fields?.[field];
653
+ const expected = schema === undefined ? undefined : keyFormValueKind(schema);
654
+ if (expected !== undefined && typeof converted !== expected) {
655
+ return refuse(`the bound on "${field}" is ${JSON.stringify(String(value))} (${typeof value}), but ` +
656
+ `the field's key form is a ${expected}.`);
657
+ }
658
+ return converted;
659
+ };
660
+ // -- validate and normalise (EDD-9093) --
661
+ const prefixValues = new Map();
662
+ const bounded = new Map();
663
+ for (const [field, raw] of Object.entries(args.bounds)) {
664
+ if (raw === undefined)
665
+ continue;
666
+ const shape = isBoundShape(raw) ? raw : undefined;
667
+ const operators = shape === undefined ? [] : Object.keys(shape).filter((key) => shape[key] !== undefined);
668
+ if (prefix.some((part) => part.field === field)) {
669
+ if (operators.some((key) => DIMENSION_OPERATORS.has(key))) {
670
+ return refuse(`"${field}" is a prefix composite: it takes one exact value, not a range bound.`);
671
+ }
672
+ prefixValues.set(field, keyForm(field, raw));
673
+ continue;
674
+ }
675
+ const dimension = dimensions.find((dim) => dim.field === field);
676
+ if (dimension === undefined) {
677
+ return refuse(indexDef.pk.composite.includes(field)
678
+ ? `"${field}" is a partition key composite: give it to the accessor.`
679
+ : `"${field}" is not a dimension or prefix composite of the index. Bound one of: ` +
680
+ `${named.join(", ")}.`);
681
+ }
682
+ const between = shape?.between;
683
+ const members = shape?.in;
684
+ const wellFormed = shape !== undefined &&
685
+ operators.length > 0 &&
686
+ operators.every((key) => DIMENSION_OPERATORS.has(key)) &&
687
+ (["eq", "between", "in"].some((key) => operators.includes(key))
688
+ ? operators.length === 1
689
+ : true) &&
690
+ !(operators.includes("gt") && operators.includes("gte")) &&
691
+ !(operators.includes("lt") && operators.includes("lte")) &&
692
+ (between === undefined || (Array.isArray(between) && between.length === 2)) &&
693
+ (members === undefined || Array.isArray(members));
694
+ if (!wellFormed) {
695
+ return refuse(`the bound on "${field}" is not one of { eq }, { between: [low, high] }, { in: [...] } ` +
696
+ `(a literals dimension), or { gt | gte } and / or { lt | lte }.`);
697
+ }
698
+ if (members !== undefined && dimension.spec.kind !== "literals") {
699
+ return refuse(`"in" bounds only a literals dimension, and "${field}" is ${dimension.spec.kind}.`);
700
+ }
701
+ const converted = {};
702
+ for (const key of operators) {
703
+ converted[key] =
704
+ key === "between" || key === "in"
705
+ ? shape[key].map((value) => keyForm(field, value))
706
+ : keyForm(field, shape[key]);
707
+ }
708
+ bounded.set(field, { raw: shape, keyForm: converted });
709
+ }
710
+ if (prefixValues.size === 0 && bounded.size === 0)
711
+ return args.query;
712
+ /** A bound's epoch milliseconds: from the domain value when it has them, else its key form. */
713
+ const epochMs = (dimension, raw, key) => DateTime.isDateTime(raw)
714
+ ? DateTime.toEpochMillis(raw)
715
+ : raw instanceof Date
716
+ ? raw.getTime()
717
+ : ZOrderCurve.epochMsOf(dimension.storage, key);
718
+ /** Both ends of a bound: domain values and key forms side by side. */
719
+ const endsOf = (field) => {
720
+ const bound = bounded.get(field);
721
+ return { raw: boundEnds(bound.raw), key: boundEnds(bound.keyForm) };
722
+ };
723
+ /**
724
+ * An `Epoch` dimension's ends in its stored unit, exactly (§11): a stored
725
+ * second `s` stands for `s × 1000` ms, so each end is converted from the
726
+ * bound's epoch milliseconds — never from its key form, which floors.
727
+ */
728
+ const storedEnds = (dimension, seconds) => {
729
+ const { raw, key } = endsOf(dimension.field);
730
+ const convert = (end) => {
731
+ const r = raw[end];
732
+ const k = key[end];
733
+ if (r === undefined || k === undefined)
734
+ return undefined;
735
+ const ms = epochMs(dimension, r.value, k.value);
736
+ if (!seconds)
737
+ return { value: ms, strict: r.strict };
738
+ const u = ms / 1000;
739
+ return end === "lower"
740
+ ? { value: r.strict ? Math.floor(u) : Math.ceil(u), strict: r.strict }
741
+ : { value: r.strict ? Math.ceil(u) : Math.floor(u), strict: r.strict };
742
+ };
743
+ return { lower: convert("lower"), upper: convert("upper") };
744
+ };
745
+ /**
746
+ * The bound a dimension's levels are quantized from: its key form, except
747
+ * on epoch seconds, where the key form of a sub-second end is floored. There
748
+ * the whole stored seconds it holds decide the levels, and whether there are
749
+ * any: `{ gte: T, lt: T + 500 ms }` holds the second `T`, `{ gt: T, lt: T + 1 s }`
750
+ * none — inverted only once converted.
751
+ */
752
+ const quantizable = (dimension) => {
753
+ const keyForm = bounded.get(dimension.field).keyForm;
754
+ const storage = dimension.storage;
755
+ if (storage._tag !== "Epoch" || storage.unit !== "epochSeconds")
756
+ return keyForm;
757
+ const { lower, upper } = storedEnds(dimension, true);
758
+ return {
759
+ ...(lower === undefined ? {} : { gte: lower.strict ? lower.value + 1 : lower.value }),
760
+ ...(upper === undefined ? {} : { lte: upper.strict ? upper.value - 1 : upper.value }),
761
+ };
762
+ };
763
+ // -- the box (§5.1) and each literals dimension's exact selection --
764
+ const literalSelection = (dimension, bound) => {
765
+ const index = (value) => Number(dimension.quantize(value));
766
+ if (bound.eq !== undefined)
767
+ return [index(bound.eq)];
768
+ if (bound.in !== undefined) {
769
+ return [...new Set(bound.in.map(index))].sort((a, b) => a - b);
770
+ }
771
+ const between = bound.between;
772
+ const lo = between !== undefined
773
+ ? index(between[0])
774
+ : bound.gt !== undefined
775
+ ? index(bound.gt) + 1
776
+ : bound.gte !== undefined
777
+ ? index(bound.gte)
778
+ : 0;
779
+ const hi = between !== undefined
780
+ ? index(between[1])
781
+ : bound.lt !== undefined
782
+ ? index(bound.lt) - 1
783
+ : bound.lte !== undefined
784
+ ? index(bound.lte)
785
+ : Number(dimension.levels) - 1;
786
+ return Array.from({ length: Math.max(0, hi - lo + 1) }, (_, i) => lo + i);
787
+ };
788
+ const { box, selections } = (() => {
789
+ try {
790
+ const quantized = ZOrderCurve.quantizeBounds(layout, Object.fromEntries(dimensions
791
+ .filter((dim) => bounded.has(dim.field))
792
+ .map((dim) => [dim.field, quantizable(dim)])));
793
+ const selected = new Map(dimensions
794
+ .filter((dim) => dim.spec.kind === "literals" && bounded.has(dim.field))
795
+ .map((dim) => [dim.field, literalSelection(dim, bounded.get(dim.field).keyForm)]));
796
+ const none = [...selected.values()].some((members) => members.length === 0);
797
+ return { box: none ? "empty" : quantized, selections: selected };
798
+ }
799
+ catch (error) {
800
+ // A value that reaches key form but no level (§3.3): thrown, like EDD-9050.
801
+ if (ZOrderCurve.isZOrderValueError(error))
802
+ throw new Error(error.message);
803
+ throw error;
804
+ }
805
+ })();
806
+ // -- exact bounds (§11): a FilterExpression where DynamoDB's order agrees, else row checks --
807
+ const path = (field) => ({ _tag: "path", segments: [field] });
808
+ const compare = (field, op, value) => ({
809
+ [ExprTag]: ExprTag,
810
+ _tag: op,
811
+ left: path(field),
812
+ right: { _tag: "value", value },
813
+ });
814
+ const membership = (field, values) => ({
815
+ [ExprTag]: ExprTag,
816
+ _tag: "in",
817
+ operand: path(field),
818
+ values: values.map((value) => ({ _tag: "value", value })),
819
+ });
820
+ const rangeFilter = (field, lower, upper) => lower !== undefined &&
821
+ upper !== undefined &&
822
+ !lower.strict &&
823
+ !upper.strict &&
824
+ lower.value === upper.value
825
+ ? [compare(field, "eq", lower.value)]
826
+ : [
827
+ ...(lower === undefined
828
+ ? []
829
+ : [compare(field, lower.strict ? "gt" : "gte", lower.value)]),
830
+ ...(upper === undefined
831
+ ? []
832
+ : [compare(field, upper.strict ? "lt" : "lte", upper.value)]),
833
+ ];
834
+ const filters = [];
835
+ const dimensionChecks = [];
836
+ for (const dimension of dimensions) {
837
+ const field = dimension.field;
838
+ if (!bounded.has(field))
839
+ continue;
840
+ const storage = dimension.storage;
841
+ if (storage._tag === "Literal") {
842
+ const values = dimension.spec.values;
843
+ const selected = selections.get(field) ?? [];
844
+ if (selected.length === values.length)
845
+ continue;
846
+ const chosen = new Set(selected.map((i) => values[i]));
847
+ const complement = values.filter((value) => !chosen.has(value));
848
+ if (chosen.size <= MAX_IN_OPERANDS) {
849
+ filters.push(membership(field, [...chosen]));
850
+ }
851
+ else if (complement.length <= MAX_IN_OPERANDS) {
852
+ // Exact: every item in the index carries the attribute (the half needs it).
853
+ filters.push({
854
+ [ExprTag]: ExprTag,
855
+ _tag: "not",
856
+ expr: membership(field, complement),
857
+ });
858
+ }
859
+ else {
860
+ const stored = storedKeyForm(args, field);
861
+ dimensionChecks.push({
862
+ field,
863
+ attribute: stored.attribute,
864
+ accepts: (row) => chosen.has(stored.read(row)),
865
+ });
866
+ }
867
+ continue;
868
+ }
869
+ const { raw, key } = endsOf(field);
870
+ switch (storage._tag) {
871
+ case "Number":
872
+ case "UtcIsoString":
873
+ case "RawString":
874
+ filters.push(...rangeFilter(field, key.lower, key.upper));
875
+ break;
876
+ case "Epoch": {
877
+ const stored = storedEnds(dimension, storage.unit === "epochSeconds");
878
+ filters.push(...rangeFilter(field, stored.lower, stored.upper));
879
+ break;
880
+ }
881
+ case "NumericString": {
882
+ // S order isn't numeric order: compared on the key form, per row.
883
+ const stored = storedKeyForm(args, field);
884
+ dimensionChecks.push({
885
+ field,
886
+ attribute: stored.attribute,
887
+ accepts: (row) => {
888
+ const value = stored.read(row);
889
+ return value !== undefined && withinEnds(value, key.lower, key.upper, compareNumeric);
890
+ },
891
+ });
892
+ break;
893
+ }
894
+ case "ZonedIsoString": {
895
+ // ISO strings with offsets don't sort chronologically: compared as epoch ms, per row.
896
+ const stored = storedKeyForm(args, field);
897
+ const toMs = (end, k) => end === undefined || k === undefined
898
+ ? undefined
899
+ : { value: epochMs(dimension, end.value, k.value), strict: end.strict };
900
+ const lower = toMs(raw.lower, key.lower);
901
+ const upper = toMs(raw.upper, key.upper);
902
+ dimensionChecks.push({
903
+ field,
904
+ attribute: stored.attribute,
905
+ accepts: (row) => {
906
+ const ms = ZOrderCurve.epochMsOf(storage, stored.read(row));
907
+ return Number.isFinite(ms) && withinEnds(ms, lower, upper, compareNumeric);
908
+ },
909
+ });
910
+ break;
911
+ }
912
+ }
913
+ }
914
+ // -- the prefix (§4.3, §7.5) --
915
+ const casing = KeyComposer.effectiveCasing(entityLike._schema, indexDef);
916
+ const textOf = (value) => valueText(casing, value);
917
+ const segmentOf = (part) => ZOrderCurve.prefixSegment(textOf(prefixValues.get(part.field)), part.hash);
918
+ /** A given prefix composite, checked on the cased value — never a hash, which can collide. */
919
+ const prefixCheck = (part) => {
920
+ const stored = storedKeyForm(args, part.field);
921
+ const wanted = textOf(prefixValues.get(part.field));
922
+ return {
923
+ field: part.field,
924
+ attribute: stored.attribute,
925
+ accepts: (row) => {
926
+ const value = stored.read(row);
927
+ return value !== undefined && textOf(value) === wanted;
928
+ },
929
+ };
930
+ };
931
+ const firstMissing = prefix.findIndex((part) => !prefixValues.has(part.field));
932
+ const leading = firstMissing === -1 ? prefix : prefix.slice(0, firstMissing);
933
+ const later = firstMissing === -1 ? [] : prefix.slice(firstMissing);
934
+ const hashed = prefix.filter((part) => part.hash !== undefined && prefixValues.has(part.field));
935
+ const parsedExactly = later.filter((part) => part.hash === undefined && prefixValues.has(part.field));
936
+ const renameExpr = entityNaming(entityLike._resolveDbName).renameExpr ?? ((expr) => expr);
937
+ const filter = filters.length === 0
938
+ ? undefined
939
+ : renameExpr(filters.length === 1
940
+ ? filters[0]
941
+ : { [ExprTag]: ExprTag, _tag: "and", exprs: filters });
942
+ return Query.plan(args.query, {
943
+ planner: zorderPlanner({
944
+ entityType: entityLike.entityType,
945
+ index: indexDef.index ?? "primary",
946
+ pkField: indexDef.pk.field,
947
+ pkValue: args.pkValue,
948
+ skField: indexDef.sk.field,
949
+ fingerprint: {
950
+ index: indexDef.index ?? "primary",
951
+ entityType: entityLike.entityType,
952
+ pk: args.pkValue,
953
+ prefix: prefix.map((part) => [
954
+ part.field,
955
+ part.hash ?? null,
956
+ prefixValues.has(part.field) ? textOf(prefixValues.get(part.field)) : null,
957
+ ]),
958
+ box,
959
+ layout: dimensions.map((dim) => ({ spec: dim.spec, storage: dim.storage, bits: dim.bits })),
960
+ },
961
+ layout,
962
+ box,
963
+ bounded: bounded.size > 0,
964
+ prefix: ZOrderCurve.concatBytes(leading.map((part) => segmentOf(part))),
965
+ tuple: later.map((part) => ({
966
+ field: part.field,
967
+ hash: part.hash,
968
+ given: prefixValues.has(part.field) ? segmentOf(part) : undefined,
969
+ })),
970
+ filter,
971
+ rowCheck: combineRowChecks([...dimensionChecks, ...hashed.map(prefixCheck)]),
972
+ filterRowCheck: combineRowChecks([
973
+ ...dimensionChecks,
974
+ ...hashed.map(prefixCheck),
975
+ ...parsedExactly.map(prefixCheck),
976
+ ]),
977
+ ranges: (maxRanges, refineFactor) => box === "empty" ? { ranges: [], exact: true } : args.plans(box, maxRanges, refineFactor),
978
+ }),
979
+ maxSkips: args.options?.maxSkips,
980
+ });
981
+ };
40
982
  /**
41
983
  * The composite key form for an arbitrary entity-like value — the same rule
42
984
  * `Entity` applies to its own keys (`internal/CompositeCodec.ts`).
@@ -218,17 +1160,17 @@ const packedFieldConfigs = (entity) => (entity._packedFields ?? []).map((field)
218
1160
  const makeFromConfig = (config) => Effect.gen(function* () {
219
1161
  // 1. Resolve the provide function from context.
220
1162
  //
221
- // Bundle a `Crypto` service into the captured context so that bound entity
1163
+ // Bundle a `SecureRandom` service into the captured context so that bound entity
222
1164
  // operations (auto-generated UUID primary keys via `generatedId`) resolve a
223
1165
  // cryptographically-secure source WITHOUT widening the public `R` of bound
224
1166
  // methods — bound `put` stays `R = never`. A caller-supplied `crypto`
225
1167
  // override (e.g. `@effect/platform-node`) takes precedence over the default
226
1168
  // `globalThis.crypto`-backed wrapper. The `provide` helper is widened to
227
- // admit `Crypto.Crypto`. See `DESIGN.md` for the `R = never` rationale.
1169
+ // admit `SecureRandom`. See `DESIGN.md` for the `R = never` rationale.
228
1170
  // Detached: no current operation or parent span is pinned for later calls (#174).
229
1171
  const baseCtx = Capacity.detachContext(yield* Effect.context());
230
1172
  const cryptoService = config.crypto ?? makeDefaultCrypto();
231
- const withCrypto = Context.add(baseCtx, Crypto.Crypto, cryptoService);
1173
+ const withCrypto = Context.add(baseCtx, SecureRandom.SecureRandom, cryptoService);
232
1174
  // Bundle the Embedder the same way, so entities with `vectorIndexes` keep
233
1175
  // `R = never` on their bound operations. An explicit `embedder` wins; an
234
1176
  // ambient one already in context is honoured; otherwise nothing is added
@@ -331,8 +1273,29 @@ const makeFromConfig = (config) => Effect.gen(function* () {
331
1273
  `the ENCODED value, but ${JSON.stringify(String(value))} encodes under neither ` +
332
1274
  `encode nor decode->encode. Supply a value of the attribute's own type.`);
333
1275
  });
1276
+ // A Z-order sort key (#171) is a binary address: its prefix composites
1277
+ // and dimensions are bounded with `.within()`, never pinned by the
1278
+ // accessor, which takes the partition key composites only.
1279
+ const zorder = KeyComposer.isZOrderHalf(indexDef.sk);
1280
+ const accessorDef = zorder
1281
+ ? { ...indexDef, sk: { field: indexDef.sk.field, composite: [] } }
1282
+ : indexDef;
1283
+ // Its range plans, cached across the accessor's queries (§5.4).
1284
+ const zorderLayout = KeyComposer.isZOrderHalf(indexDef.sk)
1285
+ ? indexDef.sk.zorderHalf.layout
1286
+ : undefined;
1287
+ const zorderPlans = zorderLayout === undefined ? undefined : makeZOrderPlans(zorderLayout);
334
1288
  return (rawComposites) => {
335
- validateQueryComposites(_indexName, indexDef, rawComposites);
1289
+ if (zorder) {
1290
+ const misplaced = indexDef.sk.composite.filter((attr) => rawComposites[attr] !== undefined);
1291
+ if (misplaced.length > 0) {
1292
+ throw new Error(`[EDD-9093] Index "${_indexName}" of entity "${entityLike.entityType}" has a ` +
1293
+ `Z-order sort key, so ${misplaced.map((attr) => `"${attr}"`).join(", ")} can't ` +
1294
+ `be passed to its accessor: pass the partition key composites ` +
1295
+ `(${indexDef.pk.composite.join(", ")}) and bound the rest with .within().`);
1296
+ }
1297
+ }
1298
+ validateQueryComposites(_indexName, accessorDef, rawComposites);
336
1299
  const compositesKeyForm = toCompositeKeyRecord(compositeKeyForm, rawComposites);
337
1300
  const pkValue = KeyComposer.composePk(entityLike._schema, entityLike.entityType, indexDef, compositesKeyForm);
338
1301
  const query = Query.make({
@@ -360,35 +1323,49 @@ const makeFromConfig = (config) => Effect.gen(function* () {
360
1323
  label: `${entityLike.entityType}.${_indexName}`,
361
1324
  },
362
1325
  });
363
- // Apply SK prefix from provided compositesKeyForm.
364
- // `composeSortKeyBeginsWith`, not `composeSortKeyPrefix` — the operand
365
- // must terminate on a segment boundary when compositesKeyForm remain, or it
366
- // matches sibling values that merely start with the supplied one
367
- // (`status_done` also matching `status_done_archived`, issue #115).
368
- const hasSkComposites = indexDef.sk.composite.some((attr) => compositesKeyForm[attr] !== undefined);
369
- const finalQuery = hasSkComposites
370
- ? Query.where(query, {
371
- beginsWith: KeyComposer.composeSortKeyBeginsWith(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm),
372
- })
1326
+ // Apply the SK condition from the provided composites
1327
+ // (`composeSortKeyCondition`): a partial prefix is a `begins_with`
1328
+ // terminated on a segment boundary, or it matches sibling values that
1329
+ // merely start with the supplied one (`status_done` also matching
1330
+ // `status_done_archived`, issue #115); a complete key is an exact `=`,
1331
+ // or `seq: 3` also matches 3.14 and `name: "a"` also matches "ab".
1332
+ const hasSkComposites = !zorder &&
1333
+ indexDef.sk.composite.some((attr) => compositesKeyForm[attr] !== undefined);
1334
+ const pinnedQuery = hasSkComposites
1335
+ ? Query.where(query, KeyComposer.composeSortKeyCondition(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm))
373
1336
  : query;
1337
+ // Rows 1.36 wrote whose key text changed sit under the key 1.36
1338
+ // composed for these pins until they move (#171): the query reads it
1339
+ // too — the partition key, and the pins' `eq` / `begins_with`. A
1340
+ // Z-order index is new in 1.37, so it has no 1.36 rows.
1341
+ const pk136 = !zorder && KeyText136.enabled(entityLike._schema)
1342
+ ? KeyText136.composePk(entityLike._schema, entityLike.entityType, indexDef, compositesKeyForm)
1343
+ : undefined;
1344
+ const finalQuery = pk136 === undefined
1345
+ ? pinnedQuery
1346
+ : Query.alsoRead136(pinnedQuery, {
1347
+ pkValue: pk136,
1348
+ rows: entityLike._indexRows136?.(indexDef),
1349
+ condition: hasSkComposites
1350
+ ? KeyText136.composeSortKeyCondition(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm)
1351
+ : undefined,
1352
+ });
374
1353
  const pathBuilder = createPathBuilder();
375
1354
  const conditionOps = createConditionOps();
376
1355
  // composeSkCondition — compose the user's `.where()` operand into a full
377
- // sort key value the same way `put` composes the stored one.
378
- //
379
- // A stored SK is `$schema#v1#entity#<name>_<cased value>#...`; comparing
380
- // a raw operand against that is meaningless (issue #101 — `gte` matched
381
- // the whole partition because `"1-009" < "ballkey_…"`, while
382
- // `begins_with` / `between` matched nothing). So the operand is placed
383
- // in the *position* of the SK composite it targets and run through the
384
- // same composer, which applies `serializeValue`, the `<name>_` prefix
385
- // and the schema casing.
1356
+ // sort key value the same way `put` composes the stored one
1357
+ // (`composeRangeUnder`).
386
1358
  const skComposites = indexDef.sk.composite;
387
1359
  const composeSkCondition = (condition, field) => {
1360
+ if (zorder) {
1361
+ throw new Error(`[EDD-9093] .where() on index "${_indexName}" of entity ` +
1362
+ `"${entityLike.entityType}": a Z-order sort key has no text order to compare ` +
1363
+ `against — bound its prefix composites and dimensions with .within().`);
1364
+ }
388
1365
  if (skComposites.length === 0) {
389
- throw new Error(`[EDD-9045] Index "${_indexName}" has no sort key compositesKeyForm, so there is ` +
1366
+ throw new Error(`[EDD-9045] Index "${_indexName}" has no sort key composites, so there is ` +
390
1367
  `nothing for .where() to constrain. Remove the .where() call, or add sort ` +
391
- `key compositesKeyForm to the index definition.`);
1368
+ `key composites to the index definition.`);
392
1369
  }
393
1370
  // How many leading composites the accessor already pinned. Pinning is
394
1371
  // a prefix by construction — `validateQueryComposites` rejects a hole
@@ -448,123 +1425,98 @@ const makeFromConfig = (config) => Effect.gen(function* () {
448
1425
  .filter((attr) => compositesKeyForm[attr] === undefined);
449
1426
  if (missing.length > 0) {
450
1427
  throw new Error(`[EDD-9004] Sort key condition on "${targetAttr}" for index "${_indexName}" ` +
451
- `requires prior compositesKeyForm: ${missing.join(", ")}. Sort key compositesKeyForm must ` +
1428
+ `requires prior composites: ${missing.join(", ")}. Sort key composites must ` +
452
1429
  `follow prefix ordering — supply them to the accessor before calling .where().`);
453
1430
  }
454
- // Compose a sort key value with the leading pinned compositesKeyForm followed
455
- // by `<targetAttr>_<value>`. Trailing compositesKeyForm are excluded — the
456
- // condition bounds the key at the target's position.
1431
+ // Compose under the pinned prefix — the key text of the composites
1432
+ // the accessor pinned, ending on a segment boundary (the target
1433
+ // follows them, so the shared delimiter rule always applies).
457
1434
  const pinnedKeyForm = {};
458
1435
  for (let i = 0; i < targetIndex; i++) {
459
1436
  pinnedKeyForm[skComposites[i]] = compositesKeyForm[skComposites[i]];
460
1437
  }
461
- // Encode the operand exactly as the accessor compositesKeyForm (and the
462
- // write path) are encoded, so both sides of the comparison come out
463
- // of one pipeline.
464
- const operand = (value) => compositeKeyForm(targetAttr, value);
465
- const compose = (value) => KeyComposer.composeSortKeyPrefix(entityLike._schema, entityLike.entityType, 1, indexDef, {
466
- ...pinnedKeyForm,
467
- [targetAttr]: operand(value),
468
- });
469
- const isLastComposite = targetIndex === skComposites.length - 1;
470
- /**
471
- * `begins_with` operand matching exactly the keys whose target
472
- * composite equals `value`. Delegates the delimiter rule (#115) to
473
- * `composeSortKeyBeginsWith` — one rule, shared with the accessor's
474
- * own prefix — so it stops on a segment boundary rather than leaking
475
- * into sibling values (`status_done` vs `status_done_archived`).
476
- */
477
- const subtreeBeginsWith = (value) => KeyComposer.composeSortKeyBeginsWith(entityLike._schema, entityLike.entityType, 1, indexDef, { ...pinnedKeyForm, [targetAttr]: operand(value) });
478
- /**
479
- * A bound sorting strictly above every key whose target composite is
480
- * `value`, and strictly below the first key of any greater value.
481
- *
482
- * Unlike `subtreeBeginsWith` the delimiter here is UNCONDITIONAL,
483
- * including on the last composite: `compose(v)￿` alone would sort
484
- * below `compose(v + "0")`, which is a strictly greater value that
485
- * must stay inside a `gt`. `compose(v)#￿` sits above `compose(v)` and
486
- * below every longer value because `#` is lower than every character
487
- * the composer emits for a value segment.
488
- */
489
- const aboveSubtree = (value) => `${compose(value)}${DynamoSchema.KEY_DELIMITER}${SK_MAX_SENTINEL}`;
490
- /** Inclusive upper bound covering the whole subtree of `value`. */
491
- const upper = (value) => isLastComposite ? compose(value) : aboveSubtree(value);
492
- // `beginsWith` / `between` / `eq` already carry the pinned compositesKeyForm
493
- // in BOTH operands, so they never escape the pinned prefix.
494
- if ("beginsWith" in condition)
495
- return { beginsWith: compose(condition.beginsWith) };
496
- if ("eq" in condition) {
497
- return isLastComposite
498
- ? { eq: compose(condition.eq) }
499
- : { beginsWith: subtreeBeginsWith(condition.eq) };
500
- }
501
- if ("between" in condition) {
502
- return { between: [compose(condition.between[0]), upper(condition.between[1])] };
503
- }
504
- // One-sided operators are open on the other side. With no pinned
505
- // compositesKeyForm that is exactly right — the open end runs to the edge of
506
- // the partition. But once the accessor has pinned leading compositesKeyForm,
507
- // DynamoDB's single sort key condition must ALSO stay inside that
508
- // prefix, so the open end is clamped and the condition becomes a
509
- // BETWEEN. (`Query.where` replaces the accessor's own `begins_with`,
510
- // so it cannot do the clamping.)
1438
+ const prefixText = KeyComposer.composeSortKeyBeginsWith(entityLike._schema, entityLike.entityType, 1, indexDef, pinnedKeyForm);
1439
+ // Operands are encoded exactly as the accessor composites (and the
1440
+ // write path) are, so both sides of the comparison come out of one
1441
+ // pipeline.
511
1442
  //
512
- // The predicate is "the accessor pinned nothing", NOT `targetIndex === 0`.
513
- // Those coincided for every shape the tests covered but are different
514
- // claims: an accessor can pin composite[0] itself, and then targeting
515
- // index 0 skipped the clamp and dropped the pin (#121). That call now
516
- // raises EDD-9053 above, so the two are equivalent again — stating the
517
- // real predicate keeps them from drifting apart a second time.
518
- if (pinnedCount === 0) {
519
- if ("lt" in condition)
520
- return { lt: compose(condition.lt) };
521
- if ("lte" in condition)
522
- return { lte: upper(condition.lte) };
523
- // `>` is already exclusive of the composed value, so only a
524
- // non-terminal target needs the subtree pushed past.
525
- if ("gt" in condition) {
526
- return { gt: isLastComposite ? compose(condition.gt) : aboveSubtree(condition.gt) };
527
- }
528
- if ("gte" in condition)
529
- return { gte: compose(condition.gte) };
530
- return condition;
1443
+ // The clamp predicate is "the accessor pinned something", NOT
1444
+ // `targetIndex > 0`. Those coincided for every shape the tests
1445
+ // covered but are different claims: an accessor can pin composite[0]
1446
+ // itself, and then targeting index 0 skipped the clamp and dropped
1447
+ // the pin (#121). That call now raises EDD-9053 above, so the two
1448
+ // are equivalent again — stating the real predicate keeps them from
1449
+ // drifting apart a second time.
1450
+ return composeRangeUnder({
1451
+ casing: KeyComposer.effectiveCasing(entityLike._schema, indexDef),
1452
+ isLast: targetIndex === skComposites.length - 1,
1453
+ }, prefixText, targetAttr, mapBound(condition, (value) => compositeKeyForm(targetAttr, value)), { clampToPrefix: pinnedCount > 0 });
1454
+ };
1455
+ /**
1456
+ * The 1.36 key a `.where()` also reads (#171): an `eq` or
1457
+ * `beginsWith` extends the pins, so the rows it selects under 1.36's
1458
+ * key text are read too. A range bound reads only the current key.
1459
+ */
1460
+ const where136 = (condition, field) => {
1461
+ if (pk136 === undefined || !("eq" in condition || "beginsWith" in condition)) {
1462
+ return undefined;
531
1463
  }
532
- // The pinned compositesKeyForm are a strict prefix by construction (the
533
- // target composite follows them), so the shared delimiter rule always
534
- // terminates this bound on a segment boundary.
535
- const pinnedPrefix = KeyComposer.composeSortKeyBeginsWith(entityLike._schema, entityLike.entityType, 1, indexDef, pinnedKeyForm);
536
- const pinnedMax = `${pinnedPrefix}${SK_MAX_SENTINEL}`;
537
- if ("gte" in condition)
538
- return { between: [compose(condition.gte), pinnedMax] };
539
- if ("gt" in condition)
540
- return { between: [aboveSubtree(condition.gt), pinnedMax] };
541
- if ("lte" in condition)
542
- return { between: [pinnedPrefix, upper(condition.lte)] };
543
- if ("lt" in condition) {
544
- // On a non-terminal composite no stored key can equal the composed
545
- // bound (trailing compositesKeyForm always follow), so BETWEEN's inclusive
546
- // high end is harmless. On the LAST composite the bound IS a
547
- // storable key, and DynamoDB has neither a half-open BETWEEN nor a
548
- // FilterExpression that may reference a key attribute — so there is
549
- // no way to say `begins_with(prefix) AND sk < value` in one key
550
- // condition. Refuse rather than silently return the boundary item.
551
- if (!isLastComposite)
552
- return { between: [pinnedPrefix, compose(condition.lt)] };
553
- throw new Error(`[EDD-9046] A strict "lt" condition on sort key composite "${targetAttr}" for ` +
554
- `index "${_indexName}" cannot be expressed once earlier compositesKeyForm ` +
555
- `(${skComposites.slice(0, targetIndex).join(", ")}) are pinned by the accessor: ` +
556
- `DynamoDB allows one sort key condition, BETWEEN is inclusive at both ends, and ` +
557
- `a FilterExpression may not reference a key attribute. Use ` +
558
- `.where((t, { between }) => between(t.${targetAttr}, low, high)) or "lte" instead.`);
1464
+ const pinnedCount = skComposites.findIndex((attr) => compositesKeyForm[attr] === undefined);
1465
+ const targetAttr = field !== undefined && skComposites.includes(field)
1466
+ ? field
1467
+ : skComposites[pinnedCount === -1 ? skComposites.length - 1 : pinnedCount];
1468
+ const pinned = {};
1469
+ for (const attr of skComposites.slice(0, skComposites.indexOf(targetAttr))) {
1470
+ pinned[attr] = compositesKeyForm[attr];
559
1471
  }
560
- return condition;
1472
+ const operand = (value) => compositeKeyForm(targetAttr, value);
1473
+ return {
1474
+ pkValue: pk136,
1475
+ rows: entityLike._indexRows136?.(indexDef),
1476
+ condition: KeyText136.composeBoundCondition(entityLike._schema, entityLike.entityType, 1, indexDef, pinned, targetAttr, "eq" in condition
1477
+ ? { eq: operand(condition.eq) }
1478
+ : { beginsWith: operand(condition.beginsWith) }),
1479
+ };
561
1480
  };
562
1481
  const bqConfig = {
563
1482
  pathBuilder,
564
1483
  conditionOps,
565
1484
  provide,
566
1485
  composeSkCondition,
567
- skFields: indexDef.sk.composite,
1486
+ where136,
1487
+ // A Z-order accessor bounds its dimensions and prefix composites
1488
+ // (#171), and takes `.zorder()`.
1489
+ ...(zorder
1490
+ ? {
1491
+ zorder: true,
1492
+ planWithin: (q, bounds, options) => planZOrderWithin({
1493
+ entityLike,
1494
+ accessor: _indexName,
1495
+ indexDef,
1496
+ encoderSource,
1497
+ compositeKeyForm,
1498
+ pkValue,
1499
+ plans: zorderPlans,
1500
+ query: q,
1501
+ bounds,
1502
+ options,
1503
+ }),
1504
+ }
1505
+ : {
1506
+ planWithin: (q, bounds, options) => planCompositeWithin({
1507
+ entityLike,
1508
+ accessor: _indexName,
1509
+ indexDef,
1510
+ encoderSource,
1511
+ compositeKeyForm,
1512
+ pinnedKeyForm: compositesKeyForm,
1513
+ pkValue,
1514
+ query: q,
1515
+ bounds,
1516
+ options,
1517
+ }),
1518
+ }),
1519
+ skFields: accessorDef.sk.composite,
568
1520
  ...entityNaming(entityLike._resolveDbName),
569
1521
  operation: { name: "Entity.query", target: entityLike.entityType, index: _indexName },
570
1522
  };
@@ -587,11 +1539,11 @@ const makeFromConfig = (config) => Effect.gen(function* () {
587
1539
  const entity = typeof rawEntity.get === "function"
588
1540
  ? rawEntity
589
1541
  : entityFromDefinition(rawEntity);
590
- // Provide the resolved services (Crypto, Embedder, Compression) into the
1542
+ // Provide the resolved services (SecureRandom, Embedder, Compression) into the
591
1543
  // bind: `bind` captures its context at bind time, so the bound CRUD
592
1544
  // methods resolve the explicit `crypto`, `embedder` and `compressors`
593
1545
  // given here — keeping them at `R = never`. `bind` respects an
594
- // already-present Crypto and only fills its own default when absent, so
1546
+ // already-present SecureRandom and only fills its own default when absent, so
595
1547
  // the override is honored.
596
1548
  const bound = yield* provide(entityBind(entity));
597
1549
  const entityLike = entity;
@@ -754,6 +1706,11 @@ const makeFromConfig = (config) => Effect.gen(function* () {
754
1706
  const skPrefix = `${pre}#${casedNames.join("#")}`;
755
1707
  query = Query.where(query, { beginsWith: skPrefix });
756
1708
  }
1709
+ // A collection's sort key prefix holds names only, so its 1.36 key
1710
+ // differs in the partition key alone — a number composite (#171).
1711
+ query = Query.alsoReadPartition136(query, KeyText136.enabled(firstMember.entityLike._schema)
1712
+ ? KeyText136.composePk(firstMember.entityLike._schema, firstMember.entityLike.entityType, indexDef, entityKeyForm(firstMember.entityLike, composites))
1713
+ : undefined);
757
1714
  // Wrap in BoundQuery that groups results by entity key
758
1715
  const pathBuilder = createPathBuilder();
759
1716
  const conditionOps = createConditionOps();
@@ -806,6 +1763,39 @@ const makeFromConfig = (config) => Effect.gen(function* () {
806
1763
  // 5. Build table operations
807
1764
  const client = yield* DynamoClient;
808
1765
  const tables = {};
1766
+ // `rekey` (#171) hands each row to the member owning it: the table's
1767
+ // entities and aggregates, those the client binds on the same table, and
1768
+ // the streams the caller passes (`DynamoClient.make` binds no streams).
1769
+ const rekeyFor = (tableName, tagKey, registered) => (options) => {
1770
+ const onTable = (member) => member._tableTag?.key === tagKey;
1771
+ const handlers = new Set();
1772
+ for (const member of [
1773
+ ...registered,
1774
+ ...Object.values(config.entities).filter(onTable),
1775
+ ...Object.values(config.aggregates ?? {}).filter(onTable),
1776
+ ...(options?.streams ?? []),
1777
+ ]) {
1778
+ const handler = Rekey.handlerOf(member);
1779
+ if (handler !== undefined)
1780
+ handlers.add(handler);
1781
+ }
1782
+ // A projection's outbox on this table, of a read model on another (#171).
1783
+ const outboxOf = new Set();
1784
+ for (const entity of [...registered, ...Object.values(config.entities)]) {
1785
+ const outbox = entity._projectionOutbox;
1786
+ if (outbox === undefined || outbox.table.Tag.key !== tagKey || outboxOf.has(entity)) {
1787
+ continue;
1788
+ }
1789
+ outboxOf.add(entity);
1790
+ const readModel = entity;
1791
+ handlers.add({
1792
+ name: readModel.entityType,
1793
+ types: [`${readModel.entityType}#outbox`],
1794
+ row: (row, ctx) => readModel._rekeyProjectionRow(row, ctx, { pk: outbox.pk, sk: outbox.sk }),
1795
+ });
1796
+ }
1797
+ return provide(Rekey.run({ tableName, members: [...handlers], options }));
1798
+ };
809
1799
  if (config.tables) {
810
1800
  for (const [tableKey, table] of Object.entries(config.tables)) {
811
1801
  const tableConfig = yield* table.Tag;
@@ -843,7 +1833,13 @@ const makeFromConfig = (config) => Effect.gen(function* () {
843
1833
  };
844
1834
  }
845
1835
  }
846
- tables[tableKey] = buildTableOperationsFromTable(tableConfig.name, mergedTable, client);
1836
+ tables[tableKey] = {
1837
+ ...buildTableOperationsFromTable(tableConfig.name, mergedTable, client),
1838
+ rekey: rekeyFor(tableConfig.name, table.Tag.key, [
1839
+ ...Object.values(mergedTable.entities),
1840
+ ...Object.values(mergedTable.aggregates),
1841
+ ]),
1842
+ };
847
1843
  }
848
1844
  }
849
1845
  else {
@@ -880,7 +1876,10 @@ const makeFromConfig = (config) => Effect.gen(function* () {
880
1876
  a,
881
1877
  ])),
882
1878
  };
883
- tables[tableConfig.name] = buildTableOperationsFromTable(tableConfig.name, syntheticTable, client);
1879
+ tables[tableConfig.name] = {
1880
+ ...buildTableOperationsFromTable(tableConfig.name, syntheticTable, client),
1881
+ rekey: rekeyFor(tableConfig.name, tag.key, [...tableEntities, ...tableAggregates]),
1882
+ };
884
1883
  }
885
1884
  }
886
1885
  return {
@@ -921,22 +1920,28 @@ const diagnoseVectorLimits = (operation, label, sent) => diagnoseFailure({
921
1920
  /** Make createTable idempotent — ignore if table already exists. */
922
1921
  const idempotentCreate = (effect) => Effect.catchIf(effect, isResourceInUse, () => Effect.void);
923
1922
  const buildTableOperationsFromTable = (tableName, table, client) => {
924
- const def = tableDefinition(table);
1923
+ // Composed when a table is created: a table holding only event streams or a
1924
+ // projection's outbox has no definition to give, but its other operations
1925
+ // (`rekey` among them) still work.
1926
+ const definition = () => tableDefinition(table);
925
1927
  const vectorIndexes = mergeVectorIndexes(table.entities);
926
1928
  const sharers = (indexName) => vectorIndexes.get(indexName)?.sharers ?? [];
927
1929
  return {
928
1930
  ...buildTableOperations(tableName, client),
929
- create: (options) => idempotentCreate(client
930
- .createTable({
931
- TableName: tableName,
932
- BillingMode: options?.billingMode ?? "PAY_PER_REQUEST",
933
- ...def,
934
- })
935
- .pipe(Effect.asVoid, diagnoseVectorLimits("CreateTable", `db.tables create of "${tableName}"`, {
936
- vectorIndexes: def.VectorIndexes ?? [],
937
- sharers,
938
- declared: vectorIndexes.size,
939
- }))),
1931
+ create: (options) => Effect.suspend(() => {
1932
+ const def = definition();
1933
+ return idempotentCreate(client
1934
+ .createTable({
1935
+ TableName: tableName,
1936
+ BillingMode: options?.billingMode ?? "PAY_PER_REQUEST",
1937
+ ...def,
1938
+ })
1939
+ .pipe(Effect.asVoid, diagnoseVectorLimits("CreateTable", `db.tables create of "${tableName}"`, {
1940
+ vectorIndexes: def.VectorIndexes ?? [],
1941
+ sharers,
1942
+ declared: vectorIndexes.size,
1943
+ })));
1944
+ }),
940
1945
  addVectorIndex: (indexName) => {
941
1946
  const entry = vectorIndexes.get(indexName);
942
1947
  if (entry === undefined) {