{"protocol":"clank-doc/1","frameworkVersion":"0.8.0","slug":"api-reference","title":"API reference","description":"This is the compact index of every public export. The focused guides contain behavioral details and examples.","group":{"id":"framework","title":"Framework"},"url":"https://docs.clank.run/docs/api-reference","source":"docs/api-reference.md","headings":["Core","DOM","Forms","Headless UI","Compiler","Deployment artifacts","Migrations","Deployment platform","Managed data plane","AI","Router","Server","Authentication","Full stack backend","SSR","Node"],"tableOfContents":[{"id":"core","title":"Core","level":2},{"id":"dom","title":"DOM","level":2},{"id":"forms","title":"Forms","level":2},{"id":"headless-ui","title":"Headless UI","level":2},{"id":"compiler","title":"Compiler","level":2},{"id":"deployment-artifacts","title":"Deployment artifacts","level":2},{"id":"migrations","title":"Migrations","level":2},{"id":"deployment-platform","title":"Deployment platform","level":2},{"id":"managed-data-plane","title":"Managed data plane","level":2},{"id":"ai","title":"AI","level":2},{"id":"router","title":"Router","level":2},{"id":"server","title":"Server","level":2},{"id":"authentication","title":"Authentication","level":2},{"id":"full-stack-backend","title":"Full-stack backend","level":2},{"id":"ssr","title":"SSR","level":2},{"id":"node","title":"Node","level":2}],"markdown":"# API reference\n\nThis is the compact index of every public export. The focused guides contain behavioral details and examples.\n\n## Core\n\n- `signal(value, options?)` → `ReactiveSignal<T>`: mutable tracked value.\n- `ReactiveSignal`: `.value`, `.get()`, `.peek()`, `.set()`, `.update()`, `.subscribe()`, `.toJSON()`.\n- `isSignal(value)`: detects signals and computed values.\n- `computed(derive, options?)` → `Computed<T>`: lazy cached derived value.\n- `effect(callback, options?)` → disposer: tracked synchronous side effect with cleanup.\n- `batch(callback)`: coalesces dependent effects.\n- `transaction(callback)`: batch with signal rollback on throw.\n- `untrack(callback)`: disables dependency capture in the callback.\n- `createRoot(callback)`: creates an ownership scope.\n- `onCleanup(callback)`: registers owned cleanup.\n- `getOwner()` / `runWithOwner(owner, callback)`: capture and restore ownership for advanced integrations.\n- `store(object)`: creates a lazy deep reactive proxy.\n- `isStore(value)`, `toRaw(value)`, `snapshot(value)`: store inspection and serialization.\n- `resource(loader, options?)`: async state with abort and stale-result protection.\n- `consumeStream(iterable, initial, reduce?)`: folds an async iterable into a signal.\n- `SIGNAL`, `STORE`: global protocol symbols for integrations.\n\n## DOM\n\n- TSX: preferred component syntax; dynamic braces become fine-grained bindings automatically.\n- `h(type, props?, ...children)` / `createElement`: lower-level VNode construction.\n- `jsx`, `jsxs`, `jsxDEV`: compiler runtime entry points.\n- `expression(read)`, `isExpression(value)`: compiler/runtime reactive boundary.\n- `Fragment`: groups children without an element.\n- `render(root, view)` → disposer: mounts an application.\n- `hydrate(root, view)` → disposer: attaches to marker-compatible SSR DOM; warns and remounts on a structural mismatch.\n- `isVNode(value)`: VNode detection.\n- `onMount(callback)`: post-mount lifecycle with optional cleanup.\n- `createContext(defaultValue)`, `provideContext(context, value)`, `useContext(context)`.\n- `Show`, `Match`, `Switch`: reactive conditional control flow.\n- `For`: O(n) keyed reconciliation with row identity preservation; use `by=\"id\"` or a key function.\n- `lazy(loader)`: promise-backed component.\n- Types: `Renderable`, `Component`, `VNode`, `ReactiveExpression`, `KeyedBlock`, `ElementType`, `ClankContext`.\n\nElement protocols include `onClick`/`on:click`, `bind:value`, `classList`, object `style`, callback/signal `ref`, directive `use`, `dangerouslySetInnerHTML`, and the `agent*` properties.\n\n## Forms\n\n- `createForm(options)` → typed headless form controller.\n- Controller state: `values`, `dirty`, `valid`, `pending`, `submitted`, `submitCount`, `status`, `result`, `error`, `formErrors`.\n- Controller methods: `field`, `setValue`, `setValues`, `setErrors`, `validate`, `submit`, `reset`, `focusFirstError`, `props`.\n- Field state: `value`, `errors`, `touched`, `dirty`, `invalid`, `message`.\n- Field helpers: `input`, `textarea`, `select`, `checkbox`, `radio`, `error`.\n- `manifest`: `clank-form/1` schema and field contract without live values.\n- Types: `FormController`, `FormField`, `FormManifest`, `FormErrorMap`, `FormStatus`, `CreateFormOptions`.\n\n## Headless UI\n\n- `createDisclosure(options)`: expandable state with trigger/panel ARIA props.\n- `createDialog(options)`: modal state, focus trap, Escape/backdrop handling, scroll lock, and focus restoration.\n- `createTabs(options)`: inferred tab values, panel relationships, roving tab index, and keyboard navigation.\n- `createPagination(options)`: page clamping, ranges, controls, and compact page items.\n- `clickOutside(handler)`: outside-pointer directive.\n- `autoFocus(element)`: mount-time focus directive.\n- Types: `DisclosureController`, `DialogController`, `TabsController`, `PaginationController`.\n\n## Compiler\n\n- `clank build [input] [output]`: compile `.ts`/`.tsx` and copy static files once.\n- `clank watch [input] [output]`: rebuild after source changes.\n- `--jsx-import-source=specifier`: choose the generated runtime module.\n- `compile(source, options?)`: programmatic TypeScript/TSX compilation.\n- `transformTSX(source, options?)`: programmatic TSX-only lowering.\n\n## Deployment artifacts\n\n- `readDeploymentConfig(root, filename?)`: read and normalize `clank.deploy.json`.\n- `parseDeploymentConfig(value)`: validate a config already in memory.\n- `createDeploymentBundle(root, config, options?)`: deterministic gzip artifact with checked files and provenance.\n- `decodeDeploymentBundle(bytes, limits?)`: bounded protocol, path, size, base64, and SHA-256 verification.\n- `extractDeploymentBundle(bundle, directory)`: exclusive extraction into a release root.\n- `deploymentDigest(bytes)`: SHA-256 artifact digest.\n- Types: `DeploymentConfig`, `DeploymentBundle`, `DeploymentFile`, `BundleLimits`.\n\n## Migrations\n\n- `loadMigrations(directory, options?)`: ordered SQL files and SHA-256 checksums.\n- `planMigrations(path, migrations)`: applied/pending state with immutable-history verification.\n- `applyMigrations(options)`: apply pending SQL in one immediate transaction.\n- `assertSafeMigrationSql(sql, id?)`: reject cross-database and transaction controls.\n- `backupSQLite(source, destination)`: consistent built-in SQLite backup.\n- `restoreSQLiteBackup(source, destination)`: replace a stopped database and clear WAL sidecars.\n- Types: `Migration`, `MigrationRecord`, `MigrationPlan`, `ApplyMigrationsOptions`.\n\n## Deployment platform\n\n- `openPlatform(options)`: browser dashboard, workspace people/invitation administration and activity, device authorization, tokens, projects, transactionally enforced limits, ingress metrics, DNS/domain lifecycle, TLS eligibility, encrypted secrets, role-filtered audit, release transaction, logs, rollback, and supervision.\n- `PlatformRuntime`: Fetch `.handle`, `.publicUrl`, `.dataDirectory`, async `.close()`.\n- Runners: dependency-free process runner or constrained Docker runner.\n- Types: `ClankPlatformOptions`, `PlatformLimits`, `PlatformRunnerOptions`, `ProcessRunnerOptions`, `DockerRunnerOptions`.\n\n## Managed data plane\n\n- `createManagedIngress(options)`: exact-host reverse proxy with fixed upstream origins, bounded streaming request bodies, hop-header stripping, safe retries, circuits, health, and request observation.\n- `inspectDomainRouting(hostname, target, resolver?)`: compare live CNAME/A/AAAA results to a configured edge target.\n- `createDomainManager(options)`: project-bound random TXT ownership challenges.\n- `createMemoryDomainStore()`: in-memory domain challenge store for local use and tests.\n- Types: `IngressRoute`, `IngressRequestMetric`, `ManagedIngress`, `DomainChallenge`, `DomainDnsResolver`, `DomainRoutingReport`.\n\n## AI\n\n- `defineApp(input)`: normalize and freeze a `clank-app/1` application blueprint.\n- `parseAppBlueprint(source, filename?)`: statically parse a JSON or constrained TypeScript data module without executing it.\n- `generateAppFiles(blueprint, options?)`: return deterministic full-stack application files.\n- `createAppPlan(blueprint, options?)`: checksum every generated file and return a `clank-plan/1` review artifact.\n- `explainApp(blueprint)`: summarize identity, data, routes, services, deployment requirements, and warnings.\n\n- `s`: runtime schema builders and JSON Schema generation. Includes string, email, URL, date, date-time, number, boolean, literal, enum, array, record, object, optional, nullable, default, refinement, union, and numeric/boolean coercion.\n- `ValidationError`: aggregate issues with paths.\n- `defineAction(definition)` → callable `Action` with `.manifest` and `.definition`.\n- `ActionError`: explicit code/status/details error.\n- `createAgentBridge(actions, options?)`: registry, discovery, bounded/origin-aware invocation, confirmation enforcement, and Fetch handler.\n- `actionRunner(action)`: reactive pending/data/error execution state.\n- `defineView(definition)`: component with machine-readable `viewManifest`.\n- `inspectAgentSurface(root)`: compact semantic UI tree with native labels/roles and form state; omits password/file values.\n- `createAgentSurface(root)`: inspect, activate, and input operations through explicit agent IDs or native element IDs.\n- Types: `Schema`, `Action`, `ActionContext`, `AgentBridge`, `ActionRunner`, `AgentNode`, `AgentSurface`.\n\n## Router\n\n- `createRouter(options)` → router with `state`, `current`, `navigate`, `resolve`, `start`, `View`, and `Link`.\n- `matchPath(pattern, pathname)`: parameter matcher.\n- `matchRoutes(routes, URL, base?)`: route selection and URL decoding.\n- `redirect(to, status?)`: Fetch redirect response.\n- Types: `RouteDefinition`, `RouteMatch`, `RouteState`, `RouteLoadContext`, `RouteGuardContext`, `Router`.\n\n## Server\n\n- `createApp(options?)` → Fetch request router with redacted errors and an error hook.\n- `.use`, `.route`, `.get`, `.post`, `.put`, `.patch`, `.delete`, `.handle`.\n- `json(value, init?)`, `text(value, init?)`, `html(value, init?)`.\n- `cors(options?)`, `securityHeaders(options?)`, `logger(write?)`: built-in middleware.\n- Types: `RequestContext`, `RequestHandler`, `Middleware`, `RequestApp`.\n\n## Authentication\n\n- `defineAuth(options?)`: default or custom-profile auth contract.\n- `openAuth(definition, database, options?)`: low-level SQLite auth runtime; normally opened automatically by `openBackend`.\n- `authState(requestAuth)`: safe serializable SSR subset.\n- `createAuthClient(options?)`: reactive auth-only client.\n- `createClient<typeof authenticatedBackend>(options?)`: combined typed API, auth, CSRF mutation, seeding, and live client.\n- `AuthGate`: reactive signed-in boundary with default auth screen.\n- `AuthForm`: default accessible email/password registration/login UI.\n- `AuthRuntime`: `.resolve`, `.handle`, `.middleware`, `.setRole`, `.disableUser`, `.revokeUserSessions`, `.verifyCsrf`, current-session refresh and subscription/status, `.close`.\n- `AuthClient`: `.user`, `.session`, `.authenticated`, `.loading`, `.error`, `.reload`, `.register`, `.login`, `.logout`, `.logoutAll`, `.changePassword`.\n- `AuthRequest`: `.user`, `.session`, `.csrfToken`, `.requireUser()`, `.requireRole()`.\n- `AuthError`: explicit safe auth code, status, and optional retry delay.\n- Types: `AuthDefinition`, `AuthDefinitionOptions`, `AuthUser`, `AuthSession`, `AuthState`, `AuthRegisterInput`, `AuthLoginInput`, `AuthUserId`, `DefaultAuthProfile`.\n\n## Full-stack backend\n\n- `defineTable(fields)`: validated document table definition; `.index(name, fields)` declares SQLite JSON expression indexes; `.owned()` scopes documents to the authenticated user.\n- `defineDatabase(tables)`: preserves table names and field schemas as the inference root.\n- `DocumentFor<Database, Table>`: inferred fields plus branded `_id`, `_creationTime`, `_version`, and `_ownerId` for owned tables.\n- `Id<Table>` / `DocumentId<Table>` / `s.id(table)`: nominal table-specific IDs.\n- `openSQLite(schema, options?)`: opens Node's built-in synchronous SQLite engine.\n- `createSQLiteDatabase(schema, connection, options?)`: wraps a compatible connection.\n- `SQLiteDatabase`: `.read`, `.tracked`, `.transaction`, `.subscribe`, `.version`, `.close`.\n- Read table: `.get`, `.query`, `.collect`.\n- Write table: `.insert`, `.patch`, `.replace`, `.delete`.\n- `DocumentWriteOptions`: `{ ifVersion }` optimistic concurrency for patch, replace, and delete.\n- `DatabaseConflictError`: stale-write error exposed as HTTP `409 VERSION_CONFLICT`.\n- Query builder: `.where`, `.orderBy`, `.limit`, `.collect`, `.first`.\n- `defineBackend({ schema, auth? }).functions(builders)`: inference-first nested function tree. Auth backends make `query`/`mutation` required and expose explicit `publicQuery`/`publicMutation`.\n- `createApi<typeof backend>()`: zero-codegen typed function-reference proxy.\n- `openBackend(definition, options?)`: consistent query cache, owner-scoped/persisted dependency invalidation, atomic mutations, manifest, bounded RPC, and SSE handler.\n- `BackendRuntime`: `.auth`, `.caller(request)`, `.query`, `.mutation`, `.subscribe`, `.handle`, `.version`, `.close`.\n- `createSyncClient(options?)`: typed browser/Fetch client with `.query`, `.mutate`, `.live`, and `.seed`.\n- `createClient<typeof backend>(options?)`: authenticated combined client with `.api` and `.auth`.\n- `BackendClientError`: safe RPC error with code/status.\n- `LiveQuery`: reactive `.data`, `.loading`, `.error`, `.version`, plus `.dispose()`.\n- `functionPath`, `functionKey`, `stableStringify`: reference and canonical argument helpers.\n- Types: `DatabaseSchema`, `TableDefinition`, `DocumentWriteOptions`, `DatabaseChange`, `SQLiteOptions`, `QueryBuilder`, `ReadDatabase`, `WriteDatabase`, `BackendFunction`, `BackendDefinition`, `FunctionReference`, `ApiOf`, `BackendRuntime`.\n\n## SSR\n\n- `renderToString(view, options?)`: escaped async HTML rendering with hydration markers by default.\n- `renderDocument(view, options?)`: complete document template with title, head content, stylesheets, state, module scripts, and optional CSP nonce.\n- `serializeState(value)`: JSON serialization safe for an HTML script element.\n- `readState<Value>(id?, root?)`: reads a serialized application state script.\n- Types: `RenderStringOptions`, `RenderDocumentOptions`.\n\n## Node\n\n- `serve(app, options?)`: bounded Fetch-standard Node HTTP server with streaming, timeouts, Host allowlists, proxy controls, and redacted errors.\n- `staticFiles(root, options?)`: traversal/symlink-aware static GET/HEAD handler with dotfile policy.\n- Types: `FetchApplication`, `ServeOptions`, `ServerHandle`, `StaticFilesOptions`.\n"}