import type { Dispatcher } from 'undici'; import { createDispatcher, dispatchFetch } from './http-transport.js'; import { refuseWithoutRegisteredToken, withSessionToken } from './registry-format.js'; import { verbCommandId } from '@volter/sdk/commands'; import type { DocumentProbeResult, DocumentProbeStep } from '@volter/sdk/document-probe'; import type { ActiveDocumentCapture, AssetCompareCapture, AssetCompareOptions, AssetKind, AssetPreviewCapture, AssetPreviewOptions, AssetPreviewShotSetDefinition, AssetPreviewSource, CaptureDimensions, DocumentCameraPose, DocumentLookOutcome, StageFrameCostReading, DocumentTableProjection, EditorChromeCapture, EditorChromeCaptureOptions, EditorState, EditorView, EditorWorkspaceName, HelperVisibility, InspectedFieldWrite, InspectedHierarchy, InspectedInspection, LabeledShotSetCapture, PresentedEditorView, ProjectInfo, RecentProject, ShadingMode, StructureOp, StructureOpOptions, StructureOpResult, TransformMode, TransformSpace, Vec3Value, ViewPreset, ViewportCapture, } from '@volter/sdk'; // The editor's default origin, spelled out because this package deliberately // does not depend on `@volter/project`. `DEFAULT_EDITOR_PORT` in // `packages/project/src/manifest/editor-port.ts` is the owner of the number and // of the never-`localhost` rule; keep this in step with it. const DEFAULT_URL = 'http://127.0.0.1:20173'; /** * A refused editor command, carrying the relay's own STRUCTURED failure code * (`/__editor/command`'s `{ ok: false, error, code }`) alongside the prose, so * a caller that reacts to a specific refusal matches the code, never the * sentence. */ export class EditorCommandError extends Error { readonly code: string | undefined; constructor(message: string, code?: string | undefined) { super(message); this.name = 'EditorCommandError'; this.code = code; } } /** * The client's own ceiling on ONE relayed command. * * A backstop for a LOST server, not a per-command budget: the server already * owns per-type budgets (`server/server-utils.ts`'s `relayCommandTimeoutMs`) * and its timer must always be the one that fires, because its message names * the tab and the remedy while this one can only say "no answer". So this is * deliberately ONE number, comfortably above the longest server budget * (120s, `play`/`capture-story-variants`) rather than a mirror of that table — * a second copy of it would drift silently, and the drift would show up as * this timer winning a race it must always lose. * * Without it a `fetch` with no `AbortSignal` waits on the OS: a dev server * that stops answering mid-command holds the CLI open indefinitely, with no * output and nothing to read. */ const COMMAND_DEADLINE_MS = 150_000; /** undici's default `headersTimeout`; a command deadline beyond it needs its own dispatcher (see `command`). */ const UNDICI_DEFAULT_HEADERS_TIMEOUT_MS = 300_000; /** Deadline for console-ledger reads and acknowledgements. */ const CONSOLE_DRAIN_TIMEOUT_MS = 1_500; /** * Node's `fetch` collapses EVERY network-layer failure into one two-word * `TypeError: fetch failed`. The real reason — `ECONNREFUSED`, `ECONNRESET`, * `EPIPE`, a DNS miss — lives only on `error.cause` (sometimes two links down, * or inside an `AggregateError`), and nothing prints it unless something walks * the chain, so a bare "fetch failed" cannot tell a dead editor from a * momentary one. This walks the chain so the message can say which. */ function describeFetchFailure(error: unknown): { code: string; detail: string } { const messages: string[] = []; let current: unknown = error; for (let depth = 0; depth < 8; depth++) { if (!(current instanceof Error)) break; if (current.message) messages.push(current.message); const code = (current as { code?: unknown }).code; if (typeof code === 'string' && code !== '') { return { code, detail: messages.join(' <- ') }; } const aggregate = (current as { errors?: unknown }).errors; if (Array.isArray(aggregate) && aggregate.length > 0) { const inner = describeFetchFailure(aggregate[0]); return { code: inner.code, detail: [...messages, inner.detail].join(' <- ') }; } current = (current as { cause?: unknown }).cause; } return { code: 'UNKNOWN', detail: messages.join(' <- ') || String(error) }; } /** * Connection failures eligible for one retry when a command opts in. An editor * response is not a transport failure and does not use this retry path. */ const RETRYABLE_TRANSPORT_CODES = new Set([ 'ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'EHOSTUNREACH', 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT', ]); /** Gap before the one automatic retry — long enough for a dev-server restart's * listen socket to come back, short enough to stay invisible. */ const TRANSPORT_RETRY_DELAY_MS = 400; /** What one undo/redo step reports back — `moved` is false when there was * nothing left in that direction, which is an answer, not an error. */ export interface HistoryStep { readonly moved: boolean; readonly canUndo: boolean; readonly canRedo: boolean; readonly undoLabel: string | null; readonly redoLabel: string | null; } /** What `open()` acknowledges: the workspace document the scene-table entry * resolved to, and the title its tab now carries — the project's own word for * that composition, not a filename. */ export interface OpenedDocument { readonly documentId: string; readonly title: string; } export class EditorClient { private readonly baseUrl: string; private readonly fetchOverride: typeof fetch | undefined; private readonly transport: | ((body: Record) => Promise>) | null; constructor(opts?: { url?: string; /** An authenticated transport for the same HTTP routes (e.g. a hosted tab). */ fetch?: typeof fetch; /** * An IN-PAGE command channel, for a client that lives inside the editor * page itself and has no editor server to reach. Given, every command goes through it instead of * `POST /__editor/command`, and answers in the route's own body shape * (`{ ok: true, ...data }` / `{ ok: false, error, code? }`). */ transport?: (body: Record) => Promise>; }) { if (opts !== undefined && (typeof opts !== 'object' || opts === null || Array.isArray(opts))) { throw new TypeError( 'EditorClient options must be an object. Use new EditorClient({ url: "http://127.0.0.1:20173" }), not new EditorClient("...").', ); } const unknownOptions = Object.keys(opts ?? {}).filter( (key) => key !== 'url' && key !== 'transport' && key !== 'fetch', ); if (unknownOptions.length > 0) { throw new Error( `EditorClient: unknown option${unknownOptions.length === 1 ? '' : 's'} ${unknownOptions.map((key) => `"${key}"`).join(', ')}. Use { url: "http://127.0.0.1:" } to target an editor.`, ); } this.baseUrl = (opts?.url ?? DEFAULT_URL).replace(/\/$/, ''); this.fetchOverride = opts?.fetch; this.transport = opts?.transport ?? null; } /** * `retryTransport` opts a command into ONE automatic retry after a transport * failure (see {@link RETRYABLE_TRANSPORT_CODES}). It is deliberately * OPT-IN and off by default: a socket that died after the request was written * cannot prove the editor did not already run the command, so a blanket retry * would risk playing/stopping/writing twice. Read-only relays — the captures — * have no such hazard and turn it on. */ private async command>( body: Record, options?: { retryTransport?: boolean; deadlineMs?: number }, ): Promise { const type = String(body['type'] ?? 'command'); const deadlineMs = options?.deadlineMs ?? COMMAND_DEADLINE_MS; if (this.transport) { const answered = (await this.transport(body)) as { ok: boolean; error?: string; code?: string; } & T; if (!answered.ok) { throw new EditorCommandError( answered.error ?? `Editor command "${type}" failed`, answered.code, ); } return answered; } const url = `${this.baseUrl}/__editor/command`; const request = JSON.stringify(body); let res: Response | undefined; let retried = false; let commandDispatcher: Dispatcher | undefined; for (;;) { try { const init: RequestInit = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: request, signal: AbortSignal.timeout(deadlineMs), }; // The route answers when the command completes. Undici's default header // timeout is 300s, independent of the abort signal; longer command budgets // use an explicit dispatcher through undici's fetch to extend that timeout. commandDispatcher = deadlineMs > UNDICI_DEFAULT_HEADERS_TIMEOUT_MS ? createDispatcher(deadlineMs + 30_000) : undefined; res = this.fetchOverride ? await this.fetchOverride(url, init) : await dispatchFetch(url, withSessionToken(url, init), commandDispatcher); break; } catch (error) { await commandDispatcher?.destroy(); commandDispatcher = undefined; // Only the deadline is reshaped into a "no answer" verdict; everything // else is a TRANSPORT failure, and Node hides its reason behind a bare // `fetch failed` (see `describeFetchFailure`). if ((error as { name?: string } | null)?.name === 'TimeoutError') { throw new EditorCommandError( `The editor at ${this.baseUrl} never answered "${type}" ` + `within ${Math.round(deadlineMs / 1000)}s — past every server-side budget, so ` + 'the server itself is not answering. Check the terminal that started this editor session.', ); } const { code, detail } = describeFetchFailure(error); if (options?.retryTransport === true && !retried && RETRYABLE_TRANSPORT_CODES.has(code)) { retried = true; await new Promise((resolve) => setTimeout(resolve, TRANSPORT_RETRY_DELAY_MS)); continue; } throw new EditorCommandError( `POST ${url} ("${type}") never reached the editor: ${code}${detail ? ` (${detail})` : ''}.` + (retried ? ` Retried once after ${TRANSPORT_RETRY_DELAY_MS}ms; it failed the same way.` : '') + (options?.retryTransport === true ? '' : ' Not retried automatically: this command can change editor state, and a socket that' + ' died after the request was written cannot prove the editor did not already run it.') + ' A transport failure means the port stopped answering, not that the editor refused —' + ' the dev server restarts on any watched source edit, and it shuts itself down after an' + ' idle window. Check the terminal that started this editor session and confirm the port' + ' this client resolved.', code, ); } } if (!this.fetchOverride) { try { refuseWithoutRegisteredToken(url, res.status); } catch (error) { await commandDispatcher?.destroy(); throw error; } } let data: { ok: boolean; error?: string; code?: string } & T; try { data = (await this.readJson(res)) as typeof data; } finally { await commandDispatcher?.destroy(); } if (!data.ok) { throw new EditorCommandError( data.error ?? `Editor command failed: ${res.status}`, data.code, ); } return data; } /** Refuse shutdown if a document cannot be saved. Does not stop the server. */ async prepareClose(): Promise { await this.command({ type: 'session-prepare-close' }); } // --- Selection --- async select(id: string | null): Promise { await this.command({ type: 'select', id }); } async selectMultiple(ids: string[]): Promise { await this.command({ type: 'select-multiple', ids }); } async selectAll(): Promise { await this.command({ type: 'select-all' }); } // --- Viewport --- async focusEntity(id: string): Promise { await this.command({ type: 'focus-entity', id }); } async focusSelection(): Promise { await this.command({ type: 'focus-selection' }); } /** * Frame the EDIT viewport camera on one entity — the strict sibling of * {@link focusEntity}. Same framing; an id the scene does not know is a * refusal naming the id (`EditorCommandError`, code `ENTITY_NOT_FOUND`) * rather than `focusEntity`'s silent no-op, so a caller that frames an * entity before capturing it cannot photograph the wrong thing. */ async frameEntity(id: string): Promise { await this.command({ type: 'frame-entity', id }); } async viewPreset(preset: ViewPreset): Promise { await this.command({ type: 'view-preset', preset }); } /** * LOOK AROUND THE OPEN MODEL, visibly. Swings the active asset * document's camera — the one on the human's screen — by `azimuth`/ * `elevation` radians, animated over `duration` seconds, and resolves when * the move ends. A human drag during the move cancels it where it stands * (`cancelledBy: 'human'`); the promise still resolves. */ async orbitDocument(options: { azimuth?: number; elevation?: number; duration?: number; }): Promise { return this.command({ type: 'document-orbit', ...options }); } /** What a frame of a 3D document's stage costs, uncapped (`document-frame-cost`). */ async frameCostDocument(options?: { readonly frames?: number; readonly stage?: string; readonly quality?: 'full' | 'navigation' }): Promise { return this.command({ type: 'document-frame-cost', ...options }); } /** A slow full revolution around the open document's subject, at a constant rate. */ async turntableDocument(options?: { seconds?: number; revolutions?: number; }): Promise { return this.command({ type: 'document-turntable', ...options }); } /** * Frame the open document's subject (its selection if it has one). `fit` * scales the fitted distance: 1 is the toolbar Frame button's tight fit. */ async frameDocument(fit?: number): Promise { return this.command({ type: 'document-frame', ...(fit === undefined ? {} : { fit }), }); } async setCamera(position: Vec3Value, target: Vec3Value, fov?: number): Promise { await this.command({ type: 'set-camera', position, target, ...(fov === undefined ? {} : { fov }), }); } async captureViewport(size?: number): Promise { const data = await this.command({ type: 'capture-viewport', ...(size === undefined ? {} : { size }), }); return { base64: data.base64, mimeType: data.mimeType }; } /** * Capture an isolated, deterministic four-view preview through the editor's * native Asset Lab. The SDK delegates rendering to the editor; it never * loads, clones, or interprets 3D assets itself. */ async captureAssetPreview( source: AssetPreviewSource, options: AssetPreviewOptions = {}, ): Promise { const data = await this.command( { type: 'capture-asset-preview', ...source, ...options, }, // Photographing changes nothing, so a momentary transport failure is // retried rather than costing the caller its capture. { retryTransport: true }, ); return { width: data.width, height: data.height, orientation: data.orientation, views: data.views, contactSheet: data.contactSheet, }; } /** * A caller-defined labeled shot set (`live`'s `assetPreviewShots`): the * DEFINITION travels with the command (see `AssetPreviewShotSetDefinition`), * and the editor's generic * capture engine renders it — see the 3D integration's * `captureShotSetAssetPreview`. Throws (via `command`'s `{ok:false}` * unwrap) with a clear message naming the missing joint(s) when the asset * lacks a bone the definition requires. */ async captureShotSetPreview( source: AssetPreviewSource, definition: AssetPreviewShotSetDefinition, options: AssetPreviewOptions = {}, ): Promise { const data = await this.command( { type: 'capture-asset-preview', ...source, ...options, shotSet: definition, }, { retryTransport: true }, ); return { width: data.width, height: data.height, shots: data.shots, warnings: data.warnings, contactSheet: data.contactSheet, }; } /** * Score the asset against a reference GLB (the editor's `screenshot * --compare ` command): matched orthographic front + side silhouettes * (equal-height bounding-box framing, both yaw-normalized to face the * camera), per-view IoU numbers, and overlay evidence images. The * reference GLB's raw bytes travel base64 in the command; the editor * renders and scores — the SDK never interprets 3D assets itself. */ async captureAssetComparePreview( source: AssetPreviewSource, refGlbBase64: string, options: AssetCompareOptions = {}, ): Promise { const { refForward, ...dimensions } = options; const data = await this.command({ type: 'capture-asset-preview', ...source, ...dimensions, compare: { glbBase64: refGlbBase64, ...(refForward ? { forward: refForward } : {}) }, }); return { width: data.width, height: data.height, views: data.views }; } // --- Panels --- /** Focus a static workspace panel by the key the editor's panel registry * holds; an unknown key refuses naming the keys it does hold. */ async showPanel(panel: string): Promise { await this.command({ type: 'show-panel', panel }); } /** Show several instances of the running project split-screen — multiplayer * authoring. Pass a total `count` (default "Player N" labels) or an array of * `names` (its length is the count; index 0 is the primary). Requires a live * play session. */ async setInstanceCount(countOrNames: number | string[]): Promise { await this.command( Array.isArray(countOrNames) ? { type: 'set-instance-count', names: countOrNames } : { type: 'set-instance-count', count: countOrNames }, ); } async openAsset(path: string, kind: AssetKind): Promise { await this.command({ type: 'open-asset-tab', path, kind }); } /** SELECT a project asset — the other half of the browser's * selection-vs-open contract (single click selects and fills the * Inspector; double click opens a document). */ async selectAsset(path: string): Promise { await this.command({ type: 'select-asset', path }); } async closeAsset(key: string): Promise { await this.command({ type: 'close-asset-tab', key }); } async toggleCommandPalette(): Promise { await this.command({ type: 'toggle-command-palette' }); } async toggleConsole(): Promise { await this.command({ type: 'toggle-console' }); } /** Switch the editor's NAMED WORKSPACE — the task-named layout memory * (`design`/`animate`/`look`, or one a package contributes). Answers the workspace now active and whether its dock * had rebuilt within the command's wait (`applied`): when it had, a following capture photographs the arrangement * that was asked for. */ async setWorkspace(workspace: EditorWorkspaceName): Promise<{ readonly workspace: EditorWorkspaceName; readonly applied: boolean }> { return this.command<{ workspace: EditorWorkspaceName; applied: boolean }>({ type: 'set-workspace', workspace }); } /** Choose a STYLE (`volter.style`) — its material, icon set and type, and the colour theme it * was drawn with (`classic`/`glass`/`maya`/`substance`, or one a package the project or * product composes carries). */ async setStyle(style: string): Promise { await this.command({ type: 'set-style', style }); } /** A view's presentation, answered resolved. With a LAYER the person's choice is recorded * first. */ async viewportPresentation( documentId: string, layer?: import('@volter/sdk/viewport-presentation').PresentationLayer, ): Promise<{ presentation: import('@volter/sdk/viewport-presentation').ViewportPresentation; binding: { stageKind: string; documentLayer: import('@volter/sdk/viewport-presentation').PresentationLayer | null } | null; bound: { viewId: string; stageKind: string }[]; lastDraw: import('@volter/sdk/viewport-presentation').ViewDrawReport | null; presets: string[]; /** The environment images registered (`./environment-images`), for `lighting.preview.environment.image`. */ environmentImages: string[]; }> { return this.command({ type: 'viewport-presentation', documentId, ...(layer ? { layer } : {}), }); } async showBuild(): Promise { await this.command({ type: 'show-build' }); } /** Atomically present a durable editor view and return its shareable URL. */ async present(view: EditorView): Promise { const presented = await this.command({ type: 'present-view', view }); return { view: presented.view, url: presented.url, warnings: presented.warnings }; } async inspect(): Promise { const data = await this.command<{ subject: InspectedInspection }>({ type: 'inspect' }); return data.subject; } /** Run one verb exposed by the active Inspector subject, by its id. */ async runInspectionAction(actionId: string): Promise { const data = await this.command<{ subject: InspectedInspection }>({ type: 'run-inspection-action', actionId, }); return data.subject; } /** * Run ONE command by id — the door to everything the command palette lists. * * Under the Code-OSS frame this is the workbench's own `ICommandService`, so * any command id works: a view's `volter..`, an editor action's * `volter.action.`, or one of VS Code's own. A call made before the * command service lands waits for it. * * The result is whatever the command answered — a view verb's state, or * `null` for a command that returns nothing. */ async runCommand(commandId: string, args?: unknown): Promise { const data = await this.command<{ result: unknown }>({ type: 'run-command', commandId, ...(args === undefined ? {} : { args }), }); return data.result; } /** * One STRUCTURE op on the authored tree — the hierarchy context menu's own * verbs, on the same helpers, for a caller with no pointer to right-click * with. `id`/`ids` default to the current selection. */ async structureOp(op: StructureOp, options: StructureOpOptions = {}): Promise { return this.command({ type: 'structure-op', op, ...options }); } /** "Extract Component…" — the hierarchy row's action, as a command. Answers * the action's own sentence, which NAMES the files it created. */ async extractComponent(options: { id?: string; name?: string } = {}): Promise<{ hint: string }> { return this.command<{ hint: string }>({ type: 'extract-component', ...options }); } /** "Fork Component…" — extract's twin: one new file, one callsite retargeted. */ async forkComponent(options: { id?: string } = {}): Promise<{ hint: string }> { return this.command<{ hint: string }>({ type: 'fork-component', ...options }); } /** * The HIERARCHY PANEL's actual rendered row tree, as data. * * The panel projects component marks, document promotion, child caps, * collapse state, search and selection scope onto the adapter tree. * * Deliberately NOT `status().entities`, which walks the raw adapter tree and * therefore answers a different question: a panel defect is invisible in it. * * Each row reports the projected child count and whether the panel draws a disclosure control. * * Rejects, naming the panel, when no hierarchy panel is mounted: an empty * tree would be a fabricated answer about a surface nobody is being shown. */ async hierarchy(): Promise { const data = await this.command<{ hierarchy: InspectedHierarchy }>({ type: 'hierarchy' }); return data.hierarchy; } /** Run the Hierarchy panel's own Expand All action. */ async expandHierarchyAll(): Promise { await this.command>({ type: 'expand-hierarchy-all' }); } /** Run the Hierarchy panel's own Collapse All action — Expand All's other * half, and the only way back to the tree's rest state through the product * (see `HierarchyPanelSnapshot.collapseAll`). */ async collapseHierarchyAll(): Promise { await this.command>({ type: 'collapse-hierarchy-all' }); } /** * Write one editable path through the active Inspector's own IO. * * The answer carries `write` as well as the subject, because an ack alone * cannot be believed: a write with no persistence route open succeeds and * changes no byte, and `write.persisted` is how the caller tells the two * apart without diffing the tree (`InspectedWriteDestination` in `types.ts`). */ async setInspectionField(path: string, value: unknown): Promise { const data = await this.command({ type: 'set-inspection-field', path, value, }); return { subject: data.subject, write: data.write }; } /** * REMOVE one editable path's authored override — the other half of the write * door, and the only one that can express byte-ABSENCE. * * {@link setInspectionField} writes a VALUE, so reverting a property an * authoring gesture ADDED puts the default back EXPLICITLY and leaves the * source one attribute heavier than it started. This drops the property, so * whatever governs it in its absence takes over — the same `io.remove` the * Inspector's revert arrow calls, the same persistence pipe, the same awaited * `{ destination, persisted }` ack. * * Rejects with `code: 'REMOVAL_UNAVAILABLE'` when the field does not declare * itself removable or the lane implements no removal door. That refusal is a * MISSING SEAM, not a failed removal, and it is coded rather than phrased * precisely so a caller can grade the two differently. */ async removeInspectionField(path: string): Promise { const data = await this.command({ type: 'remove-inspection-field', path, }); return { subject: data.subject, write: data.write }; } /** * OPEN one piece of the adapter's SCENE TABLE by id — a scene, a prefab, or * a story state, because the table makes them siblings (they differ only in * instance site). The ids are exactly what `getState().adapter.scenes.entries` * reports, so the table is both the menu and the address space. It opens * the entry's document in Play as in Edit. * * Rejects with a coded reason rather than prose: `SCENE_NOT_FOUND` (and it * names the ids that DO exist), `SCENE_NOT_OPENABLE` carrying the reason an * entry owns no document (the adapter's own, when it declared one), * `SCENE_TABLE_UNAVAILABLE` before the adapter has loaded, and * `SCENE_DOCUMENT_NOT_MOUNTED` when the host has no document for a piece the * table says is openable — a host gap, not a table statement. */ async open(id: string): Promise { return this.command({ type: 'open', id }); } /** * Undo / redo one project transaction — the same queue the keyboard shortcut * drives. `moved` is false when there was nothing left in that direction. */ async undo(): Promise { return this.command({ type: 'undo' }); } async redo(): Promise { return this.command({ type: 'redo' }); } /** Read the editor's actual current durable projection. */ async currentView(): Promise { const data = await this.command<{ view: EditorView }>({ type: 'current-view' }); return data.view; } /** Photograph the editor PAGE itself — every panel as the person sees it, at * `scale` output pixels per CSS pixel (default `devicePixelRatio`), which is * what a 1 px border or a glyph edge is judged through. */ async captureEditorChrome(options?: EditorChromeCaptureOptions): Promise { return this.command({ type: 'capture-editor-chrome', ...(options?.scale === undefined ? {} : { scale: options.scale }), ...(options?.region === undefined ? {} : { region: options.region }), ...(options?.name === undefined ? {} : { name: options.name }), }); } /** Capture the active document's render, excluding editor chrome. A number * requests a square; `{width, height}` requests that shape, bounded by * {@link CaptureDimensions}. With a view, present and capture it in one request * so discovery cannot retarget the capture between client calls. */ async captureActiveDocument( size?: CaptureDimensions, view?: EditorView, ): Promise { return this.command({ type: 'capture-active-document', ...(view ? { view } : {}), ...(typeof size === 'number' ? { size } : {}), ...(typeof size === 'object' && size !== null ? { width: size.width, height: size.height } : {}), }); } /** * Read or drive the ACTIVE center document's own DOM — the scoped * editor-chrome door, and the read/gesture half of the same subject * {@link captureActiveDocument} photographs. NOT play-mode gated, and NOT * page automation: a target outside the active document's container is * refused by name. Design and scope contract: * `packages/sdk/src/editor-document-probe.ts`. */ async documentProbe(step: DocumentProbeStep): Promise { return this.command({ type: 'document-probe', step }); } /** * A verb a package contributes: the Code-OSS command `volter.` its page half registers, * waited on as long as its declaration says (`contributes.commands`' `volter.timeoutMs`, which * the relay reads from the same manifest), so a package's long verb (a modeling chunk, minutes * under Wasm) has its budget in one place. A verb no package declares is refused by name * before anything is sent. */ async contributedVerb>( type: string, fields: Record = {}, ): Promise { const id = verbCommandId(type); const res = await this.httpFetch(`${this.baseUrl}/__editor/commands/${encodeURIComponent(id)}`); const declared = (await this.readJson(res)) as { timeoutMs: number; error?: string }; if (!res.ok) throw new Error(declared.error ?? `No package declares the command "${id}" (${res.status}).`); // Past the relay's own budget, so the relay's answer (its result or its timeout) is what arrives. return this.command({ type, ...fields }, { deadlineMs: declared.timeoutMs + 30_000 }); } /** * Run a wire-carried step against the ACTIVE document's published context * (`packages/editor-core/src/document-context-registry.ts`) — the REPL door over * an open document. `src` is JavaScript source evaluated in the page; references to the caller's * closures are unavailable. */ async documentScript(src: string): Promise { const outcome = await this.command<{ result: T }>({ type: 'document-script', src }); return outcome.result; } // --- Display (set semantics) --- async setGrid(enabled: boolean): Promise { await this.command({ type: 'set-grid', enabled }); } async setHelpers(enabled: boolean): Promise { await this.command({ type: 'set-helpers', enabled }); } async setStats(enabled: boolean): Promise { await this.command({ type: 'set-stats', enabled }); } async setShadingMode(mode: ShadingMode): Promise { await this.command({ type: 'set-shading-mode', mode }); } async setHelperType(helperType: keyof HelperVisibility, enabled: boolean): Promise { await this.command({ type: 'set-helper-type', helperType, enabled }); } // --- Transform tools (set semantics) --- async setTransformMode(mode: TransformMode): Promise { await this.command({ type: 'set-transform-mode', mode }); } async setTransformSpace(space: TransformSpace): Promise { await this.command({ type: 'set-transform-space', space }); } async setSnap(enabled: boolean): Promise { await this.command({ type: 'set-snap', enabled }); } // --- Project management --- /** A new project from one of the running product's templates or examples (its `/__editor/templates`), or its default * where neither is named. */ async createProject( name: string, location: string, from: { readonly template?: string; readonly example?: string } = {}, ): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/create-project`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, location, ...from }), }); const data = (await this.readJson(res)) as { ok?: boolean; error?: string; path?: string; config?: ProjectInfo['config']; }; if (!res.ok) { throw new Error(data.error ?? `Create project failed: ${res.status}`); } return { path: data.path as string, config: data.config as ProjectInfo['config'] }; } async openProject(path: string): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/open-project`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path }), }); const body = (await this.readJson(res)) as { error?: string }; if (!res.ok) { throw new Error(body.error ?? `Open project failed: ${res.status}`); } } async getProject(): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/project`); const data = (await this.readJson(res)) as { project: ProjectInfo | null; error?: string }; if (!res.ok) throw new Error(data.error ?? `Failed to get project: ${res.status}`); return data.project; } /** One `/__editor/asset-library/` request, for `editor.assetLibrary` (`asset-library.ts`): a GET's fields as * its query, a POST's as its JSON body. A refusal throws the route's own error. */ async assetLibraryRequest(method: 'GET' | 'POST', route: string, fields: object): Promise { const url = new URL(`${this.baseUrl}/__editor/asset-library/${route}`); if (method === 'GET') { for (const [name, value] of Object.entries(fields)) if (value !== undefined) url.searchParams.set(name, String(value)); } // A DOWNLOAD WAITS AS LONG AS THE ROUTE DOES. It answers once the whole file is in the project, and it cancels the // import when its caller goes (`res.once('close')` in the route), so undici's default 300 s headers deadline would // cancel a large asset on a slow link. Like a command whose budget passes that default (`command`), it gets its // own dispatcher, here with no deadline at all (undici sets no timer for 0, `client-h1.js` `setTimeout`): the // route sets none. A search or a file listing is one upstream lookup whose route cancels nothing, and keeps the // default as its ceiling. const dispatcher = route === 'download' ? createDispatcher(0) : undefined; try { const res = await this.httpFetch( url.toString(), method === 'GET' ? undefined : { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(fields) }, dispatcher, ); const data = (await this.readJson(res)) as T & { error?: string }; if (!res.ok) throw new Error(data.error ?? `${method} /__editor/asset-library/${route} failed: ${res.status}`); return data; } finally { await dispatcher?.destroy(); } } async listRecentProjects(): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/recent-projects`); const data = (await this.readJson(res)) as { projects: RecentProject[]; error?: string }; if (!res.ok) throw new Error(data.error ?? `Failed to list projects: ${res.status}`); return data.projects; } // --- State --- /** * The document table the host resolved — every scene, prefab, page, model, * shot, take … the project's finders produced (`getState().adapter.scenes` * is the same projection). A command, so it answers wherever the control * channel reaches, not only where `/__editor/state` is served. */ async documentTable(): Promise { return this.command({ type: 'document-table' }); } async reloadPage(): Promise { const timeoutMs = 60_000; const epochs = async () => { const { tabs } = await this.getState().catch(() => ({ tabs: [] })); return new Map(tabs.map((tab) => [tab.tabId8, tab] as const)); }; const pause = () => new Promise((settle) => setTimeout(settle, 250)); const before = await epochs(); const deadline = Date.now() + timeoutMs; await this.command({ type: 'page-reload' }); let reloaded: string[] = []; while (reloaded.length === 0) { if (Date.now() > deadline) throw new Error('The reload was ordered and no tab of this session reported a new page load.'); await pause(); const now = await epochs(); reloaded = [...now].filter(([tabId, tab]) => tab.epochCount > (before.get(tabId)?.epochCount ?? 0)).map(([tabId]) => tabId); } for (;;) { if (Date.now() > deadline) throw new Error('A new page loaded, but its command listener did not become ready.'); const now = await epochs(); if (reloaded.some((tabId) => { const listener = now.get(tabId)?.commandListener; return typeof listener !== 'string' || listener === 'ready'; })) break; await pause(); } for (;;) { try { await this.command({ type: 'current-view' }); return; } catch (error) { if (Date.now() > deadline) throw error; await pause(); } } } async getState(): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/state`); const state = (await this.readJson(res)) as EditorState; if (!res.ok) throw new Error(`Failed to get editor state: ${res.status} ${res.statusText}`); return state; } /** * The complete unresolved console set the session is holding right now. * * The console endpoint returns named conditions; command envelopes carry * only their counts. The request has a bounded header deadline. */ async getUnresolvedConsole(opts?: { all?: boolean }): Promise { const res = await this.httpFetch( `${this.baseUrl}/__editor/console${opts?.all === true ? '?all=1' : ''}`, { signal: AbortSignal.timeout(CONSOLE_DRAIN_TIMEOUT_MS) }, ); // Status first: a 404's empty body would otherwise die inside readJson // with a parse error that hides the one fact the caller classifies on // (does this server SERVE the console route at all?). if (!res.ok) { throw new Error(`Failed to read unresolved console: ${res.status}`); } return await this.readJson(res); } /** Acknowledge one named console condition. */ async acknowledgeConsole(input: { readonly id: string; readonly reason: string; readonly by: string; }): Promise { const res = await this.httpFetch(`${this.baseUrl}/__editor/console/ack`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), signal: AbortSignal.timeout(CONSOLE_DRAIN_TIMEOUT_MS * 4), }); const body = await this.readJson(res); return body; } /** * `fetch` for this client's plain routes, with the ONE thing Node's `fetch` * will not do: name why it failed. * * `readJson` below already owns "the server answered the wrong thing"; this * owns "nothing answered at all", naming the real code Node buries on * `.cause`. No retry * here — these routes create projects, run tools and acknowledge console * conditions, so repeating one is the caller's decision. The relayed * `command` path above has its own opt-in retry for the read-only captures. */ private async httpFetch( url: string, init?: RequestInit, dispatcher?: Dispatcher, ): Promise { let res: Response; try { res = this.fetchOverride ? await this.fetchOverride(url, init) : await dispatchFetch(url, withSessionToken(url, init), dispatcher); } catch (error) { if ((error as { name?: string } | null)?.name === 'TimeoutError') throw error; const { code, detail } = describeFetchFailure(error); throw new EditorCommandError( `${init?.method ?? 'GET'} ${url} never reached the editor: ${code}` + `${detail ? ` (${detail})` : ''}. Nothing answered on that port — check the terminal ` + 'that started this editor session and confirm the port this client resolved.', code, ); } if (!this.fetchOverride) refuseWithoutRegisteredToken(url, res.status); return res; } /** Require a JSON response from the editor server. */ private async readJson(res: Response): Promise { // The client's JSON response routes funnel through here, so this is // where "did the editor server answer?" is asked — the same question, and // the same JSON-content-type rule, that // `packages/sdk/src/editor-server-response.ts` owns on the browser side. // It is asked again rather than imported because THIS package is published // and depends on neither `@volter/project` nor the editor bundle (see // `DEFAULT_URL` above for that policy). // // Not theoretical here: `baseUrl` is whatever `--url`/`VOLTER_EDITOR_URL` // says, so the CLI can be pointed at a static host, which answers // `200 text/html` for a route nothing serves, and `res.json()` would die as // `Unexpected token '<'`, naming neither the URL nor the cause. const contentType = res.headers.get('content-type') ?? ''; if (!contentType.includes('application/json')) { throw new Error( `The editor at ${this.baseUrl} answered with its page fallback ` + `(${contentType || 'no content-type'}) rather than JSON, so no editor server handled ` + 'the request. Check that this URL is a running editor session.', ); } return await res.json(); } /** * Whether an editor browser tab is connected to the server *right now*. * Unlike {@link getState}, this reflects live SSE connections, not cached * state — use it to check whether commands will actually reach an editor. */ async isConnected(): Promise { const state = await this.getState(); return state.connected === true; } async waitForState( predicate: (s: EditorState) => boolean, timeoutMs = 10_000, ): Promise { const start = Date.now(); while (Date.now() - start < timeoutMs) { const state = await this.getState(); if (predicate(state)) return state; await new Promise((r) => setTimeout(r, 100)); } throw new Error(`waitForState timed out after ${timeoutMs}ms`); } }