@opencode/codemode 2.2.5 → 2.2.6

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 (133) hide show
  1. package/README.md +70 -1
  2. package/dist/codemode.d.ts +55 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +14 -9
  5. package/dist/extension.js +2 -2
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/execute.d.ts +1 -1
  9. package/dist/interpreter/execute.js +16 -4
  10. package/dist/interpreter/extensions.d.ts +3 -3
  11. package/dist/interpreter/extensions.js +17 -11
  12. package/dist/interpreter/globals.js +10 -0
  13. package/dist/interpreter/interpreter.d.ts +11 -1
  14. package/dist/interpreter/interpreter.js +86 -2
  15. package/dist/interpreter/modules.d.ts +4 -0
  16. package/dist/interpreter/modules.js +33 -0
  17. package/dist/suspend-error.d.ts +23 -0
  18. package/dist/suspend-error.js +25 -0
  19. package/dist/tool-runtime.d.ts +4 -1
  20. package/dist/vm/async.d.ts +78 -0
  21. package/dist/vm/async.js +335 -0
  22. package/dist/vm/code.d.ts +122 -0
  23. package/dist/vm/code.js +407 -0
  24. package/dist/vm/compiler/compile.d.ts +13 -0
  25. package/dist/vm/compiler/compile.js +1477 -0
  26. package/dist/vm/compiler/scope.d.ts +74 -0
  27. package/dist/vm/compiler/scope.js +515 -0
  28. package/dist/vm/data.d.ts +7 -0
  29. package/dist/vm/data.js +13 -0
  30. package/dist/vm/generators.d.ts +42 -0
  31. package/dist/vm/generators.js +413 -0
  32. package/dist/vm/host.d.ts +103 -0
  33. package/dist/vm/host.js +226 -0
  34. package/dist/vm/index.d.ts +6 -0
  35. package/dist/vm/index.js +6 -0
  36. package/dist/vm/internal-prelude.d.ts +45 -0
  37. package/dist/vm/internal-prelude.js +534 -0
  38. package/dist/vm/opcodes.d.ts +222 -0
  39. package/dist/vm/opcodes.js +235 -0
  40. package/dist/vm/prelude/bytecode.d.ts +18 -0
  41. package/dist/vm/prelude/bytecode.js +31 -0
  42. package/dist/vm/prelude/bytecode.json +1 -0
  43. package/dist/vm/prelude/helpers.d.ts +8 -0
  44. package/dist/vm/prelude/helpers.js +258 -0
  45. package/dist/vm/prelude/prelude.d.ts +21 -0
  46. package/dist/vm/prelude/prelude.js +53 -0
  47. package/dist/vm/prelude/source.d.ts +1 -0
  48. package/dist/vm/prelude/source.js +652 -0
  49. package/dist/vm/runtime/callback.d.ts +25 -0
  50. package/dist/vm/runtime/callback.js +51 -0
  51. package/dist/vm/runtime/driver.d.ts +58 -0
  52. package/dist/vm/runtime/driver.js +184 -0
  53. package/dist/vm/runtime/errors.d.ts +23 -0
  54. package/dist/vm/runtime/errors.js +169 -0
  55. package/dist/vm/runtime/execute.d.ts +80 -0
  56. package/dist/vm/runtime/execute.js +414 -0
  57. package/dist/vm/runtime/extensions.d.ts +16 -0
  58. package/dist/vm/runtime/extensions.js +270 -0
  59. package/dist/vm/runtime/generators.d.ts +6 -0
  60. package/dist/vm/runtime/generators.js +44 -0
  61. package/dist/vm/runtime/globals.d.ts +6 -0
  62. package/dist/vm/runtime/globals.js +137 -0
  63. package/dist/vm/runtime/interpreter.d.ts +50 -0
  64. package/dist/vm/runtime/interpreter.js +94 -0
  65. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  66. package/dist/vm/runtime/intrinsic-names.js +166 -0
  67. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  68. package/dist/vm/runtime/intrinsics.js +111 -0
  69. package/dist/vm/runtime/limits.d.ts +10 -0
  70. package/dist/vm/runtime/limits.js +19 -0
  71. package/dist/vm/runtime/model.d.ts +58 -0
  72. package/dist/vm/runtime/model.js +57 -0
  73. package/dist/vm/runtime/modules.d.ts +4 -0
  74. package/dist/vm/runtime/modules.js +33 -0
  75. package/dist/vm/runtime/native.d.ts +19 -0
  76. package/dist/vm/runtime/native.js +41 -0
  77. package/dist/vm/runtime/objects.d.ts +403 -0
  78. package/dist/vm/runtime/objects.js +784 -0
  79. package/dist/vm/runtime/operations.d.ts +49 -0
  80. package/dist/vm/runtime/operations.js +288 -0
  81. package/dist/vm/runtime/promises.d.ts +55 -0
  82. package/dist/vm/runtime/promises.js +232 -0
  83. package/dist/vm/runtime/references.d.ts +8 -0
  84. package/dist/vm/runtime/references.js +51 -0
  85. package/dist/vm/runtime/signals.d.ts +69 -0
  86. package/dist/vm/runtime/signals.js +68 -0
  87. package/dist/vm/runtime/source.d.ts +29 -0
  88. package/dist/vm/runtime/source.js +63 -0
  89. package/dist/vm/runtime/table.d.ts +43 -0
  90. package/dist/vm/runtime/table.js +132 -0
  91. package/dist/vm/scheduler.d.ts +178 -0
  92. package/dist/vm/scheduler.js +63 -0
  93. package/dist/vm/snapshot/codec.d.ts +87 -0
  94. package/dist/vm/snapshot/codec.js +751 -0
  95. package/dist/vm/snapshot/snapshot.d.ts +49 -0
  96. package/dist/vm/snapshot/snapshot.js +70 -0
  97. package/dist/vm/snapshot.d.ts +32 -0
  98. package/dist/vm/snapshot.js +306 -0
  99. package/dist/vm/stdlib/array.d.ts +16 -0
  100. package/dist/vm/stdlib/array.js +311 -0
  101. package/dist/vm/stdlib/bytes.d.ts +11 -0
  102. package/dist/vm/stdlib/bytes.js +222 -0
  103. package/dist/vm/stdlib/collections.d.ts +7 -0
  104. package/dist/vm/stdlib/collections.js +188 -0
  105. package/dist/vm/stdlib/console.d.ts +6 -0
  106. package/dist/vm/stdlib/console.js +93 -0
  107. package/dist/vm/stdlib/date.d.ts +2 -0
  108. package/dist/vm/stdlib/date.js +123 -0
  109. package/dist/vm/stdlib/headers.d.ts +2 -0
  110. package/dist/vm/stdlib/headers.js +92 -0
  111. package/dist/vm/stdlib/iterator.d.ts +2 -0
  112. package/dist/vm/stdlib/iterator.js +30 -0
  113. package/dist/vm/stdlib/json.d.ts +3 -0
  114. package/dist/vm/stdlib/json.js +42 -0
  115. package/dist/vm/stdlib/math.d.ts +3 -0
  116. package/dist/vm/stdlib/math.js +73 -0
  117. package/dist/vm/stdlib/number.d.ts +3 -0
  118. package/dist/vm/stdlib/number.js +72 -0
  119. package/dist/vm/stdlib/object.d.ts +6 -0
  120. package/dist/vm/stdlib/object.js +201 -0
  121. package/dist/vm/stdlib/regexp.d.ts +8 -0
  122. package/dist/vm/stdlib/regexp.js +119 -0
  123. package/dist/vm/stdlib/string.d.ts +2 -0
  124. package/dist/vm/stdlib/string.js +272 -0
  125. package/dist/vm/stdlib/url.d.ts +25 -0
  126. package/dist/vm/stdlib/url.js +255 -0
  127. package/dist/vm/stdlib/value.d.ts +6 -0
  128. package/dist/vm/stdlib/value.js +32 -0
  129. package/dist/vm/stdlib/web.d.ts +5 -0
  130. package/dist/vm/stdlib/web.js +97 -0
  131. package/dist/vm/vm.d.ts +225 -0
  132. package/dist/vm/vm.js +2931 -0
  133. package/package.json +6 -3
@@ -0,0 +1,188 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js";
3
+ import { IteratorSymbol, typeError } from "../runtime/model.js";
4
+ import { define, defineAccessor, get, hidden, MapObj, Obj, SetObj, WeakMapObj, WeakSetObj, } from "../runtime/objects.js";
5
+ import { describeValue } from "../runtime/references.js";
6
+ import { requireCallback } from "../runtime/callback.js";
7
+ // A collection from an iterable is filled by the prelude, which iterates it.
8
+ const filled = (ctx, target, init, kind) => init === undefined || init === null
9
+ ? target
10
+ : new Invoke(ctx.prelude.fn("fillCollection"), undefined, [target, init, kind], undefined);
11
+ // The callback sees the stored key (-0 is +0) and its result wins over anything it inserted itself.
12
+ const getOrInsertComputed = (ctx, owner, key, callback) => {
13
+ const table = owner.map;
14
+ if (table.has(key))
15
+ return table.get(key);
16
+ return new Invoke(ctx.prelude.fn("insertComputed"), undefined, [owner, key === 0 ? 0 : key, callback], undefined);
17
+ };
18
+ export const mapGlobal = (ctx) => {
19
+ const builtins = ctx.builtins;
20
+ const proto = builtins.Map;
21
+ const map = constructor(builtins, proto, {
22
+ name: "Map",
23
+ call: requiresNew("Map"),
24
+ construct: (args, newTarget) => filled(ctx, new MapObj(prototypeFrom(newTarget, proto)), args[0], "Map"),
25
+ });
26
+ const self = (thisValue, name) => receiver(MapObj, thisValue, `Map.prototype.${name}`);
27
+ defineAccessor(proto, "size", (thisValue) => receiver(MapObj, thisValue, "Map.prototype.size").map.size);
28
+ methods(builtins, proto, [
29
+ ["get", 1, (thisValue, args) => self(thisValue, "get").map.get(args[0])],
30
+ ["has", 1, (thisValue, args) => self(thisValue, "has").map.has(args[0])],
31
+ [
32
+ "set",
33
+ 2,
34
+ (thisValue, args) => {
35
+ const target = self(thisValue, "set");
36
+ target.map.set(args[0], args[1]);
37
+ return target;
38
+ },
39
+ ],
40
+ [
41
+ "getOrInsert",
42
+ 2,
43
+ (thisValue, args) => {
44
+ const target = self(thisValue, "getOrInsert").map;
45
+ if (!target.has(args[0]))
46
+ target.set(args[0], args[1]);
47
+ return target.get(args[0]);
48
+ },
49
+ ],
50
+ [
51
+ "getOrInsertComputed",
52
+ 2,
53
+ (thisValue, args) => {
54
+ const target = self(thisValue, "getOrInsertComputed");
55
+ return getOrInsertComputed(ctx, target, args[0], requireCallback(args[1], "Map.getOrInsertComputed"));
56
+ },
57
+ ],
58
+ ["delete", 1, (thisValue, args) => self(thisValue, "delete").map.delete(args[0])],
59
+ [
60
+ "clear",
61
+ 0,
62
+ (thisValue) => {
63
+ self(thisValue, "clear").map.clear();
64
+ return undefined;
65
+ },
66
+ ],
67
+ ...iteratorMethods(builtins, self),
68
+ ]);
69
+ define(proto, IteratorSymbol, get(proto, "entries"), hidden);
70
+ return map;
71
+ };
72
+ export const setGlobal = (ctx) => {
73
+ const builtins = ctx.builtins;
74
+ const proto = builtins.Set;
75
+ const set = constructor(builtins, proto, {
76
+ name: "Set",
77
+ call: requiresNew("Set"),
78
+ construct: (args, newTarget) => filled(ctx, new SetObj(prototypeFrom(newTarget, proto)), args[0], "Set"),
79
+ });
80
+ const self = (thisValue, name) => receiver(SetObj, thisValue, `Set.prototype.${name}`);
81
+ defineAccessor(proto, "size", (thisValue) => receiver(SetObj, thisValue, "Set.prototype.size").set.size);
82
+ methods(builtins, proto, [
83
+ ["has", 1, (thisValue, args) => self(thisValue, "has").set.has(args[0])],
84
+ [
85
+ "add",
86
+ 1,
87
+ (thisValue, args) => {
88
+ const target = self(thisValue, "add");
89
+ target.set.add(args[0]);
90
+ return target;
91
+ },
92
+ ],
93
+ ["delete", 1, (thisValue, args) => self(thisValue, "delete").set.delete(args[0])],
94
+ [
95
+ "clear",
96
+ 0,
97
+ (thisValue) => {
98
+ self(thisValue, "clear").set.clear();
99
+ return undefined;
100
+ },
101
+ ],
102
+ ...iteratorMethods(builtins, self),
103
+ ]);
104
+ define(proto, IteratorSymbol, get(proto, "values"), hidden);
105
+ return set;
106
+ };
107
+ // CanBeHeldWeakly: only program objects; tool references are rebuilt on every access, so they could never be found again.
108
+ export const weakKey = (value, label) => {
109
+ if (value instanceof Obj)
110
+ return value;
111
+ throw typeError(`Invalid value used ${label}: ${describeValue(value)} cannot be held weakly.`);
112
+ };
113
+ export const weakMapGlobal = (ctx) => {
114
+ const builtins = ctx.builtins;
115
+ const proto = builtins.WeakMap;
116
+ const weakMap = constructor(builtins, proto, {
117
+ name: "WeakMap",
118
+ call: requiresNew("WeakMap"),
119
+ construct: (args, newTarget) => filled(ctx, new WeakMapObj(prototypeFrom(newTarget, proto)), args[0], "WeakMap"),
120
+ });
121
+ const self = (thisValue, name) => receiver(WeakMapObj, thisValue, `WeakMap.prototype.${name}`).map;
122
+ // Lookups pass any key through: the host collection answers false for a non-object, as the spec requires.
123
+ const key = (value) => weakKey(value, "as weak map key");
124
+ methods(builtins, proto, [
125
+ [
126
+ "get",
127
+ 1,
128
+ (thisValue, args) => {
129
+ const target = self(thisValue, "get");
130
+ return args[0] instanceof Obj ? target.get(args[0]) : undefined;
131
+ },
132
+ ],
133
+ ["has", 1, (thisValue, args) => self(thisValue, "has").has(args[0])],
134
+ ["delete", 1, (thisValue, args) => self(thisValue, "delete").delete(args[0])],
135
+ [
136
+ "set",
137
+ 2,
138
+ (thisValue, args) => {
139
+ self(thisValue, "set").set(key(args[0]), args[1]);
140
+ return thisValue;
141
+ },
142
+ ],
143
+ [
144
+ "getOrInsert",
145
+ 2,
146
+ (thisValue, args) => {
147
+ const target = self(thisValue, "getOrInsert");
148
+ const k = key(args[0]);
149
+ if (!target.has(k))
150
+ target.set(k, args[1]);
151
+ return target.get(k);
152
+ },
153
+ ],
154
+ [
155
+ "getOrInsertComputed",
156
+ 2,
157
+ (thisValue, args) => {
158
+ const target = receiver(WeakMapObj, thisValue, "WeakMap.prototype.getOrInsertComputed");
159
+ const k = key(args[0]);
160
+ return getOrInsertComputed(ctx, target, k, requireCallback(args[1], "WeakMap.getOrInsertComputed"));
161
+ },
162
+ ],
163
+ ]);
164
+ return weakMap;
165
+ };
166
+ export const weakSetGlobal = (ctx) => {
167
+ const builtins = ctx.builtins;
168
+ const proto = builtins.WeakSet;
169
+ const weakSet = constructor(builtins, proto, {
170
+ name: "WeakSet",
171
+ call: requiresNew("WeakSet"),
172
+ construct: (args, newTarget) => filled(ctx, new WeakSetObj(prototypeFrom(newTarget, proto)), args[0], "WeakSet"),
173
+ });
174
+ const self = (thisValue, name) => receiver(WeakSetObj, thisValue, `WeakSet.prototype.${name}`).set;
175
+ methods(builtins, proto, [
176
+ ["has", 1, (thisValue, args) => self(thisValue, "has").has(args[0])],
177
+ ["delete", 1, (thisValue, args) => self(thisValue, "delete").delete(args[0])],
178
+ [
179
+ "add",
180
+ 1,
181
+ (thisValue, args) => {
182
+ self(thisValue, "add").add(weakKey(args[0], "in weak set"));
183
+ return thisValue;
184
+ },
185
+ ],
186
+ ]);
187
+ return weakSet;
188
+ };
@@ -0,0 +1,6 @@
1
+ import { Obj, type Value } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ /** Captured console: every method appends one formatted line to `logs`. */
4
+ export declare const consoleGlobal: <R>(ctx: Interpreter<R>) => Obj;
5
+ /** One value as `console.log` shows it. */
6
+ export declare const formatValue: (value: Value) => string;
@@ -0,0 +1,93 @@
1
+ import { methods } from "../runtime/native.js";
2
+ import { entries, get, Arr, Obj } from "../runtime/objects.js";
3
+ import { ToolReference } from "../../tool-runtime.js";
4
+ import { containsOpaqueReference } from "../runtime/references.js";
5
+ const consoleMethods = ["log", "info", "debug", "warn", "error", "dir", "table"];
6
+ /** Captured console: every method appends one formatted line to `logs`. */
7
+ export const consoleGlobal = (ctx) => {
8
+ const builtins = ctx.builtins;
9
+ const console = new Obj(builtins.Object);
10
+ methods(builtins, console, consoleMethods.map((name) => [
11
+ name,
12
+ 0,
13
+ (_, args) => {
14
+ ctx.logs.push(formatConsoleMessage(name, args));
15
+ return undefined;
16
+ },
17
+ ]));
18
+ return console;
19
+ };
20
+ const MAX_CONSOLE_DEPTH = 32;
21
+ const formatConsoleMessage = (name, args) => {
22
+ if (name === "dir")
23
+ return args.length === 0 ? "undefined" : formatValue(args[0]);
24
+ if (name === "table")
25
+ return formatConsoleTable(args[0], args[1]);
26
+ const prefix = name === "warn" ? "[warn] " : name === "error" ? "[error] " : name === "debug" ? "[debug] " : "";
27
+ return `${prefix}${args.map((arg) => formatValue(arg)).join(" ")}`;
28
+ };
29
+ /** One value as `console.log` shows it. */
30
+ export const formatValue = (value) => {
31
+ if (value === undefined)
32
+ return "undefined";
33
+ if (typeof value === "string")
34
+ return value;
35
+ return formatConsoleValue(value, new Set(), 0);
36
+ };
37
+ const formatConsoleValue = (value, seen, depth) => {
38
+ if (value === null || value === undefined)
39
+ return "null";
40
+ if (typeof value === "string")
41
+ return JSON.stringify(value);
42
+ if (!(value instanceof Obj))
43
+ return value instanceof ToolReference ? "[opaque reference]" : String(value);
44
+ if (depth > MAX_CONSOLE_DEPTH)
45
+ return "...";
46
+ if (seen.has(value))
47
+ return "[Circular]";
48
+ seen.add(value);
49
+ try {
50
+ return value.inspect((item) => formatConsoleValue(item, seen, depth + 1));
51
+ }
52
+ finally {
53
+ seen.delete(value);
54
+ }
55
+ };
56
+ const formatConsoleTable = (value, columnsArgument) => {
57
+ if (value === undefined)
58
+ return "undefined";
59
+ if (containsOpaqueReference(value))
60
+ return "[opaque reference]";
61
+ const columns = columnsArgument instanceof Arr ? columnsArgument.items.map(String) : undefined;
62
+ const rows = consoleTableRows(value, columns);
63
+ const keys = columns ?? Array.from(new Set(rows.flatMap((row) => Object.keys(row.values))));
64
+ const header = ["(index)", ...keys].join("\t");
65
+ return [
66
+ header,
67
+ ...rows.map((row) => [row.index, ...keys.map((key) => formatConsoleTableCell(row.values[key]))].join("\t")),
68
+ ].join("\n");
69
+ };
70
+ const consoleTableRows = (data, columns) => {
71
+ if (data instanceof Arr) {
72
+ return data.items.map((item, index) => ({ index: String(index), values: consoleTableValues(item, columns) }));
73
+ }
74
+ if (data instanceof Obj) {
75
+ return entries(data).map(([index, item]) => ({ index, values: consoleTableValues(item, columns) }));
76
+ }
77
+ return [{ index: "0", values: { Value: data } }];
78
+ };
79
+ const consoleTableValues = (value, columns) => {
80
+ if (value instanceof Obj && !(value instanceof Arr)) {
81
+ if (columns !== undefined)
82
+ return Object.fromEntries(columns.map((column) => [column, get(value, column)]));
83
+ return Object.fromEntries(entries(value));
84
+ }
85
+ return { Value: value };
86
+ };
87
+ const formatConsoleTableCell = (value) => {
88
+ if (value === undefined)
89
+ return "";
90
+ if (typeof value === "string")
91
+ return value;
92
+ return formatConsoleValue(value, new Set(), 0);
93
+ };
@@ -0,0 +1,2 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ export declare const dateGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,123 @@
1
+ import { constructor, methods, prototypeFrom, receiver } from "../runtime/native.js";
2
+ import { rangeError } from "../runtime/model.js";
3
+ import { DateObj, Obj, coerceToNumber, coerceToString } from "../runtime/objects.js";
4
+ import { withPrimitives } from "../runtime/callback.js";
5
+ const constructDate = (args, proto) => {
6
+ if (args.length === 0)
7
+ return new DateObj(proto, Date.now());
8
+ if (args.length === 1) {
9
+ const arg = args[0];
10
+ if (arg instanceof DateObj)
11
+ return new DateObj(proto, arg.time);
12
+ return withPrimitives("default", [arg], ([value]) => typeof value === "string"
13
+ ? new DateObj(proto, Date.parse(value))
14
+ : new DateObj(proto, new Date(coerceToNumber(value)).getTime()));
15
+ }
16
+ // The spec converts at most seven components, in order, so extra arguments never run program code.
17
+ return toNumbers(args.slice(0, 7), (parts) => new DateObj(proto, new Date(...parts).getTime()));
18
+ };
19
+ // ToNumber on each value in turn, so a symbol throws before any later value's conversion runs program code.
20
+ const toNumbers = (values, body) => withPrimitives("number", values, (primitives) => body(primitives.map(coerceToNumber)), true);
21
+ const getters = [
22
+ "getFullYear",
23
+ "getMonth",
24
+ "getDate",
25
+ "getDay",
26
+ "getHours",
27
+ "getMinutes",
28
+ "getSeconds",
29
+ "getMilliseconds",
30
+ "getUTCFullYear",
31
+ "getUTCMonth",
32
+ "getUTCDate",
33
+ "getUTCDay",
34
+ "getUTCHours",
35
+ "getUTCMinutes",
36
+ "getUTCSeconds",
37
+ "getUTCMilliseconds",
38
+ "getTimezoneOffset",
39
+ ];
40
+ const setters = [
41
+ ["setTime", 1],
42
+ ["setMilliseconds", 1],
43
+ ["setUTCMilliseconds", 1],
44
+ ["setSeconds", 2],
45
+ ["setUTCSeconds", 2],
46
+ ["setMinutes", 3],
47
+ ["setUTCMinutes", 3],
48
+ ["setHours", 4],
49
+ ["setUTCHours", 4],
50
+ ["setDate", 1],
51
+ ["setUTCDate", 1],
52
+ ["setMonth", 2],
53
+ ["setUTCMonth", 2],
54
+ ["setFullYear", 3],
55
+ ["setUTCFullYear", 3],
56
+ ];
57
+ export const dateGlobal = (ctx) => {
58
+ const builtins = ctx.builtins;
59
+ const proto = builtins.Date;
60
+ const date = constructor(builtins, proto, {
61
+ name: "Date",
62
+ length: 7,
63
+ // ISO instead of the host's locale string: date strings are deterministic and must not leak the host timezone.
64
+ call: () => new Date().toISOString(),
65
+ construct: (args, newTarget) => constructDate(args, prototypeFrom(newTarget, proto)),
66
+ });
67
+ methods(builtins, date, [
68
+ ["now", 0, () => Date.now()],
69
+ ["parse", 1, (_, args) => Date.parse(coerceToString(args[0]))],
70
+ [
71
+ "UTC",
72
+ 7,
73
+ (_, args) => toNumbers(args.slice(0, 7), (parts) => Date.UTC(...parts)),
74
+ ],
75
+ ]);
76
+ const self = (thisValue, name) => receiver(DateObj, thisValue, `Date.prototype.${name}`);
77
+ const iso = (value) => {
78
+ if (!Number.isFinite(value.time))
79
+ throw rangeError("Invalid time value.");
80
+ return new Date(value.time).toISOString();
81
+ };
82
+ methods(builtins, proto, [
83
+ ["getTime", 0, (thisValue) => self(thisValue, "getTime").time],
84
+ ["valueOf", 0, (thisValue) => self(thisValue, "valueOf").time],
85
+ ["toISOString", 0, (thisValue) => iso(self(thisValue, "toISOString"))],
86
+ [
87
+ "toJSON",
88
+ 1,
89
+ (thisValue) => {
90
+ const value = self(thisValue, "toJSON");
91
+ return Number.isFinite(value.time) ? iso(value) : null;
92
+ },
93
+ ],
94
+ ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
95
+ ["toDateString", 0, (thisValue) => new Date(self(thisValue, "toDateString").time).toDateString()],
96
+ ["toTimeString", 0, (thisValue) => new Date(self(thisValue, "toTimeString").time).toTimeString()],
97
+ ["toUTCString", 0, (thisValue) => new Date(self(thisValue, "toUTCString").time).toUTCString()],
98
+ ["toGMTString", 0, (thisValue) => new Date(self(thisValue, "toGMTString").time).toUTCString()],
99
+ ...["toLocaleString", "toLocaleDateString", "toLocaleTimeString"].map((name) => [
100
+ name,
101
+ 0,
102
+ (thisValue) => new Date(self(thisValue, name).time)[name]("en-US", { timeZone: "UTC" }),
103
+ ]),
104
+ ...getters.map((name) => [name, 0, (thisValue) => new Date(self(thisValue, name).time)[name]()]),
105
+ ...setters.map(([name, length]) => [
106
+ name,
107
+ length,
108
+ (thisValue, args) => {
109
+ const target = self(thisValue, name);
110
+ // Native setters read the current time before argument coercion, whose callbacks may mutate the Date.
111
+ return toNumbers([target.time, ...args.slice(0, length)], ([time, ...values]) => {
112
+ const hosted = new Date(time);
113
+ // Every setter but setTime and setFullYear leaves an invalid Date untouched and answers NaN.
114
+ if (Number.isNaN(hosted.getTime()) && name !== "setTime" && !name.endsWith("FullYear"))
115
+ return NaN;
116
+ target.time = hosted[name](...values);
117
+ return target.time;
118
+ });
119
+ },
120
+ ]),
121
+ ]);
122
+ return date;
123
+ };
@@ -0,0 +1,2 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ export declare const headersGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,92 @@
1
+ import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js";
2
+ import { IteratorSymbol, typeError } from "../runtime/model.js";
3
+ import { define, get, hidden, Arr, HeadersObj, Obj, coerceToString } from "../runtime/objects.js";
4
+ import { requireCallback } from "../runtime/callback.js";
5
+ import { attempt, pairsForEach, readPairs } from "./url.js";
6
+ const constructHeaders = (ctx, init, proto) => {
7
+ if (init === undefined)
8
+ return new HeadersObj(proto, new Headers());
9
+ if (init instanceof Obj)
10
+ return readPairs(ctx, init, "new Headers(...)", { kind: "Headers", proto });
11
+ throw typeError("new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.");
12
+ };
13
+ export const headersGlobal = (ctx) => {
14
+ const builtins = ctx.builtins;
15
+ const proto = builtins.Headers;
16
+ const headers = constructor(builtins, proto, {
17
+ name: "Headers",
18
+ call: requiresNew("Headers"),
19
+ construct: (args, newTarget) => constructHeaders(ctx, args[0], prototypeFrom(newTarget, proto)),
20
+ });
21
+ const self = (thisValue, name) => receiver(HeadersObj, thisValue, `Headers.prototype.${name}`);
22
+ const wrap = (items) => new Arr(builtins.Array, items);
23
+ const arg = (args, index) => coerceToString(args[index]);
24
+ const requireArgs = (name, args, count) => {
25
+ if (args.length < count)
26
+ throw typeError(`Headers.${name} requires ${count} argument${count === 1 ? "" : "s"}.`);
27
+ };
28
+ methods(builtins, proto, [
29
+ [
30
+ "append",
31
+ 2,
32
+ (thisValue, args) => {
33
+ requireArgs("append", args, 2);
34
+ const target = self(thisValue, "append").headers;
35
+ attempt(() => target.append(arg(args, 0), arg(args, 1)));
36
+ return undefined;
37
+ },
38
+ ],
39
+ [
40
+ "delete",
41
+ 1,
42
+ (thisValue, args) => {
43
+ requireArgs("delete", args, 1);
44
+ const target = self(thisValue, "delete").headers;
45
+ attempt(() => target.delete(arg(args, 0)));
46
+ return undefined;
47
+ },
48
+ ],
49
+ [
50
+ "get",
51
+ 1,
52
+ (thisValue, args) => {
53
+ requireArgs("get", args, 1);
54
+ const target = self(thisValue, "get").headers;
55
+ return attempt(() => target.get(arg(args, 0)));
56
+ },
57
+ ],
58
+ ["getSetCookie", 0, (thisValue) => wrap(self(thisValue, "getSetCookie").headers.getSetCookie())],
59
+ [
60
+ "has",
61
+ 1,
62
+ (thisValue, args) => {
63
+ requireArgs("has", args, 1);
64
+ const target = self(thisValue, "has").headers;
65
+ return attempt(() => target.has(arg(args, 0)));
66
+ },
67
+ ],
68
+ [
69
+ "set",
70
+ 2,
71
+ (thisValue, args) => {
72
+ requireArgs("set", args, 2);
73
+ const target = self(thisValue, "set").headers;
74
+ attempt(() => target.set(arg(args, 0), arg(args, 1)));
75
+ return undefined;
76
+ },
77
+ ],
78
+ ...iteratorMethods(builtins, self),
79
+ [
80
+ "forEach",
81
+ 1,
82
+ (thisValue, args) => {
83
+ requireArgs("forEach", args, 1);
84
+ const target = self(thisValue, "forEach");
85
+ const callback = requireCallback(args[0], "Headers.forEach");
86
+ return pairsForEach(ctx, target, Array.from(target.headers.entries()), callback, args[1]);
87
+ },
88
+ ],
89
+ ]);
90
+ define(proto, IteratorSymbol, get(proto, "entries"), hidden);
91
+ return headers;
92
+ };
@@ -0,0 +1,2 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ export declare const iteratorGlobals: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,30 @@
1
+ import { typeError } from "../runtime/model.js";
2
+ import { constructor, methods, receiver, requiresNew } from "../runtime/native.js";
3
+ import { iteratorResult, IteratorObj, Position } from "../runtime/objects.js";
4
+ // Every built-in iterator and helper shares the Iterator prototype; JS gives each collection its own, which is only
5
+ // observable through getPrototypeOf. The helpers (`map`, `take`, `Iterator.from`, ...) are the prelude's.
6
+ export const iteratorGlobals = (ctx) => {
7
+ const builtins = ctx.builtins;
8
+ const proto = builtins.Iterator;
9
+ methods(builtins, proto, [
10
+ [
11
+ "next",
12
+ 0,
13
+ (thisValue) => {
14
+ const cursor = receiver(IteratorObj, thisValue, "Iterator.prototype.next").cursor;
15
+ if (!(cursor instanceof Position))
16
+ throw typeError("Iterator.prototype.next called on an internal iterator.");
17
+ const step = cursor.step();
18
+ return iteratorResult(builtins.Object, step.value, step.done);
19
+ },
20
+ ],
21
+ ]);
22
+ return constructor(builtins, proto, {
23
+ name: "Iterator",
24
+ length: 0,
25
+ call: requiresNew("Iterator"),
26
+ construct: () => {
27
+ throw typeError("Iterator is abstract; use Iterator.from(...) or a built-in iterator.");
28
+ },
29
+ });
30
+ };
@@ -0,0 +1,3 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ import { Obj } from "../runtime/objects.js";
3
+ export declare const jsonGlobal: <R>(ctx: Interpreter<R>) => Obj;
@@ -0,0 +1,42 @@
1
+ import { methods } from "../runtime/native.js";
2
+ import { requireCallback } from "../runtime/callback.js";
3
+ import { syntaxError } from "../runtime/model.js";
4
+ import { typeofValue } from "../runtime/references.js";
5
+ import { fromJson } from "../data.js";
6
+ import { Arr, Obj, coerceToString, record } from "../runtime/objects.js";
7
+ import { Invoke, Push } from "../runtime/signals.js";
8
+ export const jsonGlobal = (ctx) => {
9
+ const json = new Obj(ctx.builtins.Object);
10
+ methods(ctx.builtins, json, [
11
+ ["parse", 2, (_, args) => parse(ctx, args)],
12
+ ["stringify", 3, (_, args) => stringify(args)],
13
+ ]);
14
+ return json;
15
+ };
16
+ const parse = (ctx, args) => {
17
+ const text = coerceToString(args[0]);
18
+ const parsed = (() => {
19
+ try {
20
+ return fromJson(ctx, JSON.parse(text));
21
+ }
22
+ catch (error) {
23
+ throw syntaxError(`JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
24
+ }
25
+ })();
26
+ if (typeofValue(args[1]) !== "function")
27
+ return parsed;
28
+ const reviver = requireCallback(args[1], "JSON.parse");
29
+ return new Invoke(ctx.prelude.fn("revive"), undefined, [record(ctx.builtins.Object, { "": parsed }), "", reviver], undefined);
30
+ };
31
+ const stringify = (args) => {
32
+ const space = args[2];
33
+ const indent = typeof space === "number" || typeof space === "string" ? space : undefined;
34
+ const replacer = args[1];
35
+ const properties = replacer instanceof Arr
36
+ ? replacer.items
37
+ .filter((item) => typeof item === "string" || typeof item === "number")
38
+ .map(String)
39
+ : undefined;
40
+ const callback = typeofValue(replacer) === "function" ? requireCallback(replacer, "JSON.stringify") : undefined;
41
+ return new Push("JSON.stringify", [args[0], callback, properties, indent]);
42
+ };
@@ -0,0 +1,3 @@
1
+ import { Obj } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ export declare const mathGlobal: <R>(ctx: Interpreter<R>) => Obj;
@@ -0,0 +1,73 @@
1
+ import { constants, methods } from "../runtime/native.js";
2
+ import { Obj, coerceToNumber } from "../runtime/objects.js";
3
+ import { withPrimitives } from "../runtime/callback.js";
4
+ export const mathGlobal = (ctx) => {
5
+ const builtins = ctx.builtins;
6
+ const math = new Obj(builtins.Object);
7
+ // Convert only the arguments a method consumes; like JS, extras are ignored
8
+ // (so built-ins work as callbacks receiving (element, index, array)).
9
+ const unary = (name, op) => [
10
+ name,
11
+ 1,
12
+ (_, args) => withPrimitives("number", [args[0]], ([a]) => op(coerceToNumber(a))),
13
+ ];
14
+ const binary = (name, op) => [
15
+ name,
16
+ 2,
17
+ (_, args) => withPrimitives("number", [args[0], args[1]], ([a, b]) => op(coerceToNumber(a), coerceToNumber(b))),
18
+ ];
19
+ const variadic = (name, op) => [
20
+ name,
21
+ 2,
22
+ (_, args) => withPrimitives("number", args, (values) => op(...values.map(coerceToNumber))),
23
+ ];
24
+ constants(math, {
25
+ PI: Math.PI,
26
+ E: Math.E,
27
+ LN2: Math.LN2,
28
+ LN10: Math.LN10,
29
+ LOG2E: Math.LOG2E,
30
+ LOG10E: Math.LOG10E,
31
+ SQRT2: Math.SQRT2,
32
+ SQRT1_2: Math.SQRT1_2,
33
+ });
34
+ methods(builtins, math, [
35
+ ["random", 0, () => Math.random()],
36
+ variadic("max", Math.max),
37
+ variadic("min", Math.min),
38
+ variadic("hypot", Math.hypot),
39
+ unary("abs", Math.abs),
40
+ unary("acos", Math.acos),
41
+ unary("acosh", Math.acosh),
42
+ unary("asin", Math.asin),
43
+ unary("asinh", Math.asinh),
44
+ unary("atan", Math.atan),
45
+ binary("atan2", Math.atan2),
46
+ unary("atanh", Math.atanh),
47
+ unary("floor", Math.floor),
48
+ unary("ceil", Math.ceil),
49
+ unary("round", Math.round),
50
+ unary("trunc", Math.trunc),
51
+ unary("sign", Math.sign),
52
+ unary("sqrt", Math.sqrt),
53
+ unary("cbrt", Math.cbrt),
54
+ binary("pow", Math.pow),
55
+ unary("cos", Math.cos),
56
+ unary("cosh", Math.cosh),
57
+ unary("sin", Math.sin),
58
+ unary("sinh", Math.sinh),
59
+ unary("tan", Math.tan),
60
+ unary("tanh", Math.tanh),
61
+ unary("log", Math.log),
62
+ unary("log2", Math.log2),
63
+ unary("log10", Math.log10),
64
+ unary("log1p", Math.log1p),
65
+ unary("exp", Math.exp),
66
+ unary("expm1", Math.expm1),
67
+ unary("f16round", Math.f16round),
68
+ unary("fround", Math.fround),
69
+ unary("clz32", Math.clz32),
70
+ binary("imul", Math.imul),
71
+ ]);
72
+ return math;
73
+ };