viell-effect-schema-http 0.15.0 → 0.16.1

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.
@@ -88,40 +88,21 @@ export type QueryFields = Readonly<
88
88
  * encoded read uses the encoded name instead, including after the added whole-group validation.
89
89
  * Conflicting values are not generally refused; give one side's name or validate a decoded mapping.
90
90
  *
91
- * Array normalization retains actual positions/length, including holes and readable hidden or
92
- * inherited cells; metadata is not converted into another element. Symbol keys keep their identity.
93
- * Hidden/inherited-position discovery requires structural array views without open or opaque
94
- * alternatives. Mixed views retain existing enumerable-child normalization, not a general proof.
95
- * These corrections do not expand constructor-default evidence. Removing an accidental failure can
96
- * expose an existing default for invalid aliases in sparse or own-iterator arrays (issue #170).
97
- * Validate and map to decoded names for those unsupported inputs; see the 0.15 migration.
98
- *
99
- * A helper accepting `Input` must handle both shapes, including nested encoded names. A helper
100
- * meant for decoded names only should declare that input shape explicitly and can supply it through
101
- * a named input mapping. Retaining an opaque value's encoded type does not force encoded reading
102
- * of its contents: the schema's own reading and constructor priority still apply. Decoded contents
103
- * give an opaque value such as a `Schema.ReadonlyMap` a predictable decoded route.
104
- *
105
- * Stable plain root data, finite closed object/union names, a successful whole constructor and
106
- * strict encoding can establish an encoded-only field overwritten by a default after a typed
107
- * strict read failure. Additional whole decoding then validates that input. If the actual winning
108
- * route instead ends in fieldwise construction after failed whole decoding, at the root or through
109
- * root union members, the same successful strict output proof retains the original refusal. This
110
- * does not replay decoding or reconstruct input. Default and writer effects can run before refusal;
111
- * other constructor and decoder choices keep their existing priority.
112
- * Ambiguous names, open/opaque/class or suspended/iterable groups, inherited/accessor fields and
113
- * changing input remain outside this proof, as do later member-constructor and unsupported recovery
114
- * routes. Successful initial whole construction also permits a nested proof through finite closed,
115
- * untransformed objects, parent unions and dense array/tuple positions. Array indices/length must
116
- * be stable own data with ordinary/null prototype and matching original strict-output length.
117
- * Every declaring parent member must use the same field
118
- * schema; stable own-data links must reach the same encoded-only field actually written by the
119
- * original strict writer. Whole decoding can repeat checks/services, refuse valid mixed-side input
120
- * or give shared-type fields their encoded meaning. Construction is not replayed. Distinct field
121
- * declarations, sparse/accessor/inherited/subclass/custom-iterator/changing arrays, array-shaped
122
- * parent union members, opaque/suspended/transformed parents and unsupported member/fieldwise paths
123
- * remain outside this extension (issue #170). Use decoded names
124
- * or a validated decoded mapping there. The Request guide describes the bounds and migration.
91
+ * Constructor-default validation is bounded: unsupported aliases can still be ignored in favor of
92
+ * defaults, including inherited-only cells, arbitrary iterators and opaque or ambiguous paths
93
+ * (issue #170). Stable sparse own cells and exact native own iterator data can qualify.
94
+ * Array normalization preserves positions and symbol identity but does not expand that proof.
95
+ * Supply one decoded shape, validated and mapped explicitly when needed, for unsupported inputs.
96
+ * Whole encoded reading can refuse mixed-side input or change a shared-type field's interpretation;
97
+ * schema checks and services can run more than once.
98
+ *
99
+ * A helper accepting `Input` must handle nested encoded alternatives too, or declare its own
100
+ * decoded-only input shape. Opaque values use their schema's own reading; supply decoded contents
101
+ * when constructor priority would otherwise lose an inner alias.
102
+ *
103
+ * See https://viell-dev.github.io/slop-effect-schema-http/schema-input for the complete current
104
+ * reading order, preservation/default boundaries and recovery.
105
+ * https://viell-dev.github.io/slop-effect-schema-http/schema-groups covers raw defaults and stacking.
125
106
  *
126
107
  * Under a union, a member that keeps every field wins over an earlier one that would strip one, on
127
108
  * both sides and at any depth. A field no member can keep beside the others is a `SchemaError` that
@@ -854,6 +835,86 @@ type GroupInput<K extends "query" | "headers", A> =
854
835
  ? { readonly [P in K]?: A }
855
836
  : { readonly [P in K]: A };
856
837
 
838
+ /** Read, recover and settle one binding before its adapter writes native header/query fields. */
839
+ const prepareGroup = <
840
+ S extends Schema.Top &
841
+ Schema.ConstraintCodec<unknown, object, unknown, unknown>,
842
+ >(
843
+ contract: S,
844
+ group: "headers" | "query",
845
+ fold: Fields.Fold,
846
+ ) => {
847
+ const read = Inputs.reader(contract, Schema.encodeEffect(contract));
848
+ const recover = Groups.recovery(contract);
849
+ const { shape, settle, taken, candidates, filled } = Shapes.bind(
850
+ contract,
851
+ fold,
852
+ );
853
+ const takenKey = group === "headers" ? "takenHeaders" : "takenQuery";
854
+ const label = group === "headers" ? "header" : "query";
855
+ return {
856
+ shape,
857
+ // Delegate directly so extraction adds no Effect boundary between the original steps.
858
+ *evaluate<I, E, R>(
859
+ self: Request<I, E, R>,
860
+ input: I,
861
+ value: Input<S>,
862
+ draft: Draft,
863
+ token: object,
864
+ defaultsFrom: (
865
+ prepared: Draft,
866
+ names: ReadonlySet<string>,
867
+ elsewhere: ReadonlySet<PropertyKey>,
868
+ ) => ReadonlyArray<readonly [string, unknown]>,
869
+ ) {
870
+ const edited = candidates(value, draft.editedFields.get(shape));
871
+ let { output, lost: lostFromInput } = yield* read(value);
872
+ let conflicts = filled(edited, output);
873
+ const own = draft[takenKey] && taken(value, output, lostFromInput);
874
+ let prepared = yield* self.prepare(
875
+ input,
876
+ own === undefined
877
+ ? draft
878
+ : {
879
+ ...draft,
880
+ [takenKey]: Shapes.taking(draft[takenKey], own, token),
881
+ },
882
+ );
883
+ if (lostFromInput.length > 0) {
884
+ const recovered = yield* recover(
885
+ value,
886
+ { output, lost: lostFromInput },
887
+ prepared[takenKey],
888
+ token,
889
+ taken,
890
+ );
891
+ if (recovered !== undefined) {
892
+ ({ output, lost: lostFromInput } = recovered.reading);
893
+ conflicts = filled(edited, output);
894
+ prepared = { ...prepared, [takenKey]: recovered.taken };
895
+ }
896
+ yield* Inputs.refuseLost(
897
+ contract,
898
+ lostFromInput,
899
+ prepared[takenKey]?.fields,
900
+ );
901
+ }
902
+ if (conflicts.length > 0)
903
+ return yield* preparationConflict(group, conflicts);
904
+ const names = Shapes.written(output, fold);
905
+ const elsewhere = Shapes.others(shape, prepared[takenKey], fold);
906
+ const defaults = defaultsFrom(prepared, names, elsewhere);
907
+ const settled = yield* Effect.mapError(settle(output, defaults), () =>
908
+ misfit(label, defaults),
909
+ );
910
+ // A field the schema does not write back would be lost, as a union member can lose one.
911
+ const lost = Shapes.lost(output, defaults, settled, fold);
912
+ if (lost.length > 0) return yield* lostFields(label, lost);
913
+ return { prepared, settled, names, defaults };
914
+ },
915
+ };
916
+ };
917
+
857
918
  /**
858
919
  * Bind a schema to the call's `{ headers }` input.
859
920
  *
@@ -895,9 +956,10 @@ type GroupInput<K extends "query" | "headers", A> =
895
956
  *
896
957
  * If an eligible anyOf union would otherwise refuse uncovered root fields, it can retry the whole
897
958
  * union with each member first, using the complete original input. Recovery needs actual sibling
898
- * claims for remaining losses and preserves every previously certified name. Annotations are kept;
899
- * union-parent checks, context and encoding, transformed/open/iterable members, nested losses and
900
- * joint backtracking are excluded. Successful reads do not retry. Recovery adds at most one
959
+ * claims for remaining losses and preserves every previously certified name. Parent checks,
960
+ * encoding checks, context/defaults and annotations are retained. Group encoding,
961
+ * transformed/open/iterable members, nested losses and joint backtracking are excluded. A final
962
+ * read/write error does not start recovery. Successful reads do not retry. Recovery adds at most one
901
963
  * whole-union read per other member; those attempts can repeat schema effects and can fail.
902
964
  *
903
965
  * A field the schema produces wins over an automatic `Accept`, `Content-Type` or `Content-Length`,
@@ -913,12 +975,7 @@ export const headers = <
913
975
  >(
914
976
  contract: S,
915
977
  ) => {
916
- const read = Inputs.reader(contract, Schema.encodeEffect(contract));
917
- const recover = Groups.recovery(contract);
918
- const { shape, settle, taken, candidates, filled } = Shapes.bind(
919
- contract,
920
- foldHeader,
921
- );
978
+ const { shape, evaluate } = prepareGroup(contract, "headers", foldHeader);
922
979
  return <I, E, R>(
923
980
  self: Request<I, E, R>,
924
981
  ): Request<
@@ -941,58 +998,20 @@ export const headers = <
941
998
  const value = (
942
999
  input.headers === undefined ? {} : input.headers
943
1000
  ) as Input<S>;
944
- const edited = candidates(value, draft.editedFields.get(shape));
945
- let { output, lost: lostFromInput } = yield* read(value);
946
- let conflicts = filled(edited, output);
947
- const own = draft.takenHeaders && taken(value, output, lostFromInput);
948
- let prepared = yield* self.prepare(
1001
+ const { prepared, settled, names, defaults } = yield* evaluate(
1002
+ self,
949
1003
  input,
950
- own === undefined
951
- ? draft
952
- : {
953
- ...draft,
954
- takenHeaders: Shapes.taking(draft.takenHeaders, own, token),
955
- },
956
- );
957
- if (lostFromInput.length > 0) {
958
- const recovered = yield* recover(
959
- value,
960
- { output, lost: lostFromInput },
961
- prepared.takenHeaders,
962
- token,
963
- taken,
964
- );
965
- if (recovered !== undefined) {
966
- ({ output, lost: lostFromInput } = recovered.reading);
967
- conflicts = filled(edited, output);
968
- prepared = { ...prepared, takenHeaders: recovered.taken };
969
- }
970
- yield* Inputs.refuseLost(
971
- contract,
972
- lostFromInput,
973
- prepared.takenHeaders?.fields,
974
- );
975
- }
976
- if (conflicts.length > 0)
977
- return yield* preparationConflict("headers", conflicts);
978
- const names = Shapes.written(output, foldHeader);
979
- const elsewhere = Shapes.others(
980
- shape,
981
- prepared.takenHeaders,
982
- foldHeader,
983
- );
984
- const defaults = prepared.headerLines.filter(
985
- ([name]) =>
986
- !names.has(foldHeader(name)) &&
987
- !elsewhere.has(foldHeader(name)) &&
988
- Shapes.allows(shape, foldHeader(name)),
989
- );
990
- const settled = yield* Effect.mapError(settle(output, defaults), () =>
991
- misfit("header", defaults),
1004
+ value,
1005
+ draft,
1006
+ token,
1007
+ (prepared, names, elsewhere) =>
1008
+ prepared.headerLines.filter(
1009
+ ([name]) =>
1010
+ !names.has(foldHeader(name)) &&
1011
+ !elsewhere.has(foldHeader(name)) &&
1012
+ Shapes.allows(shape, foldHeader(name)),
1013
+ ),
992
1014
  );
993
- // A field the schema does not write back would be lost, as a union member can lose one.
994
- const lost = Shapes.lost(output, defaults, settled, foldHeader);
995
- if (lost.length > 0) return yield* lostFields("header", lost);
996
1015
  const lines = Transport.entries(settled);
997
1016
  const replaced = new Set([
998
1017
  ...names,
@@ -1081,9 +1100,10 @@ export const headers = <
1081
1100
  *
1082
1101
  * If an eligible anyOf union would otherwise refuse uncovered root fields, it can retry the whole
1083
1102
  * union with each member first, using the complete original input. Recovery needs actual sibling
1084
- * claims for remaining losses and preserves every previously certified name. Annotations are kept;
1085
- * union-parent checks, context and encoding, transformed/open/iterable members, nested losses and
1086
- * joint backtracking are excluded. Successful reads do not retry. Recovery adds at most one
1103
+ * claims for remaining losses and preserves every previously certified name. Parent checks,
1104
+ * encoding checks, context/defaults and annotations are retained. Group encoding,
1105
+ * transformed/open/iterable members, nested losses and joint backtracking are excluded. A final
1106
+ * read/write error does not start recovery. Successful reads do not retry. Recovery adds at most one
1087
1107
  * whole-union read per other member; those attempts can repeat schema effects and can fail.
1088
1108
  */
1089
1109
  export const query = <
@@ -1092,12 +1112,7 @@ export const query = <
1092
1112
  >(
1093
1113
  contract: S,
1094
1114
  ) => {
1095
- const read = Inputs.reader(contract, Schema.encodeEffect(contract));
1096
- const recover = Groups.recovery(contract);
1097
- const { shape, settle, taken, candidates, filled } = Shapes.bind(
1098
- contract,
1099
- foldQuery,
1100
- );
1115
+ const { shape, evaluate } = prepareGroup(contract, "query", foldQuery);
1101
1116
  return <I, E, R>(
1102
1117
  self: Request<I, E, R>,
1103
1118
  ): Request<
@@ -1120,58 +1135,24 @@ export const query = <
1120
1135
  const value = (
1121
1136
  input.query === undefined ? {} : input.query
1122
1137
  ) as Input<S>;
1123
- const edited = candidates(value, draft.editedFields.get(shape));
1124
- let { output, lost: lostFromInput } = yield* read(value);
1125
- let conflicts = filled(edited, output);
1126
- const own = draft.takenQuery && taken(value, output, lostFromInput);
1127
- let prepared = yield* self.prepare(
1138
+ const { prepared, settled, names, defaults } = yield* evaluate(
1139
+ self,
1128
1140
  input,
1129
- own === undefined
1130
- ? draft
1131
- : {
1132
- ...draft,
1133
- takenQuery: Shapes.taking(draft.takenQuery, own, token),
1134
- },
1135
- );
1136
- if (lostFromInput.length > 0) {
1137
- const recovered = yield* recover(
1138
- value,
1139
- { output, lost: lostFromInput },
1140
- prepared.takenQuery,
1141
- token,
1142
- taken,
1143
- );
1144
- if (recovered !== undefined) {
1145
- ({ output, lost: lostFromInput } = recovered.reading);
1146
- conflicts = filled(edited, output);
1147
- prepared = { ...prepared, takenQuery: recovered.taken };
1148
- }
1149
- yield* Inputs.refuseLost(
1150
- contract,
1151
- lostFromInput,
1152
- prepared.takenQuery?.fields,
1153
- );
1154
- }
1155
- if (conflicts.length > 0)
1156
- return yield* preparationConflict("query", conflicts);
1157
- const names = Shapes.written(output, foldQuery);
1158
- const elsewhere = Shapes.others(shape, prepared.takenQuery, foldQuery);
1159
- const defaults = prepared.request.urlParams.params
1160
- .filter(
1161
- (param) =>
1162
- prepared.declaredQuery.has(param) &&
1163
- !isEmptySegment(prepared, param) &&
1164
- !names.has(param[0]) &&
1165
- !elsewhere.has(param[0]) &&
1166
- Shapes.allows(shape, param[0]),
1167
- )
1168
- .map((param) => [param[0], queryValue(prepared, param)] as const);
1169
- const settled = yield* Effect.mapError(settle(output, defaults), () =>
1170
- misfit("query", defaults),
1141
+ value,
1142
+ draft,
1143
+ token,
1144
+ (prepared, names, elsewhere) =>
1145
+ prepared.request.urlParams.params
1146
+ .filter(
1147
+ (param) =>
1148
+ prepared.declaredQuery.has(param) &&
1149
+ !isEmptySegment(prepared, param) &&
1150
+ !names.has(param[0]) &&
1151
+ !elsewhere.has(param[0]) &&
1152
+ Shapes.allows(shape, param[0]),
1153
+ )
1154
+ .map((param) => [param[0], queryValue(prepared, param)] as const),
1171
1155
  );
1172
- // A field the schema does not write back would be lost, as a union member can lose one.
1173
- const lost = Shapes.lost(output, defaults, settled, foldQuery);
1174
- if (lost.length > 0) return yield* lostFields("query", lost);
1175
1156
  return replaceQuery(
1176
1157
  prepared,
1177
1158
  UrlEncoding.queryEntries(settled),
@@ -1676,6 +1657,8 @@ const initialDraft = (declaration: Declaration): Draft => {
1676
1657
  * goes through the encoder. With no entries at all, the encoder still has its say.
1677
1658
  */
1678
1659
  const renderQuery = (draft: Draft, encoding: UrlEncoding.Service): string => {
1660
+ const params = draft.request.urlParams.params;
1661
+ if (params.length === 0) return encoding.query([]);
1679
1662
  const parts: Array<string> = [];
1680
1663
  let run: Array<readonly [string, string | null]> = [];
1681
1664
  const endRun = () => {
@@ -1683,7 +1666,7 @@ const renderQuery = (draft: Draft, encoding: UrlEncoding.Service): string => {
1683
1666
  if (rendered !== "") parts.push(rendered);
1684
1667
  run = [];
1685
1668
  };
1686
- for (const param of draft.request.urlParams.params) {
1669
+ for (const param of params) {
1687
1670
  const written = draft.queryText.get(param);
1688
1671
  if (written !== undefined) {
1689
1672
  endRun();
@@ -1693,7 +1676,7 @@ const renderQuery = (draft: Draft, encoding: UrlEncoding.Service): string => {
1693
1676
  }
1694
1677
  }
1695
1678
  endRun();
1696
- return parts.length === 0 ? encoding.query([]) : parts.join("&");
1679
+ return parts.join("&");
1697
1680
  };
1698
1681
 
1699
1682
  const finalize = (
@@ -80,7 +80,8 @@ export interface Service {
80
80
  * stands between other entries, each run of them is rendered by a separate call, keeping the
81
81
  * order of the query. A request with no entries gets one call with an empty array, and a query
82
82
  * made only of written text gets no call, so add a fixed entry with `Request.setQuery` in a
83
- * shared transform rather than here.
83
+ * shared transform rather than here. Returning `""` omits that run; it does not ask the renderer
84
+ * again with empty input.
84
85
  */
85
86
  readonly query: (entries: Query) => string;
86
87
  /**
@@ -1,4 +1,5 @@
1
1
  import type { SchemaAST } from "effect";
2
+ import { isNonObjectAlternative } from "./primitive.js";
2
3
 
3
4
  interface Names {
4
5
  readonly decoded: ReadonlySet<PropertyKey>;
@@ -34,6 +35,9 @@ const namesOf = (
34
35
  [(ast.encoding ?? []).map(({ to }) => to), encodings],
35
36
  ] as const) {
36
37
  for (const node of nodes) {
38
+ // This is only a union-member rule. Primitive encoding intermediates remain unsupported,
39
+ // and never enter the shared memo as an empty group view.
40
+ if (output === members && isNonObjectAlternative(node)) continue;
37
41
  const names = namesOf(node, active, known);
38
42
  if (names === undefined) {
39
43
  active.delete(ast);
@@ -44,6 +48,12 @@ const namesOf = (
44
48
  }
45
49
  }
46
50
  active.delete(ast);
51
+ // A union of primitives is still a primitive encoding intermediate. Requiring an object view
52
+ // also prevents the shared memo from turning that intermediate into an empty group view.
53
+ if (ast._tag === "Union" && members.length === 0) {
54
+ known.set(ast, undefined);
55
+ return undefined;
56
+ }
47
57
  const decoded = new Set(
48
58
  ast._tag === "Objects"
49
59
  ? ast.propertySignatures.map(({ name }) => keyOf(name))
@@ -400,9 +400,9 @@ export const reader = <S extends Schema.Top, A, R>(
400
400
  };
401
401
 
402
402
  /**
403
- * Whole-union alternatives for an anyOf group without parent behavior. Preserve every member and
403
+ * Whole-union alternatives for an anyOf group without group encoding. Preserve every member and
404
404
  * the whole input: trying one member alone would move its decoder ahead of another's constructor.
405
- * Keep annotations unchanged; parent checks, encoding and context remain excluded.
405
+ * Keep parent validation, context and annotations unchanged on every attempt.
406
406
  */
407
407
  export const reorderedReaders = <S extends Schema.Top>(contract: S) => {
408
408
  const ast = contract.ast;
@@ -410,9 +410,6 @@ export const reorderedReaders = <S extends Schema.Top>(contract: S) => {
410
410
  ast._tag !== "Union" ||
411
411
  (ast.options?.mode ?? "anyOf") !== "anyOf" ||
412
412
  ast.encoding !== undefined ||
413
- ast.context !== undefined ||
414
- ast.checks !== undefined ||
415
- ast.encodingChecks !== undefined ||
416
413
  !ast.types.every(
417
414
  (member) =>
418
415
  member._tag === "Objects" &&
@@ -430,6 +427,10 @@ export const reorderedReaders = <S extends Schema.Top>(contract: S) => {
430
427
  [member, ...ast.types.filter((_, position) => position !== index)],
431
428
  ast.options,
432
429
  ast.annotations,
430
+ ast.checks,
431
+ undefined,
432
+ ast.context,
433
+ ast.encodingChecks,
433
434
  ),
434
435
  );
435
436
  return reader(reordered, Schema.encodeEffect(reordered));
@@ -1,5 +1,6 @@
1
1
  import type { SchemaAST } from "effect";
2
2
  import { encodedInput } from "./encoded-input.js";
3
+ import { isNonObjectAlternative } from "./primitive.js";
3
4
 
4
5
  type CaptureTerminal = NonNullable<ReturnType<typeof encodedInput>>;
5
6
  type Key = string | symbol;
@@ -31,6 +32,36 @@ interface Captured {
31
32
  const keyOf = (name: PropertyKey): Key =>
32
33
  typeof name === "number" ? String(name) : name;
33
34
 
35
+ /** Canonical own positions only: symbols and index-looking metadata never become array cells. */
36
+ const arrayIndex = (key: Key, length: number): number | undefined => {
37
+ if (typeof key !== "string") return undefined;
38
+ const index = Number(key);
39
+ return Number.isInteger(index) &&
40
+ index >= 0 &&
41
+ index < length &&
42
+ String(index) === key
43
+ ? index
44
+ : undefined;
45
+ };
46
+
47
+ const arrayIterator: unknown = Object.getOwnPropertyDescriptor(
48
+ Array.prototype,
49
+ Symbol.iterator,
50
+ )?.value;
51
+
52
+ const nativeIteratorUnchanged = (): boolean => {
53
+ const current = Object.getOwnPropertyDescriptor(
54
+ Array.prototype,
55
+ Symbol.iterator,
56
+ );
57
+ return (
58
+ typeof arrayIterator === "function" &&
59
+ current !== undefined &&
60
+ "value" in current &&
61
+ current.value === arrayIterator
62
+ );
63
+ };
64
+
34
65
  /** Retain the actual enumerable output link or write, including its object identity. */
35
66
  const writtenData = (output: unknown, key: Key, array = false) => {
36
67
  if (
@@ -69,7 +100,11 @@ const writtenData = (output: unknown, key: Key, array = false) => {
69
100
  };
70
101
 
71
102
  /** Data only; capture each shared ancestor prefix once, without copying the caller's values. */
72
- const ownData = (input: unknown, names: ReadonlyArray<Key>, array = false) => {
103
+ const ownData = (
104
+ input: unknown,
105
+ names: ReadonlyArray<Key>,
106
+ array: false | "caller" | "output" = false,
107
+ ) => {
73
108
  if (typeof input !== "object" || input === null) return undefined;
74
109
  const prototype: unknown = Object.getPrototypeOf(input);
75
110
  if (
@@ -90,6 +125,12 @@ const ownData = (input: unknown, names: ReadonlyArray<Key>, array = false) => {
90
125
  )
91
126
  )
92
127
  return undefined;
128
+ const ownIterator = properties.get(Symbol.iterator);
129
+ const iteratorAllowed = () =>
130
+ ownIterator === undefined ||
131
+ (array === "caller" &&
132
+ ownIterator.value === arrayIterator &&
133
+ nativeIteratorUnchanged());
93
134
  const length: unknown = array ? properties.get("length")?.value : undefined;
94
135
  if (
95
136
  array &&
@@ -97,17 +138,10 @@ const ownData = (input: unknown, names: ReadonlyArray<Key>, array = false) => {
97
138
  !Number.isInteger(length) ||
98
139
  length < 0 ||
99
140
  length > 0xffff_ffff ||
100
- properties.has(Symbol.iterator) ||
101
- keys.filter((key) => {
102
- if (typeof key !== "string") return false;
103
- const index = Number(key);
104
- return (
105
- Number.isInteger(index) &&
106
- index >= 0 &&
107
- index < length &&
108
- String(index) === key
109
- );
110
- }).length !== length)
141
+ !iteratorAllowed() ||
142
+ (array === "output" &&
143
+ keys.filter((key) => arrayIndex(key, length) !== undefined).length !==
144
+ length))
111
145
  )
112
146
  return undefined;
113
147
  const absent = names.filter((name) => !properties.has(name));
@@ -120,6 +154,7 @@ const ownData = (input: unknown, names: ReadonlyArray<Key>, array = false) => {
120
154
  if (
121
155
  Object.getPrototypeOf(input) !== prototype ||
122
156
  (array ? !Array.isArray(input) : Symbol.iterator in input) ||
157
+ (array && !iteratorAllowed()) ||
123
158
  absent.some((name) => name in input)
124
159
  )
125
160
  return false;
@@ -148,7 +183,7 @@ const ownData = (input: unknown, names: ReadonlyArray<Key>, array = false) => {
148
183
  };
149
184
 
150
185
  /**
151
- * Nested encoded-only evidence through unchanged object/union fields and dense array positions.
186
+ * Nested encoded-only evidence through unchanged object/union fields and own array positions.
152
187
  * A parent union contributes a field only when every declaring member uses the same schema.
153
188
  * No schema or thunk runs.
154
189
  */
@@ -194,18 +229,23 @@ export const nestedEncodedInput = (ast: SchemaAST.AST) => {
194
229
  }
195
230
  viewing.add(part);
196
231
  const fields = new Map<Key, SchemaAST.AST | undefined>();
232
+ let hasObjectMember = false;
197
233
  for (const member of part.types) {
234
+ if (isNonObjectAlternative(member)) continue;
198
235
  const declared = fieldsOf(member);
199
236
  if (declared === undefined) {
200
237
  viewing.delete(part);
201
238
  views.set(part, undefined);
202
239
  return undefined;
203
240
  }
241
+ hasObjectMember = true;
204
242
  for (const [name, type] of declared) mergeField(fields, name, type);
205
243
  }
206
244
  viewing.delete(part);
207
- views.set(part, fields);
208
- return fields;
245
+ // Match the terminal view: a primitive-only union never becomes an empty object view.
246
+ const view = hasObjectMember ? fields : undefined;
247
+ views.set(part, view);
248
+ return view;
209
249
  };
210
250
  const known = new Map<SchemaAST.AST, Node | undefined>();
211
251
  const active = new Set<SchemaAST.AST>();
@@ -286,10 +326,16 @@ export const nestedEncodedInput = (ast: SchemaAST.AST) => {
286
326
  };
287
327
  }
288
328
  const positions = node.array;
289
- const data = ownData(input, node.names, positions !== undefined);
329
+ const data = ownData(
330
+ input,
331
+ node.names,
332
+ positions === undefined ? false : "caller",
333
+ );
290
334
  if (data === undefined) return undefined;
291
335
  const fields = positions
292
- ? Array.from({ length: data.length! }, (_, index) => {
336
+ ? Array.from(data.properties.keys()).flatMap((name) => {
337
+ const index = arrayIndex(name, data.length!);
338
+ if (index === undefined) return [];
293
339
  const tail = Math.max(
294
340
  positions.elements.length,
295
341
  data.length! - Math.max(0, positions.rest.length - 1),
@@ -300,8 +346,8 @@ export const nestedEncodedInput = (ast: SchemaAST.AST) => {
300
346
  : index >= tail
301
347
  ? positions.rest[index - tail + 1]
302
348
  : positions.rest[0];
303
- return child === undefined ? [] : [[String(index), child] as const];
304
- }).flat()
349
+ return child === undefined ? [] : [[name, child] as const];
350
+ })
305
351
  : node.fields;
306
352
  const children = fields.flatMap(([name, child]) => {
307
353
  const property = data.properties.get(name);
@@ -321,7 +367,7 @@ export const nestedEncodedInput = (ast: SchemaAST.AST) => {
321
367
  )
322
368
  return undefined;
323
369
  const arrayOutput = positions
324
- ? ownData(output, node.names, true)
370
+ ? ownData(output, node.names, "output")
325
371
  : undefined;
326
372
  if (
327
373
  positions &&
@@ -0,0 +1,20 @@
1
+ import type { SchemaAST } from "effect";
2
+
3
+ const nonObjectTags: ReadonlySet<SchemaAST.AST["_tag"]> = new Set([
4
+ "String",
5
+ "Number",
6
+ "Boolean",
7
+ "BigInt",
8
+ "Symbol",
9
+ "UniqueSymbol",
10
+ "Literal",
11
+ "Enum",
12
+ "TemplateLiteral",
13
+ "Null",
14
+ "Undefined",
15
+ "Never",
16
+ ]);
17
+
18
+ /** Unencoded union members that cannot consume an actual object; Void deliberately does not qualify. */
19
+ export const isNonObjectAlternative = (ast: SchemaAST.AST): boolean =>
20
+ ast.encoding === undefined && nonObjectTags.has(ast._tag);