@opencode/codemode 2.2.6 → 2.3.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 (197) hide show
  1. package/README.md +115 -29
  2. package/dist/{vm/async.d.ts → async.d.ts} +1 -1
  3. package/dist/codemode.d.ts +13 -22
  4. package/dist/codemode.js +18 -39
  5. package/dist/data.d.ts +4 -19
  6. package/dist/data.js +1 -82
  7. package/dist/extension.d.ts +20 -1
  8. package/dist/extension.js +14 -1
  9. package/dist/{vm/host.d.ts → host.d.ts} +5 -2
  10. package/dist/{vm/host.js → host.js} +9 -4
  11. package/dist/index.d.ts +1 -1
  12. package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
  13. package/dist/{vm/prelude → prelude}/helpers.js +1 -1
  14. package/dist/{vm/runtime → runtime}/driver.d.ts +18 -8
  15. package/dist/{vm/runtime → runtime}/driver.js +90 -20
  16. package/dist/{vm/runtime → runtime}/errors.js +2 -2
  17. package/dist/{vm/runtime → runtime}/execute.d.ts +18 -9
  18. package/dist/{vm/runtime → runtime}/execute.js +45 -15
  19. package/dist/{vm/runtime → runtime}/extensions.d.ts +2 -2
  20. package/dist/{vm/runtime → runtime}/extensions.js +121 -19
  21. package/dist/{vm/runtime → runtime}/globals.js +1 -1
  22. package/dist/{vm/runtime → runtime}/interpreter.d.ts +4 -1
  23. package/dist/{vm/runtime → runtime}/interpreter.js +2 -0
  24. package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
  25. package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
  26. package/dist/{vm/runtime → runtime}/objects.js +1 -1
  27. package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
  28. package/dist/{vm/runtime → runtime}/operations.js +1 -1
  29. package/dist/scan.js +2 -2
  30. package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +16 -4
  31. package/dist/{vm/scheduler.js → scheduler.js} +13 -2
  32. package/dist/{vm/snapshot → snapshot}/codec.d.ts +37 -6
  33. package/dist/{vm/snapshot → snapshot}/codec.js +112 -8
  34. package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +13 -6
  35. package/dist/{vm/snapshot → snapshot}/snapshot.js +19 -4
  36. package/dist/{vm/snapshot.js → snapshot.js} +5 -2
  37. package/dist/stdlib/array.d.ts +14 -9
  38. package/dist/stdlib/array.js +89 -276
  39. package/dist/stdlib/bytes.d.ts +11 -7
  40. package/dist/stdlib/bytes.js +112 -79
  41. package/dist/stdlib/collections.d.ts +7 -7
  42. package/dist/stdlib/collections.js +30 -339
  43. package/dist/stdlib/console.d.ts +2 -2
  44. package/dist/stdlib/console.js +3 -3
  45. package/dist/stdlib/date.d.ts +2 -2
  46. package/dist/stdlib/date.js +21 -30
  47. package/dist/stdlib/headers.d.ts +2 -2
  48. package/dist/stdlib/headers.js +15 -33
  49. package/dist/stdlib/iterator.d.ts +2 -2
  50. package/dist/stdlib/iterator.js +10 -303
  51. package/dist/stdlib/json.d.ts +2 -2
  52. package/dist/stdlib/json.js +15 -31
  53. package/dist/stdlib/math.d.ts +2 -7
  54. package/dist/stdlib/math.js +6 -30
  55. package/dist/stdlib/number.d.ts +3 -3
  56. package/dist/stdlib/number.js +8 -8
  57. package/dist/stdlib/object.d.ts +4 -4
  58. package/dist/stdlib/object.js +12 -30
  59. package/dist/stdlib/regexp.d.ts +6 -5
  60. package/dist/stdlib/regexp.js +18 -13
  61. package/dist/stdlib/string.d.ts +2 -2
  62. package/dist/stdlib/string.js +53 -53
  63. package/dist/stdlib/url.d.ts +21 -9
  64. package/dist/stdlib/url.js +55 -55
  65. package/dist/stdlib/value.d.ts +3 -4
  66. package/dist/stdlib/value.js +5 -6
  67. package/dist/stdlib/web.d.ts +4 -4
  68. package/dist/stdlib/web.js +7 -7
  69. package/dist/tool-runtime.d.ts +34 -12
  70. package/dist/tool-runtime.js +350 -68
  71. package/dist/tool-schema.d.ts +5 -0
  72. package/dist/tool-schema.js +36 -16
  73. package/dist/tool.d.ts +60 -2
  74. package/dist/tool.js +17 -1
  75. package/dist/{vm/vm.d.ts → vm.d.ts} +4 -3
  76. package/dist/{vm/vm.js → vm.js} +1 -1
  77. package/package.json +5 -7
  78. package/dist/interpreter/callback.d.ts +0 -24
  79. package/dist/interpreter/callback.js +0 -86
  80. package/dist/interpreter/errors.js +0 -173
  81. package/dist/interpreter/execute.d.ts +0 -14
  82. package/dist/interpreter/execute.js +0 -207
  83. package/dist/interpreter/extensions.d.ts +0 -9
  84. package/dist/interpreter/extensions.js +0 -248
  85. package/dist/interpreter/generators.d.ts +0 -3
  86. package/dist/interpreter/generators.js +0 -168
  87. package/dist/interpreter/globals.js +0 -144
  88. package/dist/interpreter/interpreter.d.ts +0 -48
  89. package/dist/interpreter/interpreter.js +0 -2253
  90. package/dist/interpreter/intrinsics.d.ts +0 -15
  91. package/dist/interpreter/intrinsics.js +0 -105
  92. package/dist/interpreter/model.d.ts +0 -68
  93. package/dist/interpreter/model.js +0 -54
  94. package/dist/interpreter/native.d.ts +0 -17
  95. package/dist/interpreter/native.js +0 -35
  96. package/dist/interpreter/objects.d.ts +0 -301
  97. package/dist/interpreter/objects.js +0 -592
  98. package/dist/interpreter/promises.d.ts +0 -18
  99. package/dist/interpreter/promises.js +0 -292
  100. package/dist/interpreter/runner.d.ts +0 -188
  101. package/dist/interpreter/runner.js +0 -492
  102. package/dist/interpreter/scope.d.ts +0 -16
  103. package/dist/interpreter/scope.js +0 -79
  104. package/dist/suspend-error.d.ts +0 -23
  105. package/dist/suspend-error.js +0 -25
  106. package/dist/vm/data.d.ts +0 -7
  107. package/dist/vm/data.js +0 -13
  108. package/dist/vm/index.d.ts +0 -6
  109. package/dist/vm/index.js +0 -6
  110. package/dist/vm/runtime/errors.d.ts +0 -23
  111. package/dist/vm/runtime/globals.d.ts +0 -6
  112. package/dist/vm/runtime/limits.d.ts +0 -10
  113. package/dist/vm/runtime/limits.js +0 -19
  114. package/dist/vm/runtime/modules.d.ts +0 -4
  115. package/dist/vm/runtime/modules.js +0 -33
  116. package/dist/vm/runtime/references.d.ts +0 -8
  117. package/dist/vm/runtime/references.js +0 -51
  118. package/dist/vm/stdlib/array.d.ts +0 -16
  119. package/dist/vm/stdlib/array.js +0 -311
  120. package/dist/vm/stdlib/bytes.d.ts +0 -11
  121. package/dist/vm/stdlib/bytes.js +0 -222
  122. package/dist/vm/stdlib/collections.d.ts +0 -7
  123. package/dist/vm/stdlib/collections.js +0 -188
  124. package/dist/vm/stdlib/console.d.ts +0 -6
  125. package/dist/vm/stdlib/console.js +0 -93
  126. package/dist/vm/stdlib/date.d.ts +0 -2
  127. package/dist/vm/stdlib/date.js +0 -123
  128. package/dist/vm/stdlib/headers.d.ts +0 -2
  129. package/dist/vm/stdlib/headers.js +0 -92
  130. package/dist/vm/stdlib/iterator.d.ts +0 -2
  131. package/dist/vm/stdlib/iterator.js +0 -30
  132. package/dist/vm/stdlib/json.d.ts +0 -3
  133. package/dist/vm/stdlib/json.js +0 -42
  134. package/dist/vm/stdlib/math.d.ts +0 -3
  135. package/dist/vm/stdlib/math.js +0 -73
  136. package/dist/vm/stdlib/number.d.ts +0 -3
  137. package/dist/vm/stdlib/number.js +0 -72
  138. package/dist/vm/stdlib/object.d.ts +0 -6
  139. package/dist/vm/stdlib/object.js +0 -201
  140. package/dist/vm/stdlib/regexp.d.ts +0 -8
  141. package/dist/vm/stdlib/regexp.js +0 -119
  142. package/dist/vm/stdlib/string.d.ts +0 -2
  143. package/dist/vm/stdlib/string.js +0 -272
  144. package/dist/vm/stdlib/url.d.ts +0 -25
  145. package/dist/vm/stdlib/url.js +0 -255
  146. package/dist/vm/stdlib/value.d.ts +0 -6
  147. package/dist/vm/stdlib/value.js +0 -32
  148. package/dist/vm/stdlib/web.d.ts +0 -5
  149. package/dist/vm/stdlib/web.js +0 -97
  150. /package/dist/{vm/async.js → async.js} +0 -0
  151. /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
  152. /package/dist/{vm/code.js → code.js} +0 -0
  153. /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
  154. /package/dist/{vm/compiler → compiler}/compile.js +0 -0
  155. /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
  156. /package/dist/{vm/compiler → compiler}/scope.js +0 -0
  157. /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
  158. /package/dist/{vm/generators.js → generators.js} +0 -0
  159. /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
  160. /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
  161. /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
  162. /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
  163. /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
  164. /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
  165. /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
  166. /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
  167. /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
  168. /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
  169. /package/dist/{vm/prelude → prelude}/source.js +0 -0
  170. /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
  171. /package/dist/{vm/runtime → runtime}/callback.js +0 -0
  172. /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
  173. /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
  174. /package/dist/{vm/runtime → runtime}/generators.js +0 -0
  175. /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
  176. /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
  177. /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
  178. /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
  179. /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
  180. /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
  181. /package/dist/{interpreter → runtime}/limits.js +0 -0
  182. /package/dist/{vm/runtime → runtime}/model.js +0 -0
  183. /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
  184. /package/dist/{interpreter → runtime}/modules.js +0 -0
  185. /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
  186. /package/dist/{vm/runtime → runtime}/native.js +0 -0
  187. /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
  188. /package/dist/{vm/runtime → runtime}/promises.js +0 -0
  189. /package/dist/{interpreter → runtime}/references.d.ts +0 -0
  190. /package/dist/{interpreter → runtime}/references.js +0 -0
  191. /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
  192. /package/dist/{vm/runtime → runtime}/signals.js +0 -0
  193. /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
  194. /package/dist/{vm/runtime → runtime}/source.js +0 -0
  195. /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
  196. /package/dist/{vm/runtime → runtime}/table.js +0 -0
  197. /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
@@ -1,23 +0,0 @@
1
- import type { Diagnostic } from "../../codemode.js";
2
- import { type AstNode } from "./model.js";
3
- import { type ErrorType } from "./intrinsics.js";
4
- import { type Native, ErrorObj, Obj, type Value } from "./objects.js";
5
- import type { Interpreter } from "./interpreter.js";
6
- /**
7
- * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
8
- * into text would run its own methods.
9
- */
10
- export declare const errorMessage: (error: Error) => string;
11
- /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
12
- export declare const errorType: (error: Error) => ErrorType;
13
- export declare const normalizeError: (error: unknown) => Diagnostic;
14
- /**
15
- * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
16
- * that escape a built-in become the equivalent program error here.
17
- */
18
- export declare const locate: (error: unknown, node?: AstNode) => unknown;
19
- /** The program value a handler receives for a failure; one failure always yields the same value. */
20
- export declare const materialize: <R>(ctx: Interpreter<R>, thrown: unknown) => Value;
21
- export declare const createAggregateErrorValue: <R>(ctx: Interpreter<R>, errors: Array<Value>, message: string, proto?: Obj) => ErrorObj;
22
- /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
23
- export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native;
@@ -1,6 +0,0 @@
1
- import { type Value } from "./objects.js";
2
- import type { Interpreter } from "./interpreter.js";
3
- /** Names bound in every program before extensions apply. */
4
- export declare const globalNames: ReadonlySet<string>;
5
- /** The immutable global bindings of every program, in declaration order. */
6
- export declare const globals: <R>(ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
@@ -1,10 +0,0 @@
1
- /** Longest string a built-in or operator may produce. */
2
- export declare const MAX_STRING_LENGTH: number;
3
- /** Longest array a built-in may create or grow to. */
4
- export declare const MAX_ARRAY_LENGTH = 10000000;
5
- /** Most promises that may be pending at once. */
6
- export declare const MAX_PENDING_PROMISES = 10000;
7
- /** Deepest nesting a value may have when it crosses to or from the host. */
8
- export declare const MAX_VALUE_DEPTH = 32;
9
- export declare const checkStringLength: (length: number) => void;
10
- export declare const checkArrayLength: (length: number) => void;
@@ -1,19 +0,0 @@
1
- import { rangeError } from "./model.js";
2
- // The timeout only fires between interpreter steps, so a single built-in must not be able to materialize an
3
- // unbounded value. These bound what one call may build; programs cannot reach such sizes any other way.
4
- /** Longest string a built-in or operator may produce. */
5
- export const MAX_STRING_LENGTH = 1 << 24;
6
- /** Longest array a built-in may create or grow to. */
7
- export const MAX_ARRAY_LENGTH = 10_000_000;
8
- /** Most promises that may be pending at once. */
9
- export const MAX_PENDING_PROMISES = 10_000;
10
- /** Deepest nesting a value may have when it crosses to or from the host. */
11
- export const MAX_VALUE_DEPTH = 32;
12
- export const checkStringLength = (length) => {
13
- if (length > MAX_STRING_LENGTH)
14
- throw rangeError("Invalid string length");
15
- };
16
- export const checkArrayLength = (length) => {
17
- if (length > MAX_ARRAY_LENGTH)
18
- throw rangeError("Invalid array length");
19
- };
@@ -1,4 +0,0 @@
1
- import { type Value } from "./objects.js";
2
- /** `node:fs` names the same module as `fs`. */
3
- export declare const moduleName: (specifier: string) => string;
4
- export declare const resolveModule: (specifier: string, global: (name: string) => Value) => Value;
@@ -1,33 +0,0 @@
1
- import { define, get, Obj } from "./objects.js";
2
- /**
3
- * What `import` and `require` load: a global, by the Node module name that provides it. `fs` loads the `fs` global
4
- * and `crypto` the `crypto` global; the names below come from globals with different names. A module that would be
5
- * empty isn't available.
6
- */
7
- const aliases = {
8
- "fs/promises": (global) => {
9
- const fs = global("fs");
10
- return fs instanceof Obj ? get(fs, "promises") : undefined;
11
- },
12
- url: (global) => pick(global, ["URL", "URLSearchParams"]),
13
- util: (global) => pick(global, ["TextEncoder", "TextDecoder"]),
14
- buffer: (global) => pick(global, ["Buffer", "atob", "btoa"]),
15
- };
16
- /** `node:fs` names the same module as `fs`. */
17
- export const moduleName = (specifier) => (specifier.startsWith("node:") ? specifier.slice(5) : specifier);
18
- export const resolveModule = (specifier, global) => {
19
- const name = moduleName(specifier);
20
- return global(name) ?? aliases[name]?.(global);
21
- };
22
- function pick(global, names) {
23
- const found = names.flatMap((name) => {
24
- const value = global(name);
25
- return value === undefined ? [] : [[name, value]];
26
- });
27
- if (found.length === 0)
28
- return undefined;
29
- const module = new Obj(null);
30
- for (const [name, value] of found)
31
- define(module, name, value);
32
- return module;
33
- }
@@ -1,8 +0,0 @@
1
- import { Obj, type Value } from "./objects.js";
2
- /** Interpreter machinery that is never data, unlike a Date or Map, which cross some boundaries as copies. */
3
- export declare const isOpaque: (value: Value) => boolean;
4
- export declare const containsRuntimeReference: (value: Value) => boolean;
5
- export declare const containsOpaqueReference: (value: Value) => boolean;
6
- export declare const rejectCircularInsertion: (container: Obj, value: Value, label: string, seen?: Set<object>) => void;
7
- export declare const describeValue: (value: Value) => string;
8
- export declare const typeofValue: (value: Value) => string;
@@ -1,51 +0,0 @@
1
- import { ToolReference } from "../../tool-runtime.js";
2
- import { invalidData } from "./model.js";
3
- import { Callable, getOwn, isRuntimeReference, Obj, Opaque, ownKeys } from "./objects.js";
4
- /** Interpreter machinery that is never data, unlike a Date or Map, which cross some boundaries as copies. */
5
- export const isOpaque = (value) => value instanceof Opaque || value instanceof ToolReference;
6
- // Depth-first search over a value tree. `match` stops the walk; `skip` prunes a subtree without matching it.
7
- const find = (value, match, skip, seen) => {
8
- const pending = [[value].values()];
9
- while (pending.length > 0) {
10
- const next = pending.at(-1).next();
11
- if (next.done) {
12
- pending.pop();
13
- continue;
14
- }
15
- const current = next.value;
16
- if (match(current))
17
- return true;
18
- if (!(current instanceof Obj) || skip(current) || seen.has(current))
19
- continue;
20
- seen.add(current);
21
- pending.push(ownKeys(current)
22
- .map((key) => getOwn(current, key))
23
- .values());
24
- }
25
- return false;
26
- };
27
- const never = () => false;
28
- export const containsRuntimeReference = (value) => find(value, isRuntimeReference, never, new Set());
29
- export const containsOpaqueReference = (value) => find(value, isOpaque, (current) => isRuntimeReference(current) && !isOpaque(current), new Set());
30
- // Reject cycles before mutation so later boundary walks remain safe.
31
- export const rejectCircularInsertion = (container, value, label, seen = new Set()) => {
32
- if (find(value, (current) => current === container, isRuntimeReference, seen)) {
33
- throw invalidData(`${label} contains a circular value.`);
34
- }
35
- };
36
- export const describeValue = (value) => {
37
- if (value === null || value === undefined)
38
- return String(value);
39
- if (value instanceof Obj)
40
- return value.describe;
41
- if (value instanceof ToolReference)
42
- return "a tool reference";
43
- return `a ${typeof value}`;
44
- };
45
- export const typeofValue = (value) => {
46
- if (value instanceof Callable)
47
- return "function";
48
- if (value instanceof ToolReference)
49
- return value.path.length > 0 ? "function" : "object";
50
- return typeof value;
51
- };
@@ -1,16 +0,0 @@
1
- import { Invoke } from "../runtime/signals.js";
2
- import type { Builtins } from "../runtime/intrinsics.js";
3
- import { Arr, Bytes, type Value } from "../runtime/objects.js";
4
- import type { Interpreter } from "../runtime/interpreter.js";
5
- /** Where a sort puts its result: back into an array or bytes, or into a new array. */
6
- export type SortInto = "Array.sort" | "Array.toSorted" | "Uint8Array.sort";
7
- /** The most values the default sort sorts in one native call; more sort in bounded steps (see `sortDefault`). */
8
- export declare const SORT_RUN = 4096;
9
- /**
10
- * Sorts `target`'s values: at once without a comparator, unless there are many, otherwise in the prelude
11
- * (`sortWith`), which calls it. The merges of a top-down merge sort are planned here, in post-order, so the prelude
12
- * compares in the same order as the recursive sort. Holes and undefined values sort last without being compared.
13
- */
14
- export declare const sortArray: <R>(ctx: Interpreter<R>, target: Arr | Bytes, comparator: Value, into: SortInto) => Value | Invoke;
15
- export declare const sorted: (builtins: Builtins, target: Arr | Bytes, into: SortInto, holes: number, result: Array<Value>) => Arr | Bytes;
16
- export declare const arrayGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -1,311 +0,0 @@
1
- import { Invoke } from "../runtime/signals.js";
2
- import { builtinCursor } from "../runtime/operations.js";
3
- import { constructor, methods, prototypeFrom, receiver, iteratorMethods } from "../runtime/native.js";
4
- import { checkArrayLength, checkStringLength, MAX_ARRAY_LENGTH } from "../runtime/limits.js";
5
- import { invalidData, IteratorSymbol, rangeError, typeError } from "../runtime/model.js";
6
- import { changed, define, get, hidden, Arr, Bytes, GeneratorObj, Obj, PromiseObj, coerceToInteger, coerceToNumber, coerceToString, rejectAddition, } from "../runtime/objects.js";
7
- import { describeValue, rejectCircularInsertion } from "../runtime/references.js";
8
- import { requireCallback, withPrimitives } from "../runtime/callback.js";
9
- import { compareText } from "../../tool-runtime.js";
10
- const arrayLikeSource = (source) => {
11
- // JS would treat a promise as an empty array-like; that would hide a missing `await`.
12
- if (source instanceof Obj && !(source instanceof PromiseObj)) {
13
- const length = Math.max(0, coerceToInteger(get(source, "length")));
14
- checkArrayLength(length);
15
- return { length, source };
16
- }
17
- throw invalidData(`Array.from expects an iterable or array-like value, received ${describeValue(source)}.`);
18
- };
19
- const iterable = (builtins, value) => {
20
- if (builtinCursor(builtins, value) !== undefined)
21
- return true;
22
- if (!(value instanceof Obj))
23
- return false;
24
- const method = get(value, IteratorSymbol);
25
- return method !== undefined && method !== null;
26
- };
27
- const arrayFrom = (ctx, args) => {
28
- const source = args[0];
29
- const mapper = args.length < 2 || args[1] === undefined ? undefined : requireCallback(args[1], "Array.from");
30
- if (iterable(ctx.builtins, source)) {
31
- return new Invoke(ctx.prelude.fn("arrayFromIterable"), undefined, [source, mapper, args[2]], undefined);
32
- }
33
- if (source instanceof GeneratorObj) {
34
- throw typeError(`Array.from expects a synchronous iterable or array-like value, received ${describeValue(source)}.`);
35
- }
36
- const arrayLike = arrayLikeSource(source);
37
- if (mapper === undefined) {
38
- return new Arr(ctx.builtins.Array, Array.from({ length: arrayLike.length }, (_, index) => get(arrayLike.source, index)));
39
- }
40
- return new Invoke(ctx.prelude.fn("arrayFromLike"), undefined, [arrayLike.source, arrayLike.length, mapper, args[2]], undefined);
41
- };
42
- /** The most values the default sort sorts in one native call; more sort in bounded steps (see `sortDefault`). */
43
- export const SORT_RUN = 4096;
44
- /**
45
- * Sorts `target`'s values: at once without a comparator, unless there are many, otherwise in the prelude
46
- * (`sortWith`), which calls it. The merges of a top-down merge sort are planned here, in post-order, so the prelude
47
- * compares in the same order as the recursive sort. Holes and undefined values sort last without being compared.
48
- */
49
- export const sortArray = (ctx, target, comparator, into) => {
50
- const builtins = ctx.builtins;
51
- const items = target instanceof Arr ? [...target.items] : [...target.bytes];
52
- // Counted before any comparator runs; a comparator that changes the array does not change where holes go.
53
- let holes = 0;
54
- if (target instanceof Arr)
55
- for (let index = 0; index < items.length; index++)
56
- if (!(index in target.items))
57
- holes++;
58
- const callback = comparator === undefined ? undefined : requireCallback(comparator, into);
59
- if (callback === undefined && items.length <= SORT_RUN) {
60
- return sorted(builtins, target, into, holes, items.sort((a, b) => compareText(coerceToString(a), coerceToString(b))));
61
- }
62
- const defined = new Arr(builtins.Array, items.filter((item) => item !== undefined));
63
- const undefs = items.length - defined.items.length;
64
- if (callback === undefined) {
65
- return new Invoke(ctx.prelude.fn("sortDefault"), undefined, [target, into, holes, defined, undefs], undefined);
66
- }
67
- const merges = [];
68
- const plan = (low, high) => {
69
- if (high - low <= 1)
70
- return;
71
- const middle = low + Math.floor((high - low) / 2);
72
- plan(low, middle);
73
- plan(middle, high);
74
- merges.push(low, middle, high);
75
- };
76
- plan(0, defined.items.length);
77
- const args = [target, into, holes, callback, defined, undefs, new Arr(builtins.Array, merges)];
78
- return new Invoke(ctx.prelude.fn("sortWith"), undefined, args, undefined);
79
- };
80
- export const sorted = (builtins, target, into, holes, result) => {
81
- if (target instanceof Bytes) {
82
- target.bytes.set(Uint8Array.from(result, coerceToNumber));
83
- return target;
84
- }
85
- if (into === "Array.toSorted")
86
- return new Arr(builtins.Array, result);
87
- changed(target);
88
- const items = target.items;
89
- const count = result.length - holes;
90
- result.slice(0, count).forEach((item, index) => {
91
- items[index] = item;
92
- });
93
- Array.from({ length: holes }, (_, index) => count + index).forEach((index) => {
94
- delete items[index];
95
- });
96
- return target;
97
- };
98
- // Array constructs identically with or without new, like JS.
99
- export const arrayGlobal = (ctx) => {
100
- const builtins = ctx.builtins;
101
- const proto = builtins.Array;
102
- const wrap = (items) => new Arr(proto, items);
103
- const construct = (args, into) => {
104
- if (args.length !== 1)
105
- return new Arr(into, [...args]);
106
- const first = args[0];
107
- if (typeof first !== "number")
108
- return new Arr(into, [first]);
109
- if (!Number.isInteger(first) || first < 0 || first > MAX_ARRAY_LENGTH)
110
- throw rangeError("Invalid array length.");
111
- // Sparse like JS: Array(3) has holes, and combinator loops already skip them.
112
- return new Arr(into, new Array(first));
113
- };
114
- const array = constructor(builtins, proto, {
115
- name: "Array",
116
- length: 1,
117
- call: (_, args) => construct(args, proto),
118
- construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)),
119
- });
120
- methods(builtins, array, [
121
- ["isArray", 1, (_, args) => args[0] instanceof Arr],
122
- ["of", 0, (_, args) => wrap([...args])],
123
- ["from", 1, (_, args) => arrayFrom(ctx, args)],
124
- ]);
125
- const self = (thisValue, name) => receiver(Arr, thisValue, `Array.prototype.${name}`);
126
- // A mutating method fails where its first element write, delete, or `length` write would on a frozen, sealed, or
127
- // non-extensible array. `growth` is given by the methods that always write `length`, even when it is 0; holes a
128
- // method would fill on a non-extensible array are not checked.
129
- const mutable = (target, growth) => {
130
- const length = target.items.length;
131
- if ((growth ?? 0) > 0)
132
- rejectAddition(target, length);
133
- if ((growth ?? 0) < 0 && length > 0 && !target.elements.configurable) {
134
- throw typeError(`Cannot delete property '${length - 1}'.`);
135
- }
136
- if (!target.elements.writable && (length > 0 || growth !== undefined)) {
137
- throw typeError(`Cannot assign to read only property '${length > 0 ? 0 : "length"}'.`);
138
- }
139
- changed(target);
140
- return target;
141
- };
142
- const optNumber = (value) => (value === undefined ? undefined : coerceToInteger(value));
143
- methods(builtins, proto, [
144
- [
145
- "join",
146
- 1,
147
- (thisValue, args) => {
148
- // .map would keep holes, which the conversion would then hand to the body as undefined.
149
- const parts = Array.from(self(thisValue, "join").items, (item) => item ?? "");
150
- return withPrimitives("string", [args[0] === undefined ? "," : args[0], ...parts], ([separator, ...items]) => {
151
- const joined = items.map(coerceToString).join(coerceToString(separator));
152
- checkStringLength(joined.length);
153
- return joined;
154
- });
155
- },
156
- ],
157
- [
158
- "toString",
159
- 0,
160
- (thisValue) => withPrimitives("string", Array.from(self(thisValue, "toString").items, (item) => item ?? ""), (items) => items.map(coerceToString).join(",")),
161
- ],
162
- [
163
- "includes",
164
- 1,
165
- (thisValue, args) => {
166
- return self(thisValue, "includes").items.includes(args[0], optNumber(args[1]));
167
- },
168
- ],
169
- ["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").items.indexOf(args[0], optNumber(args[1]))],
170
- [
171
- "lastIndexOf",
172
- 1,
173
- (thisValue, args) => {
174
- const target = self(thisValue, "lastIndexOf").items;
175
- // An explicit undefined is a fromIndex of 0, unlike omitting it.
176
- return args.length < 2 ? target.lastIndexOf(args[0]) : target.lastIndexOf(args[0], optNumber(args[1]));
177
- },
178
- ],
179
- ["at", 1, (thisValue, args) => self(thisValue, "at").items.at(optNumber(args[0]) ?? 0)],
180
- [
181
- "slice",
182
- 2,
183
- (thisValue, args) => wrap(self(thisValue, "slice").items.slice(optNumber(args[0]), optNumber(args[1]))),
184
- ],
185
- [
186
- "concat",
187
- 1,
188
- (thisValue, args) => {
189
- const joined = self(thisValue, "concat").items.concat(...args.map((item) => (item instanceof Arr ? item.items : item)));
190
- checkArrayLength(joined.length);
191
- return wrap(joined);
192
- },
193
- ],
194
- [
195
- "flat",
196
- 0,
197
- (thisValue, args) => {
198
- const flatten = (items, depth) => items.flatMap((item) => (item instanceof Arr && depth > 0 ? flatten(item.items, depth - 1) : [item]));
199
- const flattened = flatten(self(thisValue, "flat").items, optNumber(args[0]) ?? 1);
200
- checkArrayLength(flattened.length);
201
- return wrap(flattened);
202
- },
203
- ],
204
- [
205
- "reverse",
206
- 0,
207
- (thisValue) => {
208
- const target = self(thisValue, "reverse");
209
- // Fewer than two elements means no writes at all, so a frozen one-element array reverses fine.
210
- if (target.items.length > 1)
211
- mutable(target);
212
- target.items.reverse();
213
- return target;
214
- },
215
- ],
216
- ["sort", 1, (thisValue, args) => sortArray(ctx, mutable(self(thisValue, "sort")), args[0], "Array.sort")],
217
- ["toSorted", 1, (thisValue, args) => sortArray(ctx, self(thisValue, "toSorted"), args[0], "Array.toSorted")],
218
- ["toReversed", 0, (thisValue) => wrap([...self(thisValue, "toReversed").items].reverse())],
219
- [
220
- "with",
221
- 2,
222
- (thisValue, args) => {
223
- const target = self(thisValue, "with").items;
224
- const index = optNumber(args[0]) ?? 0;
225
- const resolved = index < 0 ? target.length + index : index;
226
- if (resolved < 0 || resolved >= target.length)
227
- throw rangeError("Array.with index is out of range.");
228
- const copied = [...target];
229
- copied[resolved] = args[1];
230
- return wrap(copied);
231
- },
232
- ],
233
- [
234
- "push",
235
- 1,
236
- (thisValue, args) => {
237
- const target = mutable(self(thisValue, "push"), args.length);
238
- // Validate all insertions before mutating to avoid partial cyclic updates.
239
- for (const item of args)
240
- rejectCircularInsertion(target, item, "Array.push result");
241
- return target.items.push(...args);
242
- },
243
- ],
244
- [
245
- "unshift",
246
- 1,
247
- (thisValue, args) => {
248
- const target = mutable(self(thisValue, "unshift"), args.length);
249
- for (const item of args)
250
- rejectCircularInsertion(target, item, "Array.unshift result");
251
- return target.items.unshift(...args);
252
- },
253
- ],
254
- ["pop", 0, (thisValue) => mutable(self(thisValue, "pop"), -1).items.pop()],
255
- ["shift", 0, (thisValue) => mutable(self(thisValue, "shift"), -1).items.shift()],
256
- [
257
- "splice",
258
- 2,
259
- (thisValue, args) => {
260
- const target = self(thisValue, "splice");
261
- const length = target.items.length;
262
- const start = optNumber(args[0]) ?? 0;
263
- const from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
264
- const deleteCount = args.length === 1 ? length - from : Math.min(Math.max(optNumber(args[1]) ?? 0, 0), length - from);
265
- const inserted = args.slice(2);
266
- for (const item of inserted)
267
- rejectCircularInsertion(target, item, "Array.splice result");
268
- mutable(target, inserted.length - deleteCount);
269
- return wrap(target.items.splice(from, deleteCount, ...inserted));
270
- },
271
- ],
272
- [
273
- "toSpliced",
274
- 2,
275
- (thisValue, args) => {
276
- const copied = [...self(thisValue, "toSpliced").items];
277
- if (args.length === 0)
278
- return wrap(copied);
279
- const start = optNumber(args[0]) ?? 0;
280
- if (args.length === 1)
281
- copied.splice(start);
282
- else
283
- copied.splice(start, optNumber(args[1]) ?? 0, ...args.slice(2));
284
- return wrap(copied);
285
- },
286
- ],
287
- [
288
- "fill",
289
- 1,
290
- (thisValue, args) => {
291
- const target = mutable(self(thisValue, "fill"));
292
- rejectCircularInsertion(target, args[0], "Array.fill result");
293
- target.items.fill(args[0], optNumber(args[1]), optNumber(args[2]));
294
- return target;
295
- },
296
- ],
297
- [
298
- "copyWithin",
299
- 2,
300
- (thisValue, args) => {
301
- const target = mutable(self(thisValue, "copyWithin"));
302
- target.items.copyWithin(optNumber(args[0]) ?? 0, optNumber(args[1]) ?? 0, optNumber(args[2]));
303
- return target;
304
- },
305
- ],
306
- ...iteratorMethods(builtins, self),
307
- // The callback methods are the prelude's.
308
- ]);
309
- define(proto, IteratorSymbol, get(proto, "values"), hidden);
310
- return array;
311
- };
@@ -1,11 +0,0 @@
1
- import { Obj, type Value } from "../runtime/objects.js";
2
- import type { Interpreter } from "../runtime/interpreter.js";
3
- export declare const finishBytes: (bytes: Uint8Array, into: Obj, offset: number) => Value;
4
- export declare const uint8ArrayGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
5
- export declare const textEncoderGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
6
- /** A `TextDecoder` holding the host decoder its label and options configured. */
7
- export declare class TextDecoderObj extends Obj {
8
- readonly decoder: TextDecoder;
9
- constructor(proto: Obj, decoder: TextDecoder);
10
- }
11
- export declare const textDecoderGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;