metano-runtime 3.0.2 → 3.2.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 (185) hide show
  1. package/dist/system/char-members.d.ts +23 -0
  2. package/dist/system/char-members.js +46 -0
  3. package/dist/system/collections/hash-core.d.ts +5 -0
  4. package/dist/system/collections/hash-core.js +24 -0
  5. package/dist/system/collections/helpers.d.ts +16 -3
  6. package/dist/system/collections/helpers.js +28 -2
  7. package/dist/system/collections/immutable-list-builder-core.d.ts +7 -2
  8. package/dist/system/collections/immutable-list-builder-core.js +11 -0
  9. package/dist/system/collections/immutable-list-core.d.ts +8 -0
  10. package/dist/system/collections/immutable-list-core.js +19 -1
  11. package/dist/system/collections/immutable-storage.d.ts +2 -0
  12. package/dist/system/collections/immutable-storage.js +6 -1
  13. package/dist/system/collections/interfaces.d.ts +13 -0
  14. package/dist/system/collections/list.d.ts +3 -0
  15. package/dist/system/collections/list.js +7 -0
  16. package/dist/system/collections/read-only-list.d.ts +11 -0
  17. package/dist/system/collections/read-only-list.js +26 -1
  18. package/dist/system/collections/sorted-list.d.ts +5 -0
  19. package/dist/system/collections/sorted-list.js +12 -1
  20. package/dist/system/comparable-compare-to.d.ts +12 -0
  21. package/dist/system/comparable-compare-to.js +20 -0
  22. package/dist/system/decimal-parsing.d.ts +12 -0
  23. package/dist/system/decimal-parsing.js +86 -0
  24. package/dist/system/exceptions/index.d.ts +1 -0
  25. package/dist/system/exceptions/index.js +1 -0
  26. package/dist/system/exceptions/throw-error.d.ts +7 -0
  27. package/dist/system/exceptions/throw-error.js +9 -0
  28. package/dist/system/hash-code.d.ts +2 -1
  29. package/dist/system/hash-code.js +5 -2
  30. package/dist/system/index.d.ts +3 -0
  31. package/dist/system/index.js +3 -0
  32. package/dist/system/int64-math.js +2 -1
  33. package/dist/system/int64.d.ts +6 -0
  34. package/dist/system/int64.js +18 -9
  35. package/dist/system/integer-division.d.ts +12 -4
  36. package/dist/system/integer-division.js +19 -2
  37. package/dist/system/json/index.d.ts +1 -1
  38. package/dist/system/json/json-serializer.d.ts +12 -1
  39. package/dist/system/json/json-serializer.js +29 -0
  40. package/dist/system/json/json-text-writer.d.ts +24 -0
  41. package/dist/system/json/json-text-writer.js +207 -0
  42. package/dist/system/json/number-from-string.js +20 -6
  43. package/dist/system/json/numeric-converters.js +41 -0
  44. package/dist/system/json/ordinal-ignore-case.d.ts +2 -0
  45. package/dist/system/json/ordinal-ignore-case.js +1 -1
  46. package/dist/system/json/serializer-context.d.ts +13 -7
  47. package/dist/system/json/serializer-context.js +23 -11
  48. package/dist/system/json/types.d.ts +20 -0
  49. package/dist/system/linq/grouping.d.ts +12 -0
  50. package/dist/system/linq/grouping.js +42 -0
  51. package/dist/system/linq/index.d.ts +4 -3
  52. package/dist/system/linq/index.js +3 -2
  53. package/dist/system/linq/linq.js +20 -1
  54. package/dist/system/linq/lookup.d.ts +17 -0
  55. package/dist/system/linq/lookup.js +20 -0
  56. package/dist/system/linq/operators.d.ts +12 -4
  57. package/dist/system/linq/operators.js +61 -15
  58. package/dist/system/linq/terminals.d.ts +29 -2
  59. package/dist/system/linq/terminals.js +71 -3
  60. package/dist/system/linq/types.d.ts +27 -4
  61. package/dist/system/math.d.ts +27 -0
  62. package/dist/system/math.js +45 -0
  63. package/dist/system/min-max.d.ts +6 -0
  64. package/dist/system/min-max.js +10 -0
  65. package/dist/system/number-parsing.d.ts +16 -4
  66. package/dist/system/number-parsing.js +21 -4
  67. package/dist/system/string-comparison.d.ts +56 -0
  68. package/dist/system/string-comparison.js +225 -0
  69. package/dist/system/string-hash-code.d.ts +14 -0
  70. package/dist/system/string-hash-code.js +37 -0
  71. package/dist/system/string-members.d.ts +5 -4
  72. package/dist/system/string-members.js +12 -11
  73. package/dist-unchecked/system/char-members.d.ts +23 -0
  74. package/dist-unchecked/system/char-members.js +46 -0
  75. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  76. package/dist-unchecked/system/collections/hash-core.js +24 -0
  77. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  78. package/dist-unchecked/system/collections/helpers.js +28 -2
  79. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  80. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  81. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  82. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  83. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  84. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  85. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  86. package/dist-unchecked/system/collections/list.d.ts +3 -0
  87. package/dist-unchecked/system/collections/list.js +7 -0
  88. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  89. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  90. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  91. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  92. package/dist-unchecked/system/comparable-compare-to.d.ts +12 -0
  93. package/dist-unchecked/system/comparable-compare-to.js +20 -0
  94. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  95. package/dist-unchecked/system/decimal-parsing.js +86 -0
  96. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  97. package/dist-unchecked/system/exceptions/index.js +1 -0
  98. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  99. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  100. package/dist-unchecked/system/hash-code.d.ts +2 -1
  101. package/dist-unchecked/system/hash-code.js +5 -2
  102. package/dist-unchecked/system/index.d.ts +3 -0
  103. package/dist-unchecked/system/index.js +3 -0
  104. package/dist-unchecked/system/int64-math.js +2 -1
  105. package/dist-unchecked/system/int64.d.ts +6 -0
  106. package/dist-unchecked/system/int64.js +18 -9
  107. package/dist-unchecked/system/integer-division.d.ts +12 -4
  108. package/dist-unchecked/system/integer-division.js +19 -2
  109. package/dist-unchecked/system/json/index.d.ts +1 -1
  110. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  111. package/dist-unchecked/system/json/json-serializer.js +29 -0
  112. package/dist-unchecked/system/json/json-text-writer.d.ts +24 -0
  113. package/dist-unchecked/system/json/json-text-writer.js +207 -0
  114. package/dist-unchecked/system/json/number-from-string.js +20 -6
  115. package/dist-unchecked/system/json/numeric-converters.js +41 -0
  116. package/dist-unchecked/system/json/ordinal-ignore-case.d.ts +2 -0
  117. package/dist-unchecked/system/json/ordinal-ignore-case.js +1 -1
  118. package/dist-unchecked/system/json/serializer-context.d.ts +13 -7
  119. package/dist-unchecked/system/json/serializer-context.js +23 -11
  120. package/dist-unchecked/system/json/types.d.ts +20 -0
  121. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  122. package/dist-unchecked/system/linq/grouping.js +42 -0
  123. package/dist-unchecked/system/linq/index.d.ts +4 -3
  124. package/dist-unchecked/system/linq/index.js +3 -2
  125. package/dist-unchecked/system/linq/linq.js +20 -1
  126. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  127. package/dist-unchecked/system/linq/lookup.js +20 -0
  128. package/dist-unchecked/system/linq/operators.d.ts +12 -4
  129. package/dist-unchecked/system/linq/operators.js +61 -15
  130. package/dist-unchecked/system/linq/terminals.d.ts +29 -2
  131. package/dist-unchecked/system/linq/terminals.js +71 -3
  132. package/dist-unchecked/system/linq/types.d.ts +27 -4
  133. package/dist-unchecked/system/math.d.ts +27 -0
  134. package/dist-unchecked/system/math.js +45 -0
  135. package/dist-unchecked/system/min-max.d.ts +6 -0
  136. package/dist-unchecked/system/min-max.js +10 -0
  137. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  138. package/dist-unchecked/system/number-parsing.js +21 -4
  139. package/dist-unchecked/system/string-comparison.d.ts +56 -0
  140. package/dist-unchecked/system/string-comparison.js +225 -0
  141. package/dist-unchecked/system/string-hash-code.d.ts +14 -0
  142. package/dist-unchecked/system/string-hash-code.js +37 -0
  143. package/dist-unchecked/system/string-members.d.ts +5 -4
  144. package/dist-unchecked/system/string-members.js +12 -11
  145. package/package.json +1 -1
  146. package/src/system/char-members.ts +57 -0
  147. package/src/system/collections/hash-core.ts +31 -0
  148. package/src/system/collections/helpers.ts +39 -4
  149. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  150. package/src/system/collections/immutable-list-core.ts +23 -1
  151. package/src/system/collections/immutable-storage.ts +8 -1
  152. package/src/system/collections/interfaces.ts +16 -0
  153. package/src/system/collections/list.ts +9 -0
  154. package/src/system/collections/read-only-list.ts +35 -1
  155. package/src/system/collections/sorted-list.ts +15 -1
  156. package/src/system/comparable-compare-to.ts +23 -0
  157. package/src/system/decimal-parsing.ts +109 -0
  158. package/src/system/exceptions/index.ts +1 -0
  159. package/src/system/exceptions/throw-error.ts +9 -0
  160. package/src/system/hash-code.ts +7 -2
  161. package/src/system/index.ts +3 -0
  162. package/src/system/int64-math.ts +2 -1
  163. package/src/system/int64.ts +27 -10
  164. package/src/system/integer-division.ts +43 -6
  165. package/src/system/json/index.ts +1 -0
  166. package/src/system/json/json-serializer.ts +42 -0
  167. package/src/system/json/json-text-writer.ts +282 -0
  168. package/src/system/json/number-from-string.ts +26 -6
  169. package/src/system/json/numeric-converters.ts +55 -0
  170. package/src/system/json/ordinal-ignore-case.ts +1 -1
  171. package/src/system/json/serializer-context.ts +28 -11
  172. package/src/system/json/types.ts +21 -0
  173. package/src/system/linq/grouping.ts +77 -0
  174. package/src/system/linq/index.ts +8 -0
  175. package/src/system/linq/linq.ts +23 -1
  176. package/src/system/linq/lookup.ts +34 -0
  177. package/src/system/linq/operators.ts +78 -15
  178. package/src/system/linq/terminals.ts +85 -3
  179. package/src/system/linq/types.ts +32 -0
  180. package/src/system/math.ts +63 -0
  181. package/src/system/min-max.ts +11 -0
  182. package/src/system/number-parsing.ts +24 -4
  183. package/src/system/string-comparison.ts +299 -0
  184. package/src/system/string-hash-code.ts +44 -0
  185. package/src/system/string-members.ts +12 -11
@@ -44,6 +44,92 @@ export function parseDecimalText(text) {
44
44
  const sign = leadingSign === "-" || trailingSign === "-" ? "-" : "";
45
45
  return `${sign}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
46
46
  }
47
+ /** The largest scale of a `decimal`. */
48
+ const DECIMAL_SCALE_MAX = 28;
49
+ /** `1e0` … `1e28`, parsed so each is the exact double .NET's table holds. */
50
+ const DOUBLE_POWERS_OF_TEN = /* @__PURE__ */ lazyValue(() => Array.from({ length: DECIMAL_SCALE_MAX + 1 }, (_, power) => Number(`1e${power}`)));
51
+ /** A scratch view that reads the biased binary exponent of a `number`. */
52
+ const EXPONENT_VIEW = /* @__PURE__ */ lazyValue(() => new DataView(new ArrayBuffer(8)));
53
+ /**
54
+ * The digits of `(decimal)d` (`digits` 15) or `(decimal)f` (`digits` 7), for
55
+ * `new Decimal(…)`, ported from .NET's `VarDecFromR8` / `VarDecFromR4`
56
+ * (#695): the value is scaled by a power of ten to `digits` significant
57
+ * digits, the scale capped at 28, rounded half to even, and trailing zeros
58
+ * are dropped from the scale. So `(decimal)(0.1 + 0.2)` is `0.3`,
59
+ * `(decimal)1000000000000005.0` is `1000000000000000` and `(decimal)1e-30`
60
+ * is `0`. The scaling is done in double arithmetic, as .NET does.
61
+ *
62
+ * @throws OverflowException for NaN, ±Infinity and a magnitude of 2^96 or more.
63
+ */
64
+ export function decimalTextFromDouble(value, digits) {
65
+ const exponent = binaryExponentOf(value);
66
+ if (exponent < -94) {
67
+ return "0";
68
+ }
69
+ if (exponent > 96) {
70
+ throw new OverflowException(DECIMAL_RANGE_MESSAGE);
71
+ }
72
+ const lowest = DOUBLE_POWERS_OF_TEN()[digits - 1];
73
+ let power = digits - 1 - ((exponent * 19728) >> 16);
74
+ let scaled = Math.abs(value);
75
+ if (power >= 0) {
76
+ power = Math.min(power, DECIMAL_SCALE_MAX);
77
+ scaled *= DOUBLE_POWERS_OF_TEN()[power];
78
+ }
79
+ else if (power !== -1 || scaled >= lowest * 10) {
80
+ scaled /= DOUBLE_POWERS_OF_TEN()[-power];
81
+ }
82
+ else {
83
+ power = 0;
84
+ }
85
+ if (scaled < lowest && power < DECIMAL_SCALE_MAX) {
86
+ scaled *= 10;
87
+ power++;
88
+ }
89
+ const mantissa = roundHalfToEven(scaled);
90
+ if (mantissa === 0) {
91
+ return "0";
92
+ }
93
+ const sign = value < 0 ? "-" : "";
94
+ return power < 0
95
+ ? `${sign}${mantissa}${"0".repeat(-power)}`
96
+ : `${sign}${scaledText(String(mantissa), power, digits - 1)}`;
97
+ }
98
+ /**
99
+ * The exponent .NET reads from a binary floating-point value: the biased
100
+ * exponent of the double minus 1022, so `2^e ≤ |value| < 2^(e+1)` gives
101
+ * `e + 1`. A `float` held as a double reads the same exponent.
102
+ */
103
+ function binaryExponentOf(value) {
104
+ const view = EXPONENT_VIEW();
105
+ view.setFloat64(0, value);
106
+ return ((view.getUint16(0) >> 4) & 0x7ff) - 1022;
107
+ }
108
+ /** `value` (below 2^53) rounded to an integer, a tie to the even one. */
109
+ function roundHalfToEven(value) {
110
+ const floor = Math.floor(value);
111
+ const rest = value - floor;
112
+ return rest > 0.5 || (rest === 0.5 && floor % 2 === 1) ? floor + 1 : floor;
113
+ }
114
+ /**
115
+ * `digitsText` divided by `10^scale`, written out after up to `maxStrip`
116
+ * trailing zeros are dropped from the scale.
117
+ */
118
+ function scaledText(digitsText, scale, maxStrip) {
119
+ let text = digitsText;
120
+ let remaining = scale;
121
+ let strippable = Math.min(scale, maxStrip);
122
+ while (strippable > 0 && text.endsWith("0")) {
123
+ text = text.slice(0, -1);
124
+ remaining--;
125
+ strippable--;
126
+ }
127
+ if (remaining === 0) {
128
+ return text;
129
+ }
130
+ const padded = text.padStart(remaining + 1, "0");
131
+ return `${padded.slice(0, -remaining)}.${padded.slice(-remaining)}`;
132
+ }
47
133
  function formatException(text) {
48
134
  return new FormatException(`The input string '${text}' was not in a correct format.`);
49
135
  }
@@ -24,3 +24,4 @@ export * from "./switch-expression-exception.ts";
24
24
  export * from "./named-exception.ts";
25
25
  export * from "./type-initialization-exception.ts";
26
26
  export * from "./to-exception.ts";
27
+ export * from "./throw-error.ts";
@@ -24,3 +24,4 @@ export * from "./switch-expression-exception.js";
24
24
  export * from "./named-exception.js";
25
25
  export * from "./type-initialization-exception.js";
26
26
  export * from "./to-exception.js";
27
+ export * from "./throw-error.js";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Throws `error` from an expression position: the tail of a lowered C#
3
+ * `switch` expression no arm matched, or an arm whose result is a throw
4
+ * expression (`_ => throw new X()`). Returning `never` lets the conditional
5
+ * chain keep the type of its other arms, with no closure allocated.
6
+ */
7
+ export declare function throwError(error: unknown): never;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Throws `error` from an expression position: the tail of a lowered C#
3
+ * `switch` expression no arm matched, or an arm whose result is a throw
4
+ * expression (`_ => throw new X()`). Returning `never` lets the conditional
5
+ * chain keep the type of its other arms, with no closure allocated.
6
+ */
7
+ export function throwError(error) {
8
+ throw error;
9
+ }
@@ -21,7 +21,8 @@ export declare class HashCode {
21
21
  constructor();
22
22
  add(value: unknown): void;
23
23
  toHashCode(): number;
24
- static combine(v1: unknown): number;
24
+ /** `HashCode.Combine(v1 … v8)` (#749): the same accumulation as {@link add} per value. */
25
+ static combine(...values: unknown[]): number;
25
26
  static combine2(v1: unknown, v2: unknown): number;
26
27
  static combine3(v1: unknown, v2: unknown, v3: unknown): number;
27
28
  static combine4(v1: unknown, v2: unknown, v3: unknown, v4: unknown): number;
@@ -150,9 +150,12 @@ export class HashCode {
150
150
  return hash;
151
151
  }
152
152
  // ─── Static combine helpers ───────────────────────────────
153
- static combine(v1) {
153
+ /** `HashCode.Combine(v1 … v8)` (#749): the same accumulation as {@link add} per value. */
154
+ static combine(...values) {
154
155
  const hc = new HashCode();
155
- hc.add(v1);
156
+ for (const value of values) {
157
+ hc.add(value);
158
+ }
156
159
  return hc.toHashCode();
157
160
  }
158
161
  static combine2(v1, v2) {
@@ -28,6 +28,9 @@ export * from "./math.ts";
28
28
  export * from "./number-parsing.ts";
29
29
  export * from "./strings.ts";
30
30
  export * from "./string-members.ts";
31
+ export * from "./string-comparison.ts";
32
+ export * from "./string-hash-code.ts";
33
+ export * from "./comparable-compare-to.ts";
31
34
  export * from "./decimal-parsing.ts";
32
35
  export * from "./array-length.ts";
33
36
  export * from "./argument-guards.ts";
@@ -28,6 +28,9 @@ export * from "./math.js";
28
28
  export * from "./number-parsing.js";
29
29
  export * from "./strings.js";
30
30
  export * from "./string-members.js";
31
+ export * from "./string-comparison.js";
32
+ export * from "./string-hash-code.js";
33
+ export * from "./comparable-compare-to.js";
31
34
  export * from "./decimal-parsing.js";
32
35
  export * from "./array-length.js";
33
36
  export * from "./argument-guards.js";
@@ -6,6 +6,7 @@
6
6
  * every 64-bit overload here.
7
7
  */
8
8
  import { ArgumentException, OverflowException } from "./exceptions/index.js";
9
+ import { throwMinGreaterThanMax } from "./min-max.js";
9
10
  import { divInt64, divUInt64, INT64_MIN, remInt64, remUInt64 } from "./int64.js";
10
11
  /** .NET's message for `Math.Abs(long.MinValue)`. */
11
12
  const NEGATE_MIN_VALUE_MESSAGE = "Negating the minimum value of a twos complement number is invalid.";
@@ -103,7 +104,7 @@ export function compareInt64(left, right) {
103
104
  }
104
105
  function clamp(value, min, max) {
105
106
  if (min > max) {
106
- throw new ArgumentException(`'${min}' cannot be greater than ${max}.`);
107
+ throwMinGreaterThanMax(min, max);
107
108
  }
108
109
  return maxInt64(min, minInt64(value, max));
109
110
  }
@@ -82,6 +82,12 @@ export declare function int64FromDecimal(value: DecimalLike): bigint;
82
82
  export declare function uint64FromDecimal(value: DecimalLike): bigint;
83
83
  /** Decimal to an integer of 32 bits or fewer: truncate exactly, then check even when unchecked. */
84
84
  export declare function narrowFromDecimal(value: DecimalLike, bits: 8 | 16 | 32, signed: boolean): number;
85
+ /**
86
+ * `(char)m`: the UTF-16 code of the truncated `decimal` (#695).
87
+ *
88
+ * @throws OverflowException("Value was either too large or too small for a character.") outside 0–65535.
89
+ */
90
+ export declare function charCodeFromDecimal(value: DecimalLike): number;
85
91
  /** `(long)b`: throws OverflowException outside the range, in every context. */
86
92
  export declare function int64FromBigInteger(value: bigint): bigint;
87
93
  /**
@@ -162,18 +162,27 @@ export function uint64FromDecimal(value) {
162
162
  }
163
163
  /** Decimal to an integer of 32 bits or fewer: truncate exactly, then check even when unchecked. */
164
164
  export function narrowFromDecimal(value, bits, signed) {
165
- const message = () => {
166
- const type = bits === 8
167
- ? signed
168
- ? "a signed byte"
169
- : "an unsigned byte"
170
- : `${signed ? "an Int" : "a UInt"}${bits}`;
171
- return `Value was either too large or too small for ${type}.`;
172
- };
173
- const integer = truncatedDecimal(value, message);
165
+ const type = bits === 8
166
+ ? signed
167
+ ? "a signed byte"
168
+ : "an unsigned byte"
169
+ : `${signed ? "an Int" : "a UInt"}${bits}`;
174
170
  const width = BigInt(bits);
175
171
  const min = signed ? -(1n << (width - 1n)) : 0n;
176
172
  const max = signed ? (1n << (width - 1n)) - 1n : (1n << width) - 1n;
173
+ return truncatedDecimalInRange(value, min, max, type);
174
+ }
175
+ /**
176
+ * `(char)m`: the UTF-16 code of the truncated `decimal` (#695).
177
+ *
178
+ * @throws OverflowException("Value was either too large or too small for a character.") outside 0–65535.
179
+ */
180
+ export function charCodeFromDecimal(value) {
181
+ return truncatedDecimalInRange(value, 0n, 0xffffn, "a character");
182
+ }
183
+ function truncatedDecimalInRange(value, min, max, type) {
184
+ const message = () => `Value was either too large or too small for ${type}.`;
185
+ const integer = truncatedDecimal(value, message);
177
186
  return Number(requireRange(integer, min, max, message));
178
187
  }
179
188
  /** `(long)b`: throws OverflowException outside the range, in every context. */
@@ -9,12 +9,20 @@
9
9
  * for integral operands (`-7 / 2` is `-3`). A `null` (or `undefined`) operand yields
10
10
  * `null`, matching C#'s lifted `int?` division.
11
11
  *
12
- * Overflow is not modelled: `int.MinValue / -1` returns `2147483648` instead of
13
- * throwing `OverflowException`, and a `long` quotient beyond `Number.MAX_SAFE_INTEGER`
14
- * loses precision, like every other `long` value mapped to `number`.
15
- *
16
12
  * @throws DivideByZeroException, with .NET's message, when `divisor` is zero,
17
13
  * where a bare `Math.trunc(dividend / divisor)` would yield `Infinity` or `NaN`.
14
+ * @throws OverflowException for `int.MinValue / -1`, whose quotient does not fit `int`.
18
15
  */
19
16
  export declare function intDiv(dividend: number, divisor: number): number;
20
17
  export declare function intDiv(dividend: number | null | undefined, divisor: number | null | undefined): number | null;
18
+ /**
19
+ * `a % b` over `int` or `uint` operands with a divisor that is not a constant:
20
+ * the remainder with the dividend's sign, as JavaScript's `%` computes it, but
21
+ * throwing where .NET throws instead of yielding `NaN` or `0` (#695). A `null`
22
+ * (or `undefined`) operand yields `null`, matching C#'s lifted `int?` remainder.
23
+ *
24
+ * @throws DivideByZeroException, with .NET's message, when `divisor` is zero.
25
+ * @throws OverflowException for `int.MinValue % -1`, as .NET does.
26
+ */
27
+ export declare function intRem(dividend: number, divisor: number): number;
28
+ export declare function intRem(dividend: number | null | undefined, divisor: number | null | undefined): number | null;
@@ -5,13 +5,30 @@
5
5
  * where C# gives `3`.
6
6
  */
7
7
  import { DivideByZeroException } from "./exceptions/divide-by-zero-exception.js";
8
+ import { OverflowException } from "./exceptions/overflow-exception.js";
9
+ const INT32_MIN = -2147483648;
8
10
  export function intDiv(dividend, divisor) {
9
11
  if (dividend == null || divisor == null) {
10
12
  return null;
11
13
  }
14
+ requireInt32Division(dividend, divisor);
15
+ // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
16
+ return Math.trunc(dividend / divisor) + 0;
17
+ }
18
+ export function intRem(dividend, divisor) {
19
+ if (dividend == null || divisor == null) {
20
+ return null;
21
+ }
22
+ requireInt32Division(dividend, divisor);
23
+ // `+ 0` turns the `-0` of `-4 % 2` into `0`.
24
+ return (dividend % divisor) + 0;
25
+ }
26
+ /** Throws what .NET throws for an `int` `/` or `%`: a zero divisor, or `int.MinValue` by `-1`. */
27
+ function requireInt32Division(dividend, divisor) {
12
28
  if (divisor === 0) {
13
29
  throw new DivideByZeroException();
14
30
  }
15
- // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
16
- return Math.trunc(dividend / divisor) + 0;
31
+ if (dividend === INT32_MIN && divisor === -1) {
32
+ throw new OverflowException();
33
+ }
17
34
  }
@@ -1,4 +1,4 @@
1
- export type { TypeDescriptor, PrimitiveDescriptor, Int64Descriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, BytesDescriptor, ArrayDescriptor, KeyedCollectionDescriptor, SequenceCollectionDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, TypeDiscriminator, UnknownDerivedTypeHandling, DerivedTypeSpec, PolymorphismSpec, JsonReadOptions, NumberTypeName, JsonConverter, SerializerContextOptions, } from "./types.ts";
1
+ export type { TypeDescriptor, PrimitiveDescriptor, Int64Descriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, BytesDescriptor, ArrayDescriptor, KeyedCollectionDescriptor, SequenceCollectionDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, TypeDiscriminator, UnknownDerivedTypeHandling, DerivedTypeSpec, PolymorphismSpec, JsonReadOptions, JsonWriteOptions, NumberTypeName, JsonConverter, SerializerContextOptions, } from "./types.ts";
2
2
  export { SerializerContext } from "./serializer-context.ts";
3
3
  export { JsonSerializer, BoundSerializer } from "./json-serializer.ts";
4
4
  export { PropertyNamingPolicy } from "./property-naming-policy.ts";
@@ -1,4 +1,4 @@
1
- import type { TypeSpec, ValueSpec, JsonConverter } from "./types.ts";
1
+ import type { TypeSpec, ValueSpec, JsonTypeInfo, JsonConverter } from "./types.ts";
2
2
  import type { SerializerContext } from "./serializer-context.ts";
3
3
  /**
4
4
  * A bound serializer that uses a SerializerContext to resolve custom converters
@@ -13,6 +13,8 @@ export declare class BoundSerializer {
13
13
  serialize<T>(value: T | null, spec: TypeSpec<T>): Record<string, unknown> | null;
14
14
  /** Serialize a non-object root (collection, map, primitive, …) to a JSON-safe value. */
15
15
  serialize<T>(value: T, spec: ValueSpec<T>): unknown;
16
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
17
+ serializeText<T>(value: T | null, spec: JsonTypeInfo<T>): string;
16
18
  /**
17
19
  * Deserialize a parsed JSON value into a typed instance; JSON `null` reads
18
20
  * as `null`, except for a struct contract (`valueType`), which throws
@@ -65,6 +67,15 @@ export declare class JsonSerializer {
65
67
  static serialize<T>(value: T | null, spec: TypeSpec<T>, converters?: readonly JsonConverter[]): Record<string, unknown> | null;
66
68
  /** Serialize a non-object root (collection, map, primitive, …) to a JSON-safe value. */
67
69
  static serialize<T>(value: T, spec: ValueSpec<T>, converters?: readonly JsonConverter[]): unknown;
70
+ /**
71
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
72
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
73
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
74
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
75
+ * integers with their exact digits, `null` as `null`. NaN and the
76
+ * infinities throw `ArgumentException`, as STJ throws for them.
77
+ */
78
+ static serializeText<T>(value: T | null, spec: JsonTypeInfo<T>, converters?: readonly JsonConverter[]): string;
68
79
  /**
69
80
  * Deserialize a parsed JSON value (`JSON.parse`'s tree) into a typed
70
81
  * instance using the given spec. `JSON.parse` has already rounded every
@@ -3,6 +3,8 @@ import { specNumberTextLeaves } from "./exact-number-reads.js";
3
3
  import { mayHoldNumberTextLeaf, parseJsonText, readJsonText } from "./json-text-reader.js";
4
4
  import { readNull } from "./null-reads.js";
5
5
  import { isValueSpec } from "./spec-kind.js";
6
+ import { writeJsonText } from "./json-text-writer.js";
7
+ import { throwIfNull } from "../argument-guards.js";
6
8
  /**
7
9
  * Serializes through either spec kind: an object contract walks its
8
10
  * properties, and writes a `null` value as JSON `null` (FR-037); a value root
@@ -46,6 +48,8 @@ function deserializeWithInfo(data, spec, converters, treeNumbers) {
46
48
  * text throws STJ's `JsonException` on every path.
47
49
  */
48
50
  function deserializeTextWithInfo(text, spec, converters) {
51
+ throwIfNull(text, "json");
52
+ throwIfNull(spec, "jsonTypeInfo");
49
53
  const leaves = specNumberTextLeaves(spec);
50
54
  const readsExactTree = leaves !== undefined && mayHoldNumberTextLeaf(text, leaves);
51
55
  if (readsExactTree) {
@@ -53,6 +57,16 @@ function deserializeTextWithInfo(text, spec, converters) {
53
57
  }
54
58
  return deserializeWithInfo(parseJsonText(text), spec, converters);
55
59
  }
60
+ /**
61
+ * Writes JSON text as System.Text.Json's `Serialize(value, JsonTypeInfo<T>)`
62
+ * does (#741): the tree `serialize` builds, written by `writeJsonText`
63
+ * (STJ's escaping and number text, not `JSON.stringify`'s), laid out as the spec's
64
+ * `writeOptions` say (`WriteIndented` and friends, #752).
65
+ */
66
+ function serializeTextWithInfo(value, spec, converters) {
67
+ throwIfNull(spec, "jsonTypeInfo");
68
+ return writeJsonText(serializeWithInfo(value, spec, converters), spec.writeOptions);
69
+ }
56
70
  /**
57
71
  * A bound serializer that uses a SerializerContext to resolve custom converters
58
72
  * and look up specs by constructor.
@@ -65,6 +79,10 @@ export class BoundSerializer {
65
79
  serialize(value, spec) {
66
80
  return serializeWithInfo(value, spec, this.context.converters);
67
81
  }
82
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
83
+ serializeText(value, spec) {
84
+ return serializeTextWithInfo(value, spec, this.context.converters);
85
+ }
68
86
  deserialize(data, spec) {
69
87
  return deserializeWithInfo(data, spec, this.context.converters);
70
88
  }
@@ -101,6 +119,17 @@ export class JsonSerializer {
101
119
  static serialize(value, spec, converters) {
102
120
  return serializeWithInfo(value, spec, converters);
103
121
  }
122
+ /**
123
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
124
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
125
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
126
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
127
+ * integers with their exact digits, `null` as `null`. NaN and the
128
+ * infinities throw `ArgumentException`, as STJ throws for them.
129
+ */
130
+ static serializeText(value, spec, converters) {
131
+ return serializeTextWithInfo(value, spec, converters);
132
+ }
104
133
  static deserialize(data, spec, converters) {
105
134
  return deserializeWithInfo(data, spec, converters);
106
135
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Writes the tree `JsonSerializer.serialize` returns as the JSON text
3
+ * System.Text.Json's `JsonSerializer.Serialize(value, JsonTypeInfo<T>)`
4
+ * writes with its default options (#741, measured on .NET 10):
5
+ *
6
+ * - no whitespace, unless the context writes indented text (#752): `writeIndented` puts each
7
+ * array element and each property on its own line, indented by `indentSize` copies of
8
+ * `indentCharacter` per level (a space and 2 by default), with `newLine` (`"\n"` by default)
9
+ * between lines, `": "` after a property name, and `[]` / `{}` for an empty container;
10
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
11
+ * `\r` and `\t` keep their short escapes; every other control character,
12
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
13
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
14
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
15
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
16
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
17
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
18
+ */
19
+ import type { JsonWriteOptions } from "./types.ts";
20
+ /**
21
+ * The JSON text of `tree`, as System.Text.Json writes it: compact, or laid out as
22
+ * `options` say (the context's `WriteIndented` family, #752).
23
+ */
24
+ export declare function writeJsonText(tree: unknown, options?: JsonWriteOptions): string;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Writes the tree `JsonSerializer.serialize` returns as the JSON text
3
+ * System.Text.Json's `JsonSerializer.Serialize(value, JsonTypeInfo<T>)`
4
+ * writes with its default options (#741, measured on .NET 10):
5
+ *
6
+ * - no whitespace, unless the context writes indented text (#752): `writeIndented` puts each
7
+ * array element and each property on its own line, indented by `indentSize` copies of
8
+ * `indentCharacter` per level (a space and 2 by default), with `newLine` (`"\n"` by default)
9
+ * between lines, `": "` after a property name, and `[]` / `{}` for an empty container;
10
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
11
+ * `\r` and `\t` keep their short escapes; every other control character,
12
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
13
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
14
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
15
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
16
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
17
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
18
+ */
19
+ import { formatDouble } from "../double-format.js";
20
+ import { ArgumentException } from "../exceptions/argument-exception.js";
21
+ import { rawJsonTextOf } from "./exact-json-number.js";
22
+ /** The message STJ throws for a NaN or infinite number written as JSON. */
23
+ const NON_FINITE_NUMBER_MESSAGE = ".NET number values such as positive and negative infinity cannot be written as valid JSON. " +
24
+ "To make it work when using 'JsonSerializer', consider specifying " +
25
+ "'JsonNumberHandling.AllowNamedFloatingPointLiterals' " +
26
+ "(see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).";
27
+ const COMPACT = {
28
+ lineStart: () => "",
29
+ lineEnd: () => "",
30
+ afterColon: "",
31
+ };
32
+ function indentedLayout(options) {
33
+ const unit = (options.indentCharacter ?? " ").repeat(options.indentSize ?? 2);
34
+ const newLine = options.newLine ?? "\n";
35
+ return {
36
+ lineStart: (depth) => newLine + unit.repeat(depth),
37
+ lineEnd: (depth) => newLine + unit.repeat(depth - 1),
38
+ afterColon: " ",
39
+ };
40
+ }
41
+ /**
42
+ * The JSON text of `tree`, as System.Text.Json writes it: compact, or laid out as
43
+ * `options` say (the context's `WriteIndented` family, #752).
44
+ */
45
+ export function writeJsonText(tree, options) {
46
+ const parts = [];
47
+ const layout = options?.writeIndented ? indentedLayout(options) : COMPACT;
48
+ writeValue(tree, parts, layout, 0);
49
+ return parts.join("");
50
+ }
51
+ function writeValue(value, parts, layout, depth) {
52
+ if (value == null) {
53
+ parts.push("null");
54
+ return;
55
+ }
56
+ switch (typeof value) {
57
+ case "string":
58
+ parts.push(quoted(value));
59
+ return;
60
+ case "number":
61
+ parts.push(numberText(value));
62
+ return;
63
+ case "bigint":
64
+ case "boolean":
65
+ parts.push(String(value));
66
+ return;
67
+ }
68
+ writeObject(value, parts, layout, depth);
69
+ }
70
+ function writeObject(value, parts, layout, depth) {
71
+ const rawText = rawJsonTextOf(value);
72
+ if (rawText !== undefined) {
73
+ parts.push(rawText);
74
+ return;
75
+ }
76
+ const toJson = value.toJSON;
77
+ if (typeof toJson === "function") {
78
+ writeValue(toJson.call(value), parts, layout, depth);
79
+ return;
80
+ }
81
+ if (Array.isArray(value)) {
82
+ writeArray(value, parts, layout, depth + 1);
83
+ return;
84
+ }
85
+ writeProperties(value, parts, layout, depth + 1);
86
+ }
87
+ /** `depth` is the nesting level of the array's elements. */
88
+ function writeArray(items, parts, layout, depth) {
89
+ parts.push("[");
90
+ items.forEach((item, index) => {
91
+ if (index > 0) {
92
+ parts.push(",");
93
+ }
94
+ parts.push(layout.lineStart(depth));
95
+ writeValue(item, parts, layout, depth);
96
+ });
97
+ if (items.length > 0) {
98
+ parts.push(layout.lineEnd(depth));
99
+ }
100
+ parts.push("]");
101
+ }
102
+ /**
103
+ * An object's own enumerable properties; an `undefined` one is skipped, as `JSON.stringify`
104
+ * skips it. `depth` is the nesting level of the properties.
105
+ */
106
+ function writeProperties(object, parts, layout, depth) {
107
+ let first = true;
108
+ parts.push("{");
109
+ for (const key of Object.keys(object)) {
110
+ const member = object[key];
111
+ if (member === undefined) {
112
+ continue;
113
+ }
114
+ if (!first) {
115
+ parts.push(",");
116
+ }
117
+ first = false;
118
+ parts.push(layout.lineStart(depth), quoted(key), ":", layout.afterColon);
119
+ writeValue(member, parts, layout, depth);
120
+ }
121
+ if (!first) {
122
+ parts.push(layout.lineEnd(depth));
123
+ }
124
+ parts.push("}");
125
+ }
126
+ function numberText(value) {
127
+ if (!Number.isFinite(value)) {
128
+ throw new ArgumentException(NON_FINITE_NUMBER_MESSAGE);
129
+ }
130
+ return formatDouble(value);
131
+ }
132
+ function quoted(text) {
133
+ for (let index = 0; index < text.length; index++) {
134
+ if (isEscaped(text.charCodeAt(index))) {
135
+ return `"${escaped(text)}"`;
136
+ }
137
+ }
138
+ return `"${text}"`;
139
+ }
140
+ /** Whether `JavaScriptEncoder.Default` escapes the UTF-16 code unit `code`. */
141
+ function isEscaped(code) {
142
+ switch (code) {
143
+ case 0x22: // "
144
+ case 0x26: // &
145
+ case 0x27: // '
146
+ case 0x2b: // +
147
+ case 0x3c: // <
148
+ case 0x3e: // >
149
+ case 0x5c: // backslash
150
+ case 0x60: // `
151
+ return true;
152
+ default:
153
+ return code < 0x20 || code >= 0x7f;
154
+ }
155
+ }
156
+ /** The short escape STJ keeps for `code`, or `undefined`. */
157
+ function shortEscapeOf(code) {
158
+ switch (code) {
159
+ case 0x08:
160
+ return "\\b";
161
+ case 0x09:
162
+ return "\\t";
163
+ case 0x0a:
164
+ return "\\n";
165
+ case 0x0c:
166
+ return "\\f";
167
+ case 0x0d:
168
+ return "\\r";
169
+ case 0x5c:
170
+ return "\\\\";
171
+ default:
172
+ return undefined;
173
+ }
174
+ }
175
+ function escaped(text) {
176
+ let result = "";
177
+ for (let index = 0; index < text.length; index++) {
178
+ const code = text.charCodeAt(index);
179
+ if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
180
+ result += unicodeEscape(code) + unicodeEscape(text.charCodeAt(index + 1));
181
+ index++;
182
+ }
183
+ else {
184
+ result += escapedCodeUnit(code);
185
+ }
186
+ }
187
+ return result;
188
+ }
189
+ function escapedCodeUnit(code) {
190
+ const shortEscape = shortEscapeOf(code);
191
+ if (shortEscape !== undefined) {
192
+ return shortEscape;
193
+ }
194
+ if (isHighSurrogate(code) || isLowSurrogate(code)) {
195
+ return unicodeEscape(0xfffd);
196
+ }
197
+ return isEscaped(code) ? unicodeEscape(code) : String.fromCharCode(code);
198
+ }
199
+ function unicodeEscape(code) {
200
+ return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
201
+ }
202
+ function isHighSurrogate(code) {
203
+ return code >= 0xd800 && code <= 0xdbff;
204
+ }
205
+ function isLowSurrogate(code) {
206
+ return code >= 0xdc00 && code <= 0xdfff;
207
+ }