@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,3 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ export declare const numberGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
3
+ export declare const booleanGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,72 @@
1
+ import { constructor, constants, methods } from "../runtime/native.js";
2
+ import { coerceToNumber } from "../runtime/objects.js";
3
+ import { typeError } from "../runtime/model.js";
4
+ import { withPrimitives } from "../runtime/callback.js";
5
+ import { coerce } from "./value.js";
6
+ export const numberGlobal = (ctx) => {
7
+ const builtins = ctx.builtins;
8
+ const number = constructor(builtins, builtins.Number, {
9
+ name: "Number",
10
+ length: 1,
11
+ call: (_, args) => coerce(ctx, "Number", args),
12
+ });
13
+ constants(number, {
14
+ MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
15
+ MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
16
+ MAX_VALUE: Number.MAX_VALUE,
17
+ MIN_VALUE: Number.MIN_VALUE,
18
+ EPSILON: Number.EPSILON,
19
+ NaN: Number.NaN,
20
+ POSITIVE_INFINITY: Number.POSITIVE_INFINITY,
21
+ NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
22
+ });
23
+ methods(builtins, number, [
24
+ ["isInteger", 1, (_, args) => Number.isInteger(args[0])],
25
+ ["isFinite", 1, (_, args) => Number.isFinite(args[0])],
26
+ ["isNaN", 1, (_, args) => Number.isNaN(args[0])],
27
+ ["isSafeInteger", 1, (_, args) => Number.isSafeInteger(args[0])],
28
+ ["parseInt", 2, (_, args) => coerce(ctx, "parseInt", args)],
29
+ ["parseFloat", 1, (_, args) => coerce(ctx, "parseFloat", args)],
30
+ ]);
31
+ const self = (thisValue, name) => {
32
+ if (typeof thisValue === "number")
33
+ return thisValue;
34
+ throw typeError(`Number.prototype.${name} requires that 'this' be a Number.`);
35
+ };
36
+ // The receiver is checked first, then the one argument converts through ToPrimitive with the number hint.
37
+ const formatting = (name, op) => [
38
+ name,
39
+ 1,
40
+ (thisValue, args) => {
41
+ const value = self(thisValue, name);
42
+ return withPrimitives("number", [args[0]], ([digits]) => op(value, digits === undefined ? undefined : coerceToNumber(digits)));
43
+ },
44
+ ];
45
+ methods(builtins, builtins.Number, [
46
+ formatting("toFixed", (value, digits) => value.toFixed(digits)),
47
+ ["toLocaleString", 0, (thisValue) => self(thisValue, "toLocaleString").toLocaleString("en-US")],
48
+ formatting("toExponential", (value, digits) => value.toExponential(digits)),
49
+ formatting("toPrecision", (value, digits) => (digits === undefined ? value.toString() : value.toPrecision(digits))),
50
+ formatting("toString", (value, radix) => value.toString(radix)),
51
+ ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")],
52
+ ]);
53
+ return number;
54
+ };
55
+ export const booleanGlobal = (ctx) => {
56
+ const builtins = ctx.builtins;
57
+ const boolean = constructor(builtins, builtins.Boolean, {
58
+ name: "Boolean",
59
+ length: 1,
60
+ call: (_, args) => coerce(ctx, "Boolean", args),
61
+ });
62
+ const self = (thisValue, name) => {
63
+ if (typeof thisValue === "boolean")
64
+ return thisValue;
65
+ throw typeError(`Boolean.prototype.${name} requires that 'this' be a Boolean.`);
66
+ };
67
+ methods(builtins, builtins.Boolean, [
68
+ ["toString", 0, (thisValue) => String(self(thisValue, "toString"))],
69
+ ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")],
70
+ ]);
71
+ return boolean;
72
+ };
@@ -0,0 +1,6 @@
1
+ import { type AstNode } from "../runtime/model.js";
2
+ import { Obj, type Value } from "../runtime/objects.js";
3
+ import type { Interpreter } from "../runtime/interpreter.js";
4
+ export declare const enumerableSource: <R>(ctx: Interpreter<R>, label: string, value: Value, node?: AstNode) => Obj;
5
+ export declare const objectAssign: <R>(ctx: Interpreter<R>, args: Array<Value>) => Value;
6
+ export declare const objectGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,201 @@
1
+ import { constructor, methods, receiver } from "../runtime/native.js";
2
+ import { AsyncIteratorSymbol, invalidData, IteratorSymbol, typeError } from "../runtime/model.js";
3
+ import { changed, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, keys, own, ownKeys, Arr, Bytes, Obj, PromiseObj, set, coerceToString, } from "../runtime/objects.js";
4
+ import { primitivePrototype } from "../runtime/intrinsics.js";
5
+ import { describeValue, rejectCircularInsertion } from "../runtime/references.js";
6
+ import { invokeMethod } from "../runtime/callback.js";
7
+ import { ToolReference } from "../../tool-runtime.js";
8
+ // ToObject for enumeration.
9
+ export const enumerableSource = (ctx, label, value, node) => {
10
+ if (value === null || value === undefined) {
11
+ throw typeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
12
+ }
13
+ if (value instanceof PromiseObj) {
14
+ throw invalidData(`${label} received an un-awaited Promise; await it before inspecting the result.`, node);
15
+ }
16
+ if (value instanceof ToolReference) {
17
+ throw invalidData(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node);
18
+ }
19
+ if (typeof value === "string")
20
+ return new Arr(ctx.builtins.Array, [...value]);
21
+ if (value instanceof Obj)
22
+ return value;
23
+ return new Obj(ctx.builtins.Object);
24
+ };
25
+ export const objectAssign = (ctx, args) => {
26
+ const target = args[0];
27
+ // JS would box a primitive target; wrappers and primitives cannot hold fields here.
28
+ if (!(target instanceof Obj)) {
29
+ throw typeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`);
30
+ }
31
+ const seen = new Set();
32
+ for (const source of args.slice(1)) {
33
+ if (source === null || source === undefined)
34
+ continue;
35
+ const from = enumerableSource(ctx, "Object.assign(...)", source);
36
+ for (const key of enumerableKeys(from)) {
37
+ rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", seen);
38
+ if (!set(target, key, getOwn(from, key))) {
39
+ throw typeError(`Cannot assign to read only property '${String(key)}'.`);
40
+ }
41
+ }
42
+ }
43
+ return target;
44
+ };
45
+ const classTag = (value) => {
46
+ if (value === null)
47
+ return "Null";
48
+ if (value === undefined)
49
+ return "Undefined";
50
+ if (value instanceof Obj)
51
+ return value.tag;
52
+ if (typeof value === "string")
53
+ return "String";
54
+ if (typeof value === "number")
55
+ return "Number";
56
+ if (typeof value === "boolean")
57
+ return "Boolean";
58
+ return "Object";
59
+ };
60
+ const propertyKey = (value) => value === AsyncIteratorSymbol || value === IteratorSymbol ? value : coerceToString(value);
61
+ // SetIntegrityLevel: primitives pass through. A typed array's bytes cannot carry attributes, so JS throws after
62
+ // already making it non-extensible.
63
+ const restrict = (level, value) => {
64
+ if (!(value instanceof Obj))
65
+ return value;
66
+ changed(value);
67
+ value.extensible = false;
68
+ if (level === "preventExtensions")
69
+ return value;
70
+ if (value instanceof Bytes && value.bytes.length > 0) {
71
+ throw typeError(`Cannot ${level} array buffer views with elements.`);
72
+ }
73
+ for (const slot of value.props.values()) {
74
+ slot.configurable = false;
75
+ if (level === "freeze" && "value" in slot)
76
+ slot.writable = false;
77
+ }
78
+ if (value instanceof Arr)
79
+ value.elements = { writable: level === "seal", enumerable: true, configurable: false };
80
+ return value;
81
+ };
82
+ // TestIntegrityLevel: array elements and `length` answer through `own`, so a non-extensible empty array is sealed
83
+ // but not frozen, as in JS.
84
+ const integrity = (value, frozen) => {
85
+ if (!(value instanceof Obj))
86
+ return true;
87
+ if (value.extensible)
88
+ return false;
89
+ return ownKeys(value).every((key) => {
90
+ const slot = own(value, key);
91
+ return slot !== undefined && !slot.configurable && !(frozen && "value" in slot && slot.writable);
92
+ });
93
+ };
94
+ // Object constructs identically with or without new, like JS. Only `keys` copies its result into the
95
+ // program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values.
96
+ export const objectGlobal = (ctx) => {
97
+ const builtins = ctx.builtins;
98
+ const construct = (args) => {
99
+ const first = args[0];
100
+ if (first === null || first === undefined)
101
+ return new Obj(builtins.Object);
102
+ if (first instanceof Obj)
103
+ return first;
104
+ throw typeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`);
105
+ };
106
+ const object = constructor(builtins, builtins.Object, {
107
+ name: "Object",
108
+ length: 1,
109
+ call: (_, args) => construct(args),
110
+ construct: (args) => construct(args),
111
+ });
112
+ methods(builtins, object, [
113
+ [
114
+ "keys",
115
+ 1,
116
+ (_, args) => new Arr(builtins.Array, args[0] instanceof ToolReference
117
+ ? [...ctx.tools.keys(args[0].path)]
118
+ : keys(enumerableSource(ctx, "Object.keys(...)", args[0]))),
119
+ ],
120
+ [
121
+ "values",
122
+ 1,
123
+ (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.values(...)", args[0])).map((entry) => entry[1])),
124
+ ],
125
+ [
126
+ "entries",
127
+ 1,
128
+ (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.entries(...)", args[0])).map((entry) => new Arr(builtins.Array, entry))),
129
+ ],
130
+ ["hasOwn", 2, (_, args) => hasOwn(enumerableSource(ctx, "Object.hasOwn(...)", args[0]), propertyKey(args[1]))],
131
+ ["is", 2, (_, args) => Object.is(args[0], args[1])],
132
+ ["assign", 2, (_, args) => objectAssign(ctx, args)],
133
+ ["freeze", 1, (_, args) => restrict("freeze", args[0])],
134
+ ["seal", 1, (_, args) => restrict("seal", args[0])],
135
+ ["preventExtensions", 1, (_, args) => restrict("preventExtensions", args[0])],
136
+ ["isFrozen", 1, (_, args) => integrity(args[0], true)],
137
+ ["isSealed", 1, (_, args) => integrity(args[0], false)],
138
+ ["isExtensible", 1, (_, args) => args[0] instanceof Obj && args[0].extensible],
139
+ [
140
+ "getPrototypeOf",
141
+ 1,
142
+ (_, args) => {
143
+ if (args[0] instanceof Obj)
144
+ return args[0].proto;
145
+ const proto = primitivePrototype(builtins, args[0]);
146
+ if (proto === undefined) {
147
+ throw typeError(`Object.getPrototypeOf cannot convert ${describeValue(args[0])} to an object.`);
148
+ }
149
+ return proto;
150
+ },
151
+ ],
152
+ [
153
+ "create",
154
+ 2,
155
+ (_, args) => {
156
+ if (args[0] !== null && !(args[0] instanceof Obj)) {
157
+ throw typeError("Object prototype may only be an Object or null.");
158
+ }
159
+ if (args[1] !== undefined) {
160
+ throw typeError("Object.create property descriptors are not supported; assign the fields after creating the object.");
161
+ }
162
+ return new Obj(args[0]);
163
+ },
164
+ ],
165
+ ]);
166
+ methods(builtins, builtins.Object, [
167
+ [
168
+ "hasOwnProperty",
169
+ 1,
170
+ (thisValue, args) => hasOwn(receiver(Obj, thisValue, "Object.prototype.hasOwnProperty"), propertyKey(args[0])),
171
+ ],
172
+ [
173
+ "isPrototypeOf",
174
+ 1,
175
+ (thisValue, args) => hasPrototype(args[0], receiver(Obj, thisValue, "Object.prototype.isPrototypeOf")),
176
+ ],
177
+ [
178
+ "propertyIsEnumerable",
179
+ 1,
180
+ (thisValue, args) => own(receiver(Obj, thisValue, "Object.prototype.propertyIsEnumerable"), propertyKey(args[0]))?.enumerable ===
181
+ true,
182
+ ],
183
+ ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
184
+ [
185
+ "toLocaleString",
186
+ 0,
187
+ (thisValue) => invokeMethod(ctx.builtins, thisValue, "toString", "Object.prototype.toLocaleString"),
188
+ ],
189
+ [
190
+ "valueOf",
191
+ 0,
192
+ (thisValue) => {
193
+ if (thisValue === null || thisValue === undefined) {
194
+ throw typeError("Object.prototype.valueOf called on null or undefined.");
195
+ }
196
+ return thisValue;
197
+ },
198
+ ],
199
+ ]);
200
+ return object;
201
+ };
@@ -0,0 +1,8 @@
1
+ import type { Builtins } from "../runtime/intrinsics.js";
2
+ import { Arr, Obj, RegExpObj, type Value } from "../runtime/objects.js";
3
+ import type { Interpreter } from "../runtime/interpreter.js";
4
+ /** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */
5
+ export declare const withHostRegex: <T>(arg: Value, method: string, extraFlags: string, work: (regex: RegExp) => T) => T;
6
+ export declare const matchToValue: (builtins: Builtins, match: RegExpMatchArray) => Arr;
7
+ export declare const constructRegExp: (builtins: Builtins, args: Array<Value>, proto?: Obj) => RegExpObj;
8
+ export declare const regexpGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,119 @@
1
+ import { constructor, methods, prototypeFrom, receiver } from "../runtime/native.js";
2
+ import { syntaxError, typeError } from "../runtime/model.js";
3
+ import { define, defineAccessor, Arr, Obj, RegExpObj, record, coerceToNumber, coerceToString, } from "../runtime/objects.js";
4
+ const flagProperties = [
5
+ "hasIndices",
6
+ "global",
7
+ "ignoreCase",
8
+ "multiline",
9
+ "sticky",
10
+ "unicode",
11
+ "unicodeSets",
12
+ "dotAll",
13
+ ];
14
+ const regexFailureReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "");
15
+ const escapeRegexHint = 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.';
16
+ /** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */
17
+ export const withHostRegex = (arg, method, extraFlags, work) => {
18
+ if (arg instanceof RegExpObj)
19
+ return arg.use(work);
20
+ // Anything else is a pattern string, as `new RegExp(arg)` would read it: undefined is the empty pattern.
21
+ const source = arg === undefined ? "" : coerceToString(arg);
22
+ return work(compilePattern(source, method, extraFlags));
23
+ };
24
+ const compilePattern = (source, method, extraFlags) => {
25
+ try {
26
+ return new RegExp(source, extraFlags);
27
+ }
28
+ catch (error) {
29
+ throw syntaxError(`String.${method} received the string ${JSON.stringify(source)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`);
30
+ }
31
+ };
32
+ export const matchToValue = (builtins, match) => {
33
+ const result = new Arr(builtins.Array, Array.from(match, (group) => group));
34
+ if (match.index !== undefined)
35
+ define(result, "index", match.index);
36
+ if (match.input !== undefined)
37
+ define(result, "input", match.input);
38
+ if (match.groups)
39
+ define(result, "groups", record(builtins.Object, match.groups));
40
+ if (match.indices)
41
+ define(result, "indices", indicesToValue(builtins, match.indices));
42
+ return result;
43
+ };
44
+ export const constructRegExp = (builtins, args, proto = builtins.RegExp) => {
45
+ const first = args[0];
46
+ const pattern = first instanceof RegExpObj ? first.source : first === undefined ? "" : coerceToString(first);
47
+ const flagsArg = args[1];
48
+ if (flagsArg !== undefined && typeof flagsArg !== "string") {
49
+ throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`);
50
+ }
51
+ const flags = flagsArg ?? (first instanceof RegExpObj ? first.flags : "");
52
+ try {
53
+ return new RegExpObj(proto, pattern, flags);
54
+ }
55
+ catch (error) {
56
+ const reason = regexFailureReason(error);
57
+ throw syntaxError(/flag/i.test(reason)
58
+ ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
59
+ : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`);
60
+ }
61
+ };
62
+ // RegExp constructs identically with or without new, like JS.
63
+ export const regexpGlobal = (ctx) => {
64
+ const builtins = ctx.builtins;
65
+ const proto = builtins.RegExp;
66
+ const regexp = constructor(builtins, proto, {
67
+ name: "RegExp",
68
+ length: 2,
69
+ call: (_, args) => constructRegExp(builtins, args),
70
+ construct: (args, newTarget) => constructRegExp(builtins, args, prototypeFrom(newTarget, proto)),
71
+ });
72
+ methods(builtins, regexp, [
73
+ [
74
+ "escape",
75
+ 1,
76
+ (_, args) => {
77
+ if (typeof args[0] !== "string")
78
+ throw typeError("RegExp.escape expects a string.");
79
+ return RegExp.escape(args[0]);
80
+ },
81
+ ],
82
+ ]);
83
+ const self = (thisValue, name) => receiver(RegExpObj, thisValue, `RegExp.prototype.${name}`);
84
+ defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").source);
85
+ defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").flags);
86
+ // One lastIndex per RegExp, so exec/test and the String methods share one counter.
87
+ defineAccessor(proto, "lastIndex", (thisValue) => self(thisValue, "lastIndex").lastIndex, (thisValue, value) => {
88
+ self(thisValue, "lastIndex").lastIndex = coerceToNumber(value);
89
+ });
90
+ for (const name of flagProperties)
91
+ defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name]);
92
+ const run = (name) => [
93
+ name,
94
+ 1,
95
+ (thisValue, args) => {
96
+ const value = self(thisValue, name);
97
+ const input = coerceToString(args[0]);
98
+ const matched = value.use((regex) => regex.exec(input));
99
+ if (name === "test")
100
+ return matched !== null;
101
+ return matched === null ? null : matchToValue(builtins, matched);
102
+ },
103
+ ];
104
+ methods(builtins, proto, [
105
+ run("exec"),
106
+ run("test"),
107
+ ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
108
+ ]);
109
+ return regexp;
110
+ };
111
+ const indicesToValue = (builtins, indices) => {
112
+ const range = (pair) => pair === undefined ? undefined : new Arr(builtins.Array, [...pair]);
113
+ const result = new Arr(builtins.Array, Array.from(indices, range));
114
+ const groups = indices.groups;
115
+ define(result, "groups", groups === undefined
116
+ ? undefined
117
+ : record(builtins.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))));
118
+ return result;
119
+ };
@@ -0,0 +1,2 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ export declare const stringGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;