@opencode/codemode 0.0.0-dev-1180 → 0.0.0-dev-1189

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 (91) hide show
  1. package/README.md +6 -12
  2. package/dist/codemode.d.ts +7 -21
  3. package/dist/codemode.js +17 -38
  4. package/dist/extension.d.ts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/scan.js +2 -2
  7. package/dist/tool-runtime.d.ts +8 -11
  8. package/dist/tool-runtime.js +13 -11
  9. package/dist/tool.d.ts +18 -9
  10. package/dist/tool.js +15 -23
  11. package/dist/vm/data.d.ts +1 -1
  12. package/dist/vm/runtime/execute.d.ts +16 -6
  13. package/dist/vm/runtime/execute.js +10 -7
  14. package/dist/vm/snapshot/codec.d.ts +3 -2
  15. package/dist/vm/snapshot/codec.js +3 -2
  16. package/dist/vm/snapshot/snapshot.d.ts +6 -3
  17. package/dist/vm/snapshot/snapshot.js +13 -2
  18. package/dist/vm/vm.d.ts +2 -2
  19. package/package.json +3 -5
  20. package/dist/data.d.ts +0 -21
  21. package/dist/data.js +0 -93
  22. package/dist/interpreter/callback.d.ts +0 -35
  23. package/dist/interpreter/callback.js +0 -98
  24. package/dist/interpreter/errors.d.ts +0 -23
  25. package/dist/interpreter/errors.js +0 -173
  26. package/dist/interpreter/execute.d.ts +0 -14
  27. package/dist/interpreter/execute.js +0 -207
  28. package/dist/interpreter/extensions.d.ts +0 -9
  29. package/dist/interpreter/extensions.js +0 -248
  30. package/dist/interpreter/generators.d.ts +0 -3
  31. package/dist/interpreter/generators.js +0 -168
  32. package/dist/interpreter/globals.d.ts +0 -6
  33. package/dist/interpreter/globals.js +0 -144
  34. package/dist/interpreter/interpreter.d.ts +0 -48
  35. package/dist/interpreter/interpreter.js +0 -2253
  36. package/dist/interpreter/intrinsics.d.ts +0 -15
  37. package/dist/interpreter/intrinsics.js +0 -105
  38. package/dist/interpreter/limits.d.ts +0 -10
  39. package/dist/interpreter/limits.js +0 -19
  40. package/dist/interpreter/model.d.ts +0 -68
  41. package/dist/interpreter/model.js +0 -54
  42. package/dist/interpreter/modules.d.ts +0 -4
  43. package/dist/interpreter/modules.js +0 -33
  44. package/dist/interpreter/native.d.ts +0 -17
  45. package/dist/interpreter/native.js +0 -35
  46. package/dist/interpreter/objects.d.ts +0 -301
  47. package/dist/interpreter/objects.js +0 -592
  48. package/dist/interpreter/promises.d.ts +0 -18
  49. package/dist/interpreter/promises.js +0 -292
  50. package/dist/interpreter/references.d.ts +0 -8
  51. package/dist/interpreter/references.js +0 -51
  52. package/dist/interpreter/runner.d.ts +0 -178
  53. package/dist/interpreter/runner.js +0 -480
  54. package/dist/interpreter/scope.d.ts +0 -16
  55. package/dist/interpreter/scope.js +0 -79
  56. package/dist/stdlib/array.d.ts +0 -11
  57. package/dist/stdlib/array.js +0 -498
  58. package/dist/stdlib/bytes.d.ts +0 -10
  59. package/dist/stdlib/bytes.js +0 -253
  60. package/dist/stdlib/collections.d.ts +0 -7
  61. package/dist/stdlib/collections.js +0 -497
  62. package/dist/stdlib/console.d.ts +0 -6
  63. package/dist/stdlib/console.js +0 -93
  64. package/dist/stdlib/date.d.ts +0 -2
  65. package/dist/stdlib/date.js +0 -132
  66. package/dist/stdlib/headers.d.ts +0 -2
  67. package/dist/stdlib/headers.js +0 -110
  68. package/dist/stdlib/iterator.d.ts +0 -2
  69. package/dist/stdlib/iterator.js +0 -322
  70. package/dist/stdlib/json.d.ts +0 -3
  71. package/dist/stdlib/json.js +0 -58
  72. package/dist/stdlib/math.d.ts +0 -8
  73. package/dist/stdlib/math.js +0 -97
  74. package/dist/stdlib/number.d.ts +0 -3
  75. package/dist/stdlib/number.js +0 -72
  76. package/dist/stdlib/object.d.ts +0 -6
  77. package/dist/stdlib/object.js +0 -219
  78. package/dist/stdlib/regexp.d.ts +0 -7
  79. package/dist/stdlib/regexp.js +0 -114
  80. package/dist/stdlib/string.d.ts +0 -2
  81. package/dist/stdlib/string.js +0 -272
  82. package/dist/stdlib/url.d.ts +0 -13
  83. package/dist/stdlib/url.js +0 -255
  84. package/dist/stdlib/value.d.ts +0 -7
  85. package/dist/stdlib/value.js +0 -33
  86. package/dist/stdlib/web.d.ts +0 -5
  87. package/dist/stdlib/web.js +0 -97
  88. package/dist/suspend-error.d.ts +0 -24
  89. package/dist/suspend-error.js +0 -25
  90. package/dist/vm/index.d.ts +0 -6
  91. package/dist/vm/index.js +0 -6
@@ -1,97 +0,0 @@
1
- import { constants, methods } from "../interpreter/native.js";
2
- import { typeError } from "../interpreter/model.js";
3
- import { Obj, coerceToNumber } from "../interpreter/objects.js";
4
- import { preserveConsumerError, withPrimitives } from "../interpreter/callback.js";
5
- export const mathGlobal = (ctx) => {
6
- const builtins = ctx.builtins;
7
- const math = new Obj(builtins.Object);
8
- // Convert only the arguments a method consumes; like JS, extras are ignored
9
- // (so built-ins work as callbacks receiving (element, index, array)).
10
- const unary = (name, op) => [
11
- name,
12
- 1,
13
- (_, args) => withPrimitives(ctx, "number", [args[0]], ([a]) => op(coerceToNumber(a))),
14
- ];
15
- const binary = (name, op) => [
16
- name,
17
- 2,
18
- (_, args) => withPrimitives(ctx, "number", [args[0], args[1]], ([a, b]) => op(coerceToNumber(a), coerceToNumber(b))),
19
- ];
20
- const variadic = (name, op) => [
21
- name,
22
- 2,
23
- (_, args) => withPrimitives(ctx, "number", args, (values) => op(...values.map(coerceToNumber))),
24
- ];
25
- constants(math, {
26
- PI: Math.PI,
27
- E: Math.E,
28
- LN2: Math.LN2,
29
- LN10: Math.LN10,
30
- LOG2E: Math.LOG2E,
31
- LOG10E: Math.LOG10E,
32
- SQRT2: Math.SQRT2,
33
- SQRT1_2: Math.SQRT1_2,
34
- });
35
- methods(builtins, math, [
36
- ["random", 0, () => Math.random()],
37
- variadic("max", Math.max),
38
- variadic("min", Math.min),
39
- variadic("hypot", Math.hypot),
40
- unary("abs", Math.abs),
41
- unary("acos", Math.acos),
42
- unary("acosh", Math.acosh),
43
- unary("asin", Math.asin),
44
- unary("asinh", Math.asinh),
45
- unary("atan", Math.atan),
46
- binary("atan2", Math.atan2),
47
- unary("atanh", Math.atanh),
48
- unary("floor", Math.floor),
49
- unary("ceil", Math.ceil),
50
- unary("round", Math.round),
51
- unary("trunc", Math.trunc),
52
- unary("sign", Math.sign),
53
- unary("sqrt", Math.sqrt),
54
- unary("cbrt", Math.cbrt),
55
- binary("pow", Math.pow),
56
- unary("cos", Math.cos),
57
- unary("cosh", Math.cosh),
58
- unary("sin", Math.sin),
59
- unary("sinh", Math.sinh),
60
- unary("tan", Math.tan),
61
- unary("tanh", Math.tanh),
62
- unary("log", Math.log),
63
- unary("log2", Math.log2),
64
- unary("log10", Math.log10),
65
- unary("log1p", Math.log1p),
66
- unary("exp", Math.exp),
67
- unary("expm1", Math.expm1),
68
- unary("f16round", Math.f16round),
69
- unary("fround", Math.fround),
70
- unary("clz32", Math.clz32),
71
- binary("imul", Math.imul),
72
- [
73
- "sumPrecise",
74
- 1,
75
- function* (_, args) {
76
- const cursor = yield* ctx.iterate(args[0]);
77
- if (cursor === undefined) {
78
- throw typeError("Math.sumPrecise expects a synchronous iterable.");
79
- }
80
- const numbers = [];
81
- while (true) {
82
- const step = yield* cursor.next();
83
- if (step.done)
84
- return Math.sumPrecise(numbers);
85
- if (typeof step.value !== "number") {
86
- yield* preserveConsumerError(cursor.close, rejectNonNumber());
87
- }
88
- numbers.push(step.value);
89
- }
90
- },
91
- ],
92
- ]);
93
- return math;
94
- };
95
- function* rejectNonNumber() {
96
- throw typeError("Math.sumPrecise expects an iterable of numbers.");
97
- }
@@ -1,3 +0,0 @@
1
- import type { Interpreter } from "../interpreter/interpreter.js";
2
- export declare const numberGlobal: <R>(ctx: Interpreter<R>) => import("../interpreter/objects.js").Native;
3
- export declare const booleanGlobal: <R>(ctx: Interpreter<R>) => import("../interpreter/objects.js").Native;
@@ -1,72 +0,0 @@
1
- import { constructor, constants, methods } from "../interpreter/native.js";
2
- import { coerceToNumber } from "../interpreter/objects.js";
3
- import { typeError } from "../interpreter/model.js";
4
- import { withPrimitives } from "../interpreter/callback.js";
5
- import { coerce, coercion } 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: coercion(ctx, "Number").call,
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(ctx, "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: coercion(ctx, "Boolean").call,
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
- };
@@ -1,6 +0,0 @@
1
- import { type AstNode } from "../interpreter/model.js";
2
- import { Obj, type Value } from "../interpreter/objects.js";
3
- import type { Interpreter } from "../interpreter/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("../interpreter/objects.js").Native;
@@ -1,219 +0,0 @@
1
- import { constructor, methods, receiver } from "../interpreter/native.js";
2
- import { AsyncIteratorSymbol, invalidData, IteratorSymbol, typeError } from "../interpreter/model.js";
3
- import { define, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, hidden, keys, own, ownKeys, Arr, Bytes, Obj, PromiseObj, set, coerceToString, } from "../interpreter/objects.js";
4
- import { primitivePrototype } from "../interpreter/intrinsics.js";
5
- import { containsOpaqueReference, describeValue, rejectCircularInsertion } from "../interpreter/references.js";
6
- import { invoke, preserveConsumerError } from "../interpreter/callback.js";
7
- import { ToolReference } from "../tool-runtime.js";
8
- import { groupBy } from "./collections.js";
9
- // ToObject for enumeration.
10
- export const enumerableSource = (ctx, label, value, node) => {
11
- if (value === null || value === undefined) {
12
- throw typeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
13
- }
14
- if (value instanceof PromiseObj) {
15
- throw invalidData(`${label} received an un-awaited Promise; await it before inspecting the result.`, node);
16
- }
17
- if (value instanceof ToolReference) {
18
- throw invalidData(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node);
19
- }
20
- if (typeof value === "string")
21
- return new Arr(ctx.builtins.Array, [...value]);
22
- if (value instanceof Obj)
23
- return value;
24
- return new Obj(ctx.builtins.Object);
25
- };
26
- export const objectAssign = (ctx, args) => {
27
- const target = args[0];
28
- // JS would box a primitive target; wrappers and primitives cannot hold fields here.
29
- if (!(target instanceof Obj)) {
30
- throw typeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`);
31
- }
32
- const seen = new Set();
33
- for (const source of args.slice(1)) {
34
- if (source === null || source === undefined)
35
- continue;
36
- const from = enumerableSource(ctx, "Object.assign(...)", source);
37
- for (const key of enumerableKeys(from)) {
38
- rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", seen);
39
- if (!set(target, key, getOwn(from, key))) {
40
- throw typeError(`Cannot assign to read only property '${String(key)}'.`);
41
- }
42
- }
43
- }
44
- return target;
45
- };
46
- function* objectFromEntries(ctx, source) {
47
- const out = new Obj(ctx.builtins.Object);
48
- const cursor = yield* ctx.iterate(source);
49
- if (cursor === undefined) {
50
- throw typeError("Object.fromEntries expects a synchronous iterable of entries.");
51
- }
52
- while (true) {
53
- const step = yield* cursor.next();
54
- if (step.done)
55
- return out;
56
- yield* preserveConsumerError(cursor.close, defineEntry(out, step.value));
57
- }
58
- }
59
- // A step, so a rejected entry closes the source iterator.
60
- function* defineEntry(out, entry) {
61
- if (!(entry instanceof Obj) || containsOpaqueReference(entry)) {
62
- throw typeError("Object.fromEntries expects [key, value] entry objects.");
63
- }
64
- define(out, coerceToString(getOwn(entry, 0)), getOwn(entry, 1));
65
- }
66
- const classTag = (value) => {
67
- if (value === null)
68
- return "Null";
69
- if (value === undefined)
70
- return "Undefined";
71
- if (value instanceof Obj)
72
- return value.tag;
73
- if (typeof value === "string")
74
- return "String";
75
- if (typeof value === "number")
76
- return "Number";
77
- if (typeof value === "boolean")
78
- return "Boolean";
79
- return "Object";
80
- };
81
- const propertyKey = (value) => value === AsyncIteratorSymbol || value === IteratorSymbol ? value : coerceToString(value);
82
- // SetIntegrityLevel: primitives pass through. A typed array's bytes cannot carry attributes, so JS throws after
83
- // already making it non-extensible.
84
- const restrict = (level, value) => {
85
- if (!(value instanceof Obj))
86
- return value;
87
- value.extensible = false;
88
- if (level === "preventExtensions")
89
- return value;
90
- if (value instanceof Bytes && value.bytes.length > 0) {
91
- throw typeError(`Cannot ${level} array buffer views with elements.`);
92
- }
93
- for (const slot of value.props.values()) {
94
- slot.configurable = false;
95
- if (level === "freeze" && "value" in slot)
96
- slot.writable = false;
97
- }
98
- if (value instanceof Arr)
99
- value.elements = { writable: level === "seal", enumerable: true, configurable: false };
100
- return value;
101
- };
102
- // TestIntegrityLevel: array elements and `length` answer through `own`, so a non-extensible empty array is sealed
103
- // but not frozen, as in JS.
104
- const integrity = (value, frozen) => {
105
- if (!(value instanceof Obj))
106
- return true;
107
- if (value.extensible)
108
- return false;
109
- return ownKeys(value).every((key) => {
110
- const slot = own(value, key);
111
- return slot !== undefined && !slot.configurable && !(frozen && "value" in slot && slot.writable);
112
- });
113
- };
114
- // Object constructs identically with or without new, like JS. Only `keys` copies its result into the
115
- // program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values.
116
- export const objectGlobal = (ctx) => {
117
- const builtins = ctx.builtins;
118
- const construct = (args) => {
119
- const first = args[0];
120
- if (first === null || first === undefined)
121
- return new Obj(builtins.Object);
122
- if (first instanceof Obj)
123
- return first;
124
- throw typeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`);
125
- };
126
- const object = constructor(builtins, builtins.Object, {
127
- name: "Object",
128
- length: 1,
129
- call: (_, args) => construct(args),
130
- construct: (args) => construct(args),
131
- });
132
- methods(builtins, object, [
133
- [
134
- "keys",
135
- 1,
136
- (_, args) => new Arr(builtins.Array, args[0] instanceof ToolReference
137
- ? [...ctx.tools.keys(args[0].path)]
138
- : keys(enumerableSource(ctx, "Object.keys(...)", args[0]))),
139
- ],
140
- [
141
- "values",
142
- 1,
143
- (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.values(...)", args[0])).map((entry) => entry[1])),
144
- ],
145
- [
146
- "entries",
147
- 1,
148
- (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.entries(...)", args[0])).map((entry) => new Arr(builtins.Array, entry))),
149
- ],
150
- ["hasOwn", 2, (_, args) => hasOwn(enumerableSource(ctx, "Object.hasOwn(...)", args[0]), propertyKey(args[1]))],
151
- ["is", 2, (_, args) => Object.is(args[0], args[1])],
152
- ["assign", 2, (_, args) => objectAssign(ctx, args)],
153
- ["fromEntries", 1, (_, args) => objectFromEntries(ctx, args[0])],
154
- ["freeze", 1, (_, args) => restrict("freeze", args[0])],
155
- ["seal", 1, (_, args) => restrict("seal", args[0])],
156
- ["preventExtensions", 1, (_, args) => restrict("preventExtensions", args[0])],
157
- ["isFrozen", 1, (_, args) => integrity(args[0], true)],
158
- ["isSealed", 1, (_, args) => integrity(args[0], false)],
159
- ["isExtensible", 1, (_, args) => args[0] instanceof Obj && args[0].extensible],
160
- [
161
- "getPrototypeOf",
162
- 1,
163
- (_, args) => {
164
- if (args[0] instanceof Obj)
165
- return args[0].proto;
166
- const proto = primitivePrototype(builtins, args[0]);
167
- if (proto === undefined) {
168
- throw typeError(`Object.getPrototypeOf cannot convert ${describeValue(args[0])} to an object.`);
169
- }
170
- return proto;
171
- },
172
- ],
173
- [
174
- "create",
175
- 2,
176
- (_, args) => {
177
- if (args[0] !== null && !(args[0] instanceof Obj)) {
178
- throw typeError("Object prototype may only be an Object or null.");
179
- }
180
- if (args[1] !== undefined) {
181
- throw typeError("Object.create property descriptors are not supported; assign the fields after creating the object.");
182
- }
183
- return new Obj(args[0]);
184
- },
185
- ],
186
- ]);
187
- define(object, "groupBy", groupBy(ctx, "Object"), hidden);
188
- methods(builtins, builtins.Object, [
189
- [
190
- "hasOwnProperty",
191
- 1,
192
- (thisValue, args) => hasOwn(receiver(Obj, thisValue, "Object.prototype.hasOwnProperty"), propertyKey(args[0])),
193
- ],
194
- [
195
- "isPrototypeOf",
196
- 1,
197
- (thisValue, args) => hasPrototype(args[0], receiver(Obj, thisValue, "Object.prototype.isPrototypeOf")),
198
- ],
199
- [
200
- "propertyIsEnumerable",
201
- 1,
202
- (thisValue, args) => own(receiver(Obj, thisValue, "Object.prototype.propertyIsEnumerable"), propertyKey(args[0]))?.enumerable ===
203
- true,
204
- ],
205
- ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
206
- ["toLocaleString", 0, (thisValue) => invoke(ctx, thisValue, "toString", "Object.prototype.toLocaleString")],
207
- [
208
- "valueOf",
209
- 0,
210
- (thisValue) => {
211
- if (thisValue === null || thisValue === undefined) {
212
- throw typeError("Object.prototype.valueOf called on null or undefined.");
213
- }
214
- return thisValue;
215
- },
216
- ],
217
- ]);
218
- return object;
219
- };
@@ -1,7 +0,0 @@
1
- import type { Builtins } from "../interpreter/intrinsics.js";
2
- import { Arr, Obj, RegExpObj, type Value } from "../interpreter/objects.js";
3
- import type { Interpreter } from "../interpreter/interpreter.js";
4
- export declare const toHostRegex: (arg: Value, method: string, extraFlags?: string) => RegExp;
5
- export declare const matchToValue: (builtins: Builtins, match: RegExpMatchArray) => Arr;
6
- export declare const constructRegExp: (builtins: Builtins, args: Array<Value>, proto?: Obj) => RegExpObj;
7
- export declare const regexpGlobal: <R>(ctx: Interpreter<R>) => import("../interpreter/objects.js").Native;
@@ -1,114 +0,0 @@
1
- import { constructor, methods, prototypeFrom, receiver } from "../interpreter/native.js";
2
- import { syntaxError, typeError } from "../interpreter/model.js";
3
- import { define, defineAccessor, Arr, Obj, RegExpObj, record, coerceToNumber, coerceToString, } from "../interpreter/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
- export const toHostRegex = (arg, method, extraFlags = "") => {
17
- if (arg instanceof RegExpObj)
18
- return arg.regex;
19
- // Anything else is a pattern string, as `new RegExp(arg)` would read it: undefined is the empty pattern.
20
- const source = arg === undefined ? "" : coerceToString(arg);
21
- try {
22
- return new RegExp(source, extraFlags);
23
- }
24
- catch (error) {
25
- throw syntaxError(`String.${method} received the string ${JSON.stringify(source)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`);
26
- }
27
- };
28
- export const matchToValue = (builtins, match) => {
29
- const result = new Arr(builtins.Array, Array.from(match, (group) => group));
30
- if (match.index !== undefined)
31
- define(result, "index", match.index);
32
- if (match.input !== undefined)
33
- define(result, "input", match.input);
34
- if (match.groups)
35
- define(result, "groups", record(builtins.Object, match.groups));
36
- if (match.indices)
37
- define(result, "indices", indicesToValue(builtins, match.indices));
38
- return result;
39
- };
40
- export const constructRegExp = (builtins, args, proto = builtins.RegExp) => {
41
- const first = args[0];
42
- const pattern = first instanceof RegExpObj ? first.regex.source : first === undefined ? "" : coerceToString(first);
43
- const flagsArg = args[1];
44
- if (flagsArg !== undefined && typeof flagsArg !== "string") {
45
- throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`);
46
- }
47
- const flags = flagsArg ?? (first instanceof RegExpObj ? first.regex.flags : "");
48
- try {
49
- return new RegExpObj(proto, pattern, flags);
50
- }
51
- catch (error) {
52
- const reason = regexFailureReason(error);
53
- throw syntaxError(/flag/i.test(reason)
54
- ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
55
- : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`);
56
- }
57
- };
58
- // RegExp constructs identically with or without new, like JS.
59
- export const regexpGlobal = (ctx) => {
60
- const builtins = ctx.builtins;
61
- const proto = builtins.RegExp;
62
- const regexp = constructor(builtins, proto, {
63
- name: "RegExp",
64
- length: 2,
65
- call: (_, args) => constructRegExp(builtins, args),
66
- construct: (args, newTarget) => constructRegExp(builtins, args, prototypeFrom(newTarget, proto)),
67
- });
68
- methods(builtins, regexp, [
69
- [
70
- "escape",
71
- 1,
72
- (_, args) => {
73
- if (typeof args[0] !== "string")
74
- throw typeError("RegExp.escape expects a string.");
75
- return RegExp.escape(args[0]);
76
- },
77
- ],
78
- ]);
79
- const self = (thisValue, name) => receiver(RegExpObj, thisValue, `RegExp.prototype.${name}`);
80
- defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").regex.source);
81
- defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").regex.flags);
82
- // The host regex holds the only lastIndex, so exec/test and the String methods share one counter.
83
- defineAccessor(proto, "lastIndex", (thisValue) => self(thisValue, "lastIndex").regex.lastIndex, (thisValue, value) => {
84
- self(thisValue, "lastIndex").regex.lastIndex = coerceToNumber(value);
85
- });
86
- for (const name of flagProperties)
87
- defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name]);
88
- const run = (name) => [
89
- name,
90
- 1,
91
- (thisValue, args) => {
92
- const value = self(thisValue, name);
93
- const matched = value.regex.exec(coerceToString(args[0]));
94
- if (name === "test")
95
- return matched !== null;
96
- return matched === null ? null : matchToValue(builtins, matched);
97
- },
98
- ];
99
- methods(builtins, proto, [
100
- run("exec"),
101
- run("test"),
102
- ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
103
- ]);
104
- return regexp;
105
- };
106
- const indicesToValue = (builtins, indices) => {
107
- const range = (pair) => pair === undefined ? undefined : new Arr(builtins.Array, [...pair]);
108
- const result = new Arr(builtins.Array, Array.from(indices, range));
109
- const groups = indices.groups;
110
- define(result, "groups", groups === undefined
111
- ? undefined
112
- : record(builtins.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))));
113
- return result;
114
- };
@@ -1,2 +0,0 @@
1
- import type { Interpreter } from "../interpreter/interpreter.js";
2
- export declare const stringGlobal: <R>(ctx: Interpreter<R>) => import("../interpreter/objects.js").Native;