Navigate

API reference

@pyric/cli/serve/worker

187 published symbols from @pyric/cli

Generated from the TypeScript declarations shipped at this import path.

Classes

RtdbOnDisconnect

Constructors

Constructor
new RtdbOnDisconnect(_repo: RtdbRefHandle, _path?: string): RtdbOnDisconnect;
Parameters
ParameterType
_repoRtdbRefHandle
_path?string
Returns

RtdbOnDisconnect

Methods

cancel()
cancel(): Promise<void>;
Returns

Promise<void>

remove()
remove(): Promise<void>;
Returns

Promise<void>

set()
set(value: unknown): Promise<void>;
Parameters
ParameterType
valueunknown
Returns

Promise<void>

setWithPriority()
setWithPriority(value: unknown, priority: string | number): Promise<void>;
Parameters
ParameterType
valueunknown
prioritystring | number
Returns

Promise<void>

update()
update(values: Record<string, unknown>): Promise<void>;
Parameters
ParameterType
valuesRecord<string, unknown>
Returns

Promise<void>

Interfaces

ClientAuth

Client-side Auth handle. Holds the port + a local currentUser mirror. Returned by getAuth(db | workerUrl). Mirrors firebase/auth’s Auth.

Properties

PropertyModifierTypeDescription
currentUserpublicClientUserLocal mirror of the worker’s currentUser, updated from the stream.
portreadonlyClientPort-
tenantIdpublicstringIdentity Platform tenant that subsequent sign-ins on THIS PORT authenticate against, or null for the project-level pool. Assign before calling a sign-in function: the value crosses the port with the sign-in request, so the worker’s session state carries it and rules evaluate the port’s operations with request.auth.token.firebase.tenant set to it.

Methods

signOut()
signOut(): Promise<void>;
Returns

Promise<void>


ClientDb

Opaque client-side Firestore handle. Holds the MessagePort to the worker.

Properties

PropertyModifierType
portreadonlyClientPort

ClientDocSnapshot

Type Parameters

Type ParameterDefault type
TDocumentData

Properties

PropertyModifierTypeDescription
idreadonlystring-
metadatareadonlySnapshotMetadata-
pathreadonlystring-
refreadonlyDocRefHandle<T>Full port-carrying reference, usable by write APIs.

Methods

data()
data(): T;
Returns

T

exists()
exists(): boolean;
Returns

boolean

get()
get(fieldPath: SnapshotFieldPath): unknown;

Production’s DocumentSnapshot.get: the stored field at fieldPath, or undefined.

Parameters
ParameterType
fieldPathSnapshotFieldPath
Returns

unknown


ClientFirebaseStorage

Worker-backed Storage handle (carries the shared MessagePort).

Properties

PropertyModifierTypeDescription
bucketreadonlystring-
namedBucket?readonlybooleanTrue for a handle getStorage opened on a bucket by name, rather than the app’s default bucket.
portreadonlyClientPort-

ClientQuerySnapshot

Properties

PropertyModifierType
docsreadonlyClientDocSnapshot<DocumentData>[]
emptyreadonlyboolean
metadatareadonlySnapshotMetadata
sizereadonlynumber

Methods

docChanges()
docChanges(options?: DocChangesOptions): DocumentChange<ClientDocSnapshot<DocumentData>>[];

Production’s QuerySnapshot.docChanges: the changes since the listener’s previous snapshot, or every document added on the first.

Parameters
ParameterType
options?DocChangesOptions
Returns

DocumentChange<ClientDocSnapshot<DocumentData>>[]

forEach()
forEach(callback: (doc: ClientDocSnapshot) => void, thisArg?: unknown): void;

Production’s QuerySnapshot.forEach: calls callback once per document, in query order.

Parameters
ParameterType
callback(doc: ClientDocSnapshot) => void
thisArg?unknown
Returns

void


ClientRtdb

Properties

PropertyModifierTypeDescription
instance?readonlyClientRtdbInstanceAbsent for a handle that names no URL, such as Studio’s; it reads and writes the default instance.
portreadonlyClientPort-

ClientSettableMetadata

Mirror of pyric/storage’s SettableMetadata (plain JSON on the wire).

Properties

PropertyType
cacheControl?string
contentDisposition?string
contentEncoding?string
contentLanguage?string
contentType?string
customMetadata?{ [key: string]: string; }

ClientStorageReference

Worker-backed Storage reference (path + name; carries the port for ops).

Properties

PropertyModifierType
bucketreadonlystring
fullPathreadonlystring
namereadonlystring
parentreadonlyClientStorageReference
portreadonlyClientPort
rootreadonlyClientStorageReference
storage?readonlyClientFirebaseStorage

Methods

toString()
toString(): string;
Returns

string


ClientTransaction

Client-side transaction handle.

Methods

delete()
delete(ref: DocRefHandle): ClientTransaction;
Parameters
ParameterType
refDocRefHandle
Returns

ClientTransaction

get()
get<T>(ref: DocRefHandle<T>): Promise<ClientDocSnapshot<T>>;
Type Parameters
Type ParameterDefault type
TDocumentData
Parameters
ParameterType
refDocRefHandle<T>
Returns

Promise<ClientDocSnapshot<T>>

set()
set<T>(
   ref: DocRefHandle<T>,
   data: T,
   options?: ClientSetOptions): ClientTransaction;
Type Parameters
Type ParameterDefault type
TDocumentData
Parameters
ParameterType
refDocRefHandle<T>
dataT
options?ClientSetOptions
Returns

ClientTransaction

update()
Call Signature
update(ref: DocRefHandle, data: Record<string, unknown>): ClientTransaction;
Parameters
ParameterType
refDocRefHandle
dataRecord<string, unknown>
Returns

ClientTransaction

Call Signature
update(
   ref: DocRefHandle,
   field: string | FieldPath,
   value: unknown, ...
   moreFieldsAndValues: unknown[]): ClientTransaction;
Parameters
ParameterType
refDocRefHandle
fieldstring | FieldPath
valueunknown
…moreFieldsAndValuesunknown[]
Returns

ClientTransaction


ClientUploadTask

Extends

Properties

PropertyModifierType
snapshotreadonlyClientUploadTaskSnapshot

Methods

cancel()
cancel(): boolean;
Returns

boolean

on()
on(
   event: string,
   nextOrObserver?:
  | (snapshot: ClientUploadTaskSnapshot) => unknown
  | {
  complete?: () => unknown;
  error?: (error: Error) => unknown;
  next?: (snapshot: ClientUploadTaskSnapshot) => unknown;
},
   error?: (error: Error) => unknown,
   complete?: () => unknown): () => void;
Parameters
ParameterType
eventstring
nextOrObserver?| (snapshot: ClientUploadTaskSnapshot) => unknown | { complete?: () => unknown; error?: (error: Error) => unknown; next?: (snapshot: ClientUploadTaskSnapshot) => unknown; }
error?(error: Error) => unknown
complete?() => unknown
Returns
(): void;
Returns

void

pause()
pause(): boolean;
Returns

boolean

resume()
resume(): boolean;
Returns

boolean


ClientUploadTaskSnapshot

Properties

PropertyModifierType
bytesTransferredreadonlynumber
metadatareadonlyFullMetadata
refreadonlyClientStorageReference
statereadonlyClientTaskState
taskreadonlyClientUploadTask
totalBytesreadonlynumber

ClientUser

Client-side User — a snapshot of the worker’s User with token accessors that RPC back to the worker. Mirrors firebase/auth’s User shape.

Properties

PropertyModifierTypeDescription
displayNamereadonlystring-
emailreadonlystring-
emailVerifiedreadonlyboolean-
isAnonymousreadonlyboolean-
phoneNumberreadonlystring-
photoURLreadonlystring-
providerDatareadonlyreadonly { displayName: string; email: string; phoneNumber: string; photoURL: string; providerId: string; uid: string; }[]-
providerIdreadonlystring-
tenantIdreadonlystringTenant this user authenticated under, or null for the project-level pool. Mirrors firebase/auth’s User.tenantId.
uidreadonlystring-

Methods

getIdToken()
getIdToken(forceRefresh?: boolean): Promise<string>;
Parameters
ParameterType
forceRefresh?boolean
Returns

Promise<string>

getIdTokenResult()
getIdTokenResult(forceRefresh?: boolean): Promise<SerializedIdTokenResult>;
Parameters
ParameterType
forceRefresh?boolean
Returns

Promise<SerializedIdTokenResult>


ClientUserCredential

Client-side UserCredential — mirrors firebase/auth.

Properties

PropertyType
operationType"link" | "signIn" | "reauthenticate"
providerIdstring
userClientUser

ClientWriteBatch

Client-side write batch. Buffers set/update/delete calls and sends them all to the worker on .commit().

Mirrors pyric/firestore’s writeBatch(db) shape: const batch = writeBatch(db); batch.set(ref, { … }); batch.delete(ref2); await batch.commit();

Methods

commit()
commit(): Promise<void>;
Returns

Promise<void>

delete()
delete(ref: DocRefHandle): ClientWriteBatch;
Parameters
ParameterType
refDocRefHandle
Returns

ClientWriteBatch

set()
set<T>(
   ref: DocRefHandle<T>,
   data: T,
   options?: ClientSetOptions): ClientWriteBatch;
Type Parameters
Type ParameterDefault type
TDocumentData
Parameters
ParameterType
refDocRefHandle<T>
dataT
options?ClientSetOptions
Returns

ClientWriteBatch

update()
Call Signature
update(ref: DocRefHandle, data: Record<string, unknown>): ClientWriteBatch;
Parameters
ParameterType
refDocRefHandle
dataRecord<string, unknown>
Returns

ClientWriteBatch

Call Signature
update(
   ref: DocRefHandle,
   field: string | FieldPath,
   value: unknown, ...
   moreFieldsAndValues: unknown[]): ClientWriteBatch;
Parameters
ParameterType
refDocRefHandle
fieldstring | FieldPath
valueunknown
…moreFieldsAndValuesunknown[]
Returns

ClientWriteBatch


CollRefHandle

Client-side collection reference.

Type Parameters

Type ParameterDefault type
_TDocumentData

Properties

PropertyModifierType
converterreadonlyFirestoreDataConverter<unknown, DocumentData>
descriptorreadonlyCollRef
idreadonlystring
pathreadonlystring
portreadonlyClientPort

Methods

withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): CollRefHandle<T>;
Type Parameters
Type ParameterDefault type
T-
D extends DocumentDataDocumentData
Parameters
ParameterType
converterFirestoreDataConverter<T, D>
Returns

CollRefHandle<T>

Call Signature
withConverter(converter: null): CollRefHandle;
Parameters
ParameterType
converternull
Returns

CollRefHandle


DisconnectClientOptions

Properties

PropertyTypeDescription
ackTimeoutMs?numberBound version-skew and worker-crash cases where no disconnect reply arrives.

DocRefHandle

Client-side document reference — carries a DocRef descriptor + port.

Type Parameters

Type ParameterDefault type
_TDocumentData

Properties

PropertyModifierType
converterreadonlyFirestoreDataConverter<unknown, DocumentData>
descriptorreadonlyDocRef
idreadonlystring
pathreadonlystring
portreadonlyClientPort

Methods

withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): DocRefHandle<T>;
Type Parameters
Type ParameterDefault type
T-
D extends DocumentDataDocumentData
Parameters
ParameterType
converterFirestoreDataConverter<T, D>
Returns

DocRefHandle<T>

Call Signature
withConverter(converter: null): DocRefHandle;
Parameters
ParameterType
converternull
Returns

DocRefHandle


PresenceSession

Properties

PropertyModifierTypeDescription
clientIdreadonlystringLogical page id — Studio uses this to label “This page”.
kindreadonlyPresenceClientKind-

Methods

stop()
stop(): void;

Stop heartbeats, listeners, and send a best-effort disconnect.

Returns

void


PresenceSnapshot

Properties

PropertyType
clientsPresenceClientRecord[]

PyricRuntimeManifest

Browser-safe SharedWorker and hosted CLIENT surface (Studio/Playground data plane).

This barrel exports ONLY the leaf client + the wire-protocol types — the pieces a browser app (the served page, or Pyric Studio’s Vite app) imports to connect by SharedWorker MessagePort or hosted WebSocket. It deliberately does NOT re-export host.ts/entry.ts:

  • host.ts imports the full pyric/firestore + pyric/auth engine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.
  • entry.ts references SharedWorkerGlobalScope and is esbuild-only.

client.ts imports only the value codec (pyric/firestore/internal/value-codec, a leaf internal seam) and type-only pyric/sandbox (erased at build), so this entry stays free of the ~10 MB rules/sandbox engine — safe to import from any browser app.

Exposed by @pyric/cli’s ./serve/worker package export so Studio can import { getFirestore, subscribeEvents, setLens } from '@pyric/cli/serve/worker' and reach the SharedWorker backend. readHostedTarget reads the host declaration; getHostedFirestore opens its WebSocket client. Both are supported adapter exports used by Studio/Playground.

Properties

PropertyTypeDescription
studioUrlstring-
worker{ name: string; servedEpoch: string; url: string; }-
worker.namestring-
worker.servedEpochstringContent epoch served by the current dev server; null in in-page mode.
worker.urlstring-

QueryHandle

Client-side query.

Type Parameters

Type ParameterDefault type
_TDocumentData

Properties

PropertyModifierType
converterreadonlyFirestoreDataConverter<unknown, DocumentData>
descriptorreadonlyQueryDescriptor
portreadonlyClientPort

Methods

withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): QueryHandle<T>;
Type Parameters
Type ParameterDefault type
T-
D extends DocumentDataDocumentData
Parameters
ParameterType
converterFirestoreDataConverter<T, D>
Returns

QueryHandle<T>

Call Signature
withConverter(converter: null): QueryHandle;
Parameters
ParameterType
converternull
Returns

QueryHandle


ResolvedIdentity

A provider identity resolved IN-PAGE (by the ServeAuthHelper’s popup/redirect picker) and handed to the worker for sign-in. Provider flows (signInWithPopup/signInWithRedirect) can’t cross the worker port — the AuthFlowResolver lives in-page — so the page resolves the picked identity and bridges it here; the worker seeds it + restoreSessions it (no password — provider users never sign in with one). See auth.acceptIdentity.

Properties

PropertyModifierTypeDescription
customClaimsreadonlyRecord<string, unknown>-
displayNamereadonlystring-
emailreadonlystring-
emailVerified?readonlybooleanThe staged user’s emailVerified (served sandbox.mockSignInResult). When present, it decides a new account’s flag and an existing account keeps its own, as the in-page mock does. Absent on a dialog identity, whose provider decides.
photoURLreadonlystringThe provider profile photo this identity carries, or null when it carries none. Named for the serialized-user convention of this protocol (photoURL); the host maps it onto the seed record’s photoUrl at the seedUsers boundary, exactly as displayName is mapped there.
providerIdreadonlystring-
uidreadonlystring-

RtdbDataSnapshot

Properties

PropertyModifierType
keyreadonlystring
priorityreadonlystring | number
refreadonlyRtdbRefHandle
sizereadonlynumber

Methods

child()
child(path: string): RtdbDataSnapshot;
Parameters
ParameterType
pathstring
Returns

RtdbDataSnapshot

exists()
exists(): boolean;
Returns

boolean

exportVal()
exportVal(): unknown;
Returns

unknown

forEach()
forEach(cb: (child: RtdbDataSnapshot) => boolean | void): boolean;
Parameters
ParameterType
cb(child: RtdbDataSnapshot) => boolean | void
Returns

boolean

hasChild()
hasChild(path: string): boolean;
Parameters
ParameterType
pathstring
Returns

boolean

hasChildren()
hasChildren(): boolean;
Returns

boolean

toJSON()
toJSON(): unknown;
Returns

unknown

val()
val(): unknown;
Returns

unknown


RtdbRefHandle

Properties

PropertyModifierTypeDescription
instance?readonlyClientRtdbInstanceThe instance the reference belongs to; see ClientRtdb.instance.
keyreadonlystring-
parentreadonlyRtdbRefHandle-
pathreadonlystring-
portreadonlyClientPort-
refreadonlyRtdbRefHandle-
rootreadonlyRtdbRefHandle-

Methods

isEqual()
isEqual(other:
  | RtdbRefHandle
  | {
  ref: RtdbRefHandle;
}): boolean;
Parameters
ParameterType
other| RtdbRefHandle | { ref: RtdbRefHandle; }
Returns

boolean

toJSON()
toJSON(): string;
Returns

string

toString()
toString(): string;
Returns

string


SerializedIdTokenResult

Wire form of getIdTokenResult().

Properties

PropertyModifierType
authTimereadonlystring
claimsreadonlyRecord<string, unknown>
expirationTimereadonlystring
issuedAtTimereadonlystring
signInProviderreadonlystring
tokenreadonlystring

SerializedUser

Wire representation of a signed-in User. The real pyric/auth User carries methods (getIdToken, getIdTokenResult) that don’t survive structured clone, so the worker flattens the fields the client mirror needs into a plain object. Token accessors on the client re-RPC to the worker (the worker holds the one real user).

null means “signed out” — there is no current user.

Properties

PropertyModifierTypeDescription
displayNamereadonlystring-
emailreadonlystring-
emailVerifiedreadonlyboolean-
isAnonymousreadonlyboolean-
phoneNumberreadonlystring-
photoURLreadonlystring-
providerDatareadonlyreadonly { displayName: string; email: string; phoneNumber: string; photoURL: string; providerId: string; uid: string; }[]-
providerIdreadonlystring-
sessionKey?readonlystringThe key of the worker session this user belongs to, the sandbox’s stand-in for a refresh token. The page stores it with the uid, and a reload hands it back to auth.restorePortSession to resume the session with the authentication time it had (#1950). Absent outside a session.
tenantIdreadonlystring-
uidreadonlystring-

SerializedUserCredential

Wire form of a UserCredential returned by the sign-in/create ops.

Properties

PropertyModifierType
additionalUserInfo?readonly{ isNewUser: boolean; profile: Record<string, unknown>; providerId: string; }
additionalUserInfo.isNewUserreadonlyboolean
additionalUserInfo.profilereadonlyRecord<string, unknown>
additionalUserInfo.providerIdreadonlystring
operationTypereadonly"link" | "signIn" | "reauthenticate"
providerIdreadonlystring
userreadonlySerializedUser

WorkerCheckpoint

One saved state as a listing reports it: the name, when it was taken, and its counts.

Properties

PropertyType
atnumber
counts{ auth: number; database: number; firestore: number; storage: number; }
counts.authnumber
counts.databasenumber
counts.firestorenumber
counts.storagenumber
namestring

WorkerReplacement

Methods

dispose()
dispose(): void;
Returns

void

request()
request(): Promise<void>;
Returns

Promise<void>

Type Aliases

AnyHandle

type AnyHandle =
  | ClientDb
  | DocRefHandle
  | CollRefHandle
  | QueryHandle;

Union of all client handles.


AuthPersistenceMode

type AuthPersistenceMode = "LOCAL" | "SESSION" | "NONE";

Persistence mode for the worker’s shared auth session. Mirrors pyric/auth’s Persistence.type. 'NONE' (inMemoryPersistence) disables the IndexedDB session record so a full close does NOT keep the user signed in; 'LOCAL' and 'SESSION' both persist the session in this single-backend model (see SESSION/LOCAL collapse note in host.ts).


PresenceClientKind

type PresenceClientKind = "app" | "studio";

PresenceVisibility

type PresenceVisibility = "visible" | "hidden";

Unsubscribe()

type Unsubscribe = () => void;

Unsubscribe function returned by every streaming subscription.

Returns

void

Variables

AUTH_LENS_STORAGE_KEY

const AUTH_LENS_STORAGE_KEY: "pyric:auth-lens" = "pyric:auth-lens";

browserLocalPersistence

const browserLocalPersistence: {
  type: "LOCAL";
};

Type Declaration

type
readonly type: "LOCAL";

browserSessionPersistence

const browserSessionPersistence: {
  type: "SESSION";
};

Type Declaration

type
readonly type: "SESSION";

inMemoryPersistence

const inMemoryPersistence: {
  type: "NONE";
};

Type Declaration

type
readonly type: "NONE";

PRESENCE_HEARTBEAT_INTERVAL_MS

const PRESENCE_HEARTBEAT_INTERVAL_MS: 15000 = 15000;

Suggested client heartbeat interval.


PRESENCE_STALE_MS

const PRESENCE_STALE_MS: 90000 = 90000;

Lease TTL. Sized to tolerate one delayed background-tab heartbeat under typical timer throttling (~1/min) without falsely evicting a live page.


PYRIC_WORKER_GENERATION_KEY

const PYRIC_WORKER_GENERATION_KEY: "pyric:worker-generation" = "pyric:worker-generation";

PYRIC_WORKER_NAME

const PYRIC_WORKER_NAME: "pyric-shared-worker" = "pyric-shared-worker";

Browser-safe SharedWorker and hosted CLIENT surface (Studio/Playground data plane).

This barrel exports ONLY the leaf client + the wire-protocol types — the pieces a browser app (the served page, or Pyric Studio’s Vite app) imports to connect by SharedWorker MessagePort or hosted WebSocket. It deliberately does NOT re-export host.ts/entry.ts:

  • host.ts imports the full pyric/firestore + pyric/auth engine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.
  • entry.ts references SharedWorkerGlobalScope and is esbuild-only.

client.ts imports only the value codec (pyric/firestore/internal/value-codec, a leaf internal seam) and type-only pyric/sandbox (erased at build), so this entry stays free of the ~10 MB rules/sandbox engine — safe to import from any browser app.

Exposed by @pyric/cli’s ./serve/worker package export so Studio can import { getFirestore, subscribeEvents, setLens } from '@pyric/cli/serve/worker' and reach the SharedWorker backend. readHostedTarget reads the host declaration; getHostedFirestore opens its WebSocket client. Both are supported adapter exports used by Studio/Playground.


PYRIC_WORKER_URL

const PYRIC_WORKER_URL: "/__pyric/sdk/worker.js" = "/__pyric/sdk/worker.js";

Stable routes and identity used by the served runtime and its UI.

Functions

acceptProviderCredential()

function acceptProviderCredential(auth: ClientAuth, identity: ResolvedIdentity): Promise<ClientUserCredential>;

Bridge a provider identity resolved IN-PAGE to the worker.

Parameters

ParameterType
authClientAuth
identityResolvedIdentity

Returns

Promise<ClientUserCredential>


addDoc()

function addDoc(coll: CollRefHandle, data: Record<string, unknown>): Promise<DocRefHandle<DocumentData>>;

Parameters

ParameterType
collCollRefHandle
dataRecord<string, unknown>

Returns

Promise<DocRefHandle<DocumentData>>


adminClearUsers()

function adminClearUsers(auth: ClientAuth): Promise<void>;

Parameters

ParameterType
authClientAuth

Returns

Promise<void>


adminCreateUser()

function adminCreateUser(auth: ClientAuth, request: CreateUserRequest): Promise<AuthUserRecord>;

Parameters

ParameterType
authClientAuth
requestCreateUserRequest

Returns

Promise<AuthUserRecord>


adminDeleteDocument()

function adminDeleteDocument(db: ClientDb, path: string): Promise<boolean>;

Parameters

ParameterType
dbClientDb
pathstring

Returns

Promise<boolean>


adminDeleteRtdbValue()

function adminDeleteRtdbValue(
   db: ClientDb | ClientRtdb,
   path: string,
instance?: string): Promise<void>;

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
instance?string

Returns

Promise<void>


adminDeleteUser()

function adminDeleteUser(auth: ClientAuth, uid: string): Promise<void>;

Parameters

ParameterType
authClientAuth
uidstring

Returns

Promise<void>


adminGetDocument()

function adminGetDocument(db: ClientDb, path: string): Promise<Record<string, unknown>>;

Parameters

ParameterType
dbClientDb
pathstring

Returns

Promise<Record<string, unknown>>


adminListDocuments()

function adminListDocuments(db: ClientDb, path: string): Promise<{
  data: unknown;
  path: string;
  phantom?: boolean;
}[]>;

Parameters

ParameterType
dbClientDb
pathstring

Returns

Promise<{ data: unknown; path: string; phantom?: boolean; }[]>


adminReadRtdbState()

function adminReadRtdbState(db: ClientDb | ClientRtdb, instance?: string): Promise<unknown>;

Parameters

ParameterType
dbClientDb | ClientRtdb
instance?string

Returns

Promise<unknown>


adminReadState()

function adminReadState(db: ClientDb, opts?: {
  maxDepth?: number;
  path?: string;
}): Promise<Record<string, unknown>>;

Parameters

ParameterType
dbClientDb
opts?{ maxDepth?: number; path?: string; }
opts.maxDepth?number
opts.path?string

Returns

Promise<Record<string, unknown>>


adminSetDocument()

function adminSetDocument(
   db: ClientDb,
   path: string,
data: unknown): Promise<void>;

Parameters

ParameterType
dbClientDb
pathstring
dataunknown

Returns

Promise<void>


adminSetRtdbValue()

function adminSetRtdbValue(
   db: ClientDb | ClientRtdb,
   path: string,
   value: unknown,
instance?: string): Promise<void>;

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
valueunknown
instance?string

Returns

Promise<void>


adminSubscribeRtdbValue()

function adminSubscribeRtdbValue(
   db: ClientDb | ClientRtdb,
   path: string,
   next: (value: unknown) => void,
   error?: (err: unknown) => void,
   instance?: string): Unsubscribe;

Subscribe with an explicit admin lens so Studio stays rules-independent.

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
next(value: unknown) => void
error?(err: unknown) => void
instance?string

Returns

Unsubscribe


adminUpdateRtdbValue()

function adminUpdateRtdbValue(
   db: ClientDb | ClientRtdb,
   path: string,
   values: Record<string, unknown>,
instance?: string): Promise<void>;

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
valuesRecord<string, unknown>
instance?string

Returns

Promise<void>


adminUpdateUser()

function adminUpdateUser(
   auth: ClientAuth,
   uid: string,
request: UpdateUserRequest): Promise<AuthUserRecord>;

Parameters

ParameterType
authClientAuth
uidstring
requestUpdateUserRequest

Returns

Promise<AuthUserRecord>


aiCountTokens()

function aiCountTokens(db: ClientDb, params: AiOpParams): Promise<Record<string, unknown>>;

Unary countTokens against the worker’s broker (deterministic).

Parameters

ParameterType
dbClientDb
paramsAiOpParams

Returns

Promise<Record<string, unknown>>


aiGenerateContent()

function aiGenerateContent(db: ClientDb, params: AiOpParams): Promise<Record<string, unknown>>;

Unary generateContent against the worker’s broker. Resolves with the complete WireResponse envelope; rejects with an Error carrying .code (and .aiEnvelope when the broker answered a wire error envelope).

Parameters

ParameterType
dbClientDb
paramsAiOpParams

Returns

Promise<Record<string, unknown>>


aiStreamGenerateContent()

function aiStreamGenerateContent(db: ClientDb, params: AiOpParams): AsyncGenerator<Record<string, unknown>>;

Streamed generateContent over an AI stream SUBSCRIPTION: chunks arrive as { chunk } snaps in order, the terminal { done: true } snap ends the iteration, and a snap __error throws (with .code / .aiEnvelope). The host auto-unsubs on done; the generator additionally sends unsub on teardown so early consumer abandonment cancels the worker-side pump (the done/unsub race is a benign no-op on the host).

Parameters

ParameterType
dbClientDb
paramsAiOpParams

Returns

AsyncGenerator<Record<string, unknown>>


and()

function and(...filters: QueryConstraintHandle[]): QueryConstraintHandle;

AND composite filter — every operand must match. See or.

Parameters

ParameterType
…filtersQueryConstraintHandle[]

Returns

QueryConstraintHandle


arrayRemove()

function arrayRemove(...values: unknown[]): SentinelMarker;

Parameters

ParameterType
…valuesunknown[]

Returns

SentinelMarker


arrayUnion()

function arrayUnion(...values: unknown[]): SentinelMarker;

Parameters

ParameterType
…valuesunknown[]

Returns

SentinelMarker


average()

function average(field: string | FieldPath): AggregateFieldDescriptor;

Factory: average-of-field aggregate. Empty input yields null.

Parameters

ParameterType
fieldstring | FieldPath

Returns

AggregateFieldDescriptor


callTool()

function callTool(
   db: ClientDb,
   name: string,
   args: Record<string, unknown>,
   actAs?: AuthLens,
   clientSessionId?: string): Promise<{
  data?: unknown;
  ok: boolean;
  summary: string;
}>;

Forward an agent tool-call to the worker so it executes against the SAME sandbox the app + Studio use. The worker runs the canonical tool dispatcher (buildSandboxDispatcher) and replies with the { ok, summary, data } result. Used by the bridge peer on the worker path (connectBridgePeer in entries/runtime.ts) so the agent shares the one authoritative sandbox.

Parameters

ParameterTypeDescription
dbClientDb-
namestring-
argsRecord<string, unknown>-
actAs?AuthLensThe bridge caller’s identity, when it has impersonated one. Relayed verbatim.
clientSessionId?stringKeep this MCP caller’s ordering and admission separate from other callers.

Returns

Promise<{ data?: unknown; ok: boolean; summary: string; }>


collection()

function collection(parent:
  | ClientDb
  | DocRefHandle<DocumentData>, ...pathSegments: string[]): CollRefHandle;

Build a collection reference. Mirrors pyric/firestore’s collection(db, path).

Parameters

ParameterType
parent| ClientDb | DocRefHandle<DocumentData>
…pathSegmentsstring[]

Returns

CollRefHandle


collectionGroup()

function collectionGroup(db: ClientDb, collectionId: string): QueryHandle;

Build a collection-group query. Mirrors pyric/firestore’s collectionGroup(db, id).

Parameters

ParameterType
dbClientDb
collectionIdstring

Returns

QueryHandle


connectAuthEmulator()

function connectAuthEmulator(
   _auth: ClientAuth,
   _url: string,
   _options?: {
  disableWarnings?: boolean;
}): void;

Connect to the auth emulator. No-op shim over the worker.

Parameters

ParameterType
_authClientAuth
_urlstring
_options?{ disableWarnings?: boolean; }
_options.disableWarnings?boolean

Returns

void


count()

function count(): AggregateFieldDescriptor;

Factory: count() aggregate field. Mirrors pyric/firestore’s count().

Returns

AggregateFieldDescriptor


createUserWithEmailAndPassword()

function createUserWithEmailAndPassword(
   auth: ClientAuth,
   email: string,
password: string): Promise<ClientUserCredential>;

Parameters

ParameterType
authClientAuth
emailstring
passwordstring

Returns

Promise<ClientUserCredential>


createWorkerReplacement()

function createWorkerReplacement(options: WorkerReplacementOptions): WorkerReplacement;

Coordinate one reload per page after the old SharedWorker announces retirement.

Parameters

ParameterType
optionsWorkerReplacementOptions

Returns

WorkerReplacement


deleteDoc()

function deleteDoc(ref: DocRefHandle): Promise<void>;

Parameters

ParameterType
refDocRefHandle

Returns

Promise<void>


deleteField()

function deleteField(): SentinelMarker;

Returns

SentinelMarker


deleteObject()

function deleteObject(reference: ClientStorageReference): Promise<void>;

Delete the object at the reference’s path (idempotent — missing = no-op, matching the sandbox backend’s delete semantics).

Parameters

ParameterType
referenceClientStorageReference

Returns

Promise<void>


deleteWorkerCheckpoint()

function deleteWorkerCheckpoint(db: ClientDb, name: string): Promise<void>;

Delete one saved state.

Parameters

ParameterType
dbClientDb
namestring

Returns

Promise<void>


disconnectClient()

function disconnectClient(db: ClientDb, options?: DisconnectClientOptions): Promise<void>;

Parameters

ParameterType
dbClientDb
options?DisconnectClientOptions

Returns

Promise<void>


disconnectPort()

function disconnectPort(port: ClientPort): void;

Drop every client-side correlation owned by a closing app port.

Parameters

ParameterType
portClientPort

Returns

void


doc()

function doc(parent:
  | ClientDb
  | CollRefHandle<DocumentData>, ...pathSegments: string[]): DocRefHandle;

Build a document reference. Mirrors pyric/firestore’s doc(db, path).

WHY CLIENT-SIDE: Firebase’s doc() is synchronous and path-only — it needs no data from the sandbox. We build a descriptor object here and include the port so execution calls can route to the worker.

Parameters

ParameterType
parent| ClientDb | CollRefHandle<DocumentData>
…pathSegmentsstring[]

Returns

DocRefHandle


endAt()

function endAt(...values: unknown[]): QueryConstraintHandle;

Parameters

ParameterType
…valuesunknown[]

Returns

QueryConstraintHandle


endBefore()

function endBefore(...values: unknown[]): QueryConstraintHandle;

Parameters

ParameterType
…valuesunknown[]

Returns

QueryConstraintHandle


eventHistory()

function eventHistory(db: ClientDb): Promise<readonly SandboxEvent[]>;

Fetch the worker sandbox’s event history as a one-shot snapshot. Resolves with the first batch a new subscriber receives, then unsubscribes, so it holds no subscription of its own. When the port already has a live stream, the history comes from the page’s copy of it, bounded like the worker’s.

Parameters

ParameterType
dbClientDb

Returns

Promise<readonly SandboxEvent[]>


exportWorkerState()

function exportWorkerState(db: ClientDb): Promise<string>;

Phase 2 (transfer): export the FULL sandbox state as a portable bundle string (the complete checkpoint format, including Storage bytes and metadata). Save it to a file and importWorkerState it into another instance.

Parameters

ParameterType
dbClientDb

Returns

Promise<string>


getActiveRules()

function getActiveRules(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;

Parameters

ParameterType
dbClientDb | ClientRtdb
service?"firestore" | "database"

Returns

Promise<unknown>


getAggregateFromServer()

function getAggregateFromServer<S>(source:
  | CollRefHandle<DocumentData>
  | QueryHandle<DocumentData>, spec: S): Promise<{
  query:   | CollRefHandle<DocumentData>
     | QueryHandle<DocumentData>;
  type: "AggregateQuerySnapshot";
  data: { [K in string | number | symbol]: number };
}>;

Run a multi-field aggregate on the worker. Mirrors pyric/firestore’s getAggregateFromServer(query, spec): spec entries are keyed by caller-chosen aliases; .data() returns the numbers under the same keys (average over no rows is null).

Type Parameters

Type Parameter
S extends AggregateSpecDescriptor

Parameters

ParameterType
source| CollRefHandle<DocumentData> | QueryHandle<DocumentData>
specS

Returns

Promise<{ query: | CollRefHandle<DocumentData> | QueryHandle<DocumentData>; type: "AggregateQuerySnapshot"; data: { [K in string | number | symbol]: number }; }>


getAuth()

function getAuth(source: string | ClientDb | URL, name?: string): ClientAuth;

Get the worker-backed Auth handle.

Parameters

ParameterType
sourcestring | ClientDb | URL
name?string

Returns

ClientAuth


getBlob()

function getBlob(reference: ClientStorageReference, maxDownloadSizeBytes?: number): Promise<Blob>;

Reconstruct binary data locally so reads work over MessagePort and JSON WebSocket.

Parameters

ParameterType
referenceClientStorageReference
maxDownloadSizeBytes?number

Returns

Promise<Blob>


getBytes()

function getBytes(reference: ClientStorageReference, maxDownloadSizeBytes?: number): Promise<ArrayBuffer>;

Read an object’s bytes (JSON-safe base64 op → ArrayBuffer). Mirrors pyric/storage’s getBytes, including the optional client-side cap.

Parameters

ParameterType
referenceClientStorageReference
maxDownloadSizeBytes?number

Returns

Promise<ArrayBuffer>


getCountFromServer()

function getCountFromServer(source:
  | CollRefHandle<DocumentData>
  | QueryHandle<DocumentData>): Promise<{
  query:   | CollRefHandle<DocumentData>
     | QueryHandle<DocumentData>;
  type: "AggregateQuerySnapshot";
  data: {
     count: number;
  };
}>;

Parameters

Returns

Promise<{ query: | CollRefHandle<DocumentData> | QueryHandle<DocumentData>; type: "AggregateQuerySnapshot"; data: { count: number; }; }>


getDoc()

function getDoc<T>(ref: DocRefHandle<T>): Promise<ClientDocSnapshot<T>>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocRefHandle<T>

Returns

Promise<ClientDocSnapshot<T>>


getDocs()

function getDocs(source:
  | CollRefHandle<DocumentData>
| QueryHandle<DocumentData>): Promise<ClientQuerySnapshot>;

Parameters

Returns

Promise<ClientQuerySnapshot>


getDownloadURL()

function getDownloadURL(reference: ClientStorageReference): Promise<string>;

Return a data:<contentType>;base64,<payload> URI for an object read through the SharedWorker. Same shape the in-process pyric/storage getDownloadURL returns, so a URL produced in worker mode resolves in every context the page hands it to rather than only inside the page that made it.

Parameters

ParameterType
referenceClientStorageReference

Returns

Promise<string>


getFirestore()

function getFirestore(
   workerUrl: string | URL,
   name?: string,
   options?: SharedWorkerConnectionOptions): ClientDb;

Parameters

ParameterType
workerUrlstring | URL
name?string
options?SharedWorkerConnectionOptions

Returns

ClientDb


getHostedFirestore()

function getHostedFirestore(target: {
  currentHostInstanceId?: () => Promise<string>;
  currentUrl?: () => Promise<string>;
  initialHostInstanceId?: string;
  onConnection?: (state: HostedConnectionState) => void;
  onError?: (error: FirebaseError) => void;
  onHostRestarted?: (restart: HostRestart) => void;
  platform?: "studio";
  projectKey: string;
  realm?: HostedSocketRealm;
  retryInitialConnection?: boolean;
  sessionToken?: () => Promise<string>;
  url: string;
}, existingPort?: ClientPort): ClientDb;

Own one app’s physical connections while retaining its logical SDK port.

Parameters

ParameterTypeDescription
target{ currentHostInstanceId?: () => Promise<string>; currentUrl?: () => Promise<string>; initialHostInstanceId?: string; onConnection?: (state: HostedConnectionState) => void; onError?: (error: FirebaseError) => void; onHostRestarted?: (restart: HostRestart) => void; platform?: "studio"; projectKey: string; realm?: HostedSocketRealm; retryInitialConnection?: boolean; sessionToken?: () => Promise<string>; url: string; }-
target.currentHostInstanceId?() => Promise<string>Reads the boot id of the host now serving the url, before a reattach. A Node process passes it: it reads init.json again, so after a host restart it presents the new boot and the host holds its config as verified. A page passes nothing and presents the boot it was served by (#1153).
target.currentUrl?() => Promise<string>Resolves the socket url again before a reattach. A Node process passes it: a host that stopped may come back on another port, which its .pyric/serve.json names. A page passes nothing and redials its own origin.
target.initialHostInstanceId?stringHost boot identity baked into the served HTML / module at compile time.
target.onConnection?(state: HostedConnectionState) => void-
target.onError?(error: FirebaseError) => void-
target.onHostRestarted?(restart: HostRestart) => voidCalled once, in a page only, when attach-ack names a later host boot than initialHostInstanceId.
target.platform?"studio"Identifies Studio’s own UI tab so the host never lists it as an app client or routes tab reads to it.
target.projectKey?string-
target.realm?HostedSocketRealmPresent outside a page; see HostedSocketRealm.
target.retryInitialConnection?boolean-
target.sessionToken?() => Promise<string>The page’s session token, which authorizes its own reads on the host’s byte route.
target.url?string-
existingPort?ClientPort-

Returns

ClientDb


getIdToken()

function getIdToken(user: ClientUser, forceRefresh?: boolean): Promise<string>;

Parameters

ParameterType
userClientUser
forceRefresh?boolean

Returns

Promise<string>


getIdTokenResult()

function getIdTokenResult(user: ClientUser, forceRefresh?: boolean): Promise<SerializedIdTokenResult>;

Parameters

ParameterType
userClientUser
forceRefresh?boolean

Returns

Promise<SerializedIdTokenResult>


getLens()

function getLens(): AuthLens;

The active default lens (read-only view), for Studio UI to reflect state.

Returns

AuthLens


getMetadata()

function getMetadata(reference: ClientStorageReference): Promise<FullMetadata>;

Read an object’s metadata (Pyric Studio inspector).

Parameters

ParameterType
referenceClientStorageReference

Returns

Promise<FullMetadata>


getProviderConfig()

function getProviderConfig(auth: ClientAuth): Promise<{
  enabled: boolean;
  providerId: string;
}[]>;

Parameters

ParameterType
authClientAuth

Returns

Promise<{ enabled: boolean; providerId: string; }[]>


getRulesStatus()

function getRulesStatus(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;

Parameters

ParameterType
dbClientDb | ClientRtdb
service?"firestore" | "database"

Returns

Promise<unknown>


getSnapshot()

function getSnapshot(db: ClientDb): Promise<SandboxSnapshot>;

Export the current sandbox snapshot (Pyric Studio rules re-run). Studio forks it locally to test a denied op against edited rules or re-issue it as the attempting user, on a throwaway branch (no live mutation).

Parameters

ParameterType
dbClientDb

Returns

Promise<SandboxSnapshot>


getStorage()

function getStorage(
   source: string | ClientDb | URL,
   name?: string,
   bucketUrl?: string,
   namedBucket?: boolean): ClientFirebaseStorage;

Get the worker-backed Storage handle. Like getAuth, accepts an existing ClientDb (reusing its port) or a worker URL (standalone).

Parameters

ParameterType
sourcestring | ClientDb | URL
name?string
bucketUrl?string
namedBucket?boolean

Returns

ClientFirebaseStorage


getWorkerInstanceId()

function getWorkerInstanceId(db: ClientDb): Promise<string>;

Ask the worker for its stable per-instance id (see host INSTANCE_ID_KEY). Studio renders a human-friendly form so a user can tell which sandbox instance they’re looking at — the same localhost:<port> in a different browser profile is a SEPARATE sandbox (a separate SharedWorker + IndexedDB), and this is how the two are told apart.

Parameters

ParameterType
dbClientDb

Returns

Promise<string>


getWorkerVersion()

function getWorkerVersion(db: ClientDb, options?: {
  timeoutMs?: number;
}): Promise<string>;

Ask the worker for its baked build version (staleness guard). The page compares it to the served bundle version and warns when a still-running OLD worker is older than what’s served (a SharedWorker can’t hot-update).

Parameters

ParameterType
dbClientDb
options?{ timeoutMs?: number; }
options.timeoutMs?number

Returns

Promise<string>


hydrateLensFromStorage()

function hydrateLensFromStorage(): AuthLens;

Read persisted auth lens from sessionStorage safely.

Returns

AuthLens


importWorkerState()

function importWorkerState(db: ClientDb, bundle: string): Promise<void>;

Phase 2 (clobber): replace this sandbox’s ENTIRE state with bundle.

Parameters

ParameterType
dbClientDb
bundlestring

Returns

Promise<void>


increment()

function increment(n: number): SentinelMarker;

Parameters

ParameterType
nnumber

Returns

SentinelMarker


limit()

function limit(n: number): QueryConstraintHandle;

Parameters

ParameterType
nnumber

Returns

QueryConstraintHandle


limitToLast()

function limitToLast(n: number): QueryConstraintHandle;

Parameters

ParameterType
nnumber

Returns

QueryConstraintHandle


listAll()

function listAll(reference: ClientStorageReference): Promise<{
  items: ClientStorageReference[];
  prefixes: ClientStorageReference[];
}>;

Enumerate immediate child items + sub-prefixes under a ref (Pyric Studio data browse). The host enforces read rules on the scanned prefix.

Parameters

ParameterType
referenceClientStorageReference

Returns

Promise<{ items: ClientStorageReference[]; prefixes: ClientStorageReference[]; }>


listRootCollections()

function listRootCollections(db: ClientDb): Promise<string[]>;

Enumerate root collection ids (Pyric Studio data browse). The modular SDK has no client listCollections, so the host scans the sandbox keyspace and returns the ids. Lens is attached (via dataRpc) but the host enumeration is lens-independent.

Parameters

ParameterType
dbClientDb

Returns

Promise<string[]>


listSubcollections()

function listSubcollections(db: ClientDb, docPath: string): Promise<string[]>;

Enumerate subcollection ids under a document path (Pyric Studio data browse).

Parameters

ParameterType
dbClientDb
docPathstring

Returns

Promise<string[]>


listUsers()

function listUsers(auth: ClientAuth): Promise<AuthUserRecord[]>;

Parameters

ParameterType
authClientAuth

Returns

Promise<AuthUserRecord[]>


listWorkerCheckpoints()

function listWorkerCheckpoints(db: ClientDb): Promise<WorkerCheckpoint[]>;

This instance’s saved states, ordered by name.

Parameters

ParameterType
dbClientDb

Returns

Promise<WorkerCheckpoint[]>


mintPresenceClientId()

function mintPresenceClientId(): string;

Mint a random client id (page-lifetime).

Returns

string


onAuthStateChanged()

function onAuthStateChanged(auth: ClientAuth, callback: ClientAuthObserver): Unsubscribe;

Parameters

ParameterType
authClientAuth
callbackClientAuthObserver

Returns

Unsubscribe


onIdTokenChanged()

function onIdTokenChanged(auth: ClientAuth, callback: ClientAuthObserver): Unsubscribe;

Parameters

ParameterType
authClientAuth
callbackClientAuthObserver

Returns

Unsubscribe


onSnapshot()

Call Signature

function onSnapshot(
   target:
  | DocRefHandle<DocumentData>
  | CollRefHandle<DocumentData>
  | QueryHandle<DocumentData>,
   observerOrNext: ObserverOrNext,
   errorCallback?: SnapshotErrorCallback): Unsubscribe;

Subscribe to a document or query. Mirrors pyric/firestore’s onSnapshot in all four call forms, with a callback or an observer, with or without options first: @pyric/ui’s hooks pass { owner } there for listener attribution, and a caller injecting this client as the hooks’ backend must not lose its callback to that slot. The owners are derived here, on the page whose stack and DOM they describe, and travel with the subscribe message.

Returns an unsub function. Sends { t:'unsub', subId } to the worker to deregister the listener on the worker side.

Parameters
ParameterType
target| DocRefHandle<DocumentData> | CollRefHandle<DocumentData> | QueryHandle<DocumentData>
observerOrNextObserverOrNext
errorCallback?SnapshotErrorCallback
Returns

Unsubscribe

Call Signature

function onSnapshot(
   target:
  | DocRefHandle<DocumentData>
  | CollRefHandle<DocumentData>
  | QueryHandle<DocumentData>,
   options: object,
   observerOrNext: ObserverOrNext,
   errorCallback?: SnapshotErrorCallback): Unsubscribe;

Subscribe to a document or query. Mirrors pyric/firestore’s onSnapshot in all four call forms, with a callback or an observer, with or without options first: @pyric/ui’s hooks pass { owner } there for listener attribution, and a caller injecting this client as the hooks’ backend must not lose its callback to that slot. The owners are derived here, on the page whose stack and DOM they describe, and travel with the subscribe message.

Returns an unsub function. Sends { t:'unsub', subId } to the worker to deregister the listener on the worker side.

Parameters
ParameterType
target| DocRefHandle<DocumentData> | CollRefHandle<DocumentData> | QueryHandle<DocumentData>
optionsobject
observerOrNextObserverOrNext
errorCallback?SnapshotErrorCallback
Returns

Unsubscribe


onWorkerRuntimeReload()

function onWorkerRuntimeReload(listener: (epoch: string) => void): () => void;

Observe the worker’s all-pages reload signal.

Parameters

ParameterType
listener(epoch: string) => void

Returns

(): void;
Returns

void


or()

function or(...filters: QueryConstraintHandle[]): QueryConstraintHandle;

OR composite filter — at least one operand must match. Operands must be filters (where(), or nested or()/and()). Mirrors pyric/firestore’s or(...); the worker rebuilds it with the real modular factory.

Parameters

ParameterType
…filtersQueryConstraintHandle[]

Returns

QueryConstraintHandle


orderBy()

function orderBy(field: string | FieldPath, direction?: "asc" | "desc"): QueryConstraintHandle;

Parameters

ParameterType
fieldstring | FieldPath
direction?"asc" | "desc"

Returns

QueryConstraintHandle


ownClientUntilPagehide()

function ownClientUntilPagehide(
   client: ClientDb,
   events?: PagehideEvents,
   disconnectClientImpl?: Disconnect): {
  disconnect: Promise<void>;
  dispose: void;
};

Own a worker port until its page permanently leaves.

Parameters

ParameterType
clientClientDb
events?PagehideEvents
disconnectClientImpl?Disconnect

Returns

{
  disconnect: Promise<void>;
  dispose: void;
}
disconnect()
disconnect(): Promise<void>;
Returns

Promise<void>

dispose()
dispose(): void;
Returns

void


preflightWorkerEpochStorage()

function preflightWorkerEpochStorage(storage: EpochStorage): void;

Prove origin storage works without publishing a successor generation.

Parameters

ParameterType
storageEpochStorage

Returns

void


query()

function query(source:
  | CollRefHandle<DocumentData>
  | QueryHandle<DocumentData>, ...constraints: QueryConstraintHandle[]): QueryHandle;

Apply query constraints to a source ref or query. Mirrors pyric/firestore’s query(source, ...constraints).

Parameters

ParameterType
source| CollRefHandle<DocumentData> | QueryHandle<DocumentData>
…constraintsQueryConstraintHandle[]

Returns

QueryHandle


readHostedTarget()

function readHostedTarget(): {
  projectKey: string;
  url: string;
};

Hosted selection is stamped before Studio starts; absence retains SharedWorker.

Returns

{
  projectKey: string;
  url: string;
}
projectKey
projectKey: string;
url
url: string;

readPyricRuntimeManifest()

function readPyricRuntimeManifest(documentLike?: RuntimeDocument, locationLike?: RuntimeLocation): PyricRuntimeManifest;

Read the server-stamped worker epoch before application code starts.

Parameters

ParameterType
documentLike?RuntimeDocument
locationLike?RuntimeLocation

Returns

PyricRuntimeManifest


ref()

function ref(parent:
  | ClientFirebaseStorage
  | ClientStorageReference, path?: string): ClientStorageReference;

Build a Storage reference. Mirrors pyric/storage’s ref(storage, path?) / ref(parentRef, path), including ref(storage, url). Client-side path math; no RPC.

Parameters

ParameterType
parent| ClientFirebaseStorage | ClientStorageReference
path?string

Returns

ClientStorageReference


relayWorkerOp()

function relayWorkerOp(
   db: ClientDb,
   op: WorkerOpPayload,
clientSessionId?: string): Promise<unknown>;

Relay one raw worker-protocol op into the SharedWorker. op is the op message minus t/id (the WorkerOpPayload wire shape); resolves with the worker’s res.value, rejects with an Error carrying .code.

Parameters

ParameterType
dbClientDb
opWorkerOpPayload
clientSessionId?string

Returns

Promise<unknown>


relayWorkerSub()

function relayWorkerSub(
   db: ClientDb,
   sub: WorkerSubPayload,
   onValue: (value: unknown) => void,
   clientSessionId?: string): () => void;

Relay a raw worker-protocol subscription into the SharedWorker. sub is the sub message minus t/subId (the WorkerSubPayload wire shape). onValue receives every snap value VERBATIM — including the worker host’s { __error: { code, message } } establishment-failure convention (listener errors are re-wrapped into the same shape so the far side sees one form). Returns the unsubscribe function.

The unified event stream (target: 'events') is NOT relayable yet — its history batches aren’t coalescible, so it needs bounded backpressure first (slice 2).

Parameters

ParameterType
dbClientDb
subWorkerSubPayload
onValue(value: unknown) => void
clientSessionId?string

Returns

(): void;
Returns

void


rememberWorkerEpoch()

function rememberWorkerEpoch(epoch: string, storage: EpochStorage): void;

Persist the generation boundary before a page reloads.

Parameters

ParameterType
epochstring
storageEpochStorage

Returns

void


resetAll()

function resetAll(db: ClientDb): Promise<{
  errors: string[];
}>;

Sandbox-owned full reset (issue #359): sandbox.resetAll() on the worker. Clears the Firestore env, the signed-in session, and EVERY registered persistable service — auth users, the RTDB tree, storage objects. Resolves once the worker acks (all services finished clearing). This is the served counterpart of calling sandbox.resetAll() on an in-process sandbox.

Parameters

ParameterType
dbClientDb

Returns

Promise<{ errors: string[]; }>


restoreWorkerCheckpoint()

function restoreWorkerCheckpoint(db: ClientDb, name: string): Promise<void>;

Clobber: replace the whole sandbox with a named saved state.

Parameters

ParameterType
dbClientDb
namestring

Returns

Promise<void>


retireWorkerRuntime()

function retireWorkerRuntime(
   db: ClientDb,
   targetEpoch: string,
   options?: {
  timeoutMs?: number;
}): Promise<void>;

Ask the current SharedWorker to drain accepted work and retire.

Parameters

ParameterType
dbClientDb
targetEpochstring
options?{ timeoutMs?: number; }
options.timeoutMs?number

Returns

Promise<void>


rtdbChild()

function rtdbChild(parent: RtdbRefHandle, path: string): RtdbRefHandle;

Parameters

ParameterType
parentRtdbRefHandle
pathstring

Returns

RtdbRefHandle


rtdbConnectDatabaseEmulator()

function rtdbConnectDatabaseEmulator(): void;

Returns

void


rtdbGet()

function rtdbGet(target: RtdbTarget): Promise<RtdbDataSnapshot>;

Parameters

ParameterType
targetRtdbTarget

Returns

Promise<RtdbDataSnapshot>


rtdbGetDatabase()

function rtdbGetDatabase(source?: string | ClientDb | URL, name?: string): ClientRtdb;

Parameters

ParameterType
source?string | ClientDb | URL
name?string

Returns

ClientRtdb


rtdbGoOffline()

function rtdbGoOffline(db: ClientRtdb): void;

Parameters

ParameterType
dbClientRtdb

Returns

void


rtdbGoOnline()

function rtdbGoOnline(db: ClientRtdb): void;

Parameters

ParameterType
dbClientRtdb

Returns

void


rtdbOff()

function rtdbOff(
   target: RtdbTarget,
   eventType?: RtdbEventType,
   callback?: object): void;

Parameters

ParameterType
targetRtdbTarget
eventType?RtdbEventType
callback?object

Returns

void


rtdbOnChildAdded()

function rtdbOnChildAdded(
   target: RtdbTarget,
   next: ChildCallback,
   cancel?: CancelOrOptions,
   options?: ListenOptions,
   identity?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
nextChildCallback
cancel?CancelOrOptions
options?ListenOptions
identity?object

Returns

Unsubscribe


rtdbOnChildChanged()

function rtdbOnChildChanged(
   target: RtdbTarget,
   next: ChildCallback,
   cancel?: CancelOrOptions,
   options?: ListenOptions,
   identity?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
nextChildCallback
cancel?CancelOrOptions
options?ListenOptions
identity?object

Returns

Unsubscribe


rtdbOnChildMoved()

function rtdbOnChildMoved(
   target: RtdbTarget,
   next: ChildCallback,
   cancel?: CancelOrOptions,
   options?: ListenOptions,
   identity?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
nextChildCallback
cancel?CancelOrOptions
options?ListenOptions
identity?object

Returns

Unsubscribe


rtdbOnChildRemoved()

function rtdbOnChildRemoved(
   target: RtdbTarget,
   next: ChildCallback,
   cancel?: CancelOrOptions,
   options?: ListenOptions,
   identity?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
nextChildCallback
cancel?CancelOrOptions
options?ListenOptions
identity?object

Returns

Unsubscribe


rtdbOnDisconnect()

function rtdbOnDisconnect(ref: RtdbRefHandle): RtdbOnDisconnect;

Parameters

ParameterType
refRtdbRefHandle

Returns

RtdbOnDisconnect


rtdbOnValue()

function rtdbOnValue(
   target: RtdbTarget,
   next: (snap: RtdbDataSnapshot) => void,
   cancelCallbackOrOptions?: (err: unknown) => void | ValueListenOptions,
   options?: ValueListenOptions,
   registryCallback?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
next(snap: RtdbDataSnapshot) => void
cancelCallbackOrOptions?(err: unknown) => void | ValueListenOptions
options?ValueListenOptions
registryCallback?object

Returns

Unsubscribe


rtdbPush()

function rtdbPush(ref: RtdbRefHandle, value?: unknown): RtdbRefHandle & PromiseLike<RtdbRefHandle>;

Parameters

ParameterType
refRtdbRefHandle
value?unknown

Returns

RtdbRefHandle & PromiseLike<RtdbRefHandle>


rtdbRef()

function rtdbRef(db: ClientRtdb, path?: string): RtdbRefHandle;

Parameters

ParameterType
dbClientRtdb
path?string

Returns

RtdbRefHandle


rtdbRemove()

function rtdbRemove(ref: RtdbRefHandle): Promise<void>;

Parameters

ParameterType
refRtdbRefHandle

Returns

Promise<void>


rtdbRunTransaction()

function rtdbRunTransaction<T>(
   ref: RtdbRefHandle,
   transactionUpdate: (current: T) => T,
options?: RtdbTransactionOptions): Promise<RtdbTransactionResult>;

Type Parameters

Type Parameter
T

Parameters

ParameterType
refRtdbRefHandle
transactionUpdate(current: T) => T
options?RtdbTransactionOptions

Returns

Promise<RtdbTransactionResult>


rtdbServerTimestamp()

function rtdbServerTimestamp(): {
};

RTDB environment controls and server-value construction for served apps.

Returns

{
}

rtdbSet()

function rtdbSet(ref: RtdbRefHandle, value: unknown): Promise<void>;

Parameters

ParameterType
refRtdbRefHandle
valueunknown

Returns

Promise<void>


rtdbSetPriority()

function rtdbSetPriority(ref: RtdbRefHandle, priority: string | number): Promise<void>;

Parameters

ParameterType
refRtdbRefHandle
prioritystring | number

Returns

Promise<void>


rtdbSetWithPriority()

function rtdbSetWithPriority(
   ref: RtdbRefHandle,
   value: unknown,
priority: string | number): Promise<void>;

Parameters

ParameterType
refRtdbRefHandle
valueunknown
prioritystring | number

Returns

Promise<void>


rtdbUpdate()

function rtdbUpdate(ref: RtdbRefHandle, values: Record<string, unknown>): Promise<void>;

Parameters

ParameterType
refRtdbRefHandle
valuesRecord<string, unknown>

Returns

Promise<void>


runTransaction()

function runTransaction<R>(
   db: ClientDb,
   updateFn: (txn: ClientTransaction) => R | Promise<R>,
   options?: {
  maxAttempts?: number;
}): Promise<R>;

Run a transaction. Mirrors pyric/firestore’s runTransaction(db, fn).

MULTI-TAB CORRECTNESS — READ-SET VALIDATION + RETRY

A transaction spans two messages: the txn.get RPC (read) and the txnCommit RPC (commit). Between those two messages another tab may write to a doc the current tab read — a silent lost update without validation. We fix this the standard way:

  1. Each txn.get(ref) records { path, data } in a per-attempt read-set (data is the raw SerializedDocData the worker returned, or null if the doc was missing).
  2. txnCommit carries both reads (the read-set) and writes.
  3. The worker re-reads each doc inside a sandbox transaction, re- serializes it the same way, and compares the JSON strings. Any mismatch → { ok: false, error: { code: 'aborted' } }.
  4. On aborted, the client discards the result of updateFn and re-runs it with a fresh transaction object (fresh reads, empty write buffer). Up to TXN_MAX_ATTEMPTS attempts are made.
  5. After the cap, throws an error with .code === 'aborted'.

This matches real Firestore’s behaviour: the SDK retries updateFn on conflict rather than surfacing the error immediately.

Type Parameters

Type Parameter
R

Parameters

ParameterType
dbClientDb
updateFn(txn: ClientTransaction) => R | Promise<R>
options?{ maxAttempts?: number; }
options.maxAttempts?number

Returns

Promise<R>


saveWorkerCheckpoint()

function saveWorkerCheckpoint(db: ClientDb, name: string): Promise<void>;

Save the whole sandbox under a name, replacing whatever that name held.

Parameters

ParameterType
dbClientDb
namestring

Returns

Promise<void>


serverTimestamp()

function serverTimestamp(): SentinelMarker;

Returns

SentinelMarker


setDatabaseRules()

function setDatabaseRules(db: ClientDb | ClientRtdb, source: unknown): Promise<{
  messages: unknown[];
  ok: boolean;
}>;

Parameters

ParameterType
dbClientDb | ClientRtdb
sourceunknown

Returns

Promise<{ messages: unknown[]; ok: boolean; }>


setDoc()

function setDoc<T>(
   ref: DocRefHandle<T>,
   data: T,
options?: ClientSetOptions): Promise<void>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocRefHandle<T>
dataT
options?ClientSetOptions

Returns

Promise<void>


setFirestoreRules()

function setFirestoreRules(db: ClientDb, source: string): Promise<{
  messages: unknown[];
  ok: boolean;
  warnings: unknown[];
}>;

Parameters

ParameterType
dbClientDb
sourcestring

Returns

Promise<{ messages: unknown[]; ok: boolean; warnings: unknown[]; }>


setLens()

function setLens(lens: AuthLens): void;

Set the default auth lens applied to subsequent Firestore DATA ops from this client (Pyric Studio & Runtime Chip). Pass { mode: 'as', uid } to read/write AS a user (rules apply), { mode: 'admin' } for the admin lens, or { mode: 'app-session' } / undefined to revert to the app’s own session.

The lens is process-wide for this client module (one served page = one worker port), mirroring how Studio drives a single active identity at a time. Auth ops are unaffected — they always operate the real session.

Persists active admin and impersonation lenses to sessionStorage under AUTH_LENS_STORAGE_KEY, and removes the key when cleared or reverted to the app session. Notifies all registered subscribeLens listeners.

Parameters

ParameterType
lensAuthLens

Returns

void


setOpIssuer()

function setOpIssuer(source: "studio"): void;

Declare who issues the ops this client module constructs. See _opIssuer.

Parameters

ParameterType
source"studio"

Returns

void


setPersistence()

function setPersistence(auth: ClientAuth, persistence: ClientPersistence): Promise<void>;

Parameters

ParameterType
authClientAuth
persistenceClientPersistence

Returns

Promise<void>


setProviderConfig()

function setProviderConfig(
   auth: ClientAuth,
   providerId: string,
enabled: boolean): Promise<void>;

Parameters

ParameterType
authClientAuth
providerIdstring
enabledboolean

Returns

Promise<void>


setRules()

function setRules(db: ClientDb, source: string): Promise<{
  warnings: unknown[];
}>;

Deploy new rules to the worker’s sandbox. Active onSnapshot listeners that were allowed by the old rules may start receiving error callbacks if the new rules deny them.

Parameters

ParameterType
dbClientDb
sourcestring

Returns

Promise<{ warnings: unknown[]; }>


signInAnonymously()

function signInAnonymously(auth: ClientAuth): Promise<ClientUserCredential>;

Parameters

ParameterType
authClientAuth

Returns

Promise<ClientUserCredential>


signInWithEmailAndPassword()

function signInWithEmailAndPassword(
   auth: ClientAuth,
   email: string,
password: string): Promise<ClientUserCredential>;

Parameters

ParameterType
authClientAuth
emailstring
passwordstring

Returns

Promise<ClientUserCredential>


signOut()

function signOut(auth: ClientAuth): Promise<void>;

Parameters

ParameterType
authClientAuth

Returns

Promise<void>


startAfter()

function startAfter(...values: unknown[]): QueryConstraintHandle;

Parameters

ParameterType
…valuesunknown[]

Returns

QueryConstraintHandle


startAt()

function startAt(...values: unknown[]): QueryConstraintHandle;

Parameters

ParameterType
…valuesunknown[]

Returns

QueryConstraintHandle


startPresence()

function startPresence(opts: StartPresenceOptions): PresenceSession;

Register this page with the worker and keep the lease alive until PresenceSession.stop or pagehide.

Parameters

ParameterType
optsStartPresenceOptions

Returns

PresenceSession


subscribeEvents()

function subscribeEvents(
   db: ClientDb,
   callback: EventBatchCallback,
   onError?: (error: Error & {
  code: string;
}) => void): Unsubscribe;

Subscribe to the worker sandbox’s unified event stream. The callback fires with each delivered BATCH of events: the FIRST call carries the history (possibly empty), each later call carries one live event. After the host restores the subscription (a reconnect or a replacement host), the next batch is its whole history again, marked { history: true }. Every subscriber on a port shares one subscription on the worker; a subscriber that joins after the worker’s history batch receives the page’s copy of it, bounded like the worker’s history. Returns an unsubscribe; the worker subscription closes when the port’s last subscriber leaves.

This is the live counterpart to sandbox.onEvent + an initial history() fold, collapsed into one subscription so a late subscriber never misses the backlog.

Parameters

ParameterType
dbClientDb
callbackEventBatchCallback
onError?(error: Error & { code: string; }) => void

Returns

Unsubscribe


subscribeLens()

function subscribeLens(listener: (lens: AuthLens) => void): () => void;

Register a listener for auth lens mutations. Returns an unsubscribe function that removes the listener.

Parameters

ParameterType
listener(lens: AuthLens) => void

Returns

(): void;
Returns

void


subscribePresence()

function subscribePresence(db: ClientDb, callback: (snapshot: PresenceSnapshot) => void): Unsubscribe;

Subscribe to the worker’s authoritative presence snapshot. The callback fires immediately with the current snapshot, then on every change.

Parameters

ParameterType
dbClientDb
callback(snapshot: PresenceSnapshot) => void

Returns

Unsubscribe


sum()

function sum(field: string | FieldPath): AggregateFieldDescriptor;

Factory: sum-of-field aggregate. Mirrors pyric/firestore’s sum().

Parameters

ParameterType
fieldstring | FieldPath

Returns

AggregateFieldDescriptor


takeAuthMail()

function takeAuthMail(auth: ClientAuth, email?: string): Promise<OutboundAuthMail>;

Consume the shared sandbox’s in-memory mailbox. Any attached page can take mail.

Parameters

ParameterType
authClientAuth
email?string

Returns

Promise<OutboundAuthMail>


updateDoc()

Call Signature

function updateDoc(ref: DocRefHandle, data: Record<string, unknown>): Promise<void>;
Parameters
ParameterType
refDocRefHandle
dataRecord<string, unknown>
Returns

Promise<void>

Call Signature

function updateDoc(
   ref: DocRefHandle,
   field: string | FieldPath,
   value: unknown, ...
moreFieldsAndValues: unknown[]): Promise<void>;
Parameters
ParameterType
refDocRefHandle
fieldstring | FieldPath
valueunknown
…moreFieldsAndValuesunknown[]
Returns

Promise<void>


uploadBytes()

function uploadBytes(
   reference: ClientStorageReference,
   data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
   metadata?: ClientSettableMetadata): Promise<{
  metadata: FullMetadata;
  ref: ClientStorageReference;
}>;

Upload bytes at the reference’s path (replaces existing content). Mirrors pyric/storage’s uploadBytes result shape.

Parameters

ParameterType
referenceClientStorageReference
dataArrayBuffer | Uint8Array<ArrayBufferLike> | Blob
metadata?ClientSettableMetadata

Returns

Promise<{ metadata: FullMetadata; ref: ClientStorageReference; }>


uploadBytesResumable()

function uploadBytesResumable(
   reference: ClientStorageReference,
   data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
   metadata?: ClientSettableMetadata): ClientUploadTask;

Parameters

ParameterType
referenceClientStorageReference
dataArrayBuffer | Uint8Array<ArrayBufferLike> | Blob
metadata?ClientSettableMetadata

Returns

ClientUploadTask


uploadString()

function uploadString(
   reference: ClientStorageReference,
   value: string,
   format?: StringFormat,
   metadata?: ClientSettableMetadata): Promise<{
  metadata: FullMetadata;
  ref: ClientStorageReference;
}>;

Upload string payload at the reference’s path. Mirrors pyric/storage’s uploadString result shape.

Parameters

ParameterType
referenceClientStorageReference
valuestring
format?StringFormat
metadata?ClientSettableMetadata

Returns

Promise<{ metadata: FullMetadata; ref: ClientStorageReference; }>


where()

function where(
   field: string | FieldPath,
   op: string,
   value: unknown): QueryConstraintHandle;

Parameters

ParameterType
fieldstring | FieldPath
opstring
valueunknown

Returns

QueryConstraintHandle


wirePort()

function wirePort(port: ClientPort): void;

Wire up the port’s onmessage handler (idempotent per-port).

Parameters

ParameterType
portClientPort

Returns

void


workerNameForEpoch()

function workerNameForEpoch(servedEpoch: string, storage: EpochStorage): string;

Select the origin’s active worker generation.

A browser that predates generation-aware workers has no stored epoch but may still have the legacy pyric-shared-worker alive. Seed the first served epoch before connecting so a new client never attaches to that incompatible worker. Later releases keep using the stored generation until replacement is explicitly committed.

Parameters

ParameterType
servedEpochstring
storageEpochStorage

Returns

string


writeBatch()

function writeBatch(db: ClientDb): ClientWriteBatch;

Parameters

ParameterType
dbClientDb

Returns

ClientWriteBatch