effect-dynamodb 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 (190) hide show
  1. package/README.md +1 -1
  2. package/dist/Aggregate.d.ts +138 -16
  3. package/dist/Aggregate.d.ts.map +1 -1
  4. package/dist/Aggregate.js +4298 -725
  5. package/dist/Aggregate.js.map +1 -1
  6. package/dist/Batch.d.ts +9 -5
  7. package/dist/Batch.d.ts.map +1 -1
  8. package/dist/Batch.js +28 -44
  9. package/dist/Batch.js.map +1 -1
  10. package/dist/Collection.d.ts.map +1 -1
  11. package/dist/Collection.js +16 -9
  12. package/dist/Collection.js.map +1 -1
  13. package/dist/ConsumedCapacity.js +1 -1
  14. package/dist/ConsumedCapacity.js.map +1 -1
  15. package/dist/DynamoClient.d.ts +44 -21
  16. package/dist/DynamoClient.d.ts.map +1 -1
  17. package/dist/DynamoClient.js +342 -124
  18. package/dist/DynamoClient.js.map +1 -1
  19. package/dist/Entity.d.ts +246 -41
  20. package/dist/Entity.d.ts.map +1 -1
  21. package/dist/Entity.js +6818 -1166
  22. package/dist/Entity.js.map +1 -1
  23. package/dist/EventStore.d.ts +37 -15
  24. package/dist/EventStore.d.ts.map +1 -1
  25. package/dist/EventStore.js +403 -163
  26. package/dist/EventStore.js.map +1 -1
  27. package/dist/Expression.d.ts.map +1 -1
  28. package/dist/Expression.js +40 -24
  29. package/dist/Expression.js.map +1 -1
  30. package/dist/Marshaller.d.ts +72 -11
  31. package/dist/Marshaller.d.ts.map +1 -1
  32. package/dist/Marshaller.js +625 -71
  33. package/dist/Marshaller.js.map +1 -1
  34. package/dist/Query.d.ts +103 -5
  35. package/dist/Query.d.ts.map +1 -1
  36. package/dist/Query.js +262 -15
  37. package/dist/Query.js.map +1 -1
  38. package/dist/StorageEncoding.d.ts +7 -1
  39. package/dist/StorageEncoding.d.ts.map +1 -1
  40. package/dist/StorageEncoding.js +8 -2
  41. package/dist/StorageEncoding.js.map +1 -1
  42. package/dist/Table.d.ts +338 -16
  43. package/dist/Table.d.ts.map +1 -1
  44. package/dist/Table.js +30 -2
  45. package/dist/Table.js.map +1 -1
  46. package/dist/Transaction.d.ts.map +1 -1
  47. package/dist/Transaction.js +70 -7
  48. package/dist/Transaction.js.map +1 -1
  49. package/dist/VectorSearchEmulation.d.ts.map +1 -1
  50. package/dist/VectorSearchEmulation.js +4 -3
  51. package/dist/VectorSearchEmulation.js.map +1 -1
  52. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  53. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  54. package/dist/change-feed/ChangeFeed.js +76 -9
  55. package/dist/change-feed/ChangeFeed.js.map +1 -1
  56. package/dist/change-feed/CheckpointStore.js +1 -1
  57. package/dist/change-feed/CheckpointStore.js.map +1 -1
  58. package/dist/change-feed/DynamoStreamsClient.d.ts +19 -10
  59. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  60. package/dist/change-feed/DynamoStreamsClient.js +24 -14
  61. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  62. package/dist/index.d.ts +2 -2
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/internal/BoundCrud.d.ts +78 -32
  67. package/dist/internal/BoundCrud.d.ts.map +1 -1
  68. package/dist/internal/BoundCrud.js +25 -0
  69. package/dist/internal/BoundCrud.js.map +1 -1
  70. package/dist/internal/BoundQuery.d.ts +46 -3
  71. package/dist/internal/BoundQuery.d.ts.map +1 -1
  72. package/dist/internal/BoundQuery.js +402 -37
  73. package/dist/internal/BoundQuery.js.map +1 -1
  74. package/dist/internal/BoundVectorQuery.d.ts +6 -0
  75. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  76. package/dist/internal/BoundVectorQuery.js +7 -4
  77. package/dist/internal/BoundVectorQuery.js.map +1 -1
  78. package/dist/internal/Capacity.d.ts +46 -5
  79. package/dist/internal/Capacity.d.ts.map +1 -1
  80. package/dist/internal/Capacity.js +177 -26
  81. package/dist/internal/Capacity.js.map +1 -1
  82. package/dist/internal/ClientOptions.d.ts +144 -0
  83. package/dist/internal/ClientOptions.d.ts.map +1 -0
  84. package/dist/internal/ClientOptions.js +290 -0
  85. package/dist/internal/ClientOptions.js.map +1 -0
  86. package/dist/internal/ConditionHolds.d.ts +29 -0
  87. package/dist/internal/ConditionHolds.d.ts.map +1 -0
  88. package/dist/internal/ConditionHolds.js +453 -0
  89. package/dist/internal/ConditionHolds.js.map +1 -0
  90. package/dist/internal/Cursor.d.ts +19 -10
  91. package/dist/internal/Cursor.d.ts.map +1 -1
  92. package/dist/internal/Cursor.js +25 -10
  93. package/dist/internal/Cursor.js.map +1 -1
  94. package/dist/internal/Digest.d.ts +20 -0
  95. package/dist/internal/Digest.d.ts.map +1 -0
  96. package/dist/internal/Digest.js +106 -0
  97. package/dist/internal/Digest.js.map +1 -0
  98. package/dist/internal/DynamoArithmetic.d.ts +33 -0
  99. package/dist/internal/DynamoArithmetic.d.ts.map +1 -0
  100. package/dist/internal/DynamoArithmetic.js +112 -0
  101. package/dist/internal/DynamoArithmetic.js.map +1 -0
  102. package/dist/internal/EntityCombinators.d.ts +23 -8
  103. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  104. package/dist/internal/EntityCombinators.js +6 -2
  105. package/dist/internal/EntityCombinators.js.map +1 -1
  106. package/dist/internal/EntityOps.d.ts +69 -8
  107. package/dist/internal/EntityOps.d.ts.map +1 -1
  108. package/dist/internal/EntityOps.js.map +1 -1
  109. package/dist/internal/EventProjection.d.ts +18 -4
  110. package/dist/internal/EventProjection.d.ts.map +1 -1
  111. package/dist/internal/EventProjection.js +36 -8
  112. package/dist/internal/EventProjection.js.map +1 -1
  113. package/dist/internal/Expr.d.ts +72 -2
  114. package/dist/internal/Expr.d.ts.map +1 -1
  115. package/dist/internal/Expr.js +264 -5
  116. package/dist/internal/Expr.js.map +1 -1
  117. package/dist/internal/ExpressionLimits.d.ts +57 -1
  118. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  119. package/dist/internal/ExpressionLimits.js +97 -4
  120. package/dist/internal/ExpressionLimits.js.map +1 -1
  121. package/dist/internal/FormGuard.d.ts +52 -0
  122. package/dist/internal/FormGuard.d.ts.map +1 -0
  123. package/dist/internal/FormGuard.js +83 -0
  124. package/dist/internal/FormGuard.js.map +1 -0
  125. package/dist/internal/Hydrate.d.ts.map +1 -1
  126. package/dist/internal/Hydrate.js +2 -1
  127. package/dist/internal/Hydrate.js.map +1 -1
  128. package/dist/internal/InputForm.d.ts +24 -0
  129. package/dist/internal/InputForm.d.ts.map +1 -0
  130. package/dist/internal/InputForm.js +44 -0
  131. package/dist/internal/InputForm.js.map +1 -0
  132. package/dist/internal/InsertStatement.d.ts +15 -0
  133. package/dist/internal/InsertStatement.d.ts.map +1 -0
  134. package/dist/internal/InsertStatement.js +18 -0
  135. package/dist/internal/InsertStatement.js.map +1 -0
  136. package/dist/internal/ItemSize.d.ts +108 -4
  137. package/dist/internal/ItemSize.d.ts.map +1 -1
  138. package/dist/internal/ItemSize.js +190 -3
  139. package/dist/internal/ItemSize.js.map +1 -1
  140. package/dist/internal/MultiProjection.d.ts +7 -2
  141. package/dist/internal/MultiProjection.d.ts.map +1 -1
  142. package/dist/internal/MultiProjection.js +18 -12
  143. package/dist/internal/MultiProjection.js.map +1 -1
  144. package/dist/internal/OperandReaders.d.ts +36 -0
  145. package/dist/internal/OperandReaders.d.ts.map +1 -0
  146. package/dist/internal/OperandReaders.js +176 -0
  147. package/dist/internal/OperandReaders.js.map +1 -0
  148. package/dist/internal/Packed.d.ts.map +1 -1
  149. package/dist/internal/Packed.js +11 -10
  150. package/dist/internal/Packed.js.map +1 -1
  151. package/dist/internal/PathBuilder.d.ts +57 -8
  152. package/dist/internal/PathBuilder.d.ts.map +1 -1
  153. package/dist/internal/PathBuilder.js +98 -24
  154. package/dist/internal/PathBuilder.js.map +1 -1
  155. package/dist/internal/ProjectionEngine.d.ts +196 -3
  156. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  157. package/dist/internal/ProjectionEngine.js +1251 -86
  158. package/dist/internal/ProjectionEngine.js.map +1 -1
  159. package/dist/internal/Rekey.d.ts +187 -21
  160. package/dist/internal/Rekey.d.ts.map +1 -1
  161. package/dist/internal/Rekey.js +1349 -63
  162. package/dist/internal/Rekey.js.map +1 -1
  163. package/dist/internal/ReturnedItem.d.ts +23 -0
  164. package/dist/internal/ReturnedItem.d.ts.map +1 -0
  165. package/dist/internal/ReturnedItem.js +39 -0
  166. package/dist/internal/ReturnedItem.js.map +1 -0
  167. package/dist/internal/RoundTrip.d.ts +45 -0
  168. package/dist/internal/RoundTrip.d.ts.map +1 -0
  169. package/dist/internal/RoundTrip.js +106 -0
  170. package/dist/internal/RoundTrip.js.map +1 -0
  171. package/dist/internal/SentRequest.d.ts +14 -0
  172. package/dist/internal/SentRequest.d.ts.map +1 -0
  173. package/dist/internal/SentRequest.js +31 -0
  174. package/dist/internal/SentRequest.js.map +1 -0
  175. package/dist/internal/TransactPlan.d.ts.map +1 -1
  176. package/dist/internal/TransactPlan.js +4 -0
  177. package/dist/internal/TransactPlan.js.map +1 -1
  178. package/dist/internal/TransactWriteOps.d.ts +70 -15
  179. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  180. package/dist/internal/TransactWriteOps.js +166 -112
  181. package/dist/internal/TransactWriteOps.js.map +1 -1
  182. package/dist/internal/TransactableOps.d.ts +230 -27
  183. package/dist/internal/TransactableOps.d.ts.map +1 -1
  184. package/dist/internal/TransactableOps.js +549 -92
  185. package/dist/internal/TransactableOps.js.map +1 -1
  186. package/dist/internal/WriteDiagnosis.d.ts +66 -3
  187. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  188. package/dist/internal/WriteDiagnosis.js +261 -15
  189. package/dist/internal/WriteDiagnosis.js.map +1 -1
  190. package/package.json +5 -5
@@ -8,49 +8,613 @@
8
8
  * and the standard `Schema.encode` / `Schema.decode` pipelines.
9
9
  */
10
10
  import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
11
- /** Marshall a JS object to a DynamoDB attribute map */
12
- export const toAttributeMap = (item) => marshall(item, { removeUndefinedValues: true, convertClassInstanceToMap: true });
13
- /** Unmarshall a DynamoDB attribute map to a JS object */
14
- export const fromAttributeMap = (item) => unmarshall(item);
15
- /** Marshall a single value to a DynamoDB attribute value */
16
- export const toAttributeValue = (value) => marshall({ v: value }, { removeUndefinedValues: true, convertClassInstanceToMap: true }).v;
17
- /** Unmarshall a single DynamoDB attribute value */
18
- export const fromAttributeValue = (value) => unmarshall({ v: value }).v;
19
- // ---------------------------------------------------------------------------
20
- // Sparse Map flatten / rebuild
21
- // ---------------------------------------------------------------------------
11
+ import { lostPath, lostRefusal, readJudged, } from "@effect-dynamodb/schema/internal/LostValues.js";
12
+ import { PROTO_ENTRY, setOwn } from "@effect-dynamodb/schema/internal/OwnNames.js";
13
+ import { sparseReader, validateSparseKey } from "@effect-dynamodb/schema/internal/SparseKey.js";
14
+ import { COOKIE_MARKER, COOKIE_PROTO, cachesCycle, isBigDecimalInstance, isCachedNormal, ZONE_MARKER, zoneEntriesWritten, } from "@effect-dynamodb/schema/internal/StoredForm.js";
15
+ import { Data } from "effect";
16
+ export { isCachedNormal };
17
+ const MARSHALL_OPTIONS = { removeUndefinedValues: true, convertClassInstanceToMap: true };
18
+ /** A set DynamoDB can't store: nothing in it, once `undefined` values are removed. */
19
+ export const isEmptySet = (value) => value instanceof Set && [...value].every((element) => element === undefined);
20
+ /** `undefined` or an empty set: stored as an absent attribute. */
21
+ export const hasNoStoredForm = (value) => value === undefined || isEmptySet(value);
22
+ const renderPath = (path, fieldOf = (attribute) => attribute) => path.reduce((text, segment, index) => typeof segment === "number"
23
+ ? `${text}[${segment}]`
24
+ : index === 0
25
+ ? fieldOf(segment)
26
+ : `${text}.${segment}`, "");
27
+ /**
28
+ * A value DynamoDB can't store, and where it is (`EDD-9124`), or a map entry keyed `__proto__`
29
+ * (`EDD-9165`). Marshalling throws this, as key composition throws `KeyValueError`; what reaches
30
+ * it is the caller's value, so a write path turns it into a `ValidationError` (`marshalOrFail`).
31
+ */
32
+ export class UnstorableValue extends Data.TaggedError("UnstorableValue") {
33
+ get message() {
34
+ return this.describe();
35
+ }
36
+ /** The refusal in words, naming a stored attribute by what `fieldOf` makes of it. */
37
+ describe(fieldOf) {
38
+ if (this.lost !== undefined) {
39
+ const [attribute, ...within] = this.path;
40
+ const root = attribute === undefined
41
+ ? "value"
42
+ : fieldOf === undefined
43
+ ? String(attribute)
44
+ : fieldOf(String(attribute));
45
+ return lostRefusal(lostPath(root, within), this.lost);
46
+ }
47
+ const refused = this.path.length === 0 ? this.reason : `"${renderPath(this.path, fieldOf)}": ${this.reason}`;
48
+ return `${refused.endsWith(".") ? refused : `${refused}.`} [${this.code ?? "EDD-9124"}]`;
49
+ }
50
+ /** The same refusal at another path. */
51
+ at(path) {
52
+ return new UnstorableValue({
53
+ path,
54
+ reason: this.reason,
55
+ ...(this.code === undefined ? {} : { code: this.code }),
56
+ ...(this.lost === undefined ? {} : { lost: { ...this.lost, path } }),
57
+ });
58
+ }
59
+ /**
60
+ * The refusal as a write reports it, `outcome` (what wasn't done) after it; a lost value's refusal
61
+ * says that itself.
62
+ */
63
+ refusal(outcome, fieldOf) {
64
+ if (this.lost === undefined)
65
+ return `${this.describe(fieldOf)} ${outcome}`;
66
+ const refused = this.describe(fieldOf);
67
+ return `${refused[0].toUpperCase()}${refused.slice(1)}`;
68
+ }
69
+ }
70
+ /** A lost value a getter returned, where it's stored: thrown out of the marshaller. */
71
+ const refuseLost = (lost) => {
72
+ throw new UnstorableValue({
73
+ path: lost.path,
74
+ reason: lostRefusal(lostPath("value", lost.path), lost),
75
+ lost,
76
+ });
77
+ };
78
+ /**
79
+ * The item as the marshaller is to read it: where it holds a part `lostIn` marked, a getter it didn't
80
+ * call, a view (`readJudged`) that judges what each such getter returns as the marshaller calls it.
81
+ * Nothing of the item is read to find out, and the item itself when it holds none, so an item
82
+ * without one is marshalled exactly as it always was.
83
+ */
84
+ const judgedAsRead = (item) => readJudged(item, [], refuseLost);
85
+ /**
86
+ * The refusal of an attribute or a map entry named `__proto__` at `path`, the name last: the
87
+ * attribute's own name where the path is just that.
88
+ */
89
+ export const protoEntryAt = (path) => new UnstorableValue({ path, reason: PROTO_ENTRY, code: "EDD-9165" });
90
+ export const isUnstorableValue = (value) => value instanceof UnstorableValue;
91
+ /**
92
+ * What marshalling stores of an object, in the order it stores it: its enumerable properties, its
93
+ * prototype's included. An `Option`'s `_tag`, or a `Result`'s, is on the prototype, and a copy of
94
+ * the own properties alone is a row that can't be read.
95
+ */
96
+ const propertiesOf = (value) => {
97
+ const properties = [];
98
+ for (const key in value)
99
+ properties.push([key, value[key]]);
100
+ return properties;
101
+ };
102
+ /**
103
+ * The value without the empty sets in its maps, the same reference when it has
104
+ * none. A list keeps its elements: leaving one out would move those after it, so
105
+ * marshalling refuses an empty set there.
106
+ */
107
+ const withoutEmptySets = (value) => {
108
+ if (typeof value !== "object" || value === null)
109
+ return value;
110
+ if (Array.isArray(value)) {
111
+ const elements = value.map((element) => withoutEmptySets(element));
112
+ return elements.some((element, index) => element !== value[index]) ? elements : value;
113
+ }
114
+ if (value instanceof Map) {
115
+ const entries = [...value].filter(([, entry]) => !isEmptySet(entry));
116
+ const next = entries.map(([key, entry]) => [key, withoutEmptySets(entry)]);
117
+ const same = entries.length === value.size && next.every(([key, entry]) => entry === value.get(key));
118
+ return same ? value : new Map(next);
119
+ }
120
+ const entries = propertiesOf(value);
121
+ const next = entries
122
+ .filter(([, entry]) => !isEmptySet(entry))
123
+ .map(([key, entry]) => [key, withoutEmptySets(entry)]);
124
+ const same = next.length === entries.length &&
125
+ next.every(([key, entry]) => entry === value[key]);
126
+ return same ? value : Object.fromEntries(next);
127
+ };
128
+ /** Values marshalling stores whole, which hold no `BigDecimal` to swap. */
129
+ const isOpaque = (value) => value instanceof Set ||
130
+ value instanceof Date ||
131
+ ArrayBuffer.isView(value) ||
132
+ value instanceof ArrayBuffer;
133
+ /**
134
+ * The enumerable data properties marshalling walks on an object, its prototypes' included, read
135
+ * from their descriptors. A getter is never called, so what's behind one isn't seen.
136
+ */
137
+ const dataValuesOf = (value) => {
138
+ const values = [];
139
+ const named = new Set();
140
+ for (let at = value; at !== null; at = Object.getPrototypeOf(at)) {
141
+ const descriptors = Object.getOwnPropertyDescriptors(at);
142
+ for (const key of Object.keys(descriptors)) {
143
+ if (named.has(key))
144
+ continue;
145
+ named.add(key);
146
+ const descriptor = descriptors[key];
147
+ if (descriptor.enumerable && "value" in descriptor)
148
+ values.push(descriptor.value);
149
+ }
150
+ }
151
+ return values;
152
+ };
153
+ /**
154
+ * Whether a value holds a `BigDecimal` whose cached `normalized` form leads into a cycle, anywhere
155
+ * marshalling would reach it through data. Only looked for once marshalling has refused the value,
156
+ * and without calling a getter, so a value holding none is then handled exactly as it always was:
157
+ * the same getter calls, the same bytes.
158
+ */
159
+ const holdsCachedCycle = (value, seen = new Set()) => {
160
+ if (typeof value !== "object" || value === null || isOpaque(value) || seen.has(value)) {
161
+ return false;
162
+ }
163
+ seen.add(value);
164
+ if (isBigDecimalInstance(value) && cachesCycle(value))
165
+ return true;
166
+ const parts = value instanceof Map ? [...value.values()] : dataValuesOf(value);
167
+ return parts.some((part) => holdsCachedCycle(part, seen));
168
+ };
22
169
  /**
23
- * Validate a sparse-map key at write time.
170
+ * The value with each `BigDecimal` whose cached `normalized` form leads into a cycle written
171
+ * without that cache: on its own prototype, with every other enumerable property it has, in order.
172
+ * A decimal nothing has cached on marshals to exactly that, so the stored bytes are a fresh
173
+ * decimal's. The same reference when the value holds no such decimal.
24
174
  *
25
- * Rules:
26
- * - Must be a string (we don't silently coerce).
27
- * - Must not contain `#` — `#` is reserved as the prefix/key delimiter.
28
- * - The composed `<prefix>#<key>` must satisfy DynamoDB's 1–255 byte
29
- * attribute-name limit.
175
+ * `Equal.equals`, `Hash.hash` and `BigDecimal.normalize` cache the normalized decimal on the one
176
+ * they're given, and that decimal holds itself, so marshalling recursed until the stack ran out.
177
+ */
178
+ const withoutCachedNormals = (value, open = new Set()) => {
179
+ if (typeof value !== "object" || value === null || isOpaque(value) || open.has(value)) {
180
+ return value;
181
+ }
182
+ open.add(value);
183
+ try {
184
+ if (isBigDecimalInstance(value) && cachesCycle(value)) {
185
+ const written = Object.create(Object.getPrototypeOf(value));
186
+ for (const key of Object.keys(value)) {
187
+ if (key === "normalized")
188
+ continue;
189
+ written[key] = withoutCachedNormals(value[key], open);
190
+ }
191
+ return written;
192
+ }
193
+ if (Array.isArray(value)) {
194
+ const elements = value.map((element) => withoutCachedNormals(element, open));
195
+ return elements.some((element, index) => element !== value[index]) ? elements : value;
196
+ }
197
+ if (value instanceof Map) {
198
+ const entries = [...value].map(([key, entry]) => [key, withoutCachedNormals(entry, open)]);
199
+ return entries.every(([key, entry]) => entry === value.get(key)) ? value : new Map(entries);
200
+ }
201
+ const entries = propertiesOf(value);
202
+ const next = entries.map(([key, entry]) => [key, withoutCachedNormals(entry, open)]);
203
+ return next.every(([, entry], index) => entry === entries[index][1])
204
+ ? value
205
+ : Object.fromEntries(next);
206
+ }
207
+ finally {
208
+ open.delete(value);
209
+ }
210
+ };
211
+ /**
212
+ * A list's elements with their indices, as marshalling walks them: a hole isn't there to walk (it
213
+ * stores the list closed up), so it has no entry, in a sparse, frozen or exotic list alike.
214
+ */
215
+ const listEntries = (list) => list.flatMap((element, index) => [[index, element]]);
216
+ /** {@link dataValuesOf}, with each value's name. */
217
+ const dataEntriesOf = (value) => {
218
+ const entries = [];
219
+ const named = new Set();
220
+ for (let at = value; at !== null; at = Object.getPrototypeOf(at)) {
221
+ const descriptors = Object.getOwnPropertyDescriptors(at);
222
+ for (const key of Object.keys(descriptors)) {
223
+ if (named.has(key))
224
+ continue;
225
+ named.add(key);
226
+ const descriptor = descriptors[key];
227
+ if (descriptor.enumerable && "value" in descriptor)
228
+ entries.push([key, descriptor.value]);
229
+ }
230
+ }
231
+ return entries;
232
+ };
233
+ /**
234
+ * The path to the first part of a value that holds a value it's inside, depth first as marshalling
235
+ * walks it, or `undefined`. Marshalling follows such a part until the stack runs out, as it does an
236
+ * Effect `Chunk`, whose empty end holds itself. Only looked for once marshalling has refused the
237
+ * value, and read from data descriptors, so no getter is called.
238
+ */
239
+ const cycleIn = (value, path = [], open = new Set()) => {
240
+ if (typeof value !== "object" || value === null || isOpaque(value))
241
+ return undefined;
242
+ if (open.has(value))
243
+ return path;
244
+ open.add(value);
245
+ try {
246
+ const parts = Array.isArray(value)
247
+ ? listEntries(value)
248
+ : value instanceof Map
249
+ ? [...value].map(([key, entry]) => [String(key), entry])
250
+ : dataEntriesOf(value);
251
+ for (const [key, part] of parts) {
252
+ const found = cycleIn(part, [...path, key], open);
253
+ if (found !== undefined)
254
+ return found;
255
+ }
256
+ return undefined;
257
+ }
258
+ finally {
259
+ open.delete(value);
260
+ }
261
+ };
262
+ const HOLDS_ITSELF = "it holds a value it's inside, so it has no end to store (an Effect Chunk is one: store " +
263
+ "Chunk.toReadonlyArray of it).";
264
+ /** A part marshalling reached that this can't reach without running a getter, or at all. */
265
+ const UNREACHED = Symbol("unreached");
266
+ /**
267
+ * A property as marshalling reads it, own or inherited, but from its descriptor: an accessor is
268
+ * {@link UNREACHED}, since reading it again would call its getter again.
269
+ */
270
+ const dataAt = (value, key) => {
271
+ for (let at = value; at !== null; at = Object.getPrototypeOf(at)) {
272
+ const descriptor = Object.getOwnPropertyDescriptor(at, key);
273
+ if (descriptor !== undefined)
274
+ return "value" in descriptor ? descriptor.value : UNREACHED;
275
+ }
276
+ return UNREACHED;
277
+ };
278
+ /**
279
+ * The elements marshalling stores of a list, in order: it leaves out `undefined` and functions, so
280
+ * the elements after one move up.
281
+ */
282
+ const storedElements = (list) => {
283
+ const stored = [];
284
+ for (let index = 0; index < list.length; index++) {
285
+ const descriptor = Object.getOwnPropertyDescriptor(list, index);
286
+ if (descriptor === undefined)
287
+ continue;
288
+ if (!("value" in descriptor))
289
+ return undefined;
290
+ const element = descriptor.value;
291
+ if (element !== undefined && typeof element !== "function")
292
+ stored.push(element);
293
+ }
294
+ return stored;
295
+ };
296
+ /**
297
+ * Gives each of Effect's cookies in `source` its expiry, and each named zone's map its name, in what
298
+ * marshalling made of them.
30
299
  *
31
- * Throws on violation. Caller is expected to translate into a tagged
32
- * `ValidationError` at the entity boundary.
300
+ * A cookie's `options.expires` is a `Date`, and marshalling stores a `Date` as an empty map: the
301
+ * expiry was lost. Here it's ISO text instead: this finds the cookie it came from by descriptors,
302
+ * calling no getter. A cookie is Effect's own, by its prototype; a map that only looks like one, one
303
+ * behind a getter and an invalid `Date` are left as marshalled.
304
+ *
305
+ * A named zone's map holding `resolvedId`, which Effect 4.1.3 gave a zone, is stored as 4.1.2 held
306
+ * it, under the name `zoneEntriesWritten` gives it and without `resolvedId`: what 1.40.0 stored on
307
+ * 4.1.2, whichever Effect is installed, however the zone was reached. That's decided on the map
308
+ * marshalling made, from the values it obtained, so it holds for a zone made fresh or read back, as
309
+ * an own property, behind a getter or inside anything.
310
+ *
311
+ * Marshalling has already run, exactly as it always did, and nothing else it made is touched.
312
+ *
313
+ * The same walk refuses a map marshalling assigned an entry keyed `__proto__` to: that set the
314
+ * map's prototype, so the entry would not be sent ({@link protoEntryAt}, `EDD-9165`). Given
315
+ * `dropped`, it tells `dropped` instead and goes on, leaving the map as marshalled.
316
+ */
317
+ const finishingInstances = (marshalled, source, dropped) => {
318
+ const path = [];
319
+ const lists = new Map();
320
+ const elementsOf = (list) => {
321
+ if (!lists.has(list))
322
+ lists.set(list, storedElements(list));
323
+ return lists.get(list);
324
+ };
325
+ const sourceAt = () => {
326
+ let value = source;
327
+ for (const step of path) {
328
+ if (typeof value !== "object" || value === null)
329
+ return UNREACHED;
330
+ if (typeof step === "number") {
331
+ const elements = Array.isArray(value) ? elementsOf(value) : undefined;
332
+ if (elements === undefined || step >= elements.length)
333
+ return UNREACHED;
334
+ value = elements[step];
335
+ }
336
+ else if (value instanceof Map) {
337
+ let found = UNREACHED;
338
+ for (const [key, entry] of value)
339
+ if (String(key) === step)
340
+ found = entry;
341
+ value = found;
342
+ }
343
+ else {
344
+ value = dataAt(value, step);
345
+ }
346
+ }
347
+ return value;
348
+ };
349
+ const date = (map) => {
350
+ const options = Object.hasOwn(map, "options") ? map.options.M : undefined;
351
+ const expires = options !== undefined && Object.hasOwn(options, "expires") ? options.expires : undefined;
352
+ if (expires?.M === undefined || Object.keys(expires.M).length > 0)
353
+ return;
354
+ const cookie = sourceAt();
355
+ if (typeof cookie !== "object" || cookie === null)
356
+ return;
357
+ if (Object.getPrototypeOf(cookie) !== COOKIE_PROTO)
358
+ return;
359
+ const given = dataAt(cookie, "options");
360
+ if (typeof given !== "object" || given === null)
361
+ return;
362
+ const expiry = dataAt(given, "expires");
363
+ if (!(expiry instanceof Date))
364
+ return;
365
+ if (Number.isNaN(Date.prototype.getTime.call(expiry)))
366
+ return;
367
+ options.expires = { S: Date.prototype.toISOString.call(expiry) };
368
+ };
369
+ const name = (map) => {
370
+ if (!Object.hasOwn(map, "resolvedId"))
371
+ return;
372
+ const entries = Object.entries(map);
373
+ const written = zoneEntriesWritten(entries, true, (attribute) => attribute.S, (id) => ({ S: id }));
374
+ if (written === entries)
375
+ return;
376
+ map.id = { S: written.find(([key]) => key === "id")[1].S };
377
+ delete map.resolvedId;
378
+ };
379
+ const visit = (attribute) => {
380
+ const map = attribute.M;
381
+ if (map !== undefined) {
382
+ // Marshalling assigned an entry keyed `__proto__`: it is this map's prototype, not stored.
383
+ if (Object.getPrototypeOf(map) !== Object.prototype) {
384
+ const refusal = protoEntryAt([...path, "__proto__"]);
385
+ if (dropped === undefined)
386
+ throw refusal;
387
+ dropped(refusal);
388
+ }
389
+ if (Object.hasOwn(map, COOKIE_MARKER))
390
+ date(map);
391
+ if (Object.hasOwn(map, ZONE_MARKER))
392
+ name(map);
393
+ for (const key of Object.keys(map)) {
394
+ path.push(key);
395
+ visit(map[key]);
396
+ path.pop();
397
+ }
398
+ return;
399
+ }
400
+ const list = attribute.L;
401
+ if (list === undefined)
402
+ return;
403
+ for (let index = 0; index < list.length; index++) {
404
+ path.push(index);
405
+ visit(list[index]);
406
+ path.pop();
407
+ }
408
+ };
409
+ visit({ M: marshalled });
410
+ return marshalled;
411
+ };
412
+ /** Whether marshalling refuses a value. A lost value a getter returned is refused as itself. */
413
+ const isRefused = (value) => {
414
+ try {
415
+ marshall({ v: value }, MARSHALL_OPTIONS);
416
+ return false;
417
+ }
418
+ catch (error) {
419
+ if (isUnstorableValue(error))
420
+ throw error;
421
+ return true;
422
+ }
423
+ };
424
+ const partsOf = (value) => {
425
+ if (Array.isArray(value))
426
+ return listEntries(value);
427
+ if (value instanceof Map)
428
+ return [...value];
429
+ if (typeof value !== "object" || value === null)
430
+ return [];
431
+ return propertiesOf(value);
432
+ };
433
+ /**
434
+ * The deepest part of a value marshalling refuses, as the error saying so. Marshalling
435
+ * walks in this order and stops at the first it refuses, so `reason` is that part's.
436
+ */
437
+ const unstorableAt = (value, path, reason) => {
438
+ for (const [key, part] of partsOf(value)) {
439
+ if (isRefused(part))
440
+ return unstorableAt(part, [...path, key], reason);
441
+ }
442
+ return new UnstorableValue({
443
+ path,
444
+ reason: isEmptySet(value) ? NO_EMPTY_SET : reason,
445
+ });
446
+ };
447
+ const NO_EMPTY_SET = "DynamoDB has no empty set, and a list element can't be left out without moving those after it.";
448
+ /**
449
+ * DynamoDB can't store an empty set, so one is an absent attribute. Marshalling
450
+ * refuses it, and only then are the item's empty sets looked for: an item without
451
+ * any costs nothing and marshals exactly as it did. A `BigDecimal` something has
452
+ * cached a normalized form on is refused the same way, since the cache holds
453
+ * itself: it's written without that cache before anything else walks the item
454
+ * ({@link withoutCachedNormals}). An item holding no such decimal
455
+ * ({@link holdsCachedCycle}, which calls no getter) goes on exactly as before.
456
+ * Whatever is still refused has no attribute to leave out, and throws
457
+ * {@link UnstorableValue}, as does a value holding one it's inside ({@link cycleIn}), which
458
+ * marshalling follows until the stack runs out. What marshalling makes of a cookie is then given the
459
+ * cookie's expiry, and what it makes of a named zone the zone's name ({@link finishingInstances}),
460
+ * and a map entry keyed `__proto__`, which marshalling drops, is refused (`EDD-9165`).
33
461
  */
34
- const validateSparseKey = (field, prefix, key) => {
35
- if (typeof key !== "string") {
36
- throw new Error(`Sparse map "${field}": key must be a string, got ${typeof key}`);
462
+ const marshallStorable = (given, dropped) => {
463
+ const item = judgedAsRead(given);
464
+ let written = item;
465
+ let marshalled;
466
+ try {
467
+ marshalled = marshall(item, MARSHALL_OPTIONS);
37
468
  }
38
- if (key.length === 0) {
39
- throw new Error(`Sparse map "${field}": key must be non-empty`);
469
+ catch (error) {
470
+ // A lost value a getter returned: refused as it is, without reading anything again.
471
+ if (isUnstorableValue(error))
472
+ throw error;
473
+ const fresh = holdsCachedCycle(item) ? withoutCachedNormals(item) : item;
474
+ // Followed further, a value holding itself would run the stack out here too.
475
+ const cycle = cycleIn(fresh);
476
+ if (cycle !== undefined)
477
+ throw new UnstorableValue({ path: cycle, reason: HOLDS_ITSELF });
478
+ written = withoutEmptySets(fresh);
479
+ try {
480
+ marshalled = marshall(written, MARSHALL_OPTIONS);
481
+ }
482
+ catch (cause) {
483
+ if (isUnstorableValue(cause))
484
+ throw cause;
485
+ throw unstorableAt(written, [], cause instanceof Error ? cause.message : String(cause));
486
+ }
40
487
  }
41
- if (key.includes("#")) {
42
- throw new Error(`Sparse map "${field}": key "${key}" must not contain '#' — the library does not silently escape`);
488
+ return finishingInstances(marshalled, written, dropped);
489
+ };
490
+ /**
491
+ * What in these attributes DynamoDB can't store, or `undefined`, for a path that
492
+ * has to know before it reads or sends anything. An attribute holding an empty set
493
+ * is left out, as when it's written.
494
+ */
495
+ export const unstorableIn = (attributes) => {
496
+ try {
497
+ marshallStorable(attributes);
498
+ return undefined;
43
499
  }
44
- const attrName = `${prefix}#${key}`;
45
- // DynamoDB attribute names: 1–255 bytes. Length check is approximate (UTF-8
46
- // bytes vs JS code units), but `key.length + prefix.length + 1` is an upper
47
- // bound on byte length when both are ASCII, which is the common case.
48
- // For full UTF-8 correctness, encode via TextEncoder.
49
- const byteLen = new TextEncoder().encode(attrName).length;
50
- if (byteLen < 1 || byteLen > 255) {
51
- throw new Error(`Sparse map "${field}": composed attribute name "${attrName}" is ${byteLen} bytes (must be 1–255)`);
500
+ catch (error) {
501
+ if (isUnstorableValue(error))
502
+ return error;
503
+ throw error;
52
504
  }
53
505
  };
506
+ /** Marshall a JS object to a DynamoDB attribute map */
507
+ export const toAttributeMap = (item) => marshallStorable(item);
508
+ /**
509
+ * Whether `map`, or a map or a list within it at any depth, holds an entry named `__proto__`. Read
510
+ * on every row, so written for speed: its own keys by `Object.keys` (an entry so named is an own
511
+ * enumerable one, as a response's JSON gives it), and indexed loops. A row holding none is walked
512
+ * once and handed to the unmarshaller as it is.
513
+ */
514
+ const holdsProtoEntry = (map) => {
515
+ const keys = Object.keys(map);
516
+ for (let index = 0; index < keys.length; index++) {
517
+ const key = keys[index];
518
+ if (key === "__proto__")
519
+ return true;
520
+ const value = map[key];
521
+ if (value == null)
522
+ continue;
523
+ const nested = value.M;
524
+ if (nested !== undefined) {
525
+ if (holdsProtoEntry(nested))
526
+ return true;
527
+ }
528
+ else {
529
+ const list = value.L;
530
+ if (list !== undefined && listHoldsProtoEntry(list))
531
+ return true;
532
+ }
533
+ }
534
+ return false;
535
+ };
536
+ const listHoldsProtoEntry = (list) => {
537
+ for (let index = 0; index < list.length; index++) {
538
+ const value = list[index];
539
+ if (value == null)
540
+ continue;
541
+ const nested = value.M;
542
+ if (nested !== undefined) {
543
+ if (holdsProtoEntry(nested))
544
+ return true;
545
+ }
546
+ else {
547
+ const inner = value.L;
548
+ if (inner !== undefined && listHoldsProtoEntry(inner))
549
+ return true;
550
+ }
551
+ }
552
+ return false;
553
+ };
554
+ /** `map` without the entries named `__proto__` it, and every map within it, holds. */
555
+ const withoutProtoEntries = (map) => {
556
+ const kept = {};
557
+ const keys = Object.keys(map);
558
+ for (let index = 0; index < keys.length; index++) {
559
+ const key = keys[index];
560
+ if (key !== "__proto__")
561
+ kept[key] = withoutProtoEntry(map[key]);
562
+ }
563
+ return kept;
564
+ };
565
+ const withoutProtoEntry = (value) => value == null
566
+ ? value
567
+ : value.M !== undefined
568
+ ? { M: withoutProtoEntries(value.M) }
569
+ : value.L !== undefined
570
+ ? { L: value.L.map((element) => withoutProtoEntry(element)) }
571
+ : value;
572
+ /**
573
+ * `item` for the AWS SDK's unmarshaller, which assigns each attribute and map entry to a plain
574
+ * object: one named `__proto__` would set that object's prototype instead, so a map stored there
575
+ * (by another writer: the library refuses to write one, `EDD-9165`) would give the object every
576
+ * entry of that map as an inherited property, read as its own fields. Such an entry is left out,
577
+ * whatever it holds. `item` itself where it holds none.
578
+ */
579
+ const readable = (item) => holdsProtoEntry(item) ? withoutProtoEntries(item) : item;
580
+ /**
581
+ * Unmarshall a DynamoDB attribute map to a JS object. An attribute or a map entry named
582
+ * `__proto__` is not read (`EDD-9165`).
583
+ */
584
+ export const fromAttributeMap = (item) => unmarshall(readable(item));
585
+ /**
586
+ * Marshall a single value to a DynamoDB attribute value. An empty set directly
587
+ * here is refused, as marshalling refuses it: a caller holding a value to send has
588
+ * no attribute to leave out, and has to decide what no value means. A refusal names
589
+ * the value's `name`, when it has one.
590
+ *
591
+ * Given `dropped`, a map entry keyed `__proto__` (`EDD-9165`) is not refused here: the value is
592
+ * marshalled as 1.40.0 marshalled it, without that entry, and `dropped` is told where it was.
593
+ * `Expression`'s builders use it, so that what they return is refused where it is sent.
594
+ */
595
+ export const toAttributeValue = (value, name, dropped) => {
596
+ const at = name === undefined ? [] : [name];
597
+ if (isEmptySet(value))
598
+ throw new UnstorableValue({ path: at, reason: "DynamoDB has no empty set." });
599
+ try {
600
+ return marshallStorable({ v: value }, dropped === undefined
601
+ ? undefined
602
+ : (refusal) => dropped(refusal.at([...at, ...refusal.path.slice(1)]))).v;
603
+ }
604
+ catch (error) {
605
+ if (!isUnstorableValue(error))
606
+ throw error;
607
+ throw error.at([...at, ...error.path.slice(1)]);
608
+ }
609
+ };
610
+ /**
611
+ * Unmarshall a single DynamoDB attribute value. A map entry named `__proto__` within it is not
612
+ * read (`EDD-9165`).
613
+ */
614
+ export const fromAttributeValue = (value) => unmarshall(readable({ v: value })).v;
615
+ // ---------------------------------------------------------------------------
616
+ // Sparse Map flatten / rebuild
617
+ // ---------------------------------------------------------------------------
54
618
  /**
55
619
  * Flatten sparse-map fields on an item before marshalling.
56
620
  *
@@ -65,7 +629,7 @@ const validateSparseKey = (field, prefix, key) => {
65
629
  */
66
630
  export const encodeSparseFields = (item, sparseFields) => {
67
631
  for (const [fieldName, sparse] of Object.entries(sparseFields)) {
68
- if (!(fieldName in item))
632
+ if (!Object.hasOwn(item, fieldName))
69
633
  continue;
70
634
  const value = item[fieldName];
71
635
  if (value === undefined || value === null) {
@@ -86,50 +650,40 @@ export const encodeSparseFields = (item, sparseFields) => {
86
650
  /**
87
651
  * Rebuild sparse-map fields on a raw item after unmarshalling.
88
652
  *
89
- * For each `(fieldName, { prefix })` in `sparseFields`:
90
- * - Walk top-level keys, collect any matching `<prefix>#<key>`,
91
- * extract the key portion, and accumulate into `out[fieldName][key]`.
92
- * - Delete the flattened attributes from the raw item.
93
- * - If no matching attributes are found, the result is `{}` — sparse fields
94
- * on the domain side are required (a `Schema.Record` always decodes to an
95
- * object, never `undefined`).
653
+ * Each attribute the reader takes as a sparse map's entry (`sparseReader`: `<prefix>#` and a
654
+ * non-empty key) moves into `raw[field][key]`. Every sparse field gets a Record, `{}` when no
655
+ * attribute is its entry — sparse fields on the domain side are required (a `Schema.Record`
656
+ * always decodes to an object, never `undefined`).
96
657
  *
97
658
  * Mutates `raw` in place.
98
659
  */
99
660
  export const decodeSparseFields = (raw, sparseFields) => {
100
661
  if (Object.keys(sparseFields).length === 0)
101
662
  return;
102
- // Build a list of (fieldName, prefix, prefixWithDelim) once so we don't
103
- // re-concatenate per attribute.
104
- const entries = [];
105
- for (const [fieldName, sparse] of Object.entries(sparseFields)) {
106
- entries.push([fieldName, sparse.prefix, `${sparse.prefix}#`]);
107
- }
108
- // Sort by prefix length descending so a longer prefix wins over a shorter
109
- // prefix that happens to be its own substring (e.g. `metric` vs `metrics`).
110
- entries.sort((a, b) => b[2].length - a[2].length);
111
- // Initialize empty buckets for each sparse field.
112
- const buckets = {};
113
- for (const [fieldName] of entries)
114
- buckets[fieldName] = {};
663
+ const { fields, entryOf } = sparseReader(sparseFields);
664
+ // An empty bucket for each sparse field: a plain object, as the row's other maps are, so
665
+ // whatever reads the row (a vector's source text, a caller's `compose`) meets an ordinary
666
+ // object. An entry's key is whatever follows the prefix in the attribute's name, so an entry
667
+ // is defined as the bucket's own property: `__proto__` is a key like any other, where
668
+ // assigning it dropped the entry.
669
+ const buckets = new Map();
670
+ for (const fieldName of fields)
671
+ buckets.set(fieldName, {});
115
672
  // One pass over keys.
116
- const keys = Object.keys(raw);
117
- for (const k of keys) {
118
- for (const [fieldName, , prefixWithDelim] of entries) {
119
- if (k.startsWith(prefixWithDelim)) {
120
- const subKey = k.substring(prefixWithDelim.length);
121
- // Skip empty sub-keys (defensive — would mean the stored attr was
122
- // literally `<prefix>#`, which validation rejects on write).
123
- if (subKey.length === 0)
124
- break;
125
- buckets[fieldName][subKey] = raw[k];
126
- delete raw[k];
127
- break;
128
- }
129
- }
673
+ for (const k of Object.keys(raw)) {
674
+ const entry = entryOf(k);
675
+ if (entry === undefined)
676
+ continue;
677
+ Object.defineProperty(buckets.get(entry.field), entry.key, {
678
+ value: raw[k],
679
+ enumerable: true,
680
+ writable: true,
681
+ configurable: true,
682
+ });
683
+ delete raw[k];
130
684
  }
131
- for (const [fieldName] of entries) {
132
- raw[fieldName] = buckets[fieldName];
685
+ for (const fieldName of fields) {
686
+ setOwn(raw, fieldName, buckets.get(fieldName));
133
687
  }
134
688
  };
135
689
  //# sourceMappingURL=Marshaller.js.map