From 7d6a85dfe1836109d5eb1bdea598bd502674f6f8 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Sun, 8 Nov 2026 21:23:09 -0500 Subject: [PATCH 01/25] Give frames origins, cross-origin windows and messages A sandbox without allow-same-origin gives a frame an opaque origin, as HTML's sandboxed origin browsing context flag does, and a frame inside a sandboxed one keeps the sandbox. A srcdoc or about:blank frame takes the origin of the document that made it. Windows of two origins hold each other through a cross-origin WindowProxy that lets through only HTML's CrossOriginProperties and throws a SecurityError for the rest, so a sandboxed frame's contentDocument is null and its parent cannot reach into it, or it into the parent. Each viewer gets one proxy per window, so contentWindow compares equal to itself. postMessage checks the target origin against these origins, gives the event the sender's serialized origin, and gives as its source the sender as the receiver holds it, so a frame's event.source === parent holds. A frame may set its parent's location across origins, which goes through the parent's navigate event, and a sandbox without allow-top-navigation stops it with a SecurityError. A srcdoc frame resolves URLs against its parent's base URL, as HTML's fallback base URL does. Where the runtime has no node:vm, as in isolated-vm, a frame got a bare object with no postMessage, location or parent. It gets a whole window built in the engine's realm, which is what DuckDuckGo's result click needs: a message to a hidden frame that sends the page to the result. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- src/internal/dom.ts | 687 +++++++++++++++++++++++++++++++----- src/internal/window.ts | 30 +- tests/frame-origins.test.ts | 312 ++++++++++++++++ tests/frames-without-vm.ts | 63 ++++ tests/iframe-realms.test.ts | 28 ++ 5 files changed, 1018 insertions(+), 102 deletions(-) create mode 100644 tests/frame-origins.test.ts create mode 100644 tests/frames-without-vm.ts diff --git a/src/internal/dom.ts b/src/internal/dom.ts index df0d80b5..29fb9b30 100644 --- a/src/internal/dom.ts +++ b/src/internal/dom.ts @@ -15975,7 +15975,7 @@ function getURLAttribute(element: Element, attribute: string): string { // document's URL. Falls back to the document's URL when there is no such // element or its href does not parse. function getDocumentBaseURL(document: Document): string { - const fallback = _(document).extra.documentURL; + const fallback = getFallbackBaseURL(document); for (const node of descendants(document)) { if (getNodeType(node) !== ELEMENT_NODE) { continue; @@ -15996,6 +15996,17 @@ function getDocumentBaseURL(document: Document): string { return fallback; } +// HTML's fallback base URL: a frame's srcdoc or about:blank document +// resolves against the base URL of the document its iframe is in. +function getFallbackBaseURL(document: Document): string { + const url = _(document).extra.documentURL; + const window = _(document).extra.defaultView as Window | null; + const frame = window === null ? null : _(window).frameOwner; + return frame !== null && (url === "about:srcdoc" || url === "about:blank") + ? getDocumentBaseURL(_(frame).document) + : url; +} + function parseInteger(value: string): number | null { const match = /^[\t\n\f\r ]*([+-]?[0-9]+)/.exec(value); if (match === null) { @@ -19239,15 +19250,16 @@ interface FrameWindowLike { } // A frame's document and the window that shows it, built in a realm of -// their own, or null where the runtime cannot make a realm. window.ts -// gives the factory, since a window is built above the DOM. +// their own where the runtime can make one, and in the engine's realm +// where it cannot. window.ts gives the factory, since a window is built +// above the DOM. type FrameWindowFactory = ( source: string, url: string, registry: CustomElementRegistry, parent: Window | null, frame: HTMLIFrameElement, -) => {document: Document; window: Window} | null; +) => {document: Document; window: Window}; let frameWindowFactory: FrameWindowFactory | null = null; @@ -19296,6 +19308,438 @@ function getTopWindow(window: Window): Window { return current; } +// Whether `window` is `ancestor`, or a frame somewhere inside it. +function isWindowWithin(window: Window, ancestor: Window): boolean { + for ( + let current: Window | null = window; + current !== null; + current = _(current).parentWindow + ) { + if (current === ancestor) { + return true; + } + } + return false; +} + +/** + * An origin, as HTML has it: a tuple origin by its serialization, or an + * opaque origin, which is an object compared by identity. + */ +type Origin = string | object; + +// The origin of `url`, with `opaque` standing for one that is opaque. +function getURLOrigin(url: string, opaque: object): Origin { + const origin = parseURL(url)?.origin ?? "null"; + return origin === "null" ? opaque : origin; +} + +// A sandbox without allow-same-origin gives a window an opaque origin of +// its own. A frame showing srcdoc or about:blank has the origin of the +// document its iframe is in, which created it. Otherwise the URL says. +function getWindowOrigin(window: Window): Origin { + const slots = _(window); + if (slots.sandboxOrigin !== null) { + return slots.sandboxOrigin; + } + const url = _(window.document).extra.documentURL; + const frame = slots.frameOwner; + if (frame !== null && (url === "about:srcdoc" || url === "about:blank")) { + return getDocumentOrigin(_(frame).document); + } + return getURLOrigin(url, window); +} + +function getDocumentOrigin(document: Document): Origin { + const window = _(document).extra.defaultView as Window | null; + return window !== null + ? getWindowOrigin(window) + : getURLOrigin(_(document).extra.documentURL, document); +} + +function serializeOrigin(origin: Origin): string { + return typeof origin === "string" ? origin : "null"; +} + +/** + * HTML's iframe sandboxing flag set, as the allow- tokens that lift its + * flags: those of the iframe's sandbox attribute that the window it is in + * has too. Null where no sandbox applies. + */ +function getFrameSandbox( + frame: HTMLIFrameElement, + parent: Window | null, +): ReadonlySet | null { + const attribute = getAttributeValue(frame, "sandbox"); + const above = parent === null ? null : _(parent).sandbox; + if (attribute === null) { + return above; + } + const tokens = splitOnASCIIWhitespace(toASCIILowercase(attribute)); + return new Set( + above === null ? tokens : tokens.filter((token) => above.has(token)), + ); +} + +/** + * HTML's "allowed by sandboxing to navigate": a sandboxed window + * navigates itself and the frames inside it, and its top window where + * allow-top-navigation lets it, or allow-top-navigation-by-user-activation + * and the user's action. + */ +function isAllowedToNavigate(source: Window, target: Window): boolean { + const sandbox = _(source).sandbox; + if (sandbox === null || isWindowWithin(target, source)) { + return true; + } + if (target !== getTopWindow(source)) { + return false; + } + return sandbox.has("allow-top-navigation") || + (sandbox.has("allow-top-navigation-by-user-activation") && + hasTransientActivation(source.document)); +} + +/** + * The window whose code calls a member of `window`, HTML's incumbent, + * where a realm tells: the frame whose realm runs, or null for the + * engine's own. + */ +function getIncumbentWindow(window: Window): Window | null { + const realm = _(window).realm !== null + ? getCallerRealm() + : getIncumbentRealm(); + return realm === null ? null : realm.global as unknown as Window; +} + +// What code of another origin reaches on a window, HTML's +// CrossOriginProperties, and what it reads as undefined. +const CROSS_ORIGIN_WINDOW_KEYS = [ + "window", + "self", + "location", + "close", + "closed", + "focus", + "blur", + "frames", + "length", + "top", + "opener", + "parent", + "postMessage", +]; + +const CROSS_ORIGIN_FALLBACK_KEYS: ReadonlyArray = [ + "then", + Symbol.toStringTag, + Symbol.hasInstance, + Symbol.isConcatSpreadable, +]; + +/** + * A window or its location as code of another origin's window, the + * viewer, holds it: HTML's cross-origin WindowProxy and Location. The + * record is the proxy's target, which the traps read and never expose. + */ +interface CrossOriginWindowRecord { + kind: "window"; + viewer: Window; + target: Window; + proxy: Window | null; + location: CrossOriginLocationRecord; + postMessage: (...args: unknown[]) => void; + close: () => void; + focus: () => void; + blur: () => void; +} + +interface CrossOriginLocationRecord { + kind: "location"; + viewer: Window; + target: Window; + proxy: object | null; + replace: (...args: unknown[]) => void; + setHref: (...args: unknown[]) => void; +} + +type CrossOriginRecord = CrossOriginWindowRecord | CrossOriginLocationRecord; + +function crossOriginError( + record: CrossOriginRecord, + key: string | symbol, +): Error { + return domError( + "SecurityError", + `Blocked a frame with origin "${ + serializeOrigin(getWindowOrigin(record.viewer)) + }" from accessing '${String(key)}' on a cross-origin ${ + record.kind === "window" ? "window" : "location" + }.`, + ); +} + +// The window of the frame at index `key` of `window`'s frames, or of the +// first one `key` names whose origin is the window's. +function getChildFrameWindow(window: Window, key: string): Window | null { + const frames = getDocumentFrames(window.document); + const frame = isArrayIndex(key) + ? frames[Number(key)] + : frames.find((each) => getAttributeValue(each, "name") === key); + if (frame === undefined) { + return null; + } + ensureFrameDocument(frame); + const content = _(frame).extra.contentWindow; + return implementsInterface(content, Window) && + (isArrayIndex(key) || getWindowOrigin(content) === getWindowOrigin(window)) + ? content + : null; +} + +function describeData(value: unknown, enumerable = false): PropertyDescriptor { + return {value, writable: false, enumerable, configurable: true}; +} + +// HTML's CrossOriginGetOwnPropertyHelper, with the fallback: what code of +// the viewer's origin may find under `key`, or a SecurityError. +function describeCrossOrigin( + record: CrossOriginRecord, + key: string | symbol, +): PropertyDescriptor { + if (CROSS_ORIGIN_FALLBACK_KEYS.includes(key)) { + return describeData(undefined); + } + if (record.kind === "location") { + if (key === "href") { + return { + get: undefined, + set: record.setHref, + enumerable: false, + configurable: true, + }; + } + if (key === "replace") { + return describeData(record.replace); + } + throw crossOriginError(record, key); + } + const {viewer, target} = record; + switch (key) { + case "window": + case "self": + case "frames": + return describeData(record.proxy); + case "location": + return describeData(record.location.proxy); + case "closed": + return describeData(target.closed || _(target).discarded); + case "length": + return describeData(getDocumentFrames(target.document).length); + case "top": + return describeData(viewWindow(viewer, getTopWindow(target))); + case "parent": + return describeData(viewWindow(viewer, _(target).parentWindow ?? target)); + case "opener": + return describeData(null); + case "postMessage": + case "close": + case "focus": + case "blur": + return describeData(record[key]); + } + const child = typeof key === "string" + ? getChildFrameWindow(target, key) + : null; + if (child === null) { + throw crossOriginError(record, key); + } + return describeData(viewWindow(viewer, child), isArrayIndex(key as string)); +} + +const CROSS_ORIGIN_HANDLER: ProxyHandler = { + get(record, key) { + const descriptor = describeCrossOrigin(record, key); + if ("value" in descriptor) { + return descriptor.value as unknown; + } + throw crossOriginError(record, key); + }, + set(record, key, value) { + if (record.kind === "window" && key === "location") { + record.location.setHref(value); + return true; + } + const descriptor = describeCrossOrigin(record, key); + if (descriptor.set === undefined) { + throw crossOriginError(record, key); + } + descriptor.set(value); + return true; + }, + has(record, key) { + describeCrossOrigin(record, key); + return true; + }, + getOwnPropertyDescriptor(record, key) { + return describeCrossOrigin(record, key); + }, + ownKeys(record) { + if (record.kind === "location") { + return ["href", "replace", ...CROSS_ORIGIN_FALLBACK_KEYS]; + } + const length = getDocumentFrames(record.target.document).length; + return [ + ...Array.from({length}, (_value, index) => String(index)), + ...CROSS_ORIGIN_WINDOW_KEYS, + ...CROSS_ORIGIN_FALLBACK_KEYS, + ]; + }, + defineProperty(record, key) { + throw crossOriginError(record, key); + }, + deleteProperty(record, key) { + throw crossOriginError(record, key); + }, + getPrototypeOf() { + return null; + }, + setPrototypeOf(_record, prototype) { + return prototype === null; + }, + isExtensible() { + return true; + }, + preventExtensions() { + return false; + }, +}; + +function crossOriginPostMessage( + record: CrossOriginWindowRecord, + ...args: unknown[] +): void { + if (args.length < 1) { + throw new TypeError( + "Failed to execute 'postMessage' on 'Window': 1 argument required, but only 0 present.", + ); + } + postWindowMessage(record.target, record.viewer, args[0], args[1]); +} + +// A cross-origin close reaches a top window the viewer may navigate. +function crossOriginClose(record: CrossOriginWindowRecord): void { + const {viewer, target} = record; + if (_(target).parentWindow === null && isAllowedToNavigate(viewer, target)) { + target.close(); + } +} + +function crossOriginFocus(record: CrossOriginWindowRecord): void { + record.target.focus(); +} + +function crossOriginBlur(record: CrossOriginWindowRecord): void { + record.target.blur(); +} + +function crossOriginSetHref( + record: CrossOriginLocationRecord, + ...args: unknown[] +): void { + navigateWindow(record.viewer, record.target, String(args[0]), "auto"); +} + +function crossOriginReplace( + record: CrossOriginLocationRecord, + ...args: unknown[] +): void { + if (args.length < 1) { + throw new TypeError( + "Failed to execute 'replace' on 'Location': 1 argument required, but only 0 present.", + ); + } + navigateWindow(record.viewer, record.target, String(args[0]), "replace"); +} + +// A cross-origin function has its own identity for each viewer, and the +// name of the member it stands for. +function bindCrossOrigin( + implementation: (record: T, ...args: unknown[]) => void, + record: T, + name: string, +): (...args: unknown[]) => void { + const bound = implementation.bind(null, record); + Object.defineProperty(bound, "name", {value: name}); + return bound; +} + +function createCrossOriginWindow(viewer: Window, target: Window): Window { + const location = { + kind: "location", + viewer, + target, + proxy: null, + } as unknown as CrossOriginLocationRecord; + location.replace = bindCrossOrigin(crossOriginReplace, location, "replace"); + location.setHref = bindCrossOrigin(crossOriginSetHref, location, "set href"); + // A name HTML does not list throws, which only a proxy can do. + // eslint-disable-next-line no-restricted-globals + location.proxy = new Proxy(location, CROSS_ORIGIN_HANDLER); + const record = { + kind: "window", + viewer, + target, + proxy: null, + location, + } as unknown as CrossOriginWindowRecord; + record.postMessage = bindCrossOrigin( + crossOriginPostMessage, + record, + "postMessage", + ); + record.close = bindCrossOrigin(crossOriginClose, record, "close"); + record.focus = bindCrossOrigin(crossOriginFocus, record, "focus"); + record.blur = bindCrossOrigin(crossOriginBlur, record, "blur"); + // eslint-disable-next-line no-restricted-globals + record.proxy = new Proxy( + record, + CROSS_ORIGIN_HANDLER, + ) as unknown as Window; + return record.proxy; +} + +/** + * `target` as code of `viewer` holds it: the window itself where the two + * have one origin, and otherwise a cross-origin WindowProxy, the one + * `viewer` gets each time. + */ +function viewWindow(viewer: Window, target: Window): Window { + if (getWindowOrigin(viewer) === getWindowOrigin(target)) { + return target; + } + const slots = _(target); + const views = slots.crossOriginViews ??= new WeakMap(); + let view = views.get(viewer); + if (view === undefined) { + view = createCrossOriginWindow(viewer, target); + views.set(viewer, view); + } + return view; +} + +// The frame's window as code of the window its iframe is in holds it. +function getFrameView( + frame: HTMLIFrameElement, +): FrameWindowLike | Window | null { + ensureFrameDocument(frame); + const window = _(frame).extra.contentWindow; + const viewer = _(_(frame).document).extra.defaultView as Window | null; + return viewer !== null && implementsInterface(window, Window) + ? viewWindow(viewer, window) + : window; +} + // The iframes of `document`'s own tree, in tree order, which are its // window's frames. Those in shadow trees are not. function getDocumentFrames(document: Document): HTMLIFrameElement[] { @@ -19331,7 +19775,10 @@ function syncFrameIndexes(document: Document): void { } for (let index = slots.frameIndexes; index < count; index++) { Object.defineProperty(slots.namedProperties, String(index), { - get: () => getDocumentFrames(document)[index]?.contentWindow ?? undefined, + get: () => { + const frame = getDocumentFrames(document)[index]; + return frame === undefined ? undefined : getFrameView(frame); + }, configurable: true, }); } @@ -19347,10 +19794,10 @@ export function setFrameWindowFactory(factory: FrameWindowFactory): void { // Removal discards it, as removal discards a browsing context. The src // attribute does nothing, because this engine performs no fetches, so a // src iframe holds about:blank, the same document a browser shows before -// navigation. Where the runtime can make a realm, the document has a -// window of its own in one, with its own interfaces and intrinsics. -// Otherwise there is no second realm: the frame's constructors are this -// realm's, and its window is a stand-in. +// navigation. The document has a window of its own. Where the runtime can +// make a realm, the window is in one, with its own interfaces and +// intrinsics; otherwise its constructors are this realm's. A window +// stands in for the frame's only where no factory builds windows. interface HTMLIFrameElementExtra extends NodeExtra { contentDocument: Document | null; contentWindow: FrameWindowLike | Window | null; @@ -19414,15 +19861,19 @@ class HTMLIFrameElement extends HTMLElement { })); } + // A document of another origin is not the iframe's document's to read. get contentDocument(): Document | null { ensureFrameDocument(this); - return _(this).extra.contentDocument; + const slots = _(this); + const window = slots.extra.contentWindow; + return implementsInterface(window, Window) && + getWindowOrigin(window) !== getDocumentOrigin(slots.document) + ? null + : slots.extra.contentDocument; } get contentWindow(): globalThis.WindowProxy | null { - ensureFrameDocument(this); - return _(this).extra.contentWindow as unknown as globalThis.WindowProxy | - null; + return getFrameView(this) as unknown as globalThis.WindowProxy | null; } getSVGDocument(): Document | null { @@ -19710,6 +20161,16 @@ function ensureFrameDocument(frame: HTMLIFrameElement): void { const built = frameWindowFactory?.(srcdoc ?? "", url, registry, parent, frame) ?? null; if (built !== null) { + const windowSlots = _(built.window); + const sandbox = getFrameSandbox(frame, parent); + windowSlots.sandbox = sandbox; + windowSlots.sandboxOrigin = + sandbox !== null && + !sandbox.has("allow-same-origin") + ? {} + : null; + // HTML names the frame's window after the iframe as it is made. + windowSlots.windowName = getAttributeValue(frame, "name") ?? ""; frameSlots.extra.contentDocument = built.document; frameSlots.extra.contentWindow = built.window; ensureFrameRenderer(frame); @@ -30988,8 +31449,8 @@ function removeNameEntry( } // The elements whose name attribute names them on the Window, as the HTML -// Standard lists them. -const NAMED_BY_NAME = new Set(["embed", "form", "img", "object"]); +// Standard lists them, and the iframe, whose name names its frame. +const NAMED_BY_NAME = new Set(["embed", "form", "iframe", "img", "object"]); function isNamedByName(element: Element): boolean { const elementSlots = _(element); @@ -39628,20 +40089,40 @@ function getLocationURL(location: Location): URL | null { return parseURL(location.href); } -// HTML's Location-object navigate. The URL resolves against the -// document's base URL. function navigateLocation( location: Location, value: string | URL, historyHandling: globalThis.NavigationHistoryBehavior, ): void { - const document = _(location).locationWindow.document as unknown as Document; + const window = _(location).locationWindow; + navigateWindow(getIncumbentWindow(window), window, value, historyHandling); +} + +/** + * HTML's Location-object navigate of `target`, by code of `source`, or of + * a window the engine cannot tell where that is null. The URL resolves + * against the base URL of the source's document, and the source's sandbox + * may forbid it. + */ +function navigateWindow( + source: Window | null, + target: Window, + value: string | URL, + historyHandling: globalThis.NavigationHistoryBehavior, +): void { + const document = target.document as unknown as Document; const url = typeof value === "string" - ? parseURL(value, getDocumentBaseURL(document)) + ? parseURL(value, getDocumentBaseURL((source ?? target).document)) : value; if (url === null) { throw domError("SyntaxError", `"${value}" is not a URL`); } + if (source !== null && !isAllowedToNavigate(source, target)) { + throw domError( + "SecurityError", + "The frame's sandbox does not allow it to navigate this window", + ); + } if (!navigateDocument(document, url, {historyHandling})) { throw failNavigation(document); } @@ -41480,15 +41961,28 @@ function syncNamedProperty(document: Document, name: string): void { } } -// The one element a name picks out, or all of them, live, when several do. +// The window of the first frame a name names, in tree order, or else the +// one element it picks out, or a live collection when several share it. function getNamedPropertyValue( document: Document, name: string, -): Element | HTMLCollection | undefined { +): Element | HTMLCollection | FrameWindowLike | Window | undefined { const documentSlots = _(document); + const named = documentSlots.extra.nameMap.get(name) ?? []; + if ( + named.some((element) => implementsInterface(element, HTMLIFrameElement)) + ) { + const frame = getDocumentFrames(document).find((each) => + getAttributeValue(each, "name") === name); + const view = frame === undefined ? null : getFrameView(frame); + if (view !== null) { + return view; + } + } const elements = new Set([ ...documentSlots.extra.idMap.get(name) ?? [], - ...documentSlots.extra.nameMap.get(name) ?? [], + ...named.filter((element) => + !implementsInterface(element, HTMLIFrameElement)), ]); if (elements.size === 0) { return undefined; @@ -41505,7 +41999,8 @@ function getNamedPropertyValue( null, (element) => getAttributeValue(element, "id") === name || - getExposedName(element) === name, + (getExposedName(element) === name && + !implementsInterface(element, HTMLIFrameElement)), ); cache.set(key, collection); } @@ -41929,6 +42424,13 @@ export interface WindowSlots extends EventTargetSlots { parentWindow: Window | null; frameOwner: HTMLIFrameElement | null; realm: Realm | null; + // A sandboxed frame's: the sandbox it was made under, and the opaque + // origin it has where the sandbox lacks allow-same-origin. + sandbox: ReadonlySet | null; + sandboxOrigin: object | null; + // The cross-origin WindowProxy each window of another origin holds this + // one by. + crossOriginViews?: WeakMap; // A frame's window whose iframe left the page or showed another // document. discarded: boolean; @@ -42206,15 +42708,15 @@ export class Window extends EventTarget { // is defined on the object, and node:vm makes a field defined on a // realm's global read-only, which a frame's window is. declare readonly document: Document; - constructor(document: Document) { + constructor(document: Document, frame: HTMLIFrameElement | null = null) { super(); this.document = document; // Attaching a document gives it a defaultView, and the attached // document is the one bare node constructors use. const documentSlots = _(document); documentSlots.extra.defaultView = this; - // A frame's window is its realm's, and leaves the top window's be. - if (getActiveRealm() === null) { + // A frame's window leaves the top window's be. + if (frame === null && getActiveRealm() === null) { ambientDocument = document; } const slots = _(this); @@ -42223,8 +42725,10 @@ export class Window extends EventTarget { ) as Record; Object.setPrototypeOf(this, slots.namedProperties); slots.parentWindow = null; - slots.frameOwner = null; + slots.frameOwner = frame; slots.realm = null; + slots.sandbox = null; + slots.sandboxOrigin = null; slots.discarded = false; slots.frameIndexes = 0; for (const name of new Set([ @@ -42398,8 +42902,13 @@ export class Window extends EventTarget { return EXTERNAL; } + // An iframe in a document of another origin is not the frame's to see. get frameElement(): globalThis.Element | null { - return _(this).frameOwner; + const frame = _(this).frameOwner; + return frame !== null && + getDocumentOrigin(_(frame).document) === getWindowOrigin(this) + ? frame + : null; } get frames(): Window { @@ -42472,7 +42981,8 @@ export class Window extends EventTarget { } get parent(): Window { - return _(this).parentWindow ?? this; + const parent = _(this).parentWindow; + return parent === null ? this : viewWindow(this, parent); } get screen(): globalThis.Screen { @@ -42505,7 +43015,7 @@ export class Window extends EventTarget { } get top(): Window | null { - return getTopWindow(this); + return viewWindow(this, getTopWindow(this)); } get visualViewport(): globalThis.VisualViewport | null { @@ -42520,15 +43030,8 @@ export class Window extends EventTarget { return true; } - // A frame showing srcdoc or about:blank has the origin of the window it - // is in, as HTML gives such a document its creator's. get origin(): string { - const url = this.document.URL; - const parent = _(this).parentWindow; - if (parent !== null && (url === "about:srcdoc" || url === "about:blank")) { - return parent.origin; - } - return parseURL(url)?.origin ?? "null"; + return serializeOrigin(getWindowOrigin(this)); } get localStorage(): Storage { @@ -42775,11 +43278,9 @@ export class Window extends EventTarget { return null; } - // HTML's window post message steps: the message is a clone made in this - // window's realm, from the window whose code posted it, which is the + // The message is from the window whose code posted it, which is the // realm a frame's binding was called from, or the realm running when a - // top window's is. It lands only if this window's origin is the one - // the poster named. + // top window's is. postMessage( message: any, targetOrigin: string, @@ -42787,51 +43288,12 @@ export class Window extends EventTarget { ): void; postMessage(message: any, options?: globalThis.WindowPostMessageOptions): void; postMessage(message: any, settings?: unknown): void { - const slots = _(this); - const callerRealm = slots.realm !== null - ? getCallerRealm() - : getIncumbentRealm(); - const source = callerRealm !== null - ? callerRealm.global as unknown as Window - : getTopWindow(this); - const named = typeof settings === "object" && settings !== null - ? (settings as {targetOrigin?: unknown}).targetOrigin - : settings; - let targetOrigin = named === undefined ? "/" : String(named); - if (targetOrigin === "/") { - targetOrigin = source.origin; - } else if (targetOrigin !== "*") { - const parsed = parseURL(targetOrigin); - if (parsed === null) { - throw domError( - "SyntaxError", - `Failed to execute 'postMessage' on 'Window': Invalid target origin '${targetOrigin}'.`, - ); - } - targetOrigin = parsed.origin; - } - const realm = slots.realm; - const data = runInRealm(realm, () => { - const clone = cloneStructured( - message, - "execute 'postMessage' on 'Window'", - ); - return realm === null ? clone : rehomeClone(clone, realm); - }); - const origin = source.origin; - queueWindowTask(this, () => { - if (targetOrigin !== "*" && targetOrigin !== this.origin) { - return; - } - const event = runInRealm(realm, () => - constructInternal(() => - new MessageEvent("message", { - data, - origin, - source: source as unknown as globalThis.MessageEventSource, - }))); - dispatch(this, event); - }); + postWindowMessage( + this, + getIncumbentWindow(this) ?? getTopWindow(this), + message, + settings, + ); } print(): void {} @@ -43246,6 +43708,57 @@ export function getProcessTimers(window: Window): Record { return _(window).processTimers!; } +/** + * HTML's window post message steps, for a message `source` posts to + * `target`: a clone made in the target's realm, which lands as a task, + * and only where the target's origin is the one the poster named. Its + * source is the poster as the target's code holds it. + */ +function postWindowMessage( + target: Window, + source: Window, + message: unknown, + settings: unknown, +): void { + const named = typeof settings === "object" && settings !== null + ? (settings as {targetOrigin?: unknown}).targetOrigin + : settings; + const text = named === undefined ? "/" : String(named); + let targetOrigin: Origin | null = null; + if (text === "/") { + targetOrigin = getWindowOrigin(source); + } else if (text !== "*") { + const parsed = parseURL(text); + if (parsed === null) { + throw domError( + "SyntaxError", + `Failed to execute 'postMessage' on 'Window': Invalid target origin '${text}'.`, + ); + } + targetOrigin = getURLOrigin(parsed.href, {}); + } + const realm = _(target).realm; + const data = runInRealm(realm, () => { + const clone = cloneStructured(message, "execute 'postMessage' on 'Window'"); + return realm === null ? clone : rehomeClone(clone, realm); + }); + const origin = serializeOrigin(getWindowOrigin(source)); + const eventSource = viewWindow(target, source); + queueWindowTask(target, () => { + if (targetOrigin !== null && targetOrigin !== getWindowOrigin(target)) { + return; + } + const event = runInRealm(realm, () => + constructInternal(() => + new MessageEvent("message", { + data, + origin, + source: eventSource as unknown as globalThis.MessageEventSource, + }))); + dispatch(target, event); + }); +} + function queueWindowTask(window: Window, task: () => void): void { const tasks = _(window).tasks ??= new Set(); const handle = runtime.setTimeout(() => { diff --git a/src/internal/window.ts b/src/internal/window.ts index 176d16c2..bc61d287 100644 --- a/src/internal/window.ts +++ b/src/internal/window.ts @@ -51,23 +51,24 @@ import { // A window starts with its interfaces and the timers any script expects // to find. The display fills in the rest (sizing, scrolling, animation -// frames, the clipboard) as it mounts the document. A frame's window is -// its realm's global object, with the realm's interfaces, and its timers -// run with the realm active. +// frames, the clipboard) as it mounts the document. A frame's window in a +// realm is the realm's global object, with the realm's interfaces, and +// its timers run with the realm active. export function buildWindow( document: Document, realm: Realm | null = null, + frame: ConstructorParameters[1] = null, ): Window { let window: Record; if (realm === null) { - window = new Window(document) as unknown as Record; + window = new Window(document, frame) as unknown as Record; } else { // The window keeps the prototype it is built with under its named // properties, so it takes the realm's first. Object.setPrototypeOf(realm.global, realm.prototypes.get(Window)!); window = runInRealm(realm, () => - constructOnto(realm.global, () => new Window(document))) as unknown as - Record; + constructOnto(realm.global, () => new Window(document, frame))) as + unknown as Record; } // HTML reports an exception a timer or a microtask lets escape, as it // does a listener's, and the page goes on. The runtime's own would end @@ -251,21 +252,20 @@ export function getInterfaceObjects(): ReadonlyMap { } // A frame's document and window, built in a realm of their own where the -// runtime can make one. Its handler attributes stay inert, as a frame's -// did before it had a realm, and its requests are the window's it is in: -// held to the same policy, and offered to the same fetch listeners. +// runtime can make one, and where it cannot, in the engine's, sharing its +// interfaces and intrinsics. Its handler attributes stay inert, and its +// requests are those of the window it is in: held to its policy, and +// offered to its fetch listeners. setFrameWindowFactory((source, url, registry, parent, frame) => { const realm = createRealm(); - if (realm === null) { - return null; - } return runInRealm(realm, () => { const document = parseHTMLDocument(source, url, true, registry); - realm.document = document; - const window = buildWindow(document, realm); + if (realm !== null) { + realm.document = document; + } + const window = buildWindow(document, realm, frame); const windowSlots = _(window); windowSlots.parentWindow = parent; - windowSlots.frameOwner = frame; windowSlots.realm = realm; const loader = parent === null ? null : getDocumentLoader(parent); if (loader !== null) { diff --git a/tests/frame-origins.test.ts b/tests/frame-origins.test.ts new file mode 100644 index 00000000..85f97207 --- /dev/null +++ b/tests/frame-origins.test.ts @@ -0,0 +1,312 @@ +/** + * Frames and their origins. + * + * A frame showing srcdoc or about:blank has the origin of the document + * that made it. A sandbox without allow-same-origin gives the frame an + * opaque origin of its own, and windows of two origins hold each other + * by HTML's cross-origin WindowProxy, which lets through only what HTML + * lists. postMessage carries messages between them, and a frame may send + * its parent to another page through the parent's location. + */ +import {spawn} from "node:child_process"; + +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {getDrawnFrameDocument} from "../src/internal/dom.ts"; +import {MockProcess, until} from "./test-utils.ts"; + +function created(): TermDOM { + return new TermDOM({ + transport: new MockProcess().transport, + url: "https://example.com/inbox", + }); +} + +function addFrame( + dom: TermDOM, + attributes: Record = {}, +): HTMLIFrameElement { + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("srcdoc", "

hi

"); + for (const [name, value] of Object.entries(attributes)) { + iframe.setAttribute(name, value); + } + dom.document.body.append(iframe); + return iframe; +} + +// The frame's own window, as its own code holds it, which a frame of +// another origin does not hand to its parent. +function inside(iframe: HTMLIFrameElement): any { + void iframe.contentWindow; + return (getDrawnFrameDocument(iframe as any) as any).defaultView; +} + +function errorName(run: () => unknown): string | null { + try { + run(); + return null; + } catch (error) { + return (error as Error).name; + } +} + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +test("a srcdoc frame and an about:blank one have their parent's origin", () => { + const dom = created(); + const srcdoc = addFrame(dom); + const blank = dom.document.createElement("iframe"); + dom.document.body.append(blank); + for (const iframe of [srcdoc, blank]) { + const frame = iframe.contentWindow as any; + expect(frame.origin).toBe("https://example.com"); + expect(iframe.contentDocument).not.toBe(null); + expect(frame.document).toBe(iframe.contentDocument); + expect(frame.parent).toBe(dom.window); + expect(frame.frameElement).toBe(iframe); + } + dom.dispose(); +}); + +test("a sandbox with allow-same-origin keeps the parent's origin", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-same-origin allow-scripts"}); + const frame = iframe.contentWindow as any; + expect(frame.origin).toBe("https://example.com"); + expect(iframe.contentDocument).not.toBe(null); + expect(frame.getSelection()).not.toBe(null); + expect(inside(iframe).parent).toBe(dom.window); + dom.dispose(); +}); + +test("a sandboxed frame has an opaque origin and no document to its parent", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts", name: "box"}); + const frame = iframe.contentWindow as any; + expect(iframe.contentDocument).toBe(null); + expect(iframe.getSVGDocument()).toBe(null); + expect(inside(iframe).origin).toBe("null"); + expect(frame).toBe(iframe.contentWindow); + expect(frame).not.toBe(inside(iframe)); + expect((dom.window as any)[0]).toBe(frame); + expect(dom.window.frames[0]).toBe(frame); + expect((dom.window as any).box).toBe(frame); + dom.dispose(); +}); + +test("a cross-origin window lets through only what HTML lists", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: ""}); + const frame = iframe.contentWindow as any; + expect(frame.window).toBe(frame); + expect(frame.self).toBe(frame); + expect(frame.frames).toBe(frame); + expect(frame.parent).toBe(dom.window); + expect(frame.top).toBe(dom.window); + expect(frame.opener).toBe(null); + expect(frame.closed).toBe(false); + expect(frame.length).toBe(0); + expect(typeof frame.postMessage).toBe("function"); + expect(frame.postMessage).toBe(frame.postMessage); + expect(frame.location).toBe(frame.location); + expect(frame.then).toBe(undefined); + expect(Object.getPrototypeOf(frame)).toBe(null); + for (const read of [ + () => frame.document, + () => frame.getSelection(), + () => frame.origin, + () => frame.name, + () => frame[0], + () => "document" in frame, + () => frame.location.href, + () => frame.location.reload(), + ]) { + expect(errorName(read)).toBe("SecurityError"); + } + expect( + errorName(() => { + frame.name = "x"; + }), + ).toBe("SecurityError"); + expect(errorName(() => Object.defineProperty(frame, "x", {value: 1}))) + .toBe("SecurityError"); + expect(typeof frame.location.replace).toBe("function"); + dom.dispose(); +}); + +test("a sandboxed frame holds its parent as a window of another origin", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + expect(frame.parent).not.toBe(dom.window); + expect(frame.parent).toBe(frame.parent); + expect(frame.top).toBe(frame.parent); + expect(frame.frameElement).toBe(null); + expect(errorName(() => frame.parent.document)).toBe("SecurityError"); + expect(frame.parent.frames[0]).toBe(frame); + dom.dispose(); +}); + +test("a frame of a sandboxed frame is sandboxed too", () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + const inner = frame.document.createElement("iframe"); + inner.setAttribute("sandbox", "allow-same-origin"); + frame.document.body.append(inner); + expect(inner.contentDocument).toBe(null); + expect(errorName(() => inner.contentWindow.origin)).toBe("SecurityError"); + const plain = frame.document.createElement("iframe"); + frame.document.body.append(plain); + expect(plain.contentDocument).toBe(null); + dom.dispose(); +}); + +test("messages cross between a page and its sandboxed frame", async () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const outer = iframe.contentWindow as any; + const frame = inside(iframe); + const heard: unknown[] = []; + dom.window.addEventListener("message", (event) => { + heard.push(["page", event.data, event.origin, event.source === outer]); + (event.source as any).postMessage("pong", "*"); + }); + frame.addEventListener("message", (event: MessageEvent) => { + heard.push([ + "frame", + event.data, + event.origin, + event.source === frame.parent, + ]); + }); + frame.parent.postMessage("ping", "*"); + expect(heard).toEqual([]); + await until(() => heard.length === 2); + expect(heard).toEqual([ + ["page", "ping", "null", true], + ["frame", "pong", "https://example.com", true], + ]); + dom.dispose(); +}); + +test("a message lands only at the origin its poster names", async () => { + const dom = created(); + const iframe = addFrame(dom, {sandbox: "allow-scripts"}); + const frame = inside(iframe); + const heard: string[] = []; + frame.addEventListener("message", (event: MessageEvent) => { + heard.push(`frame ${event.data}`); + }); + dom.window.addEventListener("message", (event) => { + heard.push(`page ${event.data}`); + }); + const outer = iframe.contentWindow as any; + outer.postMessage("named", "https://example.com"); + outer.postMessage("own", "/"); + outer.postMessage("any", "*"); + frame.parent.postMessage("to the page", "https://example.com"); + frame.parent.postMessage("to another", "https://elsewhere.example"); + frame.parent.postMessage("to its own", "/"); + expect(errorName(() => outer.postMessage("x", "not a url"))) + .toBe("SyntaxError"); + await tick(); + await tick(); + expect(heard.sort()).toEqual(["frame any", "page to the page"]); + dom.dispose(); +}); + +test("a frame sends its parent to another page through its location", async () => { + const dom = created(); + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("src", "/post3.html"); + dom.document.body.append(iframe); + const frame = iframe.contentWindow as any; + const destinations: string[] = []; + dom.window.navigation.addEventListener("navigate", (event) => { + destinations.push(event.destination.url); + event.preventDefault(); + }); + frame.addEventListener("message", (event: MessageEvent) => { + if (event.source === frame.parent) { + frame.parent.window.location.href = event.data.slice(4); + } + }); + frame.postMessage("ddg:https://example.org/result", dom.window.origin); + await until(() => destinations.length > 0); + expect(destinations).toEqual(["https://example.org/result"]); + dom.dispose(); +}); + +test("a navigation of the parent no listener takes still fails", () => { + const dom = created(); + const frame = addFrame(dom).contentWindow as any; + expect( + errorName(() => { + frame.parent.location.href = "https://example.org/"; + }), + ).toBe("NotSupportedError"); + dom.dispose(); +}); + +test("a sandbox lets a frame navigate its top window only where it says so", () => { + const dom = created(); + const destinations: string[] = []; + dom.window.navigation.addEventListener("navigate", (event) => { + destinations.push(event.destination.url); + event.preventDefault(); + }); + const barred = inside(addFrame(dom, {sandbox: "allow-scripts"})); + expect( + errorName(() => { + barred.parent.location.href = "https://example.org/barred"; + }), + ).toBe("SecurityError"); + const allowed = inside(addFrame(dom, {sandbox: "allow-top-navigation"})); + allowed.parent.location.href = "https://example.org/href"; + allowed.parent.location = "https://example.org/location"; + allowed.top.location.replace("https://example.org/replace"); + expect(destinations).toEqual([ + "https://example.org/href", + "https://example.org/location", + "https://example.org/replace", + ]); + dom.dispose(); +}); + +const bun = (globalThis as {Bun?: unknown}).Bun === undefined + ? null + : process.execPath; + +// Where the runtime has no node:vm, as in isolated-vm, a frame's window +// is built in the engine's realm, and is a whole window still. +(bun === null ? test.skip : test)( + "without node:vm, a frame has a window that posts and navigates", + async () => { + const script = new URL("./frames-without-vm.ts", import.meta.url).pathname; + const output = await new Promise((resolve) => { + const child = spawn(bun!, [script], {stdio: ["ignore", "pipe", "pipe"]}); + let text = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + text += chunk; + }); + child.stderr.pipe(process.stderr); + child.on("close", () => resolve(text)); + }); + expect(JSON.parse(output)).toEqual({ + realms: false, + postMessage: "function", + parent: true, + top: true, + frameElement: true, + location: "about:blank", + origin: "https://duckduckgo.com", + sandboxedDocument: null, + heard: ["ddg:https://example.org/result", "https://duckduckgo.com", true], + navigated: "https://example.org/result", + }); + }, +); diff --git a/tests/frames-without-vm.ts b/tests/frames-without-vm.ts new file mode 100644 index 00000000..f5430259 --- /dev/null +++ b/tests/frames-without-vm.ts @@ -0,0 +1,63 @@ +/** + * Runs DuckDuckGo's result click, a message to a hidden frame that sends + * the page to the result, where the runtime has no node:vm, as in + * isolated-vm. Prints what the frame's window had and heard, as JSON. + * The engine looks for node:vm the first time a frame is made, so the + * runtime's has to be hidden before the engine loads. + * + * bun tests/frames-without-vm.ts + */ +const getBuiltinModule = process.getBuiltinModule.bind(process); +Object.defineProperty(process, "getBuiltinModule", { + value: (id: string) => + id === "node:vm" || id === "vm" ? undefined : getBuiltinModule(id), + configurable: true, +}); + +const {TermDOM} = await import("../src/index.ts"); +const {canCreateRealms} = await import("../src/internal/realms.ts"); +const {MockProcess, until} = await import("./test-utils.ts"); + +const dom = new TermDOM({ + transport: new MockProcess().transport, + url: "https://duckduckgo.com/?q=termdom", +}); +const iframe = dom.document.createElement("iframe"); +iframe.setAttribute("src", "/post3.html"); +iframe.style.display = "none"; +dom.document.body.append(iframe); +const frame = iframe.contentWindow as any; +const sandboxed = dom.document.createElement("iframe"); +sandboxed.setAttribute("sandbox", "allow-scripts"); +dom.document.body.append(sandboxed); + +let heard: unknown[] = []; +let navigated = ""; +dom.window.navigation.addEventListener("navigate", (event) => { + navigated = event.destination.url; + event.preventDefault(); +}); +frame.addEventListener("message", (event: MessageEvent) => { + heard = [event.data, event.origin, event.source === frame.parent]; + if (event.source === frame.parent) { + frame.parent.window.location.href = event.data.slice(4); + } +}); +frame.postMessage("ddg:https://example.org/result", dom.window.origin); +await until(() => navigated !== ""); + +process.stdout.write( + JSON.stringify({ + realms: canCreateRealms(), + postMessage: typeof frame.postMessage, + parent: frame.parent === dom.window, + top: frame.top === dom.window, + frameElement: frame.frameElement === iframe, + location: frame.location.href, + origin: frame.origin, + sandboxedDocument: sandboxed.contentDocument, + heard, + navigated, + }), +); +await dom.dispose(); diff --git a/tests/iframe-realms.test.ts b/tests/iframe-realms.test.ts index a8887600..fa1daba7 100644 --- a/tests/iframe-realms.test.ts +++ b/tests/iframe-realms.test.ts @@ -12,6 +12,7 @@ import {expect, test} from "@b9g/libuild/test"; import {TermDOM} from "../src/index.ts"; +import {getDrawnFrameDocument} from "../src/internal/dom.ts"; import {canCreateRealms} from "../src/internal/realms.ts"; import {MockProcess, until} from "./test-utils.ts"; @@ -269,6 +270,33 @@ withRealms( }, ); +withRealms( + "a sandboxed frame's code holds its parent as a window of another origin", + async () => { + const dom = new TermDOM({ + transport: new MockProcess().transport, + url: "https://example.com/inbox", + }); + const iframe = dom.document.createElement("iframe"); + iframe.setAttribute("sandbox", "allow-scripts"); + dom.document.body.append(iframe); + const outer = iframe.contentWindow as any; + const frame = (getDrawnFrameDocument(iframe as any) as any).defaultView; + expect( + frame.eval("try { parent.document } catch (error) { error.name }"), + ).toBe("SecurityError"); + expect(frame.eval("parent === top && parent !== window")).toBe(true); + const heard: unknown[] = []; + dom.window.addEventListener("message", (event) => { + heard.push([event.data, event.origin, event.source === outer]); + }); + frame.eval("setTimeout(() => parent.postMessage('ping', '*'), 0)"); + await until(() => heard.length > 0); + expect(heard).toEqual([["ping", "null", true]]); + dom.dispose(); + }, +); + withRealms("a message for another origin does not land", async () => { const {dom, frame} = setup(); let heard = false; From ce8a6c273f00aec234ea0df97693fc0e9fc12cb1 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Sun, 8 Nov 2026 21:23:16 -0500 Subject: [PATCH 02/25] Describe frames, their origins and postMessage in the guide The guides said nothing about iframes. A reader needs to know that a frame's src is not loaded, where a frame gets a realm of its own, what a sandbox does to its origin, what a window of another origin lets through, and how messages and a parent's navigation cross between frames. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- docs/guides/06-images-and-canvas.md | 72 ++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index 331d315a..06baf1ab 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -1,6 +1,6 @@ --- title: Images and canvas -description: How and draw pixels, and how runs a program. +description: How and draw pixels, how `; + const frame = dom.document.querySelector("iframe")!; + let loads = 0; + frame.addEventListener("load", () => loads++); + await settle(dom); + await until(() => frames.length === 1); + expect(frames[0].init).toMatchObject({ + url: "https://frame.example/a", + html: "

framed

", + cols: 12, + rows: 3, + scripting: false, + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(loads).toBe(0); + frames[0].post({type: "load"}); + expect(loads).toBe(1); + dom.dispose(); +}); + +test("the cells a frame paints are drawn in its box, without control characters", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post(paintText(["inside", "a\x1b[2Jb"], 12)); + await settle(dom); + expect(rows(terminal, 5)).toEqual([ + "┌────────────┐", + "│inside │", + "│a [2Jb │", + "│ │", + "└────────────┘", + ]); + dom.dispose(); +}); + +test("a frame's cells claim no columns their text does not take", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + const message = paintText(["abc"], 12) as Extract< + FrameMessage, + {type: "paint"} + >; + message.cells.attrs[0] |= 0x1f << 9; + message.cells.cluster[1] = 0x110000; + message.cells.graphemes.push([0x8000_0001, "\x07"]); + message.cells.cluster[2] = 0x8000_0001; + frames[0].post(message); + await settle(dom); + expect(rows(terminal, 2)[1]).toBe("│a │"); + dom.dispose(); +}); + +test("a click focuses the frame, and its keys and mouse go there in its own cells", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await dom.attach(); + await settle(dom); + await until(() => frames.length === 1); + const frame = dom.document.querySelector("iframe")!; + let parentKeys = 0; + dom.document.addEventListener("keypress", () => parentKeys++); + // The frame's third column on its second row, inside the border. + terminal.stdin.simulateResponse("\x1b[<0;4;3M\x1b[<0;4;3m"); + await inputDispatched(); + await settle(dom); + expect(dom.document.activeElement).toBe(frame); + terminal.stdin.simulateResponse("x"); + await inputDispatched(); + const items = frames[0].sent + .filter((message) => message.type === "input") + .map((message) => message.item); + expect(items).toContainEqual({ + kind: "mouse", + button: 0, + col: 2, + row: 1, + release: false, + ticks: 1, + }); + expect(items).toContainEqual({kind: "focus", focused: true}); + expect(items).toContainEqual([ + expect.objectContaining({kind: "key", key: "x"}), + ]); + expect(parentKeys).toBe(0); + dom.dispose(); +}); + +test("the page and the frame reach each other only through messages", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + url: "https://page.example/", + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + await settle(dom); + await until(() => frames.length === 1); + expect(frame.contentDocument).toBe(null); + expect(() => (frame.contentWindow as any).document).toThrow(); + frame.contentWindow!.postMessage({hello: 1}, "https://frame.example"); + expect(frames[0].sent).toContainEqual({ + type: "message", + data: {hello: 1}, + origin: "https://page.example", + targetOrigin: "https://frame.example", + }); + const received: any[] = []; + dom.window.addEventListener("message", (event: MessageEvent) => { + received.push([ + event.data, + event.origin, + event.source === frame.contentWindow, + ]); + }); + frames[0].post({ + type: "message", + data: "elsewhere", + targetOrigin: "https://other.example", + }); + frames[0].post({type: "message", data: "back", targetOrigin: "*"}); + await until(() => received.length > 0); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(received).toEqual([["back", "https://frame.example", true]]); + dom.dispose(); +}); + +test("a frame's loads go through the page's fetch listeners, without forbidden headers", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + isolatedFrames: isolate, + }); + const headers: Array<[string, string]> = []; + dom.addEventListener("fetch", (event: any) => { + if (event.request.url === "https://frame.example/") { + event.respondWith(new Response("")); + } else if (event.request.url === "https://frame.example/data.json") { + event.request.headers.forEach((value: string, name: string) => { + headers.push([name, value]); + }); + event.respondWith(new Response("{}", {status: 201})); + } + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({ + type: "fetch", + id: 1, + request: { + url: "https://frame.example/data.json", + method: "GET", + headers: [["x-asked", "yes"], ["cookie", "stolen=1"]], + body: null, + redirect: "follow", + destination: "", + referrer: "", + }, + }); + frames[0].post({ + type: "fetch", + id: 2, + request: { + url: "file:///etc/passwd", + method: "GET", + headers: [], + body: null, + redirect: "follow", + destination: "", + referrer: "", + }, + }); + await until(() => frames[0].sent.length >= 2); + expect(headers).toEqual([["x-asked", "yes"]]); + const response = frames[0].sent.find( + (message) => message.type === "response", + ); + expect(response).toMatchObject({type: "response", id: 1}); + expect(new TextDecoder().decode((response as any).response.body)).toBe("{}"); + expect((response as any).response.status).toBe(201); + expect(frames[0].sent).toContainEqual({ + type: "fetchError", + id: 2, + message: "Failed to fetch", + }); + dom.dispose(); +}); + +test("a frame-src policy keeps a frame's document from loading", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + csp: "frame-src https://allowed.example", + isolatedFrames: isolate, + }); + const asked = answerPages(dom, { + "https://allowed.example/": "

allowed

", + "https://blocked.example/": "

blocked

", + }); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 2); + expect(asked).toEqual(["https://allowed.example/"]); + expect( + frames + .map((frame) => [frame.init.url, frame.init.html.includes("

")]) + .sort(), + ).toEqual([ + ["https://allowed.example/", true], + ["https://blocked.example/", false], + ]); + dom.dispose(); +}); + +test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goes", async () => { + const {frames, isolate} = fakeIsolator(); + const dom = new TermDOM({ + transport: new MockProcess({cols: 30, rows: 8}).transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + const [local, isolated] = dom.document.querySelectorAll("iframe"); + expect(local.contentDocument!.getElementById("here")).not.toBe(null); + isolated.remove(); + expect(frames[0].disposed).toBe(true); + dom.dispose(); +}); + +test("isolatedFrames takes \"none\" or a function", () => { + expect(() => new TermDOM({isolatedFrames: "auto" as any})).toThrow(TypeError); +}); From a55d50c5a69bc15e4e8e107c134256d0bb6b17c0 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:30:54 -0500 Subject: [PATCH 05/25] Show a frame's document from an isolate of its own The runtime a bare V8 isolate needs before TermDOM loads in it: timers, events, text encoding, Blob and FormData, fetch through the host, decompression, streams, crypto and console, each from a plain callback the host provides. The frame entry builds the document from its markup, paints it with createFrameEngine and posts the cells, and dispatches the input, messages and responses the host sends it. A blank window with the page's origin stands in for the frame's parent, so parent, top, postMessage's origin check and parent.location go through the engine's own cross-origin windows. What the frame posts to it, or navigates it to, goes to the host. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- bun.lock | 9 + package.json | 3 + src/internal/isolate/blob.ts | 296 +++++++++++++ src/internal/isolate/compression.ts | 139 ++++++ src/internal/isolate/console.ts | 60 +++ src/internal/isolate/encoding.ts | 252 +++++++++++ src/internal/isolate/events.ts | 480 ++++++++++++++++++++ src/internal/isolate/fetch.ts | 661 ++++++++++++++++++++++++++++ src/internal/isolate/frame.ts | 250 +++++++++++ src/internal/isolate/host.ts | 106 +++++ src/internal/isolate/install.ts | 128 ++++++ src/internal/isolate/network.ts | 88 ++++ src/internal/isolate/timers.ts | 132 ++++++ src/internal/isolate/vendor.d.ts | 27 ++ 14 files changed, 2631 insertions(+) create mode 100644 src/internal/isolate/blob.ts create mode 100644 src/internal/isolate/compression.ts create mode 100644 src/internal/isolate/console.ts create mode 100644 src/internal/isolate/encoding.ts create mode 100644 src/internal/isolate/events.ts create mode 100644 src/internal/isolate/fetch.ts create mode 100644 src/internal/isolate/frame.ts create mode 100644 src/internal/isolate/host.ts create mode 100644 src/internal/isolate/install.ts create mode 100644 src/internal/isolate/network.ts create mode 100644 src/internal/isolate/timers.ts create mode 100644 src/internal/isolate/vendor.d.ts diff --git a/bun.lock b/bun.lock index 2b419093..2db96789 100644 --- a/bun.lock +++ b/bun.lock @@ -30,11 +30,13 @@ "@webref/idl": "^3.84.0", "@xterm/headless": "^6", "codemirror": "^6.0.2", + "core-js-pure": "3.50.0", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", "eslint-plugin-esfold": "^0.1.14", "fast-check": "^4.10.2", + "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", "katex": "^0.18.9", @@ -49,6 +51,7 @@ "tsx": "^4.23.15", "typescript": "~6.0.3", "vue": "^3.5.43", + "web-streams-polyfill": "4.3.0", "webidl2": "^24.5.0", }, "peerDependencies": { @@ -346,6 +349,8 @@ "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "core-js-pure": ["core-js-pure@3.50.0", "", {}, "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA=="], + "cpu-features": ["cpu-features@0.0.10", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="], "crelt": ["crelt@1.0.7", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="], @@ -412,6 +417,8 @@ "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], + "file-entry-cache": ["file-entry-cache@11.1.5", "", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="], "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], @@ -606,6 +613,8 @@ "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], + "web-streams-polyfill": ["web-streams-polyfill@4.3.0", "", {}, "sha512-/Gnggvj9oSrEvJbDyyPtAnxBt5fGQM2iWOKQNu7ie1OxDgK40iZpyV3TKaRiEzVj1oA1UxKnEy9XPXh6PW3eVw=="], + "webidl2": ["webidl2@24.5.0", "", {}, "sha512-fxOigKkIem1iAgQ9t4cFOP+kWEA8y6Be/uh50FpJh0FijoeeT/VMrOyJzNLUgjy0rGMEcHeReKDCqj0g9dIe9A=="], "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], diff --git a/package.json b/package.json index ffd24df0..d421b06c 100644 --- a/package.json +++ b/package.json @@ -83,11 +83,13 @@ "@webref/idl": "^3.84.0", "@xterm/headless": "^6", "codemirror": "^6.0.2", + "core-js-pure": "3.50.0", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", "eslint-plugin-esfold": "^0.1.14", "fast-check": "^4.10.2", + "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", "katex": "^0.18.9", @@ -102,6 +104,7 @@ "tsx": "^4.23.15", "typescript": "~6.0.3", "vue": "^3.5.43", + "web-streams-polyfill": "4.3.0", "webidl2": "^24.5.0" }, "module": "./dist/index.js", diff --git a/src/internal/isolate/blob.ts b/src/internal/isolate/blob.ts new file mode 100644 index 00000000..8c960ea0 --- /dev/null +++ b/src/internal/isolate/blob.ts @@ -0,0 +1,296 @@ +import {ReadableStream} from "web-streams-polyfill"; + +import {encodeUTF8, TextDecoder, toBytes} from "./encoding.ts"; +import {DOMException} from "./events.ts"; + +const contents = new WeakMap(); + +function blobState(blob: object): {bytes: Uint8Array; type: string} { + const state = contents.get(blob); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +export function blobBytes(blob: Blob): Uint8Array { + return blobState(blob).bytes; +} + +export function isBlob(value: unknown): value is Blob { + return typeof value === "object" && value !== null && contents.has(value); +} + +const MAX_BLOB_URLS = 10000; +const blobURLs = new Map(); + +export function createObjectURL(object: unknown, origin: string): string { + if (!isBlob(object)) { + throw new TypeError("URL.createObjectURL needs a Blob"); + } + + if (blobURLs.size >= MAX_BLOB_URLS) { + throw new DOMException("Too many blob URLs", "QuotaExceededError"); + } + + const url = `blob:${origin}/${crypto.randomUUID()}`; + blobURLs.set(url, object); + return url; +} + +export function revokeObjectURL(url: unknown): void { + blobURLs.delete(String(url)); +} + +export function blobAt(url: string): Blob | undefined { + return blobURLs.get(url.replace(/#.*$/, "")); +} + +function normalizeType(type: unknown): string { + const text = type === undefined ? "" : String(type); + return /^[\x20-\x7e]*$/.test(text) ? text.toLowerCase() : ""; +} + +function concat(parts: Iterable): Uint8Array { + const chunks: Uint8Array[] = []; + let length = 0; + for (const part of parts) { + let chunk: Uint8Array; + if (isBlob(part)) { + chunk = blobBytes(part); + } else if (part instanceof ArrayBuffer || ArrayBuffer.isView(part)) { + chunk = toBytes(part).slice(); + } else { + chunk = encodeUTF8(String(part)); + } + + chunks.push(chunk); + length += chunk.length; + } + + const out = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.length; + } + + return out; +} + +export class Blob { + constructor(parts: Iterable = [], options: {type?: string} = {}) { + contents.set(this, { + bytes: concat(parts), + type: normalizeType(options.type), + }); + } + + get size(): number { + return blobState(this).bytes.length; + } + + get type(): string { + return blobState(this).type; + } + + slice(start = 0, end?: number, type?: string): Blob { + const bytes = blobState(this).bytes; + const size = bytes.length; + const from = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + const to = end === undefined + ? size + : end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + return new Blob([bytes.subarray(from, Math.max(from, to))], {type}); + } + + async arrayBuffer(): Promise { + return blobState(this).bytes.slice().buffer; + } + + async bytes(): Promise { + return blobState(this).bytes.slice(); + } + + async text(): Promise { + return new TextDecoder().decode(blobState(this).bytes); + } + + stream(): ReadableStream { + const bytes = blobState(this).bytes.slice(); + return new ReadableStream({ + start(controller) { + if (bytes.length > 0) { + controller.enqueue(bytes); + } + + controller.close(); + }, + }); + } +} + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: "Blob", + configurable: true, +}); + +const files = new WeakMap(); + +export class File extends Blob { + constructor( + parts: Iterable, + name: string, + options: {type?: string; lastModified?: number} = {}, + ) { + if (arguments.length < 2) { + throw new TypeError("File requires a name"); + } + + super(parts, options); + files.set(this, { + name: String(name), + lastModified: options.lastModified ?? Date.now(), + }); + } + + get name(): string { + const state = files.get(this); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state.name; + } + + get lastModified(): number { + const state = files.get(this); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state.lastModified; + } +} + +Object.defineProperty(File.prototype, Symbol.toStringTag, { + value: "File", + configurable: true, +}); + +type Entry = [string, string | File]; + +const forms = new WeakMap(); + +function formEntries(form: object): Entry[] { + const entries = forms.get(form); + if (entries === undefined) { + throw new TypeError("Illegal invocation"); + } + + return entries; +} + +function toEntry(name: string, value: unknown, filename?: string): Entry { + if (isBlob(value)) { + const file = value instanceof File && filename === undefined + ? value + : new File( + [value], + filename ?? (value instanceof File ? value.name : "blob"), + {type: value.type}, + ); + return [String(name), file]; + } + + return [String(name), String(value)]; +} + +export class FormData { + constructor(form?: unknown) { + if (form !== undefined) { + throw new TypeError("FormData from a form element is not supported here"); + } + + forms.set(this, []); + } + + append(name: string, value: unknown, filename?: string): void { + formEntries(this).push(toEntry(name, value, filename)); + } + + set(name: string, value: unknown, filename?: string): void { + const entries = formEntries(this); + const entry = toEntry(name, value, filename); + const index = entries.findIndex(([key]) => key === entry[0]); + if (index === -1) { + entries.push(entry); + return; + } + + entries.splice(index, 1, entry); + for (let i = entries.length - 1; i > index; i--) { + if (entries[i][0] === entry[0]) { + entries.splice(i, 1); + } + } + } + + delete(name: string): void { + const key = String(name); + const entries = formEntries(this); + forms.set(this, entries.filter(([k]) => k !== key)); + } + + get(name: string): string | File | null { + const key = String(name); + return formEntries(this).find(([k]) => k === key)?.[1] ?? null; + } + + getAll(name: string): Array { + const key = String(name); + return formEntries(this).filter(([k]) => k === key).map(([, v]) => v); + } + + has(name: string): boolean { + const key = String(name); + return formEntries(this).some(([k]) => k === key); + } + + forEach( + callback: (value: string | File, key: string, form: FormData) => void, + thisArg?: unknown, + ): void { + for (const [key, value] of formEntries(this).slice()) { + callback.call(thisArg, value, key, this); + } + } + + *entries(): IterableIterator { + for (const [key, value] of formEntries(this).slice()) { + yield [key, value]; + } + } + + *keys(): IterableIterator { + for (const [key] of formEntries(this).slice()) { + yield key; + } + } + + *values(): IterableIterator { + for (const [, value] of formEntries(this).slice()) { + yield value; + } + } + + [Symbol.iterator](): IterableIterator { + return this.entries(); + } +} + +Object.defineProperty(FormData.prototype, Symbol.toStringTag, { + value: "FormData", + configurable: true, +}); diff --git a/src/internal/isolate/compression.ts b/src/internal/isolate/compression.ts new file mode 100644 index 00000000..523122f6 --- /dev/null +++ b/src/internal/isolate/compression.ts @@ -0,0 +1,139 @@ +import {Gunzip, Inflate, Unzlib} from "fflate"; +import {ReadableStream, WritableStream} from "web-streams-polyfill"; + +import {toBytes} from "./encoding.ts"; + +const SLICE_BYTES = 4096; + +type Inflater = Gunzip | Inflate | Unzlib; + +function createInflater(format: string): Inflater { + switch (format) { + case "gzip": + return new Gunzip(); + case "deflate": + return new Unzlib(); + case "deflate-raw": + return new Inflate(); + default: + throw new TypeError(`Unsupported compression format: ${format}`); + } +} + +const streams = new WeakMap< + object, + {readable: ReadableStream; writable: WritableStream} +>(); + +export class DecompressionStream { + constructor(format: string) { + const inflater = createInflater(String(format)); + const input: Uint8Array[] = []; + const output: Uint8Array[] = []; + let inputDone = false; + let ended = false; + let wake: (() => void) | null = null; + const signal = (): void => { + const resume = wake; + wake = null; + resume?.(); + }; + inflater.ondata = (chunk, final) => { + if (chunk.length > 0) { + output.push(chunk); + } + + if (final) { + ended = true; + } + }; + const readable = new ReadableStream({ + async pull(controller) { + while (output.length === 0) { + if (input.length > 0) { + const chunk = input[0]; + const piece = chunk.subarray(0, SLICE_BYTES); + if (chunk.length > SLICE_BYTES) { + input[0] = chunk.subarray(SLICE_BYTES); + } else { + input.shift(); + } + + if (ended) { + controller.error(new TypeError("Junk after the compressed data")); + return; + } + + try { + inflater.push(piece, inputDone && input.length === 0); + } catch (error) { + controller.error( + new TypeError(`Decompression failed: ${String(error)}`), + ); + return; + } + } else if (inputDone) { + if (!ended) { + controller.error(new TypeError("The compressed data ends early")); + } else { + controller.close(); + } + + return; + } else { + await new Promise((resolve) => { + wake = resolve; + }); + } + } + + controller.enqueue(output.shift()!); + }, + cancel() { + input.length = 0; + output.length = 0; + inputDone = true; + signal(); + }, + }); + const writable = new WritableStream({ + write(chunk) { + input.push(toBytes(chunk)); + signal(); + }, + close() { + inputDone = true; + signal(); + }, + abort() { + input.length = 0; + inputDone = true; + signal(); + }, + }); + streams.set(this, {readable, writable}); + } + + get readable(): ReadableStream { + const pair = streams.get(this); + if (pair === undefined) { + throw new TypeError("Illegal invocation"); + } + + return pair.readable; + } + + get writable(): WritableStream { + const pair = streams.get(this); + if (pair === undefined) { + throw new TypeError("Illegal invocation"); + } + + return pair.writable; + } +} + +Object.defineProperty(DecompressionStream.prototype, Symbol.toStringTag, { + value: "DecompressionStream", + configurable: true, +}); diff --git a/src/internal/isolate/console.ts b/src/internal/isolate/console.ts new file mode 100644 index 00000000..4c61ce19 --- /dev/null +++ b/src/internal/isolate/console.ts @@ -0,0 +1,60 @@ +import {host} from "./host.ts"; + +function describe(value: unknown, depth: number): string { + if (typeof value === "string") { + return depth === 0 ? value : JSON.stringify(value); + } + + if (value instanceof Error) { + return value.stack ?? `${value.name}: ${value.message}`; + } + + if (typeof value === "function") { + return `[Function ${value.name || "(anonymous)"}]`; + } + + if (typeof value !== "object" || value === null) { + return String(value); + } + + if (depth > 2) { + return Array.isArray(value) ? "[Array]" : "[Object]"; + } + + try { + if (Array.isArray(value)) { + return `[${value.map((item) => describe(item, depth + 1)).join(", ")}]`; + } + + const entries = Object.keys(value) + .map((key) => + `${key}: ${describe((value as Record)[key], depth + 1)}`, + ); + return `{${entries.join(", ")}}`; + } catch (error) { + return `[object: ${error instanceof Error ? error.message : "unreadable"}]`; + } +} + +function format(args: unknown[]): string { + return args.map((arg) => describe(arg, 0)).join(" "); +} + +function method(level: string): (...args: unknown[]) => void { + return (...args: unknown[]): void => { + host.log(level, format(args)); + }; +} + +export const console = { + debug: method("debug"), + error: method("error"), + info: method("info"), + log: method("log"), + trace: method("debug"), + warn: method("warn"), +}; + +export function reportError(error: unknown): void { + host.log("error", format(["Uncaught", error])); +} diff --git a/src/internal/isolate/encoding.ts b/src/internal/isolate/encoding.ts new file mode 100644 index 00000000..eb0f81d6 --- /dev/null +++ b/src/internal/isolate/encoding.ts @@ -0,0 +1,252 @@ +export function toBytes(input: unknown): Uint8Array { + if (input === undefined) { + return new Uint8Array(0); + } + + if (input instanceof ArrayBuffer || input instanceof SharedArrayBuffer) { + return new Uint8Array(input); + } + + if (ArrayBuffer.isView(input)) { + return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + + throw new TypeError("The input must be an ArrayBuffer or a view of one"); +} + +export function encodeUTF8(input: string): Uint8Array { + const out = new Uint8Array(input.length * 3); + let length = 0; + for (let i = 0; i < input.length; i++) { + let code = input.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff && i + 1 < input.length) { + const next = input.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00); + i++; + } else { + code = 0xfffd; + } + } else if (code >= 0xd800 && code <= 0xdfff) { + code = 0xfffd; + } + + if (code < 0x80) { + out[length++] = code; + } else if (code < 0x800) { + out[length++] = 0xc0 | (code >> 6); + out[length++] = 0x80 | (code & 0x3f); + } else if (code < 0x10000) { + out[length++] = 0xe0 | (code >> 12); + out[length++] = 0x80 | ((code >> 6) & 0x3f); + out[length++] = 0x80 | (code & 0x3f); + } else { + out[length++] = 0xf0 | (code >> 18); + out[length++] = 0x80 | ((code >> 12) & 0x3f); + out[length++] = 0x80 | ((code >> 6) & 0x3f); + out[length++] = 0x80 | (code & 0x3f); + } + } + + return out.slice(0, length); +} + +export class TextEncoder { + get encoding(): string { + return "utf-8"; + } + + encode(input = ""): Uint8Array { + return encodeUTF8(String(input)); + } + + encodeInto( + input: string, + destination: Uint8Array, + ): {read: number; written: number} { + let read = 0; + let written = 0; + for (const char of String(input)) { + const bytes = encodeUTF8(char); + if (written + bytes.length > destination.length) { + break; + } + + destination.set(bytes, written); + written += bytes.length; + read += char.length; + } + + return {read, written}; + } +} + +Object.defineProperty(TextEncoder.prototype, Symbol.toStringTag, { + value: "TextEncoder", + configurable: true, +}); + +const LABELS = new Set(["utf-8", "utf8", "unicode-1-1-utf-8"]); + +interface DecoderState { + fatal: boolean; + ignoreBOM: boolean; + pending: number[]; + seenBOM: boolean; +} + +const decoders = new WeakMap(); + +function decoderState(decoder: object): DecoderState { + const state = decoders.get(decoder); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function stripBOM(state: DecoderState, text: string): string { + if (!state.seenBOM && text.length > 0) { + state.seenBOM = true; + if (!state.ignoreBOM && text.charCodeAt(0) === 0xfeff) { + return text.slice(1); + } + } + + return text; +} + +export class TextDecoder { + constructor( + label = "utf-8", + options: {fatal?: boolean; ignoreBOM?: boolean} = {}, + ) { + if (!LABELS.has(String(label).trim().toLowerCase())) { + throw new RangeError(`The encoding "${label}" is not supported`); + } + + decoders.set(this, { + fatal: !!options.fatal, + ignoreBOM: !!options.ignoreBOM, + pending: [], + seenBOM: false, + }); + } + + get encoding(): string { + return "utf-8"; + } + + get fatal(): boolean { + return decoderState(this).fatal; + } + + get ignoreBOM(): boolean { + return decoderState(this).ignoreBOM; + } + + decode(input?: unknown, options: {stream?: boolean} = {}): string { + const state = decoderState(this); + const fresh = toBytes(input); + const bytes = state.pending.length > 0 + ? Uint8Array.from([...state.pending, ...fresh]) + : fresh; + state.pending = []; + let out = ""; + let i = 0; + const fail = (): void => { + if (state.fatal) { + state.pending = []; + throw new TypeError("The encoded data was not valid UTF-8"); + } + + out += "�"; + }; + while (i < bytes.length) { + const byte = bytes[i]; + let need: number; + let code: number; + let lower = 0x80; + let upper = 0xbf; + if (byte < 0x80) { + out += String.fromCharCode(byte); + i++; + continue; + } else if (byte >= 0xc2 && byte <= 0xdf) { + need = 1; + code = byte & 0x1f; + } else if (byte >= 0xe0 && byte <= 0xef) { + need = 2; + code = byte & 0x0f; + if (byte === 0xe0) { + lower = 0xa0; + } else if (byte === 0xed) { + upper = 0x9f; + } + } else if (byte >= 0xf0 && byte <= 0xf4) { + need = 3; + code = byte & 0x07; + if (byte === 0xf0) { + lower = 0x90; + } else if (byte === 0xf4) { + upper = 0x8f; + } + } else { + fail(); + i++; + continue; + } + + let j = 1; + let valid = true; + for (; j <= need; j++) { + if (i + j >= bytes.length) { + break; + } + + const next = bytes[i + j]; + if (next < lower || next > upper) { + valid = false; + break; + } + + lower = 0x80; + upper = 0xbf; + code = (code << 6) | (next & 0x3f); + } + + if (valid && j <= need) { + if (options.stream) { + state.pending = Array.from(bytes.subarray(i)); + return stripBOM(state, out); + } + + fail(); + i += j; + continue; + } + + if (!valid) { + fail(); + i += j; + continue; + } + + out += String.fromCodePoint(code); + i += need + 1; + } + + const result = stripBOM(state, out); + if (!options.stream) { + state.seenBOM = false; + } + + return result; + } +} + +Object.defineProperty(TextDecoder.prototype, Symbol.toStringTag, { + value: "TextDecoder", + configurable: true, +}); diff --git a/src/internal/isolate/events.ts b/src/internal/isolate/events.ts new file mode 100644 index 00000000..fe522562 --- /dev/null +++ b/src/internal/isolate/events.ts @@ -0,0 +1,480 @@ +import {reportError} from "./console.ts"; +import {performance, setTimeout} from "./timers.ts"; + +const CODES: Record = { + IndexSizeError: 1, + HierarchyRequestError: 3, + WrongDocumentError: 4, + InvalidCharacterError: 5, + NoModificationAllowedError: 7, + NotFoundError: 8, + NotSupportedError: 9, + InvalidStateError: 11, + SyntaxError: 12, + InvalidModificationError: 13, + NamespaceError: 14, + InvalidAccessError: 15, + TypeMismatchError: 17, + SecurityError: 18, + NetworkError: 19, + AbortError: 20, + URLMismatchError: 21, + QuotaExceededError: 22, + TimeoutError: 23, + InvalidNodeTypeError: 24, + DataCloneError: 25, +}; + +export class DOMException extends Error { + declare readonly name: string; + declare readonly code: number; + + constructor(message = "", name = "Error") { + super(String(message)); + Object.defineProperty(this, "name", { + value: String(name), + configurable: true, + writable: true, + }); + Object.defineProperty(this, "code", { + value: CODES[String(name)] ?? 0, + configurable: true, + }); + } +} + +interface EventState { + type: string; + bubbles: boolean; + cancelable: boolean; + composed: boolean; + target: EventTarget | null; + currentTarget: EventTarget | null; + phase: number; + canceled: boolean; + stopped: boolean; + stoppedImmediately: boolean; + inPassiveListener: boolean; + timeStamp: number; +} + +const events = new WeakMap(); + +function eventState(event: object): EventState { + const state = events.get(event); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function isTrusted(): boolean { + return false; +} + +export class Event { + static readonly NONE = 0; + static readonly CAPTURING_PHASE = 1; + static readonly AT_TARGET = 2; + static readonly BUBBLING_PHASE = 3; + + constructor(type: string, init: EventInit = {}) { + if (arguments.length === 0) { + throw new TypeError("The event type is required"); + } + + events.set(this, { + type: String(type), + bubbles: !!init?.bubbles, + cancelable: !!init?.cancelable, + composed: !!init?.composed, + target: null, + currentTarget: null, + phase: 0, + canceled: false, + stopped: false, + stoppedImmediately: false, + inPassiveListener: false, + timeStamp: performance.now(), + }); + Object.defineProperty(this, "isTrusted", { + get: isTrusted, + enumerable: true, + configurable: false, + }); + } + + get type(): string { + return eventState(this).type; + } + + get bubbles(): boolean { + return eventState(this).bubbles; + } + + get cancelable(): boolean { + return eventState(this).cancelable; + } + + get composed(): boolean { + return eventState(this).composed; + } + + get target(): EventTarget | null { + return eventState(this).target; + } + + get srcElement(): EventTarget | null { + return eventState(this).target; + } + + get currentTarget(): EventTarget | null { + return eventState(this).currentTarget; + } + + get eventPhase(): number { + return eventState(this).phase; + } + + get defaultPrevented(): boolean { + return eventState(this).canceled; + } + + get returnValue(): boolean { + return !eventState(this).canceled; + } + + get cancelBubble(): boolean { + return eventState(this).stopped; + } + + set cancelBubble(value: boolean) { + if (value) { + eventState(this).stopped = true; + } + } + + get timeStamp(): number { + return eventState(this).timeStamp; + } + + composedPath(): EventTarget[] { + const state = eventState(this); + return state.currentTarget ? [state.currentTarget] : []; + } + + preventDefault(): void { + const state = eventState(this); + if (state.cancelable && !state.inPassiveListener) { + state.canceled = true; + } + } + + stopPropagation(): void { + eventState(this).stopped = true; + } + + stopImmediatePropagation(): void { + const state = eventState(this); + state.stopped = true; + state.stoppedImmediately = true; + } +} + +Object.defineProperty(Event.prototype, Symbol.toStringTag, { + value: "Event", + configurable: true, +}); + +interface Listener { + callback: EventListenerOrEventListenerObject; + capture: boolean; + once: boolean; + passive: boolean; + removed: boolean; +} + +const targets = new WeakMap>(); + +function listenersOf(target: object): Map { + let map = targets.get(target); + if (map === undefined) { + map = new Map(); + targets.set(target, map); + } + + return map; +} + +function flatten(options: boolean | EventListenerOptions | undefined): boolean { + return typeof options === "boolean" ? options : !!options?.capture; +} + +export class EventTarget { + constructor() { + listenersOf(this); + } + + addEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void { + if (callback == null) { + return; + } + + const capture = flatten(options); + const object = typeof options === "object" ? options : undefined; + const signal = object?.signal; + if (signal?.aborted) { + return; + } + + const map = listenersOf(this); + const key = String(type); + const list = map.get(key) ?? []; + if (list.some((l) => l.callback === callback && l.capture === capture)) { + return; + } + + const listener: Listener = { + callback, + capture, + once: !!object?.once, + passive: !!object?.passive, + removed: false, + }; + list.push(listener); + map.set(key, list); + signal?.addEventListener("abort", () => { + this.removeEventListener(key, callback, {capture}); + }); + } + + removeEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ): void { + const capture = flatten(options); + const map = listenersOf(this); + const list = map.get(String(type)); + if (list === undefined) { + return; + } + + const index = list.findIndex( + (l) => l.callback === callback && l.capture === capture, + ); + if (index !== -1) { + list[index].removed = true; + list.splice(index, 1); + } + } + + dispatchEvent(event: Event): boolean { + const state = eventState(event); + if (state.phase !== 0) { + throw new DOMException( + "The event is already being dispatched.", + "InvalidStateError", + ); + } + + state.target = this; + state.currentTarget = this; + state.phase = 2; + const list = listenersOf(this).get(state.type); + for (const listener of list ? list.slice() : []) { + if (listener.removed) { + continue; + } + + if (listener.once) { + this.removeEventListener(state.type, listener.callback, { + capture: listener.capture, + }); + } + + state.inPassiveListener = listener.passive; + try { + const callback = listener.callback; + if (typeof callback === "function") { + callback.call(this, event as never); + } else { + callback.handleEvent(event as never); + } + } catch (error) { + reportError(error); + } + + state.inPassiveListener = false; + if (state.stoppedImmediately) { + break; + } + } + + state.phase = 0; + state.currentTarget = null; + return !state.canceled; + } +} + +Object.defineProperty(EventTarget.prototype, Symbol.toStringTag, { + value: "EventTarget", + configurable: true, +}); + +interface SignalState { + aborted: boolean; + reason: unknown; + onabort: ((event: Event) => unknown) | null; +} + +const signals = new WeakMap(); +let constructingSignal = false; + +function signalState(signal: object): SignalState { + const state = signals.get(signal); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function createSignal(): AbortSignal { + constructingSignal = true; + try { + return new AbortSignal(); + } finally { + constructingSignal = false; + } +} + +function abortSignal(signal: AbortSignal, reason: unknown): void { + const state = signalState(signal); + if (state.aborted) { + return; + } + + state.aborted = true; + state.reason = reason === undefined + ? new DOMException("This operation was aborted", "AbortError") + : reason; + const event = new Event("abort"); + if (state.onabort) { + try { + state.onabort.call(signal, event); + } catch (error) { + reportError(error); + } + } + + signal.dispatchEvent(event); +} + +export class AbortSignal extends EventTarget { + constructor() { + if (!constructingSignal) { + throw new TypeError("Illegal constructor"); + } + + super(); + signals.set(this, {aborted: false, reason: undefined, onabort: null}); + } + + get aborted(): boolean { + return signalState(this).aborted; + } + + get reason(): unknown { + return signalState(this).reason; + } + + get onabort(): ((event: Event) => unknown) | null { + return signalState(this).onabort; + } + + set onabort(value: ((event: Event) => unknown) | null) { + signalState(this).onabort = typeof value === "function" ? value : null; + } + + static abort(reason?: unknown): AbortSignal { + const signal = createSignal(); + abortSignal(signal, reason); + return signal; + } + + static timeout(ms: number): AbortSignal { + const signal = createSignal(); + setTimeout(() => { + abortSignal( + signal, + new DOMException("The operation timed out.", "TimeoutError"), + ); + }, ms); + return signal; + } + + static any(sources: Iterable): AbortSignal { + const signal = createSignal(); + const list = Array.from(sources); + for (const source of list) { + if (source.aborted) { + abortSignal(signal, source.reason); + return signal; + } + } + + for (const source of list) { + source.addEventListener( + "abort", + () => abortSignal(signal, source.reason), + {once: true}, + ); + } + + return signal; + } + + throwIfAborted(): void { + const state = signalState(this); + if (state.aborted) { + throw state.reason; + } + } +} + +Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + value: "AbortSignal", + configurable: true, +}); + +const controllers = new WeakMap(); + +export class AbortController { + constructor() { + controllers.set(this, createSignal()); + } + + get signal(): AbortSignal { + const signal = controllers.get(this); + if (signal === undefined) { + throw new TypeError("Illegal invocation"); + } + + return signal; + } + + abort(reason?: unknown): void { + abortSignal(this.signal, reason); + } +} + +Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + value: "AbortController", + configurable: true, +}); diff --git a/src/internal/isolate/fetch.ts b/src/internal/isolate/fetch.ts new file mode 100644 index 00000000..87445983 --- /dev/null +++ b/src/internal/isolate/fetch.ts @@ -0,0 +1,661 @@ +import URLSearchParamsConstructor from "core-js-pure/actual/url-search-params/index.js"; +import URLConstructor from "core-js-pure/actual/url/index.js"; +import {ReadableStream} from "web-streams-polyfill"; + +import {Blob, blobAt, blobBytes, FormData, isBlob} from "./blob.ts"; +import {encodeUTF8, TextDecoder, toBytes} from "./encoding.ts"; +import {AbortController, type AbortSignal} from "./events.ts"; + +type HeaderList = Array<[string, string]>; + +const headerLists = + new WeakMap(); + +function headerState(headers: object): {list: HeaderList; immutable: boolean} { + const state = headerLists.get(headers); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function headerName(name: unknown): string { + const text = String(name); + if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(text)) { + throw new TypeError(`Invalid header name: ${text}`); + } + + return text.toLowerCase(); +} + +function headerValue(value: unknown): string { + const text = String(value).replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, ""); + if (/[\0\r\n]/.test(text)) { + throw new TypeError("Invalid header value"); + } + + return text; +} + +function mutable(headers: object): HeaderList { + const state = headerState(headers); + if (state.immutable) { + throw new TypeError("Headers are immutable"); + } + + return state.list; +} + +export function freezeHeaders(headers: Headers): void { + headerState(headers).immutable = true; +} + +export class Headers { + constructor(init?: unknown) { + headerLists.set(this, {list: [], immutable: false}); + if (init == null) { + return; + } + + if (init instanceof Headers) { + for (const [name, value] of headerState(init).list) { + this.append(name, value); + } + } else if ( + typeof init === "object" && Symbol.iterator in (init as object) + ) { + for (const pair of init as Iterable>) { + const items = Array.from(pair); + if (items.length !== 2) { + throw new TypeError("Each header must be a name and a value"); + } + + this.append(String(items[0]), String(items[1])); + } + } else if (typeof init === "object") { + for (const key of Object.keys(init as object)) { + this.append(key, String((init as Record)[key])); + } + } else { + throw new TypeError("Invalid headers"); + } + } + + append(name: string, value: string): void { + mutable(this).push([headerName(name), headerValue(value)]); + } + + set(name: string, value: string): void { + const key = headerName(name); + const list = mutable(this); + const index = list.findIndex(([k]) => k === key); + const entry: [string, string] = [key, headerValue(value)]; + if (index === -1) { + list.push(entry); + return; + } + + list.splice(index, 1, entry); + for (let i = list.length - 1; i > index; i--) { + if (list[i][0] === key) { + list.splice(i, 1); + } + } + } + + delete(name: string): void { + const key = headerName(name); + const list = mutable(this); + for (let i = list.length - 1; i >= 0; i--) { + if (list[i][0] === key) { + list.splice(i, 1); + } + } + } + + get(name: string): string | null { + const key = headerName(name); + const values = headerState(this) + .list.filter(([k]) => k === key) + .map(([, v]) => v); + return values.length === 0 ? null : values.join(", "); + } + + getSetCookie(): string[] { + return headerState(this) + .list.filter(([k]) => k === "set-cookie") + .map(([, v]) => v); + } + + has(name: string): boolean { + const key = headerName(name); + return headerState(this).list.some(([k]) => k === key); + } + + *entries(): IterableIterator<[string, string]> { + const names = [...new Set(headerState(this).list.map(([k]) => k))].sort(); + for (const name of names) { + yield [name, this.get(name)!]; + } + } + + *keys(): IterableIterator { + for (const [name] of this.entries()) { + yield name; + } + } + + *values(): IterableIterator { + for (const [, value] of this.entries()) { + yield value; + } + } + + forEach( + callback: (value: string, name: string, headers: Headers) => void, + thisArg?: unknown, + ): void { + for (const [name, value] of this.entries()) { + callback.call(thisArg, value, name, this); + } + } + + [Symbol.iterator](): IterableIterator<[string, string]> { + return this.entries(); + } +} + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: "Headers", + configurable: true, +}); + +interface BodyState { + stream: ReadableStream | null; + bytes: Uint8Array | null; + used: boolean; +} + +const bodies = new WeakMap(); + +function bodyState(owner: object): BodyState { + const state = bodies.get(owner); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +function extractBody( + init: unknown, + headers: Headers, +): {stream: ReadableStream | null; bytes: Uint8Array | null} { + if (init == null) { + return {stream: null, bytes: null}; + } + + let bytes: Uint8Array; + let type: string | null = null; + if (init instanceof ReadableStream) { + return {stream: init as ReadableStream, bytes: null}; + } else if (isBlob(init)) { + bytes = blobBytes(init).slice(); + type = (init as Blob).type || null; + } else if (init instanceof ArrayBuffer || ArrayBuffer.isView(init)) { + bytes = toBytes(init).slice(); + } else if (init instanceof URLSearchParamsConstructor) { + bytes = encodeUTF8(String(init)); + type = "application/x-www-form-urlencoded;charset=UTF-8"; + } else if (init instanceof FormData) { + throw new TypeError("A FormData body is not supported yet"); + } else { + bytes = encodeUTF8(String(init)); + type = "text/plain;charset=UTF-8"; + } + + if (type !== null && !headers.has("content-type")) { + headers.set("content-type", type); + } + + return {stream: null, bytes}; +} + +function streamOf(bytes: Uint8Array): ReadableStream { + return new ReadableStream({ + start(controller) { + if (bytes.length > 0) { + controller.enqueue(bytes.slice()); + } + + controller.close(); + }, + }); +} + +function bodyStream(state: BodyState): ReadableStream | null { + if (state.stream === null && state.bytes !== null) { + state.stream = streamOf(state.bytes); + } + + return state.stream; +} + +async function consume(owner: object): Promise { + const state = bodyState(owner); + if (state.used) { + throw new TypeError("Body has already been consumed"); + } + + state.used = true; + if (state.stream === null) { + return state.bytes ? state.bytes.slice() : new Uint8Array(0); + } + + const reader = state.stream.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + + const chunk = toBytes(value); + chunks.push(chunk); + length += chunk.length; + } + + const out = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.length; + } + + return out; +} + +function teeBody(state: BodyState): BodyState { + if (state.used) { + throw new TypeError("Body has already been consumed"); + } + + if (state.stream === null) { + return {stream: null, bytes: state.bytes, used: false}; + } + + const [left, right] = state.stream.tee(); + state.stream = left; + return {stream: right, bytes: null, used: false}; +} + +class Body { + get body(): ReadableStream | null { + return bodyStream(bodyState(this)); + } + + get bodyUsed(): boolean { + const state = bodyState(this); + return state.used || (state.stream?.locked ?? false); + } + + async arrayBuffer(): Promise { + return (await consume(this)).buffer as ArrayBuffer; + } + + async bytes(): Promise { + return consume(this); + } + + async text(): Promise { + return new TextDecoder().decode(await consume(this)); + } + + async json(): Promise { + return JSON.parse(await this.text()); + } + + async blob(): Promise { + const type = + (this as unknown as {headers: Headers}).headers.get("content-type"); + return new Blob([await consume(this)], {type: type ?? ""}); + } +} + +interface RequestState { + url: string; + method: string; + headers: Headers; + signal: AbortSignal; + redirect: RequestRedirect; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + destination: string; + referrer: string; + referrerPolicy: string; + integrity: string; + keepalive: boolean; +} + +const requests = new WeakMap(); + +function requestState(request: object): RequestState { + const state = requests.get(request); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +let baseURL = "about:blank"; + +export function setBaseURL(url: string): void { + baseURL = url; +} + +export function setDestination(request: Request, destination: string): void { + requestState(request).destination = destination; +} + +const METHODS = new Set([ + "DELETE", + "GET", + "HEAD", + "OPTIONS", + "POST", + "PUT", + "PATCH", +]); + +export class Request extends Body { + constructor(input: unknown, init: RequestInit = {}) { + super(); + let source: RequestState | null = null; + let url: string; + if (input instanceof Request) { + source = requestState(input); + url = source.url; + } else { + url = new URLConstructor(String(input), baseURL).href; + } + + let method = init.method ?? source?.method ?? "GET"; + if (METHODS.has(method.toUpperCase())) { + method = method.toUpperCase(); + } + + const headers = new Headers(init.headers ?? source?.headers); + const controller = new AbortController(); + const parent = init.signal ?? source?.signal; + if (parent) { + if (parent.aborted) { + controller.abort(parent.reason); + } else { + parent.addEventListener( + "abort", + () => controller.abort(parent.reason), + {once: true}, + ); + } + } + + requests.set(this, { + url, + method, + headers, + signal: controller.signal, + redirect: init.redirect ?? source?.redirect ?? "follow", + mode: init.mode ?? source?.mode ?? "cors", + credentials: init.credentials ?? source?.credentials ?? "same-origin", + cache: init.cache ?? source?.cache ?? "default", + destination: source?.destination ?? "", + referrer: init.referrer ?? source?.referrer ?? "about:client", + referrerPolicy: init.referrerPolicy ?? source?.referrerPolicy ?? "", + integrity: init.integrity ?? source?.integrity ?? "", + keepalive: init.keepalive ?? source?.keepalive ?? false, + }); + + if (init.body != null && (method === "GET" || method === "HEAD")) { + throw new TypeError("A GET or HEAD request cannot have a body"); + } + + if (init.body !== undefined) { + bodies.set(this, {...extractBody(init.body, headers), used: false}); + } else if (input instanceof Request) { + bodies.set(this, teeBody(bodyState(input))); + } else { + bodies.set(this, {stream: null, bytes: null, used: false}); + } + } + + get url(): string { + return requestState(this).url; + } + + get method(): string { + return requestState(this).method; + } + + get headers(): Headers { + return requestState(this).headers; + } + + get signal(): AbortSignal { + return requestState(this).signal; + } + + get redirect(): RequestRedirect { + return requestState(this).redirect; + } + + get mode(): RequestMode { + return requestState(this).mode; + } + + get credentials(): RequestCredentials { + return requestState(this).credentials; + } + + get cache(): RequestCache { + return requestState(this).cache; + } + + get destination(): string { + return requestState(this).destination; + } + + get referrer(): string { + return requestState(this).referrer; + } + + get referrerPolicy(): string { + return requestState(this).referrerPolicy; + } + + get integrity(): string { + return requestState(this).integrity; + } + + get keepalive(): boolean { + return requestState(this).keepalive; + } + + clone(): Request { + const state = requestState(this); + const copy = new Request(this); + setDestination(copy, state.destination); + return copy; + } +} + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: "Request", + configurable: true, +}); + +interface ResponseState { + status: number; + statusText: string; + headers: Headers; + url: string; + redirected: boolean; + type: ResponseType; +} + +const responses = new WeakMap(); + +function responseState(response: object): ResponseState { + const state = responses.get(response); + if (state === undefined) { + throw new TypeError("Illegal invocation"); + } + + return state; +} + +export function setResponseURL( + response: Response, + url: string, + redirected: boolean, +): void { + const state = responseState(response); + state.url = url; + state.redirected = redirected; + state.type = "basic"; +} + +export class Response extends Body { + constructor(body?: unknown, init: ResponseInit = {}) { + super(); + const status = init.status ?? 200; + if (status !== 0 && (status < 200 || status > 599)) { + throw new RangeError(`Invalid status ${status}`); + } + + const headers = new Headers(init.headers); + responses.set(this, { + status, + statusText: init.statusText ?? "", + headers, + url: "", + redirected: false, + type: status === 0 ? "error" : "default", + }); + bodies.set(this, {...extractBody(body, headers), used: false}); + } + + get status(): number { + return responseState(this).status; + } + + get statusText(): string { + return responseState(this).statusText; + } + + get ok(): boolean { + const status = responseState(this).status; + return status >= 200 && status < 300; + } + + get headers(): Headers { + return responseState(this).headers; + } + + get url(): string { + return responseState(this).url; + } + + get redirected(): boolean { + return responseState(this).redirected; + } + + get type(): ResponseType { + return responseState(this).type; + } + + static error(): Response { + const response = new Response(null, {status: 0}); + freezeHeaders(response.headers); + return response; + } + + static redirect(url: string, status = 302): Response { + if (![301, 302, 303, 307, 308].includes(status)) { + throw new RangeError(`Invalid redirect status ${status}`); + } + + return new Response(null, { + status, + headers: {location: new URLConstructor(String(url), baseURL).href}, + }); + } + + static json(data: unknown, init: ResponseInit = {}): Response { + const headers = new Headers(init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + + return new Response(JSON.stringify(data), { + ...init, + headers: headers as never, + }); + } + + clone(): Response { + const state = responseState(this); + const copy = new Response(null, { + status: state.status || 200, + statusText: state.statusText, + headers: state.headers as never, + }); + const copyState = responseState(copy); + copyState.status = state.status; + copyState.url = state.url; + copyState.redirected = state.redirected; + copyState.type = state.type; + bodies.set(copy, teeBody(bodyState(this))); + return copy; + } +} + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: "Response", + configurable: true, +}); + +export type Fetcher = (request: Request) => Promise; + +async function noNetwork(): Promise { + throw new TypeError("Failed to fetch: no network in this frame"); +} + +let fetcher: Fetcher = noNetwork; + +export function setFetcher(next: Fetcher): void { + fetcher = next; +} + +export async function fetch( + input: unknown, + init?: RequestInit, +): Promise { + const request = new Request(input, init); + request.signal.throwIfAborted(); + if (request.url.startsWith("blob:")) { + const blob = request.method === "GET" ? blobAt(request.url) : undefined; + if (blob === undefined) { + throw new TypeError("Failed to fetch"); + } + + return new Response(blob, { + headers: {"content-type": blob.type, "content-length": String(blob.size)}, + }); + } + + return fetcher(request); +} diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts new file mode 100644 index 00000000..7e7f7cd8 --- /dev/null +++ b/src/internal/isolate/frame.ts @@ -0,0 +1,250 @@ +/** + * A frame's document shown from an isolate of its own. The page that + * holds the iframe lives in another heap, so the frame paints into cells + * and posts them, and everything it hears, from keys to messages and + * responses, arrives through receive(). + */ +import "./install.ts"; +import "../frames.ts"; + +import {Cascade} from "../cssom.ts"; +import type {Document, Window} from "../dom.ts"; +import {Exchange, type TerminalTransport} from "../exchange.ts"; +import {exportGrid, Framebuffer} from "../framebuffer.ts"; +import {createFrameEngine} from "../frames.ts"; +import {dispatchInput, Input, resolvePendingHover} from "../input.ts"; +import {Layout} from "../layout.ts"; +import {_} from "../slots.ts"; +import {createWindow} from "../window.ts"; +import { + type FrameInit, + host, + type HostMessage, + type IsolateHost, + setHost, +} from "./host.ts"; +import {deliverError, deliverResponse} from "./network.ts"; +import {fireTimer, queueTask} from "./timers.ts"; + +export {fireTimer}; + +function nullTransport(cols: number, rows: number): TerminalTransport { + return { + cols, + rows, + readable: new ReadableStream(), + writable: new WritableStream(), + resizes: new ReadableStream(), + sharesScreen: false, + interactive: false, + ready: Promise.resolve(), + closed: new Promise(() => {}), + close() {}, + }; +} + +interface Frame { + receive(message: HostMessage): void; + dispose(): void; +} + +let frame: Frame | null = null; + +export function start(callbacks: IsolateHost, init: FrameInit): void { + if (frame !== null) { + throw new Error("This isolate already shows a frame."); + } + setHost(callbacks); + frame = createFrame(init); +} + +export function receive(message: HostMessage): void { + frame?.receive(message); +} + +export function dispose(): void { + frame?.dispose(); + frame = null; +} + +function createFrame(init: FrameInit): Frame { + let {cols, rows, cellWidth, cellHeight, pixelRatio} = init; + const window = createWindow( + init.html, + init.url, + "text/html", + init.scripting, + ) as unknown as Window; + const document = window.document as unknown as Document; + const parent = createWindow( + "", + `${init.parentOrigin}/`, + ) as unknown as Window; + _(window).parentWindow = parent; + + let queued = false; + let disposed = false; + let title = ""; + let loaded = false; + const schedule = (): void => { + if (queued || disposed) { + return; + } + queued = true; + queueTask(paint); + }; + + const exchange = createExchange(parent, init); + const loads = new AbortController(); + const engine = createFrameEngine( + document, + window, + { + colorDepth: init.colorDepth, + exchange, + cellSize: {width: cellWidth, height: cellHeight}, + devicePixelRatio: pixelRatio, + images: "cells", + canvas: "cells", + load: (request) => fetch(request), + loadSignal: loads.signal, + reportUncaught: (error) => { + host.log("error", `Uncaught ${describe(error)}`); + }, + cellPixels: () => ({ + width: Math.round(cellWidth * pixelRatio), + height: Math.round(cellHeight * pixelRatio), + }), + pixelRatio: () => pixelRatio, + }, + schedule, + ); + const extra = _(document).extra; + extra.framebuffer.measurer = exchange; + const input = new Input( + document as unknown as globalThis.Document, + extra.layout, + extra.cascade, + extra.framebuffer, + () => {}, + ); + + for (const [ + target, + view, + ] of [["self", window], ["parent", parent]] as const) { + view.navigation.addEventListener("navigate", (event) => { + const navigate = event as NavigateEvent; + if (navigate.hashChange || !navigate.cancelable) { + return; + } + navigate.preventDefault(); + host.post({type: "navigate", target, url: navigate.destination.url}); + }); + } + // The frame's postMessage to its parent lands on the stand-in, past the + // targetOrigin check, and goes on to the page. + parent.addEventListener("message", (event) => { + host.post({ + type: "message", + data: (event as MessageEvent).data, + targetOrigin: init.parentOrigin, + }); + }); + + schedule(); + + function paint(): void { + queued = false; + if (disposed) { + return; + } + resolvePendingHover(input); + const grid = engine.fit(cols, rows); + host.post({type: "paint", cells: exportGrid(grid), caret: engine.caret}); + if (document.title !== title) { + title = document.title; + host.post({type: "title", title}); + } + if (!loaded) { + loaded = true; + host.post({type: "load"}); + } + } + + return { + receive(message) { + if (disposed) { + return; + } + switch (message.type) { + case "resize": + cols = message.cols; + rows = message.rows; + cellWidth = message.cellWidth; + cellHeight = message.cellHeight; + pixelRatio = message.pixelRatio; + schedule(); + return; + case "input": + dispatchInput(input, message.item); + schedule(); + return; + case "message": { + const target = message.targetOrigin; + if ( + target !== "*" && + target !== window.origin && + !(target === "/" && message.origin === window.origin) + ) { + return; + } + const view = window as unknown as typeof globalThis; + view.dispatchEvent( + new view.MessageEvent("message", { + data: message.data, + origin: message.origin, + source: view.parent, + }), + ); + return; + } + case "response": + deliverResponse(message.id, message.response); + return; + case "fetchError": + deliverError(message.id, message.message); + return; + } + }, + dispose() { + disposed = true; + loads.abort(); + engine.dispose(); + }, + }; +} + +// The terminal a frame's engine is told about. In a page, a frame shares +// the exchange of the document its iframe is in. Here that document is +// the blank one standing in for the page, on a transport that writes +// nowhere and asks the terminal nothing. +function createExchange(window: Window, init: FrameInit): Exchange { + const layout = new Layout(window, init.cols, init.rows); + const cascade = new Cascade(window, layout); + const framebuffer = new Framebuffer(init.rows, init.cols, init.colorDepth); + return new Exchange( + nullTransport(init.cols, init.rows), + window, + layout, + cascade, + framebuffer, + init.colorScheme, + ); +} + +function describe(error: unknown): string { + return error instanceof Error + ? error.stack ?? `${error.name}: ${error.message}` + : String(error); +} diff --git a/src/internal/isolate/host.ts b/src/internal/isolate/host.ts new file mode 100644 index 00000000..8f1f0046 --- /dev/null +++ b/src/internal/isolate/host.ts @@ -0,0 +1,106 @@ +/** + * What an isolated frame asks of the process that hosts it. The isolate + * has no timers, randomness, network or output of its own, so each of + * these is a plain callback the backend provides when it loads the + * runtime. Messages are plain values and typed arrays, so any backend + * that copies structured data can carry them. + */ +import type { + ColorDepth, + WireFocus, + WireKey, + WireMouse, + WirePaste, +} from "../exchange.ts"; +import type {GridCells} from "../framebuffer.ts"; + +export interface FrameRequest { + url: string; + method: string; + headers: Array<[string, string]>; + body: Uint8Array | null; + redirect: RequestRedirect; + destination: string; + referrer: string; +} + +export interface FrameResponse { + url: string; + status: number; + statusText: string; + headers: Array<[string, string]>; + redirected: boolean; + body: Uint8Array | null; +} + +export interface FrameCaret { + col: number; + row: number; + shape: number; + color: number | null; +} + +export type FrameMessage = + {type: "paint"; cells: GridCells; caret: FrameCaret | null} | + {type: "title"; title: string} | + {type: "navigate"; target: "self" | "parent"; url: string} | + {type: "load"} | + {type: "message"; data: unknown; targetOrigin: string} | + {type: "fetch"; id: number; request: FrameRequest} | + {type: "abortFetch"; id: number}; + +export interface FrameInit { + url: string; + html: string; + parentOrigin: string; + cols: number; + rows: number; + cellWidth: number; + cellHeight: number; + pixelRatio: number; + colorDepth: ColorDepth; + colorScheme: "light" | "dark"; + scripting: boolean; +} + +export type HostMessage = + { + type: "resize"; + cols: number; + rows: number; + cellWidth: number; + cellHeight: number; + pixelRatio: number; + } | + {type: "input"; item: WireKey[] | WireMouse | WirePaste | WireFocus} | + {type: "message"; data: unknown; origin: string; targetOrigin: string} | + {type: "response"; id: number; response: FrameResponse} | + {type: "fetchError"; id: number; message: string}; + +export interface IsolateHost { + post(message: FrameMessage): void; + log(level: string, text: string): void; + setTimer(id: number, ms: number): void; + clearTimer(id: number): void; + random(length: number): Uint8Array; +} + +function missing(): never { + throw new Error("The isolate runtime has no host yet."); +} + +export const host: IsolateHost = { + post: missing, + log: missing, + setTimer: missing, + clearTimer: missing, + random: missing, +}; + +export function setHost(next: IsolateHost): void { + host.post = (message) => next.post(message); + host.log = (level, text) => next.log(level, text); + host.setTimer = (id, ms) => next.setTimer(id, ms); + host.clearTimer = (id) => next.clearTimer(id); + host.random = (length) => next.random(length); +} diff --git a/src/internal/isolate/install.ts b/src/internal/isolate/install.ts new file mode 100644 index 00000000..87d6e393 --- /dev/null +++ b/src/internal/isolate/install.ts @@ -0,0 +1,128 @@ +import atob from "core-js-pure/actual/atob.js"; +import btoa from "core-js-pure/actual/btoa.js"; +import structuredClone from "core-js-pure/actual/structured-clone.js"; +import URLSearchParams from "core-js-pure/actual/url-search-params/index.js"; +import URL from "core-js-pure/actual/url/index.js"; +import { + ReadableStream, + TransformStream, + WritableStream, +} from "web-streams-polyfill"; + +import {Blob, File, FormData} from "./blob.ts"; +import {DecompressionStream} from "./compression.ts"; +import {console} from "./console.ts"; +import {TextDecoder, TextEncoder} from "./encoding.ts"; +import { + AbortController, + AbortSignal, + DOMException, + Event, + EventTarget, +} from "./events.ts"; +import {fetch, Headers, Request, Response} from "./fetch.ts"; +import {host} from "./host.ts"; +import {installNetwork} from "./network.ts"; +import { + clearInterval, + clearTimeout, + performance, + queueMicrotask, + setInterval, + setTimeout, +} from "./timers.ts"; + +const MAX_RANDOM_BYTES = 65536; + +function getRandomValues(view: T): T { + if ( + !(view instanceof Int8Array) && + !(view instanceof Uint8Array) && + !(view instanceof Uint8ClampedArray) && + !(view instanceof Int16Array) && + !(view instanceof Uint16Array) && + !(view instanceof Int32Array) && + !(view instanceof Uint32Array) && + !(view instanceof BigInt64Array) && + !(view instanceof BigUint64Array) + ) { + throw new DOMException( + "The data is not an integer typed array", + "TypeMismatchError", + ); + } + + if (view.byteLength > MAX_RANDOM_BYTES) { + throw new DOMException( + `The length exceeds ${MAX_RANDOM_BYTES} bytes`, + "QuotaExceededError", + ); + } + + const bytes = host.random(view.byteLength); + new Uint8Array(view.buffer, view.byteOffset, view.byteLength).set(bytes); + return view; +} + +// eslint-disable-next-line acrocase/acrocase -- the Web Crypto name +function randomUUID(): string { + const bytes = getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")); + return [ + hex.slice(0, 4).join(""), + hex.slice(4, 6).join(""), + hex.slice(6, 8).join(""), + hex.slice(8, 10).join(""), + hex.slice(10).join(""), + ].join("-"); +} + +const crypto = {getRandomValues, randomUUID}; + +const globals: Record = { + AbortController, + AbortSignal, + Blob, + DOMException, + DecompressionStream, + Event, + EventTarget, + File, + FormData, + Headers, + ReadableStream, + Request, + Response, + TextDecoder, + TextEncoder, + TransformStream, + URL, + URLSearchParams, + WritableStream, + atob, + btoa, + clearInterval, + clearTimeout, + console, + crypto, + fetch, + performance, + queueMicrotask, + setInterval, + setTimeout, + structuredClone, +}; + +for (const name of Object.keys(globals)) { + Object.defineProperty(globalThis, name, { + value: globals[name], + writable: true, + configurable: true, + enumerable: false, + }); +} + +Reflect.deleteProperty(globalThis, "__core-js_shared__"); +installNetwork(); diff --git a/src/internal/isolate/network.ts b/src/internal/isolate/network.ts new file mode 100644 index 00000000..356cd1b0 --- /dev/null +++ b/src/internal/isolate/network.ts @@ -0,0 +1,88 @@ +import {Response, setFetcher, setResponseURL} from "./fetch.ts"; +import {type FrameResponse, host} from "./host.ts"; + +interface Pending { + resolve(response: Response): void; + reject(error: unknown): void; + release(): void; +} + +const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]); + +const pending = new Map(); +let nextId = 1; + +export function installNetwork(): void { + setFetcher(async (request) => { + const body = request.method === "GET" || request.method === "HEAD" + ? null + : new Uint8Array(await request.arrayBuffer()); + request.signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const id = nextId++; + const signal = request.signal; + const onAbort = (): void => { + if (pending.delete(id)) { + host.post({type: "abortFetch", id}); + reject(signal.reason); + } + }; + pending.set(id, { + resolve, + reject, + release() { + signal.removeEventListener("abort", onAbort); + }, + }); + signal.addEventListener("abort", onAbort, {once: true}); + host.post({ + type: "fetch", + id, + request: { + url: request.url, + method: request.method, + headers: [...request.headers], + body, + redirect: request.redirect, + destination: request.destination, + referrer: request.referrer, + }, + }); + }); + }); +} + +export function deliverResponse(id: number, response: FrameResponse): void { + const entry = pending.get(id); + if (entry === undefined) { + return; + } + + pending.delete(id); + entry.release(); + try { + const result = new Response( + NULL_BODY_STATUSES.has(response.status) ? null : response.body, + { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }, + ); + setResponseURL(result, response.url, response.redirected); + entry.resolve(result); + } catch (error) { + entry.reject(new TypeError(`Failed to fetch: ${String(error)}`)); + } +} + +export function deliverError(id: number, message: string): void { + const entry = pending.get(id); + if (entry === undefined) { + return; + } + + pending.delete(id); + entry.release(); + entry.reject(new TypeError(`Failed to fetch: ${message}`)); +} diff --git a/src/internal/isolate/timers.ts b/src/internal/isolate/timers.ts new file mode 100644 index 00000000..eb98401a --- /dev/null +++ b/src/internal/isolate/timers.ts @@ -0,0 +1,132 @@ +import {reportError} from "./console.ts"; +import {host} from "./host.ts"; + +interface Timer { + callback: (...args: unknown[]) => unknown; + args: unknown[]; + ms: number; + repeat: boolean; + nesting: number; +} + +const timers = new Map(); +let nextId = 1; +let currentNesting = 0; + +const NESTING_LIMIT = 5; +const NESTED_MINIMUM = 4; + +function normalizeDelay(ms: unknown): number { + const delay = Number(ms); + return delay > 0 && delay < 2 ** 31 ? delay : 0; +} + +function schedule( + callback: unknown, + ms: unknown, + args: unknown[], + repeat: boolean, + task = false, +): number { + const id = nextId++; + if (typeof callback !== "function") { + return id; + } + + const nesting = task ? 0 : currentNesting + 1; + let delay = normalizeDelay(ms); + if (nesting > NESTING_LIMIT && delay < NESTED_MINIMUM) { + delay = NESTED_MINIMUM; + } + + timers.set(id, { + callback: callback as Timer["callback"], + args, + ms: delay, + repeat, + nesting, + }); + host.setTimer(id, delay); + return id; +} + +function cancel(id: unknown): void { + const key = Number(id); + if (timers.delete(key)) { + host.clearTimer(key); + } +} + +export function setTimeout( + callback: unknown, + ms?: unknown, + ...args: unknown[] +): number { + return schedule(callback, ms, args, false); +} + +export function setInterval( + callback: unknown, + ms?: unknown, + ...args: unknown[] +): number { + return schedule(callback, ms, args, true); +} + +export function queueTask(callback: () => void): void { + schedule(callback, 0, [], false, true); +} + +export const clearTimeout = cancel; +export const clearInterval = cancel; + +export function queueMicrotask(callback: unknown): void { + if (typeof callback !== "function") { + throw new TypeError("queueMicrotask expects a function"); + } + + void Promise.resolve().then(() => { + try { + (callback as () => void)(); + } catch (error) { + reportError(error); + } + }); +} + +export function fireTimer(id: number): void { + const timer = timers.get(id); + if (timer === undefined) { + return; + } + + if (timer.repeat) { + timer.nesting++; + if (timer.nesting > NESTING_LIMIT && timer.ms < NESTED_MINIMUM) { + timer.ms = NESTED_MINIMUM; + } + + host.setTimer(id, timer.ms); + } else { + timers.delete(id); + } + + const outer = currentNesting; + currentNesting = timer.nesting; + try { + timer.callback(...timer.args); + } catch (error) { + reportError(error); + } finally { + currentNesting = outer; + } +} + +const origin = Date.now(); + +export const performance = { + timeOrigin: origin, + now(): number { + return Date.now() - origin; + }, +}; diff --git a/src/internal/isolate/vendor.d.ts b/src/internal/isolate/vendor.d.ts new file mode 100644 index 00000000..d5ecb6e8 --- /dev/null +++ b/src/internal/isolate/vendor.d.ts @@ -0,0 +1,27 @@ +declare module "core-js-pure/actual/atob.js" { + const atob: (data: string) => string; + export default atob; +} + +declare module "core-js-pure/actual/btoa.js" { + const btoa: (data: string) => string; + export default btoa; +} + +declare module "core-js-pure/actual/structured-clone.js" { + const structuredClone: ( + value: T, + options?: StructuredSerializeOptions, + ) => T; + export default structuredClone; +} + +declare module "core-js-pure/actual/url/index.js" { + const URL: typeof globalThis.URL; + export default URL; +} + +declare module "core-js-pure/actual/url-search-params/index.js" { + const URLSearchParams: typeof globalThis.URLSearchParams; + export default URLSearchParams; +} From 7470f3b69358e1e4470e0c3049e89c0e785036ee Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:35:36 -0500 Subject: [PATCH 06/25] Run isolated frames in isolated-vm, scripts and modules included createIsolatedVMFrames resolves to a FrameIsolator. Each frame gets an isolate with a memory limit, and every call into it a time limit. The backend drives the frame's timers, randomness and logs, and runs the scripts the frame reports in document order: classic scripts, modules through the page's import maps, and dynamic imports. Their sources, and everything else the frame fetches, are loaded by the page. Inside the isolate, the frame copies its window onto the global object for its scripts, and sets currentScript, readyState and the load events as the backend reports each script's start and end. The build bundles the runtime into dist/isolate-frame.js. A checkout bundles it from source on first use. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- bun.lock | 6 + package.json | 4 +- scripts/build-isolate-frame.ts | 17 ++ src/internal/isolate/bundle.ts | 80 ++++++ src/internal/isolate/frame.ts | 68 ++++- src/internal/isolate/host.ts | 6 + src/internal/isolate/messaging.ts | 125 +++++++++ src/internal/isolate/page.ts | 132 +++++++++ src/internal/isolate/scripts.ts | 158 +++++++++++ src/internal/isolatedvm.ts | 453 ++++++++++++++++++++++++++++++ src/internal/isolatedvmmodules.ts | 280 ++++++++++++++++++ 11 files changed, 1324 insertions(+), 5 deletions(-) create mode 100644 scripts/build-isolate-frame.ts create mode 100644 src/internal/isolate/bundle.ts create mode 100644 src/internal/isolate/messaging.ts create mode 100644 src/internal/isolate/page.ts create mode 100644 src/internal/isolate/scripts.ts create mode 100644 src/internal/isolatedvm.ts create mode 100644 src/internal/isolatedvmmodules.ts diff --git a/bun.lock b/bun.lock index 2db96789..cba46b58 100644 --- a/bun.lock +++ b/bun.lock @@ -31,6 +31,7 @@ "@xterm/headless": "^6", "codemirror": "^6.0.2", "core-js-pure": "3.50.0", + "esbuild": "^0.28.1", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", @@ -39,6 +40,7 @@ "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", + "isolated-vm": "^7.0.2", "katex": "^0.18.9", "marked": "^18.0.14", "marked-highlight": "^2.2.4", @@ -465,6 +467,8 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "isolated-vm": ["isolated-vm@7.0.2", "", { "dependencies": { "node-gyp-build": "^4.8.4" } }, "sha512-Z1sYxpptGyGiKblG16EJEdP5x9/68C6AuqFFsewnrxlwSlrTLHKqtRMogOjcYZ0f8/cijMaRi+XwiHVQ1+uG+g=="], + "istanbul-lib-coverage": ["istanbul-lib-coverage@3.2.2", "", {}, "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg=="], "istanbul-lib-report": ["istanbul-lib-report@3.0.1", "", { "dependencies": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^4.0.0", "supports-color": "^7.1.0" } }, "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw=="], @@ -523,6 +527,8 @@ "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], diff --git a/package.json b/package.json index d421b06c..5043de6a 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ ], "scripts": { "bench": "node bench/run.ts", - "build": "libuild build", + "build": "libuild build && node scripts/build-isolate-frame.ts", "lint": "eslint .", "prepublishOnly": "echo 'ERROR: Cannot publish from root directory. Use libuild to publish or stage the package.' && exit 1", "smoke": "node scripts/smoke.js", @@ -84,6 +84,7 @@ "@xterm/headless": "^6", "codemirror": "^6.0.2", "core-js-pure": "3.50.0", + "esbuild": "^0.28.1", "eslint": "^10", "eslint-plugin-acrocase": "^0.1.1", "eslint-plugin-crank": "^0.2.2", @@ -92,6 +93,7 @@ "fflate": "0.8.3", "ghostty-web": "0.4.0", "htm": "^3.1.1", + "isolated-vm": "^7.0.2", "katex": "^0.18.9", "marked": "^18.0.14", "marked-highlight": "^2.2.4", diff --git a/scripts/build-isolate-frame.ts b/scripts/build-isolate-frame.ts new file mode 100644 index 00000000..a49f6e50 --- /dev/null +++ b/scripts/build-isolate-frame.ts @@ -0,0 +1,17 @@ +/** + * Writes the isolated frame runtime next to the built modules, so a + * package loads it without bundling anything at run time. + * + * bun run build + */ +import {writeFile} from "node:fs/promises"; + +import { + buildFrameScript, + FRAME_SCRIPT, +} from "../src/internal/isolate/bundle.ts"; + +await writeFile( + new URL(`../dist/${FRAME_SCRIPT}`, import.meta.url), + await buildFrameScript(), +); diff --git a/src/internal/isolate/bundle.ts b/src/internal/isolate/bundle.ts new file mode 100644 index 00000000..88e59d38 --- /dev/null +++ b/src/internal/isolate/bundle.ts @@ -0,0 +1,80 @@ +/** + * The frame runtime as one classic script for a bare isolate: the engine, + * its shims and the frame entry, bundled with nothing left to import. The + * script evaluates to a function of the host's callbacks, which returns a + * function of the frame's settings, which returns the frame's dispatcher. + * A built package carries the script next to its modules, and a checkout + * bundles it from source on first use. + */ +import {readFile} from "node:fs/promises"; + +export const HOST_CALLBACKS = [ + "post", + "log", + "setTimer", + "clearTimer", + "random", + "scripts", +] as const; + +export const FRAME_SCRIPT = "isolate-frame.js"; + +const ENTRY = new URL("./frame.ts", import.meta.url); + +export async function buildFrameScript(): Promise { + const {build} = await import("esbuild"); + const result = await build({ + entryPoints: [ENTRY.pathname], + bundle: true, + write: false, + format: "iife", + globalName: "__termdomFrame", + platform: "neutral", + mainFields: ["module", "main"], + target: "es2022", + legalComments: "none", + define: {"import.meta.url": "undefined", "import.meta.litest": "undefined"}, + logLevel: "silent", + }); + return `(function (${HOST_CALLBACKS.join(", ")}) { +"use strict"; +${result.outputFiles[0].text} +const frame = __termdomFrame; +return (init) => { + frame.start({${HOST_CALLBACKS.join(", ")}}, init); + return (kind, ...args) => { + switch (kind) { + case "receive": return frame.receive(args[0]); + case "timer": return frame.fireTimer(args[0]); + case "scriptBegin": return frame.scriptBegin(args[0]); + case "scriptEnd": return frame.scriptEnd(args[0]); + case "scriptFinished": return frame.scriptFinished(args[0], args[1]); + case "interactive": return frame.documentInteractive(); + case "loaded": return frame.documentLoaded(); + case "dispose": return frame.dispose(); + } + }; +}; +})`; +} + +let script: Promise | undefined; + +export function loadFrameScript(): Promise { + script ??= (async () => { + for (const url of [ + new URL(`./${FRAME_SCRIPT}`, import.meta.url), + new URL(`../${FRAME_SCRIPT}`, import.meta.url), + ]) { + try { + return await readFile(url, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw error; + } + } + } + return buildFrameScript(); + })(); + return script; +} diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index 7e7f7cd8..06eb9ceb 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -8,7 +8,12 @@ import "./install.ts"; import "../frames.ts"; import {Cascade} from "../cssom.ts"; -import type {Document, Window} from "../dom.ts"; +import { + type Document, + findRuntimeFetchClasses, + findRuntimeGlobals, + type Window, +} from "../dom.ts"; import {Exchange, type TerminalTransport} from "../exchange.ts"; import {exportGrid, Framebuffer} from "../framebuffer.ts"; import {createFrameEngine} from "../frames.ts"; @@ -24,6 +29,8 @@ import { setHost, } from "./host.ts"; import {deliverError, deliverResponse} from "./network.ts"; +import {installPage} from "./page.ts"; +import {ScriptRunner} from "./scripts.ts"; import {fireTimer, queueTask} from "./timers.ts"; export {fireTimer}; @@ -45,6 +52,8 @@ function nullTransport(cols: number, rows: number): TerminalTransport { interface Frame { receive(message: HostMessage): void; + scripts: ScriptRunner | null; + loaded(): void; dispose(): void; } @@ -62,6 +71,39 @@ export function receive(message: HostMessage): void { frame?.receive(message); } +// The backend runs the scripts the frame reports, and tells it where each +// one starts and ends and how the document's loading goes. +export function scriptBegin(id: number): void { + if (frame !== null) { + frame.scripts?.begin(id); + } +} + +export function scriptEnd(id: number): void { + if (frame !== null) { + frame.scripts?.end(id); + } +} + +export function scriptFinished(id: number, ok: boolean): void { + if (frame !== null) { + frame.scripts?.finished(id, ok); + } +} + +export function documentInteractive(): void { + if (frame !== null) { + frame.scripts?.interactive(); + } +} + +export function documentLoaded(): void { + if (frame !== null) { + frame.scripts?.loaded(); + frame.loaded(); + } +} + export function dispose(): void { frame?.dispose(); frame = null; @@ -69,6 +111,8 @@ export function dispose(): void { function createFrame(init: FrameInit): Frame { let {cols, rows, cellWidth, cellHeight, pixelRatio} = init; + findRuntimeGlobals(); + findRuntimeFetchClasses(); const window = createWindow( init.html, init.url, @@ -152,8 +196,23 @@ function createFrame(init: FrameInit): Frame { }); }); + let scripts: ScriptRunner | null = null; + if (init.scripting) { + installPage(window); + scripts = new ScriptRunner(document as unknown as globalThis.Document); + scripts.start(); + } schedule(); + // Without scripts, the document is loaded once its first paint is out. + // With them, once the backend has run them all. + function announceLoad(): void { + if (!loaded) { + loaded = true; + host.post({type: "load"}); + } + } + function paint(): void { queued = false; if (disposed) { @@ -166,13 +225,14 @@ function createFrame(init: FrameInit): Frame { title = document.title; host.post({type: "title", title}); } - if (!loaded) { - loaded = true; - host.post({type: "load"}); + if (scripts === null) { + announceLoad(); } } return { + scripts, + loaded: announceLoad, receive(message) { if (disposed) { return; diff --git a/src/internal/isolate/host.ts b/src/internal/isolate/host.ts index 8f1f0046..8d9061bc 100644 --- a/src/internal/isolate/host.ts +++ b/src/internal/isolate/host.ts @@ -13,6 +13,7 @@ import type { WirePaste, } from "../exchange.ts"; import type {GridCells} from "../framebuffer.ts"; +import type {ScriptItem} from "./scripts.ts"; export interface FrameRequest { url: string; @@ -83,6 +84,9 @@ export interface IsolateHost { setTimer(id: number, ms: number): void; clearTimer(id: number): void; random(length: number): Uint8Array; + // The scripts the document holds, or that were added to it, for the + // backend to fetch, compile and run in order. + scripts(initial: boolean, items: ScriptItem[]): void; } function missing(): never { @@ -95,6 +99,7 @@ export const host: IsolateHost = { setTimer: missing, clearTimer: missing, random: missing, + scripts: missing, }; export function setHost(next: IsolateHost): void { @@ -103,4 +108,5 @@ export function setHost(next: IsolateHost): void { host.setTimer = (id, ms) => next.setTimer(id, ms); host.clearTimer = (id) => next.clearTimer(id); host.random = (length) => next.random(length); + host.scripts = (initial, items) => next.scripts(initial, items); } diff --git a/src/internal/isolate/messaging.ts b/src/internal/isolate/messaging.ts new file mode 100644 index 00000000..0fcda1fe --- /dev/null +++ b/src/internal/isolate/messaging.ts @@ -0,0 +1,125 @@ +import {queueTask} from "./timers.ts"; + +interface Win { + EventTarget: new () => EventTarget; + MessageEvent: new (type: string, init?: MessageEventInit) => Event; +} + +interface PortState { + other: PortState | null; + port: EventTarget; + queue: unknown[]; + started: boolean; + closed: boolean; + handler: ((event: Event) => void) | null; +} + +export function createMessageChannel(win: Win): { + MessageChannel: new () => {port1: EventTarget; port2: EventTarget}; + MessagePort: new () => EventTarget; +} { + const states = new WeakMap(); + const state = (port: object): PortState => { + const found = states.get(port); + if (found === undefined) { + throw new TypeError("Illegal invocation"); + } + + return found; + }; + + const deliver = (target: PortState): void => { + if (!target.started || target.closed) { + return; + } + + for (const data of target.queue.splice(0)) { + queueTask(() => { + if (!target.closed) { + target.port.dispatchEvent(new win.MessageEvent("message", {data})); + } + }); + } + }; + + let constructing = false; + + class MessagePort extends win.EventTarget { + constructor() { + if (!constructing) { + throw new TypeError("Illegal constructor"); + } + + super(); + states.set(this, { + other: null, + port: this, + queue: [], + started: false, + closed: false, + handler: null, + }); + } + + get onmessage(): ((event: Event) => void) | null { + return state(this).handler; + } + + set onmessage(handler: ((event: Event) => void) | null) { + const own = state(this); + if (own.handler !== null) { + this.removeEventListener("message", own.handler); + } + + own.handler = typeof handler === "function" ? handler : null; + if (own.handler !== null) { + this.addEventListener("message", own.handler); + this.start(); + } + } + + postMessage(message: unknown): void { + const own = state(this); + if (own.closed || own.other === null || own.other.closed) { + return; + } + + own.other.queue.push(structuredClone(message)); + deliver(own.other); + } + + start(): void { + const own = state(this); + own.started = true; + deliver(own); + } + + close(): void { + const own = state(this); + own.closed = true; + own.queue.length = 0; + } + } + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + + constructor() { + constructing = true; + try { + this.port1 = new MessagePort(); + this.port2 = new MessagePort(); + } finally { + constructing = false; + } + + const one = state(this.port1); + const two = state(this.port2); + one.other = two; + two.other = one; + } + } + + return {MessageChannel, MessagePort}; +} diff --git a/src/internal/isolate/page.ts b/src/internal/isolate/page.ts new file mode 100644 index 00000000..989ad0d7 --- /dev/null +++ b/src/internal/isolate/page.ts @@ -0,0 +1,132 @@ +/** + * A page's scripts run with the isolate's global object as theirs, and a + * global object cannot be swapped for the frame's window. So the window's + * members are copied onto it, its methods bound to the window, and its + * attributes read through to it, and window, self and frames name the + * global, as they would in a browser. + */ +import {createObjectURL, revokeObjectURL} from "./blob.ts"; +import {createMessageChannel} from "./messaging.ts"; + +type Win = + Record & + {location: {href: string}; parent: unknown; top: unknown}; + +const KEPT_GLOBALS = new Set([ + "constructor", + "globalThis", + "window", + "self", + "top", + "parent", + "frames", + "fetch", + "location", +]); + +export function installPage(window: object): void { + const win = window as Win; + const names = new Set(); + for ( + let object: object | null = win; + object !== null && object !== Object.prototype; + object = Object.getPrototypeOf(object) as object | null + ) { + for (const name of Object.getOwnPropertyNames(object)) { + names.add(name); + } + } + + for (const name of names) { + if (KEPT_GLOBALS.has(name)) { + continue; + } + + const existing = Object.getOwnPropertyDescriptor(globalThis, name); + if (existing !== undefined && !existing.configurable) { + continue; + } + + let value: unknown; + try { + value = win[name]; + } catch (error) { + if (!(error instanceof Error)) { + throw error; + } + + continue; + } + + if (typeof value === "function" && /^[a-z]/.test(name)) { + Object.defineProperty(globalThis, name, { + value: (value as (...args: unknown[]) => unknown).bind(win), + writable: true, + configurable: true, + }); + } else if (typeof value === "function") { + Object.defineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + }); + } else { + Object.defineProperty(globalThis, name, { + get: () => win[name], + set: (next: unknown) => { + win[name] = next; + }, + configurable: true, + }); + } + } + + for (const name of ["window", "self", "frames"]) { + Object.defineProperty(globalThis, name, { + value: globalThis, + writable: false, + configurable: false, + }); + } + + for (const name of ["parent", "top"] as const) { + Object.defineProperty(globalThis, name, { + get: () => win[name], + configurable: false, + }); + } + + Object.defineProperty(globalThis, "location", { + get: () => win.location, + set: (value: unknown) => { + win.location.href = String(value); + }, + configurable: false, + }); + const {MessageChannel, MessagePort} = createMessageChannel( + win as unknown as Parameters[0], + ); + for (const [name, value] of [ + ["MessageChannel", MessageChannel], + ["MessagePort", MessagePort], + ] as const) { + Object.defineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + }); + } + + const PageURL = (globalThis as unknown as {URL: object}).URL; + Object.defineProperty(PageURL, "createObjectURL", { + value: (object: unknown) => + createObjectURL(object, new URL(win.location.href).origin), + writable: true, + configurable: true, + }); + Object.defineProperty(PageURL, "revokeObjectURL", { + value: revokeObjectURL, + writable: true, + configurable: true, + }); +} diff --git a/src/internal/isolate/scripts.ts b/src/internal/isolate/scripts.ts new file mode 100644 index 00000000..4d4c4384 --- /dev/null +++ b/src/internal/isolate/scripts.ts @@ -0,0 +1,158 @@ +import {host} from "./host.ts"; + +const CLASSIC_TYPES = new Set([ + "", + "text/javascript", + "application/javascript", + "application/ecmascript", + "text/ecmascript", + "application/x-javascript", + "text/jscript", +]); + +export interface ScriptItem { + id: number; + kind: "classic" | "module" | "importmap"; + src: string | null; + text: string | null; + async: boolean; +} + +interface WindowLike { + Event: new (type: string, init?: EventInit) => Event; + dispatchEvent(event: Event): boolean; + MutationObserver: typeof MutationObserver; +} + +export class ScriptRunner { + readonly document: Document; + readonly elements: Map; + readonly seen: WeakSet; + nextId: number; + current: HTMLScriptElement | null; + readyState: DocumentReadyState; + + constructor(document: Document) { + this.document = document; + this.elements = new Map(); + this.seen = new WeakSet(); + this.nextId = 1; + this.current = null; + this.readyState = "loading"; + Object.defineProperty(document, "currentScript", { + get: () => this.current, + configurable: true, + enumerable: true, + }); + Object.defineProperty(document, "readyState", { + get: () => this.readyState, + configurable: true, + enumerable: true, + }); + } + + collect(root: ParentNode | Element): ScriptItem[] { + const found: HTMLScriptElement[] = []; + if ((root as Element).localName === "script") { + found.push(root as HTMLScriptElement); + } + + for (const script of root.querySelectorAll("script")) { + found.push(script); + } + + const items: ScriptItem[] = []; + for (const script of found) { + if (this.seen.has(script) || !script.isConnected) { + continue; + } + + this.seen.add(script); + const type = (script.getAttribute("type") ?? "").trim().toLowerCase(); + const kind = type === "module" + ? "module" + : type === "importmap" + ? "importmap" + : CLASSIC_TYPES.has(type) && !script.hasAttribute("nomodule") + ? "classic" + : null; + if (kind === null) { + continue; + } + + const id = this.nextId++; + const src = script.hasAttribute("src") && kind !== "importmap" + ? script.src + : null; + if (src !== null || kind === "classic") { + this.elements.set(id, script); + } + + items.push({ + id, + kind, + src, + text: src === null ? script.text : null, + async: + kind !== "importmap" && + (src !== null || kind === "module") && + script.hasAttribute("async"), + }); + } + + return items; + } + + start(): void { + const view = this.document.defaultView as unknown as WindowLike; + host.scripts(true, this.collect(this.document)); + new view.MutationObserver((records) => { + const items: ScriptItem[] = []; + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType === 1) { + items.push(...this.collect(node as Element)); + } + } + } + + if (items.length > 0) { + host.scripts(false, items); + } + }).observe(this.document, {childList: true, subtree: true}); + } + + begin(id: number): void { + this.current = this.elements.get(id) ?? null; + } + + end(id: number): void { + this.current = null; + if (this.elements.get(id)?.hasAttribute("src") === false) { + this.elements.delete(id); + } + } + + finished(id: number, ok: boolean): void { + const script = this.elements.get(id); + this.elements.delete(id); + const view = this.document.defaultView as unknown as WindowLike; + script?.dispatchEvent(new view.Event(ok ? "load" : "error")); + } + + interactive(): void { + const view = this.document.defaultView as unknown as WindowLike; + this.readyState = "interactive"; + this.document.dispatchEvent(new view.Event("readystatechange")); + this.document.dispatchEvent( + new view.Event("DOMContentLoaded", {bubbles: true}), + ); + } + + loaded(): void { + const view = this.document.defaultView as unknown as WindowLike; + this.readyState = "complete"; + this.document.dispatchEvent(new view.Event("readystatechange")); + view.dispatchEvent(new view.Event("load")); + } +} diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts new file mode 100644 index 00000000..16f7b600 --- /dev/null +++ b/src/internal/isolatedvm.ts @@ -0,0 +1,453 @@ +/** + * Frames in isolates of their own, made with isolated-vm. Each frame + * gets an isolate with a memory limit and a context running the frame + * runtime, and every call into it is held to a time limit. The backend + * drives the frame's timers, randomness and logs, and fetches, compiles + * and runs its scripts and modules in document order. Anything the frame + * fetches, its scripts included, goes to the page, which loads it under + * its own policy. + */ +import {randomFillSync} from "node:crypto"; + +import type ivm from "isolated-vm"; + +import {HOST_CALLBACKS, loadFrameScript} from "./isolate/bundle.ts"; +import type { + FrameInit, + FrameMessage, + FrameRequest, + FrameResponse, + HostMessage, +} from "./isolate/host.ts"; +import type {ScriptItem} from "./isolate/scripts.ts"; +import {ModuleLoader} from "./isolatedvmmodules.ts"; + +export const DEFAULT_MEMORY_LIMIT = 256; +export const DEFAULT_TASK_TIMEOUT = 30000; +const BOOT_TIMEOUT = 10000; +const MAX_RANDOM_BYTES = 65536; +const MAX_TIMERS = 10000; +const MAX_SCRIPTS = 1000; +const MAX_LOG_LENGTH = 4096; + +export interface IsolatedFrame { + send(message: HostMessage): void; + dispose(): void; +} + +export type FrameIsolator = ( + init: FrameInit, + receive: (message: FrameMessage) => void, +) => IsolatedFrame; + +export interface IsolatedVMOptions { + // Megabytes of heap each frame's isolate may use. + memoryLimit?: number; + // Milliseconds any one call into a frame may run. + taskTimeout?: number; + // Where a frame's console output and uncaught errors go. + log?(level: string, text: string): void; +} + +type Dispatch = ivm.Reference<(kind: string, ...args: unknown[]) => unknown>; + +/** + * Resolves to the isolator, once isolated-vm has loaded and the frame + * runtime is compiled. Rejects where isolated-vm is not installed. + */ +export async function createIsolatedVMFrames( + options: IsolatedVMOptions = {}, +): Promise { + const {default: ivmModule} = await import("isolated-vm"); + const source = await loadFrameScript(); + const memoryLimit = options.memoryLimit ?? DEFAULT_MEMORY_LIMIT; + const taskTimeout = options.taskTimeout ?? DEFAULT_TASK_TIMEOUT; + const log = options.log ?? (() => {}); + let cachedData: ivm.ExternalCopy | undefined; + return (init, receive) => { + const frame = new IsolatedVMFrame( + ivmModule, + {memoryLimit, taskTimeout, log}, + init, + receive, + ); + void frame.boot(source, cachedData).then((data) => { + cachedData ??= data; + }); + return { + send: (message) => frame.send(message), + dispose: () => frame.dispose(), + }; + }; +} + +class IsolatedVMFrame { + readonly ivm: typeof ivm; + readonly isolate: ivm.Isolate; + readonly init: FrameInit; + readonly receive: (message: FrameMessage) => void; + readonly taskTimeout: number; + readonly log: (level: string, text: string) => void; + readonly modules: ModuleLoader; + readonly timers: Map>; + readonly ownLoads: Map< + number, + {resolve(response: FrameResponse): void; reject(error: Error): void} + >; + + context!: ivm.Context; + dispatch: Dispatch | null; + queued: Array<[string, ...unknown[]]> | null; + nextOwnLoad: number; + scriptQueue: Promise; + asyncScripts: Set>; + executing: Promise; + scriptCount: number; + disposed: boolean; + + constructor( + ivmModule: typeof ivm, + limits: { + memoryLimit: number; + taskTimeout: number; + log(level: string, text: string): void; + }, + init: FrameInit, + receive: (message: FrameMessage) => void, + ) { + this.ivm = ivmModule; + this.init = init; + this.receive = receive; + this.taskTimeout = limits.taskTimeout; + this.log = (level, text) => + limits.log(String(level), String(text).slice(0, MAX_LOG_LENGTH)); + this.timers = new Map(); + this.ownLoads = new Map(); + this.dispatch = null; + this.queued = []; + this.nextOwnLoad = -1; + this.scriptQueue = Promise.resolve(); + this.asyncScripts = new Set(); + this.executing = Promise.resolve(); + this.scriptCount = 0; + this.disposed = false; + this.isolate = new ivmModule.Isolate({ + memoryLimit: limits.memoryLimit, + importModuleDynamically: (specifier, referrer) => + this.modules.import(String(specifier), String(referrer)), + onUnhandledRejection: (error) => { + this.log("error", `Unhandled rejection: ${String(error)}`); + }, + }); + this.modules = new ModuleLoader({ + isolate: this.isolate, + context: () => this.context, + baseURL: () => init.url, + timeout: () => this.taskTimeout, + fetch: (request) => this.fetchThroughPage(request), + }); + } + + async boot( + source: string, + cachedData: ivm.ExternalCopy | undefined, + ): Promise | undefined> { + const ivmModule = this.ivm; + try { + const script: ivm.Script & ivm.CachedDataResult = + await this.isolate.compileScript( + source, + { + filename: "termdom:frame", + ...(cachedData ? {cachedData} : {produceCachedData: true}), + }, + ); + this.context = await this.isolate.createContext(); + const boot = (await script.run(this.context, { + reference: true, + })) as unknown as ivm.Reference< + (...args: unknown[]) => unknown + >; + const callbacks: Record<(typeof HOST_CALLBACKS)[number], unknown> = { + post: new ivmModule.Callback( + (message: FrameMessage) => this.onPost(message), + {ignored: true}, + ), + log: new ivmModule.Callback( + (level: string, text: string) => this.log(level, text), + {ignored: true}, + ), + setTimer: new ivmModule.Callback( + (id: number, ms: number) => this.setTimer(id, ms), + {ignored: true}, + ), + clearTimer: new ivmModule.Callback( + (id: number) => this.clearTimer(id), + {ignored: true}, + ), + random: new ivmModule.Callback((length: number) => this.random(length)), + scripts: new ivmModule.Callback( + (initial: boolean, items: ScriptItem[]) => + this.runScripts(items, initial), + {ignored: true}, + ), + }; + const starter = (await boot.apply( + undefined, + HOST_CALLBACKS.map((name) => callbacks[name]) as ivm.Transferable[], + {timeout: BOOT_TIMEOUT, result: {reference: true}}, + )) as ivm.Reference<(init: FrameInit) => unknown>; + boot.release(); + this.dispatch = (await starter.apply( + undefined, + [this.init], + { + arguments: {copy: true}, + timeout: this.taskTimeout, + result: {reference: true}, + }, + )) as Dispatch; + starter.release(); + const queued = this.queued ?? []; + this.queued = null; + for (const args of queued) { + void this.call(...args); + } + return script.cachedData; + } catch (error) { + this.fail(error); + return undefined; + } + } + + call(kind: string, ...args: unknown[]): Promise { + if (this.disposed) { + return Promise.resolve(); + } + if (this.queued !== null || this.dispatch === null) { + this.queued?.push([kind, ...args]); + return Promise.resolve(); + } + return this.dispatch + .apply( + undefined, + [kind, ...args], + {arguments: {copy: true}, timeout: this.taskTimeout}, + ) + .then(() => {}, (error: unknown) => this.fail(error)); + } + + send(message: HostMessage): void { + if ( + (message.type === "response" || message.type === "fetchError") && + message.id < 0 + ) { + const own = this.ownLoads.get(message.id); + this.ownLoads.delete(message.id); + if (message.type === "response") { + own?.resolve(message.response); + } else { + own?.reject(new TypeError(`Failed to fetch: ${message.message}`)); + } + return; + } + void this.call("receive", message); + } + + onPost(message: FrameMessage): void { + if (this.disposed) { + return; + } + if ( + (message.type === "fetch" || message.type === "abortFetch") && + !(message.id > 0) + ) { + return; + } + this.receive(message); + } + + fail(error: unknown): void { + if (this.disposed) { + return; + } + const text = error instanceof Error ? error.message : String(error); + this.log("error", `The frame stopped: ${text}`); + this.dispose(); + } + + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + for (const timer of this.timers.values()) { + clearTimeout(timer); + } + this.timers.clear(); + for (const own of this.ownLoads.values()) { + own.reject(new TypeError("The frame is closed")); + } + this.ownLoads.clear(); + if (!this.isolate.isDisposed) { + this.isolate.dispose(); + } + } + + setTimer(id: number, ms: number): void { + if (this.disposed) { + return; + } + this.clearTimer(id); + if (this.timers.size >= MAX_TIMERS) { + this.log("warn", "Too many timers; this one will not fire"); + return; + } + this.timers.set( + id, + setTimeout(() => { + this.timers.delete(id); + void this.call("timer", id); + }, ms), + ); + } + + clearTimer(id: number): void { + const timer = this.timers.get(id); + if (timer !== undefined) { + clearTimeout(timer); + this.timers.delete(id); + } + } + + random(length: number): Uint8Array { + const size = Math.max(0, Math.min(Number(length) | 0, MAX_RANDOM_BYTES)); + return randomFillSync(new Uint8Array(size)); + } + + // The backend's own loads, a script's or a module's source, go to the + // page with ids below zero, so the frame's own stay above it. + fetchThroughPage(request: FrameRequest): Promise { + if (this.disposed) { + return Promise.reject(new TypeError("The frame is closed")); + } + const id = this.nextOwnLoad--; + return new Promise((resolve, reject) => { + this.ownLoads.set(id, {resolve, reject}); + this.receive({type: "fetch", id, request}); + }); + } + + runScripts(items: ScriptItem[], initial: boolean): void { + for (const script of items.slice(0, MAX_SCRIPTS - this.scriptCount)) { + this.scriptCount++; + const source = script.kind === "classic" && script.src !== null + ? this.loadScript(script.src) + : null; + source?.catch(() => {}); + if (script.async) { + const run = this.runScript(script, source); + this.asyncScripts.add(run); + void run.then(() => this.asyncScripts.delete(run)); + } else { + this.scriptQueue = this.scriptQueue.then(() => + this.runScript(script, source), + ); + } + } + if (initial) { + this.scriptQueue = this.scriptQueue.then(() => this.call("interactive")); + void this.scriptQueue + .then(async () => { + while (this.asyncScripts.size > 0) { + await Promise.all(this.asyncScripts); + } + }) + .then(() => this.call("loaded")); + } + } + + async runScript( + script: ScriptItem, + source: Promise | null, + ): Promise { + if (this.disposed) { + return; + } + let ok = true; + try { + if (script.kind === "importmap") { + this.modules.addImportMap(script.text ?? "", this.init.url); + } else if (script.kind === "module") { + if (script.src !== null) { + await this.modules.import(script.src, this.init.url); + } else { + await this.modules.importSource( + script.text ?? "", + `${this.init.url}#module-${script.id}`, + this.init.url, + ); + } + } else { + const text = script.src === null + ? script.text ?? "" + : await (source ?? this.loadScript(script.src)); + await this.execute(script, text); + } + } catch (error) { + ok = false; + if (this.isFatal(error)) { + this.fail(error); + return; + } + this.log( + "error", + `Uncaught ${error instanceof Error ? error.stack ?? error.message : String(error)}`, + ); + } + if (script.src !== null) { + void this.call("scriptFinished", script.id, ok); + } + } + + execute(script: ScriptItem, source: string): Promise { + const run = this.executing.then(async () => { + await this.call("scriptBegin", script.id); + try { + await this.context.eval(source, { + filename: script.src ?? this.init.url, + timeout: this.taskTimeout, + }); + } finally { + if (!this.disposed) { + await this.call("scriptEnd", script.id); + } + } + }); + this.executing = run.catch(() => {}); + return run; + } + + isFatal(error: unknown): boolean { + return this.isolate.isDisposed || + /timed out|memory limit|disposed/i.test(String(error)); + } + + async loadScript(url: string): Promise { + const response = await this.fetchThroughPage({ + url, + method: "GET", + headers: [["accept", "*/*"]], + body: null, + redirect: "follow", + destination: "script", + referrer: "", + }); + if (response.status < 200 || response.status > 299) { + throw new TypeError( + `Failed to load the script ${url}: ${response.status}`, + ); + } + return new TextDecoder().decode(response.body ?? new Uint8Array()); + } +} diff --git a/src/internal/isolatedvmmodules.ts b/src/internal/isolatedvmmodules.ts new file mode 100644 index 00000000..4e279362 --- /dev/null +++ b/src/internal/isolatedvmmodules.ts @@ -0,0 +1,280 @@ +/** + * Module scripts in an isolated frame: specifiers resolved through the + * page's import maps, sources loaded through the page, and each module + * compiled once in the frame's isolate and linked in order. + */ +import type ivm from "isolated-vm"; + +import type {FrameRequest, FrameResponse} from "./isolate/host.ts"; + +const JAVASCRIPT = /^(text|application)\/(x-)?(java|ecma)script$/; +const RELATIVE = /^(\.{0,2}\/)/; +const ISOLATE_REFERRER = ""; + +type SpecifierMap = Map; + +interface ImportMap { + imports: SpecifierMap; + scopes: Map; +} + +function parseURL(value: string, base?: string): string | null { + try { + return new URL(value, base).href; + } catch (error) { + if (!(error instanceof TypeError)) { + throw error; + } + + return null; + } +} + +function parseURLLike(specifier: string, base: string): string | null { + return RELATIVE.test(specifier) + ? parseURL(specifier, base) + : parseURL(specifier); +} + +function parseSpecifierMap(value: unknown, base: string): SpecifierMap { + const map: SpecifierMap = new Map(); + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return map; + } + + for (const [key, address] of Object.entries(value)) { + if (key === "") { + continue; + } + + const url = typeof address === "string" + ? parseURLLike(address, base) + : null; + map.set( + parseURLLike(key, base) ?? key, + url !== null && key.endsWith("/") && !url.endsWith("/") ? null : url, + ); + } + + return map; +} + +function matchSpecifier( + specifier: string, + map: SpecifierMap, +): string | null | undefined { + if (map.has(specifier)) { + return map.get(specifier); + } + + let best: string | undefined; + for (const key of map.keys()) { + if ( + key.endsWith("/") && + specifier.startsWith(key) && + (best === undefined || key.length > best.length) + ) { + best = key; + } + } + + if (best === undefined) { + return undefined; + } + + const address = map.get(best); + return address == null + ? null + : parseURL(specifier.slice(best.length), address); +} + +export interface ModuleHost { + isolate: ivm.Isolate; + context(): ivm.Context; + baseURL(): string; + timeout(): number; + fetch(request: FrameRequest): Promise; +} + +export class ModuleLoader { + readonly host: ModuleHost; + readonly modules: Map>; + readonly ready: Map>; + readonly urls: WeakMap; + readonly importMap: ImportMap; + linking: Promise; + + constructor(host: ModuleHost) { + this.host = host; + this.modules = new Map(); + this.ready = new Map(); + this.urls = new WeakMap(); + this.importMap = {imports: new Map(), scopes: new Map()}; + this.linking = Promise.resolve(); + } + + addImportMap(text: string, base: string): void { + const value = JSON.parse(text) as unknown; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new TypeError("An import map must be a JSON object"); + } + + const {imports, scopes} = value as {imports?: unknown; scopes?: unknown}; + for (const [key, url] of parseSpecifierMap(imports, base)) { + if (!this.importMap.imports.has(key)) { + this.importMap.imports.set(key, url); + } + } + + if (typeof scopes !== "object" || scopes === null) { + return; + } + + for (const [prefix, map] of Object.entries(scopes)) { + const scope = parseURL(prefix, base); + if (scope === null) { + continue; + } + + const existing = this.importMap.scopes.get(scope) ?? new Map(); + for (const [key, url] of parseSpecifierMap(map, base)) { + if (!existing.has(key)) { + existing.set(key, url); + } + } + + this.importMap.scopes.set(scope, existing); + } + } + + resolve(specifier: string, referrer: string): string { + const base = referrer === ISOLATE_REFERRER || referrer === "" + ? this.host.baseURL() + : referrer; + const url = parseURLLike(specifier, base); + const key = url ?? specifier; + const scopes = [...this.importMap.scopes] + .filter(([scope]) => + scope === base || (scope.endsWith("/") && base.startsWith(scope))) + .sort(([a], [b]) => b.length - a.length); + for (const map of [ + ...scopes.map(([, map]) => map), + this.importMap.imports, + ]) { + const match = matchSpecifier(key, map); + if (match === null) { + throw new TypeError( + `Failed to resolve module specifier "${specifier}": the import map blocks it`, + ); + } + + if (match !== undefined) { + return match; + } + } + + if (url === null) { + throw new TypeError( + `Failed to resolve module specifier "${specifier}": a bare specifier must be in the page's import map`, + ); + } + + return url; + } + + fetchModule(url: string): Promise { + let module = this.modules.get(url); + if (module === undefined) { + module = this.compile(url); + this.modules.set(url, module); + } + + return module; + } + + async compile(url: string): Promise { + const response = await this.host.fetch({ + url, + method: "GET", + headers: [["accept", "*/*"]], + body: null, + redirect: "follow", + destination: "script", + referrer: "", + }); + if (response.status < 200 || response.status > 299) { + throw new TypeError(`Failed to load module ${url}: ${response.status}`); + } + + const type = + response.headers.find(([name]) => name === "content-type")?.[1]; + const essence = (type ?? "").split(";")[0].trim().toLowerCase(); + if (!JAVASCRIPT.test(essence)) { + throw new TypeError( + `Failed to load module ${url}: "${essence || "no type"}" is not a JavaScript MIME type`, + ); + } + + const final = response.url || url; + const module = await this.host.isolate.compileModule( + new TextDecoder().decode(response.body ?? new Uint8Array()), + { + filename: final, + meta: (meta: {url?: string}) => { + meta.url = final; + }, + }, + ); + this.urls.set(module, response.url || url); + return module; + } + + import(specifier: string, referrer: string): Promise { + const url = this.resolve(specifier, referrer); + let module = this.ready.get(url); + if (module === undefined) { + module = this.link(url); + this.ready.set(url, module); + } + + return module; + } + + async importSource( + source: string, + url: string, + base: string, + ): Promise { + const module = await this.host.isolate.compileModule(source, { + filename: url, + meta: (meta: {url?: string}) => { + meta.url = base; + }, + }); + this.urls.set(module, url); + this.modules.set(url, Promise.resolve(module)); + return this.link(url); + } + + async link(url: string): Promise { + const module = await this.fetchModule(url); + const previous = this.linking; + let done!: () => void; + this.linking = new Promise((resolve) => (done = resolve)); + try { + await previous; + await module.instantiate(this.host.context(), (specifier, referrer) => + this.fetchModule( + this.resolve(specifier, this.urls.get(referrer) ?? ""), + ), + ); + } finally { + done(); + } + + await module.evaluate( + {timeout: this.host.timeout(), promise: true} as ivm.ScriptRunOptions, + ); + return module; + } +} From c8161743b9cfd1e41a0b08d153d5247007066421 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:45:23 -0500 Subject: [PATCH 07/25] Start isolated frames in isolated-vm with isolatedFrames: "auto" The frame runtime and the isolated-vm backend speak the page's protocol: the frame learns its parent's origin, says whether it navigates itself or its parent, and says when its isolate stopped. "auto" loads the backend with the first frame, as an optional peer dependency, and a frame whose backend cannot load crashes and says why. A frame that sends its parent elsewhere is held to its sandbox through the parent's own navigation, and the page gives the frame the cell size in CSS pixels its layout divides by. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- package.json | 4 + src/index.ts | 13 ++- src/internal/dom.ts | 20 ++++ src/internal/isolate/frame.ts | 1 + src/internal/isolate/host.ts | 78 ++------------ src/internal/isolatedframes.ts | 100 ++++++++++++++++-- src/internal/isolatedvm.ts | 17 +-- src/internal/isolateprotocol.ts | 15 ++- tests/isolated-frames.test.ts | 4 +- tests/isolated-vm-frames.test.ts | 174 +++++++++++++++++++++++++++++++ 10 files changed, 327 insertions(+), 99 deletions(-) create mode 100644 tests/isolated-vm-frames.test.ts diff --git a/package.json b/package.json index 5043de6a..d680690c 100644 --- a/package.json +++ b/package.json @@ -54,9 +54,13 @@ "parse5": "8.1.0" }, "peerDependencies": { + "isolated-vm": "^7.0.2", "node-pty": "^1.1.0" }, "peerDependenciesMeta": { + "isolated-vm": { + "optional": true + }, "node-pty": { "optional": true } diff --git a/src/index.ts b/src/index.ts index b680a46c..d063ca7e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,4 @@ import "./internal/frames.ts"; -import "./internal/isolatedframes.ts"; import "./internal/inspector.ts"; import type {CanvasCellGridContext} from "./internal/canvas.ts"; @@ -110,6 +109,7 @@ import { setDecodeWorkerURL, } from "./internal/images.ts"; import {Input, resolvePendingHover} from "./internal/input.ts"; +import {startInIsolatedVM} from "./internal/isolatedframes.ts"; import type {FrameIsolator} from "./internal/isolateprotocol.ts"; import { compressKittyUploads, @@ -373,6 +373,10 @@ export interface TermDOMOptions { * through `postMessage()`, as windows of two origins do. A page that * freezes or runs out of memory there takes its frame down alone. * - `"none"` (the default): the frame shows an empty `about:blank`. + * - `"auto"`: in a V8 isolate of its own, through the isolated-vm + * package, on Node when it is installed. Each has 256 MB of heap, + * and each call into it 30 seconds. Where isolated-vm cannot load, + * as on Bun and Deno, the frame shows nothing. * - A function: called with the frame's document and the terminal it * is drawn for, and with where to send what the frame sends. It * returns the frame, which takes the page's messages until it is @@ -380,7 +384,7 @@ export interface TermDOMOptions { * Any other value throws a TypeError. * @experimental The messages may change in a minor release. */ - isolatedFrames?: "none" | FrameIsolator; + isolatedFrames?: "none" | "auto" | FrameIsolator; /** * The colors the terminal shows, in the bits `screen.colorDepth` @@ -521,10 +525,13 @@ function toFrameIsolator( if (option === undefined || option === "none") { return null; } + if (option === "auto") { + return startInIsolatedVM; + } if (typeof option === "function") { return option; } - throw new TypeError('isolatedFrames must be "none" or a function'); + throw new TypeError('isolatedFrames must be "none", "auto" or a function'); } function toFailFast(option: unknown): boolean { diff --git a/src/internal/dom.ts b/src/internal/dom.ts index 4c1b5123..0154c5b8 100644 --- a/src/internal/dom.ts +++ b/src/internal/dom.ts @@ -40233,6 +40233,26 @@ function navigateWindow( } } +/** + * An isolated frame's navigation of the window its iframe is in, which + * `window` stands in the page for, held to the frame's sandbox. What the + * parent or its navigate listeners refuse comes to nothing, as the frame + * that asked is in another isolate. + */ +export function navigateFrameParent(window: Window, url: string): void { + const parent = _(window).parentWindow; + if (parent === null || _(window).discarded) { + return; + } + try { + navigateWindow(window, parent, url, "auto"); + } catch (error) { + if (!(error instanceof DOMException)) { + throw error; + } + } +} + // A setter of one part of the URL: the location navigates to its URL with // that part changed. A URL with an opaque path has no host, port or path // to change, and a protocol other than http and https is not one to go to. diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index 06eb9ceb..4b889994 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -150,6 +150,7 @@ function createFrame(init: FrameInit): Frame { devicePixelRatio: pixelRatio, images: "cells", canvas: "cells", + isolateFrame: null, load: (request) => fetch(request), loadSignal: loads.signal, reportUncaught: (error) => { diff --git a/src/internal/isolate/host.ts b/src/internal/isolate/host.ts index 8d9061bc..1fccc496 100644 --- a/src/internal/isolate/host.ts +++ b/src/internal/isolate/host.ts @@ -5,78 +5,16 @@ * runtime. Messages are plain values and typed arrays, so any backend * that copies structured data can carry them. */ -import type { - ColorDepth, - WireFocus, - WireKey, - WireMouse, - WirePaste, -} from "../exchange.ts"; -import type {GridCells} from "../framebuffer.ts"; +import type {FrameMessage} from "../isolateprotocol.ts"; import type {ScriptItem} from "./scripts.ts"; -export interface FrameRequest { - url: string; - method: string; - headers: Array<[string, string]>; - body: Uint8Array | null; - redirect: RequestRedirect; - destination: string; - referrer: string; -} - -export interface FrameResponse { - url: string; - status: number; - statusText: string; - headers: Array<[string, string]>; - redirected: boolean; - body: Uint8Array | null; -} - -export interface FrameCaret { - col: number; - row: number; - shape: number; - color: number | null; -} - -export type FrameMessage = - {type: "paint"; cells: GridCells; caret: FrameCaret | null} | - {type: "title"; title: string} | - {type: "navigate"; target: "self" | "parent"; url: string} | - {type: "load"} | - {type: "message"; data: unknown; targetOrigin: string} | - {type: "fetch"; id: number; request: FrameRequest} | - {type: "abortFetch"; id: number}; - -export interface FrameInit { - url: string; - html: string; - parentOrigin: string; - cols: number; - rows: number; - cellWidth: number; - cellHeight: number; - pixelRatio: number; - colorDepth: ColorDepth; - colorScheme: "light" | "dark"; - scripting: boolean; -} - -export type HostMessage = - { - type: "resize"; - cols: number; - rows: number; - cellWidth: number; - cellHeight: number; - pixelRatio: number; - } | - {type: "input"; item: WireKey[] | WireMouse | WirePaste | WireFocus} | - {type: "message"; data: unknown; origin: string; targetOrigin: string} | - {type: "response"; id: number; response: FrameResponse} | - {type: "fetchError"; id: number; message: string}; +export type { + FrameInit, + FrameMessage, + FrameRequest, + FrameResponse, + HostMessage, +} from "../isolateprotocol.ts"; export interface IsolateHost { post(message: FrameMessage): void; diff --git a/src/internal/isolatedframes.ts b/src/internal/isolatedframes.ts index 0b6e2087..001dda7d 100644 --- a/src/internal/isolatedframes.ts +++ b/src/internal/isolatedframes.ts @@ -13,6 +13,7 @@ import { Event, type HTMLIFrameElement, type IsolatedFrameView, + navigateFrameParent, receiveFrameMessage, setIsolatedFrameFactory, setRequestDestination, @@ -26,6 +27,7 @@ import { importGrid, } from "./framebuffer.ts"; import type { + FrameInit, FrameIsolator, FrameMessage, FrameRequest, @@ -33,6 +35,7 @@ import type { IsolatedFrame, } from "./isolateprotocol.ts"; import {_} from "./slots.ts"; +import {getCellSize} from "./units.ts"; // The loads a frame may have in flight at once. const MAX_FETCHES = 64; @@ -157,6 +160,7 @@ class RemoteFrame implements IsolatedFrameView { } this.url = documentURL; const framebuffer = engine.framebuffer; + const cell = getCellSize(this.parent); const view = engine.defaultView as globalThis.Window | null; const media = (query: string) => view?.matchMedia(query).matches ?? false; const sandbox = _(this.window).sandbox; @@ -164,10 +168,11 @@ class RemoteFrame implements IsolatedFrameView { { url: documentURL, html, + parentOrigin: view?.origin ?? "null", cols: this.cols, rows: this.rows, - cellWidth: framebuffer.cellPixels.width, - cellHeight: framebuffer.cellPixels.height, + cellWidth: cell.width, + cellHeight: cell.height, pixelRatio: framebuffer.pixelRatio ?? 1, colorDepth: framebuffer.writer.colorDepth, colorScheme: media("(prefers-color-scheme: dark)") ? "dark" : "light", @@ -210,7 +215,18 @@ class RemoteFrame implements IsolatedFrameView { this.changed(); break; case "navigate": - this.navigate(message.url); + if (message.target === "parent") { + navigateFrameParent(this.window, String(message.url)); + } else { + this.navigate(message.url); + } + break; + case "crash": + this.stop(); + this.cells = null; + this.caret = null; + this.stale = true; + this.changed(); break; case "load": this.frame.dispatchEvent(constructInternal(() => new Event("load"))); @@ -352,15 +368,15 @@ class RemoteFrame implements IsolatedFrameView { this.rows = rows; this.grid = new CellGrid(rows, cols); this.stale = true; - const cell = _(this.parent).extra.framebuffer; + const cell = getCellSize(this.parent); if (this.running !== null) { this.running.send({ type: "resize", cols, rows, - cellWidth: cell.cellPixels.width, - cellHeight: cell.cellPixels.height, - pixelRatio: cell.pixelRatio ?? 1, + cellWidth: cell.width, + cellHeight: cell.height, + pixelRatio: _(this.parent).extra.framebuffer.pixelRatio ?? 1, }); } } @@ -431,6 +447,76 @@ class RemoteFrame implements IsolatedFrameView { } } +// A frame started before its backend has loaded, which starts there and +// sends what it was given once the backend has. +class PendingFrame implements IsolatedFrame { + init: FrameInit; + receive: (message: FrameMessage) => void; + waiting: HostMessage[]; + frame: IsolatedFrame | null; + disposed: boolean; + + constructor( + init: FrameInit, + receive: (message: FrameMessage) => void, + backend: Promise, + ) { + this.init = init; + this.receive = receive; + this.waiting = []; + this.frame = null; + this.disposed = false; + void backend.then((isolate) => this.start(isolate)); + } + + start(isolate: FrameIsolator | string): void { + if (this.disposed) { + return; + } + if (typeof isolate === "string") { + this.receive({type: "crash", reason: isolate}); + return; + } + this.frame = isolate(this.init, this.receive); + for (const message of this.waiting.splice(0)) { + this.frame.send(message); + } + } + + send(message: HostMessage): void { + if (this.frame === null) { + this.waiting.push(message); + } else { + this.frame.send(message); + } + } + + dispose(): void { + this.disposed = true; + this.waiting = []; + this.frame?.dispose(); + } +} + +let isolatedVM: Promise | null = null; + +/** + * The isolator isolatedFrames: "auto" names: isolated-vm's, loaded with + * the first frame. Where isolated-vm cannot load, each frame crashes and + * says why. + */ +export function startInIsolatedVM( + init: FrameInit, + receive: (message: FrameMessage) => void, +): IsolatedFrame { + isolatedVM ??= import("./isolatedvm.ts") + .then((backend) => backend.createIsolatedVMFrames()) + .catch((error: unknown) => + `isolated-vm could not load: ${describeError(error)}`, + ); + return new PendingFrame(init, receive, isolatedVM); +} + setIsolatedFrameFactory((frame, window, url, parent, isolate, changed) => new RemoteFrame(frame, window, url, parent, isolate, changed), ); diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts index 16f7b600..8625db48 100644 --- a/src/internal/isolatedvm.ts +++ b/src/internal/isolatedvm.ts @@ -12,15 +12,16 @@ import {randomFillSync} from "node:crypto"; import type ivm from "isolated-vm"; import {HOST_CALLBACKS, loadFrameScript} from "./isolate/bundle.ts"; +import type {ScriptItem} from "./isolate/scripts.ts"; +import {ModuleLoader} from "./isolatedvmmodules.ts"; import type { FrameInit, + FrameIsolator, FrameMessage, FrameRequest, FrameResponse, HostMessage, -} from "./isolate/host.ts"; -import type {ScriptItem} from "./isolate/scripts.ts"; -import {ModuleLoader} from "./isolatedvmmodules.ts"; +} from "./isolateprotocol.ts"; export const DEFAULT_MEMORY_LIMIT = 256; export const DEFAULT_TASK_TIMEOUT = 30000; @@ -30,16 +31,6 @@ const MAX_TIMERS = 10000; const MAX_SCRIPTS = 1000; const MAX_LOG_LENGTH = 4096; -export interface IsolatedFrame { - send(message: HostMessage): void; - dispose(): void; -} - -export type FrameIsolator = ( - init: FrameInit, - receive: (message: FrameMessage) => void, -) => IsolatedFrame; - export interface IsolatedVMOptions { // Megabytes of heap each frame's isolate may use. memoryLimit?: number; diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts index ffb78d95..5aec0f43 100644 --- a/src/internal/isolateprotocol.ts +++ b/src/internal/isolateprotocol.ts @@ -18,6 +18,9 @@ import type {Caret, GridCells} from "./framebuffer.ts"; export interface FrameInit { url: string; html: string; + // The origin of the window the frame's iframe is in, which the frame's + // parent and top have. + parentOrigin: string; cols: number; rows: number; cellWidth: number; @@ -34,7 +37,7 @@ export interface FrameRequest { method: string; headers: Array<[string, string]>; body: Uint8Array | null; - redirect: "follow" | "manual" | "error"; + redirect: RequestRedirect; destination: string; referrer: string; } @@ -45,17 +48,21 @@ export interface FrameResponse { statusText: string; headers: Array<[string, string]>; redirected: boolean; - body: Uint8Array; + body: Uint8Array | null; } export type FrameMessage = {type: "paint"; cells: GridCells; caret: Caret | null} | {type: "title"; title: string} | - {type: "navigate"; url: string} | + // The frame went to another document, or sent its parent to one. + {type: "navigate"; target: "self" | "parent"; url: string} | {type: "load"} | {type: "message"; data: unknown; targetOrigin: string} | {type: "fetch"; id: number; request: FrameRequest} | - {type: "abortFetch"; id: number}; + {type: "abortFetch"; id: number} | + // The frame ran past its time or memory, or failed to start, and its + // isolate is gone. + {type: "crash"; reason: string}; export type HostMessage = { diff --git a/tests/isolated-frames.test.ts b/tests/isolated-frames.test.ts index a5332413..09b5acef 100644 --- a/tests/isolated-frames.test.ts +++ b/tests/isolated-frames.test.ts @@ -362,6 +362,6 @@ test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goe dom.dispose(); }); -test("isolatedFrames takes \"none\" or a function", () => { - expect(() => new TermDOM({isolatedFrames: "auto" as any})).toThrow(TypeError); +test("isolatedFrames takes \"none\", \"auto\" or a function", () => { + expect(() => new TermDOM({isolatedFrames: "yes" as any})).toThrow(TypeError); }); diff --git a/tests/isolated-vm-frames.test.ts b/tests/isolated-vm-frames.test.ts new file mode 100644 index 00000000..4d9e177d --- /dev/null +++ b/tests/isolated-vm-frames.test.ts @@ -0,0 +1,174 @@ +/** + * Frames in isolated-vm's isolates, end to end: the page loads the + * frame's document, the frame lays it out, runs its scripts and paints it + * in an isolate of its own, and the page draws it, hands it keys and + * trades messages with it. A frame that runs forever is stopped alone. + * isolated-vm loads on Node only. + */ +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {createIsolatedVMFrames} from "../src/internal/isolatedvm.ts"; +import {inputDispatched, MockProcess, nextFrame, until} from "./test-utils.ts"; + +const onNode = + (globalThis as {Bun?: unknown}).Bun === undefined && + (globalThis as {Deno?: unknown}).Deno === undefined; +const nodeTest = onNode ? test : test.skip; + +function rows(terminal: MockProcess, count: number): string[] { + const buffer = (terminal as any).terminal.buffer.active; + return Array.from( + {length: count}, + (_, row) => buffer.getLine(row).translateToString(true).trimEnd(), + ); +} + +function servePages(dom: TermDOM, pages: Record): void { + dom.addEventListener("fetch", (event: any) => { + const page = pages[event.request.url]; + if (page !== undefined) { + event.respondWith( + new Response(page, {headers: {"content-type": "text/html"}}), + ); + } + }); +} + +async function drawn( + dom: TermDOM, + terminal: MockProcess, + text: string, +): Promise { + const deadline = Date.now() + 20000; + while (Date.now() < deadline) { + await nextFrame(dom); + if (rows(terminal, 12).some((row) => row.includes(text))) { + break; + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + return rows(terminal, 12); +} + +const FRAME = "display: block; border: 1px solid; width: 30ch; height: 5px"; + +nodeTest( + "a frame's document is laid out and painted in its own isolate", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + isolatedFrames: "auto", + }); + servePages(dom, { + "https://frame.example/": "

from the isolate

", + }); + dom.document.body.innerHTML = + `

page

`; + const screen = await drawn(dom, terminal, "from the isolate"); + expect(screen.slice(0, 3)).toEqual([ + "page", + "┌────────────────────────────┐", + "│from the isolate │", + ]); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "a frame's scripts run there, and it trades messages with the page", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + url: "https://page.example/", + scripting: "enabled", + isolatedFrames: "auto", + }); + servePages(dom, { + "https://frame.example/": + "

waiting

", + }); + const received: string[] = []; + dom.window.addEventListener("message", (event: MessageEvent) => { + received.push(event.data); + }); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + await dom.attach(); + await until(() => received.includes("ready")); + expect(received).toEqual(["ready"]); + frame.contentWindow!.postMessage("ping", "https://frame.example"); + await until(() => received.includes("got ping")); + const screen = await drawn(dom, terminal, "ping from"); + expect(screen.slice(1, 3)).toEqual([ + "│ping from https:// │", + "│page.example │", + ]); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "keys typed into a focused frame reach its field", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: "auto", + }); + servePages(dom, { + "https://frame.example/": + "", + }); + dom.document.body.innerHTML = + ``; + await dom.attach(); + await drawn(dom, terminal, "┌"); + dom.document.querySelector("iframe")!.focus(); + await nextFrame(dom); + terminal.stdin.simulateResponse("typed"); + await inputDispatched(); + const screen = await drawn(dom, terminal, "typed"); + expect(screen[1]).toMatch(/^│typed/); + await dom.dispose(); + }, + 60000, +); + +nodeTest( + "a frame that runs forever is stopped, and the page goes on", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + scripting: "enabled", + isolatedFrames: await createIsolatedVMFrames({taskTimeout: 200}), + }); + servePages(dom, { + "https://spin.example/": "

spin

", + "https://calm.example/": "

calm

", + }); + dom.document.body.innerHTML = + `` + + ``; + const screen = await drawn(dom, terminal, "calm"); + expect(screen).toContain("│calm │"); + dom.document.body.append("after"); + const later = await drawn(dom, terminal, "after"); + expect(later.some((row) => row.includes("after"))).toBe(true); + await dom.dispose(); + }, + 60000, +); From 1fbba9845b516477b8a1d96ff6e24511511e4ca9 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:50:09 -0500 Subject: [PATCH 08/25] Edit, focus and click in an isolated frame, and say when it crashes The frame's stand-in exchange gets editing and the document its autofocus, as a TermDOM's own do, and the reduced motion the page has. A click arrives in the frame's cells from zero and goes to the engine from one, as a terminal reports it. A frame stopped for time, memory or a failed start posts crash. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/isolate/frame.ts | 22 ++++++++++++++++++++-- src/internal/isolatedvm.ts | 6 ++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index 4b889994..5e86c67b 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -7,13 +7,15 @@ import "./install.ts"; import "../frames.ts"; -import {Cascade} from "../cssom.ts"; +import {Cascade, setReducedMotion} from "../cssom.ts"; import { type Document, findRuntimeFetchClasses, findRuntimeGlobals, + focusInitialAutofocus, type Window, } from "../dom.ts"; +import {installEditing} from "../editing.ts"; import {Exchange, type TerminalTransport} from "../exchange.ts"; import {exportGrid, Framebuffer} from "../framebuffer.ts"; import {createFrameEngine} from "../frames.ts"; @@ -35,6 +37,8 @@ import {fireTimer, queueTask} from "./timers.ts"; export {fireTimer}; +type WireInput = Parameters[1]; + function nullTransport(cols: number, rows: number): TerminalTransport { return { cols, @@ -166,6 +170,12 @@ function createFrame(init: FrameInit): Frame { ); const extra = _(document).extra; extra.framebuffer.measurer = exchange; + installEditing(exchange); + setReducedMotion( + document as unknown as globalThis.Document, + init.reducedMotion, + ); + focusInitialAutofocus(document as unknown as globalThis.Document); const input = new Input( document as unknown as globalThis.Document, extra.layout, @@ -248,7 +258,7 @@ function createFrame(init: FrameInit): Frame { schedule(); return; case "input": - dispatchInput(input, message.item); + dispatchInput(input, toWireInput(message.item)); schedule(); return; case "message": { @@ -304,6 +314,14 @@ function createExchange(window: Window, init: FrameInit): Exchange { ); } +// The page reports a click in the frame's own cells, counted from zero. +// The engine reads mouse reports as the terminal sends them, from one. +function toWireInput(item: WireInput): WireInput { + return !Array.isArray(item) && item.kind === "mouse" + ? {...item, col: item.col + 1, row: item.row + 1} + : item; +} + function describe(error: unknown): string { return error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts index 8625db48..05c9222c 100644 --- a/src/internal/isolatedvm.ts +++ b/src/internal/isolatedvm.ts @@ -265,6 +265,12 @@ class IsolatedVMFrame { const text = error instanceof Error ? error.message : String(error); this.log("error", `The frame stopped: ${text}`); this.dispose(); + this.receive({ + type: "crash", + reason: /timed out/i.test(text) + ? "timeout" + : /memory limit/i.test(text) ? "memory" : "error", + }); } dispose(): void { From 37e78a7e65035d543d1052c3ee3d8e32ea499bb4 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:50:09 -0500 Subject: [PATCH 09/25] Load an isolated frame's linked stylesheets before its first paint TermDOM leaves to whoever loads the document. The frame fetches each one through the page, puts its rules after the link with URLs made absolute, and holds its first paint up to five seconds for them. Links added later load as they come. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/isolate/frame.ts | 22 +++++- src/internal/isolate/stylesheets.ts | 114 ++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 src/internal/isolate/stylesheets.ts diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index 5e86c67b..e98fbc32 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -33,7 +33,12 @@ import { import {deliverError, deliverResponse} from "./network.ts"; import {installPage} from "./page.ts"; import {ScriptRunner} from "./scripts.ts"; -import {fireTimer, queueTask} from "./timers.ts"; +import {loadStylesheets} from "./stylesheets.ts"; +import {clearTimeout, fireTimer, queueTask, setTimeout} from "./timers.ts"; + +// How long the first paint waits for the document's stylesheets, so it +// does not flash the page unstyled. +const STYLESHEET_WAIT = 5000; export {fireTimer}; @@ -131,6 +136,7 @@ function createFrame(init: FrameInit): Frame { _(window).parentWindow = parent; let queued = false; + let styled = false; let disposed = false; let title = ""; let loaded = false; @@ -213,7 +219,17 @@ function createFrame(init: FrameInit): Frame { scripts = new ScriptRunner(document as unknown as globalThis.Document); scripts.start(); } - schedule(); + let wait: number | undefined; + void Promise.race([ + loadStylesheets(document as unknown as globalThis.Document), + new Promise((resolve) => { + wait = setTimeout(resolve, STYLESHEET_WAIT); + }), + ]).finally(() => { + clearTimeout(wait); + styled = true; + schedule(); + }); // Without scripts, the document is loaded once its first paint is out. // With them, once the backend has run them all. @@ -226,7 +242,7 @@ function createFrame(init: FrameInit): Frame { function paint(): void { queued = false; - if (disposed) { + if (disposed || !styled) { return; } resolvePendingHover(input); diff --git a/src/internal/isolate/stylesheets.ts b/src/internal/isolate/stylesheets.ts new file mode 100644 index 00000000..2e48bc8b --- /dev/null +++ b/src/internal/isolate/stylesheets.ts @@ -0,0 +1,114 @@ +import {reportError} from "./console.ts"; +import {fetch, Request, setDestination} from "./fetch.ts"; + +const URL_TOKEN = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g; +const IMPORT_STRING = /@import\s+(['"])([^'"]+)\1/g; + +function absolutize(css: string, base: string): string { + const resolve = (url: string): string => { + if (/^(data:|#)/i.test(url)) { + return url; + } + + try { + return new URL(url, base).href; + } catch (error) { + if (!(error instanceof TypeError)) { + throw error; + } + + return url; + } + }; + return css + .replace(URL_TOKEN, (_, quote: string, url: string) => + `url(${quote}${resolve(url)}${quote})`) + .replace(IMPORT_STRING, (_, quote: string, url: string) => + `@import ${quote}${resolve(url)}${quote}`); +} + +function isStylesheetLink(element: Element): boolean { + if (element.localName !== "link" || element.hasAttribute("disabled")) { + return false; + } + + const rel = (element.getAttribute("rel") ?? "").toLowerCase().split(/\s+/); + return rel.includes("stylesheet") && !rel.includes("alternate"); +} + +export function loadStylesheets(document: Document): Promise { + const seen = new WeakSet(); + const fetchSheet = + async (link: Element): Promise => { + seen.add(link); + const href = (link as HTMLLinkElement).href; + if (!href) { + return null; + } + + const request = new Request(href); + setDestination(request, "style"); + const response = await fetch(request); + if (!response.ok) { + throw new Error(`${href} answered ${response.status}`); + } + + const style = document.createElement("style"); + const media = link.getAttribute("media"); + if (media) { + style.setAttribute("media", media); + } + + style.textContent = absolutize( + await response.text(), + response.url || href, + ); + return style; + }; + const place = (link: Element, style: HTMLStyleElement | null): void => { + if (style !== null && link.isConnected) { + link.after(style); + } + }; + const load = (link: Element): void => { + fetchSheet(link).then((style) => place(link, style), reportError); + }; + const scan = (root: ParentNode): void => { + for (const link of root.querySelectorAll("link")) { + if (!seen.has(link) && isStylesheetLink(link)) { + load(link); + } + } + }; + + const initial = [...document.querySelectorAll("link")] + .filter(isStylesheetLink); + const sheets = initial.map((link) => + fetchSheet(link).catch((error: unknown) => { + reportError(error); + return null; + }), + ); + const view = document.defaultView as unknown as { + MutationObserver: typeof MutationObserver; + }; + new view.MutationObserver((records) => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType !== 1) { + continue; + } + + const element = node as Element; + if (!seen.has(element) && isStylesheetLink(element)) { + load(element); + } else { + scan(element); + } + } + } + }).observe(document, {childList: true, subtree: true}); + return Promise.all(sheets).then((styles) => { + styles.forEach((style, i) => place(initial[i], style)); + }); +} From da2b29c55e5ac2c627678ba3cef4ec7225b559d7 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:53:13 -0500 Subject: [PATCH 10/25] Tell the page a frame's form posts and same-document URL changes A form posted from a frame navigates with its method, its fields in the encoding its enctype names, and their content type. pushState, replaceState and a fragment change send history with the new URL, and no longer pass for navigations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/isolate/frame.ts | 68 ++++++++++++++++++++++++++++++++- src/internal/isolateprotocol.ts | 13 ++++++- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index e98fbc32..d64d9538 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -196,13 +196,29 @@ function createFrame(init: FrameInit): Frame { ] of [["self", window], ["parent", parent]] as const) { view.navigation.addEventListener("navigate", (event) => { const navigate = event as NavigateEvent; - if (navigate.hashChange || !navigate.cancelable) { + if ( + navigate.hashChange || + navigate.destination.sameDocument || + !navigate.cancelable + ) { return; } navigate.preventDefault(); - host.post({type: "navigate", target, url: navigate.destination.url}); + host.post({ + type: "navigate", + target, + url: navigate.destination.url, + ...encodeForm(navigate.formData, navigate.sourceElement), + }); }); } + window.navigation.addEventListener("currententrychange", (event) => { + const type = (event as NavigationCurrentEntryChangeEvent).navigationType; + const url = window.navigation.currentEntry?.url; + if ((type === "push" || type === "replace") && url) { + host.post({type: "history", url, replace: type === "replace"}); + } + }); // The frame's postMessage to its parent lands on the stand-in, past the // targetOrigin check, and goes on to the page. parent.addEventListener("message", (event) => { @@ -330,6 +346,54 @@ function createExchange(window: Window, init: FrameInit): Exchange { ); } +// A form submitted with POST, in the encoding its enctype names. A file +// field sends its name only, since its bytes are not read here. +function encodeForm( + data: FormData | null, + source: Element | null, +): {method?: string; body?: Uint8Array; contentType?: string} { + if (data === null) { + return {}; + } + const control = source as HTMLButtonElement | HTMLInputElement | null; + const form = control?.form ?? (source as HTMLFormElement | null); + const enctype = ( + control?.getAttribute("formenctype") ?? form?.getAttribute("enctype") ?? "" + ).toLowerCase(); + const entries = [...data].map(([name, value]): [string, string] => [ + name, + typeof value === "string" ? value : value.name, + ]); + const encoder = new TextEncoder(); + if (enctype === "multipart/form-data") { + const boundary = `----termdom${Math.random().toString(16).slice(2)}`; + const parts = entries.map(([name, value]) => + `--${boundary}\r\nContent-Disposition: form-data; name="${ + name.replace(/"/g, "%22") + }"\r\n\r\n${value}\r\n`, + ); + return { + method: "POST", + body: encoder.encode(`${parts.join("")}--${boundary}--\r\n`), + contentType: `multipart/form-data; boundary=${boundary}`, + }; + } + if (enctype === "text/plain") { + return { + method: "POST", + body: encoder.encode( + entries.map(([name, value]) => `${name}=${value}\r\n`).join(""), + ), + contentType: "text/plain", + }; + } + return { + method: "POST", + body: encoder.encode(new URLSearchParams(entries).toString()), + contentType: "application/x-www-form-urlencoded", + }; +} + // The page reports a click in the frame's own cells, counted from zero. // The engine reads mouse reports as the terminal sends them, from one. function toWireInput(item: WireInput): WireInput { diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts index 5aec0f43..f5a81354 100644 --- a/src/internal/isolateprotocol.ts +++ b/src/internal/isolateprotocol.ts @@ -55,7 +55,18 @@ export type FrameMessage = {type: "paint"; cells: GridCells; caret: Caret | null} | {type: "title"; title: string} | // The frame went to another document, or sent its parent to one. - {type: "navigate"; target: "self" | "parent"; url: string} | + // A form's POST carries its method, its encoded fields and their type. + { + type: "navigate"; + target: "self" | "parent"; + url: string; + method?: string; + body?: Uint8Array | null; + contentType?: string; + } | + // The frame's document changed its URL in place: pushState, + // replaceState or a fragment. + {type: "history"; url: string; replace: boolean} | {type: "load"} | {type: "message"; data: unknown; targetOrigin: string} | {type: "fetch"; id: number; request: FrameRequest} | From 69db6f4276ba5bf793349a5af67d23d16683934b Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:53:13 -0500 Subject: [PATCH 11/25] Hold each isolated frame to its own limits, and report what it uses FrameInit.limits overrides the backend's memory and time limits for one frame. stats() gives the frame's CPU time, its longest task and its heap, or null once it is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/isolatedvm.ts | 38 ++++++++++++++++++++++++++++++--- src/internal/isolateprotocol.ts | 16 ++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts index 05c9222c..6d2c06d4 100644 --- a/src/internal/isolatedvm.ts +++ b/src/internal/isolatedvm.ts @@ -20,6 +20,7 @@ import type { FrameMessage, FrameRequest, FrameResponse, + FrameStats, HostMessage, } from "./isolateprotocol.ts"; @@ -58,7 +59,11 @@ export async function createIsolatedVMFrames( return (init, receive) => { const frame = new IsolatedVMFrame( ivmModule, - {memoryLimit, taskTimeout, log}, + { + memoryLimit: init.limits?.memoryLimit ?? memoryLimit, + taskTimeout: init.limits?.taskTimeout ?? taskTimeout, + log, + }, init, receive, ); @@ -68,6 +73,7 @@ export async function createIsolatedVMFrames( return { send: (message) => frame.send(message), dispose: () => frame.dispose(), + stats: () => frame.stats(), }; }; } @@ -94,6 +100,8 @@ class IsolatedVMFrame { asyncScripts: Set>; executing: Promise; scriptCount: number; + longestTask: number; + lastCPUTime: number; disposed: boolean; constructor( @@ -121,6 +129,8 @@ class IsolatedVMFrame { this.asyncScripts = new Set(); this.executing = Promise.resolve(); this.scriptCount = 0; + this.longestTask = 0; + this.lastCPUTime = 0; this.disposed = false; this.isolate = new ivmModule.Isolate({ memoryLimit: limits.memoryLimit, @@ -224,8 +234,30 @@ class IsolatedVMFrame { undefined, [kind, ...args], {arguments: {copy: true}, timeout: this.taskTimeout}, - ) - .then(() => {}, (error: unknown) => this.fail(error)); + ).then(() => this.measure(), (error: unknown) => this.fail(error)); + } + + // The CPU each call took, so the longest task shows a page that blocks. + measure(): void { + if (this.isolate.isDisposed) { + return; + } + const cpuTime = Number(this.isolate.cpuTime); + this.longestTask = Math.max(this.longestTask, cpuTime - this.lastCPUTime); + this.lastCPUTime = cpuTime; + } + + async stats(): Promise { + if (this.disposed || this.isolate.isDisposed) { + return null; + } + const heap = await this.isolate.getHeapStatistics(); + return { + cpuTime: Number(this.isolate.cpuTime), + longestTask: this.longestTask, + heapUsed: heap.used_heap_size, + external: heap.externally_allocated_size, + }; } send(message: HostMessage): void { diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts index f5a81354..076dcb02 100644 --- a/src/internal/isolateprotocol.ts +++ b/src/internal/isolateprotocol.ts @@ -30,6 +30,9 @@ export interface FrameInit { colorScheme: "light" | "dark"; reducedMotion: boolean; scripting: boolean; + // What a backend holds this frame to, where it holds frames to limits: + // megabytes of heap, and milliseconds any one task may run. + limits?: {memoryLimit?: number; taskTimeout?: number}; } export interface FrameRequest { @@ -93,6 +96,19 @@ export type HostMessage = export interface IsolatedFrame { send(message: HostMessage): void; dispose(): void; + // What the frame has used, where its backend can tell, or null once it + // is gone. + stats?(): Promise; +} + +export interface FrameStats { + // Nanoseconds of CPU the frame's isolate has run, and the most one + // task took. + cpuTime: number; + longestTask: number; + // Bytes of heap in use, and held outside it, as by array buffers. + heapUsed: number; + external: number; } /** From 43e7c97117b51d23eea170ed0526d35f6e53b8bf Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 13:55:32 -0500 Subject: [PATCH 12/25] Paint an isolated frame's images as kitty placeholders, and post them Where the page sends kitty images, the frame holds its images in a table of its own and paints the placeholder cells that name them, as a page does. After each paint it posts the images placed since the last one, with their pixels, and the ids it no longer shows, and the page places them under its own ids. Frames in the page's own heap still paint images in cells, since their framebuffers have no table. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/frames.ts | 5 +++ src/internal/isolate/frame.ts | 15 +++++++++ src/internal/isolateprotocol.ts | 15 +++++++++ src/internal/kitty.ts | 57 +++++++++++++++++++++++++++++++++ 4 files changed, 92 insertions(+) diff --git a/src/internal/frames.ts b/src/internal/frames.ts index 984c6436..f26912c9 100644 --- a/src/internal/frames.ts +++ b/src/internal/frames.ts @@ -228,6 +228,11 @@ export function createFrameEngine( revealTextControlCaret(page); clearGrid(grid); const context = new CellContext(grid, rows, cols, -framebuffer.scrollTop); + // A frame whose images are sent on by the page holds them in its + // framebuffer's table, and paints the placeholders that name them. + context.graphics = framebuffer.colorDepth === "rgb" + ? framebuffer.graphics + : null; context.layers = layers; paint(painter, context); // Joined here, since the layers do not leave with the grid. diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index d64d9538..d833598e 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -20,6 +20,7 @@ import {Exchange, type TerminalTransport} from "../exchange.ts"; import {exportGrid, Framebuffer} from "../framebuffer.ts"; import {createFrameEngine} from "../frames.ts"; import {dispatchInput, Input, resolvePendingHover} from "../input.ts"; +import {KittyImages, takeFrameImages} from "../kitty.ts"; import {Layout} from "../layout.ts"; import {_} from "../slots.ts"; import {createWindow} from "../window.ts"; @@ -176,6 +177,14 @@ function createFrame(init: FrameInit): Frame { ); const extra = _(document).extra; extra.framebuffer.measurer = exchange; + const graphics = init.images === "kitty" && init.colorDepth === "rgb" + ? new KittyImages(() => extra.framebuffer.cellPixels) + : null; + if (graphics !== null) { + graphics.images = true; + graphics.canvas = true; + extra.framebuffer.graphics = graphics; + } installEditing(exchange); setReducedMotion( document as unknown as globalThis.Document, @@ -263,6 +272,12 @@ function createFrame(init: FrameInit): Frame { } resolvePendingHover(input); const grid = engine.fit(cols, rows); + if (graphics !== null) { + const {added, dropped} = takeFrameImages(graphics, grid); + if (added.length > 0 || dropped.length > 0) { + host.post({type: "images", added, dropped}); + } + } host.post({type: "paint", cells: exportGrid(grid), caret: engine.caret}); if (document.title !== title) { title = document.title; diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts index 076dcb02..99cb3068 100644 --- a/src/internal/isolateprotocol.ts +++ b/src/internal/isolateprotocol.ts @@ -30,6 +30,9 @@ export interface FrameInit { colorScheme: "light" | "dark"; reducedMotion: boolean; scripting: boolean; + // "kitty" where the page sends images in the kitty graphics protocol, + // so the frame paints placeholders and posts the images' pixels. + images?: "kitty" | "cells"; // What a backend holds this frame to, where it holds frames to limits: // megabytes of heap, and milliseconds any one task may run. limits?: {memoryLimit?: number; taskTimeout?: number}; @@ -71,6 +74,9 @@ export type FrameMessage = // replaceState or a fragment. {type: "history"; url: string; replace: boolean} | {type: "load"} | + // The images the frame's placeholder cells name: those placed since its + // last paint, as RGBA pixels, and the ids it no longer shows. + {type: "images"; added: FrameImage[]; dropped: number[]} | {type: "message"; data: unknown; targetOrigin: string} | {type: "fetch"; id: number; request: FrameRequest} | {type: "abortFetch"; id: number} | @@ -92,6 +98,15 @@ export type HostMessage = {type: "response"; id: number; response: FrameResponse} | {type: "fetchError"; id: number; message: string}; +export interface FrameImage { + id: number; + width: number; + height: number; + cols: number; + rows: number; + pixels: Uint8ClampedArray; +} + /** A frame running in an isolate, as its page holds it. */ export interface IsolatedFrame { send(message: HostMessage): void; diff --git a/src/internal/kitty.ts b/src/internal/kitty.ts index 3678b89c..f935c215 100644 --- a/src/internal/kitty.ts +++ b/src/internal/kitty.ts @@ -389,6 +389,63 @@ export function takeKittyOutput( return images.passthrough ? wrapForTmux(out) : out; } +/** An image a frame placed, for the page that draws the frame to send. */ +export interface FrameImage { + id: number; + width: number; + height: number; + cols: number; + rows: number; + pixels: Uint8ClampedArray; +} + +/** + * A frame's images after a paint, where the page that draws the frame + * sends them on: those placed since the last paint, with their pixels, + * and the ids of those `screen` no longer shows, which are forgotten. A + * frame keeps no scrollback, so an image goes once it is off screen. + */ +export function takeFrameImages( + images: KittyImages, + screen: CellGrid, +): {added: FrameImage[]; dropped: number[]} { + const frame = images.frame++; + const added: FrameImage[] = []; + const dropped: number[] = []; + const {cluster, fg} = screen; + for (let index = 0; index < cluster.length; index++) { + if (isPlaceholderChar(cluster[index])) { + const image = images.byId.get(fg[index] & MAX_ID); + if (image !== undefined) { + image.seen = frame; + } + } + } + for (const [key, image] of images.byKey) { + if (image.seen < frame) { + images.byKey.delete(key); + images.byId.delete(image.id); + dropped.push(image.id); + } else if (image.pixels !== null) { + const {id, width, height, cols, rows, pixels} = image; + added.push({id, width, height, cols, rows, pixels}); + image.pixels = null; + image.encoded = null; + } + } + images.retired = images.retired.filter(({image, frame: retiredAt}) => { + if (retiredAt === frame) { + return true; + } + if (images.byId.get(image.id) === image) { + images.byId.delete(image.id); + dropped.push(image.id); + } + return false; + }); + return {added, dropped}; +} + /** * `escapes` as tmux passes them on to the terminal it runs in: each one * in a DCS of its own, with the ESCs inside doubled. From b1e4f82aff0d0cea33055555ef3d6471ba804469 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 14:06:23 -0500 Subject: [PATCH 13/25] Describe frames in isolates in the guide Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- docs/guides/06-images-and-canvas.md | 58 ++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index 06baf1ab..c8002f48 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -378,8 +378,8 @@ the page's borders. ## `'; +``` + +A frame lays its page out in the page's cell, so a page that shows web +pages wants a cell the size web pages expect, such as `cellSize: {width: +8, height: 16}` or `"auto"`. Under the default cell of one CSS pixel, a +page meant for a browser lays out 8 times as wide. + +TermDOM loads the frame's page the way it loads an image: under the +page's `csp`, where `frame-src` governs frames, and through its `fetch` +listeners. So do the frame's own stylesheets, images and scripts, +without the headers Fetch forbids a page to set, such as `Cookie`. The +frame lays out, runs its scripts and paints in its isolate, and the page +draws the cells it paints, checking each one, so a frame can't send the +terminal escape codes. + +Each frame's isolate has 256 MB of heap, and each call into it 30 +seconds. A frame that runs past either is stopped and shows nothing, and +the page goes on. A frame runs scripts where the page has `scripting: +"enabled"` and a `sandbox` attribute, if it has one, includes +`allow-scripts`. + +Click a frame, or focus it, and keys, the mouse and pastes go to the +document in it. To the page, the frame's window is one of another +origin, whatever its URL: `contentDocument` is null, and the two talk +through `postMessage()`. A frame that sets `parent.location.href` asks +the page to navigate, as above, and a link in the frame loads the new +page in a new isolate. + +`isolatedFrames` also takes a function, for an embedder that runs +frames elsewhere, such as in a process of its own. TermDOM calls it with +the frame's page and the terminal it is drawn for, and with a function +that receives what the frame sends. It returns an object with +`send(message)` and `dispose()`. The `FrameInit`, `FrameMessage` and +`HostMessage` types describe the messages. + ## `` Experimental. It may change in a minor release. From 47fc2c9b29a0f8d56758a861d3cbcfad949baf39 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 14:10:39 -0500 Subject: [PATCH 14/25] Draw the images an isolated frame posts, as the page draws a program's A frame in an isolate posts its images' pixels and paints placeholder cells that name them by its own ids. The page keeps each image it posts once its size checks out, and importGrid hands each placeholder to the frame, which turns them into the grid images a pty embed's program shows. So the page sends them in the kitty protocol where the terminal draws it, and in half blocks elsewhere, and a placeholder for an image the frame never posted draws nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- src/internal/dom.ts | 13 ++++ src/internal/framebuffer.ts | 39 +++++++++++- src/internal/isolatedframes.ts | 105 ++++++++++++++++++++++++++++++- tests/isolated-frames.test.ts | 80 ++++++++++++++++++++++- tests/isolated-vm-frames.test.ts | 47 +++++++++++++- 5 files changed, 278 insertions(+), 6 deletions(-) diff --git a/src/internal/dom.ts b/src/internal/dom.ts index 0154c5b8..47870f02 100644 --- a/src/internal/dom.ts +++ b/src/internal/dom.ts @@ -57,6 +57,7 @@ import { decodeImageOffThread, getNaturalHeight, getNaturalWidth, + type GridImage, IMAGE_ACCEPT, loadImageCodecs, MAX_IMAGE_PIXELS, @@ -19317,6 +19318,8 @@ let frameEngineFactory: FrameEngineFactory | null = null; export interface IsolatedFrameView extends BoxRenderer, ProgramInput { // A message for the frame's window, from a window of `origin`. postMessage(data: unknown, origin: string, targetOrigin: string): void; + // The images the cells the last fit returned show. + images(): GridImage[]; } // Builds a frame whose document at `url` is in another isolate, standing @@ -19904,6 +19907,7 @@ class HTMLIFrameElement extends HTMLElement { getFocusedElement(slots.document) === this ? slots.extra.frameRenderer?.caret ?? null : null, + images: () => getFrameImages(this), })); } @@ -20214,6 +20218,15 @@ function ensureFrameRenderer(frame: HTMLIFrameElement): void { } } +// The images an isolated frame's cells show. A frame in the engine's heap +// paints its images into its cells. +function getFrameImages(frame: HTMLIFrameElement): GridImage[] { + const window = _(frame).extra.contentWindow; + return implementsInterface(window, Window) + ? _(window).isolatedFrame?.images() ?? [] + : []; +} + // The frame's document changed: its cells are painted again with the // next frame of the document the iframe is in. function frameChanged(frame: HTMLIFrameElement): void { diff --git a/src/internal/framebuffer.ts b/src/internal/framebuffer.ts index f7f316b2..2e6457db 100644 --- a/src/internal/framebuffer.ts +++ b/src/internal/framebuffer.ts @@ -883,7 +883,8 @@ const STYLE_BITS = (1 << ATTR.WidthShift) - 1; // The text a cell from elsewhere shows, or a space for what a terminal // must never be sent: a control character, a lone surrogate, a code point -// past Unicode's, or a placeholder naming one of this heap's images. +// past Unicode's, or a placeholder, which would name one of this heap's +// images. function readImportedChar( char: number, border: number, @@ -911,13 +912,30 @@ function readImportedChar( return /\p{Cc}/u.test(text) ? " " : text; } +/** A placeholder cell of another heap's, at a cell of the grid. */ +export interface ImportedPlaceholder { + row: number; + col: number; + imageRow: number; + imageCol: number; + // The image's id in the other heap, from the cell's foreground. + id: number; + bg: number | null; +} + /** * Cells another heap painted, into `grid` from its top left corner, as * much of them as fits. What they name is checked as untrusted: each * cell's text and width are taken again here, so no cell can write a - * control sequence or claim columns its text does not take. + * control sequence or claim columns its text does not take. A placeholder + * for one of the other heap's images is left blank, with its background, + * and handed to `placed`, which draws the image over it. */ -export function importGrid(cells: GridCells, grid: CellGrid): void { +export function importGrid( + cells: GridCells, + grid: CellGrid, + placed?: (placeholder: ImportedPlaceholder) => void, +): void { clearGrid(grid); const graphemes = new Map(cells.graphemes); const rows = Math.min(cells.rows, grid.rows); @@ -942,6 +960,21 @@ export function importGrid(cells: GridCells, grid: CellGrid): void { col++; continue; } + if (placed !== undefined && isPlaceholderChar(char)) { + grid.cluster[to] = 0x20; + grid.attrs[to] = 1 << ATTR.WidthShift; + placed({ + row, + col, + imageRow: (char >>> 12) & 0xfff, + imageCol: char & 0xfff, + id: cells.fg[from] & 0xffffff, + bg: grid.bg[to] === 0 ? null : grid.bg[to], + }); + grid.fg[to] = 0; + col++; + continue; + } let text = readImportedChar(char, cells.border[from], graphemes); let width = getGraphemeColumns(text); if (width < 1 || col + width > cols) { diff --git a/src/internal/isolatedframes.ts b/src/internal/isolatedframes.ts index 001dda7d..354b8b57 100644 --- a/src/internal/isolatedframes.ts +++ b/src/internal/isolatedframes.ts @@ -24,9 +24,12 @@ import { type Caret, CellGrid, type GridCells, + type ImportedPlaceholder, importGrid, } from "./framebuffer.ts"; +import type {Bitmap, GridImage} from "./images.ts"; import type { + FrameImage, FrameInit, FrameIsolator, FrameMessage, @@ -34,12 +37,19 @@ import type { HostMessage, IsolatedFrame, } from "./isolateprotocol.ts"; +import {MAX_KITTY_PIXELS, MAX_PLACEHOLDER_CELLS} from "./kitty.ts"; import {_} from "./slots.ts"; import {getCellSize} from "./units.ts"; // The loads a frame may have in flight at once. const MAX_FETCHES = 64; +// The images a frame may hold at once. +const MAX_IMAGES = 256; + +// Tells each frame's images from another's among those the page shows. +let nextFrameToken = 1; + // Request headers a frame may not set, as Fetch forbids a page to. const FORBIDDEN_HEADER = /^(?:accept-charset|accept-encoding|access-control-request-headers|access-control-request-method|connection|content-length|cookie|cookie2|date|dnt|expect|host|keep-alive|origin|referer|set-cookie|te|trailer|transfer-encoding|upgrade|via|proxy-.*|sec-.*)$/i; @@ -96,6 +106,16 @@ class RemoteFrame implements IsolatedFrameView { // next fit. cells: GridCells | null; stale: boolean; + token: number; + // The images the frame posted, by its ids, and those the grid's + // placeholders show. + posted: Map< + number, + {bitmap: Bitmap; cols: number; rows: number; version: number} + >; + + shown: GridImage[]; + imageVersion: number; focused: boolean; running: IsolatedFrame | null; // What is sent before the frame has started, sent once it has. @@ -126,6 +146,10 @@ class RemoteFrame implements IsolatedFrameView { this.grid = new CellGrid(0, 0); this.cells = null; this.stale = false; + this.token = nextFrameToken++; + this.posted = new Map(); + this.shown = []; + this.imageVersion = 0; this.focused = false; this.running = null; this.waiting = []; @@ -180,6 +204,7 @@ class RemoteFrame implements IsolatedFrameView { scripting: media("(scripting: enabled)") && (sandbox === null || sandbox.has("allow-scripts")), + images: engine.images === "none" ? "cells" : "kitty", }, (message) => { if (unload === this.unload) { @@ -221,6 +246,9 @@ class RemoteFrame implements IsolatedFrameView { this.navigate(message.url); } break; + case "images": + this.receiveImages(message.added, message.dropped); + break; case "crash": this.stop(); this.cells = null; @@ -258,6 +286,45 @@ class RemoteFrame implements IsolatedFrameView { return URL.parse(this.url)?.origin ?? "null"; } + // The images the frame's next cells show, each checked against its + // size before the page holds it. + receiveImages(added: FrameImage[], dropped: number[]): void { + for (const id of dropped) { + this.posted.delete(id); + } + for (const image of added) { + const {id, width, height, cols, rows, pixels} = image; + if ( + ![id, width, height, cols, rows].every(Number.isInteger) || + id < 1 || + id > 0xffffff || + width < 1 || + height < 1 || + width * height > MAX_KITTY_PIXELS || + !(pixels instanceof Uint8ClampedArray) || + pixels.length !== width * height * 4 || + cols < 1 || + rows < 1 || + cols > MAX_PLACEHOLDER_CELLS || + rows > MAX_PLACEHOLDER_CELLS || + (!this.posted.has(id) && this.posted.size >= MAX_IMAGES) + ) { + continue; + } + this.posted.set(id, { + bitmap: {width, height, data: pixels}, + cols, + rows, + version: ++this.imageVersion, + }); + } + this.stale = true; + } + + images(): GridImage[] { + return this.shown; + } + // A caret the frame names is drawn only inside the cells it painted. readCaret(caret: Caret | null, cells: GridCells): Caret | null { if ( @@ -288,6 +355,7 @@ class RemoteFrame implements IsolatedFrameView { } this.stop(); this.unload = new AbortController(); + this.posted.clear(); this.cells = null; this.caret = null; this.stale = true; @@ -382,13 +450,48 @@ class RemoteFrame implements IsolatedFrameView { } if (this.stale) { this.stale = false; + const shown = new Map(); if (this.cells !== null) { - importGrid(this.cells, this.grid); + importGrid(this.cells, this.grid, (place) => + this.showImage(shown, place)); } + this.shown = [...shown.values()]; } return this.grid; } + // A placeholder cell shows its image only where the frame posted one + // with that id that has a cell there. + showImage(shown: Map, place: ImportedPlaceholder): void { + const image = this.posted.get(place.id); + if ( + image === undefined || + place.imageRow >= image.rows || + place.imageCol >= image.cols + ) { + return; + } + let entry = shown.get(place.id); + if (entry === undefined) { + entry = { + key: `frame:${this.token}:${place.id}`, + version: image.version, + bitmap: image.bitmap, + cols: image.cols, + rows: image.rows, + cells: [], + }; + shown.set(place.id, entry); + } + entry.cells.push({ + row: place.row, + col: place.col, + imageRow: place.imageRow, + imageCol: place.imageCol, + bg: place.bg, + }); + } + sendKey(key: WireKey): boolean { this.send({ type: "input", diff --git a/tests/isolated-frames.test.ts b/tests/isolated-frames.test.ts index 09b5acef..cf5404d2 100644 --- a/tests/isolated-frames.test.ts +++ b/tests/isolated-frames.test.ts @@ -17,8 +17,16 @@ import { type HostMessage, TermDOM, } from "../src/index.ts"; +import {toCellColor} from "../src/internal/cssvalues.ts"; import {CellGrid, exportGrid} from "../src/internal/framebuffer.ts"; -import {inputDispatched, MockProcess, nextFrame, until} from "./test-utils.ts"; +import { + captureRawOutput, + inputDispatched, + MockProcess, + nextFrame, + scriptReplies, + until, +} from "./test-utils.ts"; interface FakeFrame { init: FrameInit; @@ -365,3 +373,73 @@ test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goe test("isolatedFrames takes \"none\", \"auto\" or a function", () => { expect(() => new TermDOM({isolatedFrames: "yes" as any})).toThrow(TypeError); }); + +// A frame's red image, 2 by 1 cells, of 16 by 16 pixels, and the cells +// that show it under id 7 at the frame's top left. +function postRedImage(frame: FakeFrame, cols: number): void { + const pixels = new Uint8ClampedArray(16 * 16 * 4); + for (let index = 0; index < pixels.length; index += 4) { + pixels.set([255, 0, 0, 255], index); + } + frame.post({ + type: "images", + added: [{id: 7, width: 16, height: 16, cols: 2, rows: 1, pixels}], + dropped: [], + }); + const grid = new CellGrid(1, cols); + grid.setPlaceholder(0, 0, 0, {fg: toCellColor(7)}); + grid.setPlaceholder(1, 0, 1, {fg: toCellColor(7)}); + grid.setPlaceholder(2, 0, 0, {fg: toCellColor(8)}); + frame.post({type: "paint", cells: exportGrid(grid), caret: null}); +} + +test("a frame's images are drawn in half blocks where the terminal has no graphics", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "cells", + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + expect(frames[0].init.images).toBe("kitty"); + postRedImage(frames[0], 12); + await settle(dom); + const buffer = (terminal as any).terminal.buffer.active; + const line = buffer.getLine(1); + const backgrounds = [1, 2, 3].map((col) => { + const cell = line.getCell(col); + return cell.isBgRGB() ? cell.getBgColor() : null; + }); + expect(backgrounds).toEqual([0xff0000, 0xff0000, null]); + dom.dispose(); +}); + +test("a frame's images are sent in the kitty protocol where the terminal draws it", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 6}); + scriptReplies(terminal, [{ask: "\x1b[16t", reply: "\x1b[6;16;8t"}]); + const output = captureRawOutput(terminal); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "kitty", + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + await settle(dom); + await until(() => frames.length === 1); + postRedImage(frames[0], 12); + await settle(dom); + const uploads = output().match(/\x1b_G[^;\x1b]*/g) ?? []; + expect(uploads.length).toBe(1); + expect(uploads[0]).toContain("c=2,r=1"); + dom.dispose(); +}); diff --git a/tests/isolated-vm-frames.test.ts b/tests/isolated-vm-frames.test.ts index 4d9e177d..a52f9425 100644 --- a/tests/isolated-vm-frames.test.ts +++ b/tests/isolated-vm-frames.test.ts @@ -8,8 +8,16 @@ import {expect, test} from "@b9g/libuild/test"; import {TermDOM} from "../src/index.ts"; +import {encodePNG} from "../src/internal/imagecodecs.ts"; import {createIsolatedVMFrames} from "../src/internal/isolatedvm.ts"; -import {inputDispatched, MockProcess, nextFrame, until} from "./test-utils.ts"; +import { + captureRawOutput, + inputDispatched, + MockProcess, + nextFrame, + scriptReplies, + until, +} from "./test-utils.ts"; const onNode = (globalThis as {Bun?: unknown}).Bun === undefined && @@ -172,3 +180,40 @@ nodeTest( }, 60000, ); + +nodeTest( + "an image in a frame goes to the terminal in the kitty protocol", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + scriptReplies(terminal, [{ask: "\x1b[16t", reply: "\x1b[6;16;8t"}]); + const output = captureRawOutput(terminal); + const dom = new TermDOM({ + transport: terminal.transport, + colorDepth: "rgb", + images: "kitty", + cellSize: {width: 8, height: 16}, + isolatedFrames: "auto", + }); + const data = new Uint8ClampedArray(16 * 32 * 4).fill(255); + let binary = ""; + for (const byte of encodePNG({width: 16, height: 32, data})) { + binary += String.fromCharCode(byte); + } + servePages(dom, { + "https://frame.example/": + "" + + ``, + }); + dom.document.body.innerHTML = + ""; + await dom.attach(); + const deadline = Date.now() + 20000; + while (!/\x1b_G[^;]*c=2,r=2/.test(output()) && Date.now() < deadline) { + await nextFrame(dom); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(output()).toMatch(/\x1b_G[^;]*c=2,r=2/); + await dom.dispose(); + }, + 60000, +); From 977d97ea729d474f3c3c8804dfd46098ac6efaab Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 14:11:31 -0500 Subject: [PATCH 15/25] Keep the destination the engine gives an isolated frame's requests The engine names a request's destination as a property of its own, and the frame's fetch copied the request from its internal state instead, so an image went to the page with no destination. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/isolate/fetch.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/internal/isolate/fetch.ts b/src/internal/isolate/fetch.ts index 87445983..f9a1a466 100644 --- a/src/internal/isolate/fetch.ts +++ b/src/internal/isolate/fetch.ts @@ -412,7 +412,9 @@ export class Request extends Body { mode: init.mode ?? source?.mode ?? "cors", credentials: init.credentials ?? source?.credentials ?? "same-origin", cache: init.cache ?? source?.cache ?? "default", - destination: source?.destination ?? "", + // Read through the request, where the engine sets it as its own + // property. + destination: source === undefined ? "" : (input as Request).destination, referrer: init.referrer ?? source?.referrer ?? "about:client", referrerPolicy: init.referrerPolicy ?? source?.referrerPolicy ?? "", integrity: init.integrity ?? source?.integrity ?? "", @@ -485,10 +487,7 @@ export class Request extends Body { } clone(): Request { - const state = requestState(this); - const copy = new Request(this); - setDestination(copy, state.destination); - return copy; + return new Request(this); } } From 78b91201fafc6f3d05002c4682d054357d02f866 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 14:11:31 -0500 Subject: [PATCH 16/25] Post an isolated frame's images at any color depth The page draws a frame's images in kitty or in cells as its terminal can, so the frame paints placeholders whenever the page asks for kitty, and not only in 24-bit color. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv648YAe52aBTWbgPfn --- src/internal/frames.ts | 5 ++--- src/internal/isolate/frame.ts | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/internal/frames.ts b/src/internal/frames.ts index f26912c9..4008a48d 100644 --- a/src/internal/frames.ts +++ b/src/internal/frames.ts @@ -230,9 +230,8 @@ export function createFrameEngine( const context = new CellContext(grid, rows, cols, -framebuffer.scrollTop); // A frame whose images are sent on by the page holds them in its // framebuffer's table, and paints the placeholders that name them. - context.graphics = framebuffer.colorDepth === "rgb" - ? framebuffer.graphics - : null; + // The page draws them in kitty or in cells, as its terminal can. + context.graphics = framebuffer.graphics; context.layers = layers; paint(painter, context); // Joined here, since the layers do not leave with the grid. diff --git a/src/internal/isolate/frame.ts b/src/internal/isolate/frame.ts index d833598e..78f64bc2 100644 --- a/src/internal/isolate/frame.ts +++ b/src/internal/isolate/frame.ts @@ -177,7 +177,7 @@ function createFrame(init: FrameInit): Frame { ); const extra = _(document).extra; extra.framebuffer.measurer = exchange; - const graphics = init.images === "kitty" && init.colorDepth === "rgb" + const graphics = init.images === "kitty" ? new KittyImages(() => extra.framebuffer.cellPixels) : null; if (graphics !== null) { From a16d3957316b50539507ddd6e1c61d1e20575465 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 17:10:24 -0500 Subject: [PATCH 17/25] Fire an isolated frame's title, navigation and history on its iframe A page that shows web pages can keep an address bar and a tab title for its frame, and can keep the frame from going somewhere. A form the frame posts loads its next document with that POST. An embedder that wants other limits, or the frames' logs, takes createIsolatedVMFrames from @b9g/termdom/isolated-vm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- docs/guides/06-images-and-canvas.md | 34 ++++++- package.json | 1 + src/index.ts | 4 +- src/internal/isolatedframes.ts | 101 +++++++++++++++++++-- src/isolated-vm.ts | 19 ++++ tests/isolated-frames.test.ts | 136 ++++++++++++++++++++++++++++ tests/isolated-vm-frames.test.ts | 44 ++++++++- 7 files changed, 328 insertions(+), 11 deletions(-) create mode 100644 src/isolated-vm.ts diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index c8002f48..8702f6d6 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -489,8 +489,38 @@ Click a frame, or focus it, and keys, the mouse and pastes go to the document in it. To the page, the frame's window is one of another origin, whatever its URL: `contentDocument` is null, and the two talk through `postMessage()`. A frame that sets `parent.location.href` asks -the page to navigate, as above, and a link in the frame loads the new -page in a new isolate. +the page to navigate, as above, and a link or form in the frame loads +the new page in a new isolate. + +The iframe fires these events, so a page can show where its frame is: + +- `titlechange`: a `CustomEvent` with the frame's new title in `detail`, + without control characters. +- `navigate`: the frame is going to another page. A `CustomEvent` whose + `detail` has the `url` and the `method`, `"GET"` or `"POST"`. Call + `preventDefault()` and the frame stays where it is. +- `historychange`: the frame changed its URL in place, with + `pushState()`, `replaceState()` or a fragment. A `HistoryChangeEvent` + with the new `url` and whether it `replace`d the last one. Its `state` + is null. A URL of another origin is ignored. + +For other limits, or to log what frames print, make the isolator +yourself: + +```ts +import {createIsolatedVMFrames} from "@b9g/termdom/isolated-vm"; + +const dom = new TermDOM({ + isolatedFrames: await createIsolatedVMFrames({ + memoryLimit: 64, + taskTimeout: 5000, + log: (level, text) => console.error(level, text), + }), +}); +``` + +`memoryLimit` is in megabytes and `taskTimeout` in milliseconds. It +rejects where isolated-vm can't load. `isolatedFrames` also takes a function, for an embedder that runs frames elsewhere, such as in a process of its own. TermDOM calls it with diff --git a/package.json b/package.json index d680690c..6de98405 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ ], "exports": { ".": "./src/index.ts", + "./isolated-vm": "./src/isolated-vm.ts", "./package.json": "./package.json" }, "files": [ diff --git a/src/index.ts b/src/index.ts index d063ca7e..ba4b76fd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -376,7 +376,9 @@ export interface TermDOMOptions { * - `"auto"`: in a V8 isolate of its own, through the isolated-vm * package, on Node when it is installed. Each has 256 MB of heap, * and each call into it 30 seconds. Where isolated-vm cannot load, - * as on Bun and Deno, the frame shows nothing. + * as on Bun and Deno, the frame shows nothing. For other limits, + * pass what `createIsolatedVMFrames()` from + * `@b9g/termdom/isolated-vm` resolves to. * - A function: called with the frame's document and the terminal it * is drawn for, and with where to send what the frame sends. It * returns the frame, which takes the page's messages until it is diff --git a/src/internal/isolatedframes.ts b/src/internal/isolatedframes.ts index 354b8b57..48249f51 100644 --- a/src/internal/isolatedframes.ts +++ b/src/internal/isolatedframes.ts @@ -9,8 +9,10 @@ */ import { constructInternal, + CustomEvent, type Document, Event, + HistoryChangeEvent, type HTMLIFrameElement, type IsolatedFrameView, navigateFrameParent, @@ -47,6 +49,9 @@ const MAX_FETCHES = 64; // The images a frame may hold at once. const MAX_IMAGES = 256; +// The characters of a frame's title the page hears of. +const MAX_TITLE_LENGTH = 4096; + // Tells each frame's images from another's among those the page shows. let nextFrameToken = 1; @@ -75,6 +80,37 @@ function isWebURL(url: URL): boolean { return url.protocol === "http:" || url.protocol === "https:"; } +// A form's POST, as the frame encoded it. +interface Submission { + body: Uint8Array; + contentType: string; +} + +function readSubmission( + message: Extract, +): Submission | undefined { + if ( + typeof message.method !== "string" || + message.method.toUpperCase() !== "POST" + ) { + return undefined; + } + return { + body: message.body instanceof Uint8Array + ? Uint8Array.from(message.body) + : new Uint8Array(0), + contentType: typeof message.contentType === "string" + ? message.contentType.replace(/[\r\n]/g, "") + : "", + }; +} + +function readTitle(title: unknown): string { + return String(title) + .replace(/[\u0000-\u001f\u007f-\u009f]/g, "") + .slice(0, MAX_TITLE_LENGTH); +} + function describeError(error: unknown): string { return error instanceof Error ? error.message : "Failed to fetch"; } @@ -159,13 +195,20 @@ class RemoteFrame implements IsolatedFrameView { void this.start(url); } - async start(url: string): Promise { + async start(url: string, submission?: Submission): Promise { const unload = this.unload; const engine = _(this.parent).extra; let html: string; let documentURL = url; try { - const request = new Request(url, {signal: unload.signal}); + const request = new Request(url, { + method: submission === undefined ? "GET" : "POST", + headers: submission?.contentType + ? {"content-type": submission.contentType} + : undefined, + body: submission?.body, + signal: unload.signal, + }); setRequestDestination(request, "iframe"); const response = await engine.load(request, { initiator: this.frame as unknown as globalThis.Element, @@ -243,9 +286,19 @@ class RemoteFrame implements IsolatedFrameView { if (message.target === "parent") { navigateFrameParent(this.window, String(message.url)); } else { - this.navigate(message.url); + this.navigate(message.url, readSubmission(message)); } break; + case "history": + this.receiveHistory(message.url, message.replace); + break; + case "title": + this.frame.dispatchEvent( + constructInternal(() => + new CustomEvent("titlechange", {detail: readTitle(message.title)}), + ), + ); + break; case "images": this.receiveImages(message.added, message.dropped); break; @@ -276,6 +329,25 @@ class RemoteFrame implements IsolatedFrameView { } } + // The frame's document changed its URL in place, which keeps its + // origin. + receiveHistory(target: string, replace: unknown): void { + const url = URL.parse(String(target), this.url); + if (url === null || url.origin !== URL.parse(this.url)?.origin) { + return; + } + this.url = url.href; + this.frame.dispatchEvent( + constructInternal(() => + new HistoryChangeEvent("historychange", { + url: url.href, + state: null, + replace: replace === true, + }), + ), + ); + } + // The origin the frame's messages come from: its document's, or an // opaque one where a sandbox withholds allow-same-origin. getOrigin(): string { @@ -346,13 +418,28 @@ class RemoteFrame implements IsolatedFrameView { }; } - // The frame's document went to another URL: the isolate goes, and - // one for the new document starts. - navigate(target: string): void { + // The frame's document went to another URL, where the page's navigate + // event allows it: the isolate goes, and one for the new document + // starts. + navigate(target: string, submission?: Submission): void { const url = URL.parse(String(target), this.url); if (url === null || !isWebURL(url)) { return; } + const allowed = this.frame.dispatchEvent( + constructInternal(() => + new CustomEvent("navigate", { + cancelable: true, + detail: { + url: url.href, + method: submission === undefined ? "GET" : "POST", + }, + }), + ), + ); + if (!allowed || this.disposed) { + return; + } this.stop(); this.unload = new AbortController(); this.posted.clear(); @@ -360,7 +447,7 @@ class RemoteFrame implements IsolatedFrameView { this.caret = null; this.stale = true; this.changed(); - void this.start(url.href); + void this.start(url.href, submission); } async fetch(id: number, request: FrameRequest): Promise { diff --git a/src/isolated-vm.ts b/src/isolated-vm.ts new file mode 100644 index 00000000..74d92852 --- /dev/null +++ b/src/isolated-vm.ts @@ -0,0 +1,19 @@ +/** + * Frames in V8 isolates of their own, made with the isolated-vm + * package, with limits and a log of the embedder's choosing: + * + * new TermDOM({isolatedFrames: await createIsolatedVMFrames({ + * memoryLimit: 64, + * taskTimeout: 5000, + * })}); + * + * Each frame its isolator starts reports what it has used through + * `stats()`. isolated-vm is an optional peer dependency, and loads on + * Node only. + * @experimental The options and the frames' stats may change in a minor + * release. + */ +export { + createIsolatedVMFrames, + type IsolatedVMOptions, +} from "./internal/isolatedvm.ts"; diff --git a/tests/isolated-frames.test.ts b/tests/isolated-frames.test.ts index cf5404d2..b9807afd 100644 --- a/tests/isolated-frames.test.ts +++ b/tests/isolated-frames.test.ts @@ -443,3 +443,139 @@ test("a frame's images are sent in the kitty protocol where the terminal draws i expect(uploads[0]).toContain("c=2,r=1"); dom.dispose(); }); + +test("a frame's title comes to its iframe as titlechange, without control characters", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/": ""}); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + const titles: string[] = []; + frame.addEventListener("titlechange", (event: any) => titles.push(event.detail)); + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({type: "title", title: "News\x1b]0;evil\x07 today"}); + expect(titles).toEqual(["News]0;evil today"]); + dom.dispose(); +}); + +test("a frame goes to another document after a navigate event its page may cancel", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + const asked = answerPages(dom, { + "https://frame.example/": "", + "https://frame.example/next": "

next

", + }); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + const seen: Array<{url: string; method: string}> = []; + let cancel = true; + frame.addEventListener("navigate", (event: any) => { + seen.push(event.detail); + if (cancel) { + event.preventDefault(); + } + }); + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({type: "navigate", target: "self", url: "/blocked"}); + frames[0].post({type: "navigate", target: "self", url: "file:///etc/passwd"}); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(seen).toEqual([{url: "https://frame.example/blocked", method: "GET"}]); + expect(frames[0].disposed).toBe(false); + cancel = false; + frames[0].post({type: "navigate", target: "self", url: "next"}); + await until(() => frames.length === 2); + expect(frames[0].disposed).toBe(true); + expect(frames[1].init.html).toBe("

next

"); + expect(asked).toEqual(["https://frame.example/", "https://frame.example/next"]); + dom.dispose(); +}); + +test("a form a frame posts loads its next document with a POST", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + const posted: Array<{method: string; type: string | null; body: string}> = []; + dom.addEventListener("fetch", (event: any) => { + const request: Request = event.request; + if (request.method === "POST") { + event.respondWith( + request.text().then((body) => { + posted.push({ + method: request.method, + type: request.headers.get("content-type"), + body, + }); + return new Response("

thanks

"); + }), + ); + } else { + event.respondWith(new Response("")); + } + }); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + const methods: string[] = []; + frame.addEventListener("navigate", (event: any) => methods.push(event.detail.method)); + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({ + type: "navigate", + target: "self", + url: "https://frame.example/send", + method: "post", + body: new TextEncoder().encode("q=tea"), + contentType: "application/x-www-form-urlencoded\r\nx-evil: 1", + }); + await until(() => frames.length === 2); + expect(methods).toEqual(["POST"]); + expect(posted).toEqual([{ + method: "POST", + type: "application/x-www-form-urlencodedx-evil: 1", + body: "q=tea", + }]); + expect(frames[1].init.html).toBe("

thanks

"); + dom.dispose(); +}); + +test("a frame's history changes come to its iframe, within its own origin", async () => { + const {frames, isolate} = fakeIsolator(); + const terminal = new MockProcess({cols: 30, rows: 8}); + const dom = new TermDOM({ + transport: terminal.transport, + isolatedFrames: isolate, + }); + answerPages(dom, {"https://frame.example/a": ""}); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + const changes: Array<{url: string; replace: boolean}> = []; + frame.addEventListener("historychange", (event: any) => + changes.push({url: event.url, replace: event.replace}), + ); + await settle(dom); + await until(() => frames.length === 1); + frames[0].post({type: "history", url: "https://frame.example/b", replace: false}); + frames[0].post({type: "history", url: "https://bank.example/", replace: false}); + frames[0].post({type: "history", url: "#top", replace: true}); + expect(changes).toEqual([ + {url: "https://frame.example/b", replace: false}, + {url: "https://frame.example/b#top", replace: true}, + ]); + dom.dispose(); +}); diff --git a/tests/isolated-vm-frames.test.ts b/tests/isolated-vm-frames.test.ts index a52f9425..b7986dfb 100644 --- a/tests/isolated-vm-frames.test.ts +++ b/tests/isolated-vm-frames.test.ts @@ -9,7 +9,7 @@ import {expect, test} from "@b9g/libuild/test"; import {TermDOM} from "../src/index.ts"; import {encodePNG} from "../src/internal/imagecodecs.ts"; -import {createIsolatedVMFrames} from "../src/internal/isolatedvm.ts"; +import {createIsolatedVMFrames} from "../src/isolated-vm.ts"; import { captureRawOutput, inputDispatched, @@ -217,3 +217,45 @@ nodeTest( }, 60000, ); + +nodeTest( + "a frame's title, history and links come to its iframe as events", + async () => { + const terminal = new MockProcess({cols: 40, rows: 12}); + const dom = new TermDOM({ + transport: terminal.transport, + scripting: "enabled", + isolatedFrames: "auto", + }); + servePages(dom, { + "https://frame.example/": + "Firstgo", + "https://frame.example/next": "

next page

", + }); + dom.document.body.innerHTML = + ``; + const frame = dom.document.querySelector("iframe")!; + const events: string[] = []; + frame.addEventListener("titlechange", (event: any) => + events.push(`title ${event.detail}`), + ); + frame.addEventListener("historychange", (event: any) => + events.push(`history ${event.url}`), + ); + frame.addEventListener("navigate", (event: any) => + events.push(`navigate ${event.detail.url}`), + ); + await dom.attach(); + await drawn(dom, terminal, "next page"); + expect(events).toEqual([ + "history https://frame.example/moved", + "title First", + "navigate https://frame.example/next", + ]); + await dom.dispose(); + }, + 60000, +); From ee1e55658498dfac244770fdf2a062f20f1ed5ec Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 17:47:11 -0500 Subject: [PATCH 18/25] Reach isolated-vm, esbuild and Node's modules at run time A page that bundles TermDOM for a platform other than Node failed on the isolate backend's imports of node:crypto and node:fs/promises, and would go on to isolated-vm and esbuild. They come through the process now, as node-pty does, and randomness comes from the web's crypto. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- src/internal/isolate/bundle.ts | 30 +++++++++++++++++++++++++++--- src/internal/isolatedvm.ts | 12 +++++++----- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/internal/isolate/bundle.ts b/src/internal/isolate/bundle.ts index 88e59d38..6105881a 100644 --- a/src/internal/isolate/bundle.ts +++ b/src/internal/isolate/bundle.ts @@ -6,7 +6,10 @@ * A built package carries the script next to its modules, and a checkout * bundles it from source on first use. */ -import {readFile} from "node:fs/promises"; +import type * as FS from "node:fs/promises"; +import type * as NodeModule from "node:module"; + +import type * as ESBuild from "esbuild"; export const HOST_CALLBACKS = [ "post", @@ -19,10 +22,30 @@ export const HOST_CALLBACKS = [ export const FRAME_SCRIPT = "isolate-frame.js"; +interface NodeProcess { + getBuiltinModule?(id: string): unknown; +} + +// Node's own modules, and packages beside this one, are reached through +// the process at run time, so a bundle of TermDOM made for another +// platform imports none of them. +function getNodeBuiltin(id: string): T { + const {process} = globalThis as {process?: NodeProcess}; + if (typeof process?.getBuiltinModule !== "function") { + throw new Error(`This runtime has no ${id}`); + } + return process.getBuiltinModule(id) as T; +} + +export function requireNodePackage(id: string): T { + const {createRequire} = getNodeBuiltin("node:module"); + return createRequire(import.meta.url)(id) as T; +} + const ENTRY = new URL("./frame.ts", import.meta.url); export async function buildFrameScript(): Promise { - const {build} = await import("esbuild"); + const {build} = requireNodePackage("esbuild"); const result = await build({ entryPoints: [ENTRY.pathname], bundle: true, @@ -67,7 +90,8 @@ export function loadFrameScript(): Promise { new URL(`../${FRAME_SCRIPT}`, import.meta.url), ]) { try { - return await readFile(url, "utf8"); + const fs = getNodeBuiltin("node:fs/promises"); + return await fs.readFile(url, "utf8"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") { throw error; diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts index 6d2c06d4..52483a8b 100644 --- a/src/internal/isolatedvm.ts +++ b/src/internal/isolatedvm.ts @@ -7,11 +7,13 @@ * fetches, its scripts included, goes to the page, which loads it under * its own policy. */ -import {randomFillSync} from "node:crypto"; - import type ivm from "isolated-vm"; -import {HOST_CALLBACKS, loadFrameScript} from "./isolate/bundle.ts"; +import { + HOST_CALLBACKS, + loadFrameScript, + requireNodePackage, +} from "./isolate/bundle.ts"; import type {ScriptItem} from "./isolate/scripts.ts"; import {ModuleLoader} from "./isolatedvmmodules.ts"; import type { @@ -50,7 +52,7 @@ type Dispatch = ivm.Reference<(kind: string, ...args: unknown[]) => unknown>; export async function createIsolatedVMFrames( options: IsolatedVMOptions = {}, ): Promise { - const {default: ivmModule} = await import("isolated-vm"); + const ivmModule = requireNodePackage("isolated-vm"); const source = await loadFrameScript(); const memoryLimit = options.memoryLimit ?? DEFAULT_MEMORY_LIMIT; const taskTimeout = options.taskTimeout ?? DEFAULT_TASK_TIMEOUT; @@ -351,7 +353,7 @@ class IsolatedVMFrame { random(length: number): Uint8Array { const size = Math.max(0, Math.min(Number(length) | 0, MAX_RANDOM_BYTES)); - return randomFillSync(new Uint8Array(size)); + return crypto.getRandomValues(new Uint8Array(size)); } // The backend's own loads, a script's or a module's source, go to the From 53d457a2192d11eb59828eae32f493212efcb9b5 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 10 Nov 2026 22:58:56 -0500 Subject: [PATCH 19/25] Isolate cross-origin frames without an option or events of their own An iframe whose src is of another origin loads in an isolate where isolated-vm is installed and loads, and shows about:blank elsewhere. Its page reaches it as the web has it: load, postMessage, sandbox and frame-src. The isolatedFrames option, the exported message types, the @b9g/termdom/isolated-vm entry and the iframe's titlechange, navigate and historychange events go. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GVbRv5bxvWWH7aApVCbS3z --- docs/guides/06-images-and-canvas.md | 54 ++-------- package.json | 1 - src/index.ts | 53 +--------- src/internal/dom.ts | 9 +- src/internal/isolatedframes.ts | 78 +++++--------- src/isolated-vm.ts | 19 ---- tests/isolated-frames.test.ts | 159 +++++++++------------------- tests/isolated-vm-frames.test.ts | 46 +++----- 8 files changed, 104 insertions(+), 315 deletions(-) delete mode 100644 src/isolated-vm.ts diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index 8702f6d6..0d8e8ba1 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -378,7 +378,7 @@ the page's borders. ## `'; ``` @@ -492,43 +491,6 @@ through `postMessage()`. A frame that sets `parent.location.href` asks the page to navigate, as above, and a link or form in the frame loads the new page in a new isolate. -The iframe fires these events, so a page can show where its frame is: - -- `titlechange`: a `CustomEvent` with the frame's new title in `detail`, - without control characters. -- `navigate`: the frame is going to another page. A `CustomEvent` whose - `detail` has the `url` and the `method`, `"GET"` or `"POST"`. Call - `preventDefault()` and the frame stays where it is. -- `historychange`: the frame changed its URL in place, with - `pushState()`, `replaceState()` or a fragment. A `HistoryChangeEvent` - with the new `url` and whether it `replace`d the last one. Its `state` - is null. A URL of another origin is ignored. - -For other limits, or to log what frames print, make the isolator -yourself: - -```ts -import {createIsolatedVMFrames} from "@b9g/termdom/isolated-vm"; - -const dom = new TermDOM({ - isolatedFrames: await createIsolatedVMFrames({ - memoryLimit: 64, - taskTimeout: 5000, - log: (level, text) => console.error(level, text), - }), -}); -``` - -`memoryLimit` is in megabytes and `taskTimeout` in milliseconds. It -rejects where isolated-vm can't load. - -`isolatedFrames` also takes a function, for an embedder that runs -frames elsewhere, such as in a process of its own. TermDOM calls it with -the frame's page and the terminal it is drawn for, and with a function -that receives what the frame sends. It returns an object with -`send(message)` and `dispose()`. The `FrameInit`, `FrameMessage` and -`HostMessage` types describe the messages. - ## `` Experimental. It may change in a minor release. diff --git a/package.json b/package.json index 6de98405..d680690c 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,6 @@ ], "exports": { ".": "./src/index.ts", - "./isolated-vm": "./src/isolated-vm.ts", "./package.json": "./package.json" }, "files": [ diff --git a/src/index.ts b/src/index.ts index ba4b76fd..6b9642ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -109,8 +109,7 @@ import { setDecodeWorkerURL, } from "./internal/images.ts"; import {Input, resolvePendingHover} from "./internal/input.ts"; -import {startInIsolatedVM} from "./internal/isolatedframes.ts"; -import type {FrameIsolator} from "./internal/isolateprotocol.ts"; +import {findFrameIsolator} from "./internal/isolatedframes.ts"; import { compressKittyUploads, forgetKittyImages, @@ -164,15 +163,6 @@ import { import {createWindow} from "./internal/window.ts"; export type {CanvasCellGridContext} from "./internal/canvas.ts"; -export type { - FrameInit, - FrameIsolator, - FrameMessage, - FrameRequest, - FrameResponse, - HostMessage, - IsolatedFrame, -} from "./internal/isolateprotocol.ts"; export type {CellSize} from "./internal/units.ts"; export { HistoryChangeEvent, @@ -364,30 +354,6 @@ export interface TermDOMOptions { */ ptyEmbeds?: "none" | "auto"; - /** - * Where an ``; @@ -131,10 +138,8 @@ test("a frame's document loads through the page and starts in the isolator", asy test("the cells a frame paints are drawn in its box, without control characters", async () => { const {frames, isolate} = fakeIsolator(); const terminal = new MockProcess({cols: 30, rows: 6}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -155,10 +160,8 @@ test("the cells a frame paints are drawn in its box, without control characters" test("a frame's cells claim no columns their text does not take", async () => { const {frames, isolate} = fakeIsolator(); const terminal = new MockProcess({cols: 30, rows: 6}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -181,10 +184,8 @@ test("a frame's cells claim no columns their text does not take", async () => { test("a click focuses the frame, and its keys and mouse go there in its own cells", async () => { const {frames, isolate} = fakeIsolator(); const terminal = new MockProcess({cols: 30, rows: 8}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -225,8 +226,8 @@ test("the page and the frame reach each other only through messages", async () = const dom = new TermDOM({ transport: new MockProcess({cols: 30, rows: 8}).transport, url: "https://page.example/", - isolatedFrames: isolate, }); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -266,8 +267,8 @@ test("a frame's loads go through the page's fetch listeners, without forbidden h const {frames, isolate} = fakeIsolator(); const dom = new TermDOM({ transport: new MockProcess({cols: 30, rows: 8}).transport, - isolatedFrames: isolate, }); + useIsolator(dom, isolate); const headers: Array<[string, string]> = []; dom.addEventListener("fetch", (event: any) => { if (event.request.url === "https://frame.example/") { @@ -330,8 +331,8 @@ test("a frame-src policy keeps a frame's document from loading", async () => { const dom = new TermDOM({ transport: new MockProcess({cols: 30, rows: 8}).transport, csp: "frame-src https://allowed.example", - isolatedFrames: isolate, }); + useIsolator(dom, isolate); const asked = answerPages(dom, { "https://allowed.example/": "

allowed

", "https://blocked.example/": "

blocked

", @@ -356,8 +357,8 @@ test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goe const {frames, isolate} = fakeIsolator(); const dom = new TermDOM({ transport: new MockProcess({cols: 30, rows: 8}).transport, - isolatedFrames: isolate, }); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -370,10 +371,6 @@ test("a srcdoc frame stays in the page's heap, and a removed frame's isolate goe dom.dispose(); }); -test("isolatedFrames takes \"none\", \"auto\" or a function", () => { - expect(() => new TermDOM({isolatedFrames: "yes" as any})).toThrow(TypeError); -}); - // A frame's red image, 2 by 1 cells, of 16 by 16 pixels, and the cells // that show it under id 7 at the frame's top left. function postRedImage(frame: FakeFrame, cols: number): void { @@ -400,8 +397,8 @@ test("a frame's images are drawn in half blocks where the terminal has no graphi transport: terminal.transport, colorDepth: "rgb", images: "cells", - isolatedFrames: isolate, }); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -429,8 +426,8 @@ test("a frame's images are sent in the kitty protocol where the terminal draws i transport: terminal.transport, colorDepth: "rgb", images: "kitty", - isolatedFrames: isolate, }); + useIsolator(dom, isolate); answerPages(dom, {"https://frame.example/": ""}); dom.document.body.innerHTML = ``; @@ -444,71 +441,44 @@ test("a frame's images are sent in the kitty protocol where the terminal draws i dom.dispose(); }); -test("a frame's title comes to its iframe as titlechange, without control characters", async () => { +test("a frame goes to the document its own navigation names", async () => { const {frames, isolate} = fakeIsolator(); const terminal = new MockProcess({cols: 30, rows: 8}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); - answerPages(dom, {"https://frame.example/": ""}); - dom.document.body.innerHTML = - ``; - const frame = dom.document.querySelector("iframe")!; - const titles: string[] = []; - frame.addEventListener("titlechange", (event: any) => titles.push(event.detail)); - await settle(dom); - await until(() => frames.length === 1); - frames[0].post({type: "title", title: "News\x1b]0;evil\x07 today"}); - expect(titles).toEqual(["News]0;evil today"]); - dom.dispose(); -}); - -test("a frame goes to another document after a navigate event its page may cancel", async () => { - const {frames, isolate} = fakeIsolator(); - const terminal = new MockProcess({cols: 30, rows: 8}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); const asked = answerPages(dom, { "https://frame.example/": "", - "https://frame.example/next": "

next

", + "https://frame.example/b/next": "

next

", }); dom.document.body.innerHTML = ``; - const frame = dom.document.querySelector("iframe")!; - const seen: Array<{url: string; method: string}> = []; - let cancel = true; - frame.addEventListener("navigate", (event: any) => { - seen.push(event.detail); - if (cancel) { - event.preventDefault(); - } - }); await settle(dom); await until(() => frames.length === 1); - frames[0].post({type: "navigate", target: "self", url: "/blocked"}); frames[0].post({type: "navigate", target: "self", url: "file:///etc/passwd"}); + frames[0].post({ + type: "history", + url: "https://bank.example/", + replace: false, + }); + frames[0].post({type: "history", url: "/b/here", replace: false}); await new Promise((resolve) => setTimeout(resolve, 10)); - expect(seen).toEqual([{url: "https://frame.example/blocked", method: "GET"}]); expect(frames[0].disposed).toBe(false); - cancel = false; frames[0].post({type: "navigate", target: "self", url: "next"}); await until(() => frames.length === 2); expect(frames[0].disposed).toBe(true); expect(frames[1].init.html).toBe("

next

"); - expect(asked).toEqual(["https://frame.example/", "https://frame.example/next"]); + expect(asked).toEqual([ + "https://frame.example/", + "https://frame.example/b/next", + ]); dom.dispose(); }); test("a form a frame posts loads its next document with a POST", async () => { const {frames, isolate} = fakeIsolator(); const terminal = new MockProcess({cols: 30, rows: 8}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); + const dom = new TermDOM({transport: terminal.transport}); + useIsolator(dom, isolate); const posted: Array<{method: string; type: string | null; body: string}> = []; dom.addEventListener("fetch", (event: any) => { const request: Request = event.request; @@ -529,9 +499,6 @@ test("a form a frame posts loads its next document with a POST", async () => { }); dom.document.body.innerHTML = ``; - const frame = dom.document.querySelector("iframe")!; - const methods: string[] = []; - frame.addEventListener("navigate", (event: any) => methods.push(event.detail.method)); await settle(dom); await until(() => frames.length === 1); frames[0].post({ @@ -543,39 +510,13 @@ test("a form a frame posts loads its next document with a POST", async () => { contentType: "application/x-www-form-urlencoded\r\nx-evil: 1", }); await until(() => frames.length === 2); - expect(methods).toEqual(["POST"]); - expect(posted).toEqual([{ - method: "POST", - type: "application/x-www-form-urlencodedx-evil: 1", - body: "q=tea", - }]); - expect(frames[1].init.html).toBe("

thanks

"); - dom.dispose(); -}); - -test("a frame's history changes come to its iframe, within its own origin", async () => { - const {frames, isolate} = fakeIsolator(); - const terminal = new MockProcess({cols: 30, rows: 8}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: isolate, - }); - answerPages(dom, {"https://frame.example/a": ""}); - dom.document.body.innerHTML = - ``; - const frame = dom.document.querySelector("iframe")!; - const changes: Array<{url: string; replace: boolean}> = []; - frame.addEventListener("historychange", (event: any) => - changes.push({url: event.url, replace: event.replace}), - ); - await settle(dom); - await until(() => frames.length === 1); - frames[0].post({type: "history", url: "https://frame.example/b", replace: false}); - frames[0].post({type: "history", url: "https://bank.example/", replace: false}); - frames[0].post({type: "history", url: "#top", replace: true}); - expect(changes).toEqual([ - {url: "https://frame.example/b", replace: false}, - {url: "https://frame.example/b#top", replace: true}, + expect(posted).toEqual([ + { + method: "POST", + type: "application/x-www-form-urlencodedx-evil: 1", + body: "q=tea", + }, ]); + expect(frames[1].init.html).toBe("

thanks

"); dom.dispose(); }); diff --git a/tests/isolated-vm-frames.test.ts b/tests/isolated-vm-frames.test.ts index b7986dfb..fc83d8b1 100644 --- a/tests/isolated-vm-frames.test.ts +++ b/tests/isolated-vm-frames.test.ts @@ -9,7 +9,9 @@ import {expect, test} from "@b9g/libuild/test"; import {TermDOM} from "../src/index.ts"; import {encodePNG} from "../src/internal/imagecodecs.ts"; -import {createIsolatedVMFrames} from "../src/isolated-vm.ts"; +import {createIsolatedVMFrames} from "../src/internal/isolatedvm.ts"; +import type {FrameIsolator} from "../src/internal/isolateprotocol.ts"; +import {_} from "../src/internal/slots.ts"; import { captureRawOutput, inputDispatched, @@ -65,11 +67,7 @@ nodeTest( "a frame's document is laid out and painted in its own isolate", async () => { const terminal = new MockProcess({cols: 40, rows: 12}); - const dom = new TermDOM({ - transport: terminal.transport, - colorDepth: "rgb", - isolatedFrames: "auto", - }); + const dom = new TermDOM({transport: terminal.transport, colorDepth: "rgb"}); servePages(dom, { "https://frame.example/": "

from the isolate

", }); @@ -94,7 +92,6 @@ nodeTest( transport: terminal.transport, url: "https://page.example/", scripting: "enabled", - isolatedFrames: "auto", }); servePages(dom, { "https://frame.example/": @@ -132,10 +129,7 @@ nodeTest( "keys typed into a focused frame reach its field", async () => { const terminal = new MockProcess({cols: 40, rows: 12}); - const dom = new TermDOM({ - transport: terminal.transport, - isolatedFrames: "auto", - }); + const dom = new TermDOM({transport: terminal.transport}); servePages(dom, { "https://frame.example/": "", @@ -162,8 +156,9 @@ nodeTest( const dom = new TermDOM({ transport: terminal.transport, scripting: "enabled", - isolatedFrames: await createIsolatedVMFrames({taskTimeout: 200}), }); + (_(dom.document as never) as {extra: {isolateFrame: FrameIsolator}}) + .extra.isolateFrame = await createIsolatedVMFrames({taskTimeout: 200}); servePages(dom, { "https://spin.example/": "

spin

", "https://calm.example/": "

calm

", @@ -192,7 +187,6 @@ nodeTest( colorDepth: "rgb", images: "kitty", cellSize: {width: 8, height: 16}, - isolatedFrames: "auto", }); const data = new Uint8ClampedArray(16 * 32 * 4).fill(255); let binary = ""; @@ -219,42 +213,26 @@ nodeTest( ); nodeTest( - "a frame's title, history and links come to its iframe as events", + "a link clicked in a frame loads its next page there", async () => { const terminal = new MockProcess({cols: 40, rows: 12}); const dom = new TermDOM({ transport: terminal.transport, scripting: "enabled", - isolatedFrames: "auto", }); servePages(dom, { "https://frame.example/": - "Firstgo", "https://frame.example/next": "

next page

", }); dom.document.body.innerHTML = ``; - const frame = dom.document.querySelector("iframe")!; - const events: string[] = []; - frame.addEventListener("titlechange", (event: any) => - events.push(`title ${event.detail}`), - ); - frame.addEventListener("historychange", (event: any) => - events.push(`history ${event.url}`), - ); - frame.addEventListener("navigate", (event: any) => - events.push(`navigate ${event.detail.url}`), - ); await dom.attach(); - await drawn(dom, terminal, "next page"); - expect(events).toEqual([ - "history https://frame.example/moved", - "title First", - "navigate https://frame.example/next", - ]); + const screen = await drawn(dom, terminal, "next page"); + expect(screen[1]).toMatch(/^│next page/); await dom.dispose(); }, 60000, From b5df8c887f6ba12962d9a701c6e12ed40ccd7a51 Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Wed, 11 Nov 2026 14:27:04 -0500 Subject: [PATCH 20/25] Drop an isolated frame's own limits and its stats Nothing sets FrameInit.limits or calls stats() now that the page starts the isolated-vm backend itself, with no option an embedder reaches. Each frame is held to the backend's limits, as the guide says. Co-Authored-By: Claude --- src/internal/isolatedvm.ts | 38 +++------------------------------ src/internal/isolateprotocol.ts | 16 -------------- 2 files changed, 3 insertions(+), 51 deletions(-) diff --git a/src/internal/isolatedvm.ts b/src/internal/isolatedvm.ts index 52483a8b..14bcc3c7 100644 --- a/src/internal/isolatedvm.ts +++ b/src/internal/isolatedvm.ts @@ -22,7 +22,6 @@ import type { FrameMessage, FrameRequest, FrameResponse, - FrameStats, HostMessage, } from "./isolateprotocol.ts"; @@ -61,11 +60,7 @@ export async function createIsolatedVMFrames( return (init, receive) => { const frame = new IsolatedVMFrame( ivmModule, - { - memoryLimit: init.limits?.memoryLimit ?? memoryLimit, - taskTimeout: init.limits?.taskTimeout ?? taskTimeout, - log, - }, + {memoryLimit, taskTimeout, log}, init, receive, ); @@ -75,7 +70,6 @@ export async function createIsolatedVMFrames( return { send: (message) => frame.send(message), dispose: () => frame.dispose(), - stats: () => frame.stats(), }; }; } @@ -102,8 +96,6 @@ class IsolatedVMFrame { asyncScripts: Set>; executing: Promise; scriptCount: number; - longestTask: number; - lastCPUTime: number; disposed: boolean; constructor( @@ -131,8 +123,6 @@ class IsolatedVMFrame { this.asyncScripts = new Set(); this.executing = Promise.resolve(); this.scriptCount = 0; - this.longestTask = 0; - this.lastCPUTime = 0; this.disposed = false; this.isolate = new ivmModule.Isolate({ memoryLimit: limits.memoryLimit, @@ -236,30 +226,8 @@ class IsolatedVMFrame { undefined, [kind, ...args], {arguments: {copy: true}, timeout: this.taskTimeout}, - ).then(() => this.measure(), (error: unknown) => this.fail(error)); - } - - // The CPU each call took, so the longest task shows a page that blocks. - measure(): void { - if (this.isolate.isDisposed) { - return; - } - const cpuTime = Number(this.isolate.cpuTime); - this.longestTask = Math.max(this.longestTask, cpuTime - this.lastCPUTime); - this.lastCPUTime = cpuTime; - } - - async stats(): Promise { - if (this.disposed || this.isolate.isDisposed) { - return null; - } - const heap = await this.isolate.getHeapStatistics(); - return { - cpuTime: Number(this.isolate.cpuTime), - longestTask: this.longestTask, - heapUsed: heap.used_heap_size, - external: heap.externally_allocated_size, - }; + ) + .then(() => {}, (error: unknown) => this.fail(error)); } send(message: HostMessage): void { diff --git a/src/internal/isolateprotocol.ts b/src/internal/isolateprotocol.ts index 99cb3068..09297e6c 100644 --- a/src/internal/isolateprotocol.ts +++ b/src/internal/isolateprotocol.ts @@ -33,9 +33,6 @@ export interface FrameInit { // "kitty" where the page sends images in the kitty graphics protocol, // so the frame paints placeholders and posts the images' pixels. images?: "kitty" | "cells"; - // What a backend holds this frame to, where it holds frames to limits: - // megabytes of heap, and milliseconds any one task may run. - limits?: {memoryLimit?: number; taskTimeout?: number}; } export interface FrameRequest { @@ -111,19 +108,6 @@ export interface FrameImage { export interface IsolatedFrame { send(message: HostMessage): void; dispose(): void; - // What the frame has used, where its backend can tell, or null once it - // is gone. - stats?(): Promise; -} - -export interface FrameStats { - // Nanoseconds of CPU the frame's isolate has run, and the most one - // task took. - cpuTime: number; - longestTask: number; - // Bytes of heap in use, and held outside it, as by array buffers. - heapUsed: number; - external: number; } /** From 842216afab045a850a889bc3f88fbb8d10bb2aaa Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Thu, 12 Nov 2026 13:10:37 -0500 Subject: [PATCH 21/25] Skip the isolate tests under Node 24, where isolated-vm does not load isolated-vm 7 asks for Node 24. On CI's Node 20.19 leg its install script tried to build a binary and failed the install, so no test ran. That leg now installs without scripts, the tests that need an isolate skip under Node 24, and the guide gives the version. The lockfile takes the optional peer it was missing. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01GVbRv5n8btiCtaRBtLrLig --- .github/workflows/ci.yml | 4 +++- bun.lock | 2 ++ docs/guides/06-images-and-canvas.md | 6 +++--- tests/isolated-vm-frames.test.ts | 6 ++++-- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49b95185..ead94741 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,9 @@ jobs: with: node-version: ${{ matrix.node }} - - run: bun install --frozen-lockfile + # isolated-vm asks for Node 24. Under the floor its binary does not + # load, and its install script fails trying to build one. + - run: bun install --frozen-lockfile ${{ matrix.node == '20.19' && '--ignore-scripts' || '' }} # libuild's executable is a shell script, which npx can't start on # Windows. diff --git a/bun.lock b/bun.lock index cba46b58..e4ac7aca 100644 --- a/bun.lock +++ b/bun.lock @@ -57,9 +57,11 @@ "webidl2": "^24.5.0", }, "peerDependencies": { + "isolated-vm": "^7.0.2", "node-pty": "^1.1.0", }, "optionalPeers": [ + "isolated-vm", "node-pty", ], }, diff --git a/docs/guides/06-images-and-canvas.md b/docs/guides/06-images-and-canvas.md index 0d8e8ba1..34490785 100644 --- a/docs/guides/06-images-and-canvas.md +++ b/docs/guides/06-images-and-canvas.md @@ -450,9 +450,9 @@ otherwise throws `SecurityError`. An `