refactor(codemode): export runtime value classes as Values (#48000)

This commit is contained in:
Aiden Cline
2026-09-08 12:11:34 -05:00
committed by GitHub
Unverified
parent e791afdfa3
commit 8b09f6415a
16 changed files with 221 additions and 258 deletions
+6
View File
@@ -91,6 +91,12 @@ runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
The Effect environment is inferred from the supplied tools. `onToolCallStart` observes admitted calls with decoded
input; `onToolCallEnd` observes settled outcomes and duration. Both hooks return Effects and must not fail.
### `Values`
`Values` exports the runtime's non-JSON value classes: `Values.URL`, `Values.URLSearchParams`, `Values.Date`,
`Values.RegExp`, `Values.Map`, `Values.Set`, and `Values.Promise`. The interpreter recognizes these by class; a
program's `new URL(...)` is a `Values.URL` wrapping the host `URL`. `Values.isValue` narrows to the data-like kinds.
### OpenAPI tools
`OpenAPI.fromSpec` converts an OpenAPI 3.x document into one tool per supported operation. Dotted `operationId` values
+1
View File
@@ -2,5 +2,6 @@ export * as CodeMode from "./codemode.js"
export * as Namespace from "./namespace.js"
export * as Tool from "./tool.js"
export * as OpenAPI from "./openapi/index.js"
export { Values } from "./values.js"
export { searchSignature, toolExpression } from "./codemode.js"
export { ToolError, toolError } from "./tool-error.js"
+28 -37
View File
@@ -16,16 +16,7 @@ import {
} from "./model.js"
import { containsOpaqueReference, isRuntimeReference, rejectCircularInsertion, typeofValue } from "./references.js"
import { isBlockedMember, type SafeObject } from "../tool-runtime.js"
import {
CodeModeDate,
CodeModeMap,
CodeModePromise,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
isCodeModeValue,
} from "../values.js"
import { Values } from "../values.js"
import { dateSetterArgumentCount, invokeDateMethod, invokeDateStatic } from "../stdlib/date.js"
import { invokeMathMethod } from "../stdlib/math.js"
import { invokeNumberMethod, invokeNumberStatic } from "../stdlib/number.js"
@@ -43,7 +34,7 @@ export type CallbackRunner<R> = {
args: Array<unknown>,
node: AstNode,
) => Effect.Effect<unknown, unknown, R>
readonly settlePromise: (promise: CodeModePromise) => Effect.Effect<unknown, unknown, never>
readonly settlePromise: (promise: Values.Promise) => Effect.Effect<unknown, unknown, never>
}
// The single acceptance list for callbacks: collections, sort, string replacers,
@@ -100,7 +91,7 @@ export const invokeIntrinsic = <R>(
if (Array.isArray(ref.receiver)) {
return invokeArrayMethod(runner, ref.receiver, ref.name, args, node)
}
if (ref.receiver instanceof CodeModeDate) {
if (ref.receiver instanceof Values.Date) {
const target = ref.receiver
const argumentCount = dateSetterArgumentCount(ref.name)
if (argumentCount === undefined) return Effect.succeed(invokeDateMethod(target, ref.name, [], node))
@@ -113,19 +104,19 @@ export const invokeIntrinsic = <R>(
(values) => invokeDateMethod(target, ref.name, values, node, initialTime),
)
}
if (ref.receiver instanceof CodeModeRegExp) {
if (ref.receiver instanceof Values.RegExp) {
return Effect.succeed(invokeRegExpMethod(ref.receiver, ref.name, args, node))
}
if (ref.receiver instanceof CodeModeMap) {
if (ref.receiver instanceof Values.Map) {
return invokeMapMethod(runner, ref.receiver, ref.name, args, node)
}
if (ref.receiver instanceof CodeModeSet) {
if (ref.receiver instanceof Values.Set) {
return invokeSetMethod(runner, ref.receiver, ref.name, args, node)
}
if (ref.receiver instanceof CodeModeURL) {
if (ref.receiver instanceof Values.URL) {
return Effect.succeed(invokeURLMethod(ref.receiver, ref.name, node))
}
if (ref.receiver instanceof CodeModeURLSearchParams) {
if (ref.receiver instanceof Values.URLSearchParams) {
return invokeURLSearchParamsMethod(runner, ref.receiver, ref.name, args, node)
}
throw new InterpreterRuntimeError(`Method '${ref.name}' is not available.`, node)
@@ -136,7 +127,7 @@ const coerceNumericArgument = <R>(
value: unknown,
node: AstNode,
): Effect.Effect<number, unknown, R> => {
if (value === null || typeof value !== "object" || Array.isArray(value) || isCodeModeValue(value)) {
if (value === null || typeof value !== "object" || Array.isArray(value) || Values.isValue(value)) {
return Effect.succeed(coerceToNumber(value))
}
const object = value as Record<string, unknown>
@@ -192,7 +183,7 @@ const invokeStringMethod = (value: string, name: string, args: Array<unknown>, n
const optNum = (index: number): number | undefined => (args[index] === undefined ? undefined : num(index))
const optStr = (index: number): string | undefined => (args[index] === undefined ? undefined : str(index))
const rejectRegex = (): void => {
if (args[0] instanceof CodeModeRegExp) {
if (args[0] instanceof Values.RegExp) {
throw new InterpreterRuntimeError(
`String.${name} cannot take a regular expression; use regex.test(string) or String.search instead.`,
node,
@@ -241,7 +232,7 @@ const invokeStringMethod = (value: string, name: string, args: Array<unknown>, n
result = requestedLimit !== undefined && requestedLimit >>> 0 === 0 ? [] : [value]
break
}
if (args[0] instanceof CodeModeRegExp) {
if (args[0] instanceof Values.RegExp) {
result = value.split(args[0].regex, optNum(1))
break
}
@@ -272,7 +263,7 @@ const invokeStringMethod = (value: string, name: string, args: Array<unknown>, n
break
case "replace":
case "replaceAll": {
if (args[0] instanceof CodeModeRegExp) {
if (args[0] instanceof Values.RegExp) {
const pattern = args[0].regex
const replacement = str(1)
if (name === "replaceAll" && !pattern.global) {
@@ -368,7 +359,7 @@ const invokeArrayStatic = (name: string, args: Array<unknown>, node: AstNode): u
}
const arrayLikeSource = (source: unknown, node: AstNode): { readonly length: number; readonly source: object } => {
if (source instanceof CodeModePromise) {
if (source instanceof Values.Promise) {
throw new InterpreterRuntimeError(
"Array.from received an un-awaited Promise; await it before creating the array.",
node,
@@ -445,7 +436,7 @@ export const invokeGroupBy = <R>(
throw new InterpreterRuntimeError(`${namespace}.groupBy expects an iterable collection.`, node).as("TypeError")
}
if (namespace === "Map") {
const result = new CodeModeMap()
const result = new Values.Map()
let index = 0
while (true) {
const step = yield* cursor.next
@@ -488,10 +479,10 @@ const coerceGroupByPropertyKey = <R>(
value: unknown,
node: AstNode,
): Effect.Effect<string, unknown, R> => {
if (value === null || typeof value !== "object" || Array.isArray(value) || isCodeModeValue(value)) {
if (value === null || typeof value !== "object" || Array.isArray(value) || Values.isValue(value)) {
return Effect.succeed(coerceToString(value))
}
if (value instanceof CodeModePromise) return Effect.succeed("[object Promise]")
if (value instanceof Values.Promise) return Effect.succeed("[object Promise]")
if (isRuntimeReference(value)) {
throw new InterpreterRuntimeError("Object.groupBy callback must return a data value.", node, "InvalidDataValue")
}
@@ -543,7 +534,7 @@ const invokeStringReplacer = <R>(
}
const pattern = args[0]
if (pattern instanceof CodeModeRegExp) {
if (pattern instanceof Values.RegExp) {
if (name === "replaceAll" && !pattern.regex.global) {
throw new InterpreterRuntimeError(
`String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.regex.source}/${pattern.regex.flags}g, or use String.replace to replace only the first match.`,
@@ -566,7 +557,7 @@ const invokeStringReplacer = <R>(
// Error values are branded plain objects; boundedData would strip the brand before coercion.
output.push(
value.slice(end, match.offset),
replacement instanceof CodeModePromise
replacement instanceof Values.Promise
? "[object Promise]"
: errorBrandName(replacement)
? coerceToString(replacement)
@@ -599,7 +590,7 @@ export const applyCollectionCallback = <R>(
const invokeMapMethod = <R>(
runner: CallbackRunner<R>,
target: CodeModeMap,
target: Values.Map,
name: string,
args: Array<unknown>,
node: AstNode,
@@ -641,7 +632,7 @@ const invokeMapMethod = <R>(
const invokeSetMethod = <R>(
runner: CallbackRunner<R>,
target: CodeModeSet,
target: Values.Set,
name: string,
args: Array<unknown>,
node: AstNode,
@@ -688,7 +679,7 @@ const invokeSetMethod = <R>(
const invokeSetOperation = <R>(
runner: CallbackRunner<R>,
target: CodeModeSet,
target: Values.Set,
name: string,
source: unknown,
node: AstNode,
@@ -701,7 +692,7 @@ const invokeSetOperation = <R>(
return result
}
if (name === "intersection") {
const result = new CodeModeSet()
const result = new Values.Set()
if (target.set.size <= other.size) {
for (const item of target.set.values()) {
if (yield* other.has(item)) result.set.add(item)
@@ -758,28 +749,28 @@ const invokeSetOperation = <R>(
return true
})
const copySet = (source: CodeModeSet): CodeModeSet => {
const result = new CodeModeSet()
const copySet = (source: Values.Set): Values.Set => {
const result = new Values.Set()
for (const item of source.set.values()) result.set.add(item)
return result
}
const loadSetRecord = <R>(runner: CallbackRunner<R>, source: unknown, name: string, node: AstNode) => {
if (source instanceof CodeModeSet) {
if (source instanceof Values.Set) {
return Effect.succeed({
size: source.set.size,
has: (item: unknown) => Effect.succeed(source.set.has(item)),
keys: () => Effect.succeed(source.set.values()),
})
}
if (source instanceof CodeModeMap) {
if (source instanceof Values.Map) {
return Effect.succeed({
size: source.map.size,
has: (item: unknown) => Effect.succeed(source.map.has(item)),
keys: () => Effect.succeed(source.map.keys()),
})
}
if (source === null || typeof source !== "object" || isCodeModeValue(source)) {
if (source === null || typeof source !== "object" || Values.isValue(source)) {
throw new InterpreterRuntimeError(`Set.${name} expects a Set-like object.`, node).as("TypeError")
}
const object = source as Record<string, unknown>
@@ -809,7 +800,7 @@ const loadSetRecord = <R>(runner: CallbackRunner<R>, source: unknown, name: stri
const invokeURLSearchParamsMethod = <R>(
runner: CallbackRunner<R>,
target: CodeModeURLSearchParams,
target: Values.URLSearchParams,
name: string,
args: Array<unknown>,
node: AstNode,
+3 -3
View File
@@ -1,6 +1,6 @@
import type { Effect } from "effect"
import type { SafeObject } from "../tool-runtime.js"
import type { CodeModePromise, CodeModeRegExp, CodeModeURL } from "../values.js"
import type { Values } from "../values.js"
export type SourcePosition = {
line: number
@@ -36,7 +36,7 @@ export type StatementResult =
| { kind: "continue"; label?: string }
export type MemberReference = {
target: SafeObject | Array<unknown> | CodeModeRegExp | CodeModeURL
target: SafeObject | Array<unknown> | Values.RegExp | Values.URL
key: PropertyKey
}
@@ -99,7 +99,7 @@ export type PromiseInstanceMethodName = "then" | "catch" | "finally"
export class PromiseInstanceMethodReference {
constructor(
readonly promise: CodeModePromise,
readonly promise: Values.Promise,
readonly name: PromiseInstanceMethodName,
) {}
}
+23 -23
View File
@@ -14,25 +14,25 @@ import { caughtErrorValue, normalizeError } from "./errors.js"
import { applyCollectionCallback, isSupportedCallback, type CallbackRunner, type SupportedCallback } from "./methods.js"
import { typeofValue } from "./references.js"
import { createAggregateErrorValue } from "../stdlib/value.js"
import { CodeModePromise } from "../values.js"
import { Values } from "../values.js"
import type { SyncIteratorRunner } from "./iterator.js"
// Observation only controls rejection reporting; program completion interrupts all promise work.
export class PromiseRuntime<R> {
private readonly active = new Set<CodeModePromise>()
private readonly ids = new WeakMap<CodeModePromise, number>()
private readonly observed = new WeakSet<CodeModePromise>()
private readonly active = new Set<Values.Promise>()
private readonly ids = new WeakMap<Values.Promise, number>()
private readonly observed = new WeakSet<Values.Promise>()
private readonly failures = new Map<number, Diagnostic>()
private nextID = 0
constructor(private readonly scope: Scope.Scope) {}
create(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<CodeModePromise, never, R> {
create(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<Values.Promise, never, R> {
return Effect.suspend(() => {
// Allocate before forking so reruns get distinct IDs and diagnostics retain creation order.
const id = this.nextID++
return Effect.map(Effect.forkIn(effect, this.scope, { startImmediately: true }), (fiber) => {
const promise = new CodeModePromise(fiber)
const promise = new Values.Promise(fiber)
this.active.add(promise)
this.ids.set(promise, id)
fiber.addObserver((exit) => {
@@ -53,14 +53,14 @@ export class PromiseRuntime<R> {
}
// Observation must be recorded when responsibility transfers, before the consumer fiber runs.
markObserved(promise: CodeModePromise): void {
markObserved(promise: Values.Promise): void {
this.observed.add(promise)
const id = this.ids.get(promise)
this.ids.delete(promise)
if (id !== undefined) this.failures.delete(id)
}
await(promise: CodeModePromise): Effect.Effect<Exit.Exit<unknown, unknown>> {
await(promise: Values.Promise): Effect.Effect<Exit.Exit<unknown, unknown>> {
return Fiber.await(promise.fiber)
}
@@ -91,10 +91,10 @@ export const resolvePromiseValue = <R>(
runner: CallbackRunner<R>,
value: unknown,
node: AstNode,
own?: { promise?: CodeModePromise },
own?: { promise?: Values.Promise },
): Effect.Effect<unknown, unknown, R> => {
if (own?.promise !== undefined && value === own.promise) return Effect.fail(selfResolutionError(node))
if (value instanceof CodeModePromise) return runner.settlePromise(value)
if (value instanceof Values.Promise) return runner.settlePromise(value)
if (value === null || typeof value !== "object" || !Object.hasOwn(value, "then")) return Effect.succeed(value)
const then = (value as SafeObject).then
if (typeofValue(then) !== "function") return Effect.succeed(value)
@@ -123,9 +123,9 @@ export const resolvePromise = <R>(
promises: PromiseRuntime<R>,
value: unknown,
node: AstNode,
): Effect.Effect<CodeModePromise, never, R> => {
if (value instanceof CodeModePromise) return Effect.succeed(value)
const box: { promise?: CodeModePromise } = {}
): Effect.Effect<Values.Promise, never, R> => {
if (value instanceof Values.Promise) return Effect.succeed(value)
const box: { promise?: Values.Promise } = {}
return Effect.map(promises.create(resolvePromiseValue(runner, value, node, box)), (promise) => {
box.promise = promise
return promise
@@ -155,7 +155,7 @@ export const invokePromiseMethod = <R>(
node,
).as("TypeError")
}
const items: Array<CodeModePromise> = []
const items: Array<Values.Promise> = []
while (true) {
const step = yield* cursor.next
if (step.done) break
@@ -227,7 +227,7 @@ export const invokePromiseInstanceMethod = <R>(
ref: PromiseInstanceMethodReference,
args: Array<unknown>,
node: AstNode,
): Effect.Effect<CodeModePromise, never, R> => {
): Effect.Effect<Values.Promise, never, R> => {
const method = `Promise.prototype.${ref.name}`
promises.markObserved(ref.promise)
if (ref.name === "finally") {
@@ -243,7 +243,7 @@ export const constructPromise = <R>(
promises: PromiseRuntime<R>,
executor: unknown,
node: AstNode,
): Effect.Effect<CodeModePromise, unknown, R> => {
): Effect.Effect<Values.Promise, unknown, R> => {
if (!(executor instanceof CodeModeFunction)) {
throw new InterpreterRuntimeError(
"new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).",
@@ -252,7 +252,7 @@ export const constructPromise = <R>(
}
return Effect.gen(function* () {
const deferred = Deferred.makeUnsafe<unknown, unknown>()
const box: { promise?: CodeModePromise } = {}
const box: { promise?: Values.Promise } = {}
const promise = yield* promises.create(
Effect.flatMap(Deferred.await(deferred), (value) => resolvePromiseValue(runner, value, node, box)),
)
@@ -294,7 +294,7 @@ const reactionHandler = (value: unknown, method: string, node: AstNode): Support
// Teardown bypasses handlers; settled reactions yield once so handlers never run inline.
const reactionExit = <R>(
promises: PromiseRuntime<R>,
source: CodeModePromise,
source: Values.Promise,
): Effect.Effect<Exit.Exit<unknown, unknown>, unknown, R> =>
Effect.gen(function* () {
const exit = yield* promises.await(source)
@@ -306,13 +306,13 @@ const reactionExit = <R>(
const chainReaction = <R>(
runner: CallbackRunner<R>,
promises: PromiseRuntime<R>,
source: CodeModePromise,
source: Values.Promise,
onFulfilled: SupportedCallback | undefined,
onRejected: SupportedCallback | undefined,
method: string,
node: AstNode,
): Effect.Effect<CodeModePromise, never, R> => {
const box: { promise?: CodeModePromise } = {}
): Effect.Effect<Values.Promise, never, R> => {
const box: { promise?: Values.Promise } = {}
const body = Effect.gen(function* () {
const exit = yield* reactionExit(promises, source)
const handler = Exit.isSuccess(exit) ? onFulfilled : onRejected
@@ -330,11 +330,11 @@ const chainReaction = <R>(
const chainFinally = <R>(
runner: CallbackRunner<R>,
promises: PromiseRuntime<R>,
source: CodeModePromise,
source: Values.Promise,
cleanup: SupportedCallback | undefined,
method: string,
node: AstNode,
): Effect.Effect<CodeModePromise, never, R> =>
): Effect.Effect<Values.Promise, never, R> =>
promises.create(
Effect.gen(function* () {
const exit = yield* reactionExit(promises, source)
@@ -21,7 +21,7 @@ import {
UriFunction,
} from "./model.js"
import { ToolReference } from "../tool-runtime.js"
import { isCodeModeValue, CodeModePromise } from "../values.js"
import { Values } from "../values.js"
export const isRuntimeReference = (value: unknown): boolean =>
value instanceof CodeModeFunction ||
@@ -35,14 +35,14 @@ export const isRuntimeReference = (value: unknown): boolean =>
value instanceof PromiseNamespace ||
value instanceof PromiseMethodReference ||
value instanceof PromiseInstanceMethodReference ||
value instanceof CodeModePromise ||
value instanceof Values.Promise ||
value instanceof CoercionFunction ||
value instanceof UriFunction ||
value instanceof SearchFunction ||
value instanceof PromiseCapabilityFunction ||
value instanceof ErrorConstructorReference ||
value instanceof SymbolNamespace ||
isCodeModeValue(value)
Values.isValue(value)
function* childValues(value: object): Generator {
for (const key of Reflect.ownKeys(value)) {
@@ -81,7 +81,7 @@ export const containsOpaqueReference = (value: unknown): boolean => {
continue
}
const current = next.value
if (isCodeModeValue(current)) continue
if (Values.isValue(current)) continue
if (isRuntimeReference(current)) return true
if (current === null || typeof current !== "object" || seen.has(current)) continue
seen.add(current)
+61 -70
View File
@@ -98,16 +98,7 @@ import {
invokeCoercion,
valueConstructors,
} from "../stdlib/value.js"
import {
isCodeModeValue,
CodeModeDate,
CodeModeMap,
CodeModePromise,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
} from "../values.js"
import { Values } from "../values.js"
const globalStaticMembers: Partial<Record<GlobalNamespaceName, Set<string>>> = {
Object: objectStatics,
@@ -153,24 +144,24 @@ const instanceofValue = (lhs: unknown, rhs: unknown, node: AstNode): boolean =>
if (rhs instanceof GlobalNamespace) {
switch (rhs.name) {
case "Date":
return lhs instanceof CodeModeDate
return lhs instanceof Values.Date
case "RegExp":
return lhs instanceof CodeModeRegExp
return lhs instanceof Values.RegExp
case "Map":
return lhs instanceof CodeModeMap
return lhs instanceof Values.Map
case "Set":
return lhs instanceof CodeModeSet
return lhs instanceof Values.Set
case "URL":
return lhs instanceof CodeModeURL
return lhs instanceof Values.URL
case "URLSearchParams":
return lhs instanceof CodeModeURLSearchParams
return lhs instanceof Values.URLSearchParams
case "Array":
return Array.isArray(lhs)
case "Object":
return lhs !== null && (typeof lhs === "object" || typeofValue(lhs) === "function")
}
}
if (rhs instanceof PromiseNamespace) return lhs instanceof CodeModePromise
if (rhs instanceof PromiseNamespace) return lhs instanceof Values.Promise
if (rhs instanceof CoercionFunction && (rhs.name === "Number" || rhs.name === "String" || rhs.name === "Boolean")) {
return false
}
@@ -371,16 +362,16 @@ export class Interpreter<R> {
private createToolCallPromise(
path: ReadonlyArray<string>,
args: Array<unknown>,
): Effect.Effect<CodeModePromise, never, R> {
): Effect.Effect<Values.Promise, never, R> {
return this.createPromise(Effect.suspend(() => this.executeTool(path, args)))
}
private createPromise(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<CodeModePromise, never, R> {
private createPromise(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<Values.Promise, never, R> {
return this.promises.create(effect)
}
// Fiber exits make settlement idempotent; yielding prevents inline continuation.
private settlePromise(promise: CodeModePromise): Effect.Effect<unknown, unknown, never> {
private settlePromise(promise: Values.Promise): Effect.Effect<unknown, unknown, never> {
const promises = this.promises
return Effect.suspend(() => {
promises.markObserved(promise)
@@ -812,11 +803,11 @@ export class Interpreter<R> {
? value[Symbol.iterator]()
: typeof value === "string"
? value[Symbol.iterator]()
: value instanceof CodeModeMap
: value instanceof Values.Map
? value.map.entries()
: value instanceof CodeModeSet
: value instanceof Values.Set
? value.set.values()
: value instanceof CodeModeURLSearchParams
: value instanceof Values.URLSearchParams
? value.params.entries()
: undefined
if (iterator !== undefined) {
@@ -1478,19 +1469,19 @@ export class Interpreter<R> {
)
}
private constructDate(args: Array<unknown>, node: AstNode): Effect.Effect<CodeModeDate, unknown, R> {
if (args.length === 0) return Effect.succeed(new CodeModeDate(Date.now()))
private constructDate(args: Array<unknown>, node: AstNode): Effect.Effect<Values.Date, unknown, R> {
if (args.length === 0) return Effect.succeed(new Values.Date(Date.now()))
if (args.length === 1) {
const arg = args[0]
if (arg instanceof CodeModeDate) return Effect.succeed(new CodeModeDate(arg.time))
if (arg instanceof Values.Date) return Effect.succeed(new Values.Date(arg.time))
return Effect.map(this.toDatePrimitive(arg, node), (value) =>
typeof value === "string"
? new CodeModeDate(Date.parse(value))
: new CodeModeDate(new Date(coerceToNumber(value)).getTime()),
? new Values.Date(Date.parse(value))
: new Values.Date(new Date(coerceToNumber(value)).getTime()),
)
}
const parts = args.map((arg) => coerceToNumber(arg))
return Effect.succeed(new CodeModeDate(new Date(...(parts as [number, number])).getTime()))
return Effect.succeed(new Values.Date(new Date(...(parts as [number, number])).getTime()))
}
private toDatePrimitive(value: unknown, node: AstNode): Effect.Effect<unknown, unknown, R> {
@@ -1511,10 +1502,10 @@ export class Interpreter<R> {
})
}
private constructRegExp(args: Array<unknown>, node: AstNode): CodeModeRegExp {
private constructRegExp(args: Array<unknown>, node: AstNode): Values.RegExp {
const first = args[0]
const pattern =
first instanceof CodeModeRegExp ? first.regex.source : first === undefined ? "" : coerceToString(first)
first instanceof Values.RegExp ? first.regex.source : first === undefined ? "" : coerceToString(first)
const flagsArg = args[1]
if (flagsArg !== undefined && typeof flagsArg !== "string") {
throw new InterpreterRuntimeError(
@@ -1522,9 +1513,9 @@ export class Interpreter<R> {
node,
).as("SyntaxError")
}
const flags = flagsArg ?? (first instanceof CodeModeRegExp ? first.regex.flags : "")
const flags = flagsArg ?? (first instanceof Values.RegExp ? first.regex.flags : "")
try {
return new CodeModeRegExp(pattern, flags)
return new Values.RegExp(pattern, flags)
} catch (error) {
const reason = regexFailureReason(error)
throw new InterpreterRuntimeError(
@@ -1536,8 +1527,8 @@ export class Interpreter<R> {
}
}
private constructMap(init: unknown, node: AstNode): Effect.Effect<CodeModeMap, unknown, R> {
const target = new CodeModeMap()
private constructMap(init: unknown, node: AstNode): Effect.Effect<Values.Map, unknown, R> {
const target = new Values.Map()
if (init === undefined || init === null) return Effect.succeed(target)
const self = this
return Effect.gen(function* () {
@@ -1566,8 +1557,8 @@ export class Interpreter<R> {
})
}
private constructSet(init: unknown, node: AstNode): Effect.Effect<CodeModeSet, unknown, R> {
const target = new CodeModeSet()
private constructSet(init: unknown, node: AstNode): Effect.Effect<Values.Set, unknown, R> {
const target = new Values.Set()
if (init === undefined || init === null) return Effect.succeed(target)
const self = this
return Effect.gen(function* () {
@@ -1585,7 +1576,7 @@ export class Interpreter<R> {
})
}
private constructURL(args: Array<unknown>, node: AstNode): CodeModeURL {
private constructURL(args: Array<unknown>, node: AstNode): Values.URL {
if (args.length === 0) {
throw new InterpreterRuntimeError("new URL(...) requires a URL string and an optional base URL.", node).as(
"TypeError",
@@ -1594,7 +1585,7 @@ export class Interpreter<R> {
const input = urlArgument(args[0], "new URL input")
const base = args[1] === undefined ? undefined : urlArgument(args[1], "new URL base")
try {
return new CodeModeURL(new URL(input, base))
return new Values.URL(new URL(input, base))
} catch {
throw new InterpreterRuntimeError(
`new URL(...) received an invalid URL${base === undefined ? "" : " or base URL"}.`,
@@ -1603,14 +1594,14 @@ export class Interpreter<R> {
}
}
private constructURLSearchParams(init: unknown, node: AstNode): Effect.Effect<CodeModeURLSearchParams, unknown, R> {
if (init === undefined) return Effect.succeed(new CodeModeURLSearchParams(new URLSearchParams()))
if (init instanceof CodeModeURLSearchParams) {
return Effect.succeed(new CodeModeURLSearchParams(new URLSearchParams(init.params)))
private constructURLSearchParams(init: unknown, node: AstNode): Effect.Effect<Values.URLSearchParams, unknown, R> {
if (init === undefined) return Effect.succeed(new Values.URLSearchParams(new URLSearchParams()))
if (init instanceof Values.URLSearchParams) {
return Effect.succeed(new Values.URLSearchParams(new URLSearchParams(init.params)))
}
if (typeof init === "string") return Effect.succeed(new CodeModeURLSearchParams(new URLSearchParams(init)))
if (typeof init === "string") return Effect.succeed(new Values.URLSearchParams(new URLSearchParams(init)))
if (init === null || typeof init === "number" || typeof init === "boolean") {
return Effect.succeed(new CodeModeURLSearchParams(new URLSearchParams(coerceToString(init))))
return Effect.succeed(new Values.URLSearchParams(new URLSearchParams(coerceToString(init))))
}
const self = this
return Effect.gen(function* () {
@@ -1626,7 +1617,7 @@ export class Interpreter<R> {
node,
).as("TypeError")
}
return new CodeModeURLSearchParams(
return new Values.URLSearchParams(
new URLSearchParams(entries.map((entry): [string, string] => [entry[0] ?? "", entry[1] ?? ""])),
)
}
@@ -1639,7 +1630,7 @@ export class Interpreter<R> {
node,
).as("TypeError")
}
if (isCodeModeValue(init)) return new CodeModeURLSearchParams(new URLSearchParams())
if (Values.isValue(init)) return new Values.URLSearchParams(new URLSearchParams())
const data = boundedData(init, "new URLSearchParams input")
if (data === null || typeof data !== "object") {
throw new InterpreterRuntimeError(
@@ -1647,7 +1638,7 @@ export class Interpreter<R> {
node,
).as("TypeError")
}
return new CodeModeURLSearchParams(
return new Values.URLSearchParams(
new URLSearchParams(
Object.fromEntries(Object.entries(data).map(([key, value]) => [key, coerceToString(value)])),
),
@@ -1698,7 +1689,7 @@ export class Interpreter<R> {
// Null-prototype data needs explicit primitive coercion; identity and `in` retain raw objects.
// Dates use their default string hint for addition and loose equality, and epoch time elsewhere.
const coerceOperand = (operand: unknown): unknown => {
if (operand instanceof CodeModeDate) {
if (operand instanceof Values.Date) {
return operator === "+" || operator === "==" || operator === "!=" ? coerceToString(operand) : operand.time
}
return operand !== null && typeof operand === "object" ? coerceToString(operand) : operand
@@ -1783,7 +1774,7 @@ export class Interpreter<R> {
throw new InterpreterRuntimeError("Unary operators require data values.", node, "InvalidDataValue")
}
const operand =
value instanceof CodeModeDate
value instanceof Values.Date
? value.time
: value !== null && typeof value === "object"
? coerceToString(value)
@@ -2110,7 +2101,7 @@ export class Interpreter<R> {
if (fn.generator) return Effect.succeed(this.createGenerator(invocation, run, fn.async))
if (!fn.async) return run
// The initial yield assigns the promise before the body can self-resolve.
const box: { promise?: CodeModePromise } = {}
const box: { promise?: Values.Promise } = {}
return Effect.map(
this.createPromise(Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runner, value, fn.body, box))),
(promise) => {
@@ -2281,9 +2272,9 @@ export class Interpreter<R> {
if (
Array.isArray(value) ||
typeof value === "string" ||
value instanceof CodeModeMap ||
value instanceof CodeModeSet ||
value instanceof CodeModeURLSearchParams
value instanceof Values.Map ||
value instanceof Values.Set ||
value instanceof Values.URLSearchParams
) {
const cursor = yield* self.syncIterator(value, node)
if (!cursor) throw new InterpreterRuntimeError("Built-in iterator is unavailable.", node)
@@ -2374,7 +2365,7 @@ export class Interpreter<R> {
if (property.type === "SpreadElement") {
const spread = yield* self.evaluateExpression(getNode(property, "argument"))
if (spread === null || spread === undefined || isCodeModeValue(spread)) continue
if (spread === null || spread === undefined || Values.isValue(spread)) continue
if (typeof spread !== "object" || Array.isArray(spread) || isRuntimeReference(spread)) {
throw new InterpreterRuntimeError("Object spread requires a data object.", property, "InvalidDataValue")
}
@@ -2598,11 +2589,11 @@ export class Interpreter<R> {
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeDate) {
if (objectValue instanceof Values.Date) {
if (typeof key === "string" && dateMethods.has(key)) return new IntrinsicReference(objectValue, key)
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeRegExp) {
if (objectValue instanceof Values.RegExp) {
if (key === "lastIndex") return { target: objectValue, key }
if (typeof key === "string" && regexpProperties.has(key)) {
return new ComputedValue((objectValue.regex as unknown as Record<string, unknown>)[key])
@@ -2610,17 +2601,17 @@ export class Interpreter<R> {
if (typeof key === "string" && regexpMethods.has(key)) return new IntrinsicReference(objectValue, key)
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeMap) {
if (objectValue instanceof Values.Map) {
if (key === "size") return new ComputedValue(objectValue.map.size)
if (typeof key === "string" && mapMethods.has(key)) return new IntrinsicReference(objectValue, key)
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeSet) {
if (objectValue instanceof Values.Set) {
if (key === "size") return new ComputedValue(objectValue.set.size)
if (typeof key === "string" && setMethods.has(key)) return new IntrinsicReference(objectValue, key)
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeURL) {
if (objectValue instanceof Values.URL) {
if (key === "searchParams") {
return new ComputedValue(objectValue.searchParams)
}
@@ -2628,7 +2619,7 @@ export class Interpreter<R> {
if (typeof key === "string" && urlProperties.has(key)) return { target: objectValue, key }
return new ComputedValue(undefined)
}
if (objectValue instanceof CodeModeURLSearchParams) {
if (objectValue instanceof Values.URLSearchParams) {
if (key === "size") return new ComputedValue(objectValue.params.size)
if (typeof key === "string" && urlSearchParamsMethods.has(key)) {
return new IntrinsicReference(objectValue, key)
@@ -2637,7 +2628,7 @@ export class Interpreter<R> {
}
// Reject unknown promise properties so a missing await cannot hide.
if (objectValue instanceof CodeModePromise) {
if (objectValue instanceof Values.Promise) {
if (key === "then" || key === "catch" || key === "finally") {
return new PromiseInstanceMethodReference(objectValue, key)
}
@@ -2703,8 +2694,8 @@ export class Interpreter<R> {
if (typeof reference.key === "string") return new IntrinsicReference(reference.target, reference.key)
return Reflect.get(reference.target, reference.key)
}
if (reference.target instanceof CodeModeRegExp) return reference.target.lastIndex
if (reference.target instanceof CodeModeURL) {
if (reference.target instanceof Values.RegExp) return reference.target.lastIndex
if (reference.target instanceof Values.URL) {
return Reflect.get(reference.target.url, reference.key)
}
return Reflect.get(reference.target, reference.key)
@@ -2726,11 +2717,11 @@ export class Interpreter<R> {
reference instanceof ComputedValue ||
reference === undefined ||
isOpaqueMemberReference(reference) ||
reference.target instanceof CodeModeURL
reference.target instanceof Values.URL
) {
throw new InterpreterRuntimeError("Only data fields may be deleted.", target, "InvalidDataValue")
}
if (reference.target instanceof CodeModeRegExp) {
if (reference.target instanceof Values.RegExp) {
return Reflect.deleteProperty(reference.target.regex, reference.key)
}
return Reflect.deleteProperty(reference.target, reference.key)
@@ -2767,10 +2758,10 @@ export class Interpreter<R> {
}
private readReferenceValue(reference: MemberReference, key: PropertyKey): unknown {
if (reference.target instanceof CodeModeURL) {
if (reference.target instanceof Values.URL) {
return Reflect.get(reference.target.url, key)
}
if (reference.target instanceof CodeModeRegExp) return reference.target.lastIndex
if (reference.target instanceof Values.RegExp) return reference.target.lastIndex
return Reflect.get(reference.target, key)
}
@@ -2788,7 +2779,7 @@ export class Interpreter<R> {
target[key] = next
return
}
if (reference.target instanceof CodeModeURL) {
if (reference.target instanceof Values.URL) {
const property = key as string
if (!urlWritableProperties.has(property)) {
throw new InterpreterRuntimeError(`URL.${property} is read-only.`, node).as("TypeError")
@@ -2802,7 +2793,7 @@ export class Interpreter<R> {
throw new InterpreterRuntimeError(`URL.${property} received an invalid value.`, node).as("TypeError")
}
}
if (reference.target instanceof CodeModeRegExp) {
if (reference.target instanceof Values.RegExp) {
reference.target.lastIndex = next
return
}
+10 -19
View File
@@ -1,15 +1,6 @@
import { containsOpaqueReference, containsRuntimeReference, isRuntimeReference } from "../interpreter/references.js"
import { copyIn, copyOut } from "../tool-runtime.js"
import {
isCodeModeValue,
CodeModeDate,
CodeModeMap,
CodeModePromise,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
} from "../values.js"
import { Values } from "../values.js"
import { boundedData, coerceToString } from "./value.js"
export const consoleMethods = new Set(["log", "info", "debug", "warn", "error", "dir", "table"])
@@ -34,14 +25,14 @@ const formatConsoleValue = (value: unknown, seen: Set<object>, depth: number): s
if (typeof value === "string") return JSON.stringify(value)
if (typeof value === "number" || typeof value === "boolean") return String(value)
if (typeof value !== "object") return String(value)
if (value instanceof CodeModePromise) return "[Promise (await it to get its value)]"
if (value instanceof CodeModeDate) return coerceToString(value)
if (value instanceof CodeModeRegExp) return coerceToString(value)
if (value instanceof CodeModeURL) return coerceToString(value)
if (value instanceof CodeModeURLSearchParams) return coerceToString(value)
if (value instanceof Values.Promise) return "[Promise (await it to get its value)]"
if (value instanceof Values.Date) return coerceToString(value)
if (value instanceof Values.RegExp) return coerceToString(value)
if (value instanceof Values.URL) return coerceToString(value)
if (value instanceof Values.URLSearchParams) return coerceToString(value)
if (depth > MAX_CONSOLE_DEPTH) return "..."
if (seen.has(value)) return "[Circular]"
if (value instanceof CodeModeMap) {
if (value instanceof Values.Map) {
seen.add(value)
try {
const entries = Array.from(value.map.entries(), ([key, item]): Array<unknown> => [key, item])
@@ -50,7 +41,7 @@ const formatConsoleValue = (value: unknown, seen: Set<object>, depth: number): s
seen.delete(value)
}
}
if (value instanceof CodeModeSet) {
if (value instanceof Values.Set) {
seen.add(value)
try {
return `Set(${value.set.size}) ${formatConsoleValue(Array.from(value.set.values()), seen, depth + 1)}`
@@ -100,14 +91,14 @@ const consoleTableRows = (
if (Array.isArray(data)) {
return data.map((item, index) => ({ index: String(index), values: consoleTableValues(item, columns) }))
}
if (data !== null && typeof data === "object" && !isCodeModeValue(data)) {
if (data !== null && typeof data === "object" && !Values.isValue(data)) {
return Object.entries(data).map(([index, item]) => ({ index, values: consoleTableValues(item, columns) }))
}
return [{ index: "0", values: { Value: data } }]
}
const consoleTableValues = (value: unknown, columns: ReadonlyArray<string> | undefined): Record<string, unknown> => {
if (value !== null && typeof value === "object" && !Array.isArray(value) && !isCodeModeValue(value)) {
if (value !== null && typeof value === "object" && !Array.isArray(value) && !Values.isValue(value)) {
const source = value as Record<string, unknown>
if (columns !== undefined) return Object.fromEntries(columns.map((column) => [column, source[column]]))
return Object.fromEntries(Object.entries(source))
+3 -3
View File
@@ -1,5 +1,5 @@
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
import { CodeModeDate } from "../values.js"
import { Values } from "../values.js"
import { coerceToNumber, coerceToString } from "./value.js"
const dateSetterArguments = new Map<string, number>([
@@ -66,7 +66,7 @@ export const invokeDateStatic = (name: string, args: Array<unknown>, node: AstNo
export const dateSetterArgumentCount = (name: string): number | undefined => dateSetterArguments.get(name)
export const invokeDateMethod = (
value: CodeModeDate,
value: Values.Date,
name: string,
args: Array<number>,
node: AstNode,
@@ -174,7 +174,7 @@ export const invokeDateMethod = (
}
}
const updateDate = (value: CodeModeDate, time: number): number => {
const updateDate = (value: Values.Date, time: number): number => {
value.time = time
return time
}
+9 -16
View File
@@ -4,14 +4,7 @@ import { applyCollectionCallback } from "../interpreter/methods.js"
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
import { typeofValue } from "../interpreter/references.js"
import { copyIn, copyOut, type SafeObject } from "../tool-runtime.js"
import {
CodeModeDate,
CodeModeMap,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
} from "../values.js"
import { Values } from "../values.js"
export const jsonStatics = new Set(["parse", "stringify"])
export type JsonMethodName = "parse" | "stringify"
@@ -131,19 +124,19 @@ const stringify = <R>(
}
const toJSONValue = (value: unknown): unknown => {
if (value instanceof CodeModeDate) {
if (value instanceof Values.Date) {
return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null
}
if (value instanceof CodeModeURL) return value.url.href
if (value instanceof Values.URL) return value.url.href
return value
}
const isPlainObject = (value: unknown): value is SafeObject =>
value !== null &&
typeof value === "object" &&
!(value instanceof CodeModeDate) &&
!(value instanceof CodeModeRegExp) &&
!(value instanceof CodeModeMap) &&
!(value instanceof CodeModeSet) &&
!(value instanceof CodeModeURL) &&
!(value instanceof CodeModeURLSearchParams)
!(value instanceof Values.Date) &&
!(value instanceof Values.RegExp) &&
!(value instanceof Values.Map) &&
!(value instanceof Values.Set) &&
!(value instanceof Values.URL) &&
!(value instanceof Values.URLSearchParams)
+6 -6
View File
@@ -2,7 +2,7 @@ import { Effect } from "effect"
import { type AstNode, AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol } from "../interpreter/model.js"
import { containsOpaqueReference, rejectCircularInsertion } from "../interpreter/references.js"
import { isBlockedMember } from "../tool-runtime.js"
import { isCodeModeValue, CodeModePromise } from "../values.js"
import { Values } from "../values.js"
import { boundedData, coerceToString } from "./value.js"
import { preserveConsumerError, type SyncIteratorRunner } from "../interpreter/iterator.js"
@@ -14,8 +14,8 @@ export const invokeObjectMethod = (name: string, args: Array<unknown>, node: Ast
const requireObject = (): Record<string, unknown> => {
const input = args[0]
if (Array.isArray(input)) return input as unknown as Record<string, unknown>
if (isCodeModeValue(input)) return {}
if (input instanceof CodeModePromise) {
if (Values.isValue(input)) return {}
if (input instanceof Values.Promise) {
throw new InterpreterRuntimeError(
`Object.${name} received an un-awaited Promise; await it before inspecting the result.`,
node,
@@ -50,7 +50,7 @@ export const invokeObjectMethod = (name: string, args: Array<unknown>, node: Ast
return Object.is(args[0], args[1])
case "assign": {
const target = args[0]
if (target === null || typeof target !== "object" || Array.isArray(target) || isCodeModeValue(target)) {
if (target === null || typeof target !== "object" || Array.isArray(target) || Values.isValue(target)) {
throw new InterpreterRuntimeError("Object.assign expects a data object target.", node)
}
const out = target as Record<string, unknown>
@@ -65,7 +65,7 @@ export const invokeObjectMethod = (name: string, args: Array<unknown>, node: Ast
)
}
for (const source of args.slice(1)) {
if (source === null || source === undefined || isCodeModeValue(source)) continue
if (source === null || source === undefined || Values.isValue(source)) continue
if (typeof source !== "object" || Array.isArray(source)) {
throw new InterpreterRuntimeError("Object.assign expects data objects.", node)
}
@@ -107,7 +107,7 @@ export const invokeObjectFromEntries = <R>(
if (
step.value === null ||
typeof step.value !== "object" ||
isCodeModeValue(step.value) ||
Values.isValue(step.value) ||
containsOpaqueReference(step.value)
) {
throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] entry objects.", node).as(
+3 -3
View File
@@ -1,6 +1,6 @@
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
import { isBlockedMember, type SafeObject } from "../tool-runtime.js"
import { CodeModeRegExp } from "../values.js"
import { Values } from "../values.js"
import { coerceToNumber, coerceToString } from "./value.js"
type MatchValue = Array<unknown> & {
@@ -40,7 +40,7 @@ export const escapeRegexHint =
export const toHostRegex = (arg: unknown, method: string, node: AstNode, extraFlags = ""): RegExp => {
// Native parity: an undefined pattern behaves as an empty pattern.
if (arg === undefined) return new RegExp("", extraFlags)
if (arg instanceof CodeModeRegExp) return arg.regex
if (arg instanceof Values.RegExp) return arg.regex
if (typeof arg === "string") {
try {
return new RegExp(arg, extraFlags)
@@ -80,7 +80,7 @@ export const invokeRegExpStatic = (name: string, args: Array<unknown>, node: Ast
}
export const invokeRegExpMethod = (
value: CodeModeRegExp,
value: Values.RegExp,
name: string,
args: Array<unknown>,
node: AstNode,
+4 -4
View File
@@ -66,7 +66,7 @@ export const invokeUriFunction = (ref: UriFunction, args: Array<unknown>, node:
}
export const urlArgument = (value: unknown, label: string): string =>
value instanceof CodeModeURL ? value.url.href : uriArgument(value, label)
value instanceof Values.URL ? value.url.href : uriArgument(value, label)
export const invokeURLStatic = (name: string, args: Array<unknown>, node: AstNode): unknown => {
if (!urlStatics.has(name)) throw new InterpreterRuntimeError(`URL.${name} is not available.`, node)
@@ -75,16 +75,16 @@ export const invokeURLStatic = (name: string, args: Array<unknown>, node: AstNod
const base = args[1] === undefined ? undefined : urlArgument(args[1], `URL.${name} base`)
try {
const url = new URL(input, base)
return name === "canParse" ? true : new CodeModeURL(url)
return name === "canParse" ? true : new Values.URL(url)
} catch {
return name === "canParse" ? false : null
}
}
export const invokeURLMethod = (value: CodeModeURL, name: string, node: AstNode): string => {
export const invokeURLMethod = (value: Values.URL, name: string, node: AstNode): string => {
if (name === "toString" || name === "toJSON") return value.url.href
throw new InterpreterRuntimeError(`URL method '${name}' is not available.`, node)
}
import { type AstNode, InterpreterRuntimeError, UriFunction } from "../interpreter/model.js"
import { CodeModeURL } from "../values.js"
import { Values } from "../values.js"
import { boundedData, coerceToString } from "./value.js"
+10 -18
View File
@@ -34,13 +34,13 @@ export const boundedData = (value: unknown, label: string): unknown => copyIn(va
export const coerceToString = (value: unknown): string => {
if (value === null) return "null"
if (value === undefined) return "undefined"
if (value instanceof CodeModeDate)
if (value instanceof Values.Date)
return Number.isFinite(value.time) ? new Date(value.time).toISOString() : "Invalid Date"
if (value instanceof CodeModeRegExp) return `/${value.regex.source}/${value.regex.flags}`
if (value instanceof CodeModeMap) return "[object Map]"
if (value instanceof CodeModeSet) return "[object Set]"
if (value instanceof CodeModeURL) return value.url.href
if (value instanceof CodeModeURLSearchParams) return value.params.toString()
if (value instanceof Values.RegExp) return `/${value.regex.source}/${value.regex.flags}`
if (value instanceof Values.Map) return "[object Map]"
if (value instanceof Values.Set) return "[object Set]"
if (value instanceof Values.URL) return value.url.href
if (value instanceof Values.URLSearchParams) return value.params.toString()
if (errorBrandName(value) !== undefined) {
// Match Error.prototype.toString: "name: message", or just one when the other is empty.
const error = value as { name?: unknown; message?: unknown }
@@ -59,8 +59,8 @@ export const coerceToString = (value: unknown): string => {
}
export const coerceToNumber = (value: unknown): number => {
if (value instanceof CodeModeDate) return value.time
if (isCodeModeValue(value)) return Number.NaN
if (value instanceof Values.Date) return value.time
if (Values.isValue(value)) return Number.NaN
// Arrays coerce through our own string coercion: host Number(array) joins with host
// ToPrimitive, which throws on the null-prototype objects the interpreter produces.
if (Array.isArray(value)) return Number(coerceToString(value))
@@ -77,7 +77,7 @@ export const invokeCoercion = (ref: CoercionFunction, args: Array<unknown>, node
const raw = args[0]
// Error values are plain SafeObjects; the boundedData path below would strip their brand.
if (ref.name === "String" && errorBrandName(raw) !== undefined) return coerceToString(raw)
if (isCodeModeValue(raw)) {
if (Values.isValue(raw)) {
if (ref.name === "Boolean") return true
if (ref.name === "Number") return coerceToNumber(raw)
if (ref.name === "String") return coerceToString(raw)
@@ -103,12 +103,4 @@ export const invokeCoercion = (ref: CoercionFunction, args: Array<unknown>, node
}
import { type AstNode, CoercionFunction, InterpreterRuntimeError } from "../interpreter/model.js"
import { copyIn, type SafeObject } from "../tool-runtime.js"
import {
isCodeModeValue,
CodeModeDate,
CodeModeMap,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
} from "../values.js"
import { Values } from "../values.js"
+20 -28
View File
@@ -12,15 +12,7 @@ import {
import { isNamespace, type Namespace } from "./namespace.js"
import { isTool, type Tool } from "./tool.js"
import type { Tools } from "./tools.js"
import {
CodeModeDate,
CodeModeMap,
CodeModePromise,
CodeModeRegExp,
CodeModeSet,
CodeModeURL,
CodeModeURLSearchParams,
} from "./values.js"
import { Values } from "./values.js"
const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0)
@@ -151,7 +143,7 @@ const copyBounded = (
throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`)
}
if (value instanceof CodeModePromise) {
if (value instanceof Values.Promise) {
throw new ToolRuntimeError(
"InvalidDataValue",
`${label} contains an un-awaited Promise; await tool calls (e.g. \`const result = await tools.ns.tool(...)\`) before using their results.`,
@@ -160,46 +152,46 @@ const copyBounded = (
if (preserveCodeModeValues) {
if (
value instanceof CodeModeDate ||
value instanceof CodeModeRegExp ||
value instanceof CodeModeMap ||
value instanceof CodeModeSet ||
value instanceof CodeModeURL ||
value instanceof CodeModeURLSearchParams
value instanceof Values.Date ||
value instanceof Values.RegExp ||
value instanceof Values.Map ||
value instanceof Values.Set ||
value instanceof Values.URL ||
value instanceof Values.URLSearchParams
) {
return value
}
if (value instanceof Date) return new CodeModeDate(value.getTime())
if (value instanceof RegExp) return new CodeModeRegExp(value.source, value.flags)
if (value instanceof Date) return new Values.Date(value.getTime())
if (value instanceof RegExp) return new Values.RegExp(value.source, value.flags)
if (value instanceof Map) {
const wrapped = new CodeModeMap()
const wrapped = new Values.Map()
for (const [key, item] of value.entries()) {
wrapped.map.set(copyBounded(key, label, depth + 1, seen, true), copyBounded(item, label, depth + 1, seen, true))
}
return wrapped
}
if (value instanceof Set) {
const wrapped = new CodeModeSet()
const wrapped = new Values.Set()
for (const item of value.values()) wrapped.set.add(copyBounded(item, label, depth + 1, seen, true))
return wrapped
}
if (value instanceof URL) return new CodeModeURL(new URL(value.href))
if (value instanceof URLSearchParams) return new CodeModeURLSearchParams(new URLSearchParams(value))
if (value instanceof URL) return new Values.URL(new URL(value.href))
if (value instanceof URLSearchParams) return new Values.URLSearchParams(new URLSearchParams(value))
}
if (value instanceof CodeModeDate) {
if (value instanceof Values.Date) {
return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null
}
if (value instanceof Date) {
return Number.isFinite(value.getTime()) ? value.toISOString() : null
}
if (value instanceof CodeModeURL) return value.url.href
if (value instanceof Values.URL) return value.url.href
if (value instanceof URL) return value.href
if (
value instanceof CodeModeRegExp ||
value instanceof CodeModeMap ||
value instanceof CodeModeSet ||
value instanceof CodeModeURLSearchParams ||
value instanceof Values.RegExp ||
value instanceof Values.Map ||
value instanceof Values.Set ||
value instanceof Values.URLSearchParams ||
value instanceof RegExp ||
value instanceof Map ||
value instanceof Set ||
+30 -24
View File
@@ -1,17 +1,24 @@
export * as Values from "./values.js"
import type { Fiber } from "effect"
export class CodeModePromise {
/**
* Runtime values the interpreter recognizes by class. Each wraps the host value it stands for,
* so hosts construct these to hand a value to a program and receive them back unchanged.
*/
export class Promise {
constructor(readonly fiber: Fiber.Fiber<unknown, unknown>) {}
}
export class CodeModeDate {
export class Date {
constructor(public time: number) {}
}
export class CodeModeRegExp {
readonly regex: RegExp
export class RegExp {
readonly regex: globalThis.RegExp
constructor(pattern: string, flags: string) {
this.regex = new RegExp(pattern, flags)
this.regex = new globalThis.RegExp(pattern, flags)
}
get lastIndex(): unknown {
@@ -23,31 +30,30 @@ export class CodeModeRegExp {
}
}
export class CodeModeMap {
readonly map = new Map<unknown, unknown>()
export class Map {
readonly map = new globalThis.Map<unknown, unknown>()
}
export class CodeModeSet {
readonly set = new Set<unknown>()
export class Set {
readonly set = new globalThis.Set<unknown>()
}
export class CodeModeURLSearchParams {
constructor(readonly params: URLSearchParams) {}
export class URLSearchParams {
constructor(readonly params: globalThis.URLSearchParams) {}
}
export class CodeModeURL {
readonly searchParams: CodeModeURLSearchParams
constructor(readonly url: URL) {
this.searchParams = new CodeModeURLSearchParams(url.searchParams)
export class URL {
readonly searchParams: URLSearchParams
constructor(readonly url: globalThis.URL) {
this.searchParams = new URLSearchParams(url.searchParams)
}
}
export const isCodeModeValue = (
value: unknown,
): value is CodeModeDate | CodeModeRegExp | CodeModeMap | CodeModeSet | CodeModeURL | CodeModeURLSearchParams =>
value instanceof CodeModeDate ||
value instanceof CodeModeRegExp ||
value instanceof CodeModeMap ||
value instanceof CodeModeSet ||
value instanceof CodeModeURL ||
value instanceof CodeModeURLSearchParams
/** Data-like runtime values; excludes Promise, which never crosses a boundary. */
export const isValue = (value: unknown): value is Date | RegExp | Map | Set | URL | URLSearchParams =>
value instanceof Date ||
value instanceof RegExp ||
value instanceof Map ||
value instanceof Set ||
value instanceof URL ||
value instanceof URLSearchParams