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

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,8 +1,8 @@
1
1
  import { Cause, Deferred, Effect, Exit } from "effect";
2
2
  import { toProgram } from "../data.js";
3
3
  import { ToolReference } from "../tool-runtime.js";
4
- import { AsyncIteratorSymbol, GeneratorReturn, InterpreterRuntimeError, IteratorSymbol, locate, OptionalShortCircuit, ProgramThrow, rangeError, unsupportedSyntax, } from "./model.js";
5
- import { caughtErrorValue } from "./errors.js";
4
+ import { AsyncIteratorSymbol, CallSite, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, ProgramThrow, rangeError, typeError, unsupportedSyntax, } from "./model.js";
5
+ import { locate, materialize } from "./errors.js";
6
6
  import { globals } from "./globals.js";
7
7
  import { assign, Callable, define, get, has, hasPrototype, keys, NativeFunction, parseArrayIndex, ProgramArray, ProgramDate, ProgramFunction, ProgramGenerator, ProgramMap, ProgramObject, ProgramPromise, ProgramSet, ProgramURLSearchParams, record, remove, set, } from "./objects.js";
8
8
  import { preserveConsumerError } from "./runner.js";
@@ -45,11 +45,11 @@ const calleeDescription = (callee) => {
45
45
  // OrdinaryHasInstance: walk the left operand's chain looking for the constructor's `prototype`.
46
46
  const instanceofValue = (lhs, rhs, node) => {
47
47
  if (!(rhs instanceof Callable)) {
48
- throw new InterpreterRuntimeError("The right-hand side of 'instanceof' is not callable.", node);
48
+ throw typeError("The right-hand side of 'instanceof' is not callable.", node);
49
49
  }
50
50
  const prototype = get(rhs, "prototype");
51
51
  if (!(prototype instanceof ProgramObject)) {
52
- throw new InterpreterRuntimeError("The right-hand side of 'instanceof' has no 'prototype' object.", node);
52
+ throw typeError("The right-hand side of 'instanceof' has no 'prototype' object.", node);
53
53
  }
54
54
  return hasPrototype(lhs, prototype);
55
55
  };
@@ -132,7 +132,7 @@ const loopDeclaration = (left, statement) => {
132
132
  return undefined;
133
133
  const declaration = left.declarations.length === 1 ? left.declarations[0] : undefined;
134
134
  if (declaration === undefined) {
135
- throw new InterpreterRuntimeError(`${statement} supports one declared binding.`, left);
135
+ throw typeError(`${statement} supports one declared binding.`, left);
136
136
  }
137
137
  const kind = left.kind;
138
138
  return {
@@ -141,7 +141,6 @@ const loopDeclaration = (left, statement) => {
141
141
  lexical: kind !== "var",
142
142
  };
143
143
  };
144
- const promiseResolutionNode = { type: "PromiseResolution", start: 0, end: 0 };
145
144
  /** One program execution: the tool bridge, promise scheduler, captured logs, and the global scope built once. */
146
145
  export class Runtime {
147
146
  executeTool;
@@ -163,9 +162,9 @@ export class Runtime {
163
162
  // Calling back into the program never reads frame state, so any frame serves; the root is always alive.
164
163
  this.root = new Frame(this, new ScopeStack([globalScope]));
165
164
  this.runner = {
166
- invokeCallable: (callable, thisValue, args, node) => this.root.invokeCallable(callable, thisValue, args, node),
165
+ invokeCallable: (callable, thisValue, args) => this.root.invokeCallable(callable, thisValue, args),
167
166
  settlePromise: (promise) => this.root.settlePromise(promise),
168
- syncIterator: (value, node) => this.root.syncIterator(value, node),
167
+ syncIterator: (value) => this.root.syncIterator(value),
169
168
  prototypes,
170
169
  };
171
170
  for (const [name, value] of [...globals(this), ...extraGlobals(this)]) {
@@ -206,11 +205,11 @@ class Frame {
206
205
  break;
207
206
  }
208
207
  if (result.kind === "break" || result.kind === "continue") {
209
- throw new InterpreterRuntimeError(`Unexpected '${result.kind}' outside of a loop.`, statement);
208
+ throw typeError(`Unexpected '${result.kind}' outside of a loop.`, statement);
210
209
  }
211
210
  }
212
211
  // The implicit async body adopts returned promises before copy-out.
213
- value = yield* resolvePromiseValue(self.runtime.runner, value, program);
212
+ value = yield* resolvePromiseValue(self.runtime.runner, value);
214
213
  return value;
215
214
  }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
216
215
  }
@@ -348,7 +347,7 @@ class Frame {
348
347
  return Effect.gen(function* () {
349
348
  const discriminant = yield* self.evaluateExpression(node.discriminant);
350
349
  if (containsOpaqueReference(discriminant)) {
351
- throw new InterpreterRuntimeError("Switch discriminants must be data values.", node, "InvalidDataValue");
350
+ throw invalidData("Switch discriminants must be data values.", node);
352
351
  }
353
352
  self.scopes.push();
354
353
  return yield* Effect.gen(function* () {
@@ -366,7 +365,7 @@ class Frame {
366
365
  }
367
366
  const candidate = yield* self.evaluateExpression(test);
368
367
  if (containsOpaqueReference(candidate)) {
369
- throw new InterpreterRuntimeError("Switch case values must be data values.", test, "InvalidDataValue");
368
+ throw invalidData("Switch case values must be data values.", test);
370
369
  }
371
370
  if (candidate === discriminant) {
372
371
  selected = index;
@@ -469,7 +468,7 @@ class Frame {
469
468
  const iterator = yield* self.customIterator(right, node, awaiting);
470
469
  const cursor = iterator === undefined ? yield* self.syncIterator(right, node) : undefined;
471
470
  if (iterator === undefined && cursor === undefined) {
472
- throw new InterpreterRuntimeError(`${awaiting ? "for await...of" : "for...of"} requires an array, string, Map, Set, or URLSearchParams, or custom iterator value.`, node);
471
+ throw invalidData(`${awaiting ? "for await...of" : "for...of"} requires an array, string, Map, Set, or URLSearchParams, or custom iterator value.`, node);
473
472
  }
474
473
  const close = () => iterator
475
474
  ? self.closeIterator(iterator, node, awaiting)
@@ -477,7 +476,7 @@ class Frame {
477
476
  ? Effect.andThen(cursor?.close ?? Effect.void, Effect.yieldNow)
478
477
  : (cursor?.close ?? Effect.void);
479
478
  if (left.type === "RestElement" || left.type === "AssignmentPattern") {
480
- throw new InterpreterRuntimeError("Unsupported for...of binding.", left);
479
+ throw typeError("Unsupported for...of binding.", left);
481
480
  }
482
481
  const assignment = left.type === "VariableDeclaration" ? undefined : left;
483
482
  const evaluateBody = (value) => Effect.gen(function* () {
@@ -500,7 +499,7 @@ class Frame {
500
499
  while (true) {
501
500
  const current = iterator
502
501
  ? yield* self.nextIteratorResult(iterator, node, awaiting)
503
- : yield* cursor?.next ?? Effect.fail(new InterpreterRuntimeError("Iterator is unavailable.", node));
502
+ : yield* cursor?.next ?? Effect.die(typeError("Iterator is unavailable.", node));
504
503
  const step = cursor && awaiting ? { done: current.done, value: yield* self.awaitValue(current.value) } : current;
505
504
  if (step.done)
506
505
  return { kind: "none" };
@@ -523,8 +522,8 @@ class Frame {
523
522
  self.scopes.pop();
524
523
  })));
525
524
  }
526
- awaitValue(value, node = promiseResolutionNode) {
527
- return Effect.flatMap(resolvePromise(this.runtime.runner, this.runtime.promises, value, node), (promise) => this.settlePromise(promise));
525
+ awaitValue(value) {
526
+ return Effect.flatMap(resolvePromise(this.runtime.runner, this.runtime.promises, value), (promise) => this.settlePromise(promise));
528
527
  }
529
528
  awaitAsyncFromSyncValue(iterator, value, node, closeOnRejection) {
530
529
  const self = this;
@@ -648,12 +647,12 @@ class Frame {
648
647
  requireIteratorObject(value, context, node) {
649
648
  if (value instanceof ProgramObject)
650
649
  return value;
651
- throw new InterpreterRuntimeError(`${context} must be an object.`, node);
650
+ throw typeError(`${context} must be an object.`, node);
652
651
  }
653
652
  requireIteratorMethod(value, context, node) {
654
653
  if (typeofValue(value) === "function")
655
654
  return value;
656
- throw new InterpreterRuntimeError(`${context} must be a function.`, node);
655
+ throw typeError(`${context} must be a function.`, node);
657
656
  }
658
657
  // for...in over null/undefined iterates nothing, like JS.
659
658
  enumerableKeys(value, node) {
@@ -675,7 +674,7 @@ class Frame {
675
674
  const right = yield* self.evaluateExpression(node.right);
676
675
  const keys = self.enumerableKeys(right, node.right);
677
676
  if (left.type !== "Identifier" && left.type !== "VariableDeclaration") {
678
- throw new InterpreterRuntimeError("Unsupported for...in binding.", left);
677
+ throw typeError("Unsupported for...in binding.", left);
679
678
  }
680
679
  const assignmentName = left.type === "Identifier" ? left.name : undefined;
681
680
  for (const key of keys) {
@@ -749,7 +748,7 @@ class Frame {
749
748
  if (cause.reasons.some(Cause.isInterruptReason) || Cause.squash(cause) instanceof GeneratorReturn || !handler) {
750
749
  return Effect.failCause(cause);
751
750
  }
752
- const caught = caughtErrorValue(self.runtime.runner, Cause.squash(cause));
751
+ const caught = materialize(self.runtime.runner, Cause.squash(cause));
753
752
  const parameter = handler.param;
754
753
  self.scopes.push();
755
754
  return Effect.gen(function* () {
@@ -776,7 +775,7 @@ class Frame {
776
775
  return Effect.gen(function* () {
777
776
  for (const declaration of node.declarations) {
778
777
  if (declaration.type !== "VariableDeclarator") {
779
- throw new InterpreterRuntimeError("Unsupported variable declaration shape.", declaration);
778
+ throw typeError("Unsupported variable declaration shape.", declaration);
780
779
  }
781
780
  const init = declaration.init;
782
781
  // `var x` alone is a no-op: the binding was hoisted on function entry.
@@ -810,7 +809,7 @@ class Frame {
810
809
  }
811
810
  if (pattern.type === "ObjectPattern") {
812
811
  if (!(value instanceof ProgramObject)) {
813
- throw new InterpreterRuntimeError(`Object destructuring requires a data object or array value, received ${describeValue(value)}.`, pattern, "InvalidDataValue");
812
+ throw typeError(`Object destructuring requires a data object or array value, received ${describeValue(value)}.`, pattern);
814
813
  }
815
814
  const consumed = new Set();
816
815
  for (const property of pattern.properties) {
@@ -822,14 +821,14 @@ class Frame {
822
821
  }
823
822
  const key = yield* self.destructuringPropertyKey(property);
824
823
  consumed.add(typeof key === "symbol" ? key : String(key));
825
- yield* self.declarePattern(property.value, get(value, key), mutable, property, initialize);
824
+ yield* self.declarePattern(property.value, self.readProperty(value, key, property), mutable, property, initialize);
826
825
  }
827
826
  return;
828
827
  }
829
828
  if (pattern.type === "ArrayPattern") {
830
829
  return yield* self.destructureArrayPattern(pattern, value, (target, item, context) => self.declarePattern(target, item, mutable, context, initialize));
831
830
  }
832
- throw new InterpreterRuntimeError(`Unsupported binding pattern '${pattern.type}'.`, pattern);
831
+ throw typeError(`Unsupported binding pattern '${pattern.type}'.`, pattern);
833
832
  });
834
833
  }
835
834
  assignPattern(pattern, value, node) {
@@ -850,7 +849,7 @@ class Frame {
850
849
  }
851
850
  if (pattern.type === "ObjectPattern") {
852
851
  if (!(value instanceof ProgramObject)) {
853
- throw new InterpreterRuntimeError(`Object destructuring requires a data object or array value, received ${describeValue(value)}.`, pattern, "InvalidDataValue");
852
+ throw invalidData(`Object destructuring requires a data object or array value, received ${describeValue(value)}.`, pattern);
854
853
  }
855
854
  const consumed = new Set();
856
855
  for (const property of pattern.properties) {
@@ -862,14 +861,14 @@ class Frame {
862
861
  }
863
862
  const key = yield* self.destructuringPropertyKey(property);
864
863
  consumed.add(typeof key === "symbol" ? key : String(key));
865
- yield* self.assignPattern(property.value, get(value, key), property);
864
+ yield* self.assignPattern(property.value, self.readProperty(value, key, property), property);
866
865
  }
867
866
  return;
868
867
  }
869
868
  if (pattern.type === "ArrayPattern") {
870
869
  return yield* self.destructureArrayPattern(pattern, value, (target, item, context) => self.assignPattern(target, item, context));
871
870
  }
872
- throw new InterpreterRuntimeError(`Unsupported assignment pattern '${pattern.type}'.`, node);
871
+ throw typeError(`Unsupported assignment pattern '${pattern.type}'.`, node);
873
872
  });
874
873
  }
875
874
  evaluateDefault(pattern) {
@@ -882,7 +881,7 @@ class Frame {
882
881
  return Effect.gen(function* () {
883
882
  const cursor = yield* self.syncIterator(value, pattern);
884
883
  if (cursor === undefined) {
885
- throw new InterpreterRuntimeError("Array destructuring requires a supported iterable value.", pattern);
884
+ throw typeError("Array destructuring requires a supported iterable value.", pattern);
886
885
  }
887
886
  let done = false;
888
887
  for (const element of pattern.elements) {
@@ -920,7 +919,7 @@ class Frame {
920
919
  }
921
920
  destructuringPropertyKey(property) {
922
921
  if (property.type !== "Property" || property.kind !== "init") {
923
- throw new InterpreterRuntimeError("Unsupported object destructuring property.", property);
922
+ throw typeError("Unsupported object destructuring property.", property);
924
923
  }
925
924
  const keyNode = property.key;
926
925
  if (property.computed) {
@@ -937,7 +936,7 @@ class Frame {
937
936
  case "Literal": {
938
937
  const regex = node.regex;
939
938
  if (regex)
940
- return Effect.sync(() => constructRegExp(this.runtime.prototypes, [regex.pattern, regex.flags], node));
939
+ return Effect.sync(() => constructRegExp(this.runtime.prototypes, [regex.pattern, regex.flags]));
941
940
  return Effect.sync(() => toProgram(this.runtime.prototypes, node.value, "Literal"));
942
941
  }
943
942
  case "Identifier":
@@ -981,7 +980,7 @@ class Frame {
981
980
  return this.evaluateUpdateExpression(node);
982
981
  case "AwaitExpression": {
983
982
  // Await always suspends, including for plain values.
984
- return Effect.flatMap(this.evaluateExpression(node.argument), (value) => this.awaitValue(value, node));
983
+ return Effect.flatMap(this.evaluateExpression(node.argument), (value) => this.awaitValue(value));
985
984
  }
986
985
  case "YieldExpression":
987
986
  return this.evaluateYieldExpression(node);
@@ -1007,10 +1006,10 @@ class Frame {
1007
1006
  : callee instanceof NativeFunction
1008
1007
  ? `new ${name}(...) is not supported; call ${name}(...) without new instead.`
1009
1008
  : `${name} is not a constructor.`;
1010
- throw new InterpreterRuntimeError(message, node);
1009
+ throw typeError(message, node);
1011
1010
  }
1012
1011
  const args = yield* self.evaluateCallArguments(node.arguments);
1013
- return yield* construct(args, callee, node);
1012
+ return yield* self.native(() => construct(args, callee), node);
1014
1013
  });
1015
1014
  }
1016
1015
  evaluateBinaryExpression(node) {
@@ -1036,7 +1035,7 @@ class Frame {
1036
1035
  return has(rhs, lhs !== null && typeof lhs === "object" ? coerceToString(lhs) : lhs);
1037
1036
  }
1038
1037
  if (containsOpaqueReference(lhs) || containsOpaqueReference(rhs)) {
1039
- throw new InterpreterRuntimeError("Binary operators require data values.", node, "InvalidDataValue");
1038
+ throw invalidData("Binary operators require data values.", node);
1040
1039
  }
1041
1040
  // Null-prototype data needs explicit primitive coercion; identity and `in` retain raw objects.
1042
1041
  // Dates use their default string hint for addition and loose equality, and epoch time elsewhere.
@@ -1088,11 +1087,11 @@ class Frame {
1088
1087
  return l >>> r;
1089
1088
  case "in":
1090
1089
  if (!(rhs instanceof ProgramObject)) {
1091
- throw new InterpreterRuntimeError("The 'in' operator requires a data object on the right-hand side.", node);
1090
+ throw typeError("The 'in' operator requires a data object on the right-hand side.", node);
1092
1091
  }
1093
1092
  return has(rhs, coerceOperand(lhs));
1094
1093
  default:
1095
- throw new InterpreterRuntimeError(`Unsupported binary operator '${operator}'.`, node);
1094
+ throw typeError(`Unsupported binary operator '${operator}'.`, node);
1096
1095
  }
1097
1096
  }
1098
1097
  evaluateLogicalExpression(node) {
@@ -1104,7 +1103,7 @@ class Frame {
1104
1103
  return left ? Effect.succeed(left) : this.evaluateExpression(node.right);
1105
1104
  if (operator === "??")
1106
1105
  return left !== null && left !== undefined ? Effect.succeed(left) : this.evaluateExpression(node.right);
1107
- throw new InterpreterRuntimeError(`Unsupported logical operator '${operator}'.`, node);
1106
+ throw typeError(`Unsupported logical operator '${operator}'.`, node);
1108
1107
  });
1109
1108
  }
1110
1109
  evaluateUnaryExpression(node) {
@@ -1124,7 +1123,7 @@ class Frame {
1124
1123
  if (operator === "void")
1125
1124
  return undefined;
1126
1125
  if (containsOpaqueReference(value)) {
1127
- throw new InterpreterRuntimeError("Unary operators require data values.", node, "InvalidDataValue");
1126
+ throw invalidData("Unary operators require data values.", node);
1128
1127
  }
1129
1128
  const operand = value instanceof ProgramDate
1130
1129
  ? value.time
@@ -1143,7 +1142,7 @@ class Frame {
1143
1142
  result = ~operand;
1144
1143
  break;
1145
1144
  default:
1146
- throw new InterpreterRuntimeError(`Unsupported unary operator '${operator}'.`, node);
1145
+ throw typeError(`Unsupported unary operator '${operator}'.`, node);
1147
1146
  }
1148
1147
  return toProgram(this.runtime.prototypes, result, "Unary expression result");
1149
1148
  });
@@ -1180,7 +1179,7 @@ class Frame {
1180
1179
  return { write: true, next, result: next };
1181
1180
  }));
1182
1181
  }
1183
- throw new InterpreterRuntimeError("Assignment target must be an Identifier or MemberExpression.", left);
1182
+ throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
1184
1183
  });
1185
1184
  }
1186
1185
  evaluateLogicalAssignment(node, left, operator) {
@@ -1205,7 +1204,7 @@ class Frame {
1205
1204
  }))
1206
1205
  : Effect.succeed({ write: false, next: current, result: current }));
1207
1206
  }
1208
- throw new InterpreterRuntimeError("Assignment target must be an Identifier or MemberExpression.", left);
1207
+ throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
1209
1208
  }
1210
1209
  evaluateUpdateExpression(node) {
1211
1210
  const operator = node.operator;
@@ -1213,13 +1212,13 @@ class Frame {
1213
1212
  const prefix = node.prefix;
1214
1213
  const increment = operator === "++" ? 1 : operator === "--" ? -1 : undefined;
1215
1214
  if (increment === undefined) {
1216
- throw new InterpreterRuntimeError(`Unsupported update operator '${operator}'.`, node);
1215
+ throw typeError(`Unsupported update operator '${operator}'.`, node);
1217
1216
  }
1218
1217
  // CodeMode numeric coercion, not host Number(): null-prototype data objects would make
1219
1218
  // the host throw during ToPrimitive, and opaque runtime references must reject clearly.
1220
1219
  const operand = (current) => {
1221
1220
  if (containsOpaqueReference(current)) {
1222
- throw new InterpreterRuntimeError(`'${operator}' requires a data value.`, argument, "InvalidDataValue");
1221
+ throw invalidData(`'${operator}' requires a data value.`, argument);
1223
1222
  }
1224
1223
  return coerceToNumber(current);
1225
1224
  };
@@ -1239,7 +1238,7 @@ class Frame {
1239
1238
  return Effect.succeed({ write: true, next, result: prefix ? next : value });
1240
1239
  });
1241
1240
  }
1242
- throw new InterpreterRuntimeError("Update target must be an Identifier or MemberExpression.", argument);
1241
+ throw typeError("Update target must be an Identifier or MemberExpression.", argument);
1243
1242
  }
1244
1243
  // EvaluateCall: a member callee supplies its base object as `this`; anything else calls with undefined.
1245
1244
  evaluateCallExpression(node) {
@@ -1276,17 +1275,22 @@ class Frame {
1276
1275
  return Effect.gen(function* () {
1277
1276
  if (callable instanceof ToolReference) {
1278
1277
  if (callable.path.length === 0) {
1279
- throw new InterpreterRuntimeError("The tools root is not callable.", callee ?? node);
1278
+ throw typeError("The tools root is not callable.", callee ?? node);
1280
1279
  }
1281
1280
  return yield* self.createToolCallPromise(callable.path, args);
1282
1281
  }
1283
1282
  if (callable instanceof ProgramFunction)
1284
1283
  return yield* self.invokeFunction(callable, args);
1285
- if (callable instanceof NativeFunction)
1286
- return yield* callable.call(thisValue, args, node);
1287
- throw new InterpreterRuntimeError(`${calleeDescription(callee)} is not a function.`, callee ?? node);
1284
+ if (callable instanceof NativeFunction) {
1285
+ return yield* self.native(() => callable.call(thisValue, args), node);
1286
+ }
1287
+ throw typeError(`${calleeDescription(callee)} is not a function.`, callee ?? node);
1288
1288
  });
1289
1289
  }
1290
+ // Built-ins throw without a location, synchronously or inside their Effect; the call site supplies it.
1291
+ native(body, node) {
1292
+ return Effect.provideService(Effect.catchDefect(Effect.suspend(body), (defect) => Effect.die(locate(defect, node))), CallSite, node);
1293
+ }
1290
1294
  evaluateCallArguments(argNodes) {
1291
1295
  const self = this;
1292
1296
  return Effect.gen(function* () {
@@ -1296,7 +1300,7 @@ class Frame {
1296
1300
  const spread = yield* self.evaluateExpression(argNode.argument);
1297
1301
  const cursor = yield* self.syncIterator(spread, argNode);
1298
1302
  if (cursor === undefined)
1299
- throw new InterpreterRuntimeError("Spread arguments require a synchronous iterable.", argNode);
1303
+ throw typeError("Spread arguments require a synchronous iterable.", argNode);
1300
1304
  while (true) {
1301
1305
  const step = yield* cursor.next;
1302
1306
  if (step.done)
@@ -1341,7 +1345,7 @@ class Frame {
1341
1345
  return Effect.succeed(this.createGenerator(invocation, run, fn.async));
1342
1346
  if (!fn.async)
1343
1347
  return run;
1344
- return this.runtime.promises.createWithSelf((self) => Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, fn.body, self)));
1348
+ return this.runtime.promises.createWithSelf((self) => Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, self)));
1345
1349
  }
1346
1350
  createGenerator(invocation, run, asynchronous) {
1347
1351
  const state = { started: false, completed: false, draining: false, pending: [], pendingIndex: 0 };
@@ -1349,11 +1353,10 @@ class Frame {
1349
1353
  invocation.generatorAsync = asynchronous;
1350
1354
  const protos = this.runtime.prototypes;
1351
1355
  const result = (value, done) => record(protos.Object, { value, done });
1352
- const request = (kind, value, node) => {
1356
+ const request = (kind, value) => {
1353
1357
  const request = { kind, value, response: Deferred.makeUnsafe() };
1354
- if (!asynchronous && state.active) {
1355
- return Effect.fail(new InterpreterRuntimeError("Generator is already running.", node));
1356
- }
1358
+ if (!asynchronous && state.active)
1359
+ return Effect.die(typeError("Generator is already running."));
1357
1360
  if (asynchronous && (state.completed || (!state.started && kind !== "next"))) {
1358
1361
  state.started = true;
1359
1362
  state.completed = true;
@@ -1450,7 +1453,7 @@ class Frame {
1450
1453
  const self = this;
1451
1454
  return Effect.gen(function* () {
1452
1455
  if (!self.generatorState)
1453
- throw new InterpreterRuntimeError("yield is only valid inside a generator.", node);
1456
+ throw typeError("yield is only valid inside a generator.", node);
1454
1457
  if (node.delegate) {
1455
1458
  const value = argument ? yield* self.evaluateExpression(argument) : undefined;
1456
1459
  return yield* self.delegateYield(value, node);
@@ -1463,7 +1466,7 @@ class Frame {
1463
1466
  suspendGenerator(value, node) {
1464
1467
  const state = this.generatorState;
1465
1468
  if (!state?.active)
1466
- throw new InterpreterRuntimeError("Generator has no active request.", node);
1469
+ throw typeError("Generator has no active request.", node);
1467
1470
  Deferred.doneUnsafe(state.active.response, Exit.succeed(record(this.runtime.prototypes.Object, { value, done: false })));
1468
1471
  state.active = undefined;
1469
1472
  return Effect.flatMap(this.takeGeneratorRequest(state), (request) => {
@@ -1487,7 +1490,7 @@ class Frame {
1487
1490
  value instanceof ProgramURLSearchParams) {
1488
1491
  const cursor = yield* self.syncIterator(value, node);
1489
1492
  if (!cursor)
1490
- throw new InterpreterRuntimeError("Built-in iterator is unavailable.", node);
1493
+ throw typeError("Built-in iterator is unavailable.", node);
1491
1494
  while (true) {
1492
1495
  const step = yield* cursor.next;
1493
1496
  if (step.done)
@@ -1502,14 +1505,14 @@ class Frame {
1502
1505
  }
1503
1506
  if (error instanceof ProgramThrow) {
1504
1507
  yield* cursor.close;
1505
- throw new InterpreterRuntimeError("The delegated iterator does not provide a throw() method.", node);
1508
+ throw typeError("The delegated iterator does not provide a throw() method.", node);
1506
1509
  }
1507
1510
  return yield* Effect.failCause(resumed.cause);
1508
1511
  }
1509
1512
  }
1510
1513
  const iterator = yield* self.customIterator(value, node, self.generatorAsync);
1511
1514
  if (!iterator)
1512
- throw new InterpreterRuntimeError("yield* requires a compatible iterable value.", node);
1515
+ throw typeError("yield* requires a compatible iterable value.", node);
1513
1516
  let kind = "next";
1514
1517
  let input = undefined;
1515
1518
  while (true) {
@@ -1518,7 +1521,7 @@ class Frame {
1518
1521
  if (kind === "return")
1519
1522
  return yield* Effect.fail(new GeneratorReturn(input));
1520
1523
  yield* self.closeIterator(iterator, node, self.generatorAsync);
1521
- throw new InterpreterRuntimeError("The delegated iterator does not provide a throw() method.", node);
1524
+ throw typeError("The delegated iterator does not provide a throw() method.", node);
1522
1525
  }
1523
1526
  const called = yield* self.invokeCallable(self.requireIteratorMethod(method, `Iterator ${kind}`, node), iterator.iterator, [input], node);
1524
1527
  const result = self.requireIteratorObject(iterator.asynchronous ? yield* self.awaitValue(called) : called, `Iterator ${kind}() result`, node);
@@ -1559,7 +1562,7 @@ class Frame {
1559
1562
  continue;
1560
1563
  }
1561
1564
  if (property.kind !== "init") {
1562
- throw new InterpreterRuntimeError("Only init object properties are supported.", property);
1565
+ throw typeError("Only init object properties are supported.", property);
1563
1566
  }
1564
1567
  const keyNode = property.key;
1565
1568
  let key;
@@ -1573,7 +1576,7 @@ class Frame {
1573
1576
  key = self.toPropertyKey(keyNode.value, keyNode);
1574
1577
  }
1575
1578
  else {
1576
- throw new InterpreterRuntimeError("Unsupported object property key shape.", keyNode);
1579
+ throw typeError("Unsupported object property key shape.", keyNode);
1577
1580
  }
1578
1581
  const name = key === IteratorSymbol
1579
1582
  ? "[Symbol.iterator]"
@@ -1599,7 +1602,7 @@ class Frame {
1599
1602
  const spread = yield* self.evaluateExpression(element.argument);
1600
1603
  const cursor = yield* self.syncIterator(spread, element);
1601
1604
  if (cursor === undefined)
1602
- throw new InterpreterRuntimeError("Array spread requires a synchronous iterable.", element);
1605
+ throw typeError("Array spread requires a synchronous iterable.", element);
1603
1606
  while (true) {
1604
1607
  const step = yield* cursor.next;
1605
1608
  if (step.done)
@@ -1624,7 +1627,7 @@ class Frame {
1624
1627
  const quasi = quasis[index];
1625
1628
  // acorn only omits `cooked` for invalid escapes in tagged templates, which are unsupported.
1626
1629
  if (typeof quasi.value.cooked !== "string") {
1627
- throw new InterpreterRuntimeError("Invalid template literal quasi.", quasi);
1630
+ throw typeError("Invalid template literal quasi.", quasi);
1628
1631
  }
1629
1632
  output += quasi.value.cooked;
1630
1633
  if (index < expressions.length) {
@@ -1640,7 +1643,7 @@ class Frame {
1640
1643
  }
1641
1644
  applyCompoundAssignment(operator, current, incoming, node) {
1642
1645
  if (!compoundOperators.has(operator)) {
1643
- throw new InterpreterRuntimeError(`Unsupported assignment operator '${operator}'.`, node);
1646
+ throw typeError(`Unsupported assignment operator '${operator}'.`, node);
1644
1647
  }
1645
1648
  return this.applyBinaryOperator(operator.slice(0, -1), current, incoming, node);
1646
1649
  }
@@ -1665,7 +1668,7 @@ class Frame {
1665
1668
  : self.toPropertyKey(yield* self.evaluateExpression(propertyNode), propertyNode);
1666
1669
  if (objectValue instanceof ToolReference) {
1667
1670
  if (typeof key !== "string") {
1668
- throw new InterpreterRuntimeError("Tool paths must use string property names.", propertyNode);
1671
+ throw typeError("Tool paths must use string property names.", propertyNode);
1669
1672
  }
1670
1673
  return new ToolReference([...objectValue.path, key]);
1671
1674
  }
@@ -1686,18 +1689,22 @@ class Frame {
1686
1689
  if (typeof objectValue === "boolean")
1687
1690
  return { target: protos.Boolean, key, receiver: objectValue };
1688
1691
  if (objectValue === null || objectValue === undefined) {
1689
- throw new InterpreterRuntimeError(`Cannot read properties of ${objectValue} (reading '${String(key)}').`, objectNode);
1692
+ throw typeError(`Cannot read properties of ${objectValue} (reading '${String(key)}').`, objectNode);
1690
1693
  }
1691
- throw new InterpreterRuntimeError("Cannot access a property on a non-object value.", objectNode);
1694
+ throw typeError("Cannot access a property on a non-object value.", objectNode);
1692
1695
  });
1693
1696
  }
1694
1697
  readReference(reference, node) {
1695
1698
  // Reject unknown promise properties so a missing await cannot hide.
1696
1699
  if (reference.target instanceof ProgramPromise && !has(reference.target, reference.key)) {
1697
- throw new InterpreterRuntimeError("This value is an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.", node.object, "InvalidDataValue");
1700
+ throw invalidData("This value is an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.", node.object);
1698
1701
  }
1702
+ return this.readProperty(reference.target, reference.key, node, reference.receiver);
1703
+ }
1704
+ // Accessors throw without a location; the member or pattern that read them supplies it.
1705
+ readProperty(target, key, node, receiver = target) {
1699
1706
  try {
1700
- return get(reference.target, reference.key, reference.receiver);
1707
+ return get(target, key, receiver);
1701
1708
  }
1702
1709
  catch (error) {
1703
1710
  throw locate(error, node);
@@ -1720,17 +1727,17 @@ class Frame {
1720
1727
  evaluateDeleteExpression(argument) {
1721
1728
  const target = argument.type === "ChainExpression" ? argument.expression : argument;
1722
1729
  if (target.type !== "MemberExpression") {
1723
- throw new InterpreterRuntimeError("Only data fields may be deleted.", argument);
1730
+ throw typeError("Only data fields may be deleted.", argument);
1724
1731
  }
1725
1732
  return Effect.map(this.getMemberReference(target), (reference) => {
1726
1733
  if (reference === OptionalShortCircuit)
1727
1734
  return true;
1728
1735
  if (reference instanceof ToolReference || "value" in reference || reference.receiver !== reference.target) {
1729
- throw new InterpreterRuntimeError("Only data fields may be deleted.", target, "InvalidDataValue");
1736
+ throw invalidData("Only data fields may be deleted.", target);
1730
1737
  }
1731
1738
  if (remove(reference.target, reference.key))
1732
1739
  return true;
1733
- throw new InterpreterRuntimeError(`Cannot delete property '${String(reference.key)}'.`, target);
1740
+ throw typeError(`Cannot delete property '${String(reference.key)}'.`, target);
1734
1741
  });
1735
1742
  }
1736
1743
  // Resolve side-effecting object and key expressions exactly once.
@@ -1739,10 +1746,10 @@ class Frame {
1739
1746
  return Effect.gen(function* () {
1740
1747
  const reference = yield* self.getMemberReference(node);
1741
1748
  if (reference === OptionalShortCircuit || reference instanceof ToolReference || "value" in reference) {
1742
- throw new InterpreterRuntimeError("Only data fields may be assigned.", node);
1749
+ throw typeError("Only data fields may be assigned.", node);
1743
1750
  }
1744
1751
  if (reference.receiver !== reference.target) {
1745
- throw new InterpreterRuntimeError(`Cannot create property '${String(reference.key)}' on ${typeof reference.receiver} '${String(reference.receiver)}'.`, node);
1752
+ throw typeError(`Cannot create property '${String(reference.key)}' on ${typeof reference.receiver} '${String(reference.receiver)}'.`, node);
1746
1753
  }
1747
1754
  const key = reference.key;
1748
1755
  const { write, next, result } = yield* compute(self.readReference(reference, node));
@@ -1752,9 +1759,9 @@ class Frame {
1752
1759
  });
1753
1760
  }
1754
1761
  assignToReference(target, key, next, node) {
1755
- rejectCircularInsertion(target, next, target instanceof ProgramArray ? "Array assignment result" : "Object assignment result", node);
1756
1762
  const written = (() => {
1757
1763
  try {
1764
+ rejectCircularInsertion(target, next, target instanceof ProgramArray ? "Array assignment result" : "Object assignment result");
1758
1765
  return set(target, key, next);
1759
1766
  }
1760
1767
  catch (error) {
@@ -1765,7 +1772,7 @@ class Frame {
1765
1772
  return;
1766
1773
  if (target instanceof ProgramArray && key === "length")
1767
1774
  throw rangeError("Invalid array length", node);
1768
- throw new InterpreterRuntimeError(`Cannot assign to read only property '${String(key)}'.`, node);
1775
+ throw typeError(`Cannot assign to read only property '${String(key)}'.`, node);
1769
1776
  }
1770
1777
  toPropertyKey(value, node) {
1771
1778
  if (typeof value === "string" || typeof value === "number") {
@@ -1773,6 +1780,6 @@ class Frame {
1773
1780
  }
1774
1781
  if (value === AsyncIteratorSymbol || value === IteratorSymbol)
1775
1782
  return value;
1776
- throw new InterpreterRuntimeError("Property key must be a string or number, or Symbol.asyncIterator/Symbol.iterator.", node);
1783
+ throw typeError("Property key must be a string or number, or Symbol.asyncIterator/Symbol.iterator.", node);
1777
1784
  }
1778
1785
  }
@@ -1,4 +1,4 @@
1
- import { InterpreterRuntimeError, referenceError } from "./model.js";
1
+ import { referenceError, typeError } from "./model.js";
2
2
  export class ScopeStack {
3
3
  scopes;
4
4
  constructor(scopes) {
@@ -7,14 +7,14 @@ export class ScopeStack {
7
7
  reserve(name, mutable, node) {
8
8
  const scope = this.current();
9
9
  if (scope.has(name)) {
10
- throw new InterpreterRuntimeError(`Identifier '${name}' has already been declared.`, node);
10
+ throw typeError(`Identifier '${name}' has already been declared.`, node);
11
11
  }
12
12
  scope.set(name, { mutable, value: undefined, initialized: false });
13
13
  }
14
14
  initialize(name, value, node) {
15
15
  const binding = this.current().get(name);
16
16
  if (!binding || binding.initialized !== false) {
17
- throw new InterpreterRuntimeError(`Identifier '${name}' has not been reserved for initialization.`, node);
17
+ throw typeError(`Identifier '${name}' has not been reserved for initialization.`, node);
18
18
  }
19
19
  binding.value = value;
20
20
  binding.initialized = true;
@@ -22,7 +22,7 @@ export class ScopeStack {
22
22
  declare(name, value, mutable, node) {
23
23
  const scope = this.current();
24
24
  if (scope.has(name)) {
25
- throw new InterpreterRuntimeError(`Identifier '${name}' has already been declared.`, node);
25
+ throw typeError(`Identifier '${name}' has already been declared.`, node);
26
26
  }
27
27
  scope.set(name, { mutable, value, initialized: true });
28
28
  }
@@ -45,7 +45,7 @@ export class ScopeStack {
45
45
  throw referenceError(`Cannot access '${name}' before initialization.`, node);
46
46
  }
47
47
  if (!binding.mutable) {
48
- throw new InterpreterRuntimeError(`Cannot assign to constant '${name}'.`, node);
48
+ throw typeError(`Cannot assign to constant '${name}'.`, node);
49
49
  }
50
50
  binding.value = value;
51
51
  return value;
@@ -63,7 +63,7 @@ export class ScopeStack {
63
63
  current() {
64
64
  const scope = this.scopes[this.scopes.length - 1];
65
65
  if (!scope) {
66
- throw new InterpreterRuntimeError("Interpreter scope stack is empty.");
66
+ throw typeError("Interpreter scope stack is empty.");
67
67
  }
68
68
  return scope;
69
69
  }