metano-runtime 3.0.2 → 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 (131) 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/decimal-parsing.d.ts +12 -0
  21. package/dist/system/decimal-parsing.js +86 -0
  22. package/dist/system/exceptions/index.d.ts +1 -0
  23. package/dist/system/exceptions/index.js +1 -0
  24. package/dist/system/exceptions/throw-error.d.ts +7 -0
  25. package/dist/system/exceptions/throw-error.js +9 -0
  26. package/dist/system/int64.d.ts +6 -0
  27. package/dist/system/int64.js +18 -9
  28. package/dist/system/integer-division.d.ts +12 -4
  29. package/dist/system/integer-division.js +19 -2
  30. package/dist/system/json/json-serializer.d.ts +12 -1
  31. package/dist/system/json/json-serializer.js +28 -0
  32. package/dist/system/json/json-text-writer.d.ts +17 -0
  33. package/dist/system/json/json-text-writer.js +175 -0
  34. package/dist/system/json/number-from-string.js +20 -6
  35. package/dist/system/json/numeric-converters.js +41 -0
  36. package/dist/system/linq/grouping.d.ts +12 -0
  37. package/dist/system/linq/grouping.js +42 -0
  38. package/dist/system/linq/index.d.ts +4 -3
  39. package/dist/system/linq/index.js +3 -2
  40. package/dist/system/linq/linq.js +20 -1
  41. package/dist/system/linq/lookup.d.ts +17 -0
  42. package/dist/system/linq/lookup.js +20 -0
  43. package/dist/system/linq/operators.d.ts +12 -4
  44. package/dist/system/linq/operators.js +61 -15
  45. package/dist/system/linq/terminals.d.ts +29 -2
  46. package/dist/system/linq/terminals.js +71 -3
  47. package/dist/system/linq/types.d.ts +27 -4
  48. package/dist/system/math.d.ts +7 -0
  49. package/dist/system/math.js +14 -0
  50. package/dist/system/number-parsing.d.ts +16 -4
  51. package/dist/system/number-parsing.js +21 -4
  52. package/dist-unchecked/system/char-members.d.ts +23 -0
  53. package/dist-unchecked/system/char-members.js +46 -0
  54. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  55. package/dist-unchecked/system/collections/hash-core.js +24 -0
  56. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  57. package/dist-unchecked/system/collections/helpers.js +28 -2
  58. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  59. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  60. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  61. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  62. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  63. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  64. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  65. package/dist-unchecked/system/collections/list.d.ts +3 -0
  66. package/dist-unchecked/system/collections/list.js +7 -0
  67. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  68. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  69. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  70. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  71. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  72. package/dist-unchecked/system/decimal-parsing.js +86 -0
  73. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  74. package/dist-unchecked/system/exceptions/index.js +1 -0
  75. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  76. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  77. package/dist-unchecked/system/int64.d.ts +6 -0
  78. package/dist-unchecked/system/int64.js +18 -9
  79. package/dist-unchecked/system/integer-division.d.ts +12 -4
  80. package/dist-unchecked/system/integer-division.js +19 -2
  81. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  82. package/dist-unchecked/system/json/json-serializer.js +28 -0
  83. package/dist-unchecked/system/json/json-text-writer.d.ts +17 -0
  84. package/dist-unchecked/system/json/json-text-writer.js +175 -0
  85. package/dist-unchecked/system/json/number-from-string.js +20 -6
  86. package/dist-unchecked/system/json/numeric-converters.js +41 -0
  87. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  88. package/dist-unchecked/system/linq/grouping.js +42 -0
  89. package/dist-unchecked/system/linq/index.d.ts +4 -3
  90. package/dist-unchecked/system/linq/index.js +3 -2
  91. package/dist-unchecked/system/linq/linq.js +20 -1
  92. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  93. package/dist-unchecked/system/linq/lookup.js +20 -0
  94. package/dist-unchecked/system/linq/operators.d.ts +12 -4
  95. package/dist-unchecked/system/linq/operators.js +61 -15
  96. package/dist-unchecked/system/linq/terminals.d.ts +29 -2
  97. package/dist-unchecked/system/linq/terminals.js +71 -3
  98. package/dist-unchecked/system/linq/types.d.ts +27 -4
  99. package/dist-unchecked/system/math.d.ts +7 -0
  100. package/dist-unchecked/system/math.js +14 -0
  101. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  102. package/dist-unchecked/system/number-parsing.js +21 -4
  103. package/package.json +1 -1
  104. package/src/system/char-members.ts +57 -0
  105. package/src/system/collections/hash-core.ts +31 -0
  106. package/src/system/collections/helpers.ts +39 -4
  107. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  108. package/src/system/collections/immutable-list-core.ts +23 -1
  109. package/src/system/collections/immutable-storage.ts +8 -1
  110. package/src/system/collections/interfaces.ts +16 -0
  111. package/src/system/collections/list.ts +9 -0
  112. package/src/system/collections/read-only-list.ts +35 -1
  113. package/src/system/collections/sorted-list.ts +15 -1
  114. package/src/system/decimal-parsing.ts +109 -0
  115. package/src/system/exceptions/index.ts +1 -0
  116. package/src/system/exceptions/throw-error.ts +9 -0
  117. package/src/system/int64.ts +27 -10
  118. package/src/system/integer-division.ts +43 -6
  119. package/src/system/json/json-serializer.ts +41 -0
  120. package/src/system/json/json-text-writer.ts +224 -0
  121. package/src/system/json/number-from-string.ts +26 -6
  122. package/src/system/json/numeric-converters.ts +55 -0
  123. package/src/system/linq/grouping.ts +77 -0
  124. package/src/system/linq/index.ts +8 -0
  125. package/src/system/linq/linq.ts +23 -1
  126. package/src/system/linq/lookup.ts +34 -0
  127. package/src/system/linq/operators.ts +78 -15
  128. package/src/system/linq/terminals.ts +85 -3
  129. package/src/system/linq/types.ts +32 -0
  130. package/src/system/math.ts +19 -0
  131. package/src/system/number-parsing.ts +24 -4
@@ -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
+ }
@@ -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
- 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,15 @@ 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).
64
+ */
65
+ function serializeTextWithInfo(value, spec, converters) {
66
+ throwIfNull(spec, "jsonTypeInfo");
67
+ return writeJsonText(serializeWithInfo(value, spec, converters));
68
+ }
56
69
  /**
57
70
  * A bound serializer that uses a SerializerContext to resolve custom converters
58
71
  * and look up specs by constructor.
@@ -65,6 +78,10 @@ export class BoundSerializer {
65
78
  serialize(value, spec) {
66
79
  return serializeWithInfo(value, spec, this.context.converters);
67
80
  }
81
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
82
+ serializeText(value, spec) {
83
+ return serializeTextWithInfo(value, spec, this.context.converters);
84
+ }
68
85
  deserialize(data, spec) {
69
86
  return deserializeWithInfo(data, spec, this.context.converters);
70
87
  }
@@ -101,6 +118,17 @@ export class JsonSerializer {
101
118
  static serialize(value, spec, converters) {
102
119
  return serializeWithInfo(value, spec, converters);
103
120
  }
121
+ /**
122
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
123
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
124
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
125
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
126
+ * integers with their exact digits, `null` as `null`. NaN and the
127
+ * infinities throw `ArgumentException`, as STJ throws for them.
128
+ */
129
+ static serializeText(value, spec, converters) {
130
+ return serializeTextWithInfo(value, spec, converters);
131
+ }
104
132
  static deserialize(data, spec, converters) {
105
133
  return deserializeWithInfo(data, spec, converters);
106
134
  }
@@ -0,0 +1,17 @@
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;
7
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
8
+ * `\r` and `\t` keep their short escapes; every other control character,
9
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
10
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
11
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
12
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
13
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
14
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
15
+ */
16
+ /** The JSON text of `tree`, as System.Text.Json writes it. */
17
+ export declare function writeJsonText(tree: unknown): string;
@@ -0,0 +1,175 @@
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;
7
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
8
+ * `\r` and `\t` keep their short escapes; every other control character,
9
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
10
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
11
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
12
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
13
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
14
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
15
+ */
16
+ import { formatDouble } from "../double-format.js";
17
+ import { ArgumentException } from "../exceptions/argument-exception.js";
18
+ import { rawJsonTextOf } from "./exact-json-number.js";
19
+ /** The message STJ throws for a NaN or infinite number written as JSON. */
20
+ const NON_FINITE_NUMBER_MESSAGE = ".NET number values such as positive and negative infinity cannot be written as valid JSON. " +
21
+ "To make it work when using 'JsonSerializer', consider specifying " +
22
+ "'JsonNumberHandling.AllowNamedFloatingPointLiterals' " +
23
+ "(see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).";
24
+ /** The JSON text of `tree`, as System.Text.Json writes it. */
25
+ export function writeJsonText(tree) {
26
+ const parts = [];
27
+ writeValue(tree, parts);
28
+ return parts.join("");
29
+ }
30
+ function writeValue(value, parts) {
31
+ if (value == null) {
32
+ parts.push("null");
33
+ return;
34
+ }
35
+ switch (typeof value) {
36
+ case "string":
37
+ parts.push(quoted(value));
38
+ return;
39
+ case "number":
40
+ parts.push(numberText(value));
41
+ return;
42
+ case "bigint":
43
+ case "boolean":
44
+ parts.push(String(value));
45
+ return;
46
+ }
47
+ writeObject(value, parts);
48
+ }
49
+ function writeObject(value, parts) {
50
+ const rawText = rawJsonTextOf(value);
51
+ if (rawText !== undefined) {
52
+ parts.push(rawText);
53
+ return;
54
+ }
55
+ const toJson = value.toJSON;
56
+ if (typeof toJson === "function") {
57
+ writeValue(toJson.call(value), parts);
58
+ return;
59
+ }
60
+ if (Array.isArray(value)) {
61
+ writeArray(value, parts);
62
+ return;
63
+ }
64
+ writeProperties(value, parts);
65
+ }
66
+ function writeArray(items, parts) {
67
+ parts.push("[");
68
+ items.forEach((item, index) => {
69
+ if (index > 0) {
70
+ parts.push(",");
71
+ }
72
+ writeValue(item, parts);
73
+ });
74
+ parts.push("]");
75
+ }
76
+ /** An object's own enumerable properties; an `undefined` one is skipped, as `JSON.stringify` skips it. */
77
+ function writeProperties(object, parts) {
78
+ let first = true;
79
+ parts.push("{");
80
+ for (const key of Object.keys(object)) {
81
+ const member = object[key];
82
+ if (member === undefined) {
83
+ continue;
84
+ }
85
+ if (!first) {
86
+ parts.push(",");
87
+ }
88
+ first = false;
89
+ parts.push(quoted(key), ":");
90
+ writeValue(member, parts);
91
+ }
92
+ parts.push("}");
93
+ }
94
+ function numberText(value) {
95
+ if (!Number.isFinite(value)) {
96
+ throw new ArgumentException(NON_FINITE_NUMBER_MESSAGE);
97
+ }
98
+ return formatDouble(value);
99
+ }
100
+ function quoted(text) {
101
+ for (let index = 0; index < text.length; index++) {
102
+ if (isEscaped(text.charCodeAt(index))) {
103
+ return `"${escaped(text)}"`;
104
+ }
105
+ }
106
+ return `"${text}"`;
107
+ }
108
+ /** Whether `JavaScriptEncoder.Default` escapes the UTF-16 code unit `code`. */
109
+ function isEscaped(code) {
110
+ switch (code) {
111
+ case 0x22: // "
112
+ case 0x26: // &
113
+ case 0x27: // '
114
+ case 0x2b: // +
115
+ case 0x3c: // <
116
+ case 0x3e: // >
117
+ case 0x5c: // backslash
118
+ case 0x60: // `
119
+ return true;
120
+ default:
121
+ return code < 0x20 || code >= 0x7f;
122
+ }
123
+ }
124
+ /** The short escape STJ keeps for `code`, or `undefined`. */
125
+ function shortEscapeOf(code) {
126
+ switch (code) {
127
+ case 0x08:
128
+ return "\\b";
129
+ case 0x09:
130
+ return "\\t";
131
+ case 0x0a:
132
+ return "\\n";
133
+ case 0x0c:
134
+ return "\\f";
135
+ case 0x0d:
136
+ return "\\r";
137
+ case 0x5c:
138
+ return "\\\\";
139
+ default:
140
+ return undefined;
141
+ }
142
+ }
143
+ function escaped(text) {
144
+ let result = "";
145
+ for (let index = 0; index < text.length; index++) {
146
+ const code = text.charCodeAt(index);
147
+ if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
148
+ result += unicodeEscape(code) + unicodeEscape(text.charCodeAt(index + 1));
149
+ index++;
150
+ }
151
+ else {
152
+ result += escapedCodeUnit(code);
153
+ }
154
+ }
155
+ return result;
156
+ }
157
+ function escapedCodeUnit(code) {
158
+ const shortEscape = shortEscapeOf(code);
159
+ if (shortEscape !== undefined) {
160
+ return shortEscape;
161
+ }
162
+ if (isHighSurrogate(code) || isLowSurrogate(code)) {
163
+ return unicodeEscape(0xfffd);
164
+ }
165
+ return isEscaped(code) ? unicodeEscape(code) : String.fromCharCode(code);
166
+ }
167
+ function unicodeEscape(code) {
168
+ return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
169
+ }
170
+ function isHighSurrogate(code) {
171
+ return code >= 0xd800 && code <= 0xdbff;
172
+ }
173
+ function isLowSurrogate(code) {
174
+ return code >= 0xdc00 && code <= 0xdfff;
175
+ }
@@ -75,10 +75,10 @@ function isWithinRange(value, min, max) {
75
75
  }
76
76
  /**
77
77
  * Reads the floating-point grammar; `staysFinite` rejects a value that
78
- * overflows the target type. The value keeps double precision, as a JSON
79
- * number read into a `Single` does.
78
+ * overflows the target type, and `round` brings the double to the target's
79
+ * precision (a `Single` rounds to single precision, #695).
80
80
  */
81
- function floatingPointReader(staysFinite) {
81
+ function floatingPointReader(staysFinite, round) {
82
82
  return (text) => {
83
83
  const literal = FLOATING_POINT_LITERALS.get(text);
84
84
  if (literal !== undefined) {
@@ -89,12 +89,26 @@ function floatingPointReader(staysFinite) {
89
89
  return undefined;
90
90
  }
91
91
  const value = Number(text);
92
- return staysFinite(parts, value) ? value : undefined;
92
+ return staysFinite(parts, value) ? round(value) : undefined;
93
93
  };
94
94
  }
95
95
  function fitsDouble(_, value) {
96
96
  return Number.isFinite(value);
97
97
  }
98
+ /** The largest `Single`, `(2 − 2^-23) × 2^127`. */
99
+ const SINGLE_MAX_VALUE = 3.4028234663852886e38;
100
+ /**
101
+ * A finite double that {@link fitsSingle} accepted, rounded to single
102
+ * precision (#695). Only the threshold double itself would round to an
103
+ * infinity (a tie to even); its text was below the threshold, so it is
104
+ * `±Single.MaxValue`.
105
+ */
106
+ function roundToFiniteSingle(value) {
107
+ const single = Math.fround(value);
108
+ return Number.isFinite(single) || !Number.isFinite(value)
109
+ ? single
110
+ : Math.sign(single) * SINGLE_MAX_VALUE;
111
+ }
98
112
  /**
99
113
  * Whether the text stays below the `Single` overflow threshold. The double
100
114
  * is already rounded, so it decides every case but one: a double equal to
@@ -173,8 +187,8 @@ const INTEGER_TOKEN_READERS = /* @__PURE__ */ lazyValue(() => integerReadersOf((
173
187
  : SIGNED_INTEGER_TOKEN_PATTERN, () => (value) => value));
174
188
  const NUMBER_TEXT_READERS = /* @__PURE__ */ lazyValue(() => ({
175
189
  ...STRICT_INTEGER_READERS(),
176
- "System.Single": floatingPointReader(fitsSingle),
177
- "System.Double": floatingPointReader(fitsDouble),
190
+ "System.Single": floatingPointReader(fitsSingle, roundToFiniteSingle),
191
+ "System.Double": floatingPointReader(fitsDouble, (value) => value),
178
192
  }));
179
193
  /**
180
194
  * The number `text` spells as a `numberType`, or `undefined` when System.Text.Json
@@ -1,3 +1,4 @@
1
+ import { formatSingle } from "../double-format.js";
1
2
  import { JsonException } from "./errors.js";
2
3
  import { isDecimalText, readDecimalText } from "./decimal-text.js";
3
4
  import { exactBigIntLeafOf, exactNumberTextOf, JsonNonIntegerNumber, numberOfTreeValue, writeExactNumber, } from "./exact-json-number.js";
@@ -27,6 +28,8 @@ const passthroughConverter = {
27
28
  };
28
29
  /** The CLR name of a C# `char`, which reads as a one-code-unit `string`. */
29
30
  const CHAR_TYPE_NAME = "System.Char";
31
+ /** The CLR name of a C# `float`, whose values read rounded to single precision. */
32
+ const SINGLE_TYPE_NAME = "System.Single";
30
33
  /**
31
34
  * A `primitive`: values pass through both ways, except that a JSON string
32
35
  * for a numeric `numberType` is read by System.Text.Json's grammar when the
@@ -39,6 +42,9 @@ export function primitiveConverterOf(descriptor, readOptions, errorTypeName = de
39
42
  if (descriptor.typeName === CHAR_TYPE_NAME) {
40
43
  return charConverterOf(errorTypeName);
41
44
  }
45
+ if (numberType === SINGLE_TYPE_NAME) {
46
+ return singleConverterOf(readOptions, errorTypeName);
47
+ }
42
48
  if (numberType === undefined || !readsNumbersFromStrings(readOptions)) {
43
49
  return passthroughConverter;
44
50
  }
@@ -56,6 +62,41 @@ export function primitiveConverterOf(descriptor, readOptions, errorTypeName = de
56
62
  },
57
63
  };
58
64
  }
65
+ /**
66
+ * A `float`: a JSON number reads rounded to single precision, as
67
+ * System.Text.Json parses it into a `Single` (#695), and a string reads
68
+ * through the number grammar (which rounds too) when the context reads
69
+ * numbers from strings. A finite value writes the shortest text that reads
70
+ * back as the same `float`, as System.Text.Json writes it (`0.1`, not the
71
+ * double `0.10000000149011612`), through the exact-number leaf. A
72
+ * non-finite value passes through: System.Text.Json throws for it without
73
+ * `AllowNamedFloatingPointLiterals`, which Metano does not mirror.
74
+ */
75
+ function singleConverterOf(readOptions, errorTypeName) {
76
+ const readsStrings = readsNumbersFromStrings(readOptions);
77
+ return {
78
+ serialize: (value) => typeof value === "number" && Number.isFinite(value)
79
+ ? writeExactNumber(formatSingle(value), () => Math.fround(value))
80
+ : passthroughConverter.serialize(value),
81
+ deserialize: (value) => {
82
+ if (typeof value === "number") {
83
+ return Math.fround(value);
84
+ }
85
+ const exact = exactNumberTextOf(value);
86
+ if (exact !== undefined) {
87
+ return Math.fround(Number(exact));
88
+ }
89
+ if (typeof value !== "string" || !readsStrings) {
90
+ return value;
91
+ }
92
+ const number = readNumberTextAsNumber(value, SINGLE_TYPE_NAME);
93
+ if (number === undefined) {
94
+ throw cannotConvert(SINGLE_TYPE_NAME, errorTypeName);
95
+ }
96
+ return number;
97
+ },
98
+ };
99
+ }
59
100
  /**
60
101
  * A `long` / `ulong` — the `int64` descriptor (spec 012 FR-050), whatever
61
102
  * the read options:
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The key bucketing `groupBy`, `toLookup` and `join` share: the elements of a source
3
+ * under the equality .NET uses for a key (`EqualityComparer<K>.Default`, or a user
4
+ * comparer), in the order the keys are first seen, each bucket in source order.
5
+ */
6
+ import type { IEqualityComparer } from "../collections/default-comparer.ts";
7
+ import { HashCore } from "../collections/hash-core.ts";
8
+ import type { Grouping } from "./types.ts";
9
+ /** Elements of `source` bucketed by `keySelector`; a `null` key is skipped when `skipNullKeys`. */
10
+ export declare function bucketsOf<T, K, V = T>(source: Iterable<T>, keySelector: (item: T) => K, comparer: IEqualityComparer<K> | null | undefined, elementSelector?: (item: T) => V, skipNullKeys?: boolean): HashCore<K, V[]>;
11
+ /** The groupings of `buckets`: an iterable bucket that also reads `.key`. */
12
+ export declare function groupingsOf<K, T>(buckets: HashCore<K, T[]>): Generator<Grouping<K, T>>;
@@ -0,0 +1,42 @@
1
+ import { HashCore } from "../collections/hash-core.js";
2
+ /**
3
+ * `comparer` as .NET's `Lookup` uses it: a `null` key hashes to 0 without asking the
4
+ * comparer, which may throw on it (`GetHashCode(string value) => value.Length`).
5
+ */
6
+ function nullSafe(comparer) {
7
+ return comparer === null || comparer === undefined
8
+ ? comparer
9
+ : {
10
+ equals: (a, b) => comparer.equals(a, b),
11
+ getHashCode: (key) => key === null || key === undefined ? 0 : comparer.getHashCode(key),
12
+ };
13
+ }
14
+ /** Elements of `source` bucketed by `keySelector`; a `null` key is skipped when `skipNullKeys`. */
15
+ export function bucketsOf(source, keySelector, comparer, elementSelector, skipNullKeys = false) {
16
+ const buckets = new HashCore(nullSafe(comparer));
17
+ if (elementSelector === undefined && !skipNullKeys && comparer) {
18
+ return bucketAll(source, keySelector, buckets);
19
+ }
20
+ for (const item of source) {
21
+ const key = keySelector(item);
22
+ if (skipNullKeys && (key === null || key === undefined)) {
23
+ continue;
24
+ }
25
+ buckets.append(key, elementSelector === undefined ? item : elementSelector(item));
26
+ }
27
+ return buckets;
28
+ }
29
+ function bucketAll(source, keySelector, buckets) {
30
+ for (const item of source) {
31
+ buckets.append(keySelector(item), item);
32
+ }
33
+ return buckets;
34
+ }
35
+ /** The groupings of `buckets`: an iterable bucket that also reads `.key`. */
36
+ export function* groupingsOf(buckets) {
37
+ for (const [key, items] of buckets) {
38
+ // `Grouping` is `Iterable<T> & { key }`: the bucket array itself carries the key, so
39
+ // consumers can `for…of` the grouping and read `.key`.
40
+ yield Object.assign(items, { key });
41
+ }
42
+ }
@@ -24,9 +24,10 @@ export type { Stage } from "./linq.ts";
24
24
  export type { BinaryOp, ExprBinary, ExprCall, ExprCapture, ExprConditional, ExprConvert, ExprLambda, ExprLiteral, ExprMember, ExprNew, ExprParam, ExprTree, ExprTypeRef, ExprUnary, QueryableMeta, UnaryOp, } from "./expr-tree.ts";
25
25
  export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.ts";
26
26
  export type { ExprTreeScope } from "./expr-tree-visitor.ts";
27
- export type { AnyOperator, AnyTerminal, OperatorBase, OperatorKind, TerminalBase, TerminalKind, AppendOp, ConcatOp, DistinctByOp, DistinctOp, ExceptOp, GroupByOp, Grouping, IntersectOp, OrderByDescendingOp, OrderByOp, ThenByDescendingOp, ThenByOp, PrependOp, ReverseOp, DefaultIfEmptyOp, SelectManyOp, SelectOp, SkipOp, SkipWhileOp, TakeOp, TakeWhileOp, UnionOp, WhereOp, ZipOp, AggregateTerm, AllTerm, AnyTerm, AverageTerm, AverageInt64Term, ContainsTerm, CountTerm, ElementAtTerm, ElementAtOrDefaultTerm, FirstOrDefaultTerm, FirstTerm, LastOrDefaultTerm, LastTerm, MaxTerm, MaxInt64Term, MaxByTerm, MinTerm, MinInt64Term, MinByTerm, SingleTerm, SingleOrDefaultTerm, SumTerm, SumInt64Term, ToArrayTerm, ToMapTerm, ToSetTerm, ToListTerm, ToDictionaryTerm, ToHashSetTerm, } from "./types.ts";
28
- export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, defaultIfEmpty, } from "./operators.ts";
29
- export { toArray, toMap, toSet, toList, toDictionary, toHashSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.ts";
27
+ export type { AnyOperator, AnyTerminal, OperatorBase, OperatorKind, TerminalBase, TerminalKind, AppendOp, ConcatOp, DistinctByOp, DistinctOp, ExceptOp, GroupByOp, Grouping, IntersectOp, OrderByDescendingOp, OrderByOp, ThenByDescendingOp, ThenByOp, PrependOp, ReverseOp, DefaultIfEmptyOp, SelectManyOp, SelectOp, SkipOp, SkipWhileOp, TakeOp, TakeWhileOp, UnionOp, WhereOp, ZipOp, AggregateTerm, AllTerm, AnyTerm, AverageTerm, AverageInt64Term, ContainsTerm, CountTerm, ElementAtTerm, ElementAtOrDefaultTerm, FirstOrDefaultTerm, FirstTerm, LastOrDefaultTerm, LastTerm, MaxTerm, MaxInt64Term, MaxByTerm, MinTerm, MinInt64Term, MinByTerm, SingleTerm, SingleOrDefaultTerm, SumTerm, SumInt64Term, ToArrayTerm, ToMapTerm, ToSetTerm, ToListTerm, ToDictionaryTerm, ToHashSetTerm, ToLookupTerm, SequenceEqualTerm, JoinOp, } from "./types.ts";
28
+ export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, join, zip, defaultIfEmpty, } from "./operators.ts";
29
+ export { toArray, toMap, toSet, toList, toDictionary, toHashSet, toLookup, sequenceEqual, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.ts";
30
30
  export { averageInt64, averageNullableInt64, maxInt64Of, maxNullableInt64Of, maxUInt64Of, minInt64Of, minNullableInt64Of, minUInt64Of, sumInt64, } from "./int64-terminals.ts";
31
+ export { Lookup } from "./lookup.ts";
31
32
  export { averageDecimal, averageNullableDecimal, sumDecimal } from "./decimal-terminals.ts";
32
33
  export type { DecimalConstructor, DecimalValue } from "./decimal-terminals.ts";
@@ -21,7 +21,8 @@
21
21
  */
22
22
  export { LINQ_STAGES, getStages, linq, stages } from "./linq.js";
23
23
  export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.js";
24
- export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, defaultIfEmpty, } from "./operators.js";
25
- export { toArray, toMap, toSet, toList, toDictionary, toHashSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.js";
24
+ export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, join, zip, defaultIfEmpty, } from "./operators.js";
25
+ export { toArray, toMap, toSet, toList, toDictionary, toHashSet, toLookup, sequenceEqual, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.js";
26
26
  export { averageInt64, averageNullableInt64, maxInt64Of, maxNullableInt64Of, maxUInt64Of, minInt64Of, minNullableInt64Of, minUInt64Of, sumInt64, } from "./int64-terminals.js";
27
+ export { Lookup } from "./lookup.js";
27
28
  export { averageDecimal, averageNullableDecimal, sumDecimal } from "./decimal-terminals.js";
@@ -1,5 +1,6 @@
1
1
  export function linq(source, ...ops) {
2
- const result = ops.reduce((acc, op) => op.apply(acc), source);
2
+ const start = typeof source === "string" ? codeUnitsOf(source) : source;
3
+ const result = ops.reduce((acc, op) => op.apply(acc), start);
3
4
  // Attach the original stage list to the materialized result so an
4
5
  // IQueryable-style consumer can introspect the chain. Skipped for
5
6
  // primitive results (terminals like `count` / `sum` return numbers
@@ -44,3 +45,21 @@ export function stages(...ops) {
44
45
  return ops;
45
46
  }
46
47
  /* eslint-enable @typescript-eslint/no-explicit-any */
48
+ /**
49
+ * The UTF-16 code units of `text`, read lazily: a C# string enumerates them,
50
+ * where a JS string's own iterator yields code points, so a surrogate pair
51
+ * would be one element (#695). No array is built, so an early-exit operator
52
+ * (`first`, `any`, `take`) reads only the units it needs.
53
+ */
54
+ function codeUnitsOf(text) {
55
+ return {
56
+ [Symbol.iterator]: () => {
57
+ let index = 0;
58
+ return {
59
+ next: () => index < text.length
60
+ ? { done: false, value: text[index++] }
61
+ : { done: true, value: undefined },
62
+ };
63
+ },
64
+ };
65
+ }