@opencode/codemode 0.0.0-dev-20141 → 0.0.0-dev-20143

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.
@@ -4,14 +4,21 @@ import { Callable, type Cursor, type Value } from "./objects.js";
4
4
  /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
5
5
  * return() is a return completion, so a failing close wins over it, as after `break`. */
6
6
  export declare const preserveConsumerError: <A, R>(close: Cursor<R>["close"], effect: Effect.Effect<A, unknown, R>) => Effect.Effect<A, unknown, R>;
7
+ export type Hint = "number" | "string" | "default";
7
8
  /**
8
9
  * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
9
- * default hint as "string", like their `Symbol.toPrimitive`.
10
+ * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
11
+ * references) pass through unchanged so callers reject or describe them in their built-in form.
10
12
  */
11
- export declare const toPrimitive: <R>(ctx: Interpreter<R>, value: Value, hint: "number" | "string" | "default") => Effect.Effect<Value, unknown, R>;
13
+ export declare const toPrimitive: <R>(ctx: Interpreter<R>, value: Value, hint: Hint) => Effect.Effect<Value, unknown, R>;
12
14
  /** Invoke(value, name): calls the method the value would find through its prototype. */
13
15
  export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) => Effect.Effect<Value, unknown, R>;
14
16
  export declare const toPrimitiveString: <R>(ctx: Interpreter<R>, value: Value) => Effect.Effect<string, unknown, R>;
15
17
  export declare const toPrimitiveNumber: <R>(ctx: Interpreter<R>, value: Value) => Effect.Effect<number, unknown, R>;
18
+ /**
19
+ * Runs a synchronous native body on its arguments after ToPrimitive, in order, with one hint for all positions or
20
+ * one per position. Primitive arguments skip the Effect entirely.
21
+ */
22
+ export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) => Value) => Value | Effect.Effect<Value, unknown, R>;
16
23
  export declare const isSupportedCallback: (value: Value) => value is Callable;
17
24
  export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) => Effect.Effect<Value, unknown, R>);
@@ -2,7 +2,7 @@ import { Cause, Effect, Exit } from "effect";
2
2
  import { primitivePrototype } from "./intrinsics.js";
3
3
  import { GeneratorReturn, typeError } from "./model.js";
4
4
  import { Callable, get, Native, DateObj, Obj, coerceToNumber, coerceToString, } from "./objects.js";
5
- import { typeofValue } from "./references.js";
5
+ import { isOpaque, typeofValue } from "./references.js";
6
6
  /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
7
7
  * return() is a return completion, so a failing close wins over it, as after `break`. */
8
8
  export const preserveConsumerError = (close, effect) => Effect.flatMap(Effect.exit(effect), (exit) => {
@@ -17,10 +17,11 @@ export const preserveConsumerError = (close, effect) => Effect.flatMap(Effect.ex
17
17
  });
18
18
  /**
19
19
  * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
20
- * default hint as "string", like their `Symbol.toPrimitive`.
20
+ * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
21
+ * references) pass through unchanged so callers reject or describe them in their built-in form.
21
22
  */
22
23
  export const toPrimitive = (ctx, value, hint) => {
23
- if (!(value instanceof Obj))
24
+ if (!(value instanceof Obj) || isOpaque(value))
24
25
  return Effect.succeed(value);
25
26
  const asString = hint === "string" || (hint === "default" && value instanceof DateObj);
26
27
  const order = asString ? ["toString", "valueOf"] : ["valueOf", "toString"];
@@ -45,6 +46,15 @@ export const invoke = (ctx, value, name, label) => {
45
46
  };
46
47
  export const toPrimitiveString = (ctx, value) => Effect.map(toPrimitive(ctx, value, "string"), coerceToString);
47
48
  export const toPrimitiveNumber = (ctx, value) => Effect.map(toPrimitive(ctx, value, "number"), coerceToNumber);
49
+ /**
50
+ * Runs a synchronous native body on its arguments after ToPrimitive, in order, with one hint for all positions or
51
+ * one per position. Primitive arguments skip the Effect entirely.
52
+ */
53
+ export const withPrimitives = (ctx, hints, values, body) => {
54
+ if (!values.some((value) => value instanceof Obj))
55
+ return body(values);
56
+ return Effect.map(Effect.forEach(values, (value, index) => toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index])), body);
57
+ };
48
58
  // The single acceptance list for callbacks: collections, sort, string replacers,
49
59
  // Array.from mappers, and promise reactions all admit exactly these callables.
50
60
  // Admission means dispatchable, not necessarily invocable: new-requiring
@@ -6,6 +6,7 @@ import { containsRuntimeReference } from "./references.js";
6
6
  import { createErrorValue, isErrorType } from "./intrinsics.js";
7
7
  import { constructor, methods, prototypeFrom, receiver } from "./native.js";
8
8
  import { define, get, has, hidden, Arr, ErrorObj, Obj, coerceToString, } from "./objects.js";
9
+ import { toPrimitiveString } from "./callback.js";
9
10
  import { formatValue } from "../stdlib/console.js";
10
11
  export const normalizeError = (error) => {
11
12
  if (error instanceof PendingThrow) {
@@ -109,15 +110,15 @@ export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.buil
109
110
  return value;
110
111
  };
111
112
  const constructAggregateErrorValue = (ctx, args, proto) => Effect.gen(function* () {
113
+ const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1]);
112
114
  const cursor = yield* ctx.iterate(args[0]);
113
115
  if (cursor === undefined)
114
116
  throw typeError("new AggregateError(...) expects a synchronous iterable of errors.");
115
117
  const errors = [];
116
118
  while (true) {
117
119
  const step = yield* cursor.next;
118
- if (step.done) {
119
- return createAggregateErrorValue(ctx, errors, args[1] === undefined ? "" : coerceToString(args[1]), proto);
120
- }
120
+ if (step.done)
121
+ return createAggregateErrorValue(ctx, errors, message, proto);
121
122
  errors.push(step.value);
122
123
  }
123
124
  });
@@ -129,7 +130,7 @@ export const errorGlobal = (type, ctx) => {
129
130
  const proto = prototypeFrom(newTarget, prototype);
130
131
  const created = type === "AggregateError"
131
132
  ? constructAggregateErrorValue(ctx, args, proto)
132
- : Effect.sync(() => createErrorValue(proto, args[0] === undefined ? undefined : coerceToString(args[0])));
133
+ : Effect.map(args[0] === undefined ? Effect.undefined : toPrimitiveString(ctx, args[0]), (message) => createErrorValue(proto, message));
133
134
  // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
134
135
  const options = args[type === "AggregateError" ? 2 : 1];
135
136
  if (!(options instanceof Obj) || !has(options, "cause"))
@@ -7,13 +7,32 @@ import { locate, materialize } from "./errors.js";
7
7
  import { primitivePrototype } from "./intrinsics.js";
8
8
  import { globals } from "./globals.js";
9
9
  import { assign, Callable, define, frozen, get, hostCursor, IteratorObj, has, hidden, hasPrototype, keys, Native, parseArrayIndex, Arguments, Arr, Fn, GeneratorObj, Obj, PromiseObj, record, remove, set, coerceToNumber, coerceToString, } from "./objects.js";
10
- import { preserveConsumerError } from "./callback.js";
10
+ import { preserveConsumerError, toPrimitive } from "./callback.js";
11
11
  import { Pending, resolvePromise, resolvePromiseValue } from "./promises.js";
12
12
  import { describeValue, isOpaque, rejectCircularInsertion, typeofValue } from "./references.js";
13
13
  import { ScopeStack } from "./scope.js";
14
14
  import { constructRegExp } from "../stdlib/regexp.js";
15
15
  import { enumerableSource } from "../stdlib/object.js";
16
16
  import { compoundOperators } from "../stdlib/value.js";
17
+ /** The binary operators that convert object operands through ToPrimitive before acting on primitives. */
18
+ const primitiveOperators = new Set([
19
+ "+",
20
+ "-",
21
+ "*",
22
+ "/",
23
+ "%",
24
+ "**",
25
+ "<",
26
+ "<=",
27
+ ">",
28
+ ">=",
29
+ "&",
30
+ "|",
31
+ "^",
32
+ "<<",
33
+ ">>",
34
+ ">>>",
35
+ ]);
17
36
  // What a loop does with its body's result: exit with a StatementResult, or undefined to keep iterating.
18
37
  // Unlabelled break ends this loop; a label the loop does not carry propagates outward.
19
38
  const loopExit = (result, labels) => {
@@ -1084,9 +1103,36 @@ class Frame {
1084
1103
  const rhs = yield* self.evaluateExpression(node.right);
1085
1104
  if (operator === "instanceof")
1086
1105
  return instanceofValue(lhs, rhs, node);
1106
+ if (lhs instanceof Obj || rhs instanceof Obj)
1107
+ return yield* self.applyOperator(operator, lhs, rhs, node);
1087
1108
  return self.applyBinaryOperator(operator, lhs, rhs, node);
1088
1109
  });
1089
1110
  }
1111
+ /** ToPrimitive for an operand: data objects run their own methods; opaque values stay for the data gates below. */
1112
+ toPrimitive(value, hint, node) {
1113
+ return this.native(() => toPrimitive(this.ctx, value, hint), node);
1114
+ }
1115
+ // Arithmetic, relational, and bitwise operators convert both operands first, left then right, so a `valueOf`
1116
+ // runs (and throws) in spec order; `+` asks for the default hint and the rest for a number.
1117
+ applyOperator(operator, lhs, rhs, node) {
1118
+ if (!(lhs instanceof Obj || rhs instanceof Obj))
1119
+ return Effect.succeed(this.applyBinaryOperator(operator, lhs, rhs, node));
1120
+ // IsLooselyEqual converts only an object facing a non-nullish primitive; two objects (including tool
1121
+ // references, which are not Obj) compare by identity.
1122
+ const equality = operator === "==" || operator === "!=";
1123
+ const other = lhs instanceof Obj ? rhs : lhs;
1124
+ const converts = primitiveOperators.has(operator) ||
1125
+ (equality && other !== null && other !== undefined && typeof other !== "object");
1126
+ if (!converts)
1127
+ return Effect.succeed(this.applyBinaryOperator(operator, lhs, rhs, node));
1128
+ const hint = operator === "+" || equality ? "default" : "number";
1129
+ const self = this;
1130
+ return Effect.gen(function* () {
1131
+ const l = yield* self.toPrimitive(lhs, hint, node);
1132
+ const r = yield* self.toPrimitive(rhs, hint, node);
1133
+ return self.applyBinaryOperator(operator, l, r, node);
1134
+ });
1135
+ }
1090
1136
  applyBinaryOperator(operator, lhs, rhs, node) {
1091
1137
  if (operator === "===")
1092
1138
  return lhs === rhs;
@@ -1102,72 +1148,62 @@ class Frame {
1102
1148
  if (isOpaque(lhs) || isOpaque(rhs)) {
1103
1149
  throw invalidData("Binary operators require data values.", node);
1104
1150
  }
1105
- // Addition uses the default hint; every other operator asks for a number.
1106
- const hint = operator === "+" ? "default" : "number";
1107
- const coerceOperand = (operand) => (operand instanceof Obj ? operand.toPrimitive(hint) : operand);
1108
- const l = coerceOperand(lhs);
1109
- const r = coerceOperand(rhs);
1151
+ // Object operands were already converted by applyOperator; only primitives reach the arithmetic below.
1110
1152
  switch (operator) {
1111
1153
  case "+": {
1112
- const sum = l + r;
1154
+ const sum = lhs + rhs;
1113
1155
  if (typeof sum === "string")
1114
1156
  checkStringLength(sum.length);
1115
1157
  return sum;
1116
1158
  }
1117
1159
  case "-":
1118
- return l - r;
1160
+ return lhs - rhs;
1119
1161
  case "*":
1120
- return l * r;
1162
+ return lhs * rhs;
1121
1163
  case "/":
1122
- return l / r;
1164
+ return lhs / rhs;
1123
1165
  case "%":
1124
- return l % r;
1166
+ return lhs % rhs;
1125
1167
  case "**":
1126
- return l ** r;
1168
+ return lhs ** rhs;
1127
1169
  case "<":
1128
- return l < r;
1170
+ return lhs < rhs;
1129
1171
  case "<=":
1130
- return l <= r;
1172
+ return lhs <= rhs;
1131
1173
  case ">":
1132
- return l > r;
1174
+ return lhs > rhs;
1133
1175
  case ">=":
1134
- return l >= r;
1176
+ return lhs >= rhs;
1135
1177
  case "&":
1136
- return l & r;
1178
+ return lhs & rhs;
1137
1179
  case "|":
1138
- return l | r;
1180
+ return lhs | rhs;
1139
1181
  case "^":
1140
- return l ^ r;
1182
+ return lhs ^ rhs;
1141
1183
  case "<<":
1142
- return l << r;
1184
+ return lhs << rhs;
1143
1185
  case ">>":
1144
- return l >> r;
1186
+ return lhs >> rhs;
1145
1187
  case ">>>":
1146
- return l >>> r;
1188
+ return lhs >>> rhs;
1147
1189
  case "in":
1148
- if (!(rhs instanceof Obj)) {
1149
- throw typeError("The 'in' operator requires a data object on the right-hand side.", node);
1150
- }
1151
- return has(rhs, coerceOperand(lhs));
1190
+ throw typeError("The 'in' operator requires a data object on the right-hand side.", node);
1152
1191
  default:
1153
1192
  throw typeError(`Unsupported binary operator '${operator}'.`, node);
1154
1193
  }
1155
1194
  }
1156
- // IsLooselyEqual: objects (including functions and tool references) compare by identity, and only a
1157
- // data object facing a non-nullish primitive needs to coerce, so an opaque value is rejected only there.
1195
+ // IsLooselyEqual: objects (including functions and tool references) compare by identity, and a nullish
1196
+ // primitive never equals an object.
1158
1197
  looselyEqual(lhs, rhs, node) {
1159
1198
  const lhsObject = lhs !== null && typeof lhs === "object";
1160
1199
  const rhsObject = rhs !== null && typeof rhs === "object";
1161
1200
  if (lhsObject === rhsObject)
1162
1201
  return lhsObject ? lhs === rhs : lhs == rhs;
1163
- const object = lhsObject ? lhs : rhs;
1164
1202
  const primitive = lhsObject ? rhs : lhs;
1165
1203
  if (primitive === null || primitive === undefined)
1166
1204
  return false;
1167
- if (!(object instanceof Obj) || isOpaque(object)) {
1168
- throw invalidData("Binary operators require data values.", node);
1169
- }
1170
- return object.toPrimitive("default") == primitive;
1205
+ // Data objects were converted by applyOperator, so only an opaque reference facing a primitive gets here.
1206
+ throw invalidData("Binary operators require data values.", node);
1171
1207
  }
1172
1208
  evaluateLogicalExpression(node) {
1173
1209
  const operator = node.operator;
@@ -1190,17 +1226,19 @@ class Frame {
1190
1226
  if (operator === "typeof" && argument.type === "Identifier" && !this.scopes.resolve(argument.name)) {
1191
1227
  return Effect.succeed("undefined");
1192
1228
  }
1193
- return Effect.map(this.evaluateExpression(argument), (value) => {
1229
+ const self = this;
1230
+ return Effect.gen(function* () {
1231
+ const value = yield* self.evaluateExpression(argument);
1194
1232
  if (operator === "typeof")
1195
1233
  return typeofValue(value);
1196
1234
  if (operator === "!")
1197
1235
  return !value;
1198
1236
  if (operator === "void")
1199
1237
  return undefined;
1200
- if (isOpaque(value)) {
1238
+ const operand = yield* self.toPrimitive(value, "number", node);
1239
+ if (isOpaque(operand)) {
1201
1240
  throw invalidData("Unary operators require data values.", node);
1202
1241
  }
1203
- const operand = value instanceof Obj ? value.toPrimitive("number") : value;
1204
1242
  let result;
1205
1243
  switch (operator) {
1206
1244
  case "+":
@@ -1221,11 +1259,16 @@ class Frame {
1221
1259
  evaluateAssignmentExpression(node) {
1222
1260
  const left = node.left;
1223
1261
  const operator = node.operator;
1262
+ // The binary operator a compound assignment applies: `+=` is `+`.
1263
+ const binary = operator.slice(0, -1);
1224
1264
  const self = this;
1225
1265
  return Effect.gen(function* () {
1226
1266
  if (operator === "??=" || operator === "||=" || operator === "&&=") {
1227
1267
  return yield* self.evaluateLogicalAssignment(node, left, operator);
1228
1268
  }
1269
+ if (operator !== "=" && !compoundOperators.has(operator)) {
1270
+ throw typeError(`Unsupported assignment operator '${operator}'.`, node);
1271
+ }
1229
1272
  if (operator === "=" && (left.type === "ObjectPattern" || left.type === "ArrayPattern")) {
1230
1273
  const rightValue = yield* self.evaluateExpression(node.right);
1231
1274
  yield* self.assignPattern(left, rightValue, node);
@@ -1236,17 +1279,23 @@ class Frame {
1236
1279
  if (operator !== "=") {
1237
1280
  const current = self.scopes.get(name, left);
1238
1281
  const rightValue = yield* self.evaluateExpression(node.right);
1239
- return self.scopes.set(name, self.applyCompoundAssignment(operator, current, rightValue, node), left);
1282
+ const next = current instanceof Obj || rightValue instanceof Obj
1283
+ ? yield* self.applyOperator(binary, current, rightValue, node)
1284
+ : self.applyBinaryOperator(binary, current, rightValue, node);
1285
+ return self.scopes.set(name, next, left);
1240
1286
  }
1241
1287
  const rightValue = yield* self.evaluateNamed(node.right, name);
1242
1288
  return self.scopes.set(name, rightValue, left);
1243
1289
  }
1244
1290
  if (left.type === "MemberExpression") {
1245
- return yield* self.modifyMember(left, (current) => Effect.map(self.evaluateExpression(node.right), (rightValue) => {
1291
+ return yield* self.modifyMember(left, (current) => Effect.flatMap(self.evaluateExpression(node.right), (rightValue) => {
1246
1292
  if (operator === "=")
1247
- return { write: true, next: rightValue, result: rightValue };
1248
- const next = self.applyCompoundAssignment(operator, current, rightValue, node);
1249
- return { write: true, next, result: next };
1293
+ return Effect.succeed({ write: true, next: rightValue, result: rightValue });
1294
+ return Effect.map(self.applyOperator(binary, current, rightValue, node), (next) => ({
1295
+ write: true,
1296
+ next,
1297
+ result: next,
1298
+ }));
1250
1299
  }));
1251
1300
  }
1252
1301
  throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
@@ -1284,8 +1333,7 @@ class Frame {
1284
1333
  if (increment === undefined) {
1285
1334
  throw typeError(`Unsupported update operator '${operator}'.`, node);
1286
1335
  }
1287
- // CodeMode numeric coercion, not host Number(): null-prototype data objects would make
1288
- // the host throw during ToPrimitive, and opaque runtime references must reject clearly.
1336
+ // CodeMode numeric coercion, not host Number(), so opaque runtime references reject clearly.
1289
1337
  const operand = (current) => {
1290
1338
  if (isOpaque(current)) {
1291
1339
  throw invalidData(`'${operator}' requires a data value.`, argument);
@@ -1293,20 +1341,24 @@ class Frame {
1293
1341
  return coerceToNumber(current);
1294
1342
  };
1295
1343
  if (argument.type === "Identifier") {
1296
- return Effect.sync(() => {
1297
- const name = argument.name;
1298
- const current = operand(this.scopes.get(name, argument));
1299
- const next = current + increment;
1344
+ const name = argument.name;
1345
+ const current = this.scopes.get(name, argument);
1346
+ const update = (value) => {
1347
+ const before = operand(value);
1348
+ const next = before + increment;
1300
1349
  this.scopes.set(name, next, argument);
1301
- return prefix ? next : current;
1302
- });
1350
+ return prefix ? next : before;
1351
+ };
1352
+ if (!(current instanceof Obj))
1353
+ return Effect.sync(() => update(current));
1354
+ return Effect.map(this.toPrimitive(current, "number", argument), update);
1303
1355
  }
1304
1356
  if (argument.type === "MemberExpression") {
1305
- return this.modifyMember(argument, (current) => {
1306
- const value = operand(current);
1357
+ return this.modifyMember(argument, (current) => Effect.map(this.toPrimitive(current, "number", argument), (primitive) => {
1358
+ const value = operand(primitive);
1307
1359
  const next = value + increment;
1308
- return Effect.succeed({ write: true, next, result: prefix ? next : value });
1309
- });
1360
+ return { write: true, next, result: prefix ? next : value };
1361
+ }));
1310
1362
  }
1311
1363
  throw typeError("Update target must be an Identifier or MemberExpression.", argument);
1312
1364
  }
@@ -1723,7 +1775,7 @@ class Frame {
1723
1775
  checkStringLength(output.length);
1724
1776
  if (index < expressions.length) {
1725
1777
  const raw = yield* self.evaluateExpression(expressions[index]);
1726
- output += coerceToString(raw);
1778
+ output += coerceToString(yield* self.toPrimitive(raw, "string", expressions[index]));
1727
1779
  checkStringLength(output.length);
1728
1780
  }
1729
1781
  }
@@ -1754,12 +1806,6 @@ class Frame {
1754
1806
  evaluateConditionalExpression(node) {
1755
1807
  return Effect.flatMap(this.evaluateExpression(node.test), (test) => this.evaluateExpression(test ? node.consequent : node.alternate));
1756
1808
  }
1757
- applyCompoundAssignment(operator, current, incoming, node) {
1758
- if (!compoundOperators.has(operator)) {
1759
- throw typeError(`Unsupported assignment operator '${operator}'.`, node);
1760
- }
1761
- return this.applyBinaryOperator(operator.slice(0, -1), current, incoming, node);
1762
- }
1763
1809
  getMemberReference(node) {
1764
1810
  const objectNode = node.object;
1765
1811
  const propertyNode = node.property;
@@ -4,7 +4,7 @@ import { checkArrayLength, checkStringLength, MAX_ARRAY_LENGTH } from "../interp
4
4
  import { invalidData, IteratorSymbol, rangeError, typeError } from "../interpreter/model.js";
5
5
  import { define, get, hidden, Arr, GeneratorObj, hostIterator, Obj, PromiseObj, coerceToInteger, coerceToNumber, coerceToString, rejectAddition, } from "../interpreter/objects.js";
6
6
  import { describeValue, rejectCircularInsertion } from "../interpreter/references.js";
7
- import { applyCollectionCallback, invoke, preserveConsumerError } from "../interpreter/callback.js";
7
+ import { applyCollectionCallback, invoke, preserveConsumerError, withPrimitives } from "../interpreter/callback.js";
8
8
  import { compareText } from "../tool-runtime.js";
9
9
  const arrayLikeSource = (source) => {
10
10
  // JS would treat a promise as an empty array-like; that would hide a missing `await`.
@@ -123,19 +123,19 @@ export const arrayGlobal = (ctx) => {
123
123
  "join",
124
124
  1,
125
125
  (thisValue, args) => {
126
- const joined = self(thisValue, "join")
127
- .items.map((item) => coerceToString(item ?? ""))
128
- .join(args[0] === undefined ? "," : coerceToString(args[0]));
129
- checkStringLength(joined.length);
130
- return joined;
126
+ // .map would keep holes, which Effect.forEach would then hand to the body as undefined.
127
+ const parts = Array.from(self(thisValue, "join").items, (item) => item ?? "");
128
+ return withPrimitives(ctx, "string", [args[0] === undefined ? "," : args[0], ...parts], ([separator, ...items]) => {
129
+ const joined = items.map(coerceToString).join(coerceToString(separator));
130
+ checkStringLength(joined.length);
131
+ return joined;
132
+ });
131
133
  },
132
134
  ],
133
135
  [
134
136
  "toString",
135
137
  0,
136
- (thisValue) => self(thisValue, "toString")
137
- .items.map((item) => coerceToString(item ?? ""))
138
- .join(","),
138
+ (thisValue) => withPrimitives(ctx, "string", Array.from(self(thisValue, "toString").items, (item) => item ?? ""), (items) => items.map(coerceToString).join(",")),
139
139
  ],
140
140
  [
141
141
  "includes",
@@ -2,23 +2,27 @@ import { Effect } from "effect";
2
2
  import { constants, methods } from "../interpreter/native.js";
3
3
  import { typeError } from "../interpreter/model.js";
4
4
  import { Obj, coerceToNumber } from "../interpreter/objects.js";
5
- import { preserveConsumerError } from "../interpreter/callback.js";
6
- // Validate only the arguments a method consumes; like JS, extras are ignored
7
- // (so built-ins work as callbacks receiving (element, index, array)).
8
- const unary = (name, op) => [name, 1, (_, args) => op(coerceToNumber(args[0]))];
9
- const binary = (name, op) => [
10
- name,
11
- 2,
12
- (_, args) => op(coerceToNumber(args[0]), coerceToNumber(args[1])),
13
- ];
14
- const variadic = (name, op) => [
15
- name,
16
- 2,
17
- (_, args) => op(...args.map(coerceToNumber)),
18
- ];
5
+ import { preserveConsumerError, withPrimitives } from "../interpreter/callback.js";
19
6
  export const mathGlobal = (ctx) => {
20
7
  const builtins = ctx.builtins;
21
8
  const math = new Obj(builtins.Object);
9
+ // Convert only the arguments a method consumes; like JS, extras are ignored
10
+ // (so built-ins work as callbacks receiving (element, index, array)).
11
+ const unary = (name, op) => [
12
+ name,
13
+ 1,
14
+ (_, args) => withPrimitives(ctx, "number", [args[0]], ([a]) => op(coerceToNumber(a))),
15
+ ];
16
+ const binary = (name, op) => [
17
+ name,
18
+ 2,
19
+ (_, args) => withPrimitives(ctx, "number", [args[0], args[1]], ([a, b]) => op(coerceToNumber(a), coerceToNumber(b))),
20
+ ];
21
+ const variadic = (name, op) => [
22
+ name,
23
+ 2,
24
+ (_, args) => withPrimitives(ctx, "number", args, (values) => op(...values.map(coerceToNumber))),
25
+ ];
22
26
  constants(math, {
23
27
  PI: Math.PI,
24
28
  E: Math.E,
@@ -1,7 +1,7 @@
1
1
  import { constructor, constants, methods } from "../interpreter/native.js";
2
- import { coerceToNumber, coerceToString } from "../interpreter/objects.js";
2
+ import { coerceToNumber } from "../interpreter/objects.js";
3
3
  import { rangeError, typeError } from "../interpreter/model.js";
4
- import { coercion } from "./value.js";
4
+ import { coerce, coercion } from "./value.js";
5
5
  export const numberGlobal = (ctx) => {
6
6
  const builtins = ctx.builtins;
7
7
  const number = constructor(builtins, builtins.Number, {
@@ -24,14 +24,8 @@ export const numberGlobal = (ctx) => {
24
24
  ["isFinite", 1, (_, args) => Number.isFinite(args[0])],
25
25
  ["isNaN", 1, (_, args) => Number.isNaN(args[0])],
26
26
  ["isSafeInteger", 1, (_, args) => Number.isSafeInteger(args[0])],
27
- [
28
- "parseInt",
29
- 2,
30
- (_, args) => {
31
- return parseInt(coerceToString(args[0]), coerceToNumber(args[1]));
32
- },
33
- ],
34
- ["parseFloat", 1, (_, args) => parseFloat(coerceToString(args[0]))],
27
+ ["parseInt", 2, (_, args) => coerce(ctx, "parseInt", args)],
28
+ ["parseFloat", 1, (_, args) => coerce(ctx, "parseFloat", args)],
35
29
  ]);
36
30
  const self = (thisValue, name) => {
37
31
  if (typeof thisValue === "number")
@@ -1,6 +1,7 @@
1
- import { type Native } from "../interpreter/objects.js";
1
+ import { type Native, type Value } from "../interpreter/objects.js";
2
2
  import type { Interpreter } from "../interpreter/interpreter.js";
3
3
  export declare const compoundOperators: Set<string>;
4
4
  export type Coercion = "Number" | "String" | "Boolean" | "parseInt" | "parseFloat" | "isFinite" | "isNaN";
5
+ export declare const coerce: <R>(ctx: Interpreter<R>, name: Coercion, args: Array<Value>) => Value | import("effect/Effect").Effect<Value, unknown, R>;
5
6
  /** A global coercion function such as `Number` or `parseInt`. */
6
7
  export declare const coercion: <R>(ctx: Interpreter<R>, name: Coercion, length?: number) => Native<R>;
@@ -1,7 +1,8 @@
1
1
  import { fn } from "../interpreter/native.js";
2
2
  import { coerceToNumber, coerceToString } from "../interpreter/objects.js";
3
+ import { withPrimitives } from "../interpreter/callback.js";
3
4
  export const compoundOperators = new Set(["+=", "-=", "*=", "/=", "%=", "**=", "&=", "|=", "^=", "<<=", ">>=", ">>>="]);
4
- const coerce = (ctx, name, args) => {
5
+ export const coerce = (ctx, name, args) => {
5
6
  // Native: Number() is 0 and String() is "", unlike their undefined-argument forms; the
6
7
  // other coercers match native through the undefined-argument path below.
7
8
  if (args.length === 0) {
@@ -11,20 +12,22 @@ const coerce = (ctx, name, args) => {
11
12
  return "";
12
13
  }
13
14
  const raw = args[0];
14
- if (name === "Number")
15
- return coerceToNumber(raw);
16
15
  if (name === "Boolean")
17
16
  return Boolean(raw);
18
- if (name === "isFinite")
19
- return Number.isFinite(coerceToNumber(raw));
20
- if (name === "isNaN")
21
- return Number.isNaN(coerceToNumber(raw));
22
17
  if (name === "parseInt") {
23
- return parseInt(coerceToString(raw), coerceToNumber(args[1]));
18
+ return withPrimitives(ctx, ["string", "number"], [raw, args[1]], ([text, radix]) => parseInt(coerceToString(text), coerceToNumber(radix)));
24
19
  }
25
- if (name === "parseFloat")
26
- return parseFloat(coerceToString(raw));
27
- return coerceToString(raw);
20
+ return withPrimitives(ctx, name === "String" || name === "parseFloat" ? "string" : "number", [raw], ([value]) => {
21
+ if (name === "Number")
22
+ return coerceToNumber(value);
23
+ if (name === "isFinite")
24
+ return Number.isFinite(coerceToNumber(value));
25
+ if (name === "isNaN")
26
+ return Number.isNaN(coerceToNumber(value));
27
+ if (name === "parseFloat")
28
+ return parseFloat(coerceToString(value));
29
+ return coerceToString(value);
30
+ });
28
31
  };
29
32
  /** A global coercion function such as `Number` or `parseInt`. */
30
33
  export const coercion = (ctx, name, length = 1) => fn(ctx.builtins, name, length, (_, args) => coerce(ctx, name, args));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/codemode",
4
- "version": "0.0.0-dev-20141",
4
+ "version": "0.0.0-dev-20143",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",