@effect-dynamodb/schema 1.40.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 (104) hide show
  1. package/dist/Aggregate.d.ts.map +1 -1
  2. package/dist/Aggregate.js +4 -1
  3. package/dist/Aggregate.js.map +1 -1
  4. package/dist/DynamoModel.d.ts +35 -7
  5. package/dist/DynamoModel.d.ts.map +1 -1
  6. package/dist/DynamoModel.js +34 -16
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +20 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +5 -3
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +82 -32
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/Errors.d.ts +61 -4
  16. package/dist/Errors.d.ts.map +1 -1
  17. package/dist/Errors.js +83 -6
  18. package/dist/Errors.js.map +1 -1
  19. package/dist/KeyComposer.d.ts +46 -9
  20. package/dist/KeyComposer.d.ts.map +1 -1
  21. package/dist/KeyComposer.js +148 -58
  22. package/dist/KeyComposer.js.map +1 -1
  23. package/dist/VectorIndex.d.ts.map +1 -1
  24. package/dist/VectorIndex.js +5 -4
  25. package/dist/VectorIndex.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/internal/AggregateSchemas.d.ts +131 -6
  31. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  32. package/dist/internal/AggregateSchemas.js +250 -31
  33. package/dist/internal/AggregateSchemas.js.map +1 -1
  34. package/dist/internal/CompositeCodec.d.ts +26 -4
  35. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  36. package/dist/internal/CompositeCodec.js +127 -25
  37. package/dist/internal/CompositeCodec.js.map +1 -1
  38. package/dist/internal/EffectInstances.d.ts +8 -2
  39. package/dist/internal/EffectInstances.d.ts.map +1 -1
  40. package/dist/internal/EffectInstances.js +33 -27
  41. package/dist/internal/EffectInstances.js.map +1 -1
  42. package/dist/internal/EntityPacked.d.ts.map +1 -1
  43. package/dist/internal/EntityPacked.js +5 -4
  44. package/dist/internal/EntityPacked.js.map +1 -1
  45. package/dist/internal/EntitySchemas.d.ts +136 -3
  46. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  47. package/dist/internal/EntitySchemas.js +836 -80
  48. package/dist/internal/EntitySchemas.js.map +1 -1
  49. package/dist/internal/EntityTypes.d.ts +53 -20
  50. package/dist/internal/EntityTypes.d.ts.map +1 -1
  51. package/dist/internal/InstanceReads.d.ts +7 -0
  52. package/dist/internal/InstanceReads.d.ts.map +1 -1
  53. package/dist/internal/InstanceReads.js +47 -29
  54. package/dist/internal/InstanceReads.js.map +1 -1
  55. package/dist/internal/KeyReadings.d.ts +30 -0
  56. package/dist/internal/KeyReadings.d.ts.map +1 -0
  57. package/dist/internal/KeyReadings.js +99 -0
  58. package/dist/internal/KeyReadings.js.map +1 -0
  59. package/dist/internal/KeyText136.d.ts.map +1 -1
  60. package/dist/internal/KeyText136.js +6 -4
  61. package/dist/internal/KeyText136.js.map +1 -1
  62. package/dist/internal/LostValues.d.ts +50 -0
  63. package/dist/internal/LostValues.d.ts.map +1 -0
  64. package/dist/internal/LostValues.js +465 -0
  65. package/dist/internal/LostValues.js.map +1 -0
  66. package/dist/internal/ObjectKeyText.d.ts +29 -0
  67. package/dist/internal/ObjectKeyText.d.ts.map +1 -0
  68. package/dist/internal/ObjectKeyText.js +50 -0
  69. package/dist/internal/ObjectKeyText.js.map +1 -0
  70. package/dist/internal/OwnNames.d.ts +205 -0
  71. package/dist/internal/OwnNames.d.ts.map +1 -0
  72. package/dist/internal/OwnNames.js +415 -0
  73. package/dist/internal/OwnNames.js.map +1 -0
  74. package/dist/internal/PackedCodec.d.ts +7 -8
  75. package/dist/internal/PackedCodec.d.ts.map +1 -1
  76. package/dist/internal/PackedCodec.js +81 -55
  77. package/dist/internal/PackedCodec.js.map +1 -1
  78. package/dist/internal/RestoredKeyText.d.ts +10 -0
  79. package/dist/internal/RestoredKeyText.d.ts.map +1 -0
  80. package/dist/internal/RestoredKeyText.js +50 -0
  81. package/dist/internal/RestoredKeyText.js.map +1 -0
  82. package/dist/internal/SchemaAccessors.d.ts +132 -12
  83. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  84. package/dist/internal/SchemaAccessors.js +779 -56
  85. package/dist/internal/SchemaAccessors.js.map +1 -1
  86. package/dist/internal/SchemaIssue.d.ts +21 -0
  87. package/dist/internal/SchemaIssue.d.ts.map +1 -0
  88. package/dist/internal/SchemaIssue.js +34 -0
  89. package/dist/internal/SchemaIssue.js.map +1 -0
  90. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  91. package/dist/internal/SharedKeyAttribute.js +2 -1
  92. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  93. package/dist/internal/StoredForm.d.ts +139 -0
  94. package/dist/internal/StoredForm.d.ts.map +1 -0
  95. package/dist/internal/StoredForm.js +503 -0
  96. package/dist/internal/StoredForm.js.map +1 -0
  97. package/dist/internal/ZOrderCurve.d.ts.map +1 -1
  98. package/dist/internal/ZOrderCurve.js +2 -1
  99. package/dist/internal/ZOrderCurve.js.map +1 -1
  100. package/dist/internal/ZoneKeyText.d.ts +55 -0
  101. package/dist/internal/ZoneKeyText.d.ts.map +1 -0
  102. package/dist/internal/ZoneKeyText.js +264 -0
  103. package/dist/internal/ZoneKeyText.js.map +1 -0
  104. package/package.json +4 -4
@@ -3,12 +3,15 @@
3
3
  *
4
4
  * Extracted from Entity.ts for decomposition. Not part of the public API.
5
5
  */
6
- import { DateTime, Effect, Option, Redacted, Schema, SchemaAST, SchemaGetter, SchemaIssue, } from "effect";
6
+ import { DateTime, Effect, Exit, Option, Redacted, Schema, SchemaAST, SchemaGetter, SchemaIssue, SchemaTransformation, } from "effect";
7
7
  import { getEncoding, isConfiguredModel, isHidden, } from "../DynamoModel.js";
8
8
  import { reviveMarshalledDateTime } from "./EffectInstances.js";
9
9
  import { readingInstances } from "./InstanceReads.js";
10
+ import { hasOwnName, ownValue, PROTO_ENTRY, setOwn } from "./OwnNames.js";
10
11
  import { BETA_DATE_MARKER, DATE_MARKER } from "./PackedCodec.js";
11
- import { absentStored, firstTypeParameterAst, getSchemaFields, holdsAbsentValue, holdsPlainBigint, holdsUndefined, isDecodingDefault, isSchemaLike, lackDecision, numericTypeWithStringEncoding, storedList, transformWireKind as transformWireKindImpl, } from "./SchemaAccessors.js";
12
+ import { absentStored, firstTypeParameterAst, getSchemaFields, holdsAbsentValue, holdsPlainBigint, holdsUndefined, isDecodingDefault, isSchemaLike, isSetDeclaration, keyRenamesOf, lackDecision, membersNamedExactly, numericTypeWithStringEncoding, ReadsAbsentAs, rowCanLack, storedList, transformWireKind as transformWireKindImpl, } from "./SchemaAccessors.js";
13
+ import { CANT_SAY, issueOf } from "./SchemaIssue.js";
14
+ import { zonedIsoText } from "./StoredForm.js";
12
15
  import { parseZonedIso } from "./ZonedIso.js";
13
16
  /**
14
17
  * Resolve the effective DynamoEncoding for a model-declared field, applying
@@ -37,9 +40,9 @@ export const resolveFieldEncoding = (fieldSchema, override) => {
37
40
  export const buildFieldEncodings = (modelFields, configuredAttributes) => {
38
41
  const encodings = {};
39
42
  for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
40
- const encoding = resolveFieldEncoding(fieldSchema, configuredAttributes[fieldName]?.encoding);
43
+ const encoding = resolveFieldEncoding(fieldSchema, ownValue(configuredAttributes, fieldName)?.encoding);
41
44
  if (encoding)
42
- encodings[fieldName] = encoding;
45
+ setOwn(encodings, fieldName, encoding);
43
46
  }
44
47
  return encodings;
45
48
  };
@@ -138,7 +141,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
138
141
  // This preserves existing patterns where users declare `createdAt`
139
142
  // as a plain string composite.
140
143
  let createdAtCollision = false;
141
- if (createdAt && createdAt in modelFields) {
144
+ if (createdAt && hasOwnName(modelFields, createdAt)) {
142
145
  const modelEncoding = resolveFieldEncoding(modelFields[createdAt], configuredAttributes[createdAt]?.encoding);
143
146
  if (modelEncoding) {
144
147
  createdAtEncoding = modelEncoding;
@@ -151,7 +154,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
151
154
  }
152
155
  }
153
156
  let updatedAtCollision = false;
154
- if (updatedAt && updatedAt in modelFields) {
157
+ if (updatedAt && hasOwnName(modelFields, updatedAt)) {
155
158
  const modelEncoding = resolveFieldEncoding(modelFields[updatedAt], configuredAttributes[updatedAt]?.encoding);
156
159
  if (modelEncoding) {
157
160
  updatedAtEncoding = modelEncoding;
@@ -162,7 +165,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
162
165
  updatedAtEncoding = null;
163
166
  }
164
167
  }
165
- const versionCollision = !!(version && version in modelFields);
168
+ const versionCollision = !!(version && hasOwnName(modelFields, version));
166
169
  return {
167
170
  createdAt,
168
171
  createdAtEncoding,
@@ -415,7 +418,7 @@ const toWirePrimitive = (input, encoding) => {
415
418
  switch (encoding.storage) {
416
419
  case "string":
417
420
  if (encoding.domain === "DateTime.Zoned" && zoned)
418
- return DateTime.formatIsoZoned(zoned);
421
+ return zonedIsoText(zoned);
419
422
  return new Date(epochMs).toISOString();
420
423
  case "epochMs":
421
424
  return epochMs;
@@ -1332,6 +1335,61 @@ const absentAsDeclared = (schema, withUndefined) => {
1332
1335
  ? Effect.succeed(input)
1333
1336
  : read({}).pipe(Effect.map(({ field }) => Option.some(field)), Effect.mapError((error) => error.issue)));
1334
1337
  };
1338
+ /** `undefined`, or a set holding nothing once `undefined` is removed: no attribute is stored. */
1339
+ const storesNothing = (value) => value === undefined ||
1340
+ (value instanceof Set && [...value].every((element) => element === undefined));
1341
+ /**
1342
+ * The annotation marking a field {@link protoAbsent} made: an annotation, not identity, since the
1343
+ * modules reading it may be loaded twice (the package's source beside its build).
1344
+ */
1345
+ const PROTO_ABSENT = Symbol.for("@effect-dynamodb/schema/ProtoAbsent");
1346
+ /** Whether `field` is one {@link protoAbsent} made. */
1347
+ export const isProtoAbsent = (field) => {
1348
+ const ast = field?.ast;
1349
+ return ast?.annotations?.[PROTO_ABSENT] === true;
1350
+ };
1351
+ /**
1352
+ * A field named `__proto__`, stored under that name, of a struct the library builds over the
1353
+ * model's (#239). 1.40.0 built each such struct by assignment, `fields[name] = schema`, and
1354
+ * assigning `__proto__` set the map's prototype instead: the field wasn't in the struct. A payload
1355
+ * leaving it out was taken, and one giving it lost the value, which the parser dropped. Here a
1356
+ * payload leaving it out, or giving a value that stores nothing (`undefined`, a `None` encoded as
1357
+ * `undefined`, a set holding nothing), is read as 1.40.0 read it: the field isn't in what the struct
1358
+ * makes. A value that stores something is refused (`EDD-9165`), since no write can store it and no
1359
+ * read can return it. What a value stores is what the field, as declared, makes of it on the way to
1360
+ * storage: encoded, or as it is where it's already in its stored form.
1361
+ */
1362
+ const protoAbsent = (field) => {
1363
+ const holder = Schema.Struct({ v: field });
1364
+ const decode = Schema.decodeUnknownExit(holder);
1365
+ const encode = Schema.encodeUnknownExit(holder);
1366
+ /** The value as stored, `undefined` for none; the value as given where the field takes neither. */
1367
+ const stored = (value, encoding) => {
1368
+ const asIs = () => Exit.isSuccess(decode({ v: value })) ? Exit.succeed({ v: value }) : undefined;
1369
+ const toStored = () => {
1370
+ const encoded = encode({ v: value });
1371
+ return Exit.isSuccess(encoded) ? encoded : undefined;
1372
+ };
1373
+ for (const attempt of encoding ? [toStored, asIs] : [asIs, toStored]) {
1374
+ const held = attempt();
1375
+ if (held !== undefined && Exit.isSuccess(held)) {
1376
+ return Object.hasOwn(held.value, "v") ? held.value.v : undefined;
1377
+ }
1378
+ }
1379
+ return value;
1380
+ };
1381
+ const judge = (encoding) => SchemaGetter.transformOptionalEffect((given) => Option.isNone(given) ||
1382
+ storesNothing(given.value) ||
1383
+ storesNothing(stored(given.value, encoding))
1384
+ ? Effect.succeed(Option.none())
1385
+ : Effect.fail(new SchemaIssue.InvalidValue({ message: `${PROTO_ENTRY} [EDD-9165]` }, Option.some(given.value))));
1386
+ return Schema.optionalKey(Schema.Unknown.pipe(Schema.decodeTo(Schema.Unknown.annotate({ [PROTO_ABSENT]: true }), new SchemaTransformation.Transformation(judge(false), judge(true)))));
1387
+ };
1388
+ /**
1389
+ * `field` under `name`: where that's `__proto__`, stored so, the field {@link protoAbsent} makes of
1390
+ * the one the model `declared`, whose encoding is the stored form.
1391
+ */
1392
+ const fieldNamed = (name, field, declared, storedAsProto = true) => name === "__proto__" && storedAsProto && !isProtoAbsent(field) ? protoAbsent(declared) : field;
1335
1393
  /**
1336
1394
  * The field, reading an absent attribute as the value it stands for (`absentStored`), which is what
1337
1395
  * its `declared` schema says, if the field is that schema read some other way.
@@ -1340,7 +1398,10 @@ const readingAbsent = (field, declared = field) => {
1340
1398
  const reading = absentStored(declared);
1341
1399
  if (reading === undefined)
1342
1400
  return field;
1343
- return field.pipe(Schema.withDecodingDefaultKey(Effect.succeed(reading.stored)));
1401
+ // A stored value is read as `field` alone (`ReadsAbsentAs`): the default runs where none is.
1402
+ return field
1403
+ .pipe(Schema.withDecodingDefaultKey(Effect.succeed(reading.stored)))
1404
+ .annotate({ [ReadsAbsentAs]: field.ast });
1344
1405
  };
1345
1406
  /** Whether a struct field anywhere in the schema reads an absent attribute as a value. */
1346
1407
  const holdsAbsentRead = (schema) => {
@@ -1416,6 +1477,10 @@ const refusesUndefinedPositions = (schema, opts) => opts?.enforceChecks === true
1416
1477
  const needsDeepSubstitution = (schema, opts) => {
1417
1478
  if (schema == null || schema.ast == null)
1418
1479
  return false;
1480
+ // A ref held as less than its class (`refHeldTarget`) is another schema than the field it
1481
+ // re-points, whatever its leaves.
1482
+ if (heldStructs.has(schema))
1483
+ return true;
1419
1484
  if (opts?.undefinedPositionsOnly)
1420
1485
  return holdsUndefinedPosition(schema);
1421
1486
  if (opts?.absentReads === "only")
@@ -1766,21 +1831,26 @@ export const substituteSchemaDeep = (schema, opts) => {
1766
1831
  // by the recursion (and class instance identity is preserved).
1767
1832
  const fields = schemaFieldsOf(schema);
1768
1833
  if (fields) {
1834
+ // A field named `__proto__` is one 1.40.0's rebuilt struct didn't hold (`protoAbsent`).
1769
1835
  const subFields = {};
1770
1836
  for (const [name, field] of Object.entries(fields)) {
1771
1837
  if (opts?.skipTopLevel?.has(name) === true) {
1772
- subFields[name] = field;
1838
+ setOwn(subFields, name, fieldNamed(name, field, field));
1773
1839
  continue;
1774
1840
  }
1775
1841
  const refTarget = opts?.resolveRef?.(name, field);
1776
1842
  if (refTarget !== undefined) {
1777
1843
  const fieldOpt = optionalField(field);
1778
1844
  const sub = substituteSchemaDeep(refTarget, atField(deeper, opts, name));
1779
- subFields[name] = fieldOpt ? fieldOpt.rewrap(sub) : sub;
1845
+ setOwn(subFields, name, fieldNamed(name, fieldOpt ? fieldOpt.rewrap(sub) : sub, field));
1780
1846
  }
1781
1847
  else {
1782
1848
  const sub = substituteSchemaDeep(field, atField(deeper, opts, name));
1783
- subFields[name] = opts?.absentReads ? readingAbsent(sub) : sub;
1849
+ setOwn(subFields, name, name === "__proto__"
1850
+ ? fieldNamed(name, sub, field)
1851
+ : opts?.absentReads
1852
+ ? readingAbsent(sub)
1853
+ : sub);
1784
1854
  }
1785
1855
  }
1786
1856
  const plainStruct = Schema.Struct(subFields);
@@ -2036,6 +2106,7 @@ export const writingTuplePositions = (schema) => substituteSchemaDeep(schema, {
2036
2106
  */
2037
2107
  export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2038
2108
  const out = {};
2109
+ const storedAsProto = options?.protoRenamed !== true;
2039
2110
  const deep = {
2040
2111
  ...(options?.legacyReads ? { legacyReads: true } : {}),
2041
2112
  ...(options?.enforceChecks ? { enforceChecks: true } : {}),
@@ -2047,18 +2118,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2047
2118
  // tolerant date transform so the encode pipeline produces the right
2048
2119
  // wire primitive.
2049
2120
  if (isSelfDateSchema(schema)) {
2050
- const enc = fieldEncodings[name];
2121
+ const enc = ownValue(fieldEncodings, name);
2051
2122
  if (enc) {
2052
- out[name] = buildDateTransform(enc);
2123
+ setOwn(out, name, fieldNamed(name, buildDateTransform(enc), schema, storedAsProto));
2053
2124
  continue;
2054
2125
  }
2055
2126
  }
2056
2127
  // …also beneath a decoding default, which is kept on top (#133).
2057
2128
  const defaulted = decodingDefaultField(schema);
2058
2129
  if (defaulted !== undefined && isSelfDateSchema(defaulted.inner)) {
2059
- const enc = fieldEncodings[name];
2130
+ const enc = ownValue(fieldEncodings, name);
2060
2131
  if (enc) {
2061
- out[name] = defaulted.rewrap(buildDateTransform(enc));
2132
+ setOwn(out, name, fieldNamed(name, defaulted.rewrap(buildDateTransform(enc)), schema, storedAsProto));
2062
2133
  continue;
2063
2134
  }
2064
2135
  }
@@ -2067,7 +2138,7 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2067
2138
  // transform so the round-trip works for storage.
2068
2139
  const redactedInner = tryGetRedactedInner(schema);
2069
2140
  if (redactedInner !== undefined) {
2070
- out[name] = buildRedactedSubstitute(schema, redactedInner);
2141
+ setOwn(out, name, fieldNamed(name, buildRedactedSubstitute(schema, redactedInner), schema, storedAsProto));
2071
2142
  continue;
2072
2143
  }
2073
2144
  // 3. Default: recurse for nested substitution. Pattern B transforms
@@ -2079,16 +2150,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2079
2150
  // identity, and returns the schema unchanged when nothing nested needs it.
2080
2151
  // A configured storage override on a UNION field (`NullOr(DateTimeUtc)`)
2081
2152
  // is applied to the union's self-date member (#133).
2082
- const unionOverride = unionDateOverride(name, schema, fieldEncodings[name]);
2083
- out[name] = substituteSchemaDeep(schema, {
2153
+ const unionOverride = unionDateOverride(name, schema, ownValue(fieldEncodings, name));
2154
+ setOwn(out, name, fieldNamed(name, substituteSchemaDeep(schema, {
2084
2155
  ...deep,
2085
2156
  path: [name],
2086
2157
  ...(unionOverride === undefined ? {} : { unionDateOverride: unionOverride }),
2087
- });
2158
+ }), schema, storedAsProto));
2088
2159
  }
2089
2160
  if (options?.absentReads) {
2090
- for (const [name, field] of Object.entries(out))
2091
- out[name] = readingAbsent(field);
2161
+ for (const [name, field] of Object.entries(out)) {
2162
+ if (!isProtoAbsent(field))
2163
+ setOwn(out, name, readingAbsent(field));
2164
+ }
2092
2165
  }
2093
2166
  return out;
2094
2167
  };
@@ -2149,7 +2222,7 @@ export const validateNoTransformOverride = (modelFields, configuredAttributes) =
2149
2222
  if (!isDateTransform(schema))
2150
2223
  continue;
2151
2224
  // 1. ConfiguredModel.storedAs override?
2152
- const configOverride = configuredAttributes[name]?.encoding;
2225
+ const configOverride = ownValue(configuredAttributes, name)?.encoding;
2153
2226
  if (configOverride !== undefined) {
2154
2227
  throw new Error(conflictMessage(name));
2155
2228
  }
@@ -2191,7 +2264,52 @@ export const storedAsOverTransform = (schema) => {
2191
2264
  * leaf `Link.to` AST.
2192
2265
  */
2193
2266
  const transformWireKind = (schema) => transformWireKindImpl(schema);
2194
- export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined) => {
2267
+ /**
2268
+ * @internal The `DynamoModel.Hidden` fields of a model: a read in "model" or "record" mode leaves
2269
+ * them out, of the entity's own items and of a ref to it ({@link refHeldSchema}).
2270
+ */
2271
+ export const hiddenFieldNamesOf = (fields) => new Set(Object.keys(fields).filter((name) => isHidden(fields[name])));
2272
+ /** The targets {@link refHeldTarget} decided, each once. */
2273
+ const refHeldTargets = new WeakMap();
2274
+ /** The schemas {@link refHeldTarget} built: a target's fields without its hidden ones. */
2275
+ const heldStructs = new WeakSet();
2276
+ /**
2277
+ * @internal What a ref to an entity of model `target` holds (#241), the one decision every ref
2278
+ * position takes (an entity's `refs`, an aggregate's edges and the refs nested in their entities):
2279
+ * what a read of that entity returns, which put-time hydration and a cascade store, both through
2280
+ * `refDataOf` (the entity's own read schema encoding the item it read). A read leaves out the
2281
+ * target's `DynamoModel.Hidden` fields ({@link hiddenFieldNamesOf}), so the stored ref holds none
2282
+ * of them. Where a hidden field read absent fails, as a read decodes it (`Missing key`), the ref is
2283
+ * the target's other fields, a plain object as the entity's own read decodes it: up to 1.40.0 it
2284
+ * was the whole target, so the referencing row failed every read, after its write. Every other
2285
+ * target is held as declared, a class read back as its instance, as up to 1.40.0: one whose hidden
2286
+ * fields are optional, or read absent as a value (`Schema.Unknown`, `Schema.Any`,
2287
+ * `Schema.UndefinedOr`, a decoding default).
2288
+ */
2289
+ export const refHeldTarget = (target) => {
2290
+ const decided = refHeldTargets.get(target);
2291
+ if (decided !== undefined)
2292
+ return decided;
2293
+ const fields = getSchemaFields(target);
2294
+ const hidden = fields === undefined ? new Set() : hiddenFieldNamesOf(fields);
2295
+ // A hidden field read absent, as a read of the referencing row decodes it.
2296
+ const failsAbsent = (name) => Option.isNone(Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [name]: fields[name] }), {
2297
+ legacyReads: true,
2298
+ absentReads: true,
2299
+ }))({}));
2300
+ const held = fields !== undefined && [...hidden].some(failsAbsent)
2301
+ ? Schema.Struct(Object.fromEntries(Object.entries(fields).filter(([name]) => !hidden.has(name))))
2302
+ : target;
2303
+ if (held !== target)
2304
+ heldStructs.add(held);
2305
+ refHeldTargets.set(target, held);
2306
+ return held;
2307
+ };
2308
+ /** @internal {@link refHeldTarget}, substituted as a read or a write takes it (`options`). */
2309
+ export const refHeldSchema = (target, options) => substituteSchemaDeep(refHeldTarget(target), options);
2310
+ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined,
2311
+ /** The field `__proto__` is stored under another attribute: see `substituteSchemas`. */
2312
+ protoRenamed = false) => {
2195
2313
  // --- Substitute model fields ---
2196
2314
  // Self date schemas (with effective encoding) are replaced with bidirectional
2197
2315
  // transforms that produce the configured wire primitive. RedactedFromValue
@@ -2200,7 +2318,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2200
2318
  // transform IS the wire format and we never override it.
2201
2319
  // WRITE schemas (input / create / update / key) enforce the container checks
2202
2320
  // the substitution rebuilds; the READ schemas below do not (#133).
2203
- const fields = substituteSchemas(modelFields, fieldEncodings, { enforceChecks: true });
2321
+ const fields = substituteSchemas(modelFields, fieldEncodings, {
2322
+ enforceChecks: true,
2323
+ protoRenamed,
2324
+ });
2204
2325
  // READ schemas (model / record / item / deleted / history decode) also take
2205
2326
  // the domain-form values earlier releases left on transform fields (#133),
2206
2327
  // and read an absent attribute as the value it stands for (`absentStored`).
@@ -2209,6 +2330,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2209
2330
  const readFields = substituteSchemas(modelFields, fieldEncodings, {
2210
2331
  legacyReads: true,
2211
2332
  absentReads: true,
2333
+ protoRenamed,
2212
2334
  });
2213
2335
  // Ref fields carry the `DynamoModel.ref` annotation (an opaque Declaration that
2214
2336
  // hides the target's fields), so `substituteSchemaDeep` above can't see into
@@ -2218,22 +2340,28 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2218
2340
  // only model/record/item schemas — input/create/update replace refs with IDs.
2219
2341
  for (const ref of resolvedRefs) {
2220
2342
  const targetModel = ref.refEntity?.model;
2221
- if (!targetModel || !(ref.fieldName in fields))
2343
+ if (!targetModel || !hasOwnName(fields, ref.fieldName))
2222
2344
  continue;
2223
2345
  const resolved = isConfiguredModel(targetModel)
2224
2346
  ? targetModel.model
2225
2347
  : targetModel;
2226
- fields[ref.fieldName] = substituteSchemaDeep(resolved, { enforceChecks: true });
2227
- readFields[ref.fieldName] = substituteSchemaDeep(resolved, {
2348
+ // As optional as the model declares it (#241): a row an optional ref was left out of, or
2349
+ // removed from, reads without it. Up to 1.40.0 the target replaced the declaration whole.
2350
+ const optional = optionalField(ownValue(modelFields, ref.fieldName));
2351
+ const asDeclared = (target) => optional === undefined ? target : optional.rewrap(target);
2352
+ // What a read of the target returns (`refHeldSchema`): its required hidden fields left out.
2353
+ setOwn(fields, ref.fieldName, asDeclared(refHeldSchema(resolved, { enforceChecks: true })));
2354
+ setOwn(readFields, ref.fieldName, asDeclared(refHeldSchema(resolved, {
2228
2355
  legacyReads: true,
2229
2356
  absentReads: true,
2230
- });
2357
+ })));
2231
2358
  }
2232
2359
  // Each of Effect's look-alike declarations (a `BigDecimal`, a `Duration`, an address, a date in
2233
2360
  // an `Option`, ...) reads back as a real instance, not the map DynamoDB hands back for it. A field
2234
2361
  // holding none is the same schema it was. Encoding through one is as it was.
2235
2362
  for (const [name, field] of Object.entries(readFields)) {
2236
- readFields[name] = readingInstances(field);
2363
+ if (!isProtoAbsent(field))
2364
+ setOwn(readFields, name, readingInstances(field));
2237
2365
  }
2238
2366
  // --- Model Schema: pure model fields (decode of stored items in "model" mode) ---
2239
2367
  const modelSchema = Schema.Struct(readFields);
@@ -2244,19 +2372,19 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2244
2372
  // already in `fields` and we don't add a system-schema entry.
2245
2373
  const systemSchemaFields = {};
2246
2374
  if (systemFields.createdAt && !systemFields.createdAtCollision) {
2247
- systemSchemaFields[systemFields.createdAt] = systemFields.createdAtEncoding
2375
+ setOwn(systemSchemaFields, systemFields.createdAt, systemFields.createdAtEncoding
2248
2376
  ? buildDateTransform(systemFields.createdAtEncoding)
2249
- : Schema.DateTimeUtcFromString;
2377
+ : Schema.DateTimeUtcFromString);
2250
2378
  }
2251
2379
  if (systemFields.updatedAt && !systemFields.updatedAtCollision) {
2252
- systemSchemaFields[systemFields.updatedAt] = systemFields.updatedAtEncoding
2380
+ setOwn(systemSchemaFields, systemFields.updatedAt, systemFields.updatedAtEncoding
2253
2381
  ? buildDateTransform(systemFields.updatedAtEncoding)
2254
- : Schema.DateTimeUtcFromString;
2382
+ : Schema.DateTimeUtcFromString);
2255
2383
  }
2256
2384
  if (systemFields.version && !systemFields.versionCollision) {
2257
2385
  // An item written before the entity was `versioned` has no version: it
2258
2386
  // reads as version 0 — real versions start at 1 (#133).
2259
- systemSchemaFields[systemFields.version] = Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0)));
2387
+ setOwn(systemSchemaFields, systemFields.version, Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0))));
2260
2388
  }
2261
2389
  const recordSchema = Schema.Struct({
2262
2390
  ...readFields,
@@ -2296,6 +2424,14 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2296
2424
  };
2297
2425
  // --- Input Schema: ref-aware (swap ref fields for ID fields when refs present) ---
2298
2426
  const refFieldSet = new Set(resolvedRefs.map((r) => r.fieldName));
2427
+ // A ref's id is taken as the model takes the ref (#241): required where it's required, and left
2428
+ // out (`Schema.optionalKey`) or `undefined` too (`Schema.optional`) where the model declares the
2429
+ // ref optional, which then stores no ref. Up to 1.40.0 the id was always required.
2430
+ const refIdInput = (ref) => {
2431
+ const declared = modelFields[ref.fieldName];
2432
+ const optional = declared === undefined ? undefined : optionalField(declared);
2433
+ return optional === undefined ? ref.keySchema : optional.rewrap(ref.keySchema);
2434
+ };
2299
2435
  const buildInputFieldsAcc = () => {
2300
2436
  const acc = {};
2301
2437
  for (const [key, field] of Object.entries(fields)) {
@@ -2303,10 +2439,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2303
2439
  continue;
2304
2440
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
2305
2441
  if (adjusted !== null)
2306
- acc[key] = adjusted;
2442
+ setOwn(acc, key, adjusted);
2307
2443
  }
2308
2444
  for (const ref of resolvedRefs) {
2309
- acc[ref.idFieldName] = ref.identifierSchema;
2445
+ setOwn(acc, ref.idFieldName, refIdInput(ref));
2310
2446
  }
2311
2447
  return acc;
2312
2448
  };
@@ -2322,13 +2458,13 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2322
2458
  continue; // skip ref fields (replaced by ID fields)
2323
2459
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
2324
2460
  if (adjusted !== null)
2325
- createFieldsAcc[key] = adjusted;
2461
+ setOwn(createFieldsAcc, key, adjusted);
2326
2462
  }
2327
2463
  // Add ID fields for each ref (skip if the ref field is an omitted field)
2328
2464
  for (const ref of resolvedRefs) {
2329
2465
  if (createOmitFields.has(ref.fieldName))
2330
2466
  continue;
2331
- createFieldsAcc[ref.idFieldName] = ref.identifierSchema;
2467
+ setOwn(createFieldsAcc, ref.idFieldName, refIdInput(ref));
2332
2468
  }
2333
2469
  const createSchema = Schema.Struct(createFieldsAcc);
2334
2470
  // --- Update Schema: optional model fields minus key composites & immutable ---
@@ -2355,28 +2491,34 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2355
2491
  continue;
2356
2492
  if (strippedFromUpdate.has(key))
2357
2493
  continue;
2494
+ // A field 1.40.0's map didn't hold is one an update may leave out already (`protoAbsent`).
2495
+ if (isProtoAbsent(field)) {
2496
+ setOwn(acc, key, field);
2497
+ continue;
2498
+ }
2358
2499
  const clearable = optionalOnCollide.has(key) || lackDecision(field) !== "refuse";
2359
- acc[key] = clearable
2360
- ? Schema.optional(field)
2361
- : Schema.optionalKey(field);
2500
+ setOwn(acc, key, clearable ? Schema.optional(field) : Schema.optionalKey(field));
2362
2501
  }
2363
2502
  for (const ref of resolvedRefs) {
2364
- if (pkComposites.has(ref.fieldName))
2503
+ // A ref's id that is a primary key composite is part of the key, which no update changes.
2504
+ if (pkComposites.has(ref.fieldName) || pkComposites.has(ref.idFieldName))
2365
2505
  continue;
2366
2506
  if (immutableFields.has(ref.fieldName))
2367
2507
  continue;
2368
- acc[ref.idFieldName] = Schema.optionalKey(ref.identifierSchema);
2508
+ setOwn(acc, ref.idFieldName, Schema.optionalKey(ref.keySchema));
2369
2509
  }
2370
2510
  return acc;
2371
2511
  };
2372
2512
  const updateSchema = Schema.Struct(buildUpdateFieldsAcc());
2373
2513
  // --- Key Schema: primary key composite attributes only ---
2514
+ // A composite is a model field or a ref's id (`projectId` for `project`), which a key takes as
2515
+ // the input does. Up to 1.40.0 a ref's id was left out, and every key-taking operation died.
2374
2516
  const keyCompositeNames = primaryKeyComposites(indexes);
2375
2517
  const keyFields = {};
2376
2518
  for (const name of keyCompositeNames) {
2377
- const field = fields[name];
2519
+ const field = ownValue(fields, name) ?? resolvedRefs.find((ref) => ref.idFieldName === name)?.keySchema;
2378
2520
  if (field)
2379
- keyFields[name] = field;
2521
+ setOwn(keyFields, name, field);
2380
2522
  }
2381
2523
  const keySchema = Schema.Struct(keyFields);
2382
2524
  // --- Item Schema: record + key attrs (pk, sk, gsi*) + __edd_e__ ---
@@ -2393,9 +2535,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2393
2535
  }
2394
2536
  const keyAttrFields = {};
2395
2537
  for (const fieldName of allKeyFieldNames(indexes)) {
2396
- keyAttrFields[fieldName] = primaryKeyFieldNames.has(fieldName)
2397
- ? Schema.String
2398
- : Schema.optional(Schema.String);
2538
+ setOwn(keyAttrFields, fieldName, primaryKeyFieldNames.has(fieldName) ? Schema.String : Schema.optional(Schema.String));
2399
2539
  }
2400
2540
  const itemSchema = Schema.Struct({
2401
2541
  ...readFields,
@@ -2412,11 +2552,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2412
2552
  // --- Hidden-aware decode schemas: strip DynamoModel.Hidden fields from model/record ---
2413
2553
  // These are used for "model" and "record" decode modes. Hidden fields are
2414
2554
  // still present in "item" and "native" modes.
2415
- const hiddenFieldNames = new Set();
2416
- for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
2417
- if (isHidden(fieldSchema))
2418
- hiddenFieldNames.add(fieldName);
2419
- }
2555
+ const hiddenFieldNames = hiddenFieldNamesOf(modelFields);
2420
2556
  const hasHiddenFields = hiddenFieldNames.size > 0;
2421
2557
  const modelVisibleSchema = hasHiddenFields
2422
2558
  ? Schema.Struct(Object.fromEntries(Object.entries(readFields).filter(([k]) => !hiddenFieldNames.has(k))))
@@ -2444,7 +2580,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2444
2580
  // Compute encodings for the appendInput fields (annotation +
2445
2581
  // inferred from typeConstructor for self schemas).
2446
2582
  const appendEncodings = buildFieldEncodings(userFields, {});
2447
- const subbedFields = substituteSchemas(userFields, appendEncodings, { enforceChecks: true });
2583
+ const subbedFields = substituteSchemas(userFields, appendEncodings, {
2584
+ enforceChecks: true,
2585
+ protoRenamed,
2586
+ });
2448
2587
  return Schema.Struct(subbedFields);
2449
2588
  })()
2450
2589
  : null;
@@ -2484,7 +2623,7 @@ const childAtSegment = (schema, segment) => {
2484
2623
  const s = inner;
2485
2624
  const fields = schemaFieldsOf(inner);
2486
2625
  if (fields !== undefined)
2487
- return typeof segment === "string" ? fields[segment] : undefined;
2626
+ return typeof segment === "string" ? ownValue(fields, segment) : undefined;
2488
2627
  // An OPAQUE class — `X.check(…)`, `X.annotate(…)`, a `DynamoModel.ref` nested
2489
2628
  // in a ref target — is deliberately NOT followed. Its `.fields` are gone, so
2490
2629
  // the derived read schema keeps it unsubstituted and decodes its leaves
@@ -2523,7 +2662,7 @@ const childAtSegment = (schema, segment) => {
2523
2662
  if (isSchemaLike(s.value) && isSchemaLike(s.key))
2524
2663
  return s.value;
2525
2664
  if (isSchemaLike(s.schema) && Array.isArray(s.records)) {
2526
- const declared = schemaFieldsOf(s.schema)?.[segment];
2665
+ const declared = ownValue(schemaFieldsOf(s.schema), segment);
2527
2666
  if (declared !== undefined)
2528
2667
  return declared;
2529
2668
  const record = s.records[0];
@@ -2564,7 +2703,8 @@ const sameValue = (a, b) => {
2564
2703
  }
2565
2704
  if (isPlainObject(a) && isPlainObject(b)) {
2566
2705
  const keys = Object.keys(a);
2567
- return keys.length === Object.keys(b).length && keys.every((k) => sameValue(a[k], b[k]));
2706
+ return (keys.length === Object.keys(b).length &&
2707
+ keys.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k])));
2568
2708
  }
2569
2709
  return false;
2570
2710
  };
@@ -2590,14 +2730,24 @@ const makeAmbiguityCheck = (original) => {
2590
2730
  return () => false;
2591
2731
  // "Already wire" means the value DECODES as wire — a plain string that is not
2592
2732
  // valid base64 is a domain value for `StringFromBase64`, and is encoded.
2593
- const decodesAsWire = Schema.decodeUnknownOption(original);
2733
+ const decodesAsWire = Schema.decodeUnknownExit(original);
2594
2734
  const isType = Schema.is(Schema.make(SchemaAST.toType(original.ast)));
2595
- const encode = Schema.encodeUnknownOption(original);
2735
+ const encode = Schema.encodeUnknownExit(original);
2736
+ // A transform that can't run synchronously can't tell (#236).
2596
2737
  return (value) => {
2597
- if (decodesAsWire(value)._tag === "None" || !isType(value))
2738
+ const asWire = issueOf(() => decodesAsWire(value));
2739
+ if (asWire === CANT_SAY)
2740
+ return CANT_SAY;
2741
+ if (asWire !== undefined || !isType(value))
2598
2742
  return false;
2599
- const encoded = encode(value);
2600
- return encoded._tag === "Some" && !sameValue(encoded.value, value);
2743
+ let encoded;
2744
+ const issue = issueOf(() => {
2745
+ encoded = encode(value);
2746
+ return encoded;
2747
+ });
2748
+ if (issue === CANT_SAY)
2749
+ return CANT_SAY;
2750
+ return encoded !== undefined && Exit.isSuccess(encoded) && !sameValue(encoded.value, value);
2601
2751
  };
2602
2752
  };
2603
2753
  /**
@@ -2614,7 +2764,7 @@ const asStored = (value) => {
2614
2764
  const out = {};
2615
2765
  for (const [key, entry] of Object.entries(value)) {
2616
2766
  if (entry !== undefined)
2617
- out[key] = asStored(entry);
2767
+ setOwn(out, key, asStored(entry));
2618
2768
  }
2619
2769
  return out;
2620
2770
  };
@@ -2625,6 +2775,98 @@ const isWalkableObject = (value) => value !== null &&
2625
2775
  !(value instanceof Date) &&
2626
2776
  !DateTime.isDateTime(value) &&
2627
2777
  !Redacted.isRedacted(value);
2778
+ /**
2779
+ * What `contains` compares in what a field stores (#242): an element of a list (`Schema.Array`, a
2780
+ * tuple), a member of a set (`Schema.ReadonlySet`, stored as DynamoDB's set), and otherwise a
2781
+ * substring of text.
2782
+ *
2783
+ * @internal
2784
+ */
2785
+ export const containedKindOf = (field) => {
2786
+ const inner = optionalField(field)?.inner ?? field;
2787
+ return SchemaAST.isArrays(inner.ast) ? "list" : isSetDeclaration(inner.ast) ? "set" : "text";
2788
+ };
2789
+ /**
2790
+ * A `contains` operand in the form the field stores what it compares (#242), from what a write of
2791
+ * a whole value there stores (`value`) and of one list element (`element`): the element as a list
2792
+ * stores it; the single member of a write of a set holding it; the text a write of it stores, when
2793
+ * that's text. `undefined` when the field doesn't take it so, and the operand is sent as given.
2794
+ *
2795
+ * @internal
2796
+ */
2797
+ export const containedOperand = (kind, value, element) => (operand) => {
2798
+ if (kind === "list")
2799
+ return element(operand);
2800
+ if (kind === "set") {
2801
+ const set = value(new Set([operand]))?.stored;
2802
+ return set instanceof Set && set.size === 1 ? { stored: [...set][0] } : undefined;
2803
+ }
2804
+ const text = value(operand);
2805
+ return typeof text?.stored === "string" ? text : undefined;
2806
+ };
2807
+ /** Whether a node carries nothing a read runs: no transformation, no check. */
2808
+ const plainNode = (ast) => ast.checks === undefined &&
2809
+ ast.encoding === undefined &&
2810
+ ast.encodingChecks === undefined;
2811
+ /** The members of a plain union, each union among them in turn; any other schema alone. */
2812
+ const membersOf = (schema) => {
2813
+ const members = schema.members;
2814
+ if (!SchemaAST.isUnion(schema.ast) || !plainNode(schema.ast) || !Array.isArray(members)) {
2815
+ return [schema];
2816
+ }
2817
+ return members.flatMap(membersOf);
2818
+ };
2819
+ const SCALAR_TAGS = new Set([
2820
+ "Null",
2821
+ "Undefined",
2822
+ "String",
2823
+ "Number",
2824
+ "Boolean",
2825
+ "BigInt",
2826
+ "Symbol",
2827
+ "Literal",
2828
+ "UniqueSymbol",
2829
+ "Enum",
2830
+ "TemplateLiteral",
2831
+ ]);
2832
+ /** What holds a path's next segment: a plain struct, a plain record, or something else. */
2833
+ const parentOf = (member) => {
2834
+ const ast = member.ast;
2835
+ if (!SchemaAST.isObjects(ast) || !plainNode(ast))
2836
+ return "other";
2837
+ if (ast.indexSignatures.length === 0)
2838
+ return "struct";
2839
+ return ast.propertySignatures.length === 0 ? "record" : "other";
2840
+ };
2841
+ /** A way's end where a member doesn't hold the path's next segment ({@link UnionWay}). */
2842
+ const missingAt = (member, segment) => {
2843
+ const ast = member.ast;
2844
+ if (!plainNode(ast))
2845
+ return { _tag: "Unknown" };
2846
+ if (SCALAR_TAGS.has(ast._tag))
2847
+ return { _tag: "CannotHold" };
2848
+ if (SchemaAST.isArrays(ast))
2849
+ return { _tag: typeof segment === "string" ? "CannotHold" : "Unknown" };
2850
+ if (SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0) {
2851
+ return { _tag: typeof segment === "string" ? "Unread" : "CannotHold" };
2852
+ }
2853
+ return { _tag: "Unknown" };
2854
+ };
2855
+ /**
2856
+ * A union's member as a path's judgement reads it (#238): a struct that renames its keys as it's
2857
+ * stored ({@link keyRenamesOf}) is read as the struct it renames, by its properties' own names,
2858
+ * which a path names (each written under its stored name, which the struct reads it from).
2859
+ * Anything else as it is.
2860
+ */
2861
+ const readAs = (member) => {
2862
+ const ast = member.ast;
2863
+ if (!SchemaAST.isObjects(ast) || ast.encoding === undefined || !keyRenamesOf(ast))
2864
+ return member;
2865
+ const renamed = member.to;
2866
+ return isSchemaLike(renamed) && SchemaAST.isObjects(renamed.ast) && plainNode(renamed.ast)
2867
+ ? renamed
2868
+ : member;
2869
+ };
2628
2870
  /**
2629
2871
  * Encoders for the VALUES of path-based updates (`pathSet`, `pathAppend`,
2630
2872
  * `pathPrepend`, `pathIfNotExists`) and record-based `append` (#133).
@@ -2650,7 +2892,14 @@ export const makePathValueEncoder = (modelFields, writeFields,
2650
2892
  * field name. A ref field's own schema is opaque (the annotation drops its
2651
2893
  * `.fields`), so a path under it is followed through the target model.
2652
2894
  */
2653
- refTargets = {}) => {
2895
+ refTargets = {},
2896
+ /**
2897
+ * Whether DynamoDB can store an encoded value: an operand whose stored form it can't store is
2898
+ * sent as given ({@link operand}).
2899
+ */
2900
+ storable,
2901
+ /** The entity's READ schemas of the model's fields, which a row is decoded by (`readsAsGiven`). */
2902
+ readFields = {}) => {
2654
2903
  const recordFields = writeFields;
2655
2904
  const cache = new Map();
2656
2905
  const encoderFor = (key, resolve) => {
@@ -2678,27 +2927,50 @@ refTargets = {}) => {
2678
2927
  const element = leafAwareEncoder(originalElement, storedElement);
2679
2928
  return (value) => (Array.isArray(value) ? value.map((entry) => element(entry)) : value);
2680
2929
  }
2681
- const encode = Schema.encodeUnknownOption(stored);
2682
- const decode = Schema.decodeUnknownOption(stored);
2930
+ const encodeExit = Schema.encodeUnknownExit(stored);
2931
+ const decodeExit = Schema.decodeUnknownExit(stored);
2932
+ /** A synchronous run's value, `undefined` on a schema issue, `CANT_SAY` when it can't finish. */
2933
+ const attempt = (run, value) => {
2934
+ let exit;
2935
+ const verdict = issueOf(() => {
2936
+ exit = run(value);
2937
+ return exit;
2938
+ });
2939
+ if (verdict === CANT_SAY)
2940
+ return CANT_SAY;
2941
+ return verdict === undefined && exit !== undefined && Exit.isSuccess(exit)
2942
+ ? { value: exit.value }
2943
+ : undefined;
2944
+ };
2683
2945
  const ambiguous = makeAmbiguityCheck(original);
2684
2946
  return (value) => {
2685
- if (ambiguous(value))
2947
+ // Where the check can't tell (a schema that can't run synchronously), the value is
2948
+ // encoded as a domain value, and written as given if that can't finish either.
2949
+ if (ambiguous(value) === true)
2686
2950
  return value;
2687
2951
  // A container holding an ambiguous wire leaf (`{ b64: "aGk=", at }`) is
2688
2952
  // encoded part by part, so that leaf follows the leaf rule instead of
2689
2953
  // being encoded a second time by the whole-value encode.
2690
2954
  if (holdsAmbiguousLeaf(original, value))
2691
2955
  return encodeByParts(original, value);
2692
- const encoded = encode(value);
2693
- if (encoded._tag === "Some")
2956
+ // A schema that can't run synchronously (an asynchronous step, a defect) says nothing of
2957
+ // the value: it's written as given, as at a position nothing checks (#236).
2958
+ const encoded = attempt(encodeExit, value);
2959
+ if (encoded === CANT_SAY)
2960
+ return value;
2961
+ if (encoded !== undefined)
2694
2962
  return encoded.value;
2695
2963
  // `decode -> encode`, as `.set()` / `put` do: a plain object given for a
2696
2964
  // class-typed field, or a value already in wire form, round-trips to its
2697
2965
  // wire form instead of being marshalled as given.
2698
- const decoded = decode(value);
2699
- if (decoded._tag === "Some") {
2700
- const reencoded = encode(decoded.value);
2701
- if (reencoded._tag === "Some")
2966
+ const decoded = attempt(decodeExit, value);
2967
+ if (decoded === CANT_SAY)
2968
+ return value;
2969
+ if (decoded !== undefined) {
2970
+ const reencoded = attempt(encodeExit, decoded.value);
2971
+ if (reencoded === CANT_SAY)
2972
+ return value;
2973
+ if (reencoded !== undefined)
2702
2974
  return reencoded.value;
2703
2975
  }
2704
2976
  return encodeByParts(original, value);
@@ -2711,7 +2983,7 @@ refTargets = {}) => {
2711
2983
  check = makeAmbiguityCheck(optionalField(schema)?.inner ?? schema);
2712
2984
  ambiguityChecks.set(schema, check);
2713
2985
  }
2714
- return check(value);
2986
+ return check(value) === true;
2715
2987
  };
2716
2988
  /**
2717
2989
  * Whether a container value holds, at any depth, a leaf in ambiguous wire
@@ -2764,7 +3036,7 @@ refTargets = {}) => {
2764
3036
  const out = {};
2765
3037
  for (const [key, entry] of Object.entries(value)) {
2766
3038
  const child = childAtSegment(schema, key);
2767
- out[key] = child === undefined ? entry : partEncoder(child)(entry);
3039
+ setOwn(out, key, child === undefined ? entry : partEncoder(child)(entry));
2768
3040
  }
2769
3041
  return out;
2770
3042
  };
@@ -2776,7 +3048,7 @@ refTargets = {}) => {
2776
3048
  const [head, ...rest] = segments;
2777
3049
  if (typeof head !== "string")
2778
3050
  return undefined;
2779
- let current = refTargets[head] ?? modelFields[head];
3051
+ let current = ownValue(refTargets, head) ?? ownValue(modelFields, head);
2780
3052
  let asDeclared = false;
2781
3053
  for (const segment of rest) {
2782
3054
  if (current === undefined)
@@ -2796,7 +3068,7 @@ refTargets = {}) => {
2796
3068
  const original = at.schema;
2797
3069
  const head = segments[0];
2798
3070
  const stored = segments.length === 1
2799
- ? recordFields[head]
3071
+ ? ownValue(recordFields, head)
2800
3072
  : at.asDeclared
2801
3073
  ? original
2802
3074
  : substituteSchemaDeep(original, { enforceChecks: true });
@@ -2812,15 +3084,499 @@ refTargets = {}) => {
2812
3084
  ? null
2813
3085
  : (() => {
2814
3086
  const decode = Schema.decodeUnknownExit(schema);
3087
+ // Only a schema issue refuses: a decode that can't finish synchronously says
3088
+ // nothing of the value (#236).
2815
3089
  return (encoded) => {
2816
- const exit = decode(asStored(encoded));
2817
- return exit._tag === "Success" ? undefined : exit.cause;
3090
+ const issue = issueOf(() => decode(asStored(encoded)));
3091
+ return issue === CANT_SAY ? undefined : issue;
2818
3092
  };
2819
3093
  })();
2820
3094
  validators.set(key, fn);
2821
3095
  return fn;
2822
3096
  };
3097
+ /**
3098
+ * Every schema a row can hold the value at `segments` under (#242), each with whether it's written
3099
+ * as declared ({@link writesFirstMemberOnly}), or `undefined` where the schema alone doesn't
3100
+ * determine what a row holds there. The walk follows EVERY union member that can hold the path,
3101
+ * not only the first: a row holding a later member stores its value there under that member's
3102
+ * schema. A position that can't hold the rest of the path (a string, a number, a literal, `null`,
3103
+ * a struct without the field) is left out. One that could hold it but isn't modelled here (an
3104
+ * `Unknown` or `Any`, a suspended schema, a declaration such as an `Option` or an opaque class, a
3105
+ * container the walk can't read) makes the path undetermined, and so does an `Unknown` or `Any` at
3106
+ * the path itself.
3107
+ */
3108
+ const declaredAt = (segments) => {
3109
+ const [head, ...rest] = segments;
3110
+ if (typeof head !== "string")
3111
+ return undefined;
3112
+ const top = refTargets[head] ?? modelFields[head];
3113
+ if (top === undefined)
3114
+ return undefined;
3115
+ const holdsNoPath = new Set([
3116
+ "Null",
3117
+ "Undefined",
3118
+ "Void",
3119
+ "Never",
3120
+ "String",
3121
+ "Number",
3122
+ "Boolean",
3123
+ "BigInt",
3124
+ "Symbol",
3125
+ "UniqueSymbol",
3126
+ "Literal",
3127
+ "TemplateLiteral",
3128
+ "Enum",
3129
+ ]);
3130
+ const membersOf = (union) => {
3131
+ const members = union.members;
3132
+ return Array.isArray(members) ? members : undefined;
3133
+ };
3134
+ const through = (members, segment, asDeclared) => {
3135
+ const out = [];
3136
+ for (const [index, member] of members.entries()) {
3137
+ const reached = reach(member, segment, asDeclared(index));
3138
+ if (reached === undefined)
3139
+ return undefined;
3140
+ out.push(...reached);
3141
+ }
3142
+ return out;
3143
+ };
3144
+ const reach = (schema, segment, asDeclared) => {
3145
+ const opt = optionalField(schema);
3146
+ if (opt?.union !== undefined) {
3147
+ // An optional union writes its first member substituted and the later ones as declared.
3148
+ const members = membersOf(opt.union)?.filter((m) => m.ast._tag !== "Undefined");
3149
+ if (members === undefined)
3150
+ return undefined;
3151
+ return through(members, segment, (index) => asDeclared || index > 0);
3152
+ }
3153
+ const inner = opt?.inner ?? schema;
3154
+ const fields = schemaFieldsOf(inner);
3155
+ if (fields !== undefined) {
3156
+ const child = typeof segment === "string" ? fields[segment] : undefined;
3157
+ return child === undefined ? [] : [{ schema: child, asDeclared }];
3158
+ }
3159
+ const ast = inner.ast;
3160
+ if (holdsNoPath.has(ast._tag))
3161
+ return [];
3162
+ if (SchemaAST.isUnion(ast)) {
3163
+ const members = membersOf(inner);
3164
+ return members === undefined ? undefined : through(members, segment, () => asDeclared);
3165
+ }
3166
+ if (SchemaAST.isArrays(ast)) {
3167
+ if (typeof segment !== "number")
3168
+ return [];
3169
+ const child = childAtSegment(inner, segment);
3170
+ if (child !== undefined)
3171
+ return [{ schema: child, asDeclared }];
3172
+ // A tuple with no element there and no rest holds nothing there.
3173
+ const s = inner;
3174
+ return Array.isArray(s.elements) && ast.rest.length === 0 ? [] : undefined;
3175
+ }
3176
+ if (SchemaAST.isObjects(ast)) {
3177
+ if (typeof segment !== "string")
3178
+ return [];
3179
+ const child = childAtSegment(inner, segment);
3180
+ return child === undefined ? undefined : [{ schema: child, asDeclared }];
3181
+ }
3182
+ return undefined;
3183
+ };
3184
+ let positions = [{ schema: top, asDeclared: false }];
3185
+ for (const segment of rest) {
3186
+ const next = [];
3187
+ for (const position of positions) {
3188
+ const reached = reach(position.schema, segment, position.asDeclared);
3189
+ if (reached === undefined)
3190
+ return undefined;
3191
+ for (const p of reached) {
3192
+ if (!next.some((q) => q.schema === p.schema && q.asDeclared === p.asDeclared))
3193
+ next.push(p);
3194
+ }
3195
+ }
3196
+ positions = next;
3197
+ }
3198
+ const holdsAnything = (schema) => {
3199
+ const tag = (optionalField(schema)?.inner ?? schema).ast._tag;
3200
+ return tag === "Unknown" || tag === "Any";
3201
+ };
3202
+ return positions.some((p) => holdsAnything(p.schema)) ? undefined : positions;
3203
+ };
3204
+ const operandForms = new Map();
3205
+ const formsAt = (segments) => {
3206
+ const key = JSON.stringify(segments);
3207
+ const cached = operandForms.get(key);
3208
+ if (cached !== undefined)
3209
+ return cached;
3210
+ const declared = declaredAt(segments);
3211
+ const head = segments[0];
3212
+ const forms = declared === undefined || declared.length === 0
3213
+ ? null
3214
+ : declared.flatMap((position) => {
3215
+ const original = position.schema;
3216
+ const stored = segments.length === 1
3217
+ ? recordFields[head]
3218
+ : position.asDeclared
3219
+ ? original
3220
+ : substituteSchemaDeep(original, { enforceChecks: true });
3221
+ if (stored === undefined)
3222
+ return [];
3223
+ const formOf = (from, to) => {
3224
+ const encode = leafAwareEncoder(from, to);
3225
+ const decode = Schema.decodeUnknownExit(to);
3226
+ return (value) => {
3227
+ const encoded = encode(value);
3228
+ if (decode(asStored(encoded))._tag !== "Success")
3229
+ return undefined;
3230
+ if (storable !== undefined && !storable(encoded))
3231
+ return undefined;
3232
+ return { stored: encoded };
3233
+ };
3234
+ };
3235
+ const value = formOf(original, stored);
3236
+ const originalElement = listElementOf(original);
3237
+ const storedElement = listElementOf(stored);
3238
+ const contained = containedOperand(containedKindOf(original), value, originalElement !== undefined && storedElement !== undefined
3239
+ ? formOf(originalElement, storedElement)
3240
+ : () => undefined);
3241
+ return [{ value, contained }];
3242
+ });
3243
+ const result = forms === null || forms.length === 0 ? null : forms;
3244
+ operandForms.set(key, result);
3245
+ return result;
3246
+ };
3247
+ /**
3248
+ * Every way to the end of a path through the model's schema, by the member it takes at each union
3249
+ * of several members on the way (`choices`, keyed by where the union is: the path up to the map
3250
+ * it reads). Within a union's member a path is followed as {@link childAtSegment} follows it.
3251
+ */
3252
+ const waysTo = (segments) => {
3253
+ const [head, ...rest] = segments;
3254
+ if (typeof head !== "string")
3255
+ return [];
3256
+ const start = refTargets[head] ?? modelFields[head];
3257
+ if (start === undefined)
3258
+ return [];
3259
+ const ways = [];
3260
+ const walk = (schema, depth, choices, asDeclared, parent) => {
3261
+ if (depth === rest.length) {
3262
+ ways.push({ choices, end: { _tag: "At", original: schema, asDeclared, parent } });
3263
+ return;
3264
+ }
3265
+ const segment = rest[depth];
3266
+ const opt = optionalField(schema);
3267
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3268
+ // Through a later member of an optional union, a path is written as declared, as
3269
+ // `originalAt` writes it ({@link writesFirstMemberOnly}).
3270
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3271
+ const at = JSON.stringify(segments.slice(0, depth + 1));
3272
+ for (const member of members) {
3273
+ const chosen = members.length > 1 ? new Map(choices).set(at, member) : choices;
3274
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3275
+ const child = childAtSegment(member, segment);
3276
+ if (child !== undefined)
3277
+ walk(child, depth + 1, chosen, declared, parentOf(member));
3278
+ else
3279
+ ways.push({ choices: chosen, end: missingAt(member, segment) });
3280
+ }
3281
+ };
3282
+ walk(start, 0, new Map(), false, "other");
3283
+ return ways;
3284
+ };
3285
+ const wayStored = new Map();
3286
+ const wayDeclared = (way) => {
3287
+ if (way.asDeclared)
3288
+ return way.original;
3289
+ const found = wayStored.get(way.original);
3290
+ if (found !== undefined)
3291
+ return found;
3292
+ const stored = substituteSchemaDeep(way.original, { enforceChecks: true });
3293
+ wayStored.set(way.original, stored);
3294
+ return stored;
3295
+ };
3296
+ const wayValidators = new Map();
3297
+ const wayValidator = (way) => {
3298
+ const stored = wayDeclared(way);
3299
+ const found = wayValidators.get(stored);
3300
+ if (found !== undefined)
3301
+ return found;
3302
+ const decode = Schema.decodeUnknownExit(stored);
3303
+ const fn = (encoded) => {
3304
+ const exit = decode(asStored(encoded));
3305
+ return exit._tag === "Success" ? undefined : exit.cause;
3306
+ };
3307
+ wayValidators.set(stored, fn);
3308
+ return fn;
3309
+ };
3310
+ const wayEncoders = new Map();
3311
+ const wayEncoder = (way) => {
3312
+ const stored = wayDeclared(way);
3313
+ const found = wayEncoders.get(stored);
3314
+ if (found !== undefined)
3315
+ return found;
3316
+ const fn = leafAwareEncoder(way.original, stored);
3317
+ wayEncoders.set(stored, fn);
3318
+ return fn;
3319
+ };
3320
+ /**
3321
+ * What one clause leaves at the node it ends at (`schema`, reached as `asDeclared` says, held by a
3322
+ * `parent`): read, not read, or `"unknown"`, which the schema can't judge — a copy, an
3323
+ * increment, an append, a whole field, a list position removed.
3324
+ */
3325
+ const endVerdict = (clause, at) => {
3326
+ if (clause._tag === "Other")
3327
+ return "unknown";
3328
+ if (clause._tag === "Value")
3329
+ return wayValidator(at)(clause.encoded) === undefined;
3330
+ if (typeof clause.segments[clause.segments.length - 1] !== "string")
3331
+ return "unknown";
3332
+ if (at.parent === "record")
3333
+ return true;
3334
+ if (at.parent === "struct")
3335
+ return rowCanLack(at.original);
3336
+ return "unknown";
3337
+ };
3338
+ /** The clauses going further from a node, by the segment they take next, in order. */
3339
+ const bySegment = (below) => {
3340
+ const groups = [];
3341
+ for (const { rest, clause } of below) {
3342
+ if (rest.length === 0)
3343
+ continue;
3344
+ const [segment, ...after] = rest;
3345
+ const group = groups.find(([held]) => held === segment);
3346
+ const entry = { rest: after, clause };
3347
+ if (group === undefined)
3348
+ groups.push([segment, [entry]]);
3349
+ else
3350
+ group[1].push(entry);
3351
+ }
3352
+ return groups;
3353
+ };
3354
+ /**
3355
+ * The judgement of an update's clauses inside one field (#238), at a node: `schema`, reached as
3356
+ * `asDeclared` says ({@link writesFirstMemberOnly}), held by a `parent`.
3357
+ *
3358
+ * `strict` asks whether what they leave is read WHATEVER the row holds there, at every union the
3359
+ * clauses pass, passed through or ended at, at any depth: at a union, either (a) every member
3360
+ * reads what they leave below it, or (b) they write every property of one member that reads it
3361
+ * ({@link fixes}), so that the update itself sets which member the row holds. A member without
3362
+ * the next segment reads past it (a plain struct), or holds nothing there for DynamoDB to write
3363
+ * into (a scalar, a list given a property, a struct given a position), which refuses the update
3364
+ * and leaves the row as it was. Anything the schema can't judge isn't read, and two clauses on
3365
+ * one path (which DynamoDB refuses) aren't either.
3366
+ *
3367
+ * Otherwise it asks whether SOME row reads what they leave: one member at each union reads every
3368
+ * clause below it, the member taken alike for every clause under the same union. Anything the
3369
+ * schema can't judge is taken as read, and a member holding nothing there as not reading it.
3370
+ */
3371
+ const judge = (schema, below, asDeclared, parent, strict) => {
3372
+ const ending = below.filter(({ rest }) => rest.length === 0);
3373
+ const further = bySegment(below);
3374
+ const at = { _tag: "At", original: schema, asDeclared, parent };
3375
+ if (strict && ending.length > 0 && (ending.length > 1 || further.length > 0))
3376
+ return false;
3377
+ for (const { clause } of ending) {
3378
+ const verdict = endVerdict(clause, at);
3379
+ if (verdict === "unknown" ? !strict : verdict)
3380
+ continue;
3381
+ return false;
3382
+ }
3383
+ if (further.length === 0)
3384
+ return true;
3385
+ const opt = optionalField(schema);
3386
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3387
+ // Through a later member of an optional union, a path is written as declared, as `originalAt`
3388
+ // writes it ({@link writesFirstMemberOnly}).
3389
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3390
+ const declaredFor = (member) => asDeclared || (first !== undefined && !first.has(member));
3391
+ const reads = (member) => memberReads(member, further, declaredFor(member), strict);
3392
+ if (members.length === 1)
3393
+ return reads(members[0]);
3394
+ // Members that don't name every segment alike are written as 1.40.0 wrote them, by the names
3395
+ // given ({@link membersNamedExactly}): what they leave isn't judged.
3396
+ if (!membersNamedExactly(members))
3397
+ return !strict;
3398
+ if (!strict)
3399
+ return members.some(reads);
3400
+ return (members.every(reads) ||
3401
+ members.some((member) => fixes(member, further, declaredFor(member)) && reads(member)));
3402
+ };
3403
+ /** {@link judge} under one member, for the clauses going further, by segment. */
3404
+ const memberReads = (member, further, asDeclared, strict) => further.every(([segment, below]) => {
3405
+ const read = readAs(member);
3406
+ const child = childAtSegment(read, segment);
3407
+ if (child !== undefined)
3408
+ return judge(child, below, asDeclared, parentOf(read), strict);
3409
+ const end = missingAt(read, segment);
3410
+ if (strict)
3411
+ return end._tag !== "Unknown";
3412
+ // A clause the schema can't judge is taken as read, wherever the member leaves it.
3413
+ if (below.every(({ clause }) => clause._tag === "Other"))
3414
+ return true;
3415
+ return end._tag === "Unread" || end._tag === "Unknown";
3416
+ });
3417
+ /**
3418
+ * Whether the clauses going further from a union's member write every property of it (#238):
3419
+ * each set or removed, or, for a property holding a plain struct, every property of THAT written
3420
+ * in turn, or for one holding a union, every property of one of its members that reads what they
3421
+ * leave. What the member holds after the update is then all theirs, whatever the row held. A
3422
+ * member that isn't a plain struct isn't known to be.
3423
+ */
3424
+ const fixes = (member, further, asDeclared) => {
3425
+ const read = readAs(member);
3426
+ if (parentOf(read) !== "struct")
3427
+ return false;
3428
+ return read.ast.propertySignatures.every((property) => {
3429
+ const group = further.find(([segment]) => segment === property.name);
3430
+ if (group === undefined)
3431
+ return false;
3432
+ const child = childAtSegment(read, property.name);
3433
+ return child !== undefined && fixedBy(child, group[1], asDeclared);
3434
+ });
3435
+ };
3436
+ /** Whether the clauses below a node set all of it ({@link fixes}). */
3437
+ const fixedBy = (schema, below, asDeclared) => {
3438
+ const ending = below.filter(({ rest }) => rest.length === 0);
3439
+ if (ending.length > 0) {
3440
+ return ending.length === 1 && below.length === 1 && ending[0].clause._tag !== "Other";
3441
+ }
3442
+ const further = bySegment(below);
3443
+ const opt = optionalField(schema);
3444
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3445
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3446
+ if (members.length > 1 && !membersNamedExactly(members))
3447
+ return false;
3448
+ return members.some((member) => {
3449
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3450
+ return (fixes(member, further, declared) &&
3451
+ (members.length === 1 || memberReads(member, further, declared, true)));
3452
+ });
3453
+ };
3454
+ const reads = (clauses, strict) => {
3455
+ const head = clauses[0]?.segments[0];
3456
+ const start = typeof head === "string" ? (refTargets[head] ?? modelFields[head]) : undefined;
3457
+ // A field the walk can't follow is one the schema can't judge.
3458
+ if (start === undefined || clauses.some((clause) => clause.segments[0] !== head)) {
3459
+ return !strict;
3460
+ }
3461
+ const below = clauses.map((clause) => ({ rest: clause.segments.slice(1), clause }));
3462
+ return judge(start, below, false, "other", strict);
3463
+ };
3464
+ const readDecoders = new WeakMap();
3465
+ const readDecoder = (schema) => {
3466
+ const found = readDecoders.get(schema);
3467
+ if (found !== undefined)
3468
+ return found;
3469
+ const decode = Schema.decodeUnknownExit(schema);
3470
+ const fn = (value) => decode(asStored(value))._tag === "Success";
3471
+ readDecoders.set(schema, fn);
3472
+ return fn;
3473
+ };
3474
+ /**
3475
+ * A class as a read decodes it: from the struct of its fields (`from`), which a path into it
3476
+ * walks. Any other schema as it is.
3477
+ */
3478
+ const readSide = (schema) => {
3479
+ const { from, to } = schema;
3480
+ return schemaFieldsOf(schema) === undefined &&
3481
+ isSchemaLike(from) &&
3482
+ schemaFieldsOf(from) !== undefined &&
3483
+ isSchemaLike(to) &&
3484
+ SchemaAST.isDeclaration(to.ast)
3485
+ ? from
3486
+ : schema;
3487
+ };
3488
+ /** The READ schema's nodes at the end of a path: one by each member of each union on the way. */
3489
+ const readNodesAt = (segments) => {
3490
+ const [head, ...rest] = segments;
3491
+ if (typeof head !== "string" || !Object.hasOwn(readFields, head))
3492
+ return [];
3493
+ const nodes = [];
3494
+ const walk = (schema, depth) => {
3495
+ const opt = optionalField(schema);
3496
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3497
+ if (depth === rest.length) {
3498
+ nodes.push(...members);
3499
+ return;
3500
+ }
3501
+ for (const member of members) {
3502
+ const child = childAtSegment(readSide(member), rest[depth]);
3503
+ if (child !== undefined)
3504
+ walk(child, depth + 1);
3505
+ }
3506
+ };
3507
+ walk(readFields[head], 0);
3508
+ return nodes;
3509
+ };
2823
3510
  return {
3511
+ operand: (segments, value, kind) => {
3512
+ const forms = formsAt(segments);
3513
+ if (forms === null)
3514
+ return value;
3515
+ let chosen;
3516
+ for (const form of forms) {
3517
+ // A position that can't hold the value holds no row it could match.
3518
+ const stored = kind === "value" ? form.value(value) : form.contained(value);
3519
+ if (stored === undefined)
3520
+ continue;
3521
+ if (chosen !== undefined && !sameValue(chosen.stored, stored.stored))
3522
+ return value;
3523
+ chosen = stored;
3524
+ }
3525
+ return chosen === undefined ? value : chosen.stored;
3526
+ },
3527
+ readsAsGiven: (segments, value, kind) => {
3528
+ const nodes = readNodesAt(segments);
3529
+ if (kind === "value")
3530
+ return nodes.some((node) => readDecoder(node)(value));
3531
+ if (!Array.isArray(value))
3532
+ return false;
3533
+ return nodes.some((node) => {
3534
+ const element = listElementOf(node);
3535
+ return element !== undefined && value.every((each) => readDecoder(element)(each));
3536
+ });
3537
+ },
3538
+ pathSet: (segments, value) => {
3539
+ const first = schemaAt(segments);
3540
+ const encoded = encoderFor(`v:${JSON.stringify(segments)}`, () => first);
3541
+ const firstValidator = validatorFor(`v:${JSON.stringify(segments)}`, () => first?.stored);
3542
+ const written = encoded === null ? value : encoded(value);
3543
+ const check = (read) => (firstValidator === null ? undefined : firstValidator(read));
3544
+ const issue = check(written);
3545
+ if (issue === undefined)
3546
+ return { encoded: written, issue, otherWay: false, check };
3547
+ for (const way of waysTo(segments)) {
3548
+ if (way.end._tag !== "At")
3549
+ continue;
3550
+ const other = wayEncoder(way.end)(value);
3551
+ const taken = wayValidator(way.end);
3552
+ if (taken(other) === undefined) {
3553
+ return {
3554
+ encoded: other,
3555
+ issue: undefined,
3556
+ otherWay: true,
3557
+ refusedBefore: issue,
3558
+ check: taken,
3559
+ };
3560
+ }
3561
+ }
3562
+ return { encoded: written, issue, otherWay: false, check };
3563
+ },
3564
+ reads,
3565
+ passesUnion: (segments) => waysTo(segments).some((way) => way.choices.size > 0),
3566
+ checks: (segments, kind) => {
3567
+ const at = schemaAt(segments);
3568
+ if (at === undefined)
3569
+ return false;
3570
+ if (kind === "value")
3571
+ return true;
3572
+ // Elements are checked one by one: only a list that checks nothing of its own, and isn't
3573
+ // transformed as a whole, reads what they leave as they're checked.
3574
+ const opt = optionalField(at.stored);
3575
+ const lists = opt?.union !== undefined ? membersOf(opt.union) : [opt?.inner ?? at.stored];
3576
+ return (listElementOf(at.stored) !== undefined &&
3577
+ lists.every((list) => !SchemaAST.isArrays(list.ast) ||
3578
+ (plainNode(list.ast) && list.ast.encoding === undefined)));
3579
+ },
2824
3580
  validate: (segments, encoded) => {
2825
3581
  const fn = validatorFor(`v:${JSON.stringify(segments)}`, () => schemaAt(segments)?.stored);
2826
3582
  return fn === null ? undefined : fn(encoded);