@opencode/codemode 0.0.0-dev-19566 → 0.0.0-dev-19567

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.
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { toProgram } from "../data.js";
3
3
  import { constructor, methods, receiver } from "../interpreter/native.js";
4
- import { AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol, rangeError, } from "../interpreter/model.js";
4
+ import { AsyncIteratorSymbol, invalidData, IteratorSymbol, rangeError, typeError, } from "../interpreter/model.js";
5
5
  import { Callable, define, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, hidden, keys, own, ProgramArray, ProgramDate, ProgramError, ProgramObject, ProgramPromise, ProgramRegExp, set, } from "../interpreter/objects.js";
6
6
  import { containsOpaqueReference, describeValue, rejectCircularInsertion } from "../interpreter/references.js";
7
7
  import { preserveConsumerError } from "../interpreter/runner.js";
@@ -11,13 +11,13 @@ import { coerceToString } from "./value.js";
11
11
  // ToObject for enumeration.
12
12
  export const enumerableSource = (runner, label, value, node) => {
13
13
  if (value === null || value === undefined) {
14
- throw new InterpreterRuntimeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
14
+ throw typeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
15
15
  }
16
16
  if (value instanceof ProgramPromise) {
17
- throw new InterpreterRuntimeError(`${label} received an un-awaited Promise; await it before inspecting the result.`, node, "InvalidDataValue");
17
+ throw invalidData(`${label} received an un-awaited Promise; await it before inspecting the result.`, node);
18
18
  }
19
19
  if (value instanceof ToolReference) {
20
- throw new InterpreterRuntimeError(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node, "InvalidDataValue");
20
+ throw invalidData(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node);
21
21
  }
22
22
  if (typeof value === "string")
23
23
  return new ProgramArray(runner.prototypes.Array, [...value]);
@@ -25,34 +25,34 @@ export const enumerableSource = (runner, label, value, node) => {
25
25
  return value;
26
26
  return new ProgramObject(runner.prototypes.Object);
27
27
  };
28
- export const objectAssign = (runner, args, node) => {
28
+ export const objectAssign = (runner, args) => {
29
29
  const target = args[0];
30
30
  // JS would box a primitive target; wrappers and primitives cannot hold fields here.
31
31
  if (!(target instanceof ProgramObject)) {
32
- throw new InterpreterRuntimeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`, node);
32
+ throw typeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`);
33
33
  }
34
34
  const seen = new Set();
35
35
  for (const source of args.slice(1)) {
36
36
  if (source === null || source === undefined)
37
37
  continue;
38
- const from = enumerableSource(runner, "Object.assign(...)", source, node);
38
+ const from = enumerableSource(runner, "Object.assign(...)", source);
39
39
  for (const key of enumerableKeys(from)) {
40
- rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", node, seen);
40
+ rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", seen);
41
41
  if (!set(target, key, getOwn(from, key))) {
42
42
  if (target instanceof ProgramArray && key === "length")
43
- throw rangeError("Invalid array length", node);
44
- throw new InterpreterRuntimeError(`Cannot assign to read only property '${String(key)}'.`, node);
43
+ throw rangeError("Invalid array length");
44
+ throw typeError(`Cannot assign to read only property '${String(key)}'.`);
45
45
  }
46
46
  }
47
47
  }
48
48
  return target;
49
49
  };
50
- const objectFromEntries = (runner, source, node) => {
50
+ const objectFromEntries = (runner, source) => {
51
51
  const out = new ProgramObject(runner.prototypes.Object);
52
52
  return Effect.gen(function* () {
53
- const cursor = yield* runner.syncIterator(source, node);
53
+ const cursor = yield* runner.syncIterator(source);
54
54
  if (cursor === undefined) {
55
- throw new InterpreterRuntimeError("Object.fromEntries expects a synchronous iterable of entries.", node);
55
+ throw typeError("Object.fromEntries expects a synchronous iterable of entries.");
56
56
  }
57
57
  while (true) {
58
58
  const step = yield* cursor.next;
@@ -60,7 +60,7 @@ const objectFromEntries = (runner, source, node) => {
60
60
  return out;
61
61
  yield* preserveConsumerError(cursor, Effect.sync(() => {
62
62
  if (!(step.value instanceof ProgramObject) || containsOpaqueReference(step.value)) {
63
- throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] entry objects.", node);
63
+ throw typeError("Object.fromEntries expects [key, value] entry objects.");
64
64
  }
65
65
  define(out, coerceToString(getOwn(step.value, 0)), getOwn(step.value, 1));
66
66
  }));
@@ -95,72 +95,68 @@ const propertyKey = (value) => value === AsyncIteratorSymbol || value === Iterat
95
95
  // program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values.
96
96
  export const objectGlobal = (runner, toolKeys) => {
97
97
  const protos = runner.prototypes;
98
- const construct = (args, node) => {
98
+ const construct = (args) => {
99
99
  const first = args[0];
100
100
  if (first === null || first === undefined)
101
101
  return new ProgramObject(protos.Object);
102
102
  if (typeof first === "object")
103
103
  return first;
104
- throw new InterpreterRuntimeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`, node);
104
+ throw typeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`);
105
105
  };
106
106
  const object = constructor(protos, protos.Object, {
107
107
  name: "Object",
108
108
  length: 1,
109
- call: (_, args, node) => Effect.sync(() => construct(args, node)),
110
- construct: (args, _, node) => Effect.sync(() => construct(args, node)),
109
+ call: (_, args) => Effect.sync(() => construct(args)),
110
+ construct: (args) => Effect.sync(() => construct(args)),
111
111
  });
112
112
  methods(protos, object, [
113
113
  [
114
114
  "keys",
115
115
  1,
116
- (_, args, node) => toProgram(protos, args[0] instanceof ToolReference
116
+ (_, args) => toProgram(protos, args[0] instanceof ToolReference
117
117
  ? [...toolKeys(args[0].path)]
118
- : keys(enumerableSource(runner, "Object.keys(...)", args[0], node)), "Object.keys result"),
118
+ : keys(enumerableSource(runner, "Object.keys(...)", args[0])), "Object.keys result"),
119
119
  ],
120
120
  [
121
121
  "values",
122
122
  1,
123
- (_, args, node) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.values(...)", args[0], node)).map((entry) => entry[1])),
123
+ (_, args) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.values(...)", args[0])).map((entry) => entry[1])),
124
124
  ],
125
125
  [
126
126
  "entries",
127
127
  1,
128
- (_, args, node) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.entries(...)", args[0], node)).map((entry) => new ProgramArray(protos.Array, entry))),
129
- ],
130
- [
131
- "hasOwn",
132
- 2,
133
- (_, args, node) => hasOwn(enumerableSource(runner, "Object.hasOwn(...)", args[0], node), propertyKey(args[1])),
128
+ (_, args) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.entries(...)", args[0])).map((entry) => new ProgramArray(protos.Array, entry))),
134
129
  ],
130
+ ["hasOwn", 2, (_, args) => hasOwn(enumerableSource(runner, "Object.hasOwn(...)", args[0]), propertyKey(args[1]))],
135
131
  [
136
132
  "is",
137
133
  2,
138
- (_, args, node) => {
134
+ (_, args) => {
139
135
  if (containsOpaqueReference(args[0]) || containsOpaqueReference(args[1])) {
140
- throw new InterpreterRuntimeError("Object.is requires data values.", node, "InvalidDataValue");
136
+ throw invalidData("Object.is requires data values.");
141
137
  }
142
138
  return Object.is(args[0], args[1]);
143
139
  },
144
140
  ],
145
- ["assign", 2, (_, args, node) => objectAssign(runner, args, node)],
146
- ["fromEntries", 1, (_, args, node) => objectFromEntries(runner, args[0], node)],
141
+ ["assign", 2, (_, args) => objectAssign(runner, args)],
142
+ ["fromEntries", 1, (_, args) => objectFromEntries(runner, args[0])],
147
143
  ]);
148
144
  define(object, "groupBy", groupBy(runner, "Object"), hidden);
149
145
  methods(protos, protos.Object, [
150
146
  [
151
147
  "hasOwnProperty",
152
148
  1,
153
- (thisValue, args, node) => hasOwn(receiver(ProgramObject, thisValue, "Object.prototype.hasOwnProperty", node), propertyKey(args[0])),
149
+ (thisValue, args) => hasOwn(receiver(ProgramObject, thisValue, "Object.prototype.hasOwnProperty"), propertyKey(args[0])),
154
150
  ],
155
151
  [
156
152
  "isPrototypeOf",
157
153
  1,
158
- (thisValue, args, node) => hasPrototype(args[0], receiver(ProgramObject, thisValue, "Object.prototype.isPrototypeOf", node)),
154
+ (thisValue, args) => hasPrototype(args[0], receiver(ProgramObject, thisValue, "Object.prototype.isPrototypeOf")),
159
155
  ],
160
156
  [
161
157
  "propertyIsEnumerable",
162
158
  1,
163
- (thisValue, args, node) => own(receiver(ProgramObject, thisValue, "Object.prototype.propertyIsEnumerable", node), propertyKey(args[0]))
159
+ (thisValue, args) => own(receiver(ProgramObject, thisValue, "Object.prototype.propertyIsEnumerable"), propertyKey(args[0]))
164
160
  ?.enumerable === true,
165
161
  ],
166
162
  ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
@@ -168,9 +164,9 @@ export const objectGlobal = (runner, toolKeys) => {
168
164
  [
169
165
  "valueOf",
170
166
  0,
171
- (thisValue, _, node) => {
167
+ (thisValue) => {
172
168
  if (thisValue === null || thisValue === undefined) {
173
- throw new InterpreterRuntimeError("Object.prototype.valueOf called on null or undefined.", node);
169
+ throw typeError("Object.prototype.valueOf called on null or undefined.");
174
170
  }
175
171
  return thisValue;
176
172
  },
@@ -1,8 +1,7 @@
1
1
  import type { Prototypes } from "../interpreter/intrinsics.js";
2
- import { type AstNode } from "../interpreter/model.js";
3
2
  import { ProgramArray, ProgramObject, ProgramRegExp } from "../interpreter/objects.js";
4
3
  import type { Runner } from "../interpreter/runner.js";
5
- export declare const toHostRegex: (arg: unknown, method: string, node: AstNode, extraFlags?: string) => RegExp;
4
+ export declare const toHostRegex: (arg: unknown, method: string, extraFlags?: string) => RegExp;
6
5
  export declare const matchToValue: (protos: Prototypes, match: RegExpMatchArray) => ProgramArray;
7
- export declare const constructRegExp: (protos: Prototypes, args: Array<unknown>, node: AstNode, proto?: ProgramObject) => ProgramRegExp;
6
+ export declare const constructRegExp: (protos: Prototypes, args: Array<unknown>, proto?: ProgramObject) => ProgramRegExp;
8
7
  export declare const regexpGlobal: <R>(runner: Runner<R>) => import("../interpreter/objects.js").NativeFunction<R>;
@@ -1,6 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import { constructor, methods, prototypeFrom, receiver } from "../interpreter/native.js";
3
- import { InterpreterRuntimeError, syntaxError } from "../interpreter/model.js";
3
+ import { syntaxError, typeError } from "../interpreter/model.js";
4
4
  import { define, defineAccessor, getOwn, ProgramArray, ProgramObject, ProgramRegExp, record, set, } from "../interpreter/objects.js";
5
5
  import { coerceToNumber, coerceToString } from "./value.js";
6
6
  const flagProperties = [
@@ -15,7 +15,7 @@ const flagProperties = [
15
15
  ];
16
16
  const regexFailureReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "");
17
17
  const escapeRegexHint = 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.';
18
- export const toHostRegex = (arg, method, node, extraFlags = "") => {
18
+ export const toHostRegex = (arg, method, extraFlags = "") => {
19
19
  // Native parity: an undefined pattern behaves as an empty pattern.
20
20
  if (arg === undefined)
21
21
  return new RegExp("", extraFlags);
@@ -26,10 +26,10 @@ export const toHostRegex = (arg, method, node, extraFlags = "") => {
26
26
  return new RegExp(arg, extraFlags);
27
27
  }
28
28
  catch (error) {
29
- throw syntaxError(`String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`, node);
29
+ throw syntaxError(`String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`);
30
30
  }
31
31
  }
32
- throw new InterpreterRuntimeError(`String.${method} expects a regular expression (a /pattern/flags literal or new RegExp(...)) or a string pattern, not ${arg === null ? "null" : typeof arg}.`, node);
32
+ throw typeError(`String.${method} expects a regular expression (a /pattern/flags literal or new RegExp(...)) or a string pattern, not ${arg === null ? "null" : typeof arg}.`);
33
33
  };
34
34
  export const matchToValue = (protos, match) => {
35
35
  const result = new ProgramArray(protos.Array, Array.from(match, (group) => group));
@@ -43,12 +43,12 @@ export const matchToValue = (protos, match) => {
43
43
  define(result, "indices", indicesToValue(protos, match.indices));
44
44
  return result;
45
45
  };
46
- export const constructRegExp = (protos, args, node, proto = protos.RegExp) => {
46
+ export const constructRegExp = (protos, args, proto = protos.RegExp) => {
47
47
  const first = args[0];
48
48
  const pattern = first instanceof ProgramRegExp ? first.regex.source : first === undefined ? "" : coerceToString(first);
49
49
  const flagsArg = args[1];
50
50
  if (flagsArg !== undefined && typeof flagsArg !== "string") {
51
- throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`, node);
51
+ throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`);
52
52
  }
53
53
  const flags = flagsArg ?? (first instanceof ProgramRegExp ? first.regex.flags : "");
54
54
  try {
@@ -58,7 +58,7 @@ export const constructRegExp = (protos, args, node, proto = protos.RegExp) => {
58
58
  const reason = regexFailureReason(error);
59
59
  throw syntaxError(/flag/i.test(reason)
60
60
  ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
61
- : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`, node);
61
+ : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`);
62
62
  }
63
63
  };
64
64
  const toLength = (value) => {
@@ -74,21 +74,21 @@ export const regexpGlobal = (runner) => {
74
74
  const regexp = constructor(protos, proto, {
75
75
  name: "RegExp",
76
76
  length: 2,
77
- call: (_, args, node) => Effect.sync(() => constructRegExp(protos, args, node)),
78
- construct: (args, newTarget, node) => Effect.sync(() => constructRegExp(protos, args, node, prototypeFrom(newTarget, proto))),
77
+ call: (_, args) => Effect.sync(() => constructRegExp(protos, args)),
78
+ construct: (args, newTarget) => Effect.sync(() => constructRegExp(protos, args, prototypeFrom(newTarget, proto))),
79
79
  });
80
80
  methods(protos, regexp, [
81
81
  [
82
82
  "escape",
83
83
  1,
84
- (_, args, node) => {
84
+ (_, args) => {
85
85
  if (typeof args[0] !== "string")
86
- throw new InterpreterRuntimeError("RegExp.escape expects a string.", node);
86
+ throw typeError("RegExp.escape expects a string.");
87
87
  return RegExp.escape(args[0]);
88
88
  },
89
89
  ],
90
90
  ]);
91
- const self = (thisValue, name, node) => receiver(ProgramRegExp, thisValue, `RegExp.prototype.${name}`, node);
91
+ const self = (thisValue, name) => receiver(ProgramRegExp, thisValue, `RegExp.prototype.${name}`);
92
92
  defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").regex.source);
93
93
  defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").regex.flags);
94
94
  for (const name of flagProperties)
@@ -97,8 +97,8 @@ export const regexpGlobal = (runner) => {
97
97
  const run = (name) => [
98
98
  name,
99
99
  1,
100
- (thisValue, args, node) => {
101
- const value = self(thisValue, name, node);
100
+ (thisValue, args) => {
101
+ const value = self(thisValue, name);
102
102
  const input = coerceToString(args[0]);
103
103
  const stateful = value.regex.global || value.regex.sticky;
104
104
  value.regex.lastIndex = toLength(getOwn(value, "lastIndex"));
@@ -113,7 +113,7 @@ export const regexpGlobal = (runner) => {
113
113
  methods(protos, proto, [
114
114
  run("exec"),
115
115
  run("test"),
116
- ["toString", 0, (thisValue, _, node) => coerceToString(self(thisValue, "toString", node))],
116
+ ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
117
117
  ]);
118
118
  return regexp;
119
119
  };
@@ -1,27 +1,27 @@
1
1
  import { Effect } from "effect";
2
2
  import { toProgram } from "../data.js";
3
3
  import { constructor, methods } from "../interpreter/native.js";
4
- import { InterpreterRuntimeError, rangeError } from "../interpreter/model.js";
4
+ import { invalidData, rangeError, typeError } from "../interpreter/model.js";
5
5
  import { ProgramArray, ProgramPromise, ProgramRegExp, record } from "../interpreter/objects.js";
6
6
  import { containsOpaqueReference, typeofValue } from "../interpreter/references.js";
7
7
  import { applyCollectionCallback, isSupportedCallback } from "../interpreter/runner.js";
8
8
  import { matchToValue, toHostRegex } from "./regexp.js";
9
9
  import { coerceToNumber, coerceToString, coercion } from "./value.js";
10
10
  // console is intercepted by the interpreter before reaching here.
11
- const requireDataArgument = (name, index, arg, node) => {
11
+ const requireDataArgument = (name, index, arg) => {
12
12
  if (containsOpaqueReference(arg)) {
13
- throw new InterpreterRuntimeError(`String.${name} expects argument ${index + 1} to be a data value.`, node, "InvalidDataValue");
13
+ throw invalidData(`String.${name} expects argument ${index + 1} to be a data value.`);
14
14
  }
15
15
  return arg;
16
16
  };
17
- const replaceAllNeedsGlobal = (pattern, node) => {
17
+ const replaceAllNeedsGlobal = (pattern) => {
18
18
  if (!pattern.global) {
19
- throw new InterpreterRuntimeError(`String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.replace to replace only the first match.`, node);
19
+ throw typeError(`String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.replace to replace only the first match.`);
20
20
  }
21
21
  };
22
- const replaceWithCallback = (runner, value, name, args, node) => {
22
+ const replaceWithCallback = (runner, value, name, args) => {
23
23
  const protos = runner.prototypes;
24
- const apply = applyCollectionCallback(runner, args[1], `String.${name}`, node);
24
+ const apply = applyCollectionCallback(runner, args[1], `String.${name}`);
25
25
  const matches = [];
26
26
  const collect = (...callbackArgs) => {
27
27
  const match = callbackArgs[0];
@@ -29,7 +29,7 @@ const replaceWithCallback = (runner, value, name, args, node) => {
29
29
  const hasGroups = groups !== null && typeof groups === "object";
30
30
  const offset = callbackArgs[callbackArgs.length - (hasGroups ? 3 : 2)];
31
31
  if (typeof match !== "string" || typeof offset !== "number") {
32
- throw new InterpreterRuntimeError(`String.${name} produced an invalid replacement match.`, node);
32
+ throw typeError(`String.${name} produced an invalid replacement match.`);
33
33
  }
34
34
  if (hasGroups)
35
35
  callbackArgs[callbackArgs.length - 1] = record(protos.Object, groups);
@@ -39,14 +39,14 @@ const replaceWithCallback = (runner, value, name, args, node) => {
39
39
  const pattern = args[0];
40
40
  if (pattern instanceof ProgramRegExp) {
41
41
  if (name === "replaceAll")
42
- replaceAllNeedsGlobal(pattern.regex, node);
42
+ replaceAllNeedsGlobal(pattern.regex);
43
43
  if (name === "replace")
44
44
  value.replace(pattern.regex, collect);
45
45
  else
46
46
  value.replaceAll(pattern.regex, collect);
47
47
  }
48
48
  else {
49
- const search = coerceToString(requireDataArgument(name, 0, pattern, node));
49
+ const search = coerceToString(requireDataArgument(name, 0, pattern));
50
50
  if (name === "replace")
51
51
  value.replace(search, collect);
52
52
  else
@@ -76,9 +76,9 @@ export const stringGlobal = (runner) => {
76
76
  const codeUnits = (name, op) => [
77
77
  name,
78
78
  1,
79
- (_, args, node) => op(...args.map((arg) => {
79
+ (_, args) => op(...args.map((arg) => {
80
80
  if (typeof arg !== "number") {
81
- throw new InterpreterRuntimeError(`String.${name} expects number arguments.`, node);
81
+ throw typeError(`String.${name} expects number arguments.`);
82
82
  }
83
83
  return arg;
84
84
  })),
@@ -87,41 +87,45 @@ export const stringGlobal = (runner) => {
87
87
  codeUnits("fromCharCode", String.fromCharCode),
88
88
  codeUnits("fromCodePoint", String.fromCodePoint),
89
89
  ]);
90
- const self = (thisValue, name, node) => {
90
+ const self = (thisValue, name) => {
91
91
  if (typeof thisValue === "string")
92
92
  return thisValue;
93
93
  if (thisValue === null || thisValue === undefined) {
94
- throw new InterpreterRuntimeError(`String.prototype.${name} called on null or undefined.`, node);
94
+ throw typeError(`String.prototype.${name} called on null or undefined.`);
95
95
  }
96
96
  return coerceToString(thisValue);
97
97
  };
98
98
  // Coerce arguments like native JS; opaque runtime references still reject.
99
- const str = (name, args, index, node) => coerceToString(requireDataArgument(name, index, args[index], node));
100
- const num = (name, args, index, node) => coerceToNumber(requireDataArgument(name, index, args[index], node));
101
- const optNum = (name, args, index, node) => args[index] === undefined ? undefined : num(name, args, index, node);
102
- const optStr = (name, args, index, node) => args[index] === undefined ? undefined : str(name, args, index, node);
103
- const rejectRegex = (name, args, node) => {
99
+ const str = (name, args, index) => coerceToString(requireDataArgument(name, index, args[index]));
100
+ const num = (name, args, index) => coerceToNumber(requireDataArgument(name, index, args[index]));
101
+ const optNum = (name, args, index) => args[index] === undefined ? undefined : num(name, args, index);
102
+ const optStr = (name, args, index) => args[index] === undefined ? undefined : str(name, args, index);
103
+ const rejectRegex = (name, args) => {
104
104
  if (args[0] instanceof ProgramRegExp) {
105
- throw new InterpreterRuntimeError(`String.${name} cannot take a regular expression; use regex.test(string) or String.search instead.`, node);
105
+ throw typeError(`String.${name} cannot take a regular expression; use regex.test(string) or String.search instead.`);
106
106
  }
107
107
  };
108
- const simple = (name, length, op) => [name, length, (thisValue, args, node) => op(self(thisValue, name, node), args, node)];
109
- const replace = (name) => simple(name, 2, (value, args, node) => {
108
+ const simple = (name, length, op) => [
109
+ name,
110
+ length,
111
+ (thisValue, args) => op(self(thisValue, name), args),
112
+ ];
113
+ const replace = (name) => simple(name, 2, (value, args) => {
110
114
  if (isSupportedCallback(args[1]))
111
- return replaceWithCallback(runner, value, name, args, node);
115
+ return replaceWithCallback(runner, value, name, args);
112
116
  if (typeofValue(args[1]) === "function") {
113
- throw new InterpreterRuntimeError(`String.${name} cannot use this callable as a replacer; wrap it in an arrow function, e.g. (match) => tools.ns.tool(match).`, node);
117
+ throw typeError(`String.${name} cannot use this callable as a replacer; wrap it in an arrow function, e.g. (match) => tools.ns.tool(match).`);
114
118
  }
115
119
  if (args[0] instanceof ProgramRegExp) {
116
120
  const pattern = args[0].regex;
117
- const replacement = str(name, args, 1, node);
121
+ const replacement = str(name, args, 1);
118
122
  if (name === "replaceAll")
119
- replaceAllNeedsGlobal(pattern, node);
123
+ replaceAllNeedsGlobal(pattern);
120
124
  return name === "replace" ? value.replace(pattern, replacement) : value.replaceAll(pattern, replacement);
121
125
  }
122
126
  if (name === "replace")
123
- return value.replace(str(name, args, 0, node), str(name, args, 1, node));
124
- return value.replaceAll(str(name, args, 0, node), str(name, args, 1, node));
127
+ return value.replace(str(name, args, 0), str(name, args, 1));
128
+ return value.replaceAll(str(name, args, 0), str(name, args, 1));
125
129
  });
126
130
  methods(protos, protos.String, [
127
131
  simple("toString", 0, (value) => value),
@@ -134,47 +138,47 @@ export const stringGlobal = (runner) => {
134
138
  simple("trimEnd", 0, (value) => value.trimEnd()),
135
139
  simple("trimRight", 0, (value) => value.trimEnd()),
136
140
  // Locale/options are deliberately unsupported; comparison uses the host default locale.
137
- simple("localeCompare", 1, (value, args, node) => value.localeCompare(str("localeCompare", args, 0, node))),
138
- simple("normalize", 0, (value, args, node) => {
139
- const form = optStr("normalize", args, 0, node);
141
+ simple("localeCompare", 1, (value, args) => value.localeCompare(str("localeCompare", args, 0))),
142
+ simple("normalize", 0, (value, args) => {
143
+ const form = optStr("normalize", args, 0);
140
144
  try {
141
145
  return value.normalize(form);
142
146
  }
143
147
  catch {
144
- throw rangeError(`String.normalize expects the form "NFC", "NFD", "NFKC", or "NFKD" (got ${JSON.stringify(form)}).`, node);
148
+ throw rangeError(`String.normalize expects the form "NFC", "NFD", "NFKC", or "NFKD" (got ${JSON.stringify(form)}).`);
145
149
  }
146
150
  }),
147
- simple("split", 2, (value, args, node) => {
151
+ simple("split", 2, (value, args) => {
148
152
  const wrap = (parts) => new ProgramArray(protos.Array, parts);
149
153
  // Native: an undefined separator returns the whole string, not a split on "undefined",
150
154
  // unless the limit truncates to zero.
151
- const requestedLimit = optNum("split", args, 1, node);
155
+ const requestedLimit = optNum("split", args, 1);
152
156
  if (args[0] === undefined) {
153
157
  return wrap(requestedLimit !== undefined && requestedLimit >>> 0 === 0 ? [] : [value]);
154
158
  }
155
159
  if (args[0] instanceof ProgramRegExp)
156
160
  return wrap(value.split(args[0].regex, requestedLimit));
157
- return wrap(value.split(str("split", args, 0, node), requestedLimit === undefined ? undefined : requestedLimit >>> 0));
161
+ return wrap(value.split(str("split", args, 0), requestedLimit === undefined ? undefined : requestedLimit >>> 0));
158
162
  }),
159
- simple("slice", 2, (value, args, node) => value.slice(optNum("slice", args, 0, node), optNum("slice", args, 1, node))),
160
- simple("includes", 1, (value, args, node) => {
161
- rejectRegex("includes", args, node);
162
- return value.includes(str("includes", args, 0, node), optNum("includes", args, 1, node));
163
+ simple("slice", 2, (value, args) => value.slice(optNum("slice", args, 0), optNum("slice", args, 1))),
164
+ simple("includes", 1, (value, args) => {
165
+ rejectRegex("includes", args);
166
+ return value.includes(str("includes", args, 0), optNum("includes", args, 1));
163
167
  }),
164
- simple("startsWith", 1, (value, args, node) => {
165
- rejectRegex("startsWith", args, node);
166
- return value.startsWith(str("startsWith", args, 0, node), optNum("startsWith", args, 1, node));
168
+ simple("startsWith", 1, (value, args) => {
169
+ rejectRegex("startsWith", args);
170
+ return value.startsWith(str("startsWith", args, 0), optNum("startsWith", args, 1));
167
171
  }),
168
- simple("endsWith", 1, (value, args, node) => {
169
- rejectRegex("endsWith", args, node);
170
- return value.endsWith(str("endsWith", args, 0, node), optNum("endsWith", args, 1, node));
172
+ simple("endsWith", 1, (value, args) => {
173
+ rejectRegex("endsWith", args);
174
+ return value.endsWith(str("endsWith", args, 0), optNum("endsWith", args, 1));
171
175
  }),
172
- simple("indexOf", 1, (value, args, node) => value.indexOf(str("indexOf", args, 0, node), optNum("indexOf", args, 1, node))),
173
- simple("lastIndexOf", 1, (value, args, node) => value.lastIndexOf(str("lastIndexOf", args, 0, node), optNum("lastIndexOf", args, 1, node))),
176
+ simple("indexOf", 1, (value, args) => value.indexOf(str("indexOf", args, 0), optNum("indexOf", args, 1))),
177
+ simple("lastIndexOf", 1, (value, args) => value.lastIndexOf(str("lastIndexOf", args, 0), optNum("lastIndexOf", args, 1))),
174
178
  replace("replace"),
175
179
  replace("replaceAll"),
176
- simple("match", 1, (value, args, node) => {
177
- const pattern = toHostRegex(args[0], "match", node);
180
+ simple("match", 1, (value, args) => {
181
+ const pattern = toHostRegex(args[0], "match");
178
182
  const matched = value.match(pattern);
179
183
  if (matched === null)
180
184
  return null;
@@ -183,32 +187,32 @@ export const stringGlobal = (runner) => {
183
187
  return toProgram(protos, matched, "String.match result");
184
188
  return matchToValue(protos, matched);
185
189
  }),
186
- simple("matchAll", 1, (value, args, node) => {
187
- const pattern = toHostRegex(args[0], "matchAll", node, "g");
190
+ simple("matchAll", 1, (value, args) => {
191
+ const pattern = toHostRegex(args[0], "matchAll", "g");
188
192
  if (!pattern.global) {
189
- throw new InterpreterRuntimeError(`String.matchAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.match for a single match.`, node);
193
+ throw typeError(`String.matchAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.match for a single match.`);
190
194
  }
191
195
  return new ProgramArray(protos.Array, Array.from(value.matchAll(pattern), (match) => matchToValue(protos, match)));
192
196
  }),
193
- simple("search", 1, (value, args, node) => value.search(toHostRegex(args[0], "search", node))),
194
- simple("repeat", 1, (value, args, node) => {
195
- const count = num("repeat", args, 0, node);
197
+ simple("search", 1, (value, args) => value.search(toHostRegex(args[0], "search"))),
198
+ simple("repeat", 1, (value, args) => {
199
+ const count = num("repeat", args, 0);
196
200
  if (!Number.isFinite(count) || count < 0) {
197
- throw rangeError("String.repeat expects a finite non-negative count.", node);
201
+ throw rangeError("String.repeat expects a finite non-negative count.");
198
202
  }
199
203
  return value.repeat(count);
200
204
  }),
201
- simple("padStart", 1, (value, args, node) => value.padStart(num("padStart", args, 0, node), optStr("padStart", args, 1, node))),
202
- simple("padEnd", 1, (value, args, node) => value.padEnd(num("padEnd", args, 0, node), optStr("padEnd", args, 1, node))),
203
- simple("charAt", 1, (value, args, node) => value.charAt(optNum("charAt", args, 0, node) ?? 0)),
204
- simple("at", 1, (value, args, node) => value.at(optNum("at", args, 0, node) ?? 0)),
205
- simple("substring", 2, (value, args, node) => value.substring(optNum("substring", args, 0, node) ?? 0, optNum("substring", args, 1, node))),
206
- simple("substr", 2, (value, args, node) => value.substr(optNum("substr", args, 0, node) ?? 0, optNum("substr", args, 1, node))),
205
+ simple("padStart", 1, (value, args) => value.padStart(num("padStart", args, 0), optStr("padStart", args, 1))),
206
+ simple("padEnd", 1, (value, args) => value.padEnd(num("padEnd", args, 0), optStr("padEnd", args, 1))),
207
+ simple("charAt", 1, (value, args) => value.charAt(optNum("charAt", args, 0) ?? 0)),
208
+ simple("at", 1, (value, args) => value.at(optNum("at", args, 0) ?? 0)),
209
+ simple("substring", 2, (value, args) => value.substring(optNum("substring", args, 0) ?? 0, optNum("substring", args, 1))),
210
+ simple("substr", 2, (value, args) => value.substr(optNum("substr", args, 0) ?? 0, optNum("substr", args, 1))),
207
211
  simple("isWellFormed", 0, (value) => value.isWellFormed()),
208
212
  simple("toWellFormed", 0, (value) => value.toWellFormed()),
209
- simple("charCodeAt", 1, (value, args, node) => value.charCodeAt(optNum("charCodeAt", args, 0, node) ?? 0)),
210
- simple("codePointAt", 1, (value, args, node) => value.codePointAt(optNum("codePointAt", args, 0, node) ?? 0)),
211
- simple("concat", 1, (value, args, node) => value.concat(...args.map((_, index) => str("concat", args, index, node)))),
213
+ simple("charCodeAt", 1, (value, args) => value.charCodeAt(optNum("charCodeAt", args, 0) ?? 0)),
214
+ simple("codePointAt", 1, (value, args) => value.codePointAt(optNum("codePointAt", args, 0) ?? 0)),
215
+ simple("concat", 1, (value, args) => value.concat(...args.map((_, index) => str("concat", args, index)))),
212
216
  ]);
213
217
  return string;
214
218
  };