mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-18 15:28:48 +03:00
feat(codemode): add Promise.withResolvers, print errors in console, name values in iterable errors (#50389)
This commit is contained in:
committed by
GitHub
Unverified
parent
6f76c31ca7
commit
3f0118022b
@@ -238,6 +238,8 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
|
||||
resolving with the promise itself rejects with a `TypeError`. Resolver callables work anywhere callbacks are
|
||||
accepted, including `.then`/`.catch` handlers and collection callbacks, and vanish at the data boundary like
|
||||
any function.
|
||||
- [x] `Promise.withResolvers()`: the same promise and resolver callables as the constructor, as a `{ promise, resolve,
|
||||
reject }` object.
|
||||
- [x] Recursive assimilation of objects with an own callable `then` field across `Promise.resolve`, combinators,
|
||||
constructors, reactions, `finally`, `await`, and async returns. Thenable methods run deferred, receive
|
||||
first-call-wins resolve/reject functions, and ignore throws after settlement. Inherited/accessor `then` fields
|
||||
@@ -370,7 +372,8 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
|
||||
- [x] `JSON.stringify` function and array replacers. Function replacers receive `(key, value)` in preorder, including
|
||||
the root, but no `this` holder. Array replacers preserve requested property order, deduplicate names, coerce
|
||||
number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported.
|
||||
- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`.
|
||||
- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. An Error prints as
|
||||
`Error.prototype.toString` would show it (`Error: boom`), wherever it appears in the logged value.
|
||||
- [x] Captured `console.dir` and `console.table`.
|
||||
|
||||
## Date
|
||||
|
||||
@@ -129,6 +129,9 @@ export class ErrorObj extends Obj {
|
||||
if (shownName === "") return shownMessage
|
||||
return `${shownName}: ${shownMessage}`
|
||||
}
|
||||
override inspect() {
|
||||
return this.toString()
|
||||
}
|
||||
}
|
||||
|
||||
/** Interpreter machinery a program can hold but never inspect, serialize, or hand to the host. */
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CallSite, Throw, rangeError, typeError } from "./model.js"
|
||||
import { Callable, define, get, hidden, Arr, Fn, Obj, PromiseObj, record, type Value } from "./objects.js"
|
||||
import { constructor, fn, methods, native, receiver, requiresNew } from "./native.js"
|
||||
import { createAggregateErrorValue, locate, materialize, normalizeError } from "./errors.js"
|
||||
import { typeofValue } from "./references.js"
|
||||
import { describeValue, typeofValue } from "./references.js"
|
||||
import { applyCollectionCallback, isSupportedCallback } from "./callback.js"
|
||||
import type { Interpreter } from "./interpreter.js"
|
||||
|
||||
@@ -136,7 +136,7 @@ export const resolvePromise = <R>(ctx: Interpreter<R>, value: Value): Effect.Eff
|
||||
return ctx.pending.createWithSelf((self) => resolvePromiseValue(ctx, value, self))
|
||||
}
|
||||
|
||||
const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject"] as const
|
||||
const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers"] as const
|
||||
|
||||
const invokePromiseMethod = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
@@ -149,11 +149,18 @@ const invokePromiseMethod = <R>(
|
||||
if (name === "reject") {
|
||||
return ctx.pending.create(Effect.fail(new Throw(args[0])))
|
||||
}
|
||||
if (name === "withResolvers") {
|
||||
return Effect.map(promiseCapability(ctx), (made) =>
|
||||
record(ctx.builtins.Object, { promise: made.promise, resolve: made.resolve, reject: made.reject }),
|
||||
)
|
||||
}
|
||||
|
||||
return ctx.pending.create(
|
||||
Effect.gen(function* () {
|
||||
const cursor = yield* ctx.iterate(args[0])
|
||||
if (cursor === undefined) throw typeError(`Promise.${name} expects an array or other synchronous iterable.`)
|
||||
if (cursor === undefined) {
|
||||
throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(args[0])}.`)
|
||||
}
|
||||
const items: Array<PromiseObj> = []
|
||||
while (true) {
|
||||
const step = yield* cursor.next
|
||||
@@ -237,23 +244,30 @@ const instanceMethod = <R>(
|
||||
return chainReaction(ctx, promise, onFulfilled, onRejected, method)
|
||||
}
|
||||
|
||||
const constructPromise = <R>(ctx: Interpreter<R>, executor: Value): Effect.Effect<PromiseObj, unknown, R> => {
|
||||
if (!(executor instanceof Fn)) {
|
||||
throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).")
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
/** NewPromiseCapability: a pending promise with the resolve/reject callables that settle it exactly once. */
|
||||
const promiseCapability = <R>(ctx: Interpreter<R>) =>
|
||||
Effect.gen(function* () {
|
||||
const deferred = Deferred.makeUnsafe<Value, unknown>()
|
||||
const promise = yield* ctx.pending.createWithSelf((self) =>
|
||||
Effect.flatMap(Deferred.await(deferred), (value) => resolvePromiseValue(ctx, value, self)),
|
||||
)
|
||||
const resolve = capability(ctx, "resolve", (value) => Deferred.doneUnsafe(deferred, Exit.succeed(value)))
|
||||
const reject = capability(ctx, "reject", (value) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(value))))
|
||||
const executed = yield* Effect.exit(ctx.call(executor, undefined, [resolve, reject]))
|
||||
return { promise, resolve, reject, deferred }
|
||||
})
|
||||
|
||||
const constructPromise = <R>(ctx: Interpreter<R>, executor: Value): Effect.Effect<PromiseObj, unknown, R> => {
|
||||
if (!(executor instanceof Fn)) {
|
||||
throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).")
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
const made = yield* promiseCapability(ctx)
|
||||
const executed = yield* Effect.exit(ctx.call(executor, undefined, [made.resolve, made.reject]))
|
||||
if (!Exit.isSuccess(executed)) {
|
||||
if (Cause.hasInterruptsOnly(executed.cause)) return yield* Effect.failCause(executed.cause)
|
||||
Deferred.doneUnsafe(deferred, Exit.fail(Cause.squash(executed.cause)))
|
||||
Deferred.doneUnsafe(made.deferred, Exit.fail(Cause.squash(executed.cause)))
|
||||
}
|
||||
return promise
|
||||
return made.promise
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -26,9 +26,7 @@ const arrayLikeSource = (source: Value): { readonly length: number; readonly sou
|
||||
checkArrayLength(normalized)
|
||||
return { length: normalized, source }
|
||||
}
|
||||
throw invalidData(
|
||||
`Array.from expects an array, string, Map, Set, or array-like value, received ${describeValue(source)}.`,
|
||||
)
|
||||
throw invalidData(`Array.from expects an iterable or array-like value, received ${describeValue(source)}.`)
|
||||
}
|
||||
|
||||
const arrayFrom = <R>(ctx: Interpreter<R>, args: Array<Value>): Effect.Effect<Value, unknown, R> => {
|
||||
@@ -40,7 +38,9 @@ const arrayFrom = <R>(ctx: Interpreter<R>, args: Array<Value>): Effect.Effect<Va
|
||||
const cursor = yield* ctx.iterate(source)
|
||||
if (cursor === undefined) {
|
||||
if (source instanceof GeneratorObj) {
|
||||
throw typeError("Array.from expects a synchronous iterable or array-like value.")
|
||||
throw typeError(
|
||||
`Array.from expects a synchronous iterable or array-like value, received ${describeValue(source)}.`,
|
||||
)
|
||||
}
|
||||
const arrayLike = arrayLikeSource(source)
|
||||
const values: Array<Value> = []
|
||||
|
||||
@@ -88,7 +88,7 @@ const constructMap = <R>(ctx: Interpreter<R>, init: Value, proto: Obj) => {
|
||||
return Effect.gen(function* () {
|
||||
const cursor = yield* ctx.iterate(init)
|
||||
if (cursor === undefined) {
|
||||
throw typeError("new Map(...) expects an iterable of [key, value] pairs or no argument.")
|
||||
throw typeError(`new Map(...) expects an iterable of [key, value] pairs, received ${describeValue(init)}.`)
|
||||
}
|
||||
while (true) {
|
||||
const step = yield* cursor.next
|
||||
@@ -112,7 +112,7 @@ const constructSet = <R>(ctx: Interpreter<R>, init: Value, proto: Obj) => {
|
||||
return Effect.gen(function* () {
|
||||
const cursor = yield* ctx.iterate(init)
|
||||
if (cursor === undefined) {
|
||||
throw typeError("new Set(...) expects a synchronous iterable or no argument.")
|
||||
throw typeError(`new Set(...) expects a synchronous iterable, received ${describeValue(init)}.`)
|
||||
}
|
||||
while (true) {
|
||||
const step = yield* cursor.next
|
||||
|
||||
@@ -156,7 +156,7 @@ describe("host errors escaping built-ins", () => {
|
||||
test("an un-awaited rejection born inside promise machinery keeps its location in the warning", async () => {
|
||||
const result = await run(`Promise.all(1); return 1`)
|
||||
expect(result.ok && result.warnings?.[0]?.message).toEndWith(
|
||||
"TypeError: Promise.all expects an array or other synchronous iterable. (line 1, col 1)",
|
||||
"TypeError: Promise.all expects a synchronous iterable, received a number. (line 1, col 1)",
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -730,7 +730,7 @@ describe("Promise.all over arbitrary arrays", () => {
|
||||
|
||||
test("a non-collection argument is a clear error", async () => {
|
||||
const diagnostic = await error(`return await Promise.all(42)`)
|
||||
expect(diagnostic.message).toContain("Promise.all expects an array")
|
||||
expect(diagnostic.message).toContain("Promise.all expects a synchronous iterable, received a number")
|
||||
})
|
||||
|
||||
test("exceeding maxToolCalls inside Promise.all is a ToolCallLimitExceeded diagnostic", async () => {
|
||||
@@ -1131,8 +1131,25 @@ describe("unsupported promise surface", () => {
|
||||
})
|
||||
|
||||
test("unknown Promise statics are not functions", async () => {
|
||||
const diagnostic = await error(`return await Promise.withResolvers()`)
|
||||
expect(diagnostic.message).toContain("Promise.withResolvers is not a function")
|
||||
const diagnostic = await error(`return await Promise.try(() => 1)`)
|
||||
expect(diagnostic.message).toContain("Promise.try is not a function")
|
||||
})
|
||||
})
|
||||
|
||||
describe("Promise.withResolvers", () => {
|
||||
test("returns a pending promise with resolvers that settle it once and adopt thenables", async () => {
|
||||
expect(
|
||||
await value(`
|
||||
const first = Promise.withResolvers()
|
||||
first.resolve(Promise.resolve("adopted"))
|
||||
first.resolve("ignored")
|
||||
const second = Promise.withResolvers()
|
||||
second.reject(new Error("no"))
|
||||
let caught
|
||||
try { await second.promise } catch (e) { caught = e.message }
|
||||
return [Object.keys(first), first.promise instanceof Promise, await first.promise, caught]
|
||||
`),
|
||||
).toEqual([["promise", "resolve", "reject"], true, "adopted", "no"])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1293,6 +1293,13 @@ describe("Object.prototype.toString", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("console.log of errors", () => {
|
||||
test("prints name and message, nested too", async () => {
|
||||
const result = await run(`console.log(new Error("boom"), { e: new RangeError("r") })`)
|
||||
expect(result.logs).toEqual(['Error: boom {"e":RangeError: r}'])
|
||||
})
|
||||
})
|
||||
|
||||
describe("toLocaleString", () => {
|
||||
test("numbers and dates format as en-US in UTC; everything else falls back to toString", async () => {
|
||||
expect(
|
||||
|
||||
Reference in New Issue
Block a user