@effect-dynamodb/schema 1.39.0 → 1.40.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 (72) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +9 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +13 -0
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +5 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +61 -8
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +182 -5
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/KeyComposer.d.ts +157 -3
  16. package/dist/KeyComposer.d.ts.map +1 -1
  17. package/dist/KeyComposer.js +355 -9
  18. package/dist/KeyComposer.js.map +1 -1
  19. package/dist/internal/AggregateEdges.d.ts +3 -3
  20. package/dist/internal/AggregateSchemas.d.ts +181 -14
  21. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  22. package/dist/internal/AggregateSchemas.js +505 -45
  23. package/dist/internal/AggregateSchemas.js.map +1 -1
  24. package/dist/internal/AggregateTypes.d.ts +396 -36
  25. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  26. package/dist/internal/CompositeCodec.d.ts +274 -6
  27. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  28. package/dist/internal/CompositeCodec.js +829 -25
  29. package/dist/internal/CompositeCodec.js.map +1 -1
  30. package/dist/internal/EffectInstances.d.ts +81 -0
  31. package/dist/internal/EffectInstances.d.ts.map +1 -0
  32. package/dist/internal/EffectInstances.js +656 -0
  33. package/dist/internal/EffectInstances.js.map +1 -0
  34. package/dist/internal/EntitySchemas.d.ts +103 -27
  35. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  36. package/dist/internal/EntitySchemas.js +778 -131
  37. package/dist/internal/EntitySchemas.js.map +1 -1
  38. package/dist/internal/EntityTypes.d.ts +67 -11
  39. package/dist/internal/EntityTypes.d.ts.map +1 -1
  40. package/dist/internal/FailingAsBefore.d.ts +25 -0
  41. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  42. package/dist/internal/FailingAsBefore.js +42 -0
  43. package/dist/internal/FailingAsBefore.js.map +1 -0
  44. package/dist/internal/InstanceReads.d.ts +33 -0
  45. package/dist/internal/InstanceReads.d.ts.map +1 -0
  46. package/dist/internal/InstanceReads.js +165 -0
  47. package/dist/internal/InstanceReads.js.map +1 -0
  48. package/dist/internal/KeyText136.d.ts +4 -2
  49. package/dist/internal/KeyText136.d.ts.map +1 -1
  50. package/dist/internal/KeyText136.js +40 -9
  51. package/dist/internal/KeyText136.js.map +1 -1
  52. package/dist/internal/NumericKey.d.ts +21 -2
  53. package/dist/internal/NumericKey.d.ts.map +1 -1
  54. package/dist/internal/NumericKey.js +19 -1
  55. package/dist/internal/NumericKey.js.map +1 -1
  56. package/dist/internal/PackedCodec.d.ts +8 -1
  57. package/dist/internal/PackedCodec.d.ts.map +1 -1
  58. package/dist/internal/PackedCodec.js +49 -13
  59. package/dist/internal/PackedCodec.js.map +1 -1
  60. package/dist/internal/SchemaAccessors.d.ts +160 -1
  61. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  62. package/dist/internal/SchemaAccessors.js +994 -1
  63. package/dist/internal/SchemaAccessors.js.map +1 -1
  64. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  65. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  66. package/dist/internal/SharedKeyAttribute.js +127 -12
  67. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  68. package/dist/internal/SparseKey.d.ts +46 -0
  69. package/dist/internal/SparseKey.d.ts.map +1 -0
  70. package/dist/internal/SparseKey.js +69 -0
  71. package/dist/internal/SparseKey.js.map +1 -0
  72. package/package.json +1 -1
@@ -3,15 +3,159 @@
3
3
  *
4
4
  * Extracted from Aggregate.ts for decomposition. Not part of the public API.
5
5
  */
6
- import { Schema } from "effect";
7
- import { ConfiguredModelTag } from "../DynamoModel.js";
8
- import { extractArrayElement as extractArrayElementImpl, getSchemaFields as getSchemaFieldsImpl, isFieldOptional as isFieldOptionalImpl, } from "./SchemaAccessors.js";
9
- export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
6
+ import { Option, Schema, SchemaAST } from "effect";
7
+ import { ConfiguredModelTag, getIdentifierField } from "../DynamoModel.js";
8
+ import { bothKindsKeyRefusal, storedFieldAtPath } from "./CompositeCodec.js";
9
+ import { optionalField, resolveSystemFields } from "./EntitySchemas.js";
10
+ import { extractArrayElement as extractArrayElementImpl, extractKeyedValue, getSchemaFields as getSchemaFieldsImpl, isFieldOptional as isFieldOptionalImpl, } from "./SchemaAccessors.js";
11
+ // ---------------------------------------------------------------------------
12
+ // Timestamps
13
+ // ---------------------------------------------------------------------------
14
+ /**
15
+ * `timestamps` resolved over a value's fields, by the entity's rules: `Schema.optional` wraps the
16
+ * value that's read, a date is the library's, and any other field of that name is the caller's.
17
+ */
18
+ export const resolveAggregateStamps = (timestamps, fields, owner) => resolveSystemFields(timestamps, undefined, undefined, Object.fromEntries(Object.entries(fields ?? {}).map(([name, field]) => [
19
+ name,
20
+ optionalField(field)?.inner ?? field,
21
+ ])), {}, owner);
22
+ /**
23
+ * `[EDD-9121]`: a partition key the library would move on every write. An aggregate's rows all live
24
+ * under its partition key and a write only ever `Put`s rows under it, so the key would stop matching
25
+ * the value at the first update, and nothing could find the aggregate by what it holds.
26
+ */
27
+ export const refuseAggregateKeyOverMovingValue = (aggregate, timestamps, fields, composite) => {
28
+ const { updatedAt } = resolveAggregateStamps(timestamps, fields, `Aggregate "${aggregate}"`);
29
+ if (updatedAt !== null && composite.includes(updatedAt)) {
30
+ throw new Error(`[EDD-9121] Aggregate "${aggregate}": its partition key can't be composed from ` +
31
+ `"${updatedAt}". The library changes it on every write and a partition key never changes, ` +
32
+ `so the key would stop matching the value at the first update. Remove it from the ` +
33
+ `partition key, or use a field the library doesn't manage.`);
34
+ }
35
+ };
36
+ /**
37
+ * The fields of a `many` edge's ELEMENT, read off the parent model's field: the array's element
38
+ * (`players: Schema.Array(PlayerSheet)` → `PlayerSheet`'s), or a keyed collection's value, the
39
+ * elements of a custom `decompose` over it. `undefined` when the field says nothing about what its
40
+ * `decompose` returns, or the element exposes no fields (a scalar, or an opaque ref).
41
+ */
42
+ export const manyElementFields = (parentFields, edgeName) => {
43
+ const element = manyElementSchema(parentFields, edgeName);
44
+ return element === undefined ? undefined : getSchemaFields(element);
45
+ };
46
+ /**
47
+ * `[EDD-9121]`: a `many` edge's sort key the library would move on every write, on the root's edges
48
+ * and those of the sub-aggregates under it. Whose `updatedAt` it is, is the row's: a field of that
49
+ * name of another type is the caller's, and a root's turns the stamp off on every row.
50
+ */
51
+ export const refuseManySortKeysOverMovingValue = (aggregate, timestamps, rootFields, rootEdges) => {
52
+ const owner = `Aggregate "${aggregate}"`;
53
+ if (resolveAggregateStamps(timestamps, rootFields, owner).updatedAt === null)
54
+ return;
55
+ const walk = (fields, edges) => {
56
+ for (const [name, edge] of Object.entries(edges)) {
57
+ if (!("_tag" in edge))
58
+ continue;
59
+ if (edge._tag === "BoundSubAggregate") {
60
+ const sub = edge.aggregate;
61
+ walk(getSchemaFields(sub.schema), sub.edges);
62
+ }
63
+ else if (edge._tag === "ManyEdge") {
64
+ const entity = edge.entity;
65
+ const element = manyElementFields(fields, name) ??
66
+ (entity === undefined ? undefined : getSchemaFields(unwrapModel(entity.model)));
67
+ const { updatedAt } = resolveAggregateStamps(timestamps, element, owner);
68
+ if (updatedAt !== null && edge.sk?.composite.includes(updatedAt) === true) {
69
+ throw new Error(`[EDD-9121] Aggregate "${aggregate}": edge "${name}"'s sort key can't be composed ` +
70
+ `from "${updatedAt}". The library changes it on every write and a sort key never ` +
71
+ `changes, so the key would stop matching the value at the first update.`);
72
+ }
73
+ }
74
+ }
75
+ };
76
+ walk(rootFields, rootEdges);
77
+ };
78
+ /**
79
+ * `[EDD-9128]`: a key an aggregate composes from a field storing both numeric kinds
80
+ * (`bothKindsKeyRefusal`): its partition key, its collection and list keys, and a `many` edge's sort
81
+ * key, on the root's edges and those of the sub-aggregates under it. A sort-key composite that's a
82
+ * path into a value (`player.id`) is followed to the field a row stores there, through an optional,
83
+ * nullable, suspended or class value on the way (`storedFieldAtPath`): a value transformed on the
84
+ * way is judged by what it's stored as, so a struct storing a number at `n` and decoding it to a
85
+ * union of both kinds loads, and one storing either kind there doesn't.
86
+ */
87
+ export const refuseAggregateKeysOverBothKinds = (aggregate, rootFields, config, rootEdges) => {
88
+ const owner = `Aggregate "${aggregate}"`;
89
+ const refuse = (where, fields, composites) => {
90
+ for (const attr of composites) {
91
+ const field = storedFieldAtPath(fields, attr);
92
+ if (field === undefined)
93
+ continue;
94
+ const refused = bothKindsKeyRefusal(owner, where, attr, field);
95
+ if (refused !== undefined)
96
+ throw refused;
97
+ }
98
+ };
99
+ refuse("its partition key", rootFields, config.pk.composite);
100
+ refuse("its collection sort key", rootFields, config.collection?.sk?.composite ?? []);
101
+ if (config.list !== undefined) {
102
+ refuse("its list partition key", rootFields, config.list.pk.composite);
103
+ refuse("its list sort key", rootFields, config.list.sk.composite);
104
+ }
105
+ const walk = (fields, edges) => {
106
+ for (const [name, edge] of Object.entries(edges)) {
107
+ if (!("_tag" in edge))
108
+ continue;
109
+ if (edge._tag === "BoundSubAggregate") {
110
+ const sub = edge.aggregate;
111
+ walk(getSchemaFields(sub.schema), sub.edges);
112
+ }
113
+ else if (edge._tag === "ManyEdge") {
114
+ const entity = edge.entity;
115
+ const element = manyElementFields(fields, name) ??
116
+ (entity === undefined ? undefined : getSchemaFields(unwrapModel(entity.model)));
117
+ refuse(`edge "${name}"'s sort key`, element, edge.sk?.composite ?? []);
118
+ }
119
+ }
120
+ };
121
+ walk(rootFields, rootEdges);
122
+ };
123
+ /** The dates the rows of a value with `fields` declare, of those `timestamps` stamps. */
124
+ const managedDates = (stamps, fields) => {
125
+ const own = resolveAggregateStamps(stamps.config, fields, "Aggregate");
126
+ return new Set([own.createdAtCollision ? own.createdAt : null, own.updatedAtCollision ? own.updatedAt : null]
127
+ .filter((name) => name !== null)
128
+ .filter((name) => stamps.names.has(name)));
129
+ };
130
+ /** A managed date's input field: optional, supplied or not. */
131
+ const stampInput = (field) => Schema.optionalKey((optionalField(field)?.inner ?? field));
132
+ /** A row's value on the input: as the model has it, but for the dates the library stamps. */
133
+ const rowInput = (schema, stamps) => {
134
+ const fields = getSchemaFields(schema);
135
+ if (fields === undefined)
136
+ return schema;
137
+ const managed = managedDates(stamps, fields);
138
+ if (managed.size === 0)
139
+ return schema;
140
+ return Schema.Struct(Object.fromEntries(Object.entries(fields).map(([name, field]) => [
141
+ name,
142
+ managed.has(name) ? stampInput(field) : field,
143
+ ])));
144
+ };
145
+ export const deriveAggregateSchemas = (schema, edges, pkComposites, timestamps) => {
146
+ const own = resolveAggregateStamps(timestamps, getSchemaFields(schema), "Aggregate");
147
+ return deriveWithStamps(schema, edges, pkComposites, {
148
+ config: timestamps,
149
+ names: new Set([own.createdAt, own.updatedAt].filter((name) => name !== null)),
150
+ });
151
+ };
152
+ const deriveWithStamps = (schema, edges, pkComposites, stamps) => {
10
153
  const fields = getSchemaFields(schema);
11
154
  if (!fields) {
12
155
  return { inputSchema: schema, createSchema: schema, updateSchema: schema };
13
156
  }
14
157
  const omit = new Set(pkComposites);
158
+ const managed = managedDates(stamps, fields);
15
159
  const newFields = {};
16
160
  for (const [name, fieldSchema] of Object.entries(fields)) {
17
161
  if (omit.has(name))
@@ -19,13 +163,20 @@ export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
19
163
  const edge = edges[name];
20
164
  if (edge && "_tag" in edge) {
21
165
  const isOpt = isFieldOptional(fieldSchema);
22
- if (edge._tag === "RefEdge" || edge._tag === "OneEdge") {
23
- // RefEdge / OneEdge → ${name}Id: Schema.String
24
- newFields[`${name}Id`] = isOpt ? Schema.optionalKey(Schema.String) : Schema.String;
166
+ if ((edge._tag === "OneEdge" || edge._tag === "RefEdge") &&
167
+ (edge.entity === undefined || refKeyComposite(edge.entity) === undefined)) {
168
+ // Nothing to fetch by: no entity, or one no single id names (its key has two composites,
169
+ // or none). `create` takes the value, and refuses an id for it (`EDD-9129`).
170
+ const value = rowInput(optionalField(fieldSchema)?.inner ?? fieldSchema, stamps);
171
+ newFields[name] = isOpt ? Schema.optionalKey(value) : value;
172
+ }
173
+ else if (edge._tag === "RefEdge" || edge._tag === "OneEdge") {
174
+ const id = refIdInput(edge.entity);
175
+ newFields[`${name}Id`] = isOpt ? Schema.optionalKey(id) : id;
25
176
  }
26
177
  else if (edge._tag === "BoundSubAggregate") {
27
178
  const sub = edge.aggregate;
28
- const subSchemas = deriveAggregateSchemas(sub.schema, sub.edges, []);
179
+ const subSchemas = deriveWithStamps(sub.schema, sub.edges, [], stamps);
29
180
  newFields[name] = isOpt
30
181
  ? Schema.optionalKey(subSchemas.inputSchema)
31
182
  : subSchemas.inputSchema;
@@ -33,20 +184,20 @@ export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
33
184
  else if (edge._tag === "ManyEdge") {
34
185
  const manyEdge = edge;
35
186
  const fieldKey = manyEdge.inputField ?? name;
36
- const elemSchema = deriveElementInputSchema(fieldSchema, manyEdge.entity);
187
+ const elemSchema = deriveElementInputSchema(fieldSchema, manyEdge.entity, stamps);
37
188
  if (elemSchema) {
38
189
  newFields[fieldKey] = isOpt
39
190
  ? Schema.optionalKey(Schema.Array(elemSchema))
40
191
  : Schema.Array(elemSchema);
41
192
  }
42
193
  else {
43
- newFields[fieldKey] = fieldSchema;
194
+ newFields[fieldKey] = keyedInput(fieldSchema, stamps);
44
195
  }
45
196
  }
46
197
  continue;
47
198
  }
48
199
  // Regular field → keep as-is (toCodecJson applied at the end handles Date)
49
- newFields[name] = fieldSchema;
200
+ newFields[name] = managed.has(name) ? stampInput(fieldSchema) : fieldSchema;
50
201
  }
51
202
  const inputSchema = Schema.toCodecJson(Schema.Struct(newFields));
52
203
  // Update schema: all fields optional
@@ -62,6 +213,20 @@ export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
62
213
  // top-level `Aggregate.make` overload uses. `createSchema` aliases `inputSchema`.
63
214
  return { inputSchema, createSchema: inputSchema, updateSchema };
64
215
  };
216
+ /** A `Schema.Record` many edge's input (a custom `decompose`): its values' stamps are optional. */
217
+ const keyedInput = (fieldSchema, stamps) => {
218
+ const inner = optionalField(fieldSchema)?.inner ?? fieldSchema;
219
+ if (!SchemaAST.isObjects(inner.ast))
220
+ return fieldSchema;
221
+ const record = inner;
222
+ if (record.key === undefined || record.value === undefined)
223
+ return fieldSchema;
224
+ const value = rowInput(record.value, stamps);
225
+ if (value === record.value)
226
+ return fieldSchema;
227
+ const input = Schema.Record(record.key, value);
228
+ return isFieldOptional(fieldSchema) ? Schema.optionalKey(input) : input;
229
+ };
65
230
  /**
66
231
  * Check if a field schema represents an optional field.
67
232
  *
@@ -79,46 +244,339 @@ export const deriveEntityFieldName = (entity) => {
79
244
  const identifier = "identifier" in s && typeof s.identifier === "string" ? s.identifier : entity.entityType;
80
245
  return identifier.charAt(0).toLowerCase() + identifier.slice(1);
81
246
  };
247
+ // ---------------------------------------------------------------------------
248
+ // Ref ids: what one id of an edge's entity names, and which values hold one
249
+ // ---------------------------------------------------------------------------
250
+ /**
251
+ * The distinct attributes an entity's primary key is composed from, its partition key's first. An
252
+ * attribute in both halves (`pk: ["lineId"]`, `sk: ["lineId"]`) is one attribute: one value of it
253
+ * names one item.
254
+ */
255
+ export const refKeyComposites = (entity) => {
256
+ const primary = entity.indexes?.primary;
257
+ return [...new Set([...(primary?.pk?.composite ?? []), ...(primary?.sk?.composite ?? [])])];
258
+ };
259
+ /**
260
+ * The one attribute an id of `entity` is a value of: its primary key's only distinct composite.
261
+ * `undefined` for a key composed from more than one attribute, or none: no one id names one item.
262
+ */
263
+ export const refKeyComposite = (entity) => {
264
+ const composites = refKeyComposites(entity);
265
+ return composites.length === 1 ? composites[0] : undefined;
266
+ };
267
+ /**
268
+ * What a map the library builds or reads a definition from (a schema's fields) holds under `name`
269
+ * itself, `undefined` where it holds nothing there. Never a member every object inherits: a field
270
+ * or an edge named `constructor` or `toString` that the definition doesn't declare is not one.
271
+ */
272
+ const own = (record, name) => record !== undefined && Object.hasOwn(record, name) ? record[name] : undefined;
82
273
  /**
83
- * Derive input schema for a many-edge array element.
84
- * Extracts the element type from the field schema (which may be an Array
85
- * or optional(Array)). If the element IS the entity (matches the entity model),
86
- * transforms to Schema.String. Otherwise, finds the entity-derived field within
87
- * the element and transforms it.
274
+ * What a caller's payload gives under `name`, read as 1.39.0 read it (`payload[name]`): its own
275
+ * property, one its class gives it (a getter, a property of a prototype), or one a proxy answers
276
+ * for. A function is not given: 1.39.0 took a string for an id, a list for a `many` edge and an
277
+ * object for a sub-aggregate, never a function, so a method of the payload's class named like an id
278
+ * is no id, and neither is a member every object inherits (`constructor`, `toString`).
88
279
  */
89
- export const deriveElementInputSchema = (arrayFieldSchema, entity) => {
280
+ export const given = (payload, name) => {
281
+ const value = payload[name];
282
+ return typeof value === "function" ? undefined : value;
283
+ };
284
+ /**
285
+ * The model field an id of `entity` is a value of (its {@link refKeyComposite}), `undefined` when
286
+ * its key has no one composite or its model's fields can't be read.
287
+ */
288
+ export const refIdField = (entity) => {
289
+ const name = refKeyComposite(entity);
290
+ return name === undefined ? undefined : own(getSchemaFields(unwrapModel(entity.model)), name);
291
+ };
292
+ /**
293
+ * The schema `create` takes an id of `entity` as: its key composite's own field, so a number keyed
294
+ * entity takes a number. `Schema.String` when the field can't be read, as before.
295
+ */
296
+ const refIdInput = (entity) => refIdField(entity) ?? Schema.String;
297
+ const jsonCodecs = new WeakMap();
298
+ /** A field's JSON codec (`Schema.toCodecJson`), once per field; `null` where it has none. */
299
+ const jsonCodecOf = (field) => {
300
+ const cached = jsonCodecs.get(field);
301
+ if (cached !== undefined)
302
+ return cached;
303
+ let codec;
304
+ try {
305
+ codec = Schema.toCodecJson(field);
306
+ }
307
+ catch {
308
+ codec = null;
309
+ }
310
+ jsonCodecs.set(field, codec);
311
+ return codec;
312
+ };
313
+ /**
314
+ * An id given for `entity`, as a value of its key composite ({@link refIdField}): the value itself
315
+ * when it is one (`5` of a number, `5n` of a bigint, a `Date`), or what it decodes to from its JSON
316
+ * or stored form (`"5"` of a `NumberFromString` or a bigint, an ISO string of a date). `None` when it
317
+ * is neither: it names no item. Without a key field to read, a string is taken as given and nothing
318
+ * else, as it always was.
319
+ */
320
+ export const refIdValue = (entity, value) => {
321
+ const field = refIdField(entity);
322
+ if (field === undefined)
323
+ return typeof value === "string" ? Option.some(value) : Option.none();
324
+ const codec = field;
325
+ if (Schema.is(codec)(value))
326
+ return Option.some(value);
327
+ const json = jsonCodecOf(field);
328
+ const fromJson = json === null
329
+ ? Option.none()
330
+ : Schema.decodeUnknownOption(json)(value);
331
+ return Option.isSome(fromJson) ? fromJson : Schema.decodeUnknownOption(codec)(value);
332
+ };
333
+ // ---------------------------------------------------------------------------
334
+ // A `many` element's references: which values `create` fetches an entity for
335
+ // ---------------------------------------------------------------------------
336
+ /** What a copy of a schema node may change without changing what the node holds. */
337
+ const notWhatItHolds = new Set(["annotations", "checks", "context"]);
338
+ /**
339
+ * Whether two schema nodes are one schema: the same node, or a copy of it that changes only its
340
+ * annotations (`DynamoModel.ref`, `.annotate`), its checks (`.check`) or the optionality of the key
341
+ * it's under. Every other part is the same object. Decided from the definitions alone: a struct
342
+ * declared again with the same fields is another schema.
343
+ */
344
+ const isSameSchemaNode = (a, b) => {
345
+ if (a === b)
346
+ return true;
347
+ if (a._tag !== b._tag)
348
+ return false;
349
+ const held = (ast) => Object.keys(ast).filter((key) => !notWhatItHolds.has(key));
350
+ const keys = held(a);
351
+ return (keys.length === held(b).length &&
352
+ keys.every((key) => a[key] ===
353
+ b[key]));
354
+ };
355
+ /**
356
+ * Whether a schema is the entity's own model: the schema its definition declares (its
357
+ * `DynamoModel.configure` wrapper taken off), or a copy of it that changes only its annotations, its
358
+ * checks or its brand (`isSameSchemaNode`), compared by reference. An identifier is never identity:
359
+ * a class of the entity's identifier is another schema, as is a struct declared again with the
360
+ * entity's fields. Every question of whether a schema is the entity is asked of this.
361
+ */
362
+ export const isEntityModel = (schema, entity) => isSameSchemaNode(schema.ast, unwrapModel(entity.model).ast);
363
+ /**
364
+ * Whether a field's schema holds the entity's own model ({@link isEntityModel}), under
365
+ * `Schema.optional` / `Schema.optionalKey` at most. An `Option`, a `NullOr` or a `Result` of it holds
366
+ * something else: a record fetched for it is no value of the field.
367
+ */
368
+ const holdsEntityModel = (field, entity) => {
369
+ if (field === undefined)
370
+ return false;
371
+ const optional = optionalField(field);
372
+ if (optional?.union !== undefined)
373
+ return false;
374
+ return isEntityModel(optional?.inner ?? field, entity);
375
+ };
376
+ /**
377
+ * Whether a `many` element is the entity itself (`Array<Umpire>`): the entity's own model
378
+ * ({@link isEntityModel}). Its values are the entity whole, or an id.
379
+ */
380
+ export const isEntityElement = (element, entity) => element !== undefined && isEntityModel(element, entity);
381
+ /**
382
+ * The field of a `many` element that holds the entity, where the element's definition says so,
383
+ * `undefined` where it doesn't. All of these hold:
384
+ *
385
+ * 1. The element is a plain `Schema.Struct` or `Schema.Class`: one with fields of its own. A
386
+ * transformation, a union, a `suspend` or a declaration has none.
387
+ * 2. Its field of the entity's name (`deriveEntityFieldName`) holds the entity's own model
388
+ * (`holdsEntityModel`).
389
+ * 3. It doesn't declare `${field}Id` itself: a declared one is the element's own data.
390
+ *
391
+ * Such an element's input takes an id of the entity's key composite under `${field}Id`.
392
+ */
393
+ export const entityFieldOf = (element, entity) => {
394
+ const fields = element === undefined ? undefined : getSchemaFields(element);
395
+ if (fields === undefined)
396
+ return undefined;
397
+ const name = deriveEntityFieldName(entity);
398
+ if (Object.hasOwn(fields, `${name}Id`))
399
+ return undefined;
400
+ return holdsEntityModel(own(fields, name), entity) ? name : undefined;
401
+ };
402
+ /**
403
+ * Whether `create` fetches `entity` for `value`'s `${field}Id`, `value` a value of a definition
404
+ * declaring `fields` (`undefined` where it declares none: a union, a transformation): the parent
405
+ * model's, its `field` the edge's name, for a `one` or `ref` edge; a `many` element's, its `field`
406
+ * the entity's name (`deriveEntityFieldName`). One rule for every edge:
407
+ *
408
+ * 1. `null` and `undefined` give no id.
409
+ * 2. A string is fetched, exactly as on 1.39.0, whatever the definition declares: it replaces a
410
+ * record given whole in `field` with the one fetched, and a `${field}Id` the definition declares
411
+ * is taken out of the value, as 1.39.0 took it.
412
+ * 3. Any other id (a number, a bigint, a date: a value of the entity's key composite) is fetched only
413
+ * where the definition's `field` holds the entity's own model (`holdsEntityModel`), the definition
414
+ * doesn't declare `${field}Id`, which is then its own data, and `field` isn't given whole: a
415
+ * record given is never replaced or read again. 1.39.0 fetched none of these.
416
+ */
417
+ export const holdsRefId = (fields, field, entity, value) => {
418
+ const id = given(value, `${field}Id`);
419
+ if (id == null)
420
+ return false;
421
+ if (typeof id === "string")
422
+ return true;
423
+ return (fields !== undefined &&
424
+ !Object.hasOwn(fields, `${field}Id`) &&
425
+ holdsEntityModel(own(fields, field), entity) &&
426
+ given(value, field) == null);
427
+ };
428
+ /**
429
+ * Whether 1.39.0 fetched an element that is the entity by its own key `key` (`lineId` of a `Line`
430
+ * keyed by `lineId`) and completed. It fetched under the model's identifier (`id` without one), so
431
+ * only where that is the entity's one key composite; and it took the key out of the element given,
432
+ * so only where the element doesn't require it. Everywhere else it died composing the key, or
433
+ * refused the element without its key.
434
+ */
435
+ const fetchedByOwnKey139 = (fields, entity, key) => {
436
+ const declared = own(fields, key);
437
+ return (refKeyComposite(entity) === key &&
438
+ (getIdentifierField(entity.model)?.name ?? "id") === key &&
439
+ declared !== undefined &&
440
+ isFieldOptional(declared));
441
+ };
442
+ /**
443
+ * {@link holdsRefId} for a `many` element given as an object, of the element's schema. An element
444
+ * that is the entity ({@link isEntityElement}), given whole, holds no id in its own key: where the
445
+ * entity is keyed by `${field}Id` (`lineId` of a `Line`), that is the entity's own value, which
446
+ * 1.39.0 took for an id to fetch and failed on. It is left unfetched exactly where 1.39.0 failed:
447
+ * where 1.39.0 fetched it and completed ({@link fetchedByOwnKey139}), it is fetched.
448
+ */
449
+ export const elementHoldsRef = (element, entity, value) => {
450
+ const field = deriveEntityFieldName(entity);
451
+ const fields = element === undefined ? undefined : getSchemaFields(element);
452
+ if (isEntityElement(element, entity) &&
453
+ refKeyComposites(entity).includes(`${field}Id`) &&
454
+ !fetchedByOwnKey139(fields, entity, `${field}Id`)) {
455
+ return false;
456
+ }
457
+ return holdsRefId(fields, field, entity, value);
458
+ };
459
+ /**
460
+ * The element schema of a `many` edge, read off the parent model's field: the array's element, or a
461
+ * keyed collection's value. `undefined` when the field says nothing of it.
462
+ */
463
+ export const manyElementSchema = (parentFields, edgeName) => {
464
+ const field = own(parentFields, edgeName);
465
+ if (field === undefined)
466
+ return undefined;
467
+ return extractArrayElement(field) ?? extractKeyedValue(field);
468
+ };
469
+ /**
470
+ * Derive input schema for a many-edge array element, as `create` takes it, for an edge whose entity
471
+ * one id names:
472
+ *
473
+ * - **An element that is the entity** ({@link isEntityElement}): an id of the entity's key composite
474
+ * (`refIdInput`), or the entity whole.
475
+ * - **An element whose definition names the field holding the entity** ({@link entityFieldOf}): the
476
+ * element whole, `${field}Id` beside it or not, or with `${field}Id`, an id of the entity's key
477
+ * composite, in place of that field. Neither refuses the other's key: given both, both are kept,
478
+ * and `create` judges them as it judges a value given to it directly (`elementHoldsRef`).
479
+ * - **Any other element**, as on 1.39.0: the field of the entity's name, if it has one, taken as
480
+ * `${field}Id: Schema.String`. An element with no fields of its own (a union among them) is taken
481
+ * as declared.
482
+ *
483
+ * An entity no single id names is given whole, never by id (`EDD-9129`), so its elements are taken as
484
+ * declared. A date the library stamps is optional throughout.
485
+ */
486
+ export const deriveElementInputSchema = (arrayFieldSchema, entity, stamps) => {
90
487
  const elemSchema = extractArrayElement(arrayFieldSchema);
91
488
  if (!elemSchema)
92
489
  return undefined;
93
- const elemFields = getSchemaFields(elemSchema);
94
- // Check if the element itself IS the entity model (e.g., Array<Umpire>)
95
- if (entity && elemFields && isSchemaMatchingEntity(elemSchema, entity)) {
96
- // Element IS the entity → array of IDs (Schema.String)
97
- return Schema.String;
98
- }
99
- if (!elemFields)
100
- return elemSchema;
101
- // Element wraps entity + attributes — find the entity-derived field and transform it
102
- if (entity) {
103
- const entityFieldName = deriveEntityFieldName(entity);
104
- let hasChanges = false;
105
- const newFields = {};
106
- for (const [name, fSchema] of Object.entries(elemFields)) {
107
- if (name === entityFieldName) {
108
- // This field references the entity — transform to ${name}Id: Schema.String
109
- const isOpt = isFieldOptional(fSchema);
110
- newFields[`${name}Id`] = isOpt ? Schema.optionalKey(Schema.String) : Schema.String;
111
- hasChanges = true;
490
+ const fetched = entity !== undefined && refKeyComposite(entity) !== undefined ? entity : undefined;
491
+ if (fetched !== undefined && isEntityElement(elemSchema, fetched)) {
492
+ return Schema.Union([
493
+ refIdInput(fetched),
494
+ stampedElement(elemSchema, stamps),
495
+ ]);
496
+ }
497
+ const fields = getSchemaFields(elemSchema);
498
+ if (fields === undefined || fetched === undefined) {
499
+ return fields === undefined ? elemSchema : stampedElement(elemSchema, stamps);
500
+ }
501
+ const named = entityFieldOf(elemSchema, fetched);
502
+ if (named !== undefined) {
503
+ const own = stampedFields(fields, stamps);
504
+ const id = refIdInput(fetched);
505
+ const byId = {};
506
+ for (const [name, field] of Object.entries(own)) {
507
+ if (name === named) {
508
+ byId[`${name}Id`] = isFieldOptional(field) ? Schema.optionalKey(id) : id;
112
509
  }
113
510
  else {
114
- newFields[name] = fSchema;
511
+ byId[name] = field;
115
512
  }
116
513
  }
117
- if (!hasChanges)
118
- return elemSchema;
119
- return Schema.Struct(newFields);
514
+ return Schema.Union([
515
+ Schema.Struct({ ...own, [`${named}Id`]: Schema.optional(id) }),
516
+ Schema.Struct(byId),
517
+ ]);
120
518
  }
121
- return elemSchema;
519
+ return element139(elemSchema, fields, deriveEntityFieldName(fetched), stamps);
520
+ };
521
+ /** An element's fields, the dates the library stamps optional. */
522
+ const stampedFields = (fields, stamps) => {
523
+ const managed = stamps === undefined ? undefined : managedDates(stamps, fields);
524
+ return Object.fromEntries(Object.entries(fields).map(([name, field]) => [
525
+ name,
526
+ managed?.has(name) === true ? stampInput(field) : field,
527
+ ]));
528
+ };
529
+ /** An element as declared, the dates the library stamps optional: the element itself when none is. */
530
+ const stampedElement = (element, stamps) => {
531
+ const fields = getSchemaFields(element);
532
+ if (fields === undefined || stamps === undefined || managedDates(stamps, fields).size === 0) {
533
+ return element;
534
+ }
535
+ return Schema.Struct(stampedFields(fields, stamps));
536
+ };
537
+ /**
538
+ * An element as 1.39.0's input took it: its field of the entity's name, if it has one, as
539
+ * `${name}Id: Schema.String`, optional when the field is; the dates the library stamps optional.
540
+ * The element itself when nothing changes.
541
+ */
542
+ const element139 = (element, fields, entityFieldName, stamps) => {
543
+ const managed = stamps === undefined ? undefined : managedDates(stamps, fields);
544
+ let hasChanges = false;
545
+ const newFields = {};
546
+ for (const [name, field] of Object.entries(fields)) {
547
+ if (name === entityFieldName) {
548
+ newFields[`${name}Id`] = isFieldOptional(field)
549
+ ? Schema.optionalKey(Schema.String)
550
+ : Schema.String;
551
+ hasChanges = true;
552
+ }
553
+ else if (managed?.has(name) === true) {
554
+ newFields[name] = stampInput(field);
555
+ hasChanges = true;
556
+ }
557
+ else {
558
+ newFields[name] = field;
559
+ }
560
+ }
561
+ return hasChanges ? Schema.Struct(newFields) : element;
562
+ };
563
+ /**
564
+ * The paths of an aggregate's `many` edges, sub-aggregates included. The collection such a field is
565
+ * declared as is taken apart by `decompose` and put back by `assemble`, so it's never stored itself.
566
+ */
567
+ export const manyEdgePaths = (edges, at = "") => {
568
+ const paths = new Set();
569
+ for (const [name, edge] of Object.entries(edges ?? {})) {
570
+ const path = at === "" ? name : `${at}.${name}`;
571
+ const tagged = edge;
572
+ if (tagged._tag === "ManyEdge")
573
+ paths.add(path);
574
+ if (tagged._tag === "BoundSubAggregate") {
575
+ for (const nested of manyEdgePaths(tagged.aggregate?.edges, path))
576
+ paths.add(nested);
577
+ }
578
+ }
579
+ return paths;
122
580
  };
123
581
  /**
124
582
  * Unwrap a ConfiguredModel to get the raw Schema.Class model.
@@ -133,10 +591,12 @@ export const unwrapModel = (model) => {
133
591
  return model;
134
592
  };
135
593
  /**
136
- * Check if a schema matches an entity model (same Schema.Class identifier).
137
- * This is used to detect when an array element IS the entity (e.g., Array<Umpire>),
138
- * as opposed to wrapping the entity (e.g., Array<{ umpire: Umpire, role: string }>).
139
- * Unwraps ConfiguredModel if the entity uses DynamoModel.configure.
594
+ * Check if a schema has the same Schema.Class identifier as an entity model,
595
+ * unwrapping ConfiguredModel if the entity uses DynamoModel.configure.
596
+ *
597
+ * An identifier is not identity: two classes can share one. Nothing in the
598
+ * library decides by this any more; whether an element IS the entity (e.g.,
599
+ * Array<Umpire>) is decided by comparing the schema itself (`isEntityModel`).
140
600
  */
141
601
  export const isSchemaMatchingEntity = (schema, entity) => {
142
602
  const s = schema;