Classes
RtdbOnDisconnect
Constructors
Constructor
new RtdbOnDisconnect(_repo: RtdbRefHandle, _path?: string): RtdbOnDisconnect;
Parameters
| Parameter | Type |
|---|---|
_repo | RtdbRefHandle |
_path? | string |
Returns
Methods
cancel()
cancel(): Promise<void>;
Returns
Promise<void>
remove()
remove(): Promise<void>;
Returns
Promise<void>
set()
set(value: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
Returns
Promise<void>
setWithPriority()
setWithPriority(value: unknown, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
priority | string | number |
Returns
Promise<void>
update()
update(values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
values | Record<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
| Property | Modifier | Type | Description |
|---|---|---|---|
currentUser | public | ClientUser | Local mirror of the worker’s currentUser, updated from the stream. |
port | readonly | ClientPort | - |
tenantId | public | string | Identity 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
ClientDocSnapshot
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
id | readonly | string | - |
metadata | readonly | SnapshotMetadata | - |
path | readonly | string | - |
ref | readonly | DocRefHandle<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
| Parameter | Type |
|---|---|
fieldPath | SnapshotFieldPath |
Returns
unknown
ClientFirebaseStorage
Worker-backed Storage handle (carries the shared MessagePort).
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
bucket | readonly | string | - |
namedBucket? | readonly | boolean | True for a handle getStorage opened on a bucket by name, rather than the app’s default bucket. |
port | readonly | ClientPort | - |
ClientQuerySnapshot
Properties
| Property | Modifier | Type |
|---|---|---|
docs | readonly | ClientDocSnapshot<DocumentData>[] |
empty | readonly | boolean |
metadata | readonly | SnapshotMetadata |
size | readonly | number |
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
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
callback | (doc: ClientDocSnapshot) => void |
thisArg? | unknown |
Returns
void
ClientRtdb
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
instance? | readonly | ClientRtdbInstance | Absent for a handle that names no URL, such as Studio’s; it reads and writes the default instance. |
port | readonly | ClientPort | - |
ClientSettableMetadata
Mirror of pyric/storage’s SettableMetadata (plain JSON on the wire).
Properties
| Property | Type |
|---|---|
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
| Property | Modifier | Type |
|---|---|---|
bucket | readonly | string |
fullPath | readonly | string |
name | readonly | string |
parent | readonly | ClientStorageReference |
port | readonly | ClientPort |
root | readonly | ClientStorageReference |
storage? | readonly | ClientFirebaseStorage |
Methods
toString()
toString(): string;
Returns
string
ClientTransaction
Client-side transaction handle.
Methods
delete()
delete(ref: DocRefHandle): ClientTransaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
get()
get<T>(ref: DocRefHandle<T>): Promise<ClientDocSnapshot<T>>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle<T> |
Returns
Promise<ClientDocSnapshot<T>>
set()
set<T>(
ref: DocRefHandle<T>,
data: T,
options?: ClientSetOptions): ClientTransaction;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle<T> |
data | T |
options? | ClientSetOptions |
Returns
update()
Call Signature
update(ref: DocRefHandle, data: Record<string, unknown>): ClientTransaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
Call Signature
update(
ref: DocRefHandle,
field: string | FieldPath,
value: unknown, ...
moreFieldsAndValues: unknown[]): ClientTransaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
field | string | FieldPath |
value | unknown |
…moreFieldsAndValues | unknown[] |
Returns
ClientUploadTask
Extends
Promise<ClientUploadTaskSnapshot>
Properties
| Property | Modifier | Type |
|---|---|---|
snapshot | readonly | ClientUploadTaskSnapshot |
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
| Parameter | Type |
|---|---|
event | string |
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
| Property | Modifier | Type |
|---|---|---|
bytesTransferred | readonly | number |
metadata | readonly | FullMetadata |
ref | readonly | ClientStorageReference |
state | readonly | ClientTaskState |
task | readonly | ClientUploadTask |
totalBytes | readonly | number |
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
Methods
getIdToken()
getIdToken(forceRefresh?: boolean): Promise<string>;
Parameters
| Parameter | Type |
|---|---|
forceRefresh? | boolean |
Returns
Promise<string>
getIdTokenResult()
getIdTokenResult(forceRefresh?: boolean): Promise<SerializedIdTokenResult>;
Parameters
| Parameter | Type |
|---|---|
forceRefresh? | boolean |
Returns
Promise<SerializedIdTokenResult>
ClientUserCredential
Client-side UserCredential — mirrors firebase/auth.
Properties
| Property | Type |
|---|---|
operationType | "link" | "signIn" | "reauthenticate" |
providerId | string |
user | ClientUser |
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
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
set()
set<T>(
ref: DocRefHandle<T>,
data: T,
options?: ClientSetOptions): ClientWriteBatch;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle<T> |
data | T |
options? | ClientSetOptions |
Returns
update()
Call Signature
update(ref: DocRefHandle, data: Record<string, unknown>): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
Call Signature
update(
ref: DocRefHandle,
field: string | FieldPath,
value: unknown, ...
moreFieldsAndValues: unknown[]): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
field | string | FieldPath |
value | unknown |
…moreFieldsAndValues | unknown[] |
Returns
CollRefHandle
Client-side collection reference.
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Properties
| Property | Modifier | Type |
|---|---|---|
converter | readonly | FirestoreDataConverter<unknown, DocumentData> |
descriptor | readonly | CollRef |
id | readonly | string |
path | readonly | string |
port | readonly | ClientPort |
Methods
withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): CollRefHandle<T>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | - |
D extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
converter | FirestoreDataConverter<T, D> |
Returns
Call Signature
withConverter(converter: null): CollRefHandle;
Parameters
| Parameter | Type |
|---|---|
converter | null |
Returns
DisconnectClientOptions
Properties
| Property | Type | Description |
|---|---|---|
ackTimeoutMs? | number | Bound version-skew and worker-crash cases where no disconnect reply arrives. |
DocRefHandle
Client-side document reference — carries a DocRef descriptor + port.
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Properties
| Property | Modifier | Type |
|---|---|---|
converter | readonly | FirestoreDataConverter<unknown, DocumentData> |
descriptor | readonly | DocRef |
id | readonly | string |
path | readonly | string |
port | readonly | ClientPort |
Methods
withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): DocRefHandle<T>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | - |
D extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
converter | FirestoreDataConverter<T, D> |
Returns
DocRefHandle<T>
Call Signature
withConverter(converter: null): DocRefHandle;
Parameters
| Parameter | Type |
|---|---|
converter | null |
Returns
PresenceSession
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
clientId | readonly | string | Logical page id — Studio uses this to label “This page”. |
kind | readonly | PresenceClientKind | - |
Methods
stop()
stop(): void;
Stop heartbeats, listeners, and send a best-effort disconnect.
Returns
void
PresenceSnapshot
Properties
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.tsimports the fullpyric/firestore+pyric/authengine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.entry.tsreferencesSharedWorkerGlobalScopeand 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
QueryHandle
Client-side query.
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Properties
| Property | Modifier | Type |
|---|---|---|
converter | readonly | FirestoreDataConverter<unknown, DocumentData> |
descriptor | readonly | QueryDescriptor |
port | readonly | ClientPort |
Methods
withConverter()
Call Signature
withConverter<T, D>(converter: FirestoreDataConverter<T, D>): QueryHandle<T>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | - |
D extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
converter | FirestoreDataConverter<T, D> |
Returns
QueryHandle<T>
Call Signature
withConverter(converter: null): QueryHandle;
Parameters
| Parameter | Type |
|---|---|
converter | null |
Returns
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
RtdbDataSnapshot
Properties
| Property | Modifier | Type |
|---|---|---|
key | readonly | string |
priority | readonly | string | number |
ref | readonly | RtdbRefHandle |
size | readonly | number |
Methods
child()
child(path: string): RtdbDataSnapshot;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
exists()
exists(): boolean;
Returns
boolean
exportVal()
exportVal(): unknown;
Returns
unknown
forEach()
forEach(cb: (child: RtdbDataSnapshot) => boolean | void): boolean;
Parameters
| Parameter | Type |
|---|---|
cb | (child: RtdbDataSnapshot) => boolean | void |
Returns
boolean
hasChild()
hasChild(path: string): boolean;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
boolean
hasChildren()
hasChildren(): boolean;
Returns
boolean
toJSON()
toJSON(): unknown;
Returns
unknown
val()
val(): unknown;
Returns
unknown
RtdbRefHandle
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
instance? | readonly | ClientRtdbInstance | The instance the reference belongs to; see ClientRtdb.instance. |
key | readonly | string | - |
parent | readonly | RtdbRefHandle | - |
path | readonly | string | - |
port | readonly | ClientPort | - |
ref | readonly | RtdbRefHandle | - |
root | readonly | RtdbRefHandle | - |
Methods
isEqual()
isEqual(other:
| RtdbRefHandle
| {
ref: RtdbRefHandle;
}): boolean;
Parameters
| Parameter | Type |
|---|---|
other | | RtdbRefHandle | { ref: RtdbRefHandle; } |
Returns
boolean
toJSON()
toJSON(): string;
Returns
string
toString()
toString(): string;
Returns
string
SerializedIdTokenResult
Wire form of getIdTokenResult().
Properties
| Property | Modifier | Type |
|---|---|---|
authTime | readonly | string |
claims | readonly | Record<string, unknown> |
expirationTime | readonly | string |
issuedAtTime | readonly | string |
signInProvider | readonly | string |
token | readonly | string |
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
SerializedUserCredential
Wire form of a UserCredential returned by the sign-in/create ops.
Properties
| Property | Modifier | Type |
|---|---|---|
additionalUserInfo? | readonly | { isNewUser: boolean; profile: Record<string, unknown>; providerId: string; } |
additionalUserInfo.isNewUser | readonly | boolean |
additionalUserInfo.profile | readonly | Record<string, unknown> |
additionalUserInfo.providerId | readonly | string |
operationType | readonly | "link" | "signIn" | "reauthenticate" |
providerId | readonly | string |
user | readonly | SerializedUser |
WorkerCheckpoint
One saved state as a listing reports it: the name, when it was taken, and its counts.
Properties
| Property | Type |
|---|---|
at | number |
counts | { auth: number; database: number; firestore: number; storage: number; } |
counts.auth | number |
counts.database | number |
counts.firestore | number |
counts.storage | number |
name | string |
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.tsimports the fullpyric/firestore+pyric/authengine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.entry.tsreferencesSharedWorkerGlobalScopeand 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
| Parameter | Type |
|---|---|
auth | ClientAuth |
identity | ResolvedIdentity |
Returns
Promise<ClientUserCredential>
addDoc()
function addDoc(coll: CollRefHandle, data: Record<string, unknown>): Promise<DocRefHandle<DocumentData>>;
Parameters
| Parameter | Type |
|---|---|
coll | CollRefHandle |
data | Record<string, unknown> |
Returns
Promise<DocRefHandle<DocumentData>>
adminClearUsers()
function adminClearUsers(auth: ClientAuth): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<void>
adminCreateUser()
function adminCreateUser(auth: ClientAuth, request: CreateUserRequest): Promise<AuthUserRecord>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
request | CreateUserRequest |
Returns
Promise<AuthUserRecord>
adminDeleteDocument()
function adminDeleteDocument(db: ClientDb, path: string): Promise<boolean>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<boolean>
adminDeleteRtdbValue()
function adminDeleteRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
instance?: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
instance? | string |
Returns
Promise<void>
adminDeleteUser()
function adminDeleteUser(auth: ClientAuth, uid: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
uid | string |
Returns
Promise<void>
adminGetDocument()
function adminGetDocument(db: ClientDb, path: string): Promise<Record<string, unknown>>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<Record<string, unknown>>
adminListDocuments()
function adminListDocuments(db: ClientDb, path: string): Promise<{
data: unknown;
path: string;
phantom?: boolean;
}[]>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<{
data: unknown;
path: string;
phantom?: boolean;
}[]>
adminReadRtdbState()
function adminReadRtdbState(db: ClientDb | ClientRtdb, instance?: string): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
instance? | string |
Returns
Promise<unknown>
adminReadState()
function adminReadState(db: ClientDb, opts?: {
maxDepth?: number;
path?: string;
}): Promise<Record<string, unknown>>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
data | unknown |
Returns
Promise<void>
adminSetRtdbValue()
function adminSetRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
value: unknown,
instance?: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
value | unknown |
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
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
next | (value: unknown) => void |
error? | (err: unknown) => void |
instance? | string |
Returns
adminUpdateRtdbValue()
function adminUpdateRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
values: Record<string, unknown>,
instance?: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
values | Record<string, unknown> |
instance? | string |
Returns
Promise<void>
adminUpdateUser()
function adminUpdateUser(
auth: ClientAuth,
uid: string,
request: UpdateUserRequest): Promise<AuthUserRecord>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
uid | string |
request | UpdateUserRequest |
Returns
Promise<AuthUserRecord>
aiCountTokens()
function aiCountTokens(db: ClientDb, params: AiOpParams): Promise<Record<string, unknown>>;
Unary countTokens against the worker’s broker (deterministic).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
params | AiOpParams |
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
| Parameter | Type |
|---|---|
db | ClientDb |
params | AiOpParams |
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
| Parameter | Type |
|---|---|
db | ClientDb |
params | AiOpParams |
Returns
AsyncGenerator<Record<string, unknown>>
and()
function and(...filters: QueryConstraintHandle[]): QueryConstraintHandle;
AND composite filter — every operand must match. See or.
Parameters
| Parameter | Type |
|---|---|
…filters | QueryConstraintHandle[] |
Returns
QueryConstraintHandle
arrayRemove()
function arrayRemove(...values: unknown[]): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
SentinelMarker
arrayUnion()
function arrayUnion(...values: unknown[]): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
SentinelMarker
average()
function average(field: string | FieldPath): AggregateFieldDescriptor;
Factory: average-of-field aggregate. Empty input yields null.
Parameters
| Parameter | Type |
|---|---|
field | string | 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
| Parameter | Type | Description |
|---|---|---|
db | ClientDb | - |
name | string | - |
args | Record<string, unknown> | - |
actAs? | AuthLens | The bridge caller’s identity, when it has impersonated one. Relayed verbatim. |
clientSessionId? | string | Keep 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
| Parameter | Type |
|---|---|
parent | | ClientDb | DocRefHandle<DocumentData> |
…pathSegments | string[] |
Returns
collectionGroup()
function collectionGroup(db: ClientDb, collectionId: string): QueryHandle;
Build a collection-group query. Mirrors pyric/firestore’s collectionGroup(db, id).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
collectionId | string |
Returns
connectAuthEmulator()
function connectAuthEmulator(
_auth: ClientAuth,
_url: string,
_options?: {
disableWarnings?: boolean;
}): void;
Connect to the auth emulator. No-op shim over the worker.
Parameters
| Parameter | Type |
|---|---|
_auth | ClientAuth |
_url | string |
_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
| Parameter | Type |
|---|---|
auth | ClientAuth |
email | string |
password | string |
Returns
Promise<ClientUserCredential>
createWorkerReplacement()
function createWorkerReplacement(options: WorkerReplacementOptions): WorkerReplacement;
Coordinate one reload per page after the old SharedWorker announces retirement.
Parameters
| Parameter | Type |
|---|---|
options | WorkerReplacementOptions |
Returns
deleteDoc()
function deleteDoc(ref: DocRefHandle): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<void>
deleteWorkerCheckpoint()
function deleteWorkerCheckpoint(db: ClientDb, name: string): Promise<void>;
Delete one saved state.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
Returns
Promise<void>
disconnectClient()
function disconnectClient(db: ClientDb, options?: DisconnectClientOptions): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
options? | DisconnectClientOptions |
Returns
Promise<void>
disconnectPort()
function disconnectPort(port: ClientPort): void;
Drop every client-side correlation owned by a closing app port.
Parameters
| Parameter | Type |
|---|---|
port | ClientPort |
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
| Parameter | Type |
|---|---|
parent | | ClientDb | CollRefHandle<DocumentData> |
…pathSegments | string[] |
Returns
endAt()
function endAt(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
endBefore()
function endBefore(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
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
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string>
getActiveRules()
function getActiveRules(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | 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
| Parameter | Type |
|---|---|
source | | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
spec | S |
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
| Parameter | Type |
|---|---|
source | string | ClientDb | URL |
name? | string |
Returns
getBlob()
function getBlob(reference: ClientStorageReference, maxDownloadSizeBytes?: number): Promise<Blob>;
Reconstruct binary data locally so reads work over MessagePort and JSON WebSocket.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
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
| Parameter | Type |
|---|---|
source | | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
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 Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle<T> |
Returns
Promise<ClientDocSnapshot<T>>
getDocs()
function getDocs(source:
| CollRefHandle<DocumentData>
| QueryHandle<DocumentData>): Promise<ClientQuerySnapshot>;
Parameters
| Parameter | Type |
|---|---|
source | | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<string>
getFirestore()
function getFirestore(
workerUrl: string | URL,
name?: string,
options?: SharedWorkerConnectionOptions): ClientDb;
Parameters
| Parameter | Type |
|---|---|
workerUrl | string | URL |
name? | string |
options? | SharedWorkerConnectionOptions |
Returns
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
| Parameter | Type | Description |
|---|---|---|
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? | string | Host 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) => void | Called 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? | HostedSocketRealm | Present 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
getIdToken()
function getIdToken(user: ClientUser, forceRefresh?: boolean): Promise<string>;
Parameters
| Parameter | Type |
|---|---|
user | ClientUser |
forceRefresh? | boolean |
Returns
Promise<string>
getIdTokenResult()
function getIdTokenResult(user: ClientUser, forceRefresh?: boolean): Promise<SerializedIdTokenResult>;
Parameters
| Parameter | Type |
|---|---|
user | ClientUser |
forceRefresh? | boolean |
Returns
Promise<SerializedIdTokenResult>
getLens()
function getLens(): AuthLens;
The active default lens (read-only view), for Studio UI to reflect state.
Returns
getMetadata()
function getMetadata(reference: ClientStorageReference): Promise<FullMetadata>;
Read an object’s metadata (Pyric Studio inspector).
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<FullMetadata>
getProviderConfig()
function getProviderConfig(auth: ClientAuth): Promise<{
enabled: boolean;
providerId: string;
}[]>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<{
enabled: boolean;
providerId: string;
}[]>
getRulesStatus()
function getRulesStatus(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | 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
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
source | string | ClientDb | URL |
name? | string |
bucketUrl? | string |
namedBucket? | boolean |
Returns
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
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
db | ClientDb |
options? | { timeoutMs?: number; } |
options.timeoutMs? | number |
Returns
Promise<string>
hydrateLensFromStorage()
function hydrateLensFromStorage(): AuthLens;
Read persisted auth lens from sessionStorage safely.
Returns
importWorkerState()
function importWorkerState(db: ClientDb, bundle: string): Promise<void>;
Phase 2 (clobber): replace this sandbox’s ENTIRE state with bundle.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
bundle | string |
Returns
Promise<void>
increment()
function increment(n: number): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
SentinelMarker
limit()
function limit(n: number): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
QueryConstraintHandle
limitToLast()
function limitToLast(n: number): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
n | number |
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
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
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string[]>
listSubcollections()
function listSubcollections(db: ClientDb, docPath: string): Promise<string[]>;
Enumerate subcollection ids under a document path (Pyric Studio data browse).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
docPath | string |
Returns
Promise<string[]>
listUsers()
function listUsers(auth: ClientAuth): Promise<AuthUserRecord[]>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<AuthUserRecord[]>
listWorkerCheckpoints()
function listWorkerCheckpoints(db: ClientDb): Promise<WorkerCheckpoint[]>;
This instance’s saved states, ordered by name.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
auth | ClientAuth |
callback | ClientAuthObserver |
Returns
onIdTokenChanged()
function onIdTokenChanged(auth: ClientAuth, callback: ClientAuthObserver): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
callback | ClientAuthObserver |
Returns
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
| Parameter | Type |
|---|---|
target | | DocRefHandle<DocumentData> | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
observerOrNext | ObserverOrNext |
errorCallback? | SnapshotErrorCallback |
Returns
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
| Parameter | Type |
|---|---|
target | | DocRefHandle<DocumentData> | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
options | object |
observerOrNext | ObserverOrNext |
errorCallback? | SnapshotErrorCallback |
Returns
onWorkerRuntimeReload()
function onWorkerRuntimeReload(listener: (epoch: string) => void): () => void;
Observe the worker’s all-pages reload signal.
Parameters
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
…filters | QueryConstraintHandle[] |
Returns
QueryConstraintHandle
orderBy()
function orderBy(field: string | FieldPath, direction?: "asc" | "desc"): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
field | string | 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
| Parameter | Type |
|---|---|
client | ClientDb |
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
| Parameter | Type |
|---|---|
storage | EpochStorage |
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
| Parameter | Type |
|---|---|
source | | CollRefHandle<DocumentData> | QueryHandle<DocumentData> |
…constraints | QueryConstraintHandle[] |
Returns
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
| Parameter | Type |
|---|---|
documentLike? | RuntimeDocument |
locationLike? | RuntimeLocation |
Returns
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
| Parameter | Type |
|---|---|
parent | | ClientFirebaseStorage | ClientStorageReference |
path? | string |
Returns
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
| Parameter | Type |
|---|---|
db | ClientDb |
op | WorkerOpPayload |
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
| Parameter | Type |
|---|---|
db | ClientDb |
sub | WorkerSubPayload |
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
| Parameter | Type |
|---|---|
epoch | string |
storage | EpochStorage |
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
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<{
errors: string[];
}>
restoreWorkerCheckpoint()
function restoreWorkerCheckpoint(db: ClientDb, name: string): Promise<void>;
Clobber: replace the whole sandbox with a named saved state.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
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
| Parameter | Type |
|---|---|
db | ClientDb |
targetEpoch | string |
options? | { timeoutMs?: number; } |
options.timeoutMs? | number |
Returns
Promise<void>
rtdbChild()
function rtdbChild(parent: RtdbRefHandle, path: string): RtdbRefHandle;
Parameters
| Parameter | Type |
|---|---|
parent | RtdbRefHandle |
path | string |
Returns
rtdbConnectDatabaseEmulator()
function rtdbConnectDatabaseEmulator(): void;
Returns
void
rtdbGet()
function rtdbGet(target: RtdbTarget): Promise<RtdbDataSnapshot>;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
Returns
Promise<RtdbDataSnapshot>
rtdbGetDatabase()
function rtdbGetDatabase(source?: string | ClientDb | URL, name?: string): ClientRtdb;
Parameters
| Parameter | Type |
|---|---|
source? | string | ClientDb | URL |
name? | string |
Returns
rtdbGoOffline()
function rtdbGoOffline(db: ClientRtdb): void;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
Returns
void
rtdbGoOnline()
function rtdbGoOnline(db: ClientRtdb): void;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
Returns
void
rtdbOff()
function rtdbOff(
target: RtdbTarget,
eventType?: RtdbEventType,
callback?: object): void;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
eventType? | RtdbEventType |
callback? | object |
Returns
void
rtdbOnChildAdded()
function rtdbOnChildAdded(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildChanged()
function rtdbOnChildChanged(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildMoved()
function rtdbOnChildMoved(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildRemoved()
function rtdbOnChildRemoved(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnDisconnect()
function rtdbOnDisconnect(ref: RtdbRefHandle): RtdbOnDisconnect;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
Returns
rtdbOnValue()
function rtdbOnValue(
target: RtdbTarget,
next: (snap: RtdbDataSnapshot) => void,
cancelCallbackOrOptions?: (err: unknown) => void | ValueListenOptions,
options?: ValueListenOptions,
registryCallback?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | (snap: RtdbDataSnapshot) => void |
cancelCallbackOrOptions? | (err: unknown) => void | ValueListenOptions |
options? | ValueListenOptions |
registryCallback? | object |
Returns
rtdbPush()
function rtdbPush(ref: RtdbRefHandle, value?: unknown): RtdbRefHandle & PromiseLike<RtdbRefHandle>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value? | unknown |
Returns
RtdbRefHandle & PromiseLike<RtdbRefHandle>
rtdbRef()
function rtdbRef(db: ClientRtdb, path?: string): RtdbRefHandle;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
path? | string |
Returns
rtdbRemove()
function rtdbRemove(ref: RtdbRefHandle): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
Returns
Promise<void>
rtdbRunTransaction()
function rtdbRunTransaction<T>(
ref: RtdbRefHandle,
transactionUpdate: (current: T) => T,
options?: RtdbTransactionOptions): Promise<RtdbTransactionResult>;
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
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
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value | unknown |
Returns
Promise<void>
rtdbSetPriority()
function rtdbSetPriority(ref: RtdbRefHandle, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
priority | string | number |
Returns
Promise<void>
rtdbSetWithPriority()
function rtdbSetWithPriority(
ref: RtdbRefHandle,
value: unknown,
priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value | unknown |
priority | string | number |
Returns
Promise<void>
rtdbUpdate()
function rtdbUpdate(ref: RtdbRefHandle, values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
values | Record<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:
- Each
txn.get(ref)records{ path, data }in a per-attempt read-set (datais the rawSerializedDocDatathe worker returned, ornullif the doc was missing). txnCommitcarries bothreads(the read-set) andwrites.- 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' } }. - On
aborted, the client discards the result ofupdateFnand re-runs it with a fresh transaction object (fresh reads, empty write buffer). Up toTXN_MAX_ATTEMPTSattempts are made. - 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
| Parameter | Type |
|---|---|
db | ClientDb |
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
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
Returns
Promise<void>
serverTimestamp()
function serverTimestamp(): SentinelMarker;
Returns
SentinelMarker
setDatabaseRules()
function setDatabaseRules(db: ClientDb | ClientRtdb, source: unknown): Promise<{
messages: unknown[];
ok: boolean;
}>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
source | unknown |
Returns
Promise<{
messages: unknown[];
ok: boolean;
}>
setDoc()
function setDoc<T>(
ref: DocRefHandle<T>,
data: T,
options?: ClientSetOptions): Promise<void>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle<T> |
data | T |
options? | ClientSetOptions |
Returns
Promise<void>
setFirestoreRules()
function setFirestoreRules(db: ClientDb, source: string): Promise<{
messages: unknown[];
ok: boolean;
warnings: unknown[];
}>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
source | string |
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
| Parameter | Type |
|---|---|
lens | AuthLens |
Returns
void
setOpIssuer()
function setOpIssuer(source: "studio"): void;
Declare who issues the ops this client module constructs. See _opIssuer.
Parameters
| Parameter | Type |
|---|---|
source | "studio" |
Returns
void
setPersistence()
function setPersistence(auth: ClientAuth, persistence: ClientPersistence): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
persistence | ClientPersistence |
Returns
Promise<void>
setProviderConfig()
function setProviderConfig(
auth: ClientAuth,
providerId: string,
enabled: boolean): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
providerId | string |
enabled | boolean |
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
| Parameter | Type |
|---|---|
db | ClientDb |
source | string |
Returns
Promise<{
warnings: unknown[];
}>
signInAnonymously()
function signInAnonymously(auth: ClientAuth): Promise<ClientUserCredential>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<ClientUserCredential>
signInWithEmailAndPassword()
function signInWithEmailAndPassword(
auth: ClientAuth,
email: string,
password: string): Promise<ClientUserCredential>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
email | string |
password | string |
Returns
Promise<ClientUserCredential>
signOut()
function signOut(auth: ClientAuth): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<void>
startAfter()
function startAfter(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
startAt()
function startAt(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
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
| Parameter | Type |
|---|---|
opts | StartPresenceOptions |
Returns
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
| Parameter | Type |
|---|---|
db | ClientDb |
callback | EventBatchCallback |
onError? | (error: Error & { code: string; }) => void |
Returns
subscribeLens()
function subscribeLens(listener: (lens: AuthLens) => void): () => void;
Register a listener for auth lens mutations. Returns an unsubscribe function that removes the listener.
Parameters
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
db | ClientDb |
callback | (snapshot: PresenceSnapshot) => void |
Returns
sum()
function sum(field: string | FieldPath): AggregateFieldDescriptor;
Factory: sum-of-field aggregate. Mirrors pyric/firestore’s sum().
Parameters
| Parameter | Type |
|---|---|
field | string | 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
| Parameter | Type |
|---|---|
auth | ClientAuth |
email? | string |
Returns
Promise<OutboundAuthMail>
updateDoc()
Call Signature
function updateDoc(ref: DocRefHandle, data: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
Promise<void>
Call Signature
function updateDoc(
ref: DocRefHandle,
field: string | FieldPath,
value: unknown, ...
moreFieldsAndValues: unknown[]): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
field | string | FieldPath |
value | unknown |
…moreFieldsAndValues | unknown[] |
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
data | ArrayBuffer | 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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
data | ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob |
metadata? | ClientSettableMetadata |
Returns
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
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
value | string |
format? | StringFormat |
metadata? | ClientSettableMetadata |
Returns
Promise<{
metadata: FullMetadata;
ref: ClientStorageReference;
}>
where()
function where(
field: string | FieldPath,
op: string,
value: unknown): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
field | string | FieldPath |
op | string |
value | unknown |
Returns
QueryConstraintHandle
wirePort()
function wirePort(port: ClientPort): void;
Wire up the port’s onmessage handler (idempotent per-port).
Parameters
| Parameter | Type |
|---|---|
port | ClientPort |
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
| Parameter | Type |
|---|---|
servedEpoch | string |
storage | EpochStorage |
Returns
string
writeBatch()
function writeBatch(db: ClientDb): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |