Classes
AbstractUserDataWriter
Constructors
Constructor
new AbstractUserDataWriter(): AbstractUserDataWriter;
Returns
AggregateField
Constructors
Constructor
new AggregateField(): AggregateField;
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
field? | readonly | string |
kind | readonly | AggregateFieldType |
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
AggregateQuerySnapshot
Type Parameters
| Type Parameter | Default type |
|---|---|
T extends Record<string, number | null> | Record<string, number | null> |
Constructors
Constructor
new AggregateQuerySnapshot<T>(): AggregateQuerySnapshot<T>;
Returns
Methods
data()
data(): T;
Returns
T
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Bytes
Methods
isEqual()
isEqual(other: Bytes): boolean;
Parameters
| Parameter | Type |
|---|---|
other | Bytes |
Returns
boolean
toBase64()
toBase64(): string;
Returns
string
toJSON()
toJSON(): object;
Returns
object
toString()
toString(): string;
Returns
string
toUint8Array()
toUint8Array(): Uint8Array;
Returns
Uint8Array
fromBase64String()
static fromBase64String(base64: string): Bytes;
Parameters
| Parameter | Type |
|---|---|
base64 | string |
Returns
fromJSON()
static fromJSON(json: object): Bytes;
Parameters
| Parameter | Type |
|---|---|
json | object |
Returns
fromUint8Array()
static fromUint8Array(array: Uint8Array): Bytes;
Parameters
| Parameter | Type |
|---|---|
array | Uint8Array |
Returns
CollectionReference
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Constructors
Constructor
new CollectionReference<_T>(): CollectionReference<_T>;
Returns
Properties
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
DocumentReference
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Constructors
Constructor
new DocumentReference<_T>(): DocumentReference<_T>;
Returns
Properties
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
DocumentSnapshot
Extended by
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Constructors
Constructor
new DocumentSnapshot<T>(): DocumentSnapshot<T>;
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
exists | readonly | boolean | () => boolean |
id | readonly | string |
metadata | readonly | SnapshotMetadata |
ref | readonly | DocumentReference<T> |
Methods
data()
data(): T;
Returns
T
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
FieldPath
Constructors
Constructor
new FieldPath(...fieldNames: string[]): FieldPath;
Parameters
| Parameter | Type |
|---|---|
…fieldNames | string[] |
Returns
Methods
isEqual()
isEqual(other: FieldPath): boolean;
Parameters
| Parameter | Type |
|---|---|
other | FieldPath |
Returns
boolean
FieldValue
Constructors
Constructor
new FieldValue(): FieldValue;
Returns
Methods
arrayRemove()
static arrayRemove(...values: unknown[]): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
arrayUnion()
static arrayUnion(...values: unknown[]): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
delete()
static delete(): FieldValueSentinel;
Returns
increment()
static increment(n: number): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
serverTimestamp()
static serverTimestamp(): FieldValueSentinel;
Returns
Firestore
Constructors
Constructor
new Firestore(): Firestore;
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
[TARGET_SYMBOL] | readonly | Target |
app? | readonly | FirebaseApp |
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
FirestoreError
Extends
Error
Constructors
Constructor
new FirestoreError(code: string, message: string): FirestoreError;
Parameters
| Parameter | Type |
|---|---|
code | string |
message | string |
Returns
Overrides
Error.constructor
Properties
GeoPoint
Constructors
Constructor
new GeoPoint(lat: number, lng: number): GeoPoint;
Parameters
| Parameter | Type |
|---|---|
lat | number |
lng | number |
Returns
Accessors
latitude
Get Signature
get latitude(): number;
Returns
number
longitude
Get Signature
get longitude(): number;
Returns
number
Methods
isEqual()
isEqual(other: GeoPoint): boolean;
Parameters
| Parameter | Type |
|---|---|
other | GeoPoint |
Returns
boolean
toJSON()
toJSON(): {
latitude: number;
longitude: number;
type: string;
};
Returns
{
latitude: number;
longitude: number;
type: string;
}
latitude
latitude: number;
longitude
longitude: number;
type
type: string;
fromJSON()
static fromJSON(json: object): GeoPoint;
Parameters
| Parameter | Type |
|---|---|
json | object |
Returns
LoadBundleTask
Implements
PromiseLike<LoadBundleTaskProgress>
Constructors
Constructor
new LoadBundleTask(promise: Promise<LoadBundleTaskProgress>): LoadBundleTask;
Parameters
| Parameter | Type |
|---|---|
promise | Promise<LoadBundleTaskProgress> |
Returns
Methods
catch()
catch<TResult>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<LoadBundleTaskProgress | TResult>;
Type Parameters
| Type Parameter | Default type |
|---|---|
TResult | never |
Parameters
| Parameter | Type |
|---|---|
onrejected? | (reason: any) => TResult | PromiseLike<TResult> |
Returns
Promise<LoadBundleTaskProgress | TResult>
onProgress()
onProgress(
_next?: (progress: LoadBundleTaskProgress) => void,
_error?: (err: Error) => void,
_complete?: () => void): void;
Parameters
| Parameter | Type |
|---|---|
_next? | (progress: LoadBundleTaskProgress) => void |
_error? | (err: Error) => void |
_complete? | () => void |
Returns
void
then()
then<TResult1, TResult2>(onfulfilled?: (value: LoadBundleTaskProgress) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
Attaches callbacks for the resolution and/or rejection of the Promise.
Type Parameters
| Type Parameter | Default type |
|---|---|
TResult1 | LoadBundleTaskProgress |
TResult2 | never |
Parameters
| Parameter | Type | Description |
|---|---|---|
onfulfilled? | (value: LoadBundleTaskProgress) => TResult1 | PromiseLike<TResult1> | The callback to execute when the Promise is resolved. |
onrejected? | (reason: any) => TResult2 | PromiseLike<TResult2> | The callback to execute when the Promise is rejected. |
Returns
Promise<TResult1 | TResult2>
A Promise for the completion of which ever callback is executed.
Implementation of
PromiseLike.then
PersistentCacheIndexManager
Constructors
Constructor
new PersistentCacheIndexManager(_db: Firestore): PersistentCacheIndexManager;
Parameters
| Parameter | Type |
|---|---|
_db | Firestore |
Returns
Methods
deleteAllIndexes()
deleteAllIndexes(): Promise<void>;
Returns
Promise<void>
disableIndexAutoCreation()
disableIndexAutoCreation(): Promise<void>;
Returns
Promise<void>
enableIndexAutoCreation()
enableIndexAutoCreation(): Promise<void>;
Returns
Promise<void>
Query
Type Parameters
| Type Parameter | Default type |
|---|---|
_T | DocumentData |
Constructors
Constructor
new Query<_T>(): Query<_T>;
Returns
Query<_T>
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
QueryCompositeFilterConstraint
Extends
Constructors
Constructor
new QueryCompositeFilterConstraint(): QueryCompositeFilterConstraint;
Returns
QueryCompositeFilterConstraint
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
QueryConstraint
Extended by
QueryFieldFilterConstraintQueryCompositeFilterConstraintQueryOrderByConstraintQueryLimitConstraintQueryStartAtConstraintQueryEndAtConstraint
Constructors
Constructor
new QueryConstraint(): QueryConstraint;
Returns
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
QueryDocumentSnapshot
Extends
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Constructors
Constructor
new QueryDocumentSnapshot<T>(): QueryDocumentSnapshot<T>;
Returns
Inherited from
Properties
| Property | Modifier | Type |
|---|---|---|
exists | readonly | boolean | () => boolean |
id | readonly | string |
metadata | readonly | SnapshotMetadata |
ref | readonly | DocumentReference<T> |
Methods
data()
data(): T;
Returns
T
Overrides
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Inherited from
DocumentSnapshot.[hasInstance]
QueryEndAtConstraint
Extends
Constructors
Constructor
new QueryEndAtConstraint(): QueryEndAtConstraint;
Returns
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
QueryFieldFilterConstraint
Extends
Constructors
Constructor
new QueryFieldFilterConstraint(): QueryFieldFilterConstraint;
Returns
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
QueryLimitConstraint
Extends
Constructors
Constructor
new QueryLimitConstraint(): QueryLimitConstraint;
Returns
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
QueryOrderByConstraint
Extends
Constructors
Constructor
new QueryOrderByConstraint(): QueryOrderByConstraint;
Returns
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
QuerySnapshot
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Constructors
Constructor
new QuerySnapshot<T>(): QuerySnapshot<T>;
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
docs | readonly | readonly QueryDocumentSnapshot<T>[] |
empty | readonly | boolean |
metadata | readonly | SnapshotMetadata |
size | readonly | number |
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
QueryStartAtConstraint
Extends
Constructors
Constructor
new QueryStartAtConstraint(): QueryStartAtConstraint;
Returns
Inherited from
Properties
Methods
applySandbox()
applySandbox(q: Query): Query;
Parameters
| Parameter | Type |
|---|---|
q | Query |
Returns
Inherited from
prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
owner | object |
Returns
Inherited from
QueryConstraint.prepareSandbox
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Overrides
SandboxError
Sandbox-layer error. Catch with instanceof SandboxError and switch
on code. denialContext is populated for permission-denied only
(and only after Slice 4 wires it through).
Two construction forms are supported:
- Positional:
new SandboxError(code, message, denialContext?)— the original signature, kept for backward compatibility with existing internal call sites. - Options bag:
new SandboxError({ code, message, remediation? })— used when attaching remediation guidance.
Extends
Error
Constructors
Constructor
new SandboxError(
code: SandboxErrorCode,
message: string,
denialContext?: DenialContext): SandboxError;
Parameters
| Parameter | Type |
|---|---|
code | SandboxErrorCode |
message | string |
denialContext? | DenialContext |
Returns
Overrides
Error.constructor
Constructor
new SandboxError(options: SandboxErrorOptions): SandboxError;
Parameters
| Parameter | Type |
|---|---|
options | SandboxErrorOptions |
Returns
Overrides
Error.constructor
Properties
| Property | Modifier | Type |
|---|---|---|
code | readonly | SandboxErrorCode |
denialContext? | readonly | DenialContext |
remediation? | readonly | string |
SnapshotMetadata
Constructors
Constructor
new SnapshotMetadata(): SnapshotMetadata;
Returns
Properties
Methods
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Timestamp
Constructors
Constructor
new Timestamp(seconds: number, nanoseconds: number): Timestamp;
Parameters
| Parameter | Type |
|---|---|
seconds | number |
nanoseconds | number |
Returns
Properties
Methods
isEqual()
isEqual(other: Timestamp): boolean;
FS-B12 — value equality, mirroring fb.Timestamp.isEqual.
Parameters
| Parameter | Type |
|---|---|
other | Timestamp |
Returns
boolean
toDate()
toDate(): Date;
Returns
Date
toJSON()
toJSON(): {
nanoseconds: number;
seconds: number;
type: string;
};
FS-B12 — JSON form, mirroring fb.Timestamp.toJSON.
Returns
{
nanoseconds: number;
seconds: number;
type: string;
}
nanoseconds
nanoseconds: number;
seconds
seconds: number;
type
type: string;
toMillis()
toMillis(): number;
Returns
number
toString()
toString(): string;
FS-B12 — textual form, mirroring fb.Timestamp.toString.
Returns
string
valueOf()
valueOf(): string;
FS-B12 — primitive coercion for </<=/>=/> comparisons, mirroring
fb.Timestamp.valueOf: a zero-padded <seconds>.<nanoseconds> string
(seconds offset by MIN_SECONDS so it stays non-negative and lexically
ordered).
Returns
string
fromDate()
static fromDate(d: Date): Timestamp;
Parameters
| Parameter | Type |
|---|---|
d | Date |
Returns
fromMillis()
static fromMillis(ms: number): Timestamp;
Parameters
| Parameter | Type |
|---|---|
ms | number |
Returns
now()
static now(): Timestamp;
Returns
Transaction
Extends
Constructors
Constructor
new Transaction(): Transaction;
Returns
Inherited from
ChainTransaction.constructor
Methods
delete()
delete(ref: DocumentReference): Transaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
Returns
Inherited from
get()
Call Signature
get(ref: DocumentReference): Promise<AdminDocumentSnapshot>;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
Returns
Promise<AdminDocumentSnapshot>
Inherited from
Call Signature
get(query: Query): Promise<AdminQuerySnapshot>;
Parameters
| Parameter | Type |
|---|---|
query | Query |
Returns
Promise<AdminQuerySnapshot>
Inherited from
set()
set(ref: DocumentReference, data: DocumentData): Transaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
data | DocumentData |
Returns
Inherited from
update()
update(ref: DocumentReference, data: DocumentData): Transaction;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
data | DocumentData |
Returns
Inherited from
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
VectorValue
Methods
isEqual()
isEqual(other: VectorValue): boolean;
Parameters
| Parameter | Type |
|---|---|
other | VectorValue |
Returns
boolean
toArray()
toArray(): number[];
Returns
number[]
toJSON()
toJSON(): object;
Returns
object
create()
static create(values: number[]): VectorValue;
Parameters
| Parameter | Type |
|---|---|
values | number[] |
Returns
fromJSON()
static fromJSON(json: object): VectorValue;
Parameters
| Parameter | Type |
|---|---|
json | object |
Returns
WriteBatch
Extends
Constructors
Constructor
new WriteBatch(): WriteBatch;
Returns
Inherited from
ChainWriteBatch.constructor
Methods
commit()
commit(opts?: OperationOptions): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
opts? | OperationOptions |
Returns
Promise<void>
Inherited from
delete()
delete(ref: DocumentReference): WriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
Returns
Inherited from
set()
set(ref: DocumentReference, data: DocumentData): WriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
data | DocumentData |
Returns
Inherited from
update()
update(ref: DocumentReference, data: DocumentData): WriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
data | DocumentData |
Returns
Inherited from
[hasInstance]()
static hasInstance: boolean;
Parameters
| Parameter | Type |
|---|---|
instance | unknown |
Returns
boolean
Interfaces
DocumentChange
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Properties
| Property | Modifier | Type |
|---|---|---|
doc | readonly | QueryDocumentSnapshot<T> |
newIndex | readonly | number |
oldIndex | readonly | number |
type | readonly | DocumentChangeType |
EmulatorMockTokenOptions
Properties
ExperimentalLongPollingOptions
Properties
FirestoreDataConverter
Pair of translators between the consumer’s app model and the
underlying Firestore representation. Mirrors firebase/firestore’s
FirestoreDataConverter shape.
toFirestore(model)runs on every write (setDoc,addDoc) through a converted ref. Returns theDocumentDatato send.fromFirestore(snapshot)runs on every read (getDoc,getDocs, snapshot listener callback) through a converted ref. Receives the raw snapshot, returns the typed model.
Type Parameters
| Type Parameter | Default type |
|---|---|
AppModelType | - |
DbModelType extends DocumentData | DocumentData |
Methods
fromFirestore()
fromFirestore(snapshot: QueryDocumentSnapshot<DbModelType>): AppModelType;
Parameters
| Parameter | Type |
|---|---|
snapshot | QueryDocumentSnapshot<DbModelType> |
Returns
AppModelType
toFirestore()
toFirestore(modelObject: AppModelType): DbModelType;
Parameters
| Parameter | Type |
|---|---|
modelObject | AppModelType |
Returns
DbModelType
FirestoreDataToolDeps
Methods
resolveDb()
resolveDb(as?: As): Firestore | Promise<Firestore>;
Resolver returning a Firestore handle. Called per-dispatch with the
op’s as value: 'admin' (or undefined) → an admin-bypass Firestore;
{ uid, claims? } → a rules-enforcing Firestore acting as that user.
The host decides the posture; the tool layer does NOT enforce it. A sandbox resolver may default to admin (rules bypass is the point of seeding), but a resolver wired to a real backend should require an explicit identity or confirm-gate admin writes (see the bridge’s prod confirm-policy).
Parameters
| Parameter | Type |
|---|---|
as? | As |
Returns
Firestore | Promise<Firestore>
FirestoreInspectToolDeps
Methods
resolveSandbox()
resolveSandbox():
| LocalSandbox
| Promise<LocalSandbox>;
Resolve the sandbox whose Firestore state should be inspected.
Returns
| LocalSandbox
| Promise<LocalSandbox>
FirestoreSettings
Client-cache/network settings initializeFirestore accepts but no-ops
on sandbox targets — see the tier-1 section rationale above.
Properties
| Property | Type |
|---|---|
cacheSizeBytes? | number |
experimentalAutoDetectLongPolling? | boolean |
experimentalForceLongPolling? | boolean |
host? | string |
ignoreUndefinedProperties? | boolean |
localCache? | LocalCache |
ssl? | boolean |
Index
Properties
| Property | Type |
|---|---|
collectionGroup | string |
fields? | IndexField[] |
IndexConfiguration
Properties
| Property | Type |
|---|---|
fieldOverrides? | unknown[] |
indexes? | Index[] |
IndexField
Properties
LintResult
Properties
| Property | Type | Description |
|---|---|---|
metrics | RulesMetrics | - |
parseError? | ParseError | Structured parse failure when the source did not parse. When defined, metrics (except sourceSize) and warnings carry no signal — budget checks were skipped. Callers should branch on parseError before interpreting warnings or metrics. Why this isn’t a new severity value: a parse failure means “this isn’t a rule yet” rather than “this rule will fail at runtime”, which is a categorically different question from anything warnings answers. Adding a new severity would force every consumer to handle a third branch they don’t care about; a separate field lets old code keep working and gives new code a clean signal to check. |
warnings | LintWarning[] | - |
LoadBundleTaskProgress
Properties
| Property | Modifier | Type |
|---|---|---|
bytesLoaded | readonly | number |
documentsLoaded | readonly | number |
taskState | readonly | TaskState |
totalBytes | readonly | number |
totalDocuments | readonly | number |
LocalCache
Opaque local-cache config token accepted by initializeFirestore’s
settings.localCache. Inert — see the tier-1 section rationale above.
Properties
| Property | Modifier | Type |
|---|---|---|
[LOCAL_CACHE_SYMBOL] | readonly | "persistent" | "memory" |
garbageCollector? | readonly | MemoryGarbageCollector |
tabManager? | readonly | PersistentTabManager |
MemoryCacheSettings
Properties
| Property | Type |
|---|---|
garbageCollector? | MemoryGarbageCollector |
MemoryGarbageCollector
Opaque garbage-collector config token. Inert for the same reason — there is no memory cache tier with GC pressure to tune.
Properties
PersistenceSettings
Properties
PersistentCacheSettings
Properties
| Property | Type |
|---|---|
cacheSizeBytes? | number |
tabManager? | PersistentTabManager |
PersistentSingleTabManagerSettings
Properties
PersistentTabManager
Opaque tab-manager config token. Inert — persistence is always on,
and the SharedWorker/pyric dev path already is the one shared
store every tab talks to, so there is no separate multi-tab mode
to opt into. Carries the requested kind only for debugging.
Properties
Sandbox
A Firebase sandbox — an isolated environment with one auth identity.
Created via initializeSandbox(config). Use fork({ auth }) to
derive a new sandbox with a different identity that shares the
underlying environment (rules, data, state). Fork is the only
identity-switching mechanism — there are no per-op auth overrides
and no in-place mutation.
Extended by
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
admin | readonly | SandboxAdmin | Admin-plane access (rule-bypass reads). Identity-agnostic by design — admin reads aren’t gated on auth, so they live on the sandbox, not on a context. See SandboxAdmin. |
currentUser | public | { token?: Record<string, unknown>; uid: string; } | Current authenticated user across the sandbox. Mutated by pyric/auth’s signInAnonymously / signInWithEmailAndPassword / signOut / sandbox.setUser. Read per-call by service factories (e.g. a future getFirestore(sandbox) overload) so they see auth state changes without re-binding handles. Defaults to null (anonymous / signed out). Independent of withAuth({uid}) — withAuth still produces a frozen SandboxContext that carries its own identity for the runner’s test code (the existing pattern: explicit identity per service call). currentUser exists for the pyric/auth mirror, where consumer app code drives identity through a stateful Auth handle rather than naming it per call. |
currentUser.token? | public | Record<string, unknown> | - |
currentUser.uid | public | string | - |
Methods
clearPersistence()
clearPersistence(): Promise<void>;
Wipe the persisted blob for this sandbox’s key. In-memory state
is left intact — call reset() if you want both. Useful for
“sign out and forget” flows.
No-op when persistence is not enabled.
Returns
Promise<void>
dispose()
dispose(): void;
Tear down listener registries on this sandbox’s environment without
replacing it. Use this when you’re about to discard the sandbox
itself (e.g. runner.reseed() builds a fresh sandbox rather than
calling reset()) and want to drop callback references on the
outgoing instance defensively. Idempotent. Does not touch data.
Returns
void
enablePersistence()
enablePersistence(options: SandboxPersistenceOptions): Promise<void>;
Persist the sandbox’s data to a backend and restore it on next
enablePersistence call. The default 'indexedDB' backend turns
the sandbox into the host page’s local Firestore — writes flush
automatically and a fresh initializeSandbox() rehydrates from
the prior session.
Restoration happens before the promise resolves; awaiting this call is sufficient to guarantee in-memory state matches the persisted blob.
Idempotent across the same key — calling twice in one process
is a no-op on the second call. Different keys are rejected as an
error (a sandbox can persist to at most one backend at a time).
Listener semantics: every write event the sandbox emits triggers
a debounced flush (default 250ms). Browser hosts additionally
flush on beforeunload so a page navigation doesn’t lose the
tail of the debounce window.
See SandboxPersistenceOptions for backend selection and tuning.
Parameters
| Parameter | Type |
|---|---|
options | SandboxPersistenceOptions |
Returns
Promise<void>
enableTabSync()
enableTabSync(options?: TabSyncOptions): () => void;
Enable cross-tab realtime sync via BroadcastChannel. A write in
this tab will propagate to every OTHER tab of the same origin that
also called enableTabSync, causing their onSnapshot listeners to
re-evaluate — restoring production’s cross-client realtime behavior.
Opt-in, OFF by default. Firestore only (RTDB is a follow-on).
Returns a disable function. Calling it removes the onEvent
subscription, the channel message listener, and closes the channel
(when it was created internally). After disable, no further propagation
occurs in either direction.
Multi-writer note: concurrent writes from two tabs to the same doc produce last-write-wins divergence — there is no conflict resolution. The intended model is one active writer (one user, one tab) with observers in other tabs; this covers the overwhelming majority of local development scenarios.
Parameters
| Parameter | Type |
|---|---|
options? | TabSyncOptions |
Returns
(): void;
Returns
void
See
TabSyncOptions for channel injection (tests) and originId.
Example
// In every tab that should participate in realtime:
const sandbox = initializeSandbox();
const disableSync = sandbox.enableTabSync();
// Later, to stop syncing:
disableSync();
flush()
flush(): Promise<void>;
Force a snapshot to the configured persistence backend right now. Useful before a manual navigation, or in tests that need deterministic ordering against the debounce window. Resolves once the write hits the backend.
Throws if persistence is not enabled.
Returns
Promise<void>
history()
history(): SandboxEvent[];
Every SandboxEvent this sandbox has emitted since init or
the last reset(). Returns a defensive copy.
Use this for replay: hand the array to replay(events, rules)
from pyric/sandbox and the engine re-issues every
captured write against a fresh sandbox.
Unlike onEvent (live stream from the moment of subscribe),
history() returns every event the sandbox has seen — useful
for consumers that attach late (e.g., loading a saved session
before subscribing) or that need a snapshot at a particular moment.
reset() and dispose() each append a closing session_boundary
event; reset() then clears the history. Consumers that took a
snapshot before reset retain the boundary in their copy.
Returns
loadSnapshot()
loadSnapshot(data: SandboxSnapshot): void;
CLOBBER-restore the sandbox’s entire state from a prior snapshot:
reset() (clears firestore + the signed-in session), then rebuild firestore
from data and restore each registered service. This is a TOTAL replace —
documents absent from data do NOT survive — and is the counterpart to
snapshot. It is what makes “transfer (clobber) one instance’s data
into another” and named-branch switching possible.
Fires a session_boundary (reset phase), re-evaluates live listeners against
the loaded state, and the next persistence flush writes the loaded state.
Services present in data but not currently registered are skipped (a
snapshot taken via snapshot always includes every registered
service, so this only affects cross-instance imports from a sandbox that had
a service this one lacks).
Parameters
| Parameter | Type |
|---|---|
data | SandboxSnapshot |
Returns
void
onCurrentUserChanged()
onCurrentUserChanged(cb: (user: {
token?: Record<string, unknown>;
uid: string;
}) => void): () => void;
Subscribe to currentUser changes. Fires on every mutation —
sign-in, sign-out, user swap. Does NOT fire on subscribe.
Survives reset() and dispose() only as a no-op: a disposed
sandbox emits nothing further; a reset sandbox clears
currentUser to null (and fires the change) before swapping
the env.
Returns an unsubscribe function. Listener errors are swallowed — subscribers are observational, the sandbox does not propagate their errors.
Parameters
| Parameter | Type |
|---|---|
cb | (user: { token?: Record<string, unknown>; uid: string; }) => void |
Returns
(): void;
Returns
void
onEvent()
onEvent(cb: (event: SandboxEvent) => void): () => void;
Subscribe to every event the sandbox emits — see SandboxEvent
for the discriminated-union shape. One subscription covers
request/denial/snapshot-error/listener-lifecycle/session-boundary;
filter on event.kind to recover individual streams.
Replaces the prior three-channel surface (onRequest / onDenial
/ onSnapshotError) — see issue #307. Filter cookbook:
- All denials:
event.kind === 'request' && event.result === 'deny' - Stream errors:
event.kind === 'listener_errored' - Per-op traffic:
event.kind === 'request'
Survives sandbox.reset() — the subscription is held on the
sandbox, not on the underlying environment. A session_boundary
event with phase: 'reset' fires before the env swap so consumers
can segment their stream.
Returns an unsubscribe function. Listener errors are swallowed so a faulty subscriber can’t change rule semantics or hide other events. Both synchronous throws and rejected Promises from async callbacks are silently discarded — subscribers are observational, the sandbox doesn’t await them and doesn’t propagate their errors.
Parameters
| Parameter | Type |
|---|---|
cb | (event: SandboxEvent) => void |
Returns
(): void;
Returns
void
registerPersistableService()
registerPersistableService(name: string, hooks: PersistableService): () => void;
Register a service (auth, storage, …) as a persistence participant.
The sandbox calls hooks.snapshot() on every flush and
hooks.restore(data) on restore. If hooks.subscribe is provided,
the persistence controller subscribes and schedules a debounced
flush on each change — so auth-user edits flush promptly, not only
on the next Firestore write.
Returns an unregister function — call it if the service is torn
down before the sandbox is disposed (uncommon in practice; the
sandbox’s dispose() clears the registry anyway).
Throws failed-precondition when a service with the same name is
already registered — the auth package registers 'auth' once when
getAuth(sandbox) first creates a backend, so accidental double-
registration is a caller bug, not a no-op.
Advanced / internal API. Service packages (auth, storage) call this when they first attach to a sandbox. Consumer app code should not need to call this directly.
Parameters
| Parameter | Type |
|---|---|
name | string |
hooks | PersistableService |
Returns
(): void;
Returns
void
reset()
reset(): void;
Reset the underlying environment to a fresh state — wipes data, rules, and any service-specific configuration.
Snapshot listeners attached to the OLD environment are dropped at
the swap — they can’t survive because their target docs have been
wiped. onEvent subscribers DO survive — the registry lives on
the sandbox, and a session_boundary event with phase: 'reset'
fires before the swap so subscribers know the rollover happened.
Existing SandboxContexts continue to work — their sandbox
reference is stable; subsequent operations resolve to the new env.
Returns
void
resetAll()
resetAll(): Promise<{
errors: string[];
}>;
Reset the WHOLE sandbox: reset (Firestore env + signed-in
session), then clear every registered persistable service that
provides a PersistableService.reset hook — auth users, the
RTDB tree, storage objects. This is the one sandbox-owned “wipe
everything” path: because it iterates the service registry, a new
service that registers with a reset hook is cleared automatically,
and a consumer (Pyric Studio’s reset) cannot forget one.
Service resets may be async (storage clears IndexedDB stores); the
returned promise resolves when every service has finished clearing.
A service whose reset throws is isolated (others still clear) and
REPORTED in the returned errors (as name: message) — a reset that
leaves data behind must never look successful to the caller.
Returns
Promise<{
errors: string[];
}>
runWithProvenance()?
optional runWithProvenance<T>(provenance: EventProvenance, fn: () => T): T;
Run fn with ambient EventProvenance defaults: every event
emitted SYNCHRONOUSLY during fn that doesn’t already carry a
provenance field (on the event itself or via an explicit per-emit
override) is stamped with these values instead of the global
defaults. This is the mechanical “who issued this op” seam the
serve worker uses to tag Studio-issued ops (actor: { kind: 'studio' }) and to stamp the auth lens an op ran under
(authLens) — declared by the caller that issues the op, never
inferred from the op’s shape.
SYNCHRONOUS WINDOW: the ambient values apply only until fn
returns (for an async fn, its synchronous prefix — which covers
the local environment’s rules eval + event emission, since those
run before the op’s promise is handed back). Work an op DEFERS
(snapshot-listener deliveries and re-evals drain on a microtask,
off-stack) is intentionally OUTSIDE the window: a listener re-eval
belongs to the listener’s owner, not to whoever’s write triggered
it. Nested calls stack — the innermost window wins per field, and
each window restores the previous one on exit (including on throw).
OPTIONAL because remote sandbox proxies can’t provide an ambient
emit window (events are emitted in the worker they front). Callers
spell sandbox.runWithProvenance?.(prov, fn) ?? fn().
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
provenance | EventProvenance |
fn | () => T |
Returns
T
snapshot()
snapshot(): SandboxSnapshot;
Capture a snapshot of every service’s state. For v1 with only
Firestore, the return value carries a firestore key mapping doc
paths to data. Future services will add their own keys.
Returns
withAuth()
withAuth(auth: {
token?: Record<string, unknown>;
uid: string;
}): SandboxContext;
Derive a context bound to this sandbox under the given auth identity. Operations through services attached to the returned context evaluate rules under that identity. Many contexts can coexist for one sandbox; data is shared.
null is anonymous; an AuthState object names the user (and
optional custom claims). Passing undefined is a deliberate
error — say withAuth(null) for anonymous so the call site is
unambiguous.
Parameters
| Parameter | Type |
|---|---|
auth | { token?: Record<string, unknown>; uid: string; } |
auth.token? | Record<string, unknown> |
auth.uid | string |
Returns
Example
const sandbox = initializeSandbox();
const dbAlice = getFirestore(sandbox.withAuth({ uid: 'alice' }));
const dbAnon = getFirestore(sandbox.withAuth(null));
SandboxContext
Identity-bearing handle on a Sandbox. A
(sandbox, auth, operationContext)
tuple — cheap to create, immutable, freely shareable. Service
factories require a SandboxContext; bare Sandbox is a type
error so every call site states identity explicitly.
Constructed via Sandbox.withAuth(auth) or chained via
SandboxContext.withAuth(auth). The concrete class is exported
from pyric/sandbox for instanceof routing in service
factories; consumers don’t construct it directly.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
auth | readonly | { token?: Record<string, unknown>; uid: string; } | The identity rules evaluate under for operations through this context. |
auth.token? | public | Record<string, unknown> | - |
auth.uid | public | string | - |
operationContext | readonly | OperationContext | Immutable provenance bound to every operation issued through this handle. |
sandbox | readonly | Sandbox | The data foundation this context operates against. |
Methods
withAuth()
withAuth(auth: {
token?: Record<string, unknown>;
uid: string;
}): SandboxContext;
Derive a sibling context on the same sandbox with different auth. Replaces auth and its lens while preserving the operation source and optional plan identity.
Parameters
| Parameter | Type |
|---|---|
auth | { token?: Record<string, unknown>; uid: string; } |
auth.token? | Record<string, unknown> |
auth.uid | string |
Returns
SetOptions
Modular Web-SDK-shaped SetOptions. Either flag controls how data
combines with the existing document; passing nothing replaces the
existing doc entirely (Firestore default).
{ merge: true }— shallow-merge every top-level field indatainto the existing document, preserving fields not indata. Equivalent tofirebase/firestore’ssetDoc(ref, data, { merge: true }).{ mergeFields: [...] }— projectdatato just the listed top-level fields, then merge. Other fields indataare ignored; other fields in the existing doc are preserved.
merge and mergeFields are mutually exclusive; passing both is
a programming error (mergeFields wins on the sandbox path,
matching the JS SDK’s effective behavior).
Properties
SnapshotListenOptions
Properties
SnapshotObserver
Type Parameters
| Type Parameter |
|---|
T |
Properties
SnapshotOptions
Properties
TransactionOptions
Options accepted by the modular Web-SDK-shaped runTransaction.
Properties
UserAuth
Properties
Type Aliases
AddPrefixToKeys
type AddPrefixToKeys<Prefix, T> = { [K in keyof T as `${Prefix}.${string & K}`]: T[K] };
Type Parameters
| Type Parameter |
|---|
Prefix extends string |
T extends Record<string, unknown> |
AggregateFieldType
type AggregateFieldType = "count" | "sum" | "average";
Aggregate-field descriptor returned by count() / sum(field) /
average(field).
AggregateSpec
type AggregateSpec = Record<string, AggregateField>;
Spec passed to getAggregateFromServer(query, spec).
AggregateSpecData
type AggregateSpecData<T> = Record<string, unknown>;
Type Parameters
| Type Parameter |
|---|
T |
AggregateType
type AggregateType = "count" | "sum" | "average";
AppFirestore
type AppFirestore = Firestore & {
app: FirebaseApp;
};
Firestore handle returned by Firebase-shaped app overloads.
Type Declaration
app
readonly app: FirebaseApp;
As
type As = "admin" | UserAuth;
Who a data-plane op runs as. The default (omitted, or the literal 'admin')
is an ADMIN write that BYPASSES rules — the right mode for sandbox seeding.
A { uid, claims? } runs as that user with rules ENFORCED. The point of the
explicit literal: bypass is NAMED (as:'admin'), not the silent consequence
of omitting an auth field, and acting-as-a-user is named too.
AuthState
type AuthState =
| {
token?: Record<string, unknown>;
uid: string;
}
| null;
A signed-in identity for sandbox operations. null is anonymous.
token is the Firebase Auth token claims map (custom claims plus
standard ones). It surfaces the same way it does in production rules
via request.auth.token.*. Omit it for plain UID-only auth.
Renamed from AuthContext (pre-multi-context) so the data type
doesn’t visually collide with SandboxContext (the identity-bearing
handle). They sit at different layers — payload vs. handle — and the
names should reflect that.
ChildUpdateFields
type ChildUpdateFields<T> = Record<string, unknown>;
Type Parameters
| Type Parameter |
|---|
T |
DocumentChangeType
type DocumentChangeType = "added" | "removed" | "modified";
DocumentData
type DocumentData = Record<string, unknown>;
FieldValueSentinel
type FieldValueSentinel =
| {
}
| {
value: number;
}
| {
values: unknown[];
}
| {
values: unknown[];
}
| {
};
FirestoreErrorCode
type FirestoreErrorCode =
| "cancelled"
| "unknown"
| "invalid-argument"
| "deadline-exceeded"
| "not-found"
| "already-exists"
| "permission-denied"
| "resource-exhausted"
| "failed-precondition"
| "aborted"
| "out-of-range"
| "unimplemented"
| "internal"
| "unavailable"
| "data-loss"
| "unauthenticated";
FirestoreLocalCache
type FirestoreLocalCache = LocalCache;
ListenSource
type ListenSource = "default" | "cache";
LogLevel
type LogLevel = "debug" | "verbose" | "info" | "warn" | "error" | "silent";
Mirrors firebase/firestore’s LogLevel union.
MemoryEagerGarbageCollector
type MemoryEagerGarbageCollector = MemoryGarbageCollector & {
[GC_SYMBOL]: "eager";
};
Type Declaration
[GC_SYMBOL]
readonly [GC_SYMBOL]: "eager";
MemoryLocalCache
type MemoryLocalCache = LocalCache & {
[LOCAL_CACHE_SYMBOL]: "memory";
};
Type Declaration
[LOCAL_CACHE_SYMBOL]
readonly [LOCAL_CACHE_SYMBOL]: "memory";
MemoryLruGarbageCollector
type MemoryLruGarbageCollector = MemoryGarbageCollector & {
[GC_SYMBOL]: "lru";
};
Type Declaration
[GC_SYMBOL]
readonly [GC_SYMBOL]: "lru";
NestedUpdateFields
type NestedUpdateFields<T> = Record<string, unknown>;
Type Parameters
| Type Parameter |
|---|
T |
OrderByDirection
type OrderByDirection = "asc" | "desc";
OrderDirection
type OrderDirection = QueryOrderDirection;
PartialWithFieldValue
type PartialWithFieldValue<T> = Partial<T> | Record<string, unknown>;
Type Parameters
| Type Parameter |
|---|
T |
PersistentLocalCache
type PersistentLocalCache = LocalCache & {
[LOCAL_CACHE_SYMBOL]: "persistent";
};
Type Declaration
[LOCAL_CACHE_SYMBOL]
readonly [LOCAL_CACHE_SYMBOL]: "persistent";
PersistentMultipleTabManager
type PersistentMultipleTabManager = PersistentTabManager & {
[TAB_MANAGER_SYMBOL]: "multiple";
};
Type Declaration
[TAB_MANAGER_SYMBOL]
readonly [TAB_MANAGER_SYMBOL]: "multiple";
PersistentSingleTabManager
type PersistentSingleTabManager = PersistentTabManager & {
[TAB_MANAGER_SYMBOL]: "single";
};
Type Declaration
[TAB_MANAGER_SYMBOL]
readonly [TAB_MANAGER_SYMBOL]: "single";
Primitive
type Primitive = string | number | boolean | bigint | symbol | undefined | null;
QueryConstraintType
type QueryConstraintType =
| "where"
| "orderBy"
| "limit"
| "limitToLast"
| "startAt"
| "startAfter"
| "endAt"
| "endBefore"
| "or"
| "and";
QueryFilterConstraint
type QueryFilterConstraint = any;
QueryNonFilterConstraint
type QueryNonFilterConstraint = any;
TaskState
type TaskState = "Error" | "Running" | "Success";
UnionToIntersection
type UnionToIntersection<U> = U extends any ? (k: U) => void : never extends (k: infer I) => void ? I : never;
Type Parameters
| Type Parameter |
|---|
U |
Unsubscribe()
type Unsubscribe = () => void;
Returns
void
UpdateData
type UpdateData<T> = { [path in string]: unknown };
Type Parameters
| Type Parameter |
|---|
T |
WhereFilterOp
type WhereFilterOp = QueryWhereFilterOp;
WithFieldValue
type WithFieldValue<T> = T | Record<string, unknown>;
Type Parameters
| Type Parameter |
|---|
T |
Variables
CACHE_SIZE_UNLIMITED
const CACHE_SIZE_UNLIMITED: -1 = -1;
TARGET_SYMBOL
const TARGET_SYMBOL: unique symbol;
Hidden property on every Firestore handle. Discriminates the sandbox backend so free functions can recover their owner.
Functions
actingAs()
function actingAs(sandbox: Sandbox, identity: {
token?: Record<string, unknown>;
uid: string;
}): Firestore;
A Firestore handle scoped to a specific identity, for multi-user testing.
actingAs(sandbox, { uid }) returns a Firestore whose ops evaluate security
rules as that user (request.auth.uid === uid; custom claims via token);
actingAs(sandbox, null) is the anonymous (signed-out) path. Multiple
identities over ONE sandbox share the same store, so a write by one is
delivered to another’s onSnapshot: the basis for multi-user sync testing.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
identity | { token?: Record<string, unknown>; uid: string; } |
identity.token? | Record<string, unknown> |
identity.uid | string |
Returns
Example
import { initializeSandbox } from 'pyric/sandbox';
import { actingAs, doc, setDoc, onSnapshot } from 'pyric/firestore';
const sandbox = initializeSandbox();
const alice = actingAs(sandbox, { uid: 'alice' });
const bob = actingAs(sandbox, { uid: 'bob', token: { role: 'member' } });
onSnapshot(doc(bob, 'rooms/r1'), () => {
// fires when alice writes (same store; rules evaluated as bob)
});
await setDoc(doc(alice, 'rooms/r1'), { owner: 'alice' });
Thin sugar over getFirestore(sandbox.withAuth(identity)); the value is a
named, discoverable seam for multi-user scenarios. See
the design rationale.
addDoc()
function addDoc<T>(coll: CollectionReference<T>, data: T): Promise<DocumentReference<T>>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
coll | CollectionReference<T> |
data | T |
Returns
Promise<DocumentReference<T>>
aggregateFieldEqual()
function aggregateFieldEqual(a: any, b: any): boolean;
Parameters
| Parameter | Type |
|---|---|
a | any |
b | any |
Returns
boolean
aggregateQuerySnapshotEqual()
function aggregateQuerySnapshotEqual(a: any, b: any): boolean;
Parameters
| Parameter | Type |
|---|---|
a | any |
b | any |
Returns
boolean
and()
function and(...filters: QueryConstraint[]): QueryConstraint;
AND composite. Same shape as or() but every inner constraint
must match. Useful inside an or() to combine constraints that
would otherwise be at the top level.
Parameters
| Parameter | Type |
|---|---|
…filters | QueryConstraint[] |
Returns
arrayRemove()
function arrayRemove(...values: unknown[]): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
arrayUnion()
function arrayUnion(...values: unknown[]): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
average()
function average(field: string): AggregateField;
Factory: average-of-field aggregate.
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
clearIndexedDbPersistence()
function clearIndexedDbPersistence(db: Firestore): Promise<void>;
Sandbox: actually clears the sandbox’s persisted store via
Sandbox.clearPersistence() — the honest mapping, not a no-op. This
wipes the persisted blob (IndexedDB, or whatever backend
enablePersistence was configured with) while leaving in-memory
state untouched, matching clearPersistence’s own contract. It is
ALREADY a no-op when persistence was never enabled, so callers that
invoke this defensively at startup are safe either way.
getFirestore(ctx) (frozen SandboxContext) targets don’t carry a
live Sandbox handle with a clearPersistence method reachable the
same way as a sandbox/sandbox-live target’s .sandbox field —
both variants do, in fact, so this always has a sandbox to call into.
The real SDK requires this before Firestore starts; the sandbox’s mapped
clearPersistence() has no such restriction.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
collection()
function collection(parent:
| Firestore
| DocumentReference<DocumentData>, ...pathSegments: string[]): CollectionReference;
Parameters
| Parameter | Type |
|---|---|
parent | | Firestore | DocumentReference<DocumentData> |
…pathSegments | string[] |
Returns
collectionGroup()
function collectionGroup(db: Firestore, collectionId: string): Query;
Cross-collection query — scans every document under every
collection whose final segment matches collectionId. Mirrors
firebase/firestore’s collectionGroup(db, id) shape.
Returned Query accepts the same where / orderBy / limit
constraints as any other query.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
collectionId | string |
Returns
connectFirestoreEmulator()
function connectFirestoreEmulator(
db: Firestore,
host: string,
port: number,
options?: {
mockUserToken?: | string
| {
[claim: string]: unknown;
firebase?: {
identities?: Record<string, string[]>;
sign_in_provider?: string;
};
sub?: string;
user_id?: string;
};
}): void;
No-op in the sandbox mirror because the sandbox already runs locally.
The option shape remains source-compatible with Firebase so canonical initialization code can call it unconditionally.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
host | string |
port | number |
options? | { mockUserToken?: | string | { [claim: string]: unknown; firebase?: { identities?: Record<string, string[]>; sign_in_provider?: string; }; sub?: string; user_id?: string; }; } |
options.mockUserToken? | | string | { [claim: string]: unknown; firebase?: { identities?: Record<string, string[]>; sign_in_provider?: string; }; sub?: string; user_id?: string; } |
Returns
void
count()
function count(): AggregateField;
Factory: count() aggregate.
Returns
createFirestoreDataTools()
function createFirestoreDataTools(deps: FirestoreDataToolDeps): ToolHandler<unknown, unknown>[];
Modular Web-SDK-shaped Firestore data tools — get, list, create,
update, delete. Each tool’s auth arg is forwarded to the
resolver; omitted = admin mode, supplied = user mode.
Parameters
| Parameter | Type |
|---|---|
deps | FirestoreDataToolDeps |
Returns
ToolHandler<unknown, unknown>[]
createFirestoreInspectTools()
function createFirestoreInspectTools(deps: FirestoreInspectToolDeps): ToolHandler<unknown, unknown>[];
sandbox_inspect — the missing-tool tax this entire library
used to charge agents. Without it, debugging “why aren’t my rules
working?” took 51 tool calls + 72k tokens of grepping node_modules
(recorded in CLAUDE_DEBUG_SESSION.md). With it, the same diagnosis
is one tool call:
{ rules: { source, sizeBytes, isEmpty, lint: { errors, warnings, findings } }, documents: { totalCount, byCollection }, events: { totalCount, recentDenials, recentRequests } }
Returns a snapshot of sandbox state — current rules, lint summary, document census by collection, and the most-recent denials + requests from sandbox.history(). Everything an agent needs to localize a sandbox bug in one round-trip.
Sandbox-only. resolveSandbox must return the owning Sandbox.
Parameters
| Parameter | Type |
|---|---|
deps | FirestoreInspectToolDeps |
Returns
ToolHandler<unknown, unknown>[]
deleteAllPersistentCacheIndexes()
function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
indexManager | PersistentCacheIndexManager |
Returns
Promise<void>
deleteDoc()
function deleteDoc(ref: DocumentReference): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
Returns
Promise<void>
deleteField()
function deleteField(): FieldValueSentinel;
Returns
disableNetwork()
function disableNetwork(db: Firestore): Promise<void>;
Sandbox: no-op success. There is no network in the sandbox — every op is a local call into the in-memory/IndexedDB-backed store — so there is nothing to disable. This deliberately does NOT simulate an offline mode: queued writes still commit immediately rather than queuing, because the sandbox cannot honestly deliver “queued until reconnected” when there is no connection to lose in the first place. App code that calls this to prep for flaky connectivity will not crash, but it also will not observe write-queuing behavior.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
disablePersistentCacheIndexAutoCreation()
function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
indexManager | PersistentCacheIndexManager |
Returns
Promise<void>
doc()
function doc<T>(parent:
| Firestore
| CollectionReference<T>, ...pathSegments: string[]): DocumentReference<T>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
parent | | Firestore | CollectionReference<T> |
…pathSegments | string[] |
Returns
documentId()
function documentId(): FieldPath;
Returns
documentSnapshotFromJSON()
function documentSnapshotFromJSON(db: Firestore, json: string): DocumentSnapshot;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
json | string |
Returns
enableIndexedDbPersistence()
function enableIndexedDbPersistence(db: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;
Enables the persistence lifecycle before first use. As in the browser SDK,
initialization after another Firestore operation rejects with
failed-precondition.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
persistenceSettings? | PersistenceSettings |
Returns
Promise<void>
enableMultiTabIndexedDbPersistence()
function enableMultiTabIndexedDbPersistence(db: Firestore): Promise<void>;
Sandbox: no-op success, same rationale as enableIndexedDbPersistence. Multi-tab coordination is meaningless here too: the sandbox’s SharedWorker path already IS the single shared store every tab talks to, so there’s no separate “multi-tab” mode to opt into.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
enableNetwork()
function enableNetwork(db: Firestore): Promise<void>;
Sandbox: no-op success, symmetric with disableNetwork — since network was never disabled locally, there is nothing to re-enable.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
enablePersistentCacheIndexAutoCreation()
function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
indexManager | PersistentCacheIndexManager |
Returns
Promise<void>
endAt()
Call Signature
function endAt(snapshot: DocumentSnapshot): QueryConstraint;
End the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included.
Parameters
| Parameter | Type |
|---|---|
snapshot | DocumentSnapshot |
Returns
Call Signature
function endAt(...values: unknown[]): QueryConstraint;
End the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included.
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
endBefore()
Call Signature
function endBefore(snapshot: DocumentSnapshot): QueryConstraint;
Same as endAt, but EXCLUDES the document at the cursor — the
result ends at the prior ordered position.
Parameters
| Parameter | Type |
|---|---|
snapshot | DocumentSnapshot |
Returns
Call Signature
function endBefore(...values: unknown[]): QueryConstraint;
Same as endAt, but EXCLUDES the document at the cursor — the
result ends at the prior ordered position.
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
ensureFirestoreConfigured()
function ensureFirestoreConfigured(db: Firestore): void;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
void
executeWrite()
function executeWrite<T>(db: Firestore, action: (batch: WriteBatch) => Promise<T>): Promise<T>;
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
action | (batch: WriteBatch) => Promise<T> |
Returns
Promise<T>
getAdminFirestore()
Call Signature
function getAdminFirestore(sandbox: Sandbox): Firestore;
Construct a rules-bypassing sandbox Firestore handle — the Pyric
Studio admin lens (Gap #2). Every modular op issued against the returned
handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/
count/writeBatch/runTransaction) SKIPS security-rule evaluation and
is treated as ALLOW, while still going through the same store + emitting
the same events + waking the same listeners. This is the modular sibling
of the path-string sandbox.admin.* bypass; it reuses the underlying
LocalEnvironment bypass execution path (the bypassRules op flag),
not a parallel reimplementation.
Sandbox-only. There is no prod analog (you cannot bypass deployed
security rules from a client), so this overload set accepts only a
Sandbox, SandboxContext, or a privately-associated FirebaseApp.
Admin ops are identity-agnostic (rules are off), so the
handle is a FROZEN sandbox target: it does not track
sandbox.currentUser.
Intended for Studio’s “edit anything as admin” surfaces (F2) and the
serve worker’s { mode: 'admin' } auth lens. For rules-applied
impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules
Call Signature
function getAdminFirestore(ctx: SandboxContext): Firestore;
Construct a rules-bypassing sandbox Firestore handle — the Pyric
Studio admin lens (Gap #2). Every modular op issued against the returned
handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/
count/writeBatch/runTransaction) SKIPS security-rule evaluation and
is treated as ALLOW, while still going through the same store + emitting
the same events + waking the same listeners. This is the modular sibling
of the path-string sandbox.admin.* bypass; it reuses the underlying
LocalEnvironment bypass execution path (the bypassRules op flag),
not a parallel reimplementation.
Sandbox-only. There is no prod analog (you cannot bypass deployed
security rules from a client), so this overload set accepts only a
Sandbox, SandboxContext, or a privately-associated FirebaseApp.
Admin ops are identity-agnostic (rules are off), so the
handle is a FROZEN sandbox target: it does not track
sandbox.currentUser.
Intended for Studio’s “edit anything as admin” surfaces (F2) and the
serve worker’s { mode: 'admin' } auth lens. For rules-applied
impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.
Parameters
| Parameter | Type |
|---|---|
ctx | SandboxContext |
Returns
Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules
Call Signature
function getAdminFirestore(app: FirebaseApp): Firestore;
Construct a rules-bypassing sandbox Firestore handle — the Pyric
Studio admin lens (Gap #2). Every modular op issued against the returned
handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/
count/writeBatch/runTransaction) SKIPS security-rule evaluation and
is treated as ALLOW, while still going through the same store + emitting
the same events + waking the same listeners. This is the modular sibling
of the path-string sandbox.admin.* bypass; it reuses the underlying
LocalEnvironment bypass execution path (the bypassRules op flag),
not a parallel reimplementation.
Sandbox-only. There is no prod analog (you cannot bypass deployed
security rules from a client), so this overload set accepts only a
Sandbox, SandboxContext, or a privately-associated FirebaseApp.
Admin ops are identity-agnostic (rules are off), so the
handle is a FROZEN sandbox target: it does not track
sandbox.currentUser.
Intended for Studio’s “edit anything as admin” surfaces (F2) and the
serve worker’s { mode: 'admin' } auth lens. For rules-applied
impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.
Parameters
| Parameter | Type |
|---|---|
app | FirebaseApp |
Returns
Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules
getAggregateFromServer()
function getAggregateFromServer<S>(source:
| Query<DocumentData>
| CollectionReference<DocumentData>, spec: S): Promise<AggregateQuerySnapshot<{ [K in string | number | symbol]: number }>>;
Run a multi-field aggregate against the query. Spec entries are
keyed by caller-chosen aliases; the returned snapshot’s .data()
uses the same keys.
The sandbox target dispatches straight into the chainable adapter.
Type Parameters
| Type Parameter |
|---|
S extends AggregateSpec |
Parameters
| Parameter | Type |
|---|---|
source | | Query<DocumentData> | CollectionReference<DocumentData> |
spec | S |
Returns
Promise<AggregateQuerySnapshot<{ [K in string | number | symbol]: number }>>
getCountFromServer()
function getCountFromServer(source:
| Query<DocumentData>
| CollectionReference<DocumentData>): Promise<AggregateQuerySnapshot<{
count: number;
}>>;
Count documents matching the query. Returns a snapshot whose
.data() yields { count: N } — same shape firebase/firestore’s
getCountFromServer produces.
Parameters
| Parameter | Type |
|---|---|
source | | Query<DocumentData> | CollectionReference<DocumentData> |
Returns
Promise<AggregateQuerySnapshot<{
count: number;
}>>
getDoc()
function getDoc<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<T> |
Returns
Promise<DocumentSnapshot<T>>
getDocFromCache()
function getDocFromCache<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
Sandbox: delegates to getDoc. Real Firebase THROWS
'unavailable' here on a cache miss (nothing local matches the
ref); pyric never misses — the local store always has whatever is
there — so this never throws for that reason. Documented divergence,
not a claim of parity.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<T> |
Returns
Promise<DocumentSnapshot<T>>
getDocFromServer()
function getDocFromServer<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
Sandbox: delegates to getDoc. The sandbox store IS the authoritative, always-fresh source — there is no separate server round-trip to force, so “from server” and the default read are the same honest thing.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<T> |
Returns
Promise<DocumentSnapshot<T>>
getDocs()
function getDocs<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
query | Query<T> |
Returns
Promise<QuerySnapshot<T>>
getDocsFromCache()
function getDocsFromCache<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
Query-plural form of getDocFromCache — same cache-miss divergence.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
query | Query<T> |
Returns
Promise<QuerySnapshot<T>>
getDocsFromServer()
function getDocsFromServer<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
Query-plural form of getDocFromServer.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
query | Query<T> |
Returns
Promise<QuerySnapshot<T>>
getFirestore()
Call Signature
function getFirestore(ctx: SandboxContext): Firestore;
Construct a Firestore handle. Three overloads dispatch by the input’s shape:
SandboxContext→ sandbox-backed Firestore with a frozen identity (the ctx’sauthchosen atgetFirestoretime). Best for runner/test code that names identity explicitly per scenario.Sandbox→ sandbox-backed Firestore that readssandbox.currentUserper-call. Best for app code that drives identity throughpyric/auth— every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
| Parameter | Type |
|---|---|
ctx | SandboxContext |
Returns
Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));
// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth); // subsequent db ops use the new identity
// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);
Call Signature
function getFirestore(sandbox: Sandbox): Firestore;
Construct a Firestore handle. Three overloads dispatch by the input’s shape:
SandboxContext→ sandbox-backed Firestore with a frozen identity (the ctx’sauthchosen atgetFirestoretime). Best for runner/test code that names identity explicitly per scenario.Sandbox→ sandbox-backed Firestore that readssandbox.currentUserper-call. Best for app code that drives identity throughpyric/auth— every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));
// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth); // subsequent db ops use the new identity
// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);
Call Signature
function getFirestore(app: FirebaseApp): AppFirestore;
Construct a Firestore handle. Three overloads dispatch by the input’s shape:
SandboxContext→ sandbox-backed Firestore with a frozen identity (the ctx’sauthchosen atgetFirestoretime). Best for runner/test code that names identity explicitly per scenario.Sandbox→ sandbox-backed Firestore that readssandbox.currentUserper-call. Best for app code that drives identity throughpyric/auth— every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
| Parameter | Type |
|---|---|
app | FirebaseApp |
Returns
Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));
// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth); // subsequent db ops use the new identity
// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);
Call Signature
function getFirestore(): AppFirestore;
Construct a Firestore handle. Three overloads dispatch by the input’s shape:
SandboxContext→ sandbox-backed Firestore with a frozen identity (the ctx’sauthchosen atgetFirestoretime). Best for runner/test code that names identity explicitly per scenario.Sandbox→ sandbox-backed Firestore that readssandbox.currentUserper-call. Best for app code that drives identity throughpyric/auth— every Firestore op evaluates rules under whatever user is currently signed in.
Returns
Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));
// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth); // subsequent db ops use the new identity
// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);
Call Signature
function getFirestore(target?:
| FirebaseApp
| Sandbox
| SandboxContext): Firestore;
Construct a Firestore handle. Three overloads dispatch by the input’s shape:
SandboxContext→ sandbox-backed Firestore with a frozen identity (the ctx’sauthchosen atgetFirestoretime). Best for runner/test code that names identity explicitly per scenario.Sandbox→ sandbox-backed Firestore that readssandbox.currentUserper-call. Best for app code that drives identity throughpyric/auth— every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
| Parameter | Type |
|---|---|
target? | | FirebaseApp | Sandbox | SandboxContext |
Returns
Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));
// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth); // subsequent db ops use the new identity
// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);
getPersistentCacheIndexManager()
function getPersistentCacheIndexManager(db: Firestore): PersistentCacheIndexManager;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
increment()
function increment(n: number): FieldValueSentinel;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
initializeFirestore()
function initializeFirestore(
app:
| FirebaseApp
| Sandbox
| SandboxContext,
_settings?: FirestoreSettings,
_databaseId?: string): Firestore;
Delegates to getFirestore and returns the same handle. Accepts
the settings argument (so the explicit-init pattern app code commonly
writes — initializeFirestore(app, { localCache: persistentLocalCache(...) } )
— no longer crashes at import) but no-ops the cache/network settings:
persistence is already the sandbox default, so there is nothing left to
configure into existence.
Parameters
| Parameter | Type |
|---|---|
app | | FirebaseApp | Sandbox | SandboxContext |
_settings? | FirestoreSettings |
_databaseId? | string |
Returns
limit()
function limit(n: number): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
limitToLast()
function limitToLast(n: number): QueryConstraint;
Limit the query to the LAST n documents in the ordered result.
Requires at least one orderBy on the query (production-aligned —
the simulator throws at execute time without one).
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
loadBundle()
function loadBundle(db: Firestore, bundleData:
| string
| ArrayBuffer
| ReadableStream<Uint8Array<ArrayBufferLike>>): LoadBundleTask;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
bundleData | | string | ArrayBuffer | ReadableStream<Uint8Array<ArrayBufferLike>> |
Returns
memoryEagerGarbageCollector()
function memoryEagerGarbageCollector(): MemoryGarbageCollector;
Inert config token accepted by memoryLocalCache’s garbageCollector.
Returns
memoryLocalCache()
function memoryLocalCache(settings?: {
garbageCollector?: MemoryGarbageCollector;
}): LocalCache;
Inert config token — the memory-cache counterpart of persistentLocalCache.
Parameters
| Parameter | Type |
|---|---|
settings? | { garbageCollector?: MemoryGarbageCollector; } |
settings.garbageCollector? | MemoryGarbageCollector |
Returns
memoryLruGarbageCollector()
function memoryLruGarbageCollector(_settings?: {
cacheSizeBytes?: number;
}): MemoryGarbageCollector;
Inert config token accepted by memoryLocalCache’s garbageCollector.
Parameters
| Parameter | Type |
|---|---|
_settings? | { cacheSizeBytes?: number; } |
_settings.cacheSizeBytes? | number |
Returns
namedQuery()
function namedQuery(db: Firestore, name: string): Promise<Query<DocumentData>>;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
name | string |
Returns
Promise<Query<DocumentData>>
onSnapshot()
Call Signature
function onSnapshot<T>(
ref: T,
observerOrNext:
| SnapshotObserver<unknown>
| (snap: unknown) => void,
errorOrNothing?: (error: unknown) => void): Unsubscribe;
Type Parameters
| Type Parameter |
|---|
T extends | DocumentReference<DocumentData> | Query<DocumentData> |
Parameters
| Parameter | Type |
|---|---|
ref | T |
observerOrNext | | SnapshotObserver<unknown> | (snap: unknown) => void |
errorOrNothing? | (error: unknown) => void |
Returns
Call Signature
function onSnapshot<T>(
ref: T,
options: SnapshotListenOptions,
observerOrNext:
| SnapshotObserver<unknown>
| (snap: unknown) => void,
errorOrNothing?: (error: unknown) => void): Unsubscribe;
Type Parameters
| Type Parameter |
|---|
T extends | DocumentReference<DocumentData> | Query<DocumentData> |
Parameters
| Parameter | Type |
|---|---|
ref | T |
options | SnapshotListenOptions |
observerOrNext | | SnapshotObserver<unknown> | (snap: unknown) => void |
errorOrNothing? | (error: unknown) => void |
Returns
onSnapshotResume()
function onSnapshotResume(
query: Query,
snapshot: QuerySnapshot,
observerOrNext: unknown,
error?: unknown,
complete?: unknown): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
query | Query |
snapshot | QuerySnapshot |
observerOrNext | unknown |
error? | unknown |
complete? | unknown |
Returns
onSnapshotsInSync()
function onSnapshotsInSync(db: Firestore, observerOrCallback:
| () => void
| {
complete?: () => void;
error?: (error: unknown) => void;
next?: () => void;
}): Unsubscribe;
Registers a service-scoped synchronization observer. It receives an initial signal and a batched signal after snapshot listeners deliver their latest local state, matching the production-observed callback ordering.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
observerOrCallback | | () => void | { complete?: () => void; error?: (error: unknown) => void; next?: () => void; } |
Returns
or()
function or(...filters: QueryConstraint[]): QueryConstraint;
OR composite — at least one of the inner constraints must match.
Each argument must itself be a filter constraint (where(), or
nested or() / and()); passing orderBy() or limit() here is
a type error at runtime.
Mirrors firebase/firestore’s or(...filters) shape.
Parameters
| Parameter | Type |
|---|---|
…filters | QueryConstraint[] |
Returns
orderBy()
function orderBy(field: string | FieldPath, direction?: QueryOrderDirection): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
field | string | FieldPath |
direction? | QueryOrderDirection |
Returns
persistentLocalCache()
function persistentLocalCache(settings?: {
cacheSizeBytes?: number;
tabManager?: PersistentTabManager;
}): LocalCache;
Inert config token. Real Firebase uses this to select an on-disk,
persistent IndexedDB cache tier; the sandbox has no separate cache
tier — persistence is already the default — so this just returns a
tagged token initializeFirestore can accept without crashing.
Parameters
| Parameter | Type |
|---|---|
settings? | { cacheSizeBytes?: number; tabManager?: PersistentTabManager; } |
settings.cacheSizeBytes? | number |
settings.tabManager? | PersistentTabManager |
Returns
persistentMultipleTabManager()
function persistentMultipleTabManager(): PersistentTabManager;
Inert config token accepted by persistentLocalCache’s tabManager.
Returns
persistentSingleTabManager()
function persistentSingleTabManager(_settings?: {
forceOwnership?: boolean;
}): PersistentTabManager;
Inert config token accepted by persistentLocalCache’s tabManager.
Parameters
| Parameter | Type |
|---|---|
_settings? | { forceOwnership?: boolean; } |
_settings.forceOwnership? | boolean |
Returns
query()
function query<T>(source:
| CollectionReference<T>
| Query<T>, ...constraints: QueryConstraint[]): Query<T>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
source | | CollectionReference<T> | Query<T> |
…constraints | QueryConstraint[] |
Returns
Query<T>
queryEqual()
function queryEqual(a: Query, b: Query): boolean;
Parameters
Returns
boolean
querySnapshotFromJSON()
function querySnapshotFromJSON(db: Firestore, json: string): QuerySnapshot;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
json | string |
Returns
refEqual()
function refEqual(a: DocumentReference, b: DocumentReference): boolean;
Parameters
| Parameter | Type |
|---|---|
a | DocumentReference |
b | DocumentReference |
Returns
boolean
runTransaction()
function runTransaction<R>(
db: Firestore,
fn: (tx: Transaction) => R | Promise<R>,
options?: TransactionOptions): Promise<R>;
Type Parameters
| Type Parameter |
|---|
R |
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
fn | (tx: Transaction) => R | Promise<R> |
options? | TransactionOptions |
Returns
Promise<R>
serverTimestamp()
function serverTimestamp(): FieldValueSentinel;
Returns
setDoc()
function setDoc<T>(
ref: DocumentReference<T>,
data: T,
options?: SetOptions): Promise<void>;
Type Parameters
| Type Parameter | Default type |
|---|---|
T | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<T> |
data | T |
options? | SetOptions |
Returns
Promise<void>
setIndexConfiguration()
function setIndexConfiguration(db: Firestore, configuration: string | IndexConfiguration): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
configuration | string | IndexConfiguration |
Returns
Promise<void>
setLogLevel()
function setLogLevel(logLevel: LogLevel): void;
Accepted no-op: the sandbox has no modular-SDK-style logger to wire
a level into (it uses host-level console logging directly, gated
by pyric dev’s own flags, not this call). Exists purely so app
code that calls this defensively at startup doesn’t crash on a
missing export.
Parameters
| Parameter | Type |
|---|---|
logLevel | LogLevel |
Returns
void
snapshotEqual()
function snapshotEqual(a:
| DocumentSnapshot<DocumentData>
| QuerySnapshot<DocumentData>, b:
| DocumentSnapshot<DocumentData>
| QuerySnapshot<DocumentData>): boolean;
Parameters
| Parameter | Type |
|---|---|
a | | DocumentSnapshot<DocumentData> | QuerySnapshot<DocumentData> |
b | | DocumentSnapshot<DocumentData> | QuerySnapshot<DocumentData> |
Returns
boolean
startAfter()
Call Signature
function startAfter(snapshot: DocumentSnapshot): QueryConstraint;
Same as startAt, but EXCLUDES the document at the cursor — the
result starts at the next ordered position.
Parameters
| Parameter | Type |
|---|---|
snapshot | DocumentSnapshot |
Returns
Call Signature
function startAfter(...values: unknown[]): QueryConstraint;
Same as startAt, but EXCLUDES the document at the cursor — the
result starts at the next ordered position.
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
startAt()
Call Signature
function startAt(snapshot: DocumentSnapshot): QueryConstraint;
Start the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included in the result. Two overloads:
startAt(snapshot) — values come from snapshot.data() indexed
by the query’s orderBy fields.
startAt(...values) — explicit positional values (one per
orderBy clause).
Parameters
| Parameter | Type |
|---|---|
snapshot | DocumentSnapshot |
Returns
Call Signature
function startAt(...values: unknown[]): QueryConstraint;
Start the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included in the result. Two overloads:
startAt(snapshot) — values come from snapshot.data() indexed
by the query’s orderBy fields.
startAt(...values) — explicit positional values (one per
orderBy clause).
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
sum()
function sum(field: string): AggregateField;
Factory: sum-of-field aggregate.
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
terminate()
function terminate(db: Firestore): Promise<void>;
Terminates this Firestore service target only. Held references become unusable and owned listeners stop, while sibling Firestore handles and other services on the same Sandbox remain alive.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
updateDoc()
function updateDoc(ref: DocumentReference, data: DocumentData): Promise<void>;
updateDoc does NOT run the converter. Matches firebase/firestore’s
Web SDK shape — partial updates can target any subset of fields, so
a translator built around a full AppModelType would be a type-shape
mismatch. Use the underlying DocumentData view (withConverter(ref, null)) for typed-and-untyped mixed access if you need both styles
against the same path.
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference |
data | DocumentData |
Returns
Promise<void>
vector()
function vector(values?: number[]): VectorValue;
Parameters
| Parameter | Type |
|---|---|
values? | number[] |
Returns
waitForPendingWrites()
function waitForPendingWrites(db: Firestore): Promise<void>;
Resolves after writes that were issued while offline receive their modeled acknowledgement on reconnect.
Parameters
| Parameter | Type |
|---|---|
db | Firestore |
Returns
Promise<void>
where()
function where(
field: string | FieldPath,
op: QueryWhereFilterOp,
value: unknown): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
field | string | FieldPath |
op | QueryWhereFilterOp |
value | unknown |
Returns
withConverter()
Call Signature
function withConverter<AppModel, DbModel>(ref: DocumentReference<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): DocumentReference<AppModel>;
Type Parameters
| Type Parameter | Default type |
|---|---|
AppModel | - |
DbModel extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<DocumentData> |
converter | FirestoreDataConverter<AppModel, DbModel> |
Returns
DocumentReference<AppModel>
Call Signature
function withConverter(ref: DocumentReference<unknown>, converter: null): DocumentReference<DocumentData>;
Parameters
| Parameter | Type |
|---|---|
ref | DocumentReference<unknown> |
converter | null |
Returns
DocumentReference<DocumentData>
Call Signature
function withConverter<AppModel, DbModel>(ref: CollectionReference<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): CollectionReference<AppModel>;
Type Parameters
| Type Parameter | Default type |
|---|---|
AppModel | - |
DbModel extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
ref | CollectionReference<DocumentData> |
converter | FirestoreDataConverter<AppModel, DbModel> |
Returns
CollectionReference<AppModel>
Call Signature
function withConverter(ref: CollectionReference<unknown>, converter: null): CollectionReference<DocumentData>;
Parameters
| Parameter | Type |
|---|---|
ref | CollectionReference<unknown> |
converter | null |
Returns
CollectionReference<DocumentData>
Call Signature
function withConverter<AppModel, DbModel>(q: Query<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): Query<AppModel>;
Type Parameters
| Type Parameter | Default type |
|---|---|
AppModel | - |
DbModel extends DocumentData | DocumentData |
Parameters
| Parameter | Type |
|---|---|
q | Query<DocumentData> |
converter | FirestoreDataConverter<AppModel, DbModel> |
Returns
Query<AppModel>
Call Signature
function withConverter(q: Query<unknown>, converter: null): Query<DocumentData>;
Parameters
| Parameter | Type |
|---|---|
q | Query<unknown> |
converter | null |
Returns
writeBatch()
function writeBatch(db: Firestore): WriteBatch;
Parameters
| Parameter | Type |
|---|---|
db | Firestore |