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
@@ -4,15 +4,19 @@
4
4
  * Extracts common patterns: table name resolution, primary key composition,
5
5
  * and put-item construction (validation + key composition + system fields).
6
6
  */
7
+ import { isConfiguredModel } from "@effect-dynamodb/schema/DynamoModel.js";
7
8
  import { ValidationError } from "@effect-dynamodb/schema/Errors.js";
8
9
  import { makeDefaultCrypto } from "@effect-dynamodb/schema/internal/DefaultCrypto.js";
9
10
  import { resolveUniqueFields } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
10
- import { isKeyValueError } from "@effect-dynamodb/schema/internal/NumericKey.js";
11
- import { isShardSourceError } from "@effect-dynamodb/schema/internal/Shards.js";
12
- import { isZOrderValueError } from "@effect-dynamodb/schema/internal/ZOrderCurve.js";
11
+ import { given, ownValue } from "@effect-dynamodb/schema/internal/OwnNames.js";
12
+ import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
13
13
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
14
- import { DateTime, Effect, Option, Schema } from "effect";
15
- import { fromAttributeMap, toAttributeMap } from "../Marshaller.js";
14
+ import { DateTime, Effect, Option } from "effect";
15
+ import { SecureRandom } from "effect/crypto";
16
+ import { fromAttributeMap, isUnstorableValue, toAttributeMap } from "../Marshaller.js";
17
+ import { resolveTtlAttributeName, tableKeyAttributes } from "../Table.js";
18
+ import { isRefusedValue } from "./Capacity.js";
19
+ import { encodeInput } from "./InputForm.js";
16
20
  /**
17
21
  * @internal Hidden per-incarnation token of a versioned entity (#133): set
18
22
  * when an item is created, it tells an item apart from a deleted-and-recreated
@@ -20,23 +24,310 @@ import { fromAttributeMap, toAttributeMap } from "../Marshaller.js";
20
24
  * `__edd_e__` so it cannot collide with a model field; never decoded.
21
25
  */
22
26
  export const INCARNATION_TOKEN = "__edd_i__";
23
- /** @internal */
24
- export const projectionTombstonesOf = (entity) => entity._projectionTombstones;
25
- /**
26
- * @internal `create` over a projection tombstone (#154): read the key, and
27
- * when it holds the entity's tombstone, carry the projection's kept fields
28
- * over into `item` (stored names, wire values) — its checkpoints, so a late
29
- * redelivery is still recognised — with the revision one higher, and return
30
- * the guard naming that very tombstone. `None` when there is no tombstone:
31
- * `create`'s own guard applies.
32
- */
33
- export const overTombstone = (entity, client, tableName, item) => Effect.gen(function* () {
34
- const layout = projectionTombstonesOf(entity);
35
- if (layout === undefined)
27
+ /**
28
+ * @internal The row token (#237) on the rows of a read model that `rowTokened` says carry one:
29
+ * 128 random bits (base64url), then the tags of the projection layouts that have written the row
30
+ * (`layoutTag`), each `.`-prefixed. Every projection write, tombstone and rebuild write, and
31
+ * `create` over a tombstone, writes a fresh one, conditioned on the one it read (`rowTokenTerm`):
32
+ * a write that read the row before another fails, whichever projection made the other and
33
+ * whatever counters it reset. Named like `__edd_e__`; never decoded.
34
+ */
35
+ export const ROW_TOKEN = "__edd_rt__";
36
+ /**
37
+ * @internal The tags of the layouts that have written a row, from its row token as read: none
38
+ * for a row without one.
39
+ */
40
+ export const rowWriters = (token) => token?.S === undefined ? [] : token.S.split(".").slice(1);
41
+ /**
42
+ * @internal Whether a read model's rows carry the row token (`ROW_TOKEN`): more than one
43
+ * projection layout is recorded on it. Asked when a write is made, so a projection defined later
44
+ * counts. With one layout, the projection's own revision or checkpoint serialises its writes, and
45
+ * it sends and stores what 1.40.0 did.
46
+ */
47
+ export const rowTokened = (entity) => (projectionLayoutsOf(entity)?.length ?? 0) > 1;
48
+ /**
49
+ * @internal The attributes a read model's rows and tombstones hold under names its definitions
50
+ * decide (#237), or `undefined` when its model's fields can't be listed: each model field, by its
51
+ * name and its stored name (`field:`); every key attribute of its table (`tableKeyAttributes`:
52
+ * every member's, every aggregate's and every event stream's index, its own included) and of its
53
+ * own indexes; its `created` / `updated` timestamps and its version; the table's TTL attribute
54
+ * (`ttlName`, from the table's layer, `undefined` where that isn't known: an aggregate's checks);
55
+ * and each of its projections' outboxes on its table, by key and index attribute. A sparse map's
56
+ * entries (`<prefix>#<key>`) always hold a `#`, so never one of the library's names.
57
+ */
58
+ const rowItemNames = (entity, ttlName) => {
59
+ const member = entity;
60
+ const model = isConfiguredModel(member.model) ? member.model.model : member.model;
61
+ if (model === undefined)
62
+ return undefined;
63
+ const fields = getSchemaFields(model);
64
+ if (fields === undefined)
65
+ return undefined;
66
+ const names = new Set();
67
+ for (const field of Object.keys(fields)) {
68
+ names.add(field);
69
+ const probe = { [field]: 1 };
70
+ member._renameToDynamo?.(probe);
71
+ for (const stored of Object.keys(probe))
72
+ names.add(stored);
73
+ }
74
+ for (const index of Object.values(member.indexes ?? {})) {
75
+ names.add(index.pk.field);
76
+ if (index.sk !== undefined)
77
+ names.add(index.sk.field);
78
+ }
79
+ for (const name of tableKeyAttributes(member._tableTag) ?? [])
80
+ names.add(name);
81
+ const system = member.systemFields;
82
+ for (const name of [system?.createdAt, system?.updatedAt, system?.version]) {
83
+ if (typeof name === "string")
84
+ names.add(name);
85
+ }
86
+ if (ttlName !== undefined)
87
+ names.add(ttlName);
88
+ for (const outbox of member._projectionOutboxes ?? []) {
89
+ if (outbox.table !== undefined && outbox.table.Tag !== member._tableTag)
90
+ continue;
91
+ names.add(outbox.pk).add(outbox.sk);
92
+ if (outbox.index !== undefined)
93
+ names.add(outbox.index.pk).add(outbox.index.sk);
94
+ }
95
+ return names;
96
+ };
97
+ /**
98
+ * @internal Whether a read model's rows may carry the row token (`ROW_TOKEN`, #237): its name is
99
+ * free on them (`rowItemNames`). The one decision, from the definitions and the table's TTL
100
+ * attribute (`ttlName`), never from a stored row: where anything the read model's definitions
101
+ * name is `__edd_rt__`, its rows carry none, no write names it or reads one, and its projections
102
+ * write, carry and refuse as with one projection layout (`rowTokened` only adds to this).
103
+ */
104
+ export const rowTokenInUse = (entity, ttlName) => rowItemNames(entity, ttlName)?.has(ROW_TOKEN) === false;
105
+ const tokenRandom = makeDefaultCrypto();
106
+ /**
107
+ * @internal A fresh row token recording `writers` (deduplicated, sorted) after its random part,
108
+ * from the `SecureRandom` in context, else Web Crypto: no requirement is added.
109
+ */
110
+ export const freshRowToken = (writers) => Effect.serviceOption(SecureRandom.SecureRandom).pipe(Effect.flatMap((random) => (Option.isSome(random) ? random.value : tokenRandom).randomBytes(16)), Effect.map((bytes) => {
111
+ let binary = "";
112
+ for (const byte of bytes)
113
+ binary += String.fromCharCode(byte);
114
+ const random = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
115
+ return [random, ...[...new Set(writers)].sort()].join(".");
116
+ }));
117
+ /**
118
+ * @internal The term proving a row still holds the token a write read: the stored value as the
119
+ * read returned it, or its absence.
120
+ */
121
+ export const rowTokenTerm = (read) => read === undefined
122
+ ? { expression: "attribute_not_exists(#eddRt)", names: { "#eddRt": ROW_TOKEN }, values: {} }
123
+ : { expression: "#eddRt = :eddRt", names: { "#eddRt": ROW_TOKEN }, values: { ":eddRt": read } };
124
+ /**
125
+ * @internal The term naming each attribute of `names` as `item` holds it, or its absence (#237).
126
+ * Every projection write changes the projection's revision, else its checkpoint, whichever library
127
+ * wrote it, so a row read without a row token is proven as read by the projections' bookkeeping.
128
+ */
129
+ export const heldTerm = (item, names) => {
130
+ const terms = [];
131
+ const placeholders = {};
132
+ const values = {};
133
+ let i = 0;
134
+ for (const name of names) {
135
+ placeholders[`#eddTb${i}`] = name;
136
+ const value = Object.hasOwn(item, name) ? item[name] : undefined;
137
+ if (value === undefined)
138
+ terms.push(`attribute_not_exists(#eddTb${i})`);
139
+ else {
140
+ terms.push(`#eddTb${i} = :eddTb${i}`);
141
+ values[`:eddTb${i}`] = value;
142
+ }
143
+ i++;
144
+ }
145
+ return terms.length === 0
146
+ ? undefined
147
+ : { expression: terms.join(" AND "), names: placeholders, values };
148
+ };
149
+ /**
150
+ * @internal The term proving a row a write read (`item`, as stored) is still as read (#237): the
151
+ * row token it held; else the projections' bookkeeping `names` as it held them (`heldTerm`) and,
152
+ * on a read model whose rows carry the token (`rowTokened`), the token's absence. A row without a
153
+ * token was last written by a process still on 1.40.0, which writes none, or before the token:
154
+ * the bookkeeping proves a write by either landed since, the token's absence one by this release.
155
+ * `inUse` is `rowTokenInUse`: where the token's name is taken, an attribute of that name is the
156
+ * user's, and only the bookkeeping is named.
157
+ */
158
+ export const asReadTerm = (entity, item, names, inUse) => {
159
+ const read = inUse && Object.hasOwn(item, ROW_TOKEN) ? item[ROW_TOKEN] : undefined;
160
+ if (read !== undefined)
161
+ return rowTokenTerm(read);
162
+ const held = heldTerm(item, names);
163
+ return inUse && rowTokened(entity) ? andRaw(rowTokenTerm(undefined), held) : held;
164
+ };
165
+ /** @internal Both conditions, either of which may be absent. Their placeholders must differ. */
166
+ export const andRaw = (a, b) => a === undefined
167
+ ? b
168
+ : b === undefined
169
+ ? a
170
+ : {
171
+ expression: `(${a.expression}) AND (${b.expression})`,
172
+ names: { ...a.names, ...b.names },
173
+ values: { ...a.values, ...b.values },
174
+ };
175
+ /**
176
+ * @internal A projection layout's tag, in outbox items' marks and row tokens: FNV-1a (32-bit, base
177
+ * 36) of its roles, `removal` and `ttl`, so every program defining the projection gives it the
178
+ * same tag.
179
+ */
180
+ export const layoutTag = (layout) => {
181
+ let hash = 0x811c9dc5;
182
+ for (const char of JSON.stringify([layout.roles, layout.removal, layout.ttl])) {
183
+ hash ^= char.charCodeAt(0);
184
+ hash = Math.imul(hash, 0x01000193) >>> 0;
185
+ }
186
+ return hash.toString(36);
187
+ };
188
+ /**
189
+ * @internal The layout of every projection defined on the read model, one entry per distinct
190
+ * layout; `undefined` when none is.
191
+ */
192
+ export const projectionLayoutsOf = (entity) => entity._projectionLayouts;
193
+ /**
194
+ * @internal Whether a projection defined on the read model has `removal`: its rows may be
195
+ * tombstones, which `create` takes the place of (`overTombstone`), so `create` reads first.
196
+ */
197
+ export const hasProjectionTombstones = (entity) => entity._projectionTombstones === true;
198
+ /** A domain field's stored attribute name on `entity`. */
199
+ const storedName = (entity, field) => {
200
+ const probe = { [field]: 1 };
201
+ entity._renameToDynamo(probe);
202
+ return Object.keys(probe)[0] ?? field;
203
+ };
204
+ /**
205
+ * `[EDD-9133]` among `layouts`: a stored attribute one projection names in two roles. The problem,
206
+ * or `undefined`. `current` is the layout being defined, named "this projection". Two projections
207
+ * may name one attribute in different roles: each writes its own, so two that never write one
208
+ * row (rows of disjoint keys) work as on 1.39.0. Two that share rows and swap names can't be told
209
+ * apart from them, and are as broken as on 1.39.0.
210
+ */
211
+ const roleConflict = (entity, layouts, current) => {
212
+ const whose = (layout) => layout === current ? "this projection's" : `${layout.label}'s`;
213
+ const as = (field, stored) => field === stored ? `"${field}"` : `"${field}" (stored as "${stored}")`;
214
+ for (const layout of layouts) {
215
+ const first = new Map();
216
+ for (const [field, role] of layout.roles) {
217
+ const stored = storedName(entity, field);
218
+ const held = first.get(stored);
219
+ if (held === undefined) {
220
+ first.set(stored, { layout, field, role });
221
+ continue;
222
+ }
223
+ if (held.role === role)
224
+ continue;
225
+ const second = held.field === field ? `its ${role}` : `${as(field, stored)} its ${role}`;
226
+ return (`[EDD-9133] ${current.label}: on read model "${entity.entityType}", ` +
227
+ `${as(held.field, stored)} is ${whose(held.layout)} ${held.role}, and ${second}. A ` +
228
+ "projection of the read model has `removal`, and a tombstone carries a checkpoint as it " +
229
+ "is and raises a revision: an attribute holds one role in a projection. Give each its " +
230
+ "own field.");
231
+ }
232
+ }
233
+ return undefined;
234
+ };
235
+ /**
236
+ * @internal Record a projection's layout on its read model, beside those of the other projections
237
+ * defined on it, and whether it has `removal`. On a read model one of whose projections has
238
+ * `removal`, a stored attribute one projection names in two roles is refused (`[EDD-9133]`), before
239
+ * anything is recorded: its tombstone carries a checkpoint as it is and raises a revision, so the
240
+ * two would overwrite each other's values. The refusal comes at whichever definition completes the
241
+ * conflict (the projection's own, or the first `removal`), so the order projections are defined in
242
+ * doesn't decide it. Without `removal` nothing is refused: rows are never tombstones. Two
243
+ * projections naming one attribute in different roles are not refused (`roleConflict`). A layout
244
+ * already there moves to the end rather than being added again, so a projection defined over and
245
+ * over (in a function, say) doesn't grow the list.
246
+ */
247
+ export const addProjectionLayout = (entity, layout) => {
248
+ const holder = entity;
249
+ const same = (other) => other.removal === layout.removal &&
250
+ other.ttl === layout.ttl &&
251
+ other.roles.length === layout.roles.length &&
252
+ other.roles.every(([field, role], i) => {
253
+ const [f, r] = layout.roles[i];
254
+ return field === f && role === r;
255
+ });
256
+ const layouts = [...(holder._projectionLayouts ?? []).filter((other) => !same(other)), layout];
257
+ if (layout.removal || hasProjectionTombstones(entity)) {
258
+ const problem = roleConflict(entity, layouts, layout);
259
+ if (problem !== undefined)
260
+ throw new Error(problem);
261
+ }
262
+ holder._projectionLayouts = layouts;
263
+ if (layout.removal)
264
+ holder._projectionTombstones = true;
265
+ };
266
+ /**
267
+ * @internal Whether the read model's TTL attribute must be checked against the attributes its
268
+ * projections keep (`projectionTtlConflict`): a projection's tombstones set it (`removal.ttl`).
269
+ * Only then is the table resolved for it.
270
+ */
271
+ export const projectionTtlChecked = (entity) => hasProjectionTombstones(entity) &&
272
+ (projectionLayoutsOf(entity) ?? []).some((layout) => layout.ttl);
273
+ /**
274
+ * @internal `[EDD-9133]` at run time, once the table's TTL attribute is known: an attribute a
275
+ * projection keeps on the read model's rows that is stored as the TTL attribute, which another's
276
+ * tombstones set (`removal.ttl`). The problem, or `undefined` when there is none. Like the
277
+ * definition's refusal, only on a read model one of whose projections has `removal`.
278
+ */
279
+ export const projectionTtlConflict = (entity, ttlAttribute) => {
280
+ if (!projectionTtlChecked(entity))
281
+ return undefined;
282
+ for (const layout of projectionLayoutsOf(entity) ?? []) {
283
+ for (const [field, role] of layout.roles) {
284
+ if (storedName(entity, field) === ttlAttribute) {
285
+ return (`[EDD-9133] "${field}" is a projection's ${role} on read model "${entity.entityType}", ` +
286
+ `stored as "${ttlAttribute}", the table's TTL attribute, which a projection's ` +
287
+ "tombstones set (`removal.ttl`). An attribute holds one role: give the " +
288
+ `${role} its own field.`);
289
+ }
290
+ }
291
+ }
292
+ return undefined;
293
+ };
294
+ /**
295
+ * @internal `create` over a projection tombstone (#154): read the key, and when it holds the
296
+ * entity's tombstone, carry what the projections with `removal` keep on one over into `item`
297
+ * (stored names, wire values), and return the guard naming that very tombstone. `None` when there
298
+ * is no tombstone: `create`'s own guard applies. A tombstone holds the attributes of the projection
299
+ * that wrote it, which may be any of those with `removal`: each one's checkpoints (and map, and
300
+ * owners) the tombstone holds are carried as they are, so a late redelivery is still recognised,
301
+ * and its revision one higher. An attribute two of them name is taken in the role the one defined
302
+ * last gives it, as 1.39.0 took every attribute from that one. A projection without `removal`
303
+ * writes no tombstone, and isn't consulted. When a projection's tombstones set the table's TTL
304
+ * attribute, it is never carried, so the row doesn't expire with the tombstone: a projection
305
+ * naming it is refused when it writes (`projectionTtlConflict`), and one defined after a tombstone
306
+ * was written would otherwise carry its expiry onto the row.
307
+ *
308
+ * Each value is stored as the row stores any value of the field: a sparse map as its entries (a
309
+ * tombstone holds it whole, as 1.39.0's did), an entry whose key sparse storage can't hold left
310
+ * off, never the whole map; a packed field packed (#237), read first by its stored form, since a
311
+ * tombstone holds it natively and one written before may hold it packed. A row with nothing
312
+ * packed carried packs nothing, so its request is unchanged.
313
+ *
314
+ * Where the row token's name is free (`rowTokenInUse`, with the table's TTL attribute), on a read
315
+ * model whose rows carry it (`rowTokened`), or when the tombstone holds one, the tombstone also
316
+ * holds the bookkeeping of the other projections that had written the row (#237): those of
317
+ * projections without `removal` are carried after, each attribute the others haven't named, in
318
+ * the same way. The row gets a fresh token recording the projections whose bookkeeping it holds.
319
+ * `term` proves the tombstone is still as read (`asReadTerm`): its token, else every projection's
320
+ * bookkeeping as it holds it (or its absence), so a tombstone written since fails it. The removal
321
+ * stamp alone has a millisecond's resolution, so a row written over the tombstone and removed
322
+ * again within one would pass it, and its newer checkpoints be lost to the older ones.
323
+ */
324
+ export const overTombstone = (entity, client, table, item) => Effect.gen(function* () {
325
+ if (!hasProjectionTombstones(entity))
36
326
  return Option.none();
327
+ const layouts = projectionLayoutsOf(entity) ?? [];
37
328
  const primary = entity.indexes.primary;
38
329
  const { Item } = yield* client.getItem({
39
- TableName: tableName,
330
+ TableName: table.name,
40
331
  Key: toAttributeMap({
41
332
  [primary.pk.field]: item[primary.pk.field],
42
333
  [primary.sk.field]: item[primary.sk.field],
@@ -46,24 +337,106 @@ export const overTombstone = (entity, client, tableName, item) => Effect.gen(fun
46
337
  if (Item === undefined || !isProjectionTombstone(Item, entity.entityType))
47
338
  return Option.none();
48
339
  const tomb = fromAttributeMap(Item);
49
- const dbName = (field) => {
50
- const probe = { [field]: 1 };
51
- entity._renameToDynamo(probe);
52
- return Object.keys(probe)[0] ?? field;
340
+ const ttl = layouts.some((layout) => layout.ttl) ? resolveTtlAttributeName(table) : undefined;
341
+ // An attribute is the tombstone's own, never a member it inherits.
342
+ const held = (name) => (Object.hasOwn(tomb, name) ? tomb[name] : undefined);
343
+ // A value as the row stores it: a sparse map as its entries, each one sparse storage can hold.
344
+ const carry = (name, value) => {
345
+ const holds = (part) => {
346
+ try {
347
+ entity._serializeSparseFields(part);
348
+ return true;
349
+ }
350
+ catch {
351
+ return false;
352
+ }
353
+ };
354
+ const whole = { [name]: value };
355
+ if (holds(whole)) {
356
+ Object.assign(item, whole);
357
+ return;
358
+ }
359
+ if (typeof value !== "object" || value === null)
360
+ return;
361
+ for (const [entry, v] of Object.entries(value)) {
362
+ const part = { [name]: { [entry]: v } };
363
+ if (holds(part))
364
+ Object.assign(item, part);
365
+ }
53
366
  };
54
- for (const field of layout.kept) {
55
- const name = dbName(field);
56
- if (tomb[name] !== undefined)
57
- item[name] = tomb[name];
367
+ // The projections with `removal`, the one defined last first. Each attribute once, in the role
368
+ // of the first that names it: its checkpoints, then its revision, as with one layout.
369
+ const taken = new Set();
370
+ const carried = new Set();
371
+ const ordered = [...layouts].reverse();
372
+ for (const layout of [
373
+ ...ordered.filter((layout) => layout.removal),
374
+ ...ordered.filter((layout) => !layout.removal),
375
+ ]) {
376
+ const mine = layout.roles
377
+ .map(([field, role]) => [storedName(entity, field), role])
378
+ .filter(([name]) => name !== ttl && !taken.has(name));
379
+ for (const [name, role] of mine) {
380
+ taken.add(name);
381
+ if (role !== "revision" && held(name) !== undefined) {
382
+ carry(name, held(name));
383
+ carried.add(name);
384
+ }
385
+ }
386
+ for (const [name, role] of mine) {
387
+ if (role === "revision" && held(name) !== undefined) {
388
+ item[name] = Number(held(name)) + 1;
389
+ carried.add(name);
390
+ }
391
+ }
58
392
  }
59
- if (layout.revision !== undefined) {
60
- const name = dbName(layout.revision);
61
- if (tomb[name] !== undefined)
62
- item[name] = Number(tomb[name]) + 1;
393
+ // A packed field as the row stores it: read by its stored form, then packed. Only what was
394
+ // carried: the fields the caller gave are packed already.
395
+ const stored = entity._dispatchAttributes.filter((name) => carried.has(name));
396
+ if (stored.length > 0) {
397
+ const part = {};
398
+ for (const name of stored)
399
+ part[name] = held(name);
400
+ yield* entity._unpackFields(part, "create");
401
+ Object.assign(item, part);
402
+ yield* entity._packFields(item, "create", new Set(stored));
63
403
  }
64
- return Option.some({
65
- eq: { __edd_e__: `${entity.entityType}#tombstone`, __edd_removed__: tomb.__edd_removed__ },
66
- });
404
+ const inUse = rowTokenInUse(entity, resolveTtlAttributeName(table));
405
+ const read = inUse && Object.hasOwn(Item, ROW_TOKEN) ? Item[ROW_TOKEN] : undefined;
406
+ const term = asReadTerm(entity, Item, taken, inUse);
407
+ if (inUse && (rowTokened(entity) || read !== undefined)) {
408
+ // The projections whose bookkeeping the row holds: those this program doesn't define kept.
409
+ const known = new Map(layouts.map((layout) => [layoutTag(layout), layout]));
410
+ const writers = rowWriters(read).filter((tag) => {
411
+ const layout = known.get(tag);
412
+ return (layout === undefined ||
413
+ layout.roles.some(([field]) => {
414
+ const name = storedName(entity, field);
415
+ return carried.has(name) || Object.hasOwn(item, name);
416
+ }));
417
+ });
418
+ item[ROW_TOKEN] = yield* freshRowToken(writers);
419
+ }
420
+ return Option.some({ guard: tombstoneGuard(entity.entityType, tomb), term });
421
+ });
422
+ /** The guard naming a tombstone by its marker and removal stamp. */
423
+ const tombstoneGuard = (entityType, tomb) => ({
424
+ eq: { __edd_e__: `${entityType}#tombstone`, __edd_removed__: tomb.__edd_removed__ },
425
+ });
426
+ /**
427
+ * @internal Flatten `entity`'s sparse-map fields on `item` (stored names) into per-entry
428
+ * attributes, refusing a key it can't store with a `ValidationError` for `operation`. The
429
+ * transactional put and a projection's tombstone (on a copy) go through it, and `Entity.put`
430
+ * refuses through the same `_serializeSparseFields`, so each refuses the same key the same way,
431
+ * before sending anything.
432
+ */
433
+ export const serializeSparseOrFail = (entity, item, operation) => Effect.try({
434
+ try: () => entity._serializeSparseFields(item),
435
+ catch: (e) => new ValidationError({
436
+ entityType: entity.entityType,
437
+ operation,
438
+ cause: e instanceof Error ? e.message : String(e),
439
+ }),
67
440
  });
68
441
  /**
69
442
  * A projection tombstone (#154) of `entityType` — written at a removed row's
@@ -81,6 +454,48 @@ export const KEY_TEXT = "__edd_kt__";
81
454
  /** The read-model row an outbox item was written for: its key attributes' text. */
82
455
  export const OUTBOX_ROW_PK = "__edd_row_pk__";
83
456
  export const OUTBOX_ROW_SK = "__edd_row_sk__";
457
+ /**
458
+ * The effect an outbox item holds, and the read model it was written for (#237):
459
+ * `<read model tag>.<effect tag>` (`ProjectionEngine.outboxMark`), the tag of the read model's key
460
+ * template (`ProjectionEngine.readModelTag`) then a hash of the projection and the event. Written
461
+ * from 1.41.0 where its name is free (`outboxMarkInUse`); part of no key. Read models of one entity
462
+ * type share the outbox index's partition, and a key alone can't always say whose an item is
463
+ * (`[shop]` with `north#branch_b1` beside `[shop, branch]`): `outboxOwnership` reads it first. An
464
+ * item's `Put` replaces only the item of the same effect (`ProjectionEngine.writeRow`).
465
+ */
466
+ export const OUTBOX_READ_MODEL = "__edd_rm__";
467
+ /**
468
+ * @internal The attributes a read model's projections' outbox items hold under names something
469
+ * else decides (#237): each outbox's key attributes and its index's, and every key attribute of
470
+ * the table it is on (`tableKeyAttributes`: any item holding one is in that index).
471
+ */
472
+ const outboxItemNames = (entity) => {
473
+ const member = entity;
474
+ const names = new Set();
475
+ for (const outbox of member._projectionOutboxes ?? []) {
476
+ if (outbox.table === undefined) {
477
+ const primary = member.indexes?.primary;
478
+ if (primary !== undefined)
479
+ names.add(primary.pk.field).add(primary.sk.field);
480
+ }
481
+ else
482
+ names.add(outbox.pk).add(outbox.sk);
483
+ if (outbox.index !== undefined)
484
+ names.add(outbox.index.pk).add(outbox.index.sk);
485
+ for (const name of tableKeyAttributes(outbox.table?.Tag ?? member._tableTag) ?? []) {
486
+ names.add(name);
487
+ }
488
+ }
489
+ return names;
490
+ };
491
+ /**
492
+ * @internal Whether a read model's outbox items carry their mark (`OUTBOX_READ_MODEL`, #237): its
493
+ * name is free on them (`outboxItemNames`). The one decision, from the definitions: where an
494
+ * outbox's key or index attribute, or a key attribute of its table, is named `__edd_rm__`, the
495
+ * read model's items carry none, their `Put` no condition, and its drainers read no mark, as on
496
+ * 1.40.0.
497
+ */
498
+ export const outboxMarkInUse = (entity) => !outboxItemNames(entity).has(OUTBOX_READ_MODEL);
84
499
  /** A drainer's claim on an outbox item: its token, and the epoch millis it holds until. */
85
500
  export const OUTBOX_CLAIM = "__edd_claim__";
86
501
  export const OUTBOX_CLAIMED_UNTIL = "__edd_claimed_until__";
@@ -236,6 +651,11 @@ input, details) => {
236
651
  "immutable fields and the version counter. Compiling it as a Put would reset " +
237
652
  "them. Use put() or create() here, or run the upsert as its own operation."));
238
653
  }
654
+ if (opType === "put" && putKind === "insert") {
655
+ return Effect.fail(fail("insert", "insert is a PartiQL INSERT, and this request would send a PutItem, which a role " +
656
+ "limited to dynamodb:PartiQLInsert can't run. Use put() or create() here, or run " +
657
+ "the insert as its own operation."));
658
+ }
239
659
  // --- what a planned write cannot carry (EDD-9059 – EDD-9061) -------------
240
660
  if (opType === "update" && details?.updateState?.cascade !== undefined) {
241
661
  return Effect.fail(fail("[EDD-9059] cascade", "a cascade is a follow-up write to other entities after the update commits, so it " +
@@ -279,9 +699,7 @@ input, details) => {
279
699
  // stay missing and the primary key would compose around an `undefined`.
280
700
  if (opType === "put" && entity.generatedId != null) {
281
701
  const idField = entity.generatedId.field;
282
- const supplied = typeof input === "object" &&
283
- input !== null &&
284
- input[idField] != null;
702
+ const supplied = typeof input === "object" && input !== null && given(input, idField) != null;
285
703
  if (!supplied) {
286
704
  return Effect.fail(fail(`an omitted generated id ("${idField}")`, "generating one needs the SecureRandom service, which is not in scope here. Supply " +
287
705
  `"${idField}" on the input and this path writes it as given — only the ` +
@@ -317,34 +735,62 @@ export const resolveTableNames = (infos) => Effect.gen(function* () {
317
735
  * that composes an item's keys goes through this, so the failure is typed instead
318
736
  * of a defect. Any other throw stays a defect.
319
737
  */
320
- export const composeKeysOrFail = (entityType, operation, compose) => Effect.try({ try: compose, catch: (error) => error }).pipe(Effect.catch((error) => isZOrderValueError(error) || isKeyValueError(error) || isShardSourceError(error)
738
+ export const composeKeysOrFail = (entityType, operation, compose) => Effect.try({ try: compose, catch: (error) => error }).pipe(Effect.catch((error) => isRefusedValue(error)
321
739
  ? Effect.fail(new ValidationError({ entityType, operation, cause: error }))
322
740
  : Effect.die(error)));
323
741
  /**
324
- * Compose the primary key for an entity item.
742
+ * Marshal an item holding a caller's values. A value DynamoDB can't store (an
743
+ * empty set in a list, `NaN`, a number past `Number.MAX_SAFE_INTEGER`, …) fails with
744
+ * a `ValidationError` naming the field; `fieldOf` names a stored attribute by its
745
+ * model field. So does a value it composes into a key and can't place, as
746
+ * {@link composeKeysOrFail} says. Any other throw stays a defect.
325
747
  */
326
- export const composePrimaryKey = (entity, key) => {
748
+ export const marshalOrFail = (entityType, operation, marshal, options = {}) => Effect.try({ try: marshal, catch: (error) => error }).pipe(Effect.catch((error) => isUnstorableValue(error)
749
+ ? Effect.fail(new ValidationError({
750
+ entityType,
751
+ operation,
752
+ cause: error.refusal(options.outcome ?? "Nothing was written.", options.fieldOf),
753
+ }))
754
+ : isRefusedValue(error)
755
+ ? Effect.fail(new ValidationError({ entityType, operation, cause: error }))
756
+ : Effect.die(error)));
757
+ /** An entity item's primary key, from a record already in the composite key form. */
758
+ const primaryKeyOf = (entity, recordKeyForm) => {
327
759
  const primary = entity.indexes.primary;
328
760
  const schema = entity._schema;
329
- // The caller's key is a DOMAIN record (`{ takenAt: DateTime }`), and every
330
- // `KeyComposer` input must first go through the composite key-form rule or it
331
- // composes a different string than `Entity.put` wrote — a `DateEpochMs` PK
332
- // composite made `Batch.get` return null and `Batch.write(delete)` report
333
- // success against a row it never touched (#111).
334
- const recordKeyForm = entity._keyForm(key);
335
761
  return {
336
762
  [primary.pk.field]: KeyComposer.composePk(schema, entity.entityType, primary, recordKeyForm),
337
763
  [primary.sk.field]: KeyComposer.composeSk(schema, entity.entityType, 1, primary, recordKeyForm),
338
764
  };
339
765
  };
340
766
  /**
341
- * {@link composePrimaryKey}, failing with a `ValidationError` for `operation`
342
- * where a composite has no key text (`NaN`, `[EDD-9096]`) — the key-taking
343
- * multi-item ops (`Batch.get`, `Batch.write` deletes, `transactGet`,
344
- * `transactWrite` deletes and condition checks), as an entity's own `get` and
345
- * `delete` do.
767
+ * The primary key of the row a caller's DOMAIN key record names: the key
768
+ * `Entity.put` wrote for it (`_domainKeyForm`). The projection engine reads a
769
+ * read-model row, writes its tombstone and keys its outbox items through this,
770
+ * as the row itself is written by the read model's own `put`.
771
+ */
772
+ export const composePrimaryKey = (entity, key) =>
773
+ // Every `KeyComposer` input must first go through the composite key-form rule
774
+ // or it composes a different string than `Entity.put` wrote — a `DateEpochMs`
775
+ // PK composite made `Batch.get` return null and `Batch.write(delete)` report
776
+ // success against a row it never touched (#111).
777
+ primaryKeyOf(entity, entity._domainKeyForm(key));
778
+ /**
779
+ * The primary key of the item a caller's key names, failing with a
780
+ * `ValidationError` for `operation` where a composite has no key text (`NaN`,
781
+ * `[EDD-9096]`) — the key-taking multi-item ops (`Batch.get`, `Batch.write`
782
+ * deletes, `transactGet`, `transactWrite` deletes and condition checks), as an
783
+ * entity's own `get` and `delete` do.
784
+ *
785
+ * The caller's key is a DOMAIN record (`{ takenAt: DateTime }`), as an entity's
786
+ * own `get` takes it, so it goes through `_domainKeyForm`: the key `Entity.put`
787
+ * wrote for it, the key that `get` composes. For a codec `encode` takes on its
788
+ * own output (`x:` prepended), that is the key of the stored text: a domain
789
+ * value that is also such a text (`"x:MiX"`) is encoded first, as `put` does.
790
+ * It sends the key it sent on 1.39.0, whose `put` keyed the stored text encoded
791
+ * once more, so it found nothing there.
346
792
  */
347
- export const composePrimaryKeyOrFail = (entity, key, operation) => composeKeysOrFail(entity.entityType, operation, () => composePrimaryKey(entity, key));
793
+ export const composePrimaryKeyOrFail = (entity, key, operation) => composeKeysOrFail(entity.entityType, operation, () => primaryKeyOf(entity, entity._domainKeyForm(key)));
348
794
  /**
349
795
  * Validate input, compose all keys, and build a marshalled put item.
350
796
  *
@@ -358,64 +804,84 @@ export const composePrimaryKeyOrFail = (entity, key, operation) => composeKeysOr
358
804
  * `createdAt`. `Entity._planPut` needs them to derive uniqueness sentinels and
359
805
  * the retain snapshot from the same values that were written (#113), and to
360
806
  * keep a replaced item's `createdAt` (#133); re-deriving `now` there would risk
361
- * a skew between an item's `createdAt` and its snapshot's TTL.
807
+ * a skew between an item's `createdAt` and its snapshot's TTL. `options.createdAt`
808
+ * is the `createdAt` of a row being rewritten, which no input supplies.
362
809
  */
363
- export const validateAndBuildPutItem = (entity, input, operation) => Effect.gen(function* () {
810
+ export const validateAndBuildPutItem = (entity, input, operation, options) => Effect.gen(function* () {
364
811
  // Clock-backed time source resolved once per op; threaded into the sync
365
812
  // timestamp builder so the value is deterministic under `TestClock`.
366
813
  const now = yield* DateTime.now;
367
814
  const inputSchema = entity.schemas.inputSchema;
368
- // Encode → fall back to decode-then-encode (mirrors Entity.put).
815
+ // The input's stored form, decided as `Entity.put` decides it (`InputForm`).
369
816
  // Omitted decoding defaults are stored, exactly as `Entity.put` does.
370
817
  const filled = yield* entity._fillDecodingDefaults(input);
371
818
  const unsentineled = entity._unsentineledDefaults(input);
372
- const encoded = yield* Schema.encodeUnknownEffect(inputSchema)(filled).pipe(Effect.catch(() => Schema.decodeUnknownEffect(inputSchema)(filled).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(inputSchema)(decoded)))), Effect.mapError((cause) => new ValidationError({
819
+ const encoded = yield* encodeInput(inputSchema, filled).pipe(Effect.mapError(({ stored }) => new ValidationError({
373
820
  entityType: entity.entityType,
374
821
  operation,
375
- cause,
822
+ cause: stored,
376
823
  })));
824
+ yield* entity._refuseNotReadBack(encoded, operation);
377
825
  const item = { ...encoded };
378
826
  item.__edd_e__ = entity.entityType;
379
827
  if (unsentineled.length > 0)
380
828
  item[UNSENTINELED_DEFAULTS] = new Set(unsentineled);
829
+ // System fields (collision-aware), stamped before the keys are composed,
830
+ // as `Entity.put` does: an index may be composed from one. When a
831
+ // timestamp field collides with a model-declared field, the user may have
832
+ // supplied their own value (already encoded to wire by `Schema.encode`);
833
+ // else generate a wire primitive directly. They are placed in the item
834
+ // after the keys, where 1.39.0 placed them, so the request is the same.
835
+ const sf = entity.systemFields;
836
+ const createdAtSupplied = sf.createdAt !== null && ownValue(item, sf.createdAt) !== undefined;
837
+ const stamps = {};
838
+ if (sf.createdAt) {
839
+ if (options?.createdAt !== undefined) {
840
+ stamps[sf.createdAt] = generateTimestampPrimitive(options.createdAt, sf.createdAtEncoding);
841
+ }
842
+ else if (ownValue(item, sf.createdAt) === undefined) {
843
+ stamps[sf.createdAt] = generateTimestampPrimitive(now, sf.createdAtEncoding);
844
+ }
845
+ }
846
+ if (sf.updatedAt) {
847
+ if (ownValue(item, sf.updatedAt) === undefined) {
848
+ stamps[sf.updatedAt] = generateTimestampPrimitive(now, sf.updatedAtEncoding);
849
+ }
850
+ }
851
+ if (sf.version)
852
+ stamps[sf.version] = 1;
381
853
  // Same normalisation `Entity.put` applies. Without it a `BigIntFromString`
382
854
  // composite composed `txn_420` here and `txn_000…0420` there, so the two
383
855
  // APIs wrote two different rows for the same logical item and neither
384
856
  // accessor could read the transact-written one (#111).
385
- const keys = yield* composeKeysOrFail(entity.entityType, operation, () => KeyComposer.composeAllKeys(entity._schema, entity.entityType, 1, entity.indexes, entity._keyForm(encoded)));
386
- Object.assign(item, keys);
857
+ const composed = { ...encoded };
858
+ for (const field of [sf.createdAt, sf.updatedAt, sf.version]) {
859
+ if (field)
860
+ composed[field] = Object.hasOwn(stamps, field) ? stamps[field] : ownValue(item, field);
861
+ }
862
+ // The item is written whole: every key composed from it is its own, and an object composing
863
+ // `[object Object]` into one is refused where it's composed (`EDD-9162`).
864
+ const own = entity._ownSchema();
865
+ const composeKeys = (carried) => composeKeysOrFail(entity.entityType, operation, () => KeyComposer.composeAllKeys(own, entity.entityType, 1, entity.indexes, entity._keyForm({ ...composed, ...carried })));
866
+ Object.assign(item, yield* composeKeys({}));
387
867
  // A unique field's sentinel key is composed from its value later, on the
388
868
  // guarded path, after this item is marshalled. One with no key text
389
869
  // (`NaN`, `[EDD-9096]`) is refused here, as `Entity.put` refuses it, not
390
- // by the marshaller as a defect.
870
+ // by the marshaller as a defect; so is an object composing `[object Object]`
871
+ // into a sentinel composed.
391
872
  yield* composeKeysOrFail(entity.entityType, operation, () => {
392
873
  for (const def of Object.values(entity.unique ?? {})) {
393
874
  for (const field of resolveUniqueFields(def)) {
394
- const value = encoded[field];
875
+ const value = ownValue(encoded, field);
395
876
  if (value !== undefined && value !== null) {
396
877
  KeyComposer.compositeText(entity._schema, value);
397
878
  }
398
879
  }
399
880
  }
881
+ if (own !== entity._schema)
882
+ entity._composeUniqueSentinels(own, composed);
400
883
  });
401
- // System fields (collision-aware). When a timestamp field collides with a
402
- // model-declared field, the user may have supplied their own value
403
- // (already encoded to wire by `Schema.encode`); else generate a wire
404
- // primitive directly.
405
- const sf = entity.systemFields;
406
- const createdAtSupplied = sf.createdAt !== null && item[sf.createdAt] !== undefined;
407
- if (sf.createdAt) {
408
- if (item[sf.createdAt] === undefined) {
409
- item[sf.createdAt] = generateTimestampPrimitive(now, sf.createdAtEncoding);
410
- }
411
- }
412
- if (sf.updatedAt) {
413
- if (item[sf.updatedAt] === undefined) {
414
- item[sf.updatedAt] = generateTimestampPrimitive(now, sf.updatedAtEncoding);
415
- }
416
- }
417
- if (sf.version)
418
- item[sf.version] = 1;
884
+ Object.assign(item, stamps);
419
885
  if (entity._incarnationToken)
420
886
  item[INCARNATION_TOKEN] = yield* freshIncarnationToken;
421
887
  // Rename domain fields to their stored attribute names, in the same
@@ -425,20 +891,11 @@ export const validateAndBuildPutItem = (entity, input, operation) => Effect.gen(
425
891
  // `_planPut` derives the retain snapshot from this same item,
426
892
  // so the snapshot inherited the wrong shape too (#111).
427
893
  entity._renameToDynamo(item);
428
- // Flatten sparse-map fields into per-entry top-level attributes. Throws
429
- // on invalid keys; surface as ValidationError at the entity boundary.
430
- try {
431
- entity._serializeSparseFields(item);
432
- }
433
- catch (e) {
434
- return yield* new ValidationError({
435
- entityType: entity.entityType,
436
- operation,
437
- cause: e instanceof Error ? e.message : String(e),
438
- });
439
- }
894
+ // Flatten sparse-map fields into per-entry top-level attributes.
895
+ yield* serializeSparseOrFail(entity, item, operation);
440
896
  // Pack `storedAs: DynamoModel.Packed` fields, as `Entity.put` does (#147).
441
897
  yield* entity._packFields(item, operation);
442
- return { item, marshalled: toAttributeMap(item), now, createdAtSupplied };
898
+ const marshalled = yield* marshalOrFail(entity.entityType, operation, () => toAttributeMap(item), { fieldOf: entity._fieldOfAttribute });
899
+ return { item, marshalled, now, createdAtSupplied, composeKeys };
443
900
  });
444
901
  //# sourceMappingURL=TransactableOps.js.map