# Client API URL: /docs/api/client Client API [#client-api] Use the client API when you need to create a kernel runtime, configure filesystem access, or manage worker connections. The factory and constructors are the primary entry points for integrating `@taucad/runtime` into an application. createRuntimeClient [#createruntimeclient] `/`string` shape so consumers without typed plugins still\ntype-check.", "entries": [ { "name": "geometryPool", "description": "Shared memory pool for zero-IPC geometry data exchange. Populated during connect().", "tags": [], "type": "SharedPool | undefined", "simplifiedType": "object | undefined", "required": true, "deprecated": false }, { "name": "capabilities", "description": "Capabilities manifest from the worker, available after initialization.", "tags": [], "type": "CapabilitiesManifest | undefined", "simplifiedType": "CapabilitiesManifest | undefined", "required": true, "deprecated": false }, { "name": "activeKernelId", "description": "Active kernel ID from the worker, available after the first render selects a kernel.", "tags": [], "type": "CollectKernelIds | undefined", "simplifiedType": "CollectKernelIds | undefined", "required": true, "deprecated": false }, { "name": "routesFor", "description": "Returns every {@link ExportRoute} from the current capabilities manifest\nwhose `targetFormat` matches `format`, preserving manifest order.\n\nReturns an empty array when no manifest has been received yet or when no\nroute matches the requested format. Consumers building format pickers\nshould subscribe to `'capabilities'` to refresh derived UI state.", "tags": [], "type": "(format: KnownTargetFormats) => ReadonlyArray>", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "bestRouteFor", "description": "Selects the best {@link ExportRoute} for `format` using the framework\ntiebreak rules:\n\n1. When `kernelId` is supplied, prefer routes for that kernel; fall back\n to the manifest-order routes when no candidate matches.\n2. Prefer `brep` fidelity over `mesh` fidelity.\n3. Prefer direct routes (`transcoderId === undefined`) over transcoded\n routes.\n4. Otherwise return the first manifest-order match.\n\nReturns `undefined` when no route matches the requested format or when\nthe manifest has not yet been received.", "tags": [], "type": "(format: KnownTargetFormats, kernelId?: CollectKernelIds) => ExportRoute | undefined", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "connect", "description": "Connect to the runtime worker and initialize with a filesystem.", "tags": [ { "name": "param", "text": "options - Connection options: `{ fileSystem }` for main-thread relay, `{ port }` for direct bridge" } ], "type": "(options: ConnectOptions) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "render", "description": "Render geometry from inline code.\n\n`code` is a filename-to-content map. When only a single key exists,\n`file` is optional (inferred from the only key). When multiple keys\nexist, `file` is required to specify the entry point.\n\nAuto-creates an in-memory filesystem, writes code, connects, and renders.\nCannot be used with a port-based connection.\nRender geometry from the connected filesystem.\n\n`file` can be a string shorthand (e.g., `'/src/main.ts'`) or a `GeometryFile`.\nCache invalidation is handled automatically by the worker's filesystem watch subscription.", "tags": [], "type": "{ >(input: CodeInput & { options?: CollectRenderOptions; }): Promise; (input: FileInput & { options?: CollectRenderOptions; }): Promise; }", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "export", "description": "Export geometry from inline code (self-rendering).\n\nInternally renders the code first, then exports.\nExport geometry from the connected filesystem (self-rendering).\n\nInternally renders the file first, then exports.\nExport geometry from the last render in the specified format.\n\nWhen `Kernels`/`Transcoders` carry type information (from typed plugins),\nthe options are type-checked against the declared per-format schemas\nvia {@link MergeExportMap }.", "tags": [ { "name": "param", "text": "format - Export format identifier (e.g., 'stl', 'step', '3mf')" }, { "name": "param", "text": "options - Per-call format-specific options" }, { "name": "returns", "text": "Export result with a single ExportFile" } ], "type": "{ >(format: KnownTargetFormats, input: CodeInput): Promise; (format: KnownTargetFormats, input: FileInput): Promise; >(format: F, options?: ExportOptionsFor): Promise; }", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "setFile", "description": "Set the active file for autonomous rendering (filesystem mode).\nThe worker will immediately render and then watch for file changes.", "tags": [ { "name": "param", "text": "file - File path string or GeometryFile" }, { "name": "param", "text": "parameters - Parameters for the model" }, { "name": "param", "text": "options - Optional kernel-specific render options" } ], "type": "(file: string | GeometryFile, parameters?: Record, options?: CollectRenderOptions) => void", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "setParameters", "description": "Update parameters for autonomous rendering (filesystem mode).\nThe worker debounces and re-renders with the new parameters.", "tags": [ { "name": "param", "text": "parameters - Updated parameters for the model" } ], "type": "(parameters: Record) => void", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "setRenderTimeout", "description": "Set the wall-clock render timeout enforced by the main-thread RuntimeWorkerClient.\nWhen the timer fires, the abort generation is incremented via SharedArrayBuffer\nand the abort reason is set to `timeout`, causing the worker's cooperative\nabort proxy to throw.", "tags": [ { "name": "param", "text": "seconds - Timeout in seconds. 0 disables the timeout." } ], "type": "(seconds: number) => void", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "notifyFileChanged", "description": "Proactive cache invalidation without triggering a render.\nUsed by inline code mode. In filesystem mode, the worker's watch\nsubscription handles invalidation automatically.", "tags": [ { "name": "param", "text": "paths - Changed file paths" } ], "type": "(paths: string[]) => void", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "on", "description": "Subscribe to client events. Returns an unsubscribe function.\nSubscribable at any time during the client lifecycle.", "tags": [ { "name": "param", "text": "event - Event name" }, { "name": "param", "text": "handler - Event handler" }, { "name": "returns", "text": "Unsubscribe function" } ], "type": "{ (event: \"geometry\", handler: (result: HashedGeometryResult) => void): () => void; (event: \"state\", handler: (state: WorkerState, detail?: string) => void): () => void; (event: \"log\", handler: (entry: LogEntry) => void): () => void; (event: \"progress\", handler: (phase: RenderPhase, detail?: Record) => void): () => void; (event: \"telemetry\", handler: (entries: PerformanceEntryData[]) => void): () => void; (event: \"parametersResolved\", handler: (result: GetParametersResult) => void): () => void; (event: \"error\", handler: (issues: KernelIssue[]) => void): () => void; (event: \"capabilities\", handler: (manifest: CapabilitiesManifest) => void): () => void; (event: \"activeKernel\", handler: (kernelId: CollectKernelIds | undefined) => void): () => void; }", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "terminate", "description": "Terminate the worker and clean up all resources.", "tags": [], "type": "() => void", "simplifiedType": "function", "required": true, "deprecated": false } ] }} /> createRuntimeClientOptions [#createruntimeclientoptions] A helper that provides full intellisense when declaring options -- without importing the `RuntimeClientOptions` type -- and smart-merges a base configuration with partial overrides. Identity overload [#identity-overload] Provides type inference for the options object: ```typescript import { createRuntimeClientOptions } from '@taucad/runtime'; import { replicad } from '@taucad/runtime/kernels'; import { esbuild } from '@taucad/runtime/bundler'; const options = createRuntimeClientOptions({ kernels: [replicad()], bundlers: [esbuild()], }); ``` Merge overload [#merge-overload] Smart-merges a base with overrides using three strategies based on field type: | Field type | Examples | Strategy | | ------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Plugin arrays | `kernels`, `middleware`, `bundlers` | **ID-based merge** -- plugins with a matching `id` are replaced in-place (preserving priority order); new IDs are appended | | Opaque fields | `transport`, `fileSystem` | **Full replacement** -- the override replaces the base value entirely | ```typescript import { createRuntimeClientOptions } from '@taucad/runtime'; import { openscad, replicad, jscad } from '@taucad/runtime/kernels'; import { parameterCache, geometryCache } from '@taucad/runtime/middleware'; import { esbuild } from '@taucad/runtime/bundler'; const defaults = createRuntimeClientOptions({ kernels: [openscad(), replicad(), jscad()], middleware: [parameterCache(), geometryCache()], bundlers: [esbuild()], }); // Replace replicad with a debug-enabled version (matched by id) const debug = createRuntimeClientOptions(defaults, { kernels: [replicad({ withSourceMapping: true })], }); ``` Methods [#methods] | Method | Signature | Description | | ------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------- | | `connect` | `(options: ConnectOptions) => Promise` | Initialize the worker and establish the transport connection. | | `render` | `(input: CodeInput \| FileInput) => Promise` | Render geometry from code or a file (request/response). | | `export` | `(format, input?) => Promise` | Export geometry to STEP, STL, GLB, etc. | | `setFile` | `(file, parameters?, options?) => void` | Set the active file for autonomous rendering. | | `setParameters` | `(parameters) => void` | Update parameters for autonomous re-render (50ms debounce). | | `notifyFileChanged` | `(paths: string[]) => void` | Notify the worker that files changed (for inline code mode). | | `on` | `(event, handler) => () => void` | Subscribe to worker events. Returns an unsubscribe function. | | `terminate` | `() => void` | Shut down the worker and release resources. | Render Input Types [#render-input-types] `), `file` is required\nto specify the entry point.", "entries": [ { "name": "code", "description": "Inline source code as a filename-to-content map.", "tags": [], "type": "T", "simplifiedType": "T", "required": true, "deprecated": false }, { "name": "parameters", "description": "Parameters for the model's main function.", "tags": [ { "name": "default", "text": "\\{\\}" } ], "type": "Record | undefined", "simplifiedType": "Record", "required": false, "deprecated": false }, { "name": "options", "description": "Kernel-specific render options.", "tags": [], "type": "Record | undefined", "simplifiedType": "Record", "required": false, "deprecated": false }, { "name": "changedPaths", "description": "Not applicable in inline mode (client auto-manages).", "tags": [ { "name": "internal", "text": "" } ], "type": "undefined", "simplifiedType": "", "required": false, "deprecated": false }, { "name": "file", "description": "Entry point filename. Required when key count is unknown at compile time.\nEntry point filename. Required for multi-file code.\nEntry point filename. Optional for single-file code (inferred from the only key).", "tags": [], "type": "keyof T | string | undefined", "simplifiedType": "string | keyof T", "required": false, "deprecated": false } ] }} /> | undefined", "simplifiedType": "Record", "required": false, "deprecated": false }, { "name": "options", "description": "Kernel-specific render options.", "tags": [], "type": "Record | undefined", "simplifiedType": "Record", "required": false, "deprecated": false } ] }} /> Presets [#presets] `presets.all()` returns a `PresetOptions` object containing all built-in kernels, middleware, and bundlers. The type is `{ kernels: KernelPlugin[]; middleware: MiddlewarePlugin[]; bundlers: BundlerPlugin[] }`. See [`KernelPlugin`](./kernels), [`MiddlewarePlugin`](./middleware), and [`BundlerPlugin`](./bundler) for details: ```typescript import { createRuntimeClient, presets } from '@taucad/runtime'; const client = createRuntimeClient(presets.all()); ``` Merge with additional options: ```typescript import { createRuntimeClient, presets } from '@taucad/runtime'; import { fromNodeFS } from '@taucad/runtime/filesystem/node'; const client = createRuntimeClient({ ...presets.all(), fileSystem: fromNodeFS('/path/to/project'), }); ``` Filesystem [#filesystem] ; (path: string): Promise>; }", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "writeFile", "description": "Write file (text or binary).", "tags": [], "type": "(path: string, data: Uint8Array | string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "mkdir", "description": "Create directory, optionally recursive.", "tags": [], "type": "(path: string, options?: { recursive?: boolean; }) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "readdir", "description": "List directory entries (file/dir names).", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "unlink", "description": "Delete file.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "rmdir", "description": "Remove an empty directory.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "rename", "description": "Rename / move a file or directory.", "tags": [], "type": "(oldPath: string, newPath: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "stat", "description": "Get file or directory metadata.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "lstat", "description": "Get file or directory metadata without following symlinks.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "exists", "description": "Check if path exists.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "watch", "description": "Subscribe to filesystem change events for the given paths.\nReturns an unsubscribe function. Events are filtered server-side.", "tags": [], "type": "((request: RuntimeWatchRequest, handler: (event: RuntimeWatchEvent) => void) => () => void) | undefined", "simplifiedType": "function", "required": false, "deprecated": false }, { "name": "readFiles", "description": "Batch-read multiple files as binary. Default: `Promise.all(paths.map(readFile))`.", "tags": [], "type": "(paths: string[]) => Promise>>", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "readdirContents", "description": "Read all file contents in a directory (skips subdirectories).", "tags": [], "type": "(directoryPath: string) => Promise>>", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "readdirStat", "description": "Get stat information for all entries in a directory.", "tags": [], "type": "(directoryPath: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false }, { "name": "ensureDir", "description": "Ensure a directory exists, creating parents as needed. Default: `mkdir(path, { recursive: true })`.", "tags": [], "type": "(path: string) => Promise", "simplifiedType": "function", "required": true, "deprecated": false } ] }} /> `fromMemoryFS`, `fromNodeFS`, and `fromFsLike` implement `RuntimeFileSystemBase` for in-memory, Node.js, and any fs-compatible backends respectively. Error Types [#error-types] **`RenderSupersededError`** -- Thrown when a newer `render()` call supersedes the current one. Use `isRenderSupersededError(error)` for realm-safe detection. **`RenderAbortedError`** -- Thrown when a render is aborted via the SharedArrayBuffer abort channel. Use `isRenderAbortedError(error)` for realm-safe detection. Event Subscription [#event-subscription] Subscribe to client events with `client.on(event, handler)`. Returns an unsubscribe function. | Event | Handler Signature | When | | -------------------- | ---------------------------------------------------------------- | ------------------------------ | | `geometry` | `(result: HashedGeometryResult) => void` | Render completes (autonomous) | | `state` | `(state: WorkerState, detail?: string) => void` | Worker state changes | | `log` | `(entry: { level, message, origin?, data? }) => void` | Kernel/middleware log messages | | `progress` | `(phase: RenderPhase, detail?: Record) => void` | Render phase transitions | | `telemetry` | `(entries: PerformanceEntryData[]) => void` | Performance entries | | `parametersResolved` | `(result: GetParametersResult) => void` | Parameters extracted | Usage [#usage] ```typescript import { createRuntimeClient, fromMemoryFS } from '@taucad/runtime'; import { replicad } from '@taucad/runtime/kernels'; import { esbuild } from '@taucad/runtime/bundler'; const client = createRuntimeClient({ kernels: [replicad()], bundlers: [esbuild()], fileSystem: fromMemoryFS(), }); const result = await client.render({ code: { 'main.ts': 'export default () => {}' }, }); client.terminate(); ``` Related [#related] * [Quick Start](../getting-started/quick-start) * [Set Up the Filesystem](../guides/filesystem-setup) * [Handle Errors](../guides/error-handling) * [Render Lifecycle](../concepts/render-lifecycle)