### Install zero-svelte Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Install the zero-svelte package. Requires Svelte 5+ and @rocicorp/zero ^0.25 as peer dependencies. ```bash npm install zero-svelte # Peers: Svelte 5+, @rocicorp/zero ^0.25 ``` -------------------------------- ### Zero 0.25 schema setup with typed queries Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Schema setup for Zero 0.25 pattern. Defines a 'todo' table, creates a typed ZQL builder, and reusable queries with validators. Registers the schema as the default type to avoid explicit generics. ```ts // schema.ts import { createBuilder, createSchema, defineQueries, defineQuery, table, string, boolean } from '@rocicorp/zero'; import { type } from 'arktype'; // or zod const todos = table('todo') .columns({ id: string(), title: string(), completed: boolean() }) .primaryKey('id'); export const schema = createSchema({ tables: [todos] }); export type Schema = typeof schema; // Typed ZQL builder for raw queries export const zql = createBuilder(schema); // Reusable queries with validators export const queries = defineQueries({ todo: { all: defineQuery(() => zql.todo), byCompleted: defineQuery( type({ completed: 'boolean' }), ({ args: { completed } }) => zql.todo.where('completed', '=', completed) ) } }); // Register as default type (removes need for explicit generics) declare module '@rocicorp/zero' { interface DefaultTypes { schema: Schema; } } ``` -------------------------------- ### Example: `destroy` manual lifecycle Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md Example usage of `destroy` for manual lifecycle control. In practice, `Query` instances in Svelte components are garbage-collected with their effects. ```ts const q = z.createQuery(zql.todo); // ... later, when done: q.destroy(); ``` -------------------------------- ### Run an ephemeral query Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Example usage of the `run` method. It runs an ephemeral query and awaits the resulting rows. ```ts const rows = await z.run(queries.todo.all()); ``` -------------------------------- ### Cache hit example for getView Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewStore.md Shows that calling getView with the same query and enabled=true returns the same ViewWrapper instance due to hash-based caching. ```ts // Both handles share one materialized view (same query hash) const a = z.viewStore.getView(z, queryDef, true); const b = z.viewStore.getView(z, queryDef, true); a === b; // true (cache hit) ``` -------------------------------- ### Class Z Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Documentation for the Z class, including its constructor and usage example. ```APIDOC ## Class `Z` ### Description Reactive wrapper around `@rocicorp/zero`'s `Zero` client for Svelte 5. Owns a single `Zero` instance (held in `$state`), proxies its API, exposes a reactive `connectionState`, deduplicates materialized query views via an internal `ViewStore`, and supports rebuilding/tearing down the underlying client. ### Import ```ts import { Z } from 'zero-svelte'; ``` ### Class Declaration ```ts export class Z< TSchema extends BaseDefaultSchema = DefaultSchema, MD extends CustomMutatorDefs | undefined = undefined > ``` `TSchema` and `MD` mirror the underlying `Zero` generics. In a typical app they are inferred from the `schema`/`mutators` passed to the constructor; if the schema is registered globally via `declare module '@rocicorp/zero' { interface DefaultTypes { schema: Schema } }` (see `src/schema.ts`), the defaults apply and no explicit generics are needed. ### Constructor ```ts constructor(z_options: ZeroOptions) ``` `ZeroOptions` is defined by `@rocicorp/zero` (external package, not defined in this repo). Fields observed in this repository's usage (`src/routes/zero.svelte.ts`): `cacheURL`, `schema`, `mutators`, `userID`, `kvStore`. See [configuration.md](../configuration.md) for the full observed options and the note about the external definition. The constructor immediately calls `this.build(z_options)`, so a `Z` is fully connected to a live `Zero` instance as soon as it is constructed. `Z` can therefore be created once at module scope and shared. ### Example ```ts // src/lib/zero.svelte.ts (pattern from src/routes/zero.svelte.ts) import { PUBLIC_SERVER } from '$env/static/public'; import { Z } from 'zero-svelte'; import { mutators } from '../mutators.js'; import { schema } from '../schema.js'; export const z = new Z({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); export { mutators }; ``` ``` -------------------------------- ### Schema Setup with defineQueries (src/schema.ts) Source: https://github.com/stolinski/zero-svelte/blob/main/README.md Defines a typed schema with tables, relationships, and reusable queries using @rocicorp/zero. Includes a module augmentation to set the default schema type, removing the need for explicit generics. ```ts import { boolean, createBuilder, createSchema, defineQueries, defineQuery, relationships, string, table } from '@rocicorp/zero'; import { type } from 'arktype'; // or use zod const types = table('type').columns({ id: string(), name: string() }).primaryKey('id'); const todos = table('todo') .columns({ id: string(), title: string(), completed: boolean(), type_id: string() }) .primaryKey('id'); const todoRelationship = relationships(todos, ({ one }) => ({ type: one({ sourceField: ['type_id'], destField: ['id'], destSchema: types }) })); export const schema = createSchema({ tables: [types, todos], relationships: [todoRelationship] }); export type Schema = typeof schema; // Create a typed ZQL builder for raw queries export const zql = createBuilder(schema); // Define reusable queries with validators export const queries = defineQueries({ todo: { all: defineQuery(() => zql.todo.related('type')), byCompleted: defineQuery(type({ completed: 'boolean' }), ({ args: { completed } }) => zql.todo.where('completed', '=', completed).related('type') ) }, type: { all: defineQuery(() => zql.type) } }); // Register schema as default type for Zero (removes need for explicit generics) declare module '@rocicorp/zero' { interface DefaultTypes { schema: Schema; } } ``` -------------------------------- ### Example: `updateQuery` with filter Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md Example usage of `updateQuery` to apply a filter. Creates a query and updates it with a new query based on a `typeId` parameter. ```ts const todos = z.createQuery(zql.todo.related('type')); function applyFilter(typeId: string | undefined) { const q = typeId ? zql.todo.where('type_id', '=', typeId).related('type') : zql.todo.related('type'); todos.updateQuery(q); } ``` -------------------------------- ### Materialize a query into a view Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Example usage of the `materialize` method. It materializes a query into a view, adds a listener to log snapshots, and notes that `view.destroy()` should be called afterwards. ```ts const view = z.materialize(zql.todo.related('type')); view.addListener((snap) => console.log(snap)); // then view.destroy() ``` -------------------------------- ### q alias for createQuery Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md The `q` function is an alias for `createQuery` with an identical signature and return type. It accepts a query or query request and an optional `enabled` flag (default `true`), returning a `Query` object. The example shows how to create a query for related todos using `z.q`. ```ts q< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, enabled: boolean = true ): Query ``` ```ts const todos = z.q(zql.todo.related('type')); // zql from createBuilder(schema) ``` -------------------------------- ### ensureSubscribed usage example Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Forces the view to stay live even outside a reactive context. ```typescript // Force the view to stay live even outside a reactive context view.ensureSubscribed(); ``` -------------------------------- ### detailsOnly usage example Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Accesses the status details without subscribing, returning an object with type 'unknown', 'complete', or 'error'. ```typescript view.detailsOnly; // { type: 'unknown' | 'complete' | 'error' } ``` -------------------------------- ### Disabled getView example Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewStore.md Shows that calling getView with enabled=false returns a fresh, inert wrapper that never materializes and is not cached. The dataOnly property reflects the default format. ```ts // Disabled: inert wrapper, never materializes, never cached const gated = z.viewStore.getView(z, queryDef, false); gated.dataOnly; // format default ([] or undefined, depending on singular format) ``` -------------------------------- ### preload query into cache Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md The `preload` function preloads the query result into the local cache, useful for query-time UX before navigation. It returns a handle with `cleanup()` to release the query (rows may be kept for the configured `ttl`) and `complete` promise that resolves when materialized or fails on query error. The example shows preloading with a 30-second TTL and awaiting completion. ```ts preload< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, options?: | { /** * Time To Live. This is the amount of time to keep the rows associated with * this query after {@linkcode cleanup} has been called. */ ttl?: TTL | undefined; } | undefined ): { cleanup: () => void; complete: Promise } ``` ```ts const { cleanup, complete } = z.preload(zql.todo, { ttl: 30_000 }); await complete; ``` -------------------------------- ### z.build(z_options: ZeroOptions) Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/configuration.md Builds a new Z instance with the provided options, allowing runtime swapping of configuration (e.g., after auth changes). ```APIDOC ## z.build(z_options: ZeroOptions) ### Description Builds a new Z instance with the provided options, allowing runtime swapping of configuration (e.g., after auth changes). ### Method build ### Parameters #### Options Object (ZeroOptions) - **cacheURL** (string) - Required - URL of the zero-cache server that syncs data to the client. - **schema** (Schema) - Required - Zero schema used for typing queries; may be omitted if registered via `declare module '@rocicorp/zero' { interface DefaultTypes { schema: Schema } }`. - **mutators** (result of `defineMutators({...})`) - Required - Mutation definitions executed by `z.mutate(...)`. - **userID** (string) - Required - User ID under which syncs/mutations run. - **kvStore** ('mem') - Required - Client storage backend for the local cache. ### Request Example ```ts const z = z.build({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); ``` ### Response Returns a new Z instance. ### Notes Other ZeroOptions members (auth tokens, server overrides, log config, etc.) exist in the external type but are not enumerated here. ``` -------------------------------- ### Create Z Instance (src/lib/zero.svelte.ts) Source: https://github.com/stolinski/zero-svelte/blob/main/README.md Creates a Z instance with cacheURL, schema, mutators, userID, and kvStore. Exports the instance and mutators for use in components. ```ts import { PUBLIC_SERVER } from '$env/static/public'; import { Z } from 'zero-svelte'; import { mutators } from '../mutators.js'; import { schema } from '../schema.js'; // No need for explicit Schema generic when using DefaultTypes export const z = new Z({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); export { mutators }; ``` -------------------------------- ### new Z(z_options: ZeroOptions) Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/configuration.md The main constructor for the zero-svelte library. Accepts a ZeroOptions object to configure the client, including cache URL, schema, mutators, user ID, and KV store. ```APIDOC ## new Z(z_options: ZeroOptions) ### Description Creates a new Zero client instance with the provided configuration options. ### Method Constructor ### Parameters #### Options Object (ZeroOptions) - **cacheURL** (string) - Required - URL of the zero-cache server that syncs data to the client. - **schema** (Schema) - Required - Zero schema used for typing queries; may be omitted if registered via `declare module '@rocicorp/zero' { interface DefaultTypes { schema: Schema } }`. - **mutators** (result of `defineMutators({...})`) - Required - Mutation definitions executed by `z.mutate(...)`. - **userID** (string) - Required - User ID under which syncs/mutations run. - **kvStore** ('mem') - Required - Client storage backend for the local cache. ### Request Example ```ts const z = new Z({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); ``` ### Response Returns a new Z instance. ### Notes Other ZeroOptions members (auth tokens, server overrides, log config, etc.) exist in the external type but are not enumerated here. ``` -------------------------------- ### Initialize Zero instance with Z Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Creates a new Zero instance with cacheURL, schema, mutators, userID, and kvStore. Exports the instance and mutators for use in the app. ```ts // zero.svelte.ts import { Z } from 'zero-svelte'; import { schema } from './schema'; import { mutators } from './mutators'; export const z = new Z({ cacheURL: 'http://localhost:4848', schema, mutators, userID: 'anon', kvStore: 'mem' }); export { mutators }; ``` -------------------------------- ### Construct Z with ZeroOptions in zero.svelte.ts Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/configuration.md Canonical construction of the Z instance in src/routes/zero.svelte.ts. Uses the PUBLIC_SERVER environment variable for cacheURL, the schema from src/schema.ts, mutators from src/mutators.ts, a fixed userID of 'anon', and the 'mem' kvStore. ```ts export const z = new Z({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); ``` -------------------------------- ### dataOnly usage example Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Accesses the data without subscribing, returning rows or a single row (or undefined for empty singular query). ```typescript view.dataOnly; // rows or single row (or undefined for empty singular query) ``` -------------------------------- ### Basic query with defineQuery Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Creates a query using z.createQuery with a query defined in the schema. Iterates over the results in a Svelte each block. ```svelte {#each todos.data as todo (todo.id)}
{todo.title}
{/each} ``` -------------------------------- ### Rebuild Zero instance on auth change and close Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Shows how to rebuild the Zero instance when authentication changes and clean up when done. The build method accepts the same options with a new auth token, and close is called to release resources. ```ts // Rebuild when auth changes z.build({ ...options, auth: newToken }); // Clean up when done z.close(); ``` -------------------------------- ### Constructor signature for Z Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Constructor accepts ZeroOptions from @rocicorp/zero. Observed fields include cacheURL, schema, mutators, userID, kvStore. ```ts constructor(z_options: ZeroOptions) ``` -------------------------------- ### Update Query with updateQuery Source: https://github.com/stolinski/zero-svelte/blob/main/README.md Use this Svelte component to update a query instance in place. The 'updateQuery' method allows you to change the query definition without recreating the query object, which is useful for dynamic filtering. The example shows how to apply a filter based on a selected type ID. ```svelte ``` -------------------------------- ### Z.run (runOptions option) Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/configuration.md The `runOptions` option for `Z.run` provides additional run configuration. ```APIDOC ## Z.run (runOptions option) ### Description The `runOptions` option for `Z.run` provides additional run configuration. ### Parameters - **runOptions** (RunOptions | undefined) - Optional - Additional run options. `RunOptions` is from `@rocicorp/zero`. ### Usage Pass as an option to `Z.run`. ### Example ```ts z.run(query, { runOptions: { /* ... */ } }); ``` ``` -------------------------------- ### q Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md The `q` function is an alias for `createQuery` with an identical signature and return type. It accepts a query and an optional enabled flag, returning a `Query` object. ```APIDOC ## `q` ### Description Alias for `createQuery` with an identical signature and return type (`Query`); it simply delegates. ### Signature ```ts q< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, enabled: boolean = true ): Query ``` ### Parameters - **query** (`QueryOrQueryRequest`) - Required - The query to execute. - **enabled** (`boolean`) - Optional - Whether the query is enabled. Defaults to `true`. ### Return Value - `Query` - The query result. ### Example ```ts const todos = z.q(zql.todo.related('type')); // zql from createBuilder(schema) ``` ``` -------------------------------- ### Package entry point exports in package.json Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/index.md Defines the package entry point and export map for zero-svelte. The "." export condition provides TypeScript types, a Svelte-specific entry, and a default entry, all pointing to the dist build. ```json { "exports": { ".": { "types": "./dist/index.d.ts", "svelte": "./dist/index.js", "default": "./dist/index.js" } }, "svelte": "./dist/index.js", "types": "./dist/index.d.ts" } ``` -------------------------------- ### Basic Usage with Mutations (+page.svelte) Source: https://github.com/stolinski/zero-svelte/blob/main/README.md Shows a Svelte component that creates a query, handles form submission to insert todos, and toggles completion. Uses the mutators pattern for mutations. ```svelte
    {#each todos.data as todo (todo.id)}
  • toggleTodo(todo.id, !todo.completed)} /> {todo.title} - {todo.type?.name}
  • {/each}
``` -------------------------------- ### Raw ZQL for local-only filtering Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Builds a query dynamically using raw ZQL and $derived.by, applying a local ILIKE filter on the title without a server round-trip. ```svelte ``` -------------------------------- ### Query constructor Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md Creates a new Query instance. Usually you do not construct Query directly; obtain one via Z.createQuery or Z.q. ```APIDOC ## Query constructor ### Description Creates a new Query instance. Usually you do not construct Query directly; obtain one via Z.createQuery or Z.q. ### Method constructor ### Signature ```ts constructor( query: QueryDef, z: Z, enabled: boolean = true ) ``` ### Parameters - **query** (QueryDef) - Required - The resolved Zero query definition (QueryDef from @rocicorp/zero) - **z** (Z) - Required - The owning Z instance; used to reach its ViewStore - **enabled** (boolean) - Optional, default `true` - Passed to viewStore.getView(...); when false no view is materialized and .data returns the un-materialized default ### Behavior During construction the Query: 1. Asks z.viewStore.getView(z, query, enabled) for a ViewWrapper (deduplicated by query hash). 2. Creates a persistent effect via $effect.root(() => { $effect(() => { void this.#view?.current; }); }) — reading #view.current activates and continuously maintains the underlying subscription. The effect root is stored in #cleanup. ``` -------------------------------- ### build method signature Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Signature of the build method. Replaces the underlying Zero instance, unsubscribing from the previous connection state, then resubscribes and syncs #connectionState. Use this to rebuild the client with new options, e.g., after login/logout. ```ts build(z_options: ZeroOptions) ``` -------------------------------- ### Query constructor signature Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md Constructor signature for Query. The enabled parameter defaults to true and is passed to viewStore.getView; when false no view is materialized and .data returns the un-materialized default. ```ts constructor( query: QueryDef, z: Z, enabled: boolean = true ) ``` -------------------------------- ### Module-scope Z instance creation Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Creates a shared Z instance at module scope, connecting to a live Zero client immediately. Uses environment variable for cache URL and exports mutators. ```ts // src/lib/zero.svelte.ts (pattern from src/routes/zero.svelte.ts) import { PUBLIC_SERVER } from '$env/static/public'; import { Z } from 'zero-svelte'; import { mutators } from '../mutators.js'; import { schema } from '../schema.js'; export const z = new Z({ cacheURL: PUBLIC_SERVER, schema, mutators, userID: 'anon', kvStore: 'mem' }); export { mutators }; ``` -------------------------------- ### Basic createQuery usage Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Creates a query using a query from `defineQuery` (src/schema.ts). ```ts const todos = z.createQuery(queries.todo.all()); // query from defineQuery (src/schema.ts) ``` -------------------------------- ### ViewWrapper constructor Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Constructor signature for ViewWrapper, taking the owning Z, query definition, callbacks for materialization/dematerialization, and an enabled flag. ```typescript constructor( private z: Z, private query: QueryDef, private onMaterialized: (view: ViewWrapper) => void, private onDematerialized: () => void, private enabled: boolean ) ``` -------------------------------- ### Getter `current` Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Getter that activates subscription tracking and returns the current data and status. ```APIDOC ## Getter `current` ```ts get current(): readonly [HumanReadable, QueryResultDetails] ``` Calls `this.#subscribe()` (activating subscription tracking for the current effect), then returns `[this.#data[''], this.#status]`. This is the read path used by `Query`'s persistent `$effect`: ```ts // Inside Query's constructor (src/lib/query.svelte.ts): $effect(() => { void this.#view?.current; // activates and maintains the subscription }); ``` ``` -------------------------------- ### run Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Runs an ephemeral query and returns a promise of the rows. This method is part of the Zero client API and is used to execute a query without materializing it. ```APIDOC ## `run` ```ts run< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, runOptions?: RunOptions | undefined ) ``` Runs an ephemeral query (`NOTIFY`-based, non-materialized) and returns a promise of the rows; delegates to `this.#zero.run(resolved, runOptions)`. `RunOptions` and the exact resolved value are defined by `@rocicorp/zero` (external); the source passes the query through `addContextToQuery` first so synced `defineQuery` queries work. ```ts const rows = await z.run(queries.todo.all()); ``` ``` -------------------------------- ### POST /api/mutate handler with handleMutateRequest Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/endpoints.md Server-side handler for POST /api/mutate in the demo SvelteKit app. It creates a Postgres-backed Zero db provider from ZERO_UPSTREAM_DB, resolves the mutator by name with mustGetMutator, and runs it inside a transactional Zero server context with a hardcoded ctx: { userId: 'anon' }. No auth is enforced; unknown mutator names cause mustGetMutator to throw. ```ts import { ZERO_UPSTREAM_DB } from '$env/static/private'; import { mustGetMutator } from '@rocicorp/zero'; import { handleMutateRequest } from '@rocicorp/zero/server'; import { zeroNodePg } from '@rocicorp/zero/server/adapters/pg'; import { mutators } from '../../../mutators.js'; import { schema } from '../../../schema.js'; import type { RequestEvent } from '@sveltejs/kit'; // Create db provider using the Zero pg adapter const dbProvider = zeroNodePg(schema, ZERO_UPSTREAM_DB); export async function POST({ request }: RequestEvent) { const result = await handleMutateRequest( dbProvider, (transact) => transact((tx, name, args) => { const mutator = mustGetMutator(mutators, name); return mutator.fn({ args, tx, ctx: { userId: 'anon' } }); }), request ); return new Response(JSON.stringify(result)); } ``` -------------------------------- ### getView Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewStore.md Returns (and registers) the ViewWrapper for the given query. If enabled is false, returns a non-materializing wrapper without touching the cache. ```APIDOC ## getView ### Description Returns (and registers) the `ViewWrapper` for the given query. If `enabled` is `false`, returns a non-materializing wrapper without touching the cache. ### Method N/A (class method) ### Endpoint N/A (SDK method) ### Parameters - **z** (`Z`) - Required - The owning `Z` instance passed on to the wrapper (used for materialization) - **query** (`QueryDef`) - Required - The resolved Zero query definition (`QueryDef` from `@rocicorp/zero`) - **enabled** (`boolean`) - Optional, default `true` - When `false`, returns a **non-materializing** wrapper and does not touch the cache ### Returns `ViewWrapper` ### Behavior 1. **Disabled:** if `enabled` is falsy, returns a brand-new `ViewWrapper` constructed with no-op `onMaterialized`/`onDematerialized` callbacks and `false` enabled flag. The cache is not consulted or updated — every `getView` call with `enabled=false` returns a fresh, inert wrapper. 2. **Enabled:** computes `const hash = asQueryInternals(query).hash()` (`asQueryInternals` from `@rocicorp/zero/bindings`). 3. Wrapped in `untrack(...)` (from `svelte`) so state mutations performed here are not tracked by `$derived`/effects — this is what allows `createQuery` to be called safely inside `$derived`. 4. Looks up `#views.get(hash)`. If missing, constructs a new `ViewWrapper`, registering: - `onMaterialized`: verifies the cache entry for `hash` is still this view, then stores it; if the existing entry is a **different** view, throws `Error('View already exists')` (see [errors.md](../errors.md)). - `onDematerialized`: `this.#views.delete(hash)`. The new wrapper is stored in the map immediately (so concurrent `getView` calls for the same hash share the wrapper), then returned. 5. If present, returns the existing wrapper. ### Example ```ts // Both handles share one materialized view (same query hash) const a = z.viewStore.getView(z, queryDef, true); const b = z.viewStore.getView(z, queryDef, true); a === b; // true (cache hit) ``` ```ts // Disabled: inert wrapper, never materializes, never cached const gated = z.viewStore.getView(z, queryDef, false); gated.dataOnly; // format default ([] or undefined, depending on singular format) ``` ``` -------------------------------- ### getView method signature Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewStore.md Method signature for getView. Returns and registers the ViewWrapper for the given query. The enabled parameter defaults to true; when false, returns a non-materializing wrapper without touching the cache. ```ts getView< TTable extends keyof TSchema['tables'] & string, TSchema extends BaseDefaultSchema, TReturn, MD extends CustomMutatorDefs | undefined = undefined >( z: Z, query: QueryDef, enabled: boolean = true ): ViewWrapper ``` -------------------------------- ### Svelte: Handle connection states with needs-auth, error, closed Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/errors.md Use this Svelte block to render UI based on z.connectionState.name. For 'needs-auth', show a sign-in button that re-authenticates with a new token. For 'error', display the reason and a retry button. For 'closed', show a closed message. ```svelte {#if z.connectionState.name === 'needs-auth'} {:else if z.connectionState.name === 'error'} Error: {z.connectionState.reason} {:else if z.connectionState.name === 'closed'} Closed {/if} ``` -------------------------------- ### Local-only Filtering with Raw ZQL Source: https://github.com/stolinski/zero-svelte/blob/main/README.md Filters data already synced client-side without server round-trips, ideal for search. Uses $derived.by to conditionally apply a where clause with ILIKE. ```svelte {#each searchResults.data as todo (todo.id)}
{todo.title}
{/each} ``` -------------------------------- ### Query API Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md API documentation for the Query class methods and getter. ```APIDOC ## Getter `current` (deprecated) ### Description Deprecated alias that returns `this.data`. ### Method GET ### Endpoint `current` ### Parameters None ### Response Returns `this.data`. ``` ```APIDOC ## Method `updateQuery` ### Description Replaces the query in place, keeping the same `Query` instance (and therefore the same component bindings). Internally, it resolves the new query and obtains (or reuses) the `ViewWrapper` for the new query hash. Assigning `#view` (a `$state` field) triggers reactivity in any component reading `.data`/`.details`. ### Method CALL ### Endpoint `updateQuery` ### Parameters - `newQuery` (`QueryOrQueryRequest`) - Required - The replacement query (`zql` builder result or `defineQuery` result) - `enabled` (`boolean`) - Optional - Default: `true` - Whether the new query should materialize ### Request Example ```ts const todos = z.createQuery(zql.todo.related('type')); function applyFilter(typeId: string | undefined) { const q = typeId ? zql.todo.where('type_id', '=', typeId).related('type') : zql.todo.related('type'); todos.updateQuery(q); } ``` ``` ```APIDOC ## Method `destroy` ### Description Destroys the persistent effect root (`this.#cleanup?.()`). This tears down the subscriber that keeps the `ViewWrapper` alive; when the last consumer of the view is gone, `ViewWrapper`'s cleanup runs (`removeListener`, `view.destroy()`, `onDematerialized()`), evicting the view from the `ViewStore`. ### Method CALL ### Endpoint `destroy` ### Parameters None ### Request Example ```ts const q = z.createQuery(zql.todo); // ... later, when done: q.destroy(); ``` ``` -------------------------------- ### POST /api/query handler for Zero synced queries Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/endpoints.md Server-side endpoint for Zero synced queries. Resolves the query by name via mustGetQuery, calls its function with args and an empty context, and returns the computed result. No auth is enforced; unknown query names cause mustGetQuery to throw. ```ts import { mustGetQuery } from '@rocicorp/zero'; import { handleQueryRequest } from '@rocicorp/zero/server'; import { queries, schema } from '../../../schema.js'; import type { RequestEvent } from '@sveltejs/kit'; export async function POST({ request }: RequestEvent) { const result = await handleQueryRequest( (name, args) => { const query = mustGetQuery(queries, name); // Pass args and context (ctx) to the query function return query.fn({ args, ctx: {} }); }, schema, request ); return new Response(JSON.stringify(result)); } ``` -------------------------------- ### run method signature Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Type signature for the `run` method. It runs an ephemeral query (NOTIFY-based, non-materialized) and returns a promise of the rows. Delegates to `this.#zero.run(resolved, runOptions)` after passing the query through `addContextToQuery` so synced `defineQuery` queries work. `RunOptions` and the exact resolved value are defined by `@rocicorp/zero` (external). ```ts run< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, runOptions?: RunOptions | undefined ) ``` -------------------------------- ### Getter `view` Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Query.md Returns the underlying ViewWrapper or undefined. Kept for backwards compatibility; prefer data/details. ```APIDOC ## Getter `view` ### Description Returns the underlying `ViewWrapper` or `undefined`. Kept for backwards compatibility; prefer `data`/`details`. ### Method `get view()` ### Returns - **Type**: `ViewWrapper | undefined` - **Description**: The underlying view wrapper or `undefined`. ### See Also - [ViewWrapper class](./ViewWrapper.md) ``` -------------------------------- ### Getters (Public API) Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md A table of all public getters available on the Zero Svelte wrapper, including their types and descriptions. These getters provide access to the underlying Zero instance's query builder, mutation executor, connection state, and more. ```APIDOC ## Getters (Public API) ### Description These getters are available on the Zero Svelte wrapper instance (e.g., `z`) and provide access to the underlying Zero instance's functionality. ### Getter List | Getter | Type | Description | |--------|------|-------------| | `query` | `Zero['query']` | Zero's type-safe query builder (e.g. `z.query.todo`) | | `mutate` | `Zero['mutate']` | Zero mutation executor; call `z.mutate(mutator(...))` with a mutator result from `defineMutators` | | `mutateBatch` | `Zero['mutateBatch']` | Batch executor for multiple mutations | | `clientID` | `string` | Unique client identifier of the underlying Zero instance | | `userID` | `string \| undefined` | The authenticated user ID of the underlying Zero instance | | `context` | `Zero['context']` | Current Zero query context (used to resolve `defineQuery` queries) | | `online` | `boolean` | **Deprecated.** `true` only when `connectionState.name === 'connected'`. Use `connectionState` instead. | | `connectionState` | `ConnectionState` | Reactive connection state: `connecting` \| `connected` \| `disconnected` \| `needs-auth` \| `error` \| `closed`. Re-exported type from `@rocicorp/zero`. | | `connection` | `Connection` | Connection API for manual lifecycle control (e.g. retry with new auth). Re-exported type from `@rocicorp/zero`. | | `viewStore` | `ViewStore` | Per-instance materialized-view cache (see [ViewStore class](./ViewStore.md)) | | `current` | `Zero` | **Deprecated.** Direct access to the underlying Zero instance. Use `z.query`, `z.mutate`, `z.build` instead. | ### Usage Example `connectionState` is a `$state` field updated by a subscription to `Zero.connection.state` (established in `build()`), so reading it in a component is reactive. ```svelte {#if z.connectionState.name === 'connected'} Connected {:else if z.connectionState.name === 'needs-auth'} {:else if z.connectionState.name === 'error'} Error: {z.connectionState.reason} {:else if z.connectionState.name === 'closed'} Closed {/if} ``` ``` -------------------------------- ### Updating a query in place Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Creates a query and later updates it with a new ZQL condition using updateQuery. ```ts const todos = z.createQuery(zql.todo); // Later: todos.updateQuery(zql.todo.where('completed', '=', true)); ``` -------------------------------- ### Rebuild with changed auth Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md Rebuilds the client with changed auth, as documented in the README 'Build' usage pattern. Pass a new options object, such as a new userID, to reset the instance state. ```ts z.build({ ...previousOptions, userID: newUserId }); ``` -------------------------------- ### preload Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/Z.md The `preload` function preloads the query result into the local cache, useful for query-time UX before navigation. It returns a handle with `cleanup` and `complete`. ```APIDOC ## `preload` ### Description Preloads the query result into the local cache (useful for query-time UX before navigation). Returns a handle with `cleanup` and `complete`. ### Signature ```ts preload< TTable extends keyof TSchema['tables'] & string, TInput extends ReadonlyJSONValue | undefined, TOutput extends ReadonlyJSONValue | undefined, TReturn = PullRow, TContext extends BaseDefaultContext = DefaultContext >( query: QueryOrQueryRequest, options?: { /** * Time To Live. This is the amount of time to keep the rows associated with * this query after {@linkcode cleanup} has been called. */ ttl?: TTL | undefined; } | undefined ): { cleanup: () => void; complete: Promise } ``` ### Parameters - **query** (`QueryOrQueryRequest`) - Required - The query to preload. - **options** (`object`) - Optional - Options for preloading. - **ttl** (`TTL`) - Optional - Time To Live. The amount of time to keep the rows associated with this query after `cleanup` has been called. ### Return Value - **cleanup** (`() => void`) - Releases the query from the cache (rows may be kept for the configured `ttl`). - **complete** (`Promise`) - Resolves when the query has been materialized (or fails on query error; per `@rocicorp/zero` semantics delegated by `this.#zero.preload`). ### Example ```ts const { cleanup, complete } = z.preload(zql.todo, { ttl: 30_000 }); await complete; ``` ``` -------------------------------- ### Connection State Handling in Svelte Source: https://github.com/stolinski/zero-svelte/blob/main/llms.txt Svelte component that reacts to Zero's connection state (Zero 0.25+). Handles connected, connecting, disconnected, needs-auth, and error states, with appropriate UI and actions. ```svelte {#if z.connectionState.name === 'connected'} Connected {:else if z.connectionState.name === 'connecting'} Connecting... {:else if z.connectionState.name === 'disconnected'} Offline: {z.connectionState.reason} {:else if z.connectionState.name === 'needs-auth'} {:else if z.connectionState.name === 'error'} {/if} ``` -------------------------------- ### Getter current signature Source: https://github.com/stolinski/zero-svelte/blob/main/_autodocs/api-reference/ViewWrapper.md Returns a readonly tuple of the human-readable data and query result details. Activates subscription tracking when accessed. ```typescript get current(): readonly [HumanReadable, QueryResultDetails] ```