@opencode/codemode 0.0.0-dev-892 → 0.0.0-dev-900

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 (117) hide show
  1. package/README.md +3 -0
  2. package/dist/codemode.d.ts +2 -0
  3. package/dist/codemode.js +10 -4
  4. package/dist/vm/async.d.ts +78 -0
  5. package/dist/vm/async.js +335 -0
  6. package/dist/vm/code.d.ts +122 -0
  7. package/dist/vm/code.js +407 -0
  8. package/dist/vm/compiler/compile.d.ts +13 -0
  9. package/dist/vm/compiler/compile.js +1477 -0
  10. package/dist/vm/compiler/scope.d.ts +74 -0
  11. package/dist/vm/compiler/scope.js +515 -0
  12. package/dist/vm/data.d.ts +7 -0
  13. package/dist/vm/data.js +13 -0
  14. package/dist/vm/generators.d.ts +42 -0
  15. package/dist/vm/generators.js +413 -0
  16. package/dist/vm/host.d.ts +103 -0
  17. package/dist/vm/host.js +226 -0
  18. package/dist/vm/index.d.ts +3 -0
  19. package/dist/vm/index.js +3 -0
  20. package/dist/vm/internal-prelude.d.ts +45 -0
  21. package/dist/vm/internal-prelude.js +534 -0
  22. package/dist/vm/opcodes.d.ts +222 -0
  23. package/dist/vm/opcodes.js +235 -0
  24. package/dist/vm/prelude/bytecode.d.ts +18 -0
  25. package/dist/vm/prelude/bytecode.js +31 -0
  26. package/dist/vm/prelude/bytecode.json +1 -0
  27. package/dist/vm/prelude/helpers.d.ts +8 -0
  28. package/dist/vm/prelude/helpers.js +258 -0
  29. package/dist/vm/prelude/prelude.d.ts +21 -0
  30. package/dist/vm/prelude/prelude.js +53 -0
  31. package/dist/vm/prelude/source.d.ts +1 -0
  32. package/dist/vm/prelude/source.js +652 -0
  33. package/dist/vm/runtime/callback.d.ts +25 -0
  34. package/dist/vm/runtime/callback.js +51 -0
  35. package/dist/vm/runtime/driver.d.ts +41 -0
  36. package/dist/vm/runtime/driver.js +142 -0
  37. package/dist/vm/runtime/errors.d.ts +23 -0
  38. package/dist/vm/runtime/errors.js +169 -0
  39. package/dist/vm/runtime/execute.d.ts +22 -0
  40. package/dist/vm/runtime/execute.js +278 -0
  41. package/dist/vm/runtime/extensions.d.ts +16 -0
  42. package/dist/vm/runtime/extensions.js +270 -0
  43. package/dist/vm/runtime/generators.d.ts +6 -0
  44. package/dist/vm/runtime/generators.js +44 -0
  45. package/dist/vm/runtime/globals.d.ts +6 -0
  46. package/dist/vm/runtime/globals.js +137 -0
  47. package/dist/vm/runtime/interpreter.d.ts +50 -0
  48. package/dist/vm/runtime/interpreter.js +94 -0
  49. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  50. package/dist/vm/runtime/intrinsic-names.js +166 -0
  51. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  52. package/dist/vm/runtime/intrinsics.js +111 -0
  53. package/dist/vm/runtime/limits.d.ts +10 -0
  54. package/dist/vm/runtime/limits.js +19 -0
  55. package/dist/vm/runtime/model.d.ts +58 -0
  56. package/dist/vm/runtime/model.js +57 -0
  57. package/dist/vm/runtime/modules.d.ts +4 -0
  58. package/dist/vm/runtime/modules.js +33 -0
  59. package/dist/vm/runtime/native.d.ts +19 -0
  60. package/dist/vm/runtime/native.js +41 -0
  61. package/dist/vm/runtime/objects.d.ts +403 -0
  62. package/dist/vm/runtime/objects.js +784 -0
  63. package/dist/vm/runtime/operations.d.ts +49 -0
  64. package/dist/vm/runtime/operations.js +288 -0
  65. package/dist/vm/runtime/promises.d.ts +55 -0
  66. package/dist/vm/runtime/promises.js +232 -0
  67. package/dist/vm/runtime/references.d.ts +8 -0
  68. package/dist/vm/runtime/references.js +51 -0
  69. package/dist/vm/runtime/signals.d.ts +69 -0
  70. package/dist/vm/runtime/signals.js +68 -0
  71. package/dist/vm/runtime/source.d.ts +29 -0
  72. package/dist/vm/runtime/source.js +63 -0
  73. package/dist/vm/runtime/table.d.ts +43 -0
  74. package/dist/vm/runtime/table.js +132 -0
  75. package/dist/vm/scheduler.d.ts +178 -0
  76. package/dist/vm/scheduler.js +63 -0
  77. package/dist/vm/snapshot/codec.d.ts +88 -0
  78. package/dist/vm/snapshot/codec.js +752 -0
  79. package/dist/vm/snapshot/snapshot.d.ts +39 -0
  80. package/dist/vm/snapshot/snapshot.js +69 -0
  81. package/dist/vm/snapshot.d.ts +29 -0
  82. package/dist/vm/snapshot.js +304 -0
  83. package/dist/vm/stdlib/array.d.ts +16 -0
  84. package/dist/vm/stdlib/array.js +311 -0
  85. package/dist/vm/stdlib/bytes.d.ts +11 -0
  86. package/dist/vm/stdlib/bytes.js +222 -0
  87. package/dist/vm/stdlib/collections.d.ts +7 -0
  88. package/dist/vm/stdlib/collections.js +188 -0
  89. package/dist/vm/stdlib/console.d.ts +6 -0
  90. package/dist/vm/stdlib/console.js +93 -0
  91. package/dist/vm/stdlib/date.d.ts +2 -0
  92. package/dist/vm/stdlib/date.js +123 -0
  93. package/dist/vm/stdlib/headers.d.ts +2 -0
  94. package/dist/vm/stdlib/headers.js +92 -0
  95. package/dist/vm/stdlib/iterator.d.ts +2 -0
  96. package/dist/vm/stdlib/iterator.js +30 -0
  97. package/dist/vm/stdlib/json.d.ts +3 -0
  98. package/dist/vm/stdlib/json.js +42 -0
  99. package/dist/vm/stdlib/math.d.ts +3 -0
  100. package/dist/vm/stdlib/math.js +73 -0
  101. package/dist/vm/stdlib/number.d.ts +3 -0
  102. package/dist/vm/stdlib/number.js +72 -0
  103. package/dist/vm/stdlib/object.d.ts +6 -0
  104. package/dist/vm/stdlib/object.js +201 -0
  105. package/dist/vm/stdlib/regexp.d.ts +8 -0
  106. package/dist/vm/stdlib/regexp.js +119 -0
  107. package/dist/vm/stdlib/string.d.ts +2 -0
  108. package/dist/vm/stdlib/string.js +272 -0
  109. package/dist/vm/stdlib/url.d.ts +25 -0
  110. package/dist/vm/stdlib/url.js +255 -0
  111. package/dist/vm/stdlib/value.d.ts +6 -0
  112. package/dist/vm/stdlib/value.js +32 -0
  113. package/dist/vm/stdlib/web.d.ts +5 -0
  114. package/dist/vm/stdlib/web.js +97 -0
  115. package/dist/vm/vm.d.ts +224 -0
  116. package/dist/vm/vm.js +2921 -0
  117. package/package.json +5 -2
@@ -0,0 +1,784 @@
1
+ import { ToolReference } from "../../tool-runtime.js";
2
+ import { checkArrayLength } from "./limits.js";
3
+ import { AsyncIteratorSymbol, IteratorSymbol, rangeError, Throw, typeError, } from "./model.js";
4
+ import { Invoke } from "./signals.js";
5
+ import { CodeFlags } from "../opcodes.js";
6
+ import { OrderedTable } from "./table.js";
7
+ // The objects made while a runtime's intrinsics are being made, in creation order; see `makingIntrinsics`.
8
+ let making;
9
+ /**
10
+ * Runs `make`, which makes a runtime's intrinsics, and returns every object made meanwhile, in creation order, after
11
+ * `first` (the built-in prototypes, made before). An object's index in the list is its static intrinsic id.
12
+ */
13
+ export const makingIntrinsics = (first, make) => {
14
+ const made = [...first];
15
+ making = made;
16
+ try {
17
+ return [make(), made];
18
+ }
19
+ finally {
20
+ making = undefined;
21
+ }
22
+ };
23
+ /** Marks an intrinsic as changed by the program, so saving a run records it; any other object is left alone. */
24
+ export const changed = (target) => {
25
+ if (target.intrinsic > 0)
26
+ target.intrinsic = -target.intrinsic;
27
+ };
28
+ /** Ordinary assignment: writable, enumerable, configurable. */
29
+ export const data = { writable: true, enumerable: true, configurable: true };
30
+ /** Built-in methods and `constructor`: writable and configurable but hidden from enumeration. */
31
+ export const hidden = { writable: true, enumerable: false, configurable: true };
32
+ /** Function `name` and `length`: read-only but deletable. */
33
+ export const readonly = { writable: false, enumerable: false, configurable: true };
34
+ /** Constants such as `Math.PI` and a constructor's `prototype`. */
35
+ export const frozen = { writable: false, enumerable: false, configurable: false };
36
+ /**
37
+ * An object owned by the program: own properties plus a prototype link. Subclasses answer, in one place, how a
38
+ * built-in kind of object prints, coerces, iterates, and crosses to the host.
39
+ */
40
+ export class Obj {
41
+ proto;
42
+ props = new Map();
43
+ /** [[Extensible]]: cleared by `Object.preventExtensions`, `seal`, and `freeze`. */
44
+ extensible = true;
45
+ /**
46
+ * 0 for an object the program made. For an intrinsic, its id plus one while it is as the runtime made it, negated
47
+ * once it changes (see `changed` and `IntrinsicNames`).
48
+ */
49
+ intrinsic = 0;
50
+ constructor(proto) {
51
+ this.proto = proto;
52
+ if (making !== undefined)
53
+ making.push(this);
54
+ }
55
+ /** The class name `Object.prototype.toString` reports: `[object Map]`. */
56
+ tag = "Object";
57
+ /** How diagnostics refer to a value of this kind. */
58
+ get describe() {
59
+ if (this.tag === "Object")
60
+ return "a data object";
61
+ return `${/^[AEIO]/.test(this.tag) ? "an" : "a"} ${this.tag}`;
62
+ }
63
+ /** ToString without consulting program-defined methods. */
64
+ toString() {
65
+ return `[object ${this.tag}]`;
66
+ }
67
+ /** ToPrimitive without consulting program-defined methods: only a Date answers a number hint differently. */
68
+ toPrimitive(hint) {
69
+ return this.toString();
70
+ }
71
+ /** ToNumber without consulting program-defined methods. */
72
+ toNumber() {
73
+ return Number(this.toPrimitive("number"));
74
+ }
75
+ /** How `console.log` shows the value; `item` formats a child with cycle and depth tracking. */
76
+ inspect(item) {
77
+ return `{${entries(this)
78
+ .map(([key, value]) => `${JSON.stringify(key)}:${item(value)}`)
79
+ .join(",")}}`;
80
+ }
81
+ /** A copy the host can hold; `item` converts a child. A `__proto__` key never reaches host code. */
82
+ toHost(item) {
83
+ return Object.fromEntries(entries(this)
84
+ .filter(([key]) => key !== "__proto__")
85
+ .map(([key, value]) => [key, item(value)]));
86
+ }
87
+ /** The built-in iteration `for...of` and spread use, when this kind of object has one. */
88
+ iterator(builtins) {
89
+ return undefined;
90
+ }
91
+ }
92
+ export class Arr extends Obj {
93
+ items;
94
+ tag = "Array";
95
+ /** The attributes every live element shares; `seal` and `freeze` narrow them since elements have no slots. */
96
+ elements = data;
97
+ constructor(proto, items = []) {
98
+ super(proto);
99
+ this.items = items;
100
+ }
101
+ get describe() {
102
+ return "an array";
103
+ }
104
+ toString() {
105
+ return this.items.map((item) => (item === null || item === undefined ? "" : coerceToString(item))).join(",");
106
+ }
107
+ inspect(item) {
108
+ return `[${this.items.map(item).join(",")}]`;
109
+ }
110
+ toHost(item) {
111
+ return this.items.map(item);
112
+ }
113
+ iterator(builtins) {
114
+ return new Position(this, "values", builtins.Array);
115
+ }
116
+ }
117
+ /** An object with the [[ErrorData]] slot: what `Error.prototype.toString` and the host boundary recognize as an error. */
118
+ export class ErrorObj extends Obj {
119
+ tag = "Error";
120
+ /**
121
+ * The interpreter failure this error materialized from, so rethrowing it keeps the diagnostic kind and location. It
122
+ * is plain data (type, message, kind, suggestions, and the node it is located at), shared with the failure so a
123
+ * location attached later is seen here too.
124
+ */
125
+ failure;
126
+ /** Error.prototype.toString: "name: message", or just one when the other is empty. */
127
+ toString() {
128
+ const name = get(this, "name");
129
+ const message = get(this, "message");
130
+ const shownName = typeof name === "string" ? name : "Error";
131
+ const shownMessage = typeof message === "string" ? message : "";
132
+ if (shownMessage === "")
133
+ return shownName;
134
+ if (shownName === "")
135
+ return shownMessage;
136
+ return `${shownName}: ${shownMessage}`;
137
+ }
138
+ inspect() {
139
+ return this.toString();
140
+ }
141
+ }
142
+ /** Interpreter machinery a program can hold but never inspect, serialize, or hand to the host. */
143
+ export class Opaque extends Obj {
144
+ inspect() {
145
+ return "[opaque reference]";
146
+ }
147
+ }
148
+ export class Callable extends Opaque {
149
+ length;
150
+ tag = "Function";
151
+ constructor(proto, name, length) {
152
+ super(proto);
153
+ this.length = length;
154
+ define(this, "length", length, readonly);
155
+ define(this, "name", name, readonly);
156
+ }
157
+ get describe() {
158
+ return "a function";
159
+ }
160
+ }
161
+ /** A program or prelude function: its bytecode, and the cells of the bindings it captured. */
162
+ export class Fn extends Callable {
163
+ code;
164
+ cells;
165
+ constructor(proto, code, cells, name = code.name) {
166
+ super(proto, name, code.length);
167
+ this.code = code;
168
+ this.cells = cells;
169
+ }
170
+ get generator() {
171
+ return (this.code.flags & CodeFlags.GENERATOR) !== 0;
172
+ }
173
+ }
174
+ /** The strict `arguments` object: an ordinary object with indexed own properties and a hidden `length`. */
175
+ export class Arguments extends Obj {
176
+ tag = "Arguments";
177
+ constructor(proto, args) {
178
+ super(proto);
179
+ args.forEach((arg, index) => define(this, String(index), arg));
180
+ define(this, "length", args.length, hidden);
181
+ }
182
+ iterator(builtins) {
183
+ return new Position(keys(this).map((key) => get(this, key)), "values", builtins.Array);
184
+ }
185
+ }
186
+ /**
187
+ * Natives are made only with the intrinsics, so each one has an intrinsic name and run state never holds a host
188
+ * closure. When `check` is on (tests turn it on), making a native for a runtime whose intrinsics are `sealed` (keyed by
189
+ * its `Function.prototype`) throws, unless it declares one of the `RuntimeNative` exceptions.
190
+ */
191
+ export const nativeRule = {
192
+ check: false,
193
+ sealed: new WeakSet(),
194
+ };
195
+ /**
196
+ * A built-in function: a `Native` made with the intrinsics, or a data kind such as `BoundFn` or `Resolver` whose state
197
+ * is plain fields and whose behaviour lives on its class.
198
+ */
199
+ export class Builtin extends Callable {
200
+ }
201
+ export class Native extends Builtin {
202
+ call;
203
+ construct;
204
+ callback;
205
+ constructor(proto, options) {
206
+ if (nativeRule.check && options.runtime === undefined && nativeRule.sealed.has(proto)) {
207
+ throw new Error(`Native "${options.name}" was made after the intrinsics; make it a data kind instead.`);
208
+ }
209
+ super(proto, options.name, options.length ?? 0);
210
+ nativeRule.observe?.(this);
211
+ this.call = options.call;
212
+ this.construct = options.construct;
213
+ this.callback = options.callback ?? true;
214
+ }
215
+ invoke(thisValue, args, site) {
216
+ return this.call(thisValue, args, site);
217
+ }
218
+ }
219
+ /** `Function.prototype.bind`'s result: calls `target` with the bound receiver and leading arguments. */
220
+ export class BoundFn extends Builtin {
221
+ target;
222
+ boundThis;
223
+ boundArgs;
224
+ construct = undefined;
225
+ callback = true;
226
+ constructor(proto, target, boundThis, boundArgs) {
227
+ super(proto, `bound ${coerceToString(get(target, "name"))}`, Math.max(0, target.length - boundArgs.length));
228
+ this.target = target;
229
+ this.boundThis = boundThis;
230
+ this.boundArgs = boundArgs;
231
+ }
232
+ invoke(_, args, site) {
233
+ return new Invoke(this.target, this.boundThis, [...this.boundArgs, ...args], site);
234
+ }
235
+ }
236
+ /** A `resolve` or `reject` function handed to an executor or thenable: settles its shared `Resolving` once. */
237
+ export class Resolver extends Builtin {
238
+ resolving;
239
+ kind;
240
+ construct = undefined;
241
+ callback = true;
242
+ constructor(proto, name, resolving, kind) {
243
+ super(proto, name, 1);
244
+ this.resolving = resolving;
245
+ this.kind = kind;
246
+ }
247
+ invoke(_, args) {
248
+ if (this.kind === "resolve")
249
+ this.resolving.resolve(args[0]);
250
+ else
251
+ this.resolving.reject(new Throw(args[0]));
252
+ return undefined;
253
+ }
254
+ }
255
+ export class PromiseObj extends Opaque {
256
+ id;
257
+ tag = "Promise";
258
+ state = "pending";
259
+ /** The value, or the failure as thrown; a handler receives it materialized. */
260
+ result = undefined;
261
+ reactions = [];
262
+ /** [[PromiseIsHandled]]: a reaction was attached, so a rejection is not reported as unhandled. */
263
+ handled = false;
264
+ constructor(proto,
265
+ /** Creation order, for reporting unhandled rejections in the order their promises were made. */
266
+ id) {
267
+ super(proto);
268
+ this.id = id;
269
+ }
270
+ get describe() {
271
+ return "an un-awaited Promise";
272
+ }
273
+ inspect() {
274
+ return "[Promise (await it to get its value)]";
275
+ }
276
+ }
277
+ export class GeneratorObj extends Opaque {
278
+ asynchronous;
279
+ tag = "Generator";
280
+ state = "suspendedStart";
281
+ /** The suspended body's frame, kept while it waits for the next request, which puts it back on the job stack. */
282
+ frame = undefined;
283
+ /** An async generator's requests, oldest first, each with what settles its promise. */
284
+ queue = [];
285
+ constructor(proto, asynchronous) {
286
+ super(proto);
287
+ this.asynchronous = asynchronous;
288
+ }
289
+ get describe() {
290
+ return "a generator";
291
+ }
292
+ }
293
+ const finished = { done: true, value: undefined };
294
+ /**
295
+ * A built-in iterator's place in its source, as data: what it walks, what it yields, and the next index. Iteration is
296
+ * live, as in JS: an array iterator reads the length on every step, and a Map or Set iterator is kept in place by its
297
+ * table. Once done it stays done. There is nothing to close.
298
+ */
299
+ export class Position {
300
+ source;
301
+ kind;
302
+ arrays;
303
+ index = 0;
304
+ done = false;
305
+ constructor(source, kind,
306
+ /** The prototype of the `[key, value]` arrays `entries()` yields. */
307
+ arrays) {
308
+ this.source = source;
309
+ this.kind = kind;
310
+ this.arrays = arrays;
311
+ if (source instanceof MapObj)
312
+ source.map.track(this);
313
+ if (source instanceof SetObj)
314
+ source.set.track(this);
315
+ }
316
+ step() {
317
+ if (this.done)
318
+ return finished;
319
+ const source = this.source;
320
+ if (typeof source === "string") {
321
+ if (this.index >= source.length)
322
+ return this.finish();
323
+ const point = source.codePointAt(this.index);
324
+ const value = source.slice(this.index, this.index + (point > 0xffff ? 2 : 1));
325
+ this.index += value.length;
326
+ return { done: false, value };
327
+ }
328
+ if (source instanceof MapObj || source instanceof SetObj) {
329
+ const table = source instanceof MapObj ? source.map : source.set;
330
+ const at = table.advance(this);
331
+ if (at < 0)
332
+ return finished;
333
+ const key = table.keys[at];
334
+ return this.yield(key, source instanceof MapObj ? table.values[at] : key);
335
+ }
336
+ if (source instanceof HeadersObj || source instanceof URLSearchParamsObj) {
337
+ // The host recomputes the sorted list on every step, as the spec's pair iterators do.
338
+ const list = Array.from(source instanceof HeadersObj ? source.headers.entries() : source.params.entries());
339
+ const entry = list[this.index];
340
+ if (entry === undefined)
341
+ return this.finish();
342
+ this.index++;
343
+ return this.yield(entry[0], entry[1]);
344
+ }
345
+ const items = source instanceof Arr ? source.items : source instanceof Bytes ? source.bytes : source;
346
+ if (this.index >= items.length)
347
+ return this.finish();
348
+ const at = this.index++;
349
+ return this.yield(at, items[at]);
350
+ }
351
+ yield(key, value) {
352
+ if (this.kind === "keys")
353
+ return { done: false, value: key };
354
+ if (this.kind === "values")
355
+ return { done: false, value };
356
+ return { done: false, value: new Arr(this.arrays, [key, value]) };
357
+ }
358
+ finish() {
359
+ this.done = true;
360
+ return finished;
361
+ }
362
+ }
363
+ /** A built-in iterator: a live cursor over a host collection or an iterator helper, yielding program values. */
364
+ export class IteratorObj extends Opaque {
365
+ cursor;
366
+ tag = "Iterator";
367
+ constructor(proto, cursor) {
368
+ super(proto);
369
+ this.cursor = cursor;
370
+ }
371
+ get describe() {
372
+ return "an iterator";
373
+ }
374
+ }
375
+ /** A built-in iterator over a collection, e.g. `array.values()`. */
376
+ export const positionIterator = (builtins, source, kind) => new IteratorObj(builtins.Iterator, new Position(source, kind, builtins.Array));
377
+ /** A built-in object around a host value: data-like, so it prints as itself and crosses to extensions as a copy. */
378
+ export class Wrapper extends Obj {
379
+ inspect(item) {
380
+ return this.toString();
381
+ }
382
+ }
383
+ export class DateObj extends Wrapper {
384
+ time;
385
+ tag = "Date";
386
+ constructor(proto, time) {
387
+ super(proto);
388
+ this.time = time;
389
+ }
390
+ toString() {
391
+ return Number.isFinite(this.time) ? new Date(this.time).toISOString() : "Invalid Date";
392
+ }
393
+ toPrimitive(hint) {
394
+ return hint === "number" ? this.time : this.toString();
395
+ }
396
+ toHost() {
397
+ return new Date(this.time);
398
+ }
399
+ }
400
+ /** A RegExp as data: its source, flags, and `lastIndex`; the host regex is only a compiled cache of the first two. */
401
+ export class RegExpObj extends Wrapper {
402
+ tag = "RegExp";
403
+ source;
404
+ flags;
405
+ /** Shared by `exec`/`test` and the String methods, as the host regex's own `lastIndex` would be. */
406
+ lastIndex = 0;
407
+ compiled;
408
+ constructor(proto, pattern, flags) {
409
+ super(proto);
410
+ // Compiling validates the pattern and flags, and normalizes both as the host spells them.
411
+ this.compiled = new RegExp(pattern, flags);
412
+ this.source = this.compiled.source;
413
+ this.flags = this.compiled.flags;
414
+ }
415
+ /** The compiled regex, for reading what it is; anything that matches goes through `use`. */
416
+ get regex() {
417
+ this.compiled ??= new RegExp(this.source, this.flags);
418
+ return this.compiled;
419
+ }
420
+ /** Runs host regex work starting from this object's `lastIndex`, and keeps the `lastIndex` the work leaves. */
421
+ use(work) {
422
+ const regex = this.regex;
423
+ regex.lastIndex = this.lastIndex;
424
+ try {
425
+ return work(regex);
426
+ }
427
+ finally {
428
+ this.lastIndex = regex.lastIndex;
429
+ }
430
+ }
431
+ toString() {
432
+ return `/${this.source}/${this.flags}`;
433
+ }
434
+ toHost() {
435
+ return new RegExp(this.source, this.flags);
436
+ }
437
+ }
438
+ export class MapObj extends Wrapper {
439
+ tag = "Map";
440
+ map = new OrderedTable();
441
+ inspect(item) {
442
+ return `Map(${this.map.size}) [${[...this.map].map(([key, value]) => `[${item(key)},${item(value)}]`).join(",")}]`;
443
+ }
444
+ toHost(item) {
445
+ return new Map([...this.map].map(([key, value]) => [item(key), item(value)]));
446
+ }
447
+ iterator(builtins) {
448
+ return new Position(this, "entries", builtins.Array);
449
+ }
450
+ }
451
+ export class SetObj extends Wrapper {
452
+ tag = "Set";
453
+ set = new OrderedTable();
454
+ inspect(item) {
455
+ return `Set(${this.set.size}) [${[...this.set.liveKeys()].map(item).join(",")}]`;
456
+ }
457
+ toHost(item) {
458
+ return new Set([...this.set.liveKeys()].map(item));
459
+ }
460
+ iterator(builtins) {
461
+ return new Position(this, "values", builtins.Array);
462
+ }
463
+ }
464
+ /**
465
+ * Keys are held strongly for the run, which is short-lived; garbage collection is not observable in Code Mode, and a
466
+ * plain table keeps the state as data.
467
+ */
468
+ export class WeakMapObj extends Wrapper {
469
+ tag = "WeakMap";
470
+ map = new Map();
471
+ inspect() {
472
+ return "WeakMap { <items unknown> }";
473
+ }
474
+ }
475
+ export class WeakSetObj extends Wrapper {
476
+ tag = "WeakSet";
477
+ set = new Set();
478
+ inspect() {
479
+ return "WeakSet { <items unknown> }";
480
+ }
481
+ }
482
+ export class URLSearchParamsObj extends Wrapper {
483
+ params;
484
+ tag = "URLSearchParams";
485
+ constructor(proto, params) {
486
+ super(proto);
487
+ this.params = params;
488
+ }
489
+ toString() {
490
+ return this.params.toString();
491
+ }
492
+ toHost() {
493
+ return new URLSearchParams(this.params);
494
+ }
495
+ iterator(builtins) {
496
+ return new Position(this, "entries", builtins.Array);
497
+ }
498
+ }
499
+ export class HeadersObj extends Wrapper {
500
+ headers;
501
+ tag = "Headers";
502
+ constructor(proto, headers) {
503
+ super(proto);
504
+ this.headers = headers;
505
+ }
506
+ inspect() {
507
+ return `Headers ${JSON.stringify(Object.fromEntries(this.headers))}`;
508
+ }
509
+ toHost() {
510
+ return new Headers(this.headers);
511
+ }
512
+ iterator(builtins) {
513
+ return new Position(this, "entries", builtins.Array);
514
+ }
515
+ }
516
+ export class URLObj extends Wrapper {
517
+ url;
518
+ tag = "URL";
519
+ searchParams;
520
+ constructor(proto, searchParamsProto, url) {
521
+ super(proto);
522
+ this.url = url;
523
+ this.searchParams = new URLSearchParamsObj(searchParamsProto, url.searchParams);
524
+ }
525
+ toString() {
526
+ return this.url.href;
527
+ }
528
+ toHost() {
529
+ return new URL(this.url.href);
530
+ }
531
+ }
532
+ /** A `Uint8Array`: the host array does the byte clamping and ignores out-of-range writes, as JS does. */
533
+ export class Bytes extends Wrapper {
534
+ bytes;
535
+ tag = "Uint8Array";
536
+ constructor(proto, bytes) {
537
+ super(proto);
538
+ this.bytes = bytes;
539
+ }
540
+ toString() {
541
+ return this.bytes.join(",");
542
+ }
543
+ inspect() {
544
+ return `Uint8Array(${this.bytes.length}) [${this.bytes.join(",")}]`;
545
+ }
546
+ toHost() {
547
+ return new Uint8Array(this.bytes);
548
+ }
549
+ iterator(builtins) {
550
+ return new Position(this, "values", builtins.Array);
551
+ }
552
+ }
553
+ /** ToString without consulting program-defined methods. */
554
+ export const coerceToString = (value) => (value instanceof Obj ? value.toString() : String(value));
555
+ /** ToNumber without consulting program-defined methods; tool references are not numbers. */
556
+ export const coerceToNumber = (value) => {
557
+ if (value instanceof Obj)
558
+ return value.toNumber();
559
+ return value instanceof ToolReference ? Number.NaN : Number(value);
560
+ };
561
+ /** ToIntegerOrInfinity: NaN is 0, fractions truncate. */
562
+ export const coerceToInteger = (value) => {
563
+ const number = coerceToNumber(value);
564
+ return Number.isNaN(number) ? 0 : Math.trunc(number);
565
+ };
566
+ /** Values that cannot cross the data boundary: opaque machinery and host-backed wrappers. */
567
+ export const isRuntimeReference = (value) => value instanceof Opaque || value instanceof Wrapper || value instanceof ToolReference;
568
+ const MAX_ARRAY_INDEX = 4_294_967_295;
569
+ export const parseArrayIndex = (key) => {
570
+ if (typeof key === "number")
571
+ return Number.isInteger(key) && key >= 0 && key < MAX_ARRAY_INDEX ? key : undefined;
572
+ const property = String(key);
573
+ if (!/^(0|[1-9]\d*)$/.test(property))
574
+ return undefined;
575
+ const index = Number(property);
576
+ return index < MAX_ARRAY_INDEX ? index : undefined;
577
+ };
578
+ const canonical = (key) => (typeof key === "symbol" ? key : String(key));
579
+ const isIndexed = (target) => target instanceof Arr || target instanceof Bytes;
580
+ const elements = (target) => (target instanceof Arr ? target.items : target.bytes);
581
+ const index = (target, key) => isIndexed(target) && typeof key !== "symbol" ? parseArrayIndex(key) : undefined;
582
+ /** The own property under `key`, including an array's live indexes and `length`. */
583
+ export const own = (target, key) => {
584
+ // Most lookups are a name on a plain object or a prototype.
585
+ if (typeof key === "string" && !isIndexed(target))
586
+ return target.props.get(key);
587
+ const name = typeof key === "number" && isIndexed(target) ? key : canonical(key);
588
+ if (isIndexed(target)) {
589
+ const at = index(target, name);
590
+ if (at !== undefined) {
591
+ const items = elements(target);
592
+ if (!(at in items))
593
+ return undefined;
594
+ return { value: items[at], ...(target instanceof Arr ? target.elements : data) };
595
+ }
596
+ if (target instanceof Arr && name === "length") {
597
+ return { value: target.items.length, writable: target.elements.writable, enumerable: false, configurable: false };
598
+ }
599
+ }
600
+ return target.props.get(typeof name === "number" ? String(name) : name);
601
+ };
602
+ const read = (slot, receiver) => "value" in slot ? slot.value : slot.get === undefined ? undefined : slot.get(receiver);
603
+ export const hasOwn = (target, key) => own(target, key) !== undefined;
604
+ export const getOwn = (target, key) => {
605
+ const slot = own(target, key);
606
+ return slot === undefined ? undefined : read(slot, target);
607
+ };
608
+ /** [[Get]]: walks the prototype chain; accessors see `receiver`, which is the primitive for wrapper prototypes. */
609
+ export const get = (target, key, receiver = target) => {
610
+ // An array's present element, without making its property slot.
611
+ if (typeof key === "number" && target instanceof Arr && key in target.items && parseArrayIndex(key) !== undefined)
612
+ return target.items[key];
613
+ for (let current = target; current !== null; current = current.proto) {
614
+ const slot = own(current, key);
615
+ if (slot !== undefined)
616
+ return read(slot, receiver);
617
+ }
618
+ return undefined;
619
+ };
620
+ export const has = (target, key) => {
621
+ for (let current = target; current !== null; current = current.proto) {
622
+ if (own(current, key) !== undefined)
623
+ return true;
624
+ }
625
+ return false;
626
+ };
627
+ export const hasPrototype = (value, proto) => {
628
+ for (let current = value instanceof Obj ? value.proto : null; current !== null; current = current.proto) {
629
+ if (current === proto)
630
+ return true;
631
+ }
632
+ return false;
633
+ };
634
+ const writeElement = (target, name, value) => {
635
+ const at = index(target, name);
636
+ if (at !== undefined) {
637
+ if (target instanceof Bytes) {
638
+ target.bytes[at] = typeof value === "number" ? value : Number(value);
639
+ return true;
640
+ }
641
+ if (!(at in target.items))
642
+ rejectAddition(target, at);
643
+ changed(target);
644
+ target.items[at] = value;
645
+ return true;
646
+ }
647
+ if (!(target instanceof Arr) || name !== "length")
648
+ return undefined;
649
+ const length = typeof value === "number" ? value : Number(value);
650
+ if (!Number.isInteger(length) || length < 0)
651
+ throw rangeError("Invalid array length");
652
+ // Shrinking deletes elements, which a sealed array forbids.
653
+ if (length < target.items.length && !target.elements.configurable)
654
+ return false;
655
+ checkArrayLength(length);
656
+ changed(target);
657
+ target.items.length = length;
658
+ return true;
659
+ };
660
+ /** [[Set]]: an inherited setter or read-only property decides before an own data property is created. */
661
+ export const set = (target, key, value) => {
662
+ // Overwriting an array's present, writable element: no setter or read-only slot can decide first.
663
+ if (typeof key === "number" && target instanceof Arr && target.elements.writable && key in target.items) {
664
+ if (parseArrayIndex(key) !== undefined) {
665
+ changed(target);
666
+ target.items[key] = value;
667
+ return true;
668
+ }
669
+ }
670
+ const name = canonical(key);
671
+ for (let current = target; current !== null; current = current.proto) {
672
+ const slot = own(current, key);
673
+ if (slot === undefined)
674
+ continue;
675
+ if (!("value" in slot)) {
676
+ if (slot.set === undefined)
677
+ return false;
678
+ slot.set(target, value);
679
+ return true;
680
+ }
681
+ if (!slot.writable)
682
+ return false;
683
+ if (current !== target)
684
+ break;
685
+ if (isIndexed(target)) {
686
+ const written = writeElement(target, typeof key === "number" ? key : name, value);
687
+ if (written !== undefined)
688
+ return written;
689
+ }
690
+ changed(target);
691
+ slot.value = value;
692
+ return true;
693
+ }
694
+ if (isIndexed(target)) {
695
+ const written = writeElement(target, typeof key === "number" ? key : name, value);
696
+ if (written !== undefined)
697
+ return written;
698
+ }
699
+ rejectAddition(target, name);
700
+ changed(target);
701
+ target.props.set(name, { value, ...data });
702
+ return true;
703
+ };
704
+ /** Creating a property on a non-extensible object is the one [[Set]] failure with its own message. */
705
+ export const rejectAddition = (target, key) => {
706
+ if (target.extensible)
707
+ return;
708
+ throw typeError(`Cannot add property ${String(key)}, object is not extensible.`);
709
+ };
710
+ /** [[DefineOwnProperty]] for a data property, ignoring the chain. */
711
+ export const define = (target, key, value, attrs = data) => {
712
+ const name = canonical(key);
713
+ if (isIndexed(target) && writeElement(target, name, value) !== undefined)
714
+ return;
715
+ changed(target);
716
+ target.props.set(name, { value, ...attrs });
717
+ };
718
+ export const defineAccessor = (target, key, get, set) => {
719
+ changed(target);
720
+ target.props.set(canonical(key), { get, set, enumerable: false, configurable: true });
721
+ };
722
+ export const remove = (target, key) => {
723
+ const name = canonical(key);
724
+ if (isIndexed(target)) {
725
+ const at = index(target, name);
726
+ if (at !== undefined) {
727
+ if (target instanceof Bytes)
728
+ return !(at in target.bytes);
729
+ if (at in target.items && !target.elements.configurable)
730
+ return false;
731
+ changed(target);
732
+ return delete target.items[at];
733
+ }
734
+ if (target instanceof Arr && name === "length")
735
+ return false;
736
+ }
737
+ const slot = target.props.get(name);
738
+ if (slot === undefined)
739
+ return true;
740
+ if (!slot.configurable)
741
+ return false;
742
+ changed(target);
743
+ target.props.delete(name);
744
+ return true;
745
+ };
746
+ // JS order: array indexes, integer-like keys ascending, other strings, then symbols.
747
+ export const ownKeys = (target) => {
748
+ const strings = [...target.props.keys()].filter((key) => typeof key === "string");
749
+ const symbols = [...target.props.keys()].filter((key) => typeof key === "symbol");
750
+ return [
751
+ ...(isIndexed(target) ? Object.keys(elements(target)) : []),
752
+ ...(target instanceof Arr ? ["length"] : []),
753
+ ...strings.filter((key) => parseArrayIndex(key) !== undefined).sort((a, b) => Number(a) - Number(b)),
754
+ ...strings.filter((key) => parseArrayIndex(key) === undefined),
755
+ ...symbols,
756
+ ];
757
+ };
758
+ const enumerable = (target, key) => own(target, key)?.enumerable === true;
759
+ /** Own enumerable keys, including the iterator symbols; what spread and `Object.assign` copy. */
760
+ export const enumerableKeys = (target) => ownKeys(target).filter((key) => (typeof key === "string" || key === IteratorSymbol || key === AsyncIteratorSymbol) && enumerable(target, key));
761
+ /** Own enumerable string keys: `Object.keys`. */
762
+ export const keys = (target) => ownKeys(target).filter((key) => typeof key === "string" && enumerable(target, key));
763
+ /** Own enumerable string entries: `Object.entries` and serialization. */
764
+ export const entries = (target) => keys(target).map((key) => [key, getOwn(target, key)]);
765
+ /** An iterator result `{ value, done }`, built directly since every iteration step makes one. */
766
+ export const iteratorResult = (proto, value, done) => {
767
+ const target = new Obj(proto);
768
+ target.props.set("value", { value, writable: true, enumerable: true, configurable: true });
769
+ target.props.set("done", { value: done, writable: true, enumerable: true, configurable: true });
770
+ return target;
771
+ };
772
+ export const record = (proto, fields) => {
773
+ const target = new Obj(proto);
774
+ for (const [key, value] of Object.entries(fields))
775
+ define(target, key, value);
776
+ return target;
777
+ };
778
+ export const assign = (target, source, skip) => {
779
+ for (const key of enumerableKeys(source)) {
780
+ if (skip?.has(key))
781
+ continue;
782
+ set(target, key, getOwn(source, key));
783
+ }
784
+ };