metano-runtime 3.0.1 → 3.1.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 (211) hide show
  1. package/dist/system/char-members.d.ts +51 -0
  2. package/dist/system/char-members.js +108 -0
  3. package/dist/system/collections/array-helpers.d.ts +28 -0
  4. package/dist/system/collections/array-helpers.js +105 -0
  5. package/dist/system/collections/hash-core.d.ts +5 -0
  6. package/dist/system/collections/hash-core.js +24 -0
  7. package/dist/system/collections/helpers.d.ts +16 -3
  8. package/dist/system/collections/helpers.js +28 -2
  9. package/dist/system/collections/immutable-list-builder-core.d.ts +7 -2
  10. package/dist/system/collections/immutable-list-builder-core.js +11 -0
  11. package/dist/system/collections/immutable-list-core.d.ts +8 -0
  12. package/dist/system/collections/immutable-list-core.js +19 -1
  13. package/dist/system/collections/immutable-storage.d.ts +2 -0
  14. package/dist/system/collections/immutable-storage.js +6 -1
  15. package/dist/system/collections/index.d.ts +2 -0
  16. package/dist/system/collections/index.js +2 -0
  17. package/dist/system/collections/interfaces.d.ts +13 -0
  18. package/dist/system/collections/list.d.ts +3 -0
  19. package/dist/system/collections/list.js +8 -11
  20. package/dist/system/collections/read-only-list.d.ts +11 -0
  21. package/dist/system/collections/read-only-list.js +26 -1
  22. package/dist/system/collections/sorted-list.d.ts +5 -0
  23. package/dist/system/collections/sorted-list.js +12 -1
  24. package/dist/system/collections/string-comparer.d.ts +14 -0
  25. package/dist/system/collections/string-comparer.js +45 -0
  26. package/dist/system/decimal-parsing.d.ts +12 -0
  27. package/dist/system/decimal-parsing.js +86 -0
  28. package/dist/system/exceptions/index.d.ts +1 -0
  29. package/dist/system/exceptions/index.js +1 -0
  30. package/dist/system/exceptions/throw-error.d.ts +7 -0
  31. package/dist/system/exceptions/throw-error.js +9 -0
  32. package/dist/system/index.d.ts +5 -0
  33. package/dist/system/index.js +5 -0
  34. package/dist/system/int64.d.ts +6 -0
  35. package/dist/system/int64.js +18 -9
  36. package/dist/system/integer-division.d.ts +12 -4
  37. package/dist/system/integer-division.js +19 -2
  38. package/dist/system/json/contract-name.d.ts +2 -1
  39. package/dist/system/json/contract-name.js +3 -2
  40. package/dist/system/json/converters.d.ts +15 -52
  41. package/dist/system/json/converters.js +33 -317
  42. package/dist/system/json/dictionary-keys.js +1 -3
  43. package/dist/system/json/index.d.ts +1 -1
  44. package/dist/system/json/index.js +1 -1
  45. package/dist/system/json/json-serializer.d.ts +12 -1
  46. package/dist/system/json/json-serializer.js +29 -1
  47. package/dist/system/json/json-text-writer.d.ts +17 -0
  48. package/dist/system/json/json-text-writer.js +175 -0
  49. package/dist/system/json/null-reads.d.ts +2 -1
  50. package/dist/system/json/null-reads.js +3 -1
  51. package/dist/system/json/number-from-string.d.ts +2 -0
  52. package/dist/system/json/number-from-string.js +24 -6
  53. package/dist/system/json/numeric-converters.d.ts +4 -4
  54. package/dist/system/json/numeric-converters.js +46 -8
  55. package/dist/system/json/numeric-enum-members.d.ts +3 -3
  56. package/dist/system/json/numeric-enum-members.js +2 -4
  57. package/dist/system/json/spec-plans.d.ts +102 -0
  58. package/dist/system/json/spec-plans.js +312 -0
  59. package/dist/system/json/types.d.ts +15 -9
  60. package/dist/system/lazy.d.ts +15 -0
  61. package/dist/system/lazy.js +43 -0
  62. package/dist/system/linq/grouping.d.ts +12 -0
  63. package/dist/system/linq/grouping.js +42 -0
  64. package/dist/system/linq/index.d.ts +4 -3
  65. package/dist/system/linq/index.js +3 -2
  66. package/dist/system/linq/linq.js +20 -1
  67. package/dist/system/linq/lookup.d.ts +17 -0
  68. package/dist/system/linq/lookup.js +20 -0
  69. package/dist/system/linq/operators.d.ts +35 -5
  70. package/dist/system/linq/operators.js +82 -31
  71. package/dist/system/linq/terminals.d.ts +41 -2
  72. package/dist/system/linq/terminals.js +122 -2
  73. package/dist/system/linq/types.d.ts +48 -4
  74. package/dist/system/math.d.ts +7 -0
  75. package/dist/system/math.js +14 -0
  76. package/dist/system/number-members.d.ts +10 -0
  77. package/dist/system/number-members.js +25 -0
  78. package/dist/system/number-parsing.d.ts +16 -4
  79. package/dist/system/number-parsing.js +21 -4
  80. package/dist/system/string-builder.d.ts +30 -0
  81. package/dist/system/string-builder.js +86 -0
  82. package/dist/system/task-completion-source.d.ts +37 -0
  83. package/dist/system/task-completion-source.js +81 -0
  84. package/dist-unchecked/system/char-members.d.ts +51 -0
  85. package/dist-unchecked/system/char-members.js +108 -0
  86. package/dist-unchecked/system/collections/array-helpers.d.ts +28 -0
  87. package/dist-unchecked/system/collections/array-helpers.js +105 -0
  88. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  89. package/dist-unchecked/system/collections/hash-core.js +24 -0
  90. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  91. package/dist-unchecked/system/collections/helpers.js +28 -2
  92. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  93. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  94. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  95. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  96. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  97. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  98. package/dist-unchecked/system/collections/index.d.ts +2 -0
  99. package/dist-unchecked/system/collections/index.js +2 -0
  100. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  101. package/dist-unchecked/system/collections/list.d.ts +3 -0
  102. package/dist-unchecked/system/collections/list.js +8 -11
  103. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  104. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  105. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  106. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  107. package/dist-unchecked/system/collections/string-comparer.d.ts +14 -0
  108. package/dist-unchecked/system/collections/string-comparer.js +45 -0
  109. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  110. package/dist-unchecked/system/decimal-parsing.js +86 -0
  111. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  112. package/dist-unchecked/system/exceptions/index.js +1 -0
  113. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  114. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  115. package/dist-unchecked/system/index.d.ts +5 -0
  116. package/dist-unchecked/system/index.js +5 -0
  117. package/dist-unchecked/system/int64.d.ts +6 -0
  118. package/dist-unchecked/system/int64.js +18 -9
  119. package/dist-unchecked/system/integer-division.d.ts +12 -4
  120. package/dist-unchecked/system/integer-division.js +19 -2
  121. package/dist-unchecked/system/json/contract-name.d.ts +2 -1
  122. package/dist-unchecked/system/json/contract-name.js +3 -2
  123. package/dist-unchecked/system/json/converters.d.ts +15 -52
  124. package/dist-unchecked/system/json/converters.js +33 -317
  125. package/dist-unchecked/system/json/dictionary-keys.js +1 -3
  126. package/dist-unchecked/system/json/index.d.ts +1 -1
  127. package/dist-unchecked/system/json/index.js +1 -1
  128. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  129. package/dist-unchecked/system/json/json-serializer.js +29 -1
  130. package/dist-unchecked/system/json/json-text-writer.d.ts +17 -0
  131. package/dist-unchecked/system/json/json-text-writer.js +175 -0
  132. package/dist-unchecked/system/json/null-reads.d.ts +2 -1
  133. package/dist-unchecked/system/json/null-reads.js +3 -1
  134. package/dist-unchecked/system/json/number-from-string.d.ts +2 -0
  135. package/dist-unchecked/system/json/number-from-string.js +24 -6
  136. package/dist-unchecked/system/json/numeric-converters.d.ts +4 -4
  137. package/dist-unchecked/system/json/numeric-converters.js +46 -8
  138. package/dist-unchecked/system/json/numeric-enum-members.d.ts +3 -3
  139. package/dist-unchecked/system/json/numeric-enum-members.js +2 -4
  140. package/dist-unchecked/system/json/spec-plans.d.ts +102 -0
  141. package/dist-unchecked/system/json/spec-plans.js +312 -0
  142. package/dist-unchecked/system/json/types.d.ts +15 -9
  143. package/dist-unchecked/system/lazy.d.ts +15 -0
  144. package/dist-unchecked/system/lazy.js +43 -0
  145. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  146. package/dist-unchecked/system/linq/grouping.js +42 -0
  147. package/dist-unchecked/system/linq/index.d.ts +4 -3
  148. package/dist-unchecked/system/linq/index.js +3 -2
  149. package/dist-unchecked/system/linq/linq.js +20 -1
  150. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  151. package/dist-unchecked/system/linq/lookup.js +20 -0
  152. package/dist-unchecked/system/linq/operators.d.ts +35 -5
  153. package/dist-unchecked/system/linq/operators.js +82 -31
  154. package/dist-unchecked/system/linq/terminals.d.ts +41 -2
  155. package/dist-unchecked/system/linq/terminals.js +122 -2
  156. package/dist-unchecked/system/linq/types.d.ts +48 -4
  157. package/dist-unchecked/system/math.d.ts +7 -0
  158. package/dist-unchecked/system/math.js +14 -0
  159. package/dist-unchecked/system/number-members.d.ts +10 -0
  160. package/dist-unchecked/system/number-members.js +25 -0
  161. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  162. package/dist-unchecked/system/number-parsing.js +21 -4
  163. package/dist-unchecked/system/string-builder.d.ts +30 -0
  164. package/dist-unchecked/system/string-builder.js +86 -0
  165. package/dist-unchecked/system/task-completion-source.d.ts +37 -0
  166. package/dist-unchecked/system/task-completion-source.js +81 -0
  167. package/package.json +1 -1
  168. package/src/system/char-members.ts +131 -0
  169. package/src/system/collections/array-helpers.ts +139 -0
  170. package/src/system/collections/hash-core.ts +31 -0
  171. package/src/system/collections/helpers.ts +39 -4
  172. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  173. package/src/system/collections/immutable-list-core.ts +23 -1
  174. package/src/system/collections/immutable-storage.ts +8 -1
  175. package/src/system/collections/index.ts +2 -0
  176. package/src/system/collections/interfaces.ts +16 -0
  177. package/src/system/collections/list.ts +10 -15
  178. package/src/system/collections/read-only-list.ts +35 -1
  179. package/src/system/collections/sorted-list.ts +15 -1
  180. package/src/system/collections/string-comparer.ts +57 -0
  181. package/src/system/decimal-parsing.ts +109 -0
  182. package/src/system/exceptions/index.ts +1 -0
  183. package/src/system/exceptions/throw-error.ts +9 -0
  184. package/src/system/index.ts +5 -0
  185. package/src/system/int64.ts +27 -10
  186. package/src/system/integer-division.ts +43 -6
  187. package/src/system/json/contract-name.ts +3 -2
  188. package/src/system/json/converters.ts +38 -526
  189. package/src/system/json/dictionary-keys.ts +6 -4
  190. package/src/system/json/index.ts +1 -1
  191. package/src/system/json/json-serializer.ts +42 -1
  192. package/src/system/json/json-text-writer.ts +224 -0
  193. package/src/system/json/null-reads.ts +3 -1
  194. package/src/system/json/number-from-string.ts +31 -6
  195. package/src/system/json/numeric-converters.ts +60 -8
  196. package/src/system/json/numeric-enum-members.ts +4 -6
  197. package/src/system/json/spec-plans.ts +524 -0
  198. package/src/system/json/types.ts +15 -9
  199. package/src/system/lazy.ts +62 -0
  200. package/src/system/linq/grouping.ts +77 -0
  201. package/src/system/linq/index.ts +14 -0
  202. package/src/system/linq/linq.ts +23 -1
  203. package/src/system/linq/lookup.ts +34 -0
  204. package/src/system/linq/operators.ts +109 -17
  205. package/src/system/linq/terminals.ts +161 -2
  206. package/src/system/linq/types.ts +66 -3
  207. package/src/system/math.ts +19 -0
  208. package/src/system/number-members.ts +29 -0
  209. package/src/system/number-parsing.ts +24 -4
  210. package/src/system/string-builder.ts +117 -0
  211. package/src/system/task-completion-source.ts +106 -0
@@ -1,8 +1,7 @@
1
1
  import type {
2
2
  TypeDescriptor,
3
- TypeSpec,
4
- PropertySpec,
5
3
  ArrayDescriptor,
4
+ IntegerTypeName,
6
5
  BrandedDescriptor,
7
6
  EnumDescriptor,
8
7
  KeyedCollectionDescriptor,
@@ -11,35 +10,25 @@ import type {
11
10
  RefDescriptor,
12
11
  JsonConverter,
13
12
  JsonReadOptions,
14
- PolymorphismSpec,
15
- TypeDiscriminator,
16
- ValueSpec,
17
13
  } from "./types.ts";
18
14
  import type { ValueConverter } from "./value-converter.ts";
19
15
  import { byteArrayConverter } from "./byte-array-converter.ts";
20
- // Only the contract walks (the hot path: one container per object) open and
21
- // close containers with enter/exit; the collection converters keep the
22
- // closure-based `readContainer` / `writeContainer` (#456).
23
- import {
24
- enterReadContainer,
25
- enterWriteContainer,
26
- exitContainer,
27
- readContainer,
28
- writeContainer,
29
- } from "./container-depth.ts";
30
- import { cannotConvertTo, cannotConvertToTypeName } from "./contract-name.ts";
16
+ // The collection converters keep the closure-based `readContainer` /
17
+ // `writeContainer`; only the contract walks of `spec-plans.ts` (the hot path:
18
+ // one container per object) open and close containers with enter/exit (#456).
19
+ import { readContainer, writeContainer } from "./container-depth.ts";
20
+ import { cannotConvertToTypeName } from "./contract-name.ts";
31
21
  import { dictionaryKeyConverterOf } from "./dictionary-keys.ts";
32
22
  import { readNull, valueTypeNameOf } from "./null-reads.ts";
33
- import { type ConverterSetCache, createConverterSetCache } from "./converter-set-cache.ts";
34
23
  import { JsonException } from "./errors.ts";
35
24
  import { exactBigIntLeafOf, numberOfTreeValue, treeWithDoubles } from "./exact-json-number.ts";
36
25
  import { forwardsNumberTexts } from "./exact-number-reads.ts";
37
26
  import {
27
+ DEFAULT_ENUM_INTEGER_TYPE,
38
28
  holdsBigInts,
39
29
  type Int64EnumDescriptor,
40
- isNumericEnumValue,
41
- numericEnumMembers,
42
30
  } from "./numeric-enum-members.ts";
31
+ import { isUnsignedIntegerType, isWithinIntegerRange } from "./number-from-string.ts";
43
32
  import {
44
33
  decimalConverterOf,
45
34
  type ErrorTypeName,
@@ -49,13 +38,7 @@ import {
49
38
  primitiveConverterOf,
50
39
  } from "./numeric-converters.ts";
51
40
  import { temporalConverterOf } from "./temporal-reads.ts";
52
- import { contractNameOf } from "./contract-name.ts";
53
- import {
54
- hasTaggedRegistration,
55
- resolveDeserializeTarget,
56
- resolveSerializeTarget,
57
- } from "./polymorphism.ts";
58
- import { type PropertyLookup, propertyLookupPlanOf } from "./property-lookup.ts";
41
+ import type { SpecPlans } from "./spec-plans.ts";
59
42
 
60
43
  // ─── Converter Resolution ────────────────────────────────────────────────────
61
44
 
@@ -69,7 +52,7 @@ import { type PropertyLookup, propertyLookupPlanOf } from "./property-lookup.ts"
69
52
  * (#485). Under exact tree numbers, only the built-in converters that read a
70
53
  * number's exact text see a number leaf (`withNumberTextsAsDoubles`).
71
54
  */
72
- function resolveConverter(
55
+ export function resolveConverter(
73
56
  descriptor: TypeDescriptor,
74
57
  plans: SpecPlans,
75
58
  readOptions?: JsonReadOptions,
@@ -415,15 +398,16 @@ function enumConverter(descriptor: EnumDescriptor) {
415
398
 
416
399
  // ─── Enum (Numeric) ──────────────────────────────────────────────────────────
417
400
 
401
+ /**
402
+ * A numeric enum reads any integer of its underlying type, whether a member
403
+ * declares it or not, as System.Text.Json does (#369): a `[Flags]`
404
+ * combination (`3` for `Read | Write`) and an undeclared value (`42`) both
405
+ * read. Any other JSON value, an integer outside the underlying type
406
+ * included, throws System.Text.Json's conversion error naming the enum.
407
+ */
418
408
  function numericEnumConverter(descriptor: NumericEnumDescriptor) {
419
- const validValues = new Set(numericEnumMembers(descriptor).map(([, value]) => value));
420
409
  const reader = holdsBigInts(descriptor) ? int64EnumReader(descriptor) : undefined;
421
-
422
- const invalidValue = (value: unknown) =>
423
- new JsonException(
424
- `Invalid numeric enum value: ${typeof value === "bigint" ? value : JSON.stringify(value)}. ` +
425
- `Expected one of: ${[...validValues].join(", ")}`,
426
- );
410
+ const numberType = descriptor.numberType ?? DEFAULT_ENUM_INTEGER_TYPE;
427
411
 
428
412
  return {
429
413
  // A 32-bit enum value is already a number.
@@ -434,17 +418,33 @@ function numericEnumConverter(descriptor: NumericEnumDescriptor) {
434
418
  throw cannotConvertToTypeName(descriptor.typeName);
435
419
  }
436
420
 
437
- const read = reader ? reader.deserialize(value) : value;
421
+ if (reader) {
422
+ return reader.deserialize(value);
423
+ }
438
424
 
439
- if (!isNumericEnumValue(read) || !validValues.has(read)) {
440
- throw invalidValue(read);
425
+ if (!isIntegerOfType(value, numberType)) {
426
+ throw cannotConvertToTypeName(descriptor.typeName);
441
427
  }
442
428
 
443
- return read;
429
+ return value;
444
430
  },
445
431
  };
446
432
  }
447
433
 
434
+ /**
435
+ * Whether `value` is a `number` holding an integer within `numberType`'s
436
+ * range. An unsigned type takes no sign, not even `-0`'s (measured: STJ
437
+ * throws for `-0` into a `byte` enum, as for a `ulong`).
438
+ */
439
+ function isIntegerOfType(value: unknown, numberType: IntegerTypeName): value is number {
440
+ return (
441
+ typeof value === "number" &&
442
+ Number.isInteger(value) &&
443
+ !(Object.is(value, -0) && isUnsignedIntegerType(numberType)) &&
444
+ isWithinIntegerRange(BigInt(value), numberType)
445
+ );
446
+ }
447
+
448
448
  /**
449
449
  * A 64-bit enum's values are `bigint`s (#701): they are written as their
450
450
  * exact digits and read from the exact token, in the underlying type's
@@ -536,481 +536,6 @@ function refConverter(descriptor: RefDescriptor, plans: SpecPlans) {
536
536
  };
537
537
  }
538
538
 
539
- // ─── Core serialize/deserialize by spec ──────────────────────────────────────
540
-
541
- /**
542
- * Collects all properties from a spec chain, walking the base hierarchy.
543
- * Base properties come first, own properties last: the declaration order a
544
- * factory reads, **not** the wire order (see `collectWireProperties`). An
545
- * override appears once per spec that declares it.
546
- */
547
- export function collectProperties(spec: TypeSpec): readonly PropertySpec[] {
548
- const base = spec.base ? collectProperties(spec.base) : [];
549
- return [...base, ...spec.properties];
550
- }
551
-
552
- /**
553
- * The properties a spec writes and reads, in System.Text.Json's wire order
554
- * (FR-009): the spec's own properties, then its base's, recursively. A JSON
555
- * name appears once, from its most-derived declaration, and a base
556
- * declaration whose `ts` name a more-derived spec lists in
557
- * `ignoredProperties` (a `[JsonIgnore]` override) is left out. When any
558
- * property has an `order` (`[JsonPropertyOrder]`), the list is then sorted by
559
- * it, stably, across the whole chain (measured: `{"Der2":20,"Base3":3,"Der1":10,
560
- * "Base1":1,"Der3":30,"Base2":2}` for orders -5, -5, 0, 0, 1, 5).
561
- */
562
- export function collectWireProperties(spec: TypeSpec): readonly PropertySpec[] {
563
- const wire: PropertySpec[] = [];
564
- const writtenNames = new Set<string>();
565
- const ignoredNames = new Set<string>();
566
-
567
- for (const contract of specChainOf(spec)) {
568
- const visible = contract.properties.filter(
569
- (property) => !ignoredNames.has(property.ts) && !writtenNames.has(property.json),
570
- );
571
-
572
- for (const property of visible) {
573
- writtenNames.add(property.json);
574
- wire.push(property);
575
- }
576
-
577
- for (const name of contract.ignoredProperties ?? []) {
578
- ignoredNames.add(name);
579
- }
580
- }
581
-
582
- return wire.some(hasExplicitOrder) ? wire.sort(byPropertyOrder) : wire;
583
- }
584
-
585
- function hasExplicitOrder(property: PropertySpec): boolean {
586
- return property.order !== undefined;
587
- }
588
-
589
- function byPropertyOrder(left: PropertySpec, right: PropertySpec): number {
590
- return (left.order ?? 0) - (right.order ?? 0);
591
- }
592
-
593
- /** The spec and its bases, most-derived first. */
594
- function* specChainOf(spec: TypeSpec): Generator<TypeSpec> {
595
- yield spec;
596
-
597
- if (spec.base) {
598
- yield* specChainOf(spec.base);
599
- }
600
- }
601
-
602
- // ─── Spec plans ──────────────────────────────────────────────────────────────
603
-
604
- /**
605
- * Everything the reads and writes of one spec share, compiled on its first
606
- * use (#456): the wire properties (`collectWireProperties`, with ignored
607
- * overrides), their converters resolved under the spec's read options
608
- * (numbers from strings included), and the case-insensitive key index. A
609
- * polymorphic base dispatches per value through its own cached dispatch
610
- * index (`polymorphism.ts`), then runs the chosen contract's plan.
611
- *
612
- * Writes use the converters resolved for reads: read options never change
613
- * how a value is written (FR-048 item 5).
614
- */
615
- interface SpecPlan {
616
- /** Writes through the spec, dispatching a polymorphic base (FR-005, FR-006). */
617
- readonly serialize: (value: unknown) => Record<string, unknown>;
618
- /** Reads through the spec, dispatching a polymorphic base (FR-007). */
619
- readonly deserialize: (data: unknown) => unknown;
620
- /** Writes `value` with exactly the spec's properties, after the tag when one is given. */
621
- readonly writeContract: (value: unknown, typeMetadata?: TypeMetadata) => Record<string, unknown>;
622
- /**
623
- * Reads `raw` with exactly the spec's properties and builds it with the
624
- * spec's factory. `metadataKey` is the discriminator a polymorphic read
625
- * consumed.
626
- */
627
- readonly readContract: (raw: Record<string, unknown>, metadataKey?: string) => unknown;
628
- }
629
-
630
- /**
631
- * One property of a plan, with its resolved converter, and whether the
632
- * contract sets it after construction only when the payload carries it
633
- * (`TypeSpec.assignIfPresent`).
634
- */
635
- interface PropertyPlan {
636
- readonly property: PropertySpec;
637
- readonly converter: ValueConverter;
638
- readonly assignIfPresent: boolean;
639
- }
640
-
641
- /**
642
- * How the tree being read holds its numbers: `parsed`, each a `number`, as
643
- * `JSON.parse` builds it; `exact`, some as leaves, as `readJsonText` builds
644
- * it (#457): a `JsonNumberText` for those with more significant digits than
645
- * a double holds and, for a spec that reads a 64-bit integer, a
646
- * `JsonNonIntegerNumber` for the other ones with a fraction or an exponent
647
- * (`NumberTextLeaves`).
648
- */
649
- export type TreeNumbers = "parsed" | "exact";
650
-
651
- /**
652
- * The plans compiled under one set of custom converters for one kind of
653
- * tree numbers, each built once.
654
- */
655
- interface SpecPlans {
656
- readonly customConverters: readonly JsonConverter[];
657
- readonly treeNumbers: TreeNumbers;
658
- planOf(spec: TypeSpec): SpecPlan;
659
- valueConverterOf(spec: ValueSpec): ValueConverter;
660
- }
661
-
662
- /**
663
- * The plans of every custom-converter set, per kind of tree numbers. A plan
664
- * holds converters resolved against its set, so the set is part of the key:
665
- * plans are cached per spec inside each set's entry
666
- * (`converter-set-cache.ts`). Only `deserializeText` reads exact trees, so
667
- * the `exact` plans exist only for the specs it reads that way.
668
- */
669
- const specPlansByTreeNumbers: Readonly<Record<TreeNumbers, ConverterSetCache<SpecPlans>>> = {
670
- parsed: /* @__PURE__ */ createConverterSetCache((converters) =>
671
- createSpecPlans(converters, "parsed"),
672
- ),
673
- exact: /* @__PURE__ */ createConverterSetCache((converters) =>
674
- createSpecPlans(converters, "exact"),
675
- ),
676
- };
677
-
678
- function specPlansFor(
679
- customConverters: readonly JsonConverter[] | undefined,
680
- treeNumbers: TreeNumbers = "parsed",
681
- ): SpecPlans {
682
- return specPlansByTreeNumbers[treeNumbers].entryFor(customConverters);
683
- }
684
-
685
- function createSpecPlans(
686
- customConverters: readonly JsonConverter[],
687
- treeNumbers: TreeNumbers,
688
- ): SpecPlans {
689
- const specPlans = new WeakMap<TypeSpec, SpecPlan>();
690
- const valueConverters = new WeakMap<ValueSpec, ValueConverter>();
691
-
692
- const plans: SpecPlans = {
693
- customConverters,
694
- treeNumbers,
695
- planOf: (spec) => cachedIn(specPlans, spec, () => compileSpecPlan(spec, plans)),
696
- valueConverterOf: (spec) =>
697
- cachedIn(valueConverters, spec, () =>
698
- resolveConverter(spec.descriptor, plans, spec.readOptions),
699
- ),
700
- };
701
-
702
- return plans;
703
- }
704
-
705
- /**
706
- * How a property's conversion error names the declaring contract, as
707
- * System.Text.Json does (#485): `{"At":"03:04:60"}` on a `HolderTimeOnly`
708
- * names `HolderTimeOnly`, while a value root or an element names the
709
- * temporal type itself.
710
- */
711
- function contractErrorNameOf(spec: TypeSpec): ErrorTypeName {
712
- return () => contractNameOf(spec);
713
- }
714
-
715
- /**
716
- * Compiles `spec` without calling into it: nested specs and derived
717
- * contracts are resolved when a value first reaches them, so the plan of a
718
- * recursive spec never compiles itself.
719
- *
720
- * Every property's converter is resolved here, on the spec's first use, so a
721
- * malformed descriptor (a hand-written spec error) fails then, even when the
722
- * value lacks that property.
723
- */
724
- function compileSpecPlan(spec: TypeSpec, plans: SpecPlans): SpecPlan {
725
- const properties = collectWireProperties(spec);
726
-
727
- const assignedIfPresent = new Set(spec.assignIfPresent);
728
-
729
- const propertyPlans = properties.map<PropertyPlan>((property) => ({
730
- property,
731
- converter: resolveConverter(property.type, plans, spec.readOptions, contractErrorNameOf(spec)),
732
- assignIfPresent: assignedIfPresent.has(property.ts),
733
- }));
734
-
735
- const writeContract = contractWriterOf(propertyPlans);
736
- const readContract = contractReaderOf(spec, propertyPlans);
737
- const { polymorphism } = spec;
738
-
739
- if (!polymorphism) {
740
- return {
741
- serialize: (value) => writeContract(value),
742
- deserialize: (data) => readContract(requireJsonObject(data, spec)),
743
- writeContract,
744
- readContract,
745
- };
746
- }
747
-
748
- return {
749
- serialize: (value) => serializePolymorphic(value, spec, polymorphism, plans),
750
- deserialize: (data) => deserializePolymorphic(data, spec, polymorphism, plans),
751
- writeContract,
752
- readContract,
753
- };
754
- }
755
-
756
- /**
757
- * Serialize a TS object to a JSON-safe plain object using the given spec. A
758
- * polymorphic spec first chooses the derived contract and writes its tag
759
- * before every property (FR-005); the chosen contract is never dispatched
760
- * again (FR-006).
761
- */
762
- export function serializeWithSpec(
763
- value: unknown,
764
- spec: TypeSpec,
765
- customConverters?: readonly JsonConverter[],
766
- ): Record<string, unknown> {
767
- return specPlansFor(customConverters).planOf(spec).serialize(value);
768
- }
769
-
770
- function serializePolymorphic(
771
- value: unknown,
772
- spec: TypeSpec,
773
- polymorphism: PolymorphismSpec,
774
- plans: SpecPlans,
775
- ): Record<string, unknown> {
776
- const target = resolveSerializeTarget(value, spec, polymorphism);
777
-
778
- const typeMetadata =
779
- target.tag === undefined ? undefined : { name: polymorphism.discriminator, tag: target.tag };
780
-
781
- return plans.planOf(target.spec).writeContract(value, typeMetadata);
782
- }
783
-
784
- /** The type discriminator a polymorphic write puts first. */
785
- interface TypeMetadata {
786
- readonly name: string;
787
- readonly tag: TypeDiscriminator;
788
- }
789
-
790
- /** Writes a value with exactly the given properties, after the tag when one is given. */
791
- function contractWriterOf(propertyPlans: readonly PropertyPlan[]): SpecPlan["writeContract"] {
792
- const writeProperties = propertyWriterOf(propertyPlans);
793
-
794
- return (value, typeMetadata) => {
795
- enterWriteContainer();
796
-
797
- try {
798
- const result: Record<string, unknown> = {};
799
-
800
- if (typeMetadata) {
801
- result[typeMetadata.name] = typeMetadata.tag;
802
- }
803
-
804
- writeProperties(value as Record<string, unknown>, result);
805
-
806
- return result;
807
- } finally {
808
- exitContainer();
809
- }
810
- };
811
- }
812
-
813
- /** Writes every property of `source` into `result`, in wire order. */
814
- function propertyWriterOf(
815
- propertyPlans: readonly PropertyPlan[],
816
- ): (source: Record<string, unknown>, result: Record<string, unknown>) => void {
817
- return (source, result) => {
818
- for (const { property, converter } of propertyPlans) {
819
- const tsValue = source[property.ts];
820
-
821
- if (tsValue == null && property.omitWhenNull) {
822
- continue;
823
- }
824
-
825
- if (tsValue == null && property.optional) {
826
- result[property.json] = null;
827
- continue;
828
- }
829
-
830
- result[property.json] = converter.serialize(tsValue);
831
- }
832
- };
833
- }
834
-
835
- /**
836
- * Deserialize unknown data (from JSON.parse) into a typed instance using the
837
- * spec. A polymorphic spec reads the derived contract its tag selects
838
- * (FR-007). `treeNumbers` says how `data` holds its numbers; a root number
839
- * leaf reads as the number it is, which no contract accepts.
840
- */
841
- export function deserializeWithSpec<T>(
842
- data: unknown,
843
- spec: TypeSpec<T>,
844
- customConverters?: readonly JsonConverter[],
845
- treeNumbers: TreeNumbers = "parsed",
846
- ): T {
847
- const plan = specPlansFor(customConverters, treeNumbers).planOf(spec);
848
- const root = treeNumbers === "exact" ? numberOfTreeValue(data) : data;
849
-
850
- // The plan reads `spec` or one of its registered derived contracts, so it builds a `T`.
851
- return plan.deserialize(root) as T;
852
- }
853
-
854
- function deserializePolymorphic(
855
- data: unknown,
856
- spec: TypeSpec,
857
- polymorphism: PolymorphismSpec,
858
- plans: SpecPlans,
859
- ): unknown {
860
- const raw = requireJsonObject(data, spec);
861
- const target = resolveDeserializeTarget(raw, spec, polymorphism);
862
- const metadataKey = consumedMetadataKeyOf(polymorphism);
863
-
864
- return plans.planOf(target).readContract(raw, metadataKey);
865
- }
866
-
867
- /**
868
- * The discriminator a polymorphic read consumes as metadata, never as a
869
- * property; none for a hierarchy without tags, which reads like a
870
- * non-polymorphic contract.
871
- */
872
- function consumedMetadataKeyOf(polymorphism: PolymorphismSpec): string | undefined {
873
- return hasTaggedRegistration(polymorphism) ? polymorphism.discriminator : undefined;
874
- }
875
-
876
- /** `data` as a JSON object; any other JSON value cannot be converted to the contract. */
877
- function requireJsonObject(data: unknown, spec: TypeSpec): Record<string, unknown> {
878
- if (data === null || typeof data !== "object" || Array.isArray(data)) {
879
- throw cannotConvertTo(spec);
880
- }
881
-
882
- return data as Record<string, unknown>;
883
- }
884
-
885
- /**
886
- * Reads a JSON object with exactly the given properties of `spec` and builds
887
- * it with `spec`'s factory, under `spec`'s read options.
888
- */
889
- function contractReaderOf(
890
- spec: TypeSpec,
891
- propertyPlans: readonly PropertyPlan[],
892
- ): SpecPlan["readContract"] {
893
- const properties = propertyPlans.map(({ property }) => property);
894
- const lookupPlan = propertyLookupPlanOf(properties, spec.readOptions);
895
- const readProperties = propertyReaderOf(spec, propertyPlans);
896
- const assignPresentMembers = presentMemberAssignerOf(propertyPlans);
897
-
898
- return (raw, metadataKey) => {
899
- enterReadContainer("object");
900
-
901
- try {
902
- const deserialized = readProperties(lookupPlan(raw, metadataKey));
903
-
904
- return assignPresentMembers(spec.factory(deserialized), deserialized);
905
- } finally {
906
- exitContainer();
907
- }
908
- };
909
- }
910
-
911
- /**
912
- * Sets every member of the contract's `assignIfPresent` list the payload
913
- * carried on the constructed value, in wire order (System.Text.Json follows
914
- * the payload's order; the order only shows through setter side effects).
915
- */
916
- function presentMemberAssignerOf(
917
- propertyPlans: readonly PropertyPlan[],
918
- ): (value: unknown, deserialized: Record<string, unknown>) => unknown {
919
- const names = propertyPlans
920
- .filter(({ assignIfPresent }) => assignIfPresent)
921
- .map(({ property }) => property.ts);
922
-
923
- if (names.length === 0) {
924
- return (value) => value;
925
- }
926
-
927
- return (value, deserialized) => {
928
- const target = value as Record<string, unknown>;
929
-
930
- for (const name of names) {
931
- if (name in deserialized) {
932
- target[name] = deserialized[name];
933
- }
934
- }
935
-
936
- return value;
937
- };
938
- }
939
-
940
- /**
941
- * Reads every property through `jsonValueOf` into the factory's input. An
942
- * absent (missing or `null`) optional property reads as `null`; a missing
943
- * required one throws; a missing one of the contract's `assignIfPresent`
944
- * list is left out; a `null` on a non-nullable value-type property throws
945
- * naming the declaring contract, as System.Text.Json does (#471).
946
- */
947
- function propertyReaderOf(
948
- spec: TypeSpec,
949
- propertyPlans: readonly PropertyPlan[],
950
- ): (jsonValueOf: PropertyLookup) => Record<string, unknown> {
951
- return (jsonValueOf) => {
952
- const deserialized: Record<string, unknown> = {};
953
-
954
- for (const { property, converter, assignIfPresent } of propertyPlans) {
955
- const jsonValue = jsonValueOf(property);
956
-
957
- if (jsonValue === undefined && assignIfPresent) {
958
- continue;
959
- }
960
-
961
- const isAbsent = jsonValue == null;
962
-
963
- if (isAbsent && property.optional) {
964
- deserialized[property.ts] = null;
965
- continue;
966
- }
967
-
968
- if (
969
- jsonValue === null &&
970
- !property.optional &&
971
- valueTypeNameOf(property.type) !== undefined
972
- ) {
973
- throw cannotConvertTo(spec);
974
- }
975
-
976
- if (jsonValue === undefined) {
977
- throw new JsonException(`Missing required property: "${property.json}"`);
978
- }
979
-
980
- deserialized[property.ts] = converter.deserialize(jsonValue);
981
- }
982
-
983
- return deserialized;
984
- };
985
- }
986
-
987
- // ─── Value specs ─────────────────────────────────────────────────────────────
988
-
989
- /**
990
- * Serializes a non-object root through its descriptor, exactly as a property
991
- * of that type would be (custom converters still match by kind).
992
- */
993
- export function serializeWithValueSpec(
994
- value: unknown,
995
- spec: ValueSpec,
996
- customConverters?: readonly JsonConverter[],
997
- ): unknown {
998
- return specPlansFor(customConverters).valueConverterOf(spec).serialize(value);
999
- }
1000
-
1001
- /**
1002
- * Deserializes a non-object root through its descriptor, under the spec's
1003
- * read options. `treeNumbers` says how `data` holds its numbers.
1004
- */
1005
- export function deserializeWithValueSpec(
1006
- data: unknown,
1007
- spec: ValueSpec,
1008
- customConverters?: readonly JsonConverter[],
1009
- treeNumbers: TreeNumbers = "parsed",
1010
- ): unknown {
1011
- return specPlansFor(customConverters, treeNumbers).valueConverterOf(spec).deserialize(data);
1012
- }
1013
-
1014
539
  // ─── Memoization ─────────────────────────────────────────────────────────────
1015
540
 
1016
541
  /** `create()` on first call, its result afterwards (a failed call is retried). */
@@ -1025,16 +550,3 @@ function lazy<T>(create: () => T): () => T {
1025
550
  return memo.value as T;
1026
551
  };
1027
552
  }
1028
-
1029
- function cachedIn<K extends object, V>(cache: WeakMap<K, V>, key: K, build: () => V): V {
1030
- const cached = cache.get(key);
1031
-
1032
- if (cached !== undefined) {
1033
- return cached;
1034
- }
1035
-
1036
- const built = build();
1037
- cache.set(key, built);
1038
-
1039
- return built;
1040
- }
@@ -16,7 +16,12 @@ import {
16
16
  readExactNumberText,
17
17
  readNumberTextAsNumber,
18
18
  } from "./number-from-string.ts";
19
- import { holdsBigInts, type NumericEnumValue, numericEnumMembers } from "./numeric-enum-members.ts";
19
+ import {
20
+ DEFAULT_ENUM_INTEGER_TYPE,
21
+ holdsBigInts,
22
+ type NumericEnumValue,
23
+ numericEnumMembers,
24
+ } from "./numeric-enum-members.ts";
20
25
  import { ordinalIgnoreCaseKeyOf } from "./ordinal-ignore-case.ts";
21
26
  import { temporalTextOf } from "./temporal-text.ts";
22
27
  import { readTemporalText } from "./temporal-reads.ts";
@@ -39,9 +44,6 @@ const BOOLEAN_KEYS = /* @__PURE__ */ lazyValue(
39
44
  /** `Guid` property names are read in the `D` format only (`8-4-4-4-12`). */
40
45
  const GUID_D_FORMAT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
41
46
 
42
- /** The underlying type of an enum key whose descriptor names none, the C# default. */
43
- const DEFAULT_ENUM_INTEGER_TYPE: IntegerTypeName = "System.Int32";
44
-
45
47
  const ENUM_NAME_SEPARATOR = ",";
46
48
 
47
49
  const booleanKeyConverter = /* @__PURE__ */ keyConverter(
@@ -30,6 +30,6 @@ export type {
30
30
  export { SerializerContext } from "./serializer-context.ts";
31
31
  export { JsonSerializer, BoundSerializer } from "./json-serializer.ts";
32
32
  export { PropertyNamingPolicy } from "./property-naming-policy.ts";
33
- export { collectProperties, collectWireProperties } from "./converters.ts";
33
+ export { collectProperties, collectWireProperties } from "./spec-plans.ts";
34
34
  export { JsonException, NotSupportedException } from "./errors.ts";
35
35
  export { publicJsonShape } from "./public-json-shape.ts";