Pyric
Navigate

API reference

@pyric/cli/serve/worker

175 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-

ClientDb

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

Properties

PropertyModifierType
portreadonlyClientPort

ClientDocSnapshot

Properties

PropertyModifierTypeDescription
idreadonlystring-
pathreadonlystring-
refreadonlyDocRefHandleFull port-carrying reference, usable by write APIs.

Methods

data()
data(): Record<string, unknown>;
Returns

Record<string, unknown>

exists()
exists(): boolean;
Returns

boolean


ClientFirebaseStorage

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

Properties

PropertyModifierType
bucketreadonlystring
portreadonlyClientPort

ClientQuerySnapshot

Properties

PropertyModifierType
docsreadonlyClientDocSnapshot[]
emptyreadonlyboolean
sizereadonlynumber

ClientRtdb

Properties

PropertyModifierType
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): void;
Parameters
ParameterType
refDocRefHandle
Returns

void

get()
get(ref: DocRefHandle): Promise<ClientDocSnapshot>;
Parameters
ParameterType
refDocRefHandle
Returns

Promise<ClientDocSnapshot>

set()
set(
   ref: DocRefHandle,
   data: Record<string, unknown>,
   options?: {
  merge?: boolean;
  mergeFields?: string[];
}): void;
Parameters
ParameterType
refDocRefHandle
dataRecord<string, unknown>
options?{ merge?: boolean; mergeFields?: string[]; }
options.merge?boolean
options.mergeFields?string[]
Returns

void

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

void


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

PropertyModifierType
displayNamereadonlystring
emailreadonlystring
emailVerifiedreadonlyboolean
isAnonymousreadonlyboolean
phoneNumberreadonlystring
photoURLreadonlystring
providerDatareadonlyreadonly { displayName: string; email: string; phoneNumber: string; photoURL: string; providerId: string; uid: string; }[]
providerIdreadonlystring
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"signIn" | "link" | "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(
   ref: DocRefHandle,
   data: Record<string, unknown>,
   options?: {
  merge?: boolean;
  mergeFields?: string[];
}): ClientWriteBatch;
Parameters
ParameterType
refDocRefHandle
dataRecord<string, unknown>
options?{ merge?: boolean; mergeFields?: string[]; }
options.merge?boolean
options.mergeFields?string[]
Returns

ClientWriteBatch

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

ClientWriteBatch


CollRefHandle

Client-side collection reference.

Properties

PropertyModifierType
descriptorreadonlyCollRef
idreadonlystring
pathreadonlystring
portreadonlyClientPort

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.

Properties

PropertyModifierType
descriptorreadonlyDocRef
idreadonlystring
pathreadonlystring
portreadonlyClientPort

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

Authoritative presence snapshot owned by the SharedWorker host.

Properties

PropertyType
clientsPresenceClientRecord[]

PyricRuntimeManifest

Browser-safe SharedWorker CLIENT surface (Pyric Studio 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 to the pyric-shared-worker over its MessagePort. 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 live SharedWorker backend.

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.

Properties

PropertyModifierType
descriptorreadonlyQueryDescriptor
portreadonlyClientPort

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

PropertyModifierType
customClaimsreadonlyRecord<string, unknown>
displayNamereadonlystring
emailreadonlystring
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

PropertyModifierType
keyreadonlystring
parentreadonlyRtdbRefHandle
pathreadonlystring
portreadonlyClientPort
rootreadonlyRtdbRefHandle

Methods

isEqual()
isEqual(other: RtdbRefHandle): boolean;
Parameters
ParameterType
otherRtdbRefHandle
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

PropertyModifierType
displayNamereadonlystring
emailreadonlystring
emailVerifiedreadonlyboolean
isAnonymousreadonlyboolean
phoneNumberreadonlystring
photoURLreadonlystring
providerDatareadonlyreadonly { displayName: string; email: string; phoneNumber: string; photoURL: string; providerId: string; uid: string; }[]
providerIdreadonlystring
uidreadonlystring

SerializedUserCredential

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

Properties

PropertyModifierType
operationTypereadonly"signIn" | "link" | "reauthenticate"
providerIdreadonlystring
userreadonlySerializedUser

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";

Logical page kind for presence (#227).


PresenceVisibility

type PresenceVisibility = "visible" | "hidden";

Page Visibility API state carried on presence records.


Unsubscribe()

type Unsubscribe = () => void;

Unsubscribe function returned by every streaming subscription.

Returns

void

Variables

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";
};

Persistence markers — mirror firebase/auth / pyric/auth.

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 CLIENT surface (Pyric Studio 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 to the pyric-shared-worker over its MessagePort. 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 live SharedWorker backend.


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 (the provider sign-in seam). The entry adapter’s worker-path signInWithPopup/ signInWithRedirect runs the in-page AuthFlowResolver (which can’t cross the worker port), then calls this with the picked identity; the worker seeds it + signs it in, returning a worker-backed credential. The mirror updates eagerly (like the email/anon paths) so a synchronous auth.currentUser read right after the await reflects the new user.

Parameters

ParameterType
authClientAuth
identityResolvedIdentity

Returns

Promise<ClientUserCredential>


addDoc()

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

Parameters

ParameterType
collCollRefHandle
dataRecord<string, unknown>

Returns

Promise<DocRefHandle>


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): Promise<void>;

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring

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): Promise<unknown>;

Parameters

ParameterType
dbClientDb | ClientRtdb

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): Promise<void>;

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
valueunknown

Returns

Promise<void>


adminSubscribeRtdbValue()

function adminSubscribeRtdbValue(
   db: ClientDb | ClientRtdb,
   path: string,
   next: (value: unknown) => void,
   error?: (err: unknown) => void): 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

Returns

Unsubscribe


adminUpdateRtdbValue()

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

Parameters

ParameterType
dbClientDb | ClientRtdb
pathstring
valuesRecord<string, unknown>

Returns

Promise<void>


adminUpdateUser()

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

Parameters

ParameterType
authClientAuth
uidstring
requestUpdateUserRequest

Returns

Promise<AuthUserRecord>


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): AggregateFieldDescriptor;

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

Parameters

ParameterType
fieldstring

Returns

AggregateFieldDescriptor


callTool()

function callTool(
   db: ClientDb,
   name: string,
   args: Record<string, unknown>): 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

ParameterType
dbClientDb
namestring
argsRecord<string, unknown>

Returns

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


collection()

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

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

Parameters

ParameterType
parentClientDb | DocRefHandle
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: the worker’s sandbox IS the emulator-equivalent backend, so there’s nothing to point at. Present for surface parity so app code that calls it doesn’t break.

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>


deleteWorkerBranch()

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

Phase 3: delete a named branch.

Parameters

ParameterType
dbClientDb
namestring

Returns

Promise<void>


disconnectClient()

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

Parameters

ParameterType
dbClientDb
options?DisconnectClientOptions

Returns

Promise<void>


doc()

function doc(parent: ClientDb | CollRefHandle, ...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
parentClientDb | CollRefHandle
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 (every event so far). Opens a transient stream sub, resolves with the initial history batch, and tears the sub down immediately — so it never holds a live subscription. Useful for a late, snapshot-only consumer.

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 chunk format the persist layer uses, so wrapper types round-trip). 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 | QueryHandle, spec: S): Promise<{
  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
sourceCollRefHandle | QueryHandle
specS

Returns

Promise<{ data: { [K in string | number | symbol]: number }; }>


getAuth()

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

Get the worker-backed Auth handle.

Mirrors pyric/auth’s getAuth(sandbox) / firebase/auth’s getAuth(app) — but the input is either an existing ClientDb (reusing its port, the common case in serve where Firestore + auth share one worker) or a worker URL (standalone).

The returned handle seeds its currentUser mirror by opening an internal authState subscription that keeps it live across tabs.

Parameters

ParameterType
sourcestring | ClientDb | URL
name?string

Returns

ClientAuth


getBlob()

function getBlob(reference: ClientStorageReference): Promise<Blob>;

Read an object’s bytes as a Blob (Pyric Studio inspector preview). MessagePort-only — a Blob cannot cross the JSON bridge relay.

Parameters

ParameterType
referenceClientStorageReference

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 | QueryHandle): Promise<{
  data: {
     count: number;
  };
}>;

Parameters

ParameterType
sourceCollRefHandle | QueryHandle

Returns

Promise<{ data: { count: number; }; }>


getDoc()

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

Parameters

ParameterType
refDocRefHandle

Returns

Promise<ClientDocSnapshot>


getDocs()

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

Parameters

ParameterType
sourceCollRefHandle | QueryHandle

Returns

Promise<ClientQuerySnapshot>


getDownloadURL()

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

Return a page-owned URL for an object read through the SharedWorker.

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


getIdToken()

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

Top-level mirror of firebase/auth’s getIdToken(user).

Parameters

ParameterType
userClientUser
forceRefresh?boolean

Returns

Promise<string>


getIdTokenResult()

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

Top-level mirror of firebase/auth’s getIdTokenResult(user).

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): 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

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>


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[]>


listWorkerBranches()

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

Phase 3: list this instance’s saved branch names.

Parameters

ParameterType
dbClientDb

Returns

Promise<string[]>


mintPresenceClientId()

function mintPresenceClientId(): string;

Mint a random client id (page-lifetime).

Returns

string


onAuthStateChanged()

function onAuthStateChanged(auth: ClientAuth, callback: (user: ClientUser) => void): Unsubscribe;

Subscribe to auth-state changes. Mirrors firebase/auth’s onAuthStateChanged. Fires immediately with THIS PORT’s current session, then on every change to it (#754: sessions are per-port — another tab’s sign-in is a different user, not an update to this one). Updates the handle’s currentUser mirror before invoking the callback.

Parameters

ParameterType
authClientAuth
callback(user: ClientUser) => void

Returns

Unsubscribe


onIdTokenChanged()

function onIdTokenChanged(auth: ClientAuth, callback: (user: ClientUser) => void): Unsubscribe;

Subscribe to ID-token changes. Mirrors firebase/auth’s onIdTokenChanged — fires on THIS PORT’s identity transitions (per-port sessions, #754).

Parameters

ParameterType
authClientAuth
callback(user: ClientUser) => void

Returns

Unsubscribe


onSnapshot()

function onSnapshot(
   target:
  | DocRefHandle
  | CollRefHandle
  | QueryHandle,
   callback: (snap:
  | ClientDocSnapshot
  | ClientQuerySnapshot) => void,
   errorCallback?: (err: unknown) => void): Unsubscribe;

Subscribe to a document or query. Mirrors pyric/firestore’s onSnapshot.

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

Parameters

ParameterType
target| DocRefHandle | CollRefHandle | QueryHandle
callback(snap: | ClientDocSnapshot | ClientQuerySnapshot) => void
errorCallback?(err: unknown) => void

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, direction?: "asc" | "desc"): QueryConstraintHandle;

Parameters

ParameterType
fieldstring
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 | QueryHandle, ...constraints: QueryConstraintHandle[]): QueryHandle;

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

Parameters

ParameterType
sourceCollRefHandle | QueryHandle
constraintsQueryConstraintHandle[]

Returns

QueryHandle


readPyricRuntimeManifest()

function readPyricRuntimeManifest(documentLike?: RuntimeDocument): PyricRuntimeManifest;

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

Parameters

ParameterType
documentLike?RuntimeDocument

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). Client-side path math; no RPC.

Parameters

ParameterType
parent| ClientFirebaseStorage | ClientStorageReference
path?string

Returns

ClientStorageReference


relayWorkerOp()

function relayWorkerOp(db: ClientDb, op: WorkerOpPayload): 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

Returns

Promise<unknown>


relayWorkerSub()

function relayWorkerSub(
   db: ClientDb,
   sub: WorkerSubPayload,
   onValue: (value: unknown) => void): () => 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

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[]; }>


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
  | {
  onlyOnce?: boolean;
},
   options?: {
  onlyOnce?: boolean;
},
   registryCallback?: object): Unsubscribe;

Parameters

ParameterType
targetRtdbTarget
next(snap: RtdbDataSnapshot) => void
cancelCallbackOrOptions?| (err: unknown) => void | { onlyOnce?: boolean; }
options?{ onlyOnce?: boolean; }
options.onlyOnce?boolean
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>): 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>

Returns

Promise<R>


saveWorkerBranch()

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

Phase 3: save the live sandbox as a named branch (a saved state bundle).

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(
   ref: DocRefHandle,
   data: Record<string, unknown>,
   options?: {
  merge?: boolean;
  mergeFields?: string[];
}): Promise<void>;

Parameters

ParameterType
refDocRefHandle
dataRecord<string, unknown>
options?{ merge?: boolean; mergeFields?: string[]; }
options.merge?boolean
options.mergeFields?string[]

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). 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.

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>;

Record the session-persistence mode on the worker (surface parity). The effective persistence is CLIENT-side (#754): the entry adapter mirrors the mode into the page’s SessionStore, which decides where — or whether — this tab’s session uid is stored for reload restore.

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: (events: readonly SandboxEvent[]) => 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 initial history() snapshot (possibly empty), each subsequent call carries one live event. Returns an unsubscribe that deregisters on the worker.

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
callback(events: readonly SandboxEvent[]) => void

Returns

Unsubscribe


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): AggregateFieldDescriptor;

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

Parameters

ParameterType
fieldstring

Returns

AggregateFieldDescriptor


switchWorkerBranch()

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

Phase 3 (clobber): switch the live sandbox to a named branch’s state.

Parameters

ParameterType
dbClientDb
namestring

Returns

Promise<void>


updateDoc()

function updateDoc(ref: DocRefHandle, data: Record<string, unknown>): Promise<void>;

Parameters

ParameterType
refDocRefHandle
dataRecord<string, 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

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,
   op: string,
   value: unknown): QueryConstraintHandle;

Parameters

ParameterType
fieldstring
opstring
valueunknown

Returns

QueryConstraintHandle


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