Pyric
Navigate

API reference

pyric/database

67 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

Database

Opaque RTDB handle. Routes via TARGET_SYMBOL.

Constructors

Constructor
new Database(target?: Target, app?: FirebaseApp): Database;
Parameters
ParameterType
target?Target
app?FirebaseApp
Returns

Database

Properties

PropertyModifierTypeDefault value
[TARGET_SYMBOL]readonlyTargetundefined
appreadonlyFirebaseAppundefined
typereadonly"database""database"

DataSnapshot

Firebase-shaped RTDB snapshot runtime value.

Extended by

Constructors

Constructor
new DataSnapshot(implementation?: DataSnapshotImplementation): DataSnapshot;
Parameters
ParameterType
implementation?DataSnapshotImplementation
Returns

DataSnapshot

Properties

PropertyModifierType
refreadonlyDatabaseReference

Accessors

key
Get Signature
get key(): string;
Returns

string

priority
Get Signature
get priority(): string | number;
Returns

string | number

size
Get Signature
get size(): number;
Returns

number

Methods

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

DataSnapshot

exists()
exists(): boolean;
Returns

boolean

exportVal()
exportVal(): JsonValue;
Returns

JsonValue

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

boolean

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

boolean

hasChildren()
hasChildren(): boolean;
Returns

boolean

toJSON()
toJSON(): JsonValue;
Returns

JsonValue

val()
val(): JsonValue;
Returns

JsonValue


OnDisconnect

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>


QueryConstraint

Opaque constraint produced by the order/filter/limit query functions.

Constructors

Constructor
new QueryConstraint(type?: QueryConstraintType, internal?: Constraint): QueryConstraint;
Parameters
ParameterType
type?QueryConstraintType
internal?Constraint
Returns

QueryConstraint

Properties

PropertyModifierType
[CONSTRAINT_SYMBOL]readonlyConstraint
typereadonlyQueryConstraintType

TransactionResult

Result of runTransaction. Matches firebase/database’s TransactionResult for the fields agent / playground code reads idiomatically.

committed === false when the update fn aborted by returning undefined. The snapshot still resolves — it reflects the pre- transaction value (oracle: rtdb-modular-runtransaction-abort-undefined.jsonafterValOnServer: 100 preserved).

On rule denial the promise rejects with a plain Error whose message === 'permission_denied' (lowercase, no .code); see rtdb-modular-runtransaction-on-rules-denied-path.json.

Constructors

Constructor
new TransactionResult(committed?: boolean, snapshot?: DataSnapshot): TransactionResult;
Parameters
ParameterType
committed?boolean
snapshot?DataSnapshot
Returns

TransactionResult

Properties

PropertyModifierType
committedreadonlyboolean
snapshotreadonlyDataSnapshot

Methods

toJSON()
toJSON(): {
  committed: boolean;
  snapshot: JsonValue;
};
Returns
{
  committed: boolean;
  snapshot: JsonValue;
}
committed
committed: boolean;
snapshot
snapshot: JsonValue;

Interfaces

DatabaseReference

RTDB-shaped reference. Backend-opaque to consumers; mirrors firebase/database’s DatabaseReference for the subset of methods the modular SDK uses idiomatically as plain free-function args.

key is the last path segment (matches DatabaseReference.key). null for the root ref. parent is the ref one segment up (null at root). root is always the root ref.

toString() returns a stable sandbox:// URL.

Extends

Extended by

Properties

PropertyModifierType
[QUERY_SYMBOL]readonlytrue
keyreadonlystring
parentreadonlyDatabaseReference
refreadonlyDatabaseReference
rootreadonlyDatabaseReference

Methods

isEqual()
isEqual(other: Query): boolean;
Parameters
ParameterType
otherQuery
Returns

boolean

Inherited from

Query.isEqual

toJSON()
toJSON(): string;
Returns

string

Inherited from

Query.toJSON

toString()
toString(): string;
Returns

string

Inherited from

Query.toString


DataSnapshotImplementation

Properties

PropertyModifierType
keyreadonlystring
priorityreadonlystring | number
refreadonlyDatabaseReference
sizereadonlynumber

Methods

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

DataSnapshot

exists()
exists(): boolean;
Returns

boolean

exportVal()
exportVal(): JsonValue;
Returns

JsonValue

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

boolean

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

boolean

hasChildren()
hasChildren(): boolean;
Returns

boolean

toJSON()
toJSON(): JsonValue;
Returns

JsonValue

val()
val(): JsonValue;
Returns

JsonValue


IteratedDataSnapshot

Child snapshot supplied during ordered iteration; its key is never null.

Extends

Properties

PropertyModifierTypeOverrides
keyreadonlystringDataSnapshot.key
refreadonlyDatabaseReference-

Accessors

priority
Get Signature
get priority(): string | number;
Returns

string | number

Inherited from

DataSnapshot.priority

size
Get Signature
get size(): number;
Returns

number

Inherited from

DataSnapshot.size

Methods

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

DataSnapshot

Inherited from

DataSnapshot.child

exists()
exists(): boolean;
Returns

boolean

Inherited from

DataSnapshot.exists

exportVal()
exportVal(): JsonValue;
Returns

JsonValue

Inherited from

DataSnapshot.exportVal

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

boolean

Inherited from

DataSnapshot.forEach

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

boolean

Inherited from

DataSnapshot.hasChild

hasChildren()
hasChildren(): boolean;
Returns

boolean

Inherited from

DataSnapshot.hasChildren

toJSON()
toJSON(): JsonValue;
Returns

JsonValue

Inherited from

DataSnapshot.toJSON

val()
val(): JsonValue;
Returns

JsonValue

Inherited from

DataSnapshot.val


ListenOptions

Properties

PropertyModifierType
onlyOnce?readonlyboolean

Query

RTDB-shaped reference. Backend-opaque to consumers; mirrors firebase/database’s DatabaseReference for the subset of methods the modular SDK uses idiomatically as plain free-function args.

key is the last path segment (matches DatabaseReference.key). null for the root ref. parent is the ref one segment up (null at root). root is always the root ref.

toString() returns a stable sandbox:// URL.

Extended by

Properties

PropertyModifierType
[QUERY_SYMBOL]readonlytrue
refreadonlyDatabaseReference

Methods

isEqual()
isEqual(other: Query): boolean;
Parameters
ParameterType
otherQuery
Returns

boolean

toJSON()
toJSON(): string;
Returns

string

toString()
toString(): string;
Returns

string


ThenableReference

The return type of push — a regular DatabaseReference with .then / .catch attached so it can be awaited. Mirrors firebase/database’s ThenableReference (api/Reference_impl.ts:569).

Critical (DB-B7): the ref + its .key are available SYNCHRONOUSLY — the key is minted client-side. The promise covers only the optional value write; a rules-denied write rejects the promise (it does NOT throw synchronously and lose the key). Oracle: rtdb-push-autoid-format.json.

Extends

Properties

PropertyModifierType
[QUERY_SYMBOL]readonlytrue
keyreadonlystring
parentreadonlyDatabaseReference
refreadonlyDatabaseReference
rootreadonlyDatabaseReference

Methods

catch()
catch<TResult>(onrejected?: (reason: unknown) => TResult | PromiseLike<TResult>): Promise<DatabaseReference | TResult>;
Type Parameters
Type ParameterDefault type
TResultnever
Parameters
ParameterType
onrejected?(reason: unknown) => TResult | PromiseLike<TResult>
Returns

Promise<DatabaseReference | TResult>

isEqual()
isEqual(other: Query): boolean;
Parameters
ParameterType
otherQuery
Returns

boolean

Inherited from

DatabaseReference.isEqual

then()
then<TResult1, TResult2>(onfulfilled?: (value: DatabaseReference) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
Type Parameters
Type ParameterDefault type
TResult1DatabaseReference
TResult2never
Parameters
ParameterType
onfulfilled?(value: DatabaseReference) => TResult1 | PromiseLike<TResult1>
onrejected?(reason: unknown) => TResult2 | PromiseLike<TResult2>
Returns

Promise<TResult1 | TResult2>

toJSON()
toJSON(): string;
Returns

string

Inherited from

DatabaseReference.toJSON

toString()
toString(): string;
Returns

string

Inherited from

DatabaseReference.toString


TransactionOptions

Properties

PropertyModifierType
applyLocally?readonlyboolean

Type Aliases

AppDatabase

type AppDatabase = Database & {
  app: FirebaseApp;
};

Database handle returned by Firebase-shaped app overloads.

Type Declaration

app
readonly app: FirebaseApp;

EmulatorMockTokenOptions

type EmulatorMockTokenOptions =
  | {
  user_id: string;
}
  | {
  sub: string;
} & Partial<FirebaseIdTokenShape>;

EventType

type EventType =
  | "value"
  | "child_added"
  | "child_changed"
  | "child_moved"
  | "child_removed";

JsonValue

type JsonValue =
  | null
  | boolean
  | number
  | string
  | JsonValue[]
  | {
[key: string]: JsonValue;
};

RTDB-shaped in-memory JSON tree.

The data layer for the modular SDK’s sandbox target. RTDB stores a single nested JSON tree; reads name a path and walk; writes either replace a subtree (set) or merge top-level keys (update).

Path semantics (matches firebase/database):

  • '/' is the root.
  • Leading + trailing slashes are stripped; empty segments are ignored.
  • null at any level erases that subtree. Locked by oracle observation packages/conformance/observations/rtdb/rtdb-remove-vs-set-null.json which says set(ref, null) and remove(ref) produce equivalent end states.
  • A read of an absent path returns null (NOT an error). Matches the DataSnapshot.val() contract.

Trimming: when a write or delete leaves a sibling-less empty branch, the empty branch is removed. RTDB’s documented invariant: “Empty nodes don’t exist”. The crawl + listener layers count on this so exists() and hasChildren() match prod.

This module is identity-agnostic — rules evaluation happens in local-environment.ts. The tree just stores bytes.


QueryConstraintType

type QueryConstraintType =
  | "orderByChild"
  | "orderByKey"
  | "orderByPriority"
  | "orderByValue"
  | "startAt"
  | "startAfter"
  | "endAt"
  | "endBefore"
  | "equalTo"
  | "limitToFirst"
  | "limitToLast";

Unsubscribe()

type Unsubscribe = () => void;

Returns

void

Variables

CONSTRAINT_SYMBOL

const CONSTRAINT_SYMBOL: unique symbol;

Hidden brand on every QueryConstraint.


QUERY_SYMBOL

const QUERY_SYMBOL: unique symbol;

Hidden brand on every Query.


sandbox

const sandbox: {
  setData: void;
  setRules: void;
  snapshotState: JsonValue;
};

Type Declaration

setData()
setData(db: Database, data: Record<string, unknown>): void;

Bulk-load data bypassing rules. The supplied map’s keys are absolute paths ('/users/alice') and the values land at those paths. Convenient for test fixtures.

Parameters
ParameterType
dbDatabase
dataRecord<string, unknown>
Returns

void

setRules()
setRules(db: Database, rulesJson: {
  rules: Record<string, unknown>;
}): void;

Replace deployed rules. Pass null to clear (sandbox returns to default-allow). Rules are evaluated through the existing RTDB rules simulator — the same engine used by the rules tooling.

Parameters
ParameterType
dbDatabase
rulesJson{ rules: Record<string, unknown>; }
rulesJson.rulesRecord<string, unknown>
Returns

void

Example
sandbox.setRules(db, {
  rules: {
    '.read': 'auth != null',
    '.write': 'auth != null',
  },
});

snapshotState()
snapshotState(db: Database): JsonValue;

Snapshot the full sandbox tree (rule-bypass read). Usually a keyed object; may be a primitive when the root holds one (DB-B13).

Parameters
ParameterType
dbDatabase
Returns

JsonValue


TARGET_SYMBOL

const TARGET_SYMBOL: unique symbol;

Hidden brand on every Database handle.

Functions

buildSandboxRef()

function buildSandboxRef(target: SandboxTarget | SandboxLiveTarget, path: string): DatabaseReference;

Build a sandbox-backed DatabaseReference. Cached parent / root pointers are computed lazily so a long chain doesn’t materialise every intermediate ref upfront.

Parameters

ParameterType
targetSandboxTarget | SandboxLiveTarget
pathstring

Returns

DatabaseReference


child()

function child(parent: DatabaseReference, path: string): DatabaseReference;

Sub-path constructor. child(ref, 'sub/path') returns a ref at <ref>/sub/path.

Mirrors firebase/database’s child(parent, path) — leading + empty segments stripped; the result inherits the parent’s target.

Parameters

ParameterType
parentDatabaseReference
pathstring

Returns

DatabaseReference


connectDatabaseEmulator()

function connectDatabaseEmulator(
   _db: Database,
   _host: string,
   _port: number,
   _options?: {
  mockUserToken?: string | EmulatorMockTokenOptions;
}): void;

connectDatabaseEmulator(db, host, port) is an accepted no-op because the selected backend already is the local sandbox.

Parameters

ParameterType
_dbDatabase
_hoststring
_portnumber
_options?{ mockUserToken?: string | EmulatorMockTokenOptions; }
_options.mockUserToken?string | EmulatorMockTokenOptions

Returns

void


enableLogging()

function enableLogging(logger?: boolean | (message: string) => void, persistent?: boolean): void;

enableLogging(logger?, persistent?) — toggle RTDB SDK logging.

Accepted no-op: the sandbox has no modular-SDK-style logger to wire a level/sink into (it uses host-level console logging directly, gated by pyric dev’s own flags — matching pyric/firestore’s setLogLevel). Accepted so init code that calls it compiles + runs.

Parameters

ParameterType
logger?boolean | (message: string) => void
persistent?boolean

Returns

void


endAt()

function endAt(value: JsonValue, key?: string): QueryConstraint;

endAt(value, key?) — INCLUSIVE upper bound. Adjacent to startAt; same key tie-breaker semantics.

Parameters

ParameterType
valueJsonValue
key?string

Returns

QueryConstraint


endBefore()

function endBefore(value: JsonValue, key?: string): QueryConstraint;

endBefore(value, key?) — EXCLUSIVE upper bound. Locked by rtdb-modular-startafter-endbefore-exclusive.json.

Parameters

ParameterType
valueJsonValue
key?string

Returns

QueryConstraint


equalTo()

function equalTo(value: JsonValue, key?: string): QueryConstraint;

equalTo(value, key?) — sugar for startAt(value, key) + endAt(value, key). Returns ALL matching children (no uniqueness). Locked by oracle observation rtdb-modular-equalTo-filter.json.

Parameters

ParameterType
valueJsonValue
key?string

Returns

QueryConstraint


forceLongPolling()

function forceLongPolling(): void;

forceLongPolling() — force the long-polling transport for all subsequent getDatabase connections.

No-op: transport selection is meaningless to the in-process/worker sandbox, which never opens a real socket. Accepted so init code that calls it unconditionally compiles + runs.

Returns

void


forceWebSockets()

function forceWebSockets(): void;

forceWebSockets() — force the WebSocket transport for all subsequent getDatabase connections.

No-op: transport selection is not applicable to the in-process/worker sandbox (see forceLongPolling).

Returns

void


get()

function get(r: Query | DatabaseReference): Promise<DataSnapshot>;

get(ref) — one-shot read at the ref’s path. Resolves to a DataSnapshot-shaped object.

Runs through the sandbox rule engine; denial throws the plain-Error shape locked by the oracle.

Absent path → snap.val() === null && snap.exists() === false. Matches the SDK’s DataSnapshot.val() contract.

Parameters

ParameterType
rQuery | DatabaseReference

Returns

Promise<DataSnapshot>


getAdminDatabase()

Call Signature

function getAdminDatabase(sandbox: Sandbox): Database;

Sandbox-only rules-bypass RTDB handle. Mirrors Firestore’s getAdminFirestore(sandbox) for Studio/Playground data browsers and controlled admin tools.

Parameters
ParameterType
sandboxSandbox
Returns

Database

Call Signature

function getAdminDatabase(ctx: SandboxContext): Database;

Sandbox-only rules-bypass RTDB handle. Mirrors Firestore’s getAdminFirestore(sandbox) for Studio/Playground data browsers and controlled admin tools.

Parameters
ParameterType
ctxSandboxContext
Returns

Database

Call Signature

function getAdminDatabase(app: FirebaseApp): Database;

Sandbox-only rules-bypass RTDB handle. Mirrors Firestore’s getAdminFirestore(sandbox) for Studio/Playground data browsers and controlled admin tools.

Parameters
ParameterType
appFirebaseApp
Returns

Database


getDatabase()

Call Signature

function getDatabase(ctx: SandboxContext): Database;

Build a sandbox Database handle:

  • SandboxContext → sandbox-backed, frozen identity.
  • Sandbox → sandbox-backed, live identity (per-op currentUser).
Parameters
ParameterType
ctxSandboxContext
Returns

Database

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getDatabase, ref, set, get } from 'pyric/database';

const sandbox = initializeSandbox();
const db = getDatabase(sandbox.withAuth({ uid: 'alice' }));
await set(ref(db, 'greetings/hello'), { text: 'hi' });
const snap = await get(ref(db, 'greetings/hello'));
console.log(snap.val()); // { text: 'hi' }

Call Signature

function getDatabase(sandbox: Sandbox): Database;

Build a sandbox Database handle:

  • SandboxContext → sandbox-backed, frozen identity.
  • Sandbox → sandbox-backed, live identity (per-op currentUser).
Parameters
ParameterType
sandboxSandbox
Returns

Database

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getDatabase, ref, set, get } from 'pyric/database';

const sandbox = initializeSandbox();
const db = getDatabase(sandbox.withAuth({ uid: 'alice' }));
await set(ref(db, 'greetings/hello'), { text: 'hi' });
const snap = await get(ref(db, 'greetings/hello'));
console.log(snap.val()); // { text: 'hi' }

Call Signature

function getDatabase(app: FirebaseApp): AppDatabase;

Build a sandbox Database handle:

  • SandboxContext → sandbox-backed, frozen identity.
  • Sandbox → sandbox-backed, live identity (per-op currentUser).
Parameters
ParameterType
appFirebaseApp
Returns

AppDatabase

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getDatabase, ref, set, get } from 'pyric/database';

const sandbox = initializeSandbox();
const db = getDatabase(sandbox.withAuth({ uid: 'alice' }));
await set(ref(db, 'greetings/hello'), { text: 'hi' });
const snap = await get(ref(db, 'greetings/hello'));
console.log(snap.val()); // { text: 'hi' }

Call Signature

function getDatabase(): AppDatabase;

Build a sandbox Database handle:

  • SandboxContext → sandbox-backed, frozen identity.
  • Sandbox → sandbox-backed, live identity (per-op currentUser).
Returns

AppDatabase

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getDatabase, ref, set, get } from 'pyric/database';

const sandbox = initializeSandbox();
const db = getDatabase(sandbox.withAuth({ uid: 'alice' }));
await set(ref(db, 'greetings/hello'), { text: 'hi' });
const snap = await get(ref(db, 'greetings/hello'));
console.log(snap.val()); // { text: 'hi' }

goOffline()

function goOffline(db: Database): void;

goOffline(db) — disconnect the client from the RTDB backend.

Drains this client’s one-shot onDisconnect queue. The shared data backend remains available to other Database clients and listeners.

Parameters

ParameterType
dbDatabase

Returns

void


goOnline()

function goOnline(db: Database): void;

goOnline(db) — reconnect the client to the RTDB backend.

Reconnects the logical client. Executed disconnect operations are not resurrected; reads and writes remain synchronous in the local sandbox.

Parameters

ParameterType
dbDatabase

Returns

void


increment()

function increment(delta: number): IncrementSentinel;

increment(delta) — returns the { ".sv": { increment: delta } } sentinel that atomically adds delta to the current value at the write’s field. Starts from 0 when the field is absent or non-numeric (oracle: rtdb-modular-increment-from-missing.json).

The sandbox backend resolves it against the field’s prior value at write time. Mirrors firebase/database’s increment (api/ServerValue.ts:38-44).

Parameters

ParameterType
deltanumber

Returns

IncrementSentinel


limitToFirst()

function limitToFirst(n: number): QueryConstraint;

limitToFirst(n) — keep the first N children of the ordered window. Locked by oracle observation rtdb-modular-limittofirst-vs-limittolast.json.

Parameters

ParameterType
nnumber

Returns

QueryConstraint


limitToLast()

function limitToLast(n: number): QueryConstraint;

limitToLast(n) — keep the last N children of the ordered window. Locked by oracle observation rtdb-modular-limittofirst-vs-limittolast.json.

Parameters

ParameterType
nnumber

Returns

QueryConstraint


off()

function off(
   r: Query | DatabaseReference,
   eventType?: "value" | ChildEvent,
   callback?: (snap: DataSnapshot) => void): void;

off(ref, eventType?, callback?) — unsubscribe variant.

Semantics (locked by oracle observation packages/conformance/observations/rtdb-modular/rtdb-modular-off-stops-child-fires.json):

  • off(ref) (no eventType) removes ALL listeners at that ref — value + every child event variety.
  • off(ref, 'value') removes only value listeners.
  • off(ref, 'child_added') (or any child event type) removes only that variety.
  • off(ref, eventType, cb) removes only the matching callback.

The returned-unsubscribe pattern from onValue / onChild* is functionally equivalent to off(ref, eventType, cb) for a specific registration — both are supported.

Parameters

ParameterType
rQuery | DatabaseReference
eventType?"value" | ChildEvent
callback?(snap: DataSnapshot) => void

Returns

void


onChildAdded()

function onChildAdded(
   r: Query | DatabaseReference,
   cb: (snap: DataSnapshot, previousChildName: string) => void,
   cancelCallbackOrOptions?: ListenOptions | (error: Error) => void,
   options?: ListenOptions): Unsubscribe;

onChildAdded(ref, cb) — subscribe to child-added events at the ref’s path.

Semantics (locked by oracle observations under packages/conformance/observations/rtdb-modular/rtdb-modular-onchildadded-*.json):

  • On subscribe, replays every existing direct child of ref’s path (one fire per existing key, in default priority/key order).
  • After subscribe, fires exactly once per new direct child write.

Also accepts a Query (a query(ref, ...) with orderBy* / limitTo* constraints): child events are then computed against the ordered, windowed result — a child ENTERING the window fires child_added; on subscribe the current window is replayed in window order.

Returns an unsubscribe; calling it twice is a no-op.

Parameters

ParameterType
rQuery | DatabaseReference
cb(snap: DataSnapshot, previousChildName: string) => void
cancelCallbackOrOptions?ListenOptions | (error: Error) => void
options?ListenOptions

Returns

Unsubscribe


onChildChanged()

function onChildChanged(
   r: Query | DatabaseReference,
   cb: (snap: DataSnapshot, previousChildName: string) => void,
   cancelCallbackOrOptions?: ListenOptions | (error: Error) => void,
   options?: ListenOptions): Unsubscribe;

onChildChanged(ref, cb) — subscribe to child-changed events.

Semantics (oracle: rtdb-modular-onchildchanged-fires-on-update):

  • No initial replay.
  • Fires when an existing direct child’s value transitions to a NEW non-null value. Snapshot carries the NEW value.
  • Does NOT fire for added or removed children.

Also accepts a Query: fires when a child that is IN the query window changes value (an in-window update).

Parameters

ParameterType
rQuery | DatabaseReference
cb(snap: DataSnapshot, previousChildName: string) => void
cancelCallbackOrOptions?ListenOptions | (error: Error) => void
options?ListenOptions

Returns

Unsubscribe


onChildMoved()

function onChildMoved(
   r: Query | DatabaseReference,
   cb: (snap: DataSnapshot, previousChildName: string) => void,
   cancelCallbackOrOptions?: ListenOptions | (error: Error) => void,
   options?: ListenOptions): Unsubscribe;

onChildMoved(ref, cb) — subscribe to child-moved events.

Semantics (oracle: rtdb-modular-onchildmoved-with-orderby):

  • Explicit queries use their active orderBy* index.
  • Plain refs use Firebase’s default priority index, so changing a child’s priority can move it while an ordinary value-only write does not.

Accepts a Query and fires when the active ordered value changes, including the Firebase previousChildName second callback argument.

Parameters

ParameterType
rQuery | DatabaseReference
cb(snap: DataSnapshot, previousChildName: string) => void
cancelCallbackOrOptions?ListenOptions | (error: Error) => void
options?ListenOptions

Returns

Unsubscribe


onChildRemoved()

function onChildRemoved(
   r: Query | DatabaseReference,
   cb: (snap: DataSnapshot, previousChildName: string) => void,
   cancelCallbackOrOptions?: ListenOptions | (error: Error) => void,
   options?: ListenOptions): Unsubscribe;

onChildRemoved(ref, cb) — subscribe to child-removed events.

Semantics (oracle: rtdb-modular-onchildremoved-fires-on-delete):

  • No initial replay.
  • Fires when a direct child is deleted (via remove(child) or set(child, null)).
  • Snapshot carries the PRIOR (now-removed) value — the listener sees what was there before deletion.

Also accepts a Query: a child LEAVING the query window (e.g. displaced past a limitTo* boundary or filtered out) fires child_removed carrying its prior value.

Parameters

ParameterType
rQuery | DatabaseReference
cb(snap: DataSnapshot, previousChildName: string) => void
cancelCallbackOrOptions?ListenOptions | (error: Error) => void
options?ListenOptions

Returns

Unsubscribe


onDisconnect()

function onDisconnect(r: DatabaseReference): OnDisconnect;

Register a one-shot write for this Database client’s next disconnect. Registration checks rules immediately; execution checks them again.

Parameters

ParameterType
rDatabaseReference

Returns

OnDisconnect


onValue()

function onValue(
   r: Query | DatabaseReference,
   cb: (snap: DataSnapshot) => void,
   cancelCallbackOrOptions?: ListenOptions | (error: Error) => void,
   options?: ListenOptions): Unsubscribe;

onValue(ref, cb) — subscribe to value changes at the ref’s path.

Fires immediately on subscribe with the current value (or null + exists: false for an absent path), then on every subsequent write that touches the path or any descendant.

Returns an unsubscribe function. The unsubscribe is idempotent; calling it twice is a no-op.

options.onlyOnce (DB-B12): when true, the listener auto-unsubscribes after its first fire (mirrors api/Reference_impl.ts:975-980).

With a cancellation callback, an initially denied listen returns normally and reports the Firebase PERMISSION_DENIED error asynchronously. Without one, the sandbox preserves its legacy synchronous throw.

Parameters

ParameterType
rQuery | DatabaseReference
cb(snap: DataSnapshot) => void
cancelCallbackOrOptions?ListenOptions | (error: Error) => void
options?ListenOptions

Returns

Unsubscribe


orderByChild()

function orderByChild(path: string): QueryConstraint;

orderByChild('path') — order children by the value at the nested child path. Locked by oracle observation rtdb-modular-orderbychild-window.json.

Parameters

ParameterType
pathstring

Returns

QueryConstraint


orderByKey()

function orderByKey(): QueryConstraint;

orderByKey() — order children lexicographically by key string. Locked by oracle observation rtdb-modular-orderbykey-window.json.

Returns

QueryConstraint


orderByPriority()

function orderByPriority(): QueryConstraint;

orderByPriority() — order children by their RTDB priority metadata, with Firebase’s key ordering as the tie-breaker.

Returns

QueryConstraint


orderByValue()

function orderByValue(): QueryConstraint;

orderByValue() — order children by primitive value. Prod requires .indexOn: ".value" (oracle: rtdb-modular-orderbyvalue-numeric.json threw Index not defined against blockingfun); sandbox does NOT enforce indexes (the rules engine here checks read-allow only, not query-index conformance).

Returns

QueryConstraint


push()

function push(r: DatabaseReference, value?: unknown): ThenableReference;

push(ref, value?) — mint an auto-id child key under ref’s path, optionally writing value at the new child.

Returns a ref at the new child path. The ref’s key is the minted id (locked by oracle observation rtdb-push-autoid-format.json: 20 chars, leading -, lex-sortable).

Production note: the key is minted client-side (no server round-trip required); it’s available synchronously on the returned ref even when the optional write is denied by rules. The oracle observation confirms this — the sandbox matches.

Parameters

ParameterType
rDatabaseReference
value?unknown

Returns

ThenableReference


pushKey()

function pushKey(): string;

Pre-mint a push key without writing. Used by callers that need the key for a multi-path update (update(rootRef, { [\/users/${key}`]: … })`). Returns a freshly-minted key.

Returns

string


query()

function query(refOrQuery: Query | DatabaseReference, ...constraints: QueryConstraint[]): Query;

query(ref, ...constraints) — wrap a ref in an immutable constraint chain. The resulting Query routes through get/onValue and applies the ordering + filtering + limit pipeline on the sandbox backend.

Chaining is supported — query(query(ref, orderByChild('x')), limitToFirst(2)) folds both constraints into one spec.

Locked semantics (oracle):

  • orderByChild('p') + startAt(v) + endAt(w) is BOTH-inclusive (rtdb-modular-orderbychild-window.json).
  • orderByKey() + startAt('b') + endAt('d') matches [b, c, d] (rtdb-modular-orderbykey-window.json).
  • orderByValue() + limitToFirst(3) returns the 3 smallest by value (rtdb-modular-orderbyvalue-numeric.json — note: prod requires .indexOn: ".value"; sandbox does not enforce indexes).
  • orderByChild('group') + equalTo('b') returns ALL matching children (rtdb-modular-equalTo-filter.json).
  • limitToFirst(N) / limitToLast(N) take from the start / end of the ordered window (rtdb-modular-limittofirst-vs-limittolast.json).
  • startAfter / endBefore are EXCLUSIVE (rtdb-modular-startafter-endbefore-exclusive.json).

Parameters

ParameterType
refOrQueryQuery | DatabaseReference
constraintsQueryConstraint[]

Returns

Query


ref()

function ref(db: Database, path?: string): DatabaseReference;

Build a DatabaseReference at path (default root).

Path normalisation: leading + trailing slashes are stripped; empty path / '/' becomes the root.

Parameters

ParameterType
dbDatabase
path?string

Returns

DatabaseReference


refFromURL()

function refFromURL(db: Database, url: string): DatabaseReference;

refFromURL(db, url) — build a DatabaseReference from an absolute database URL (https://<namespace>.firebaseio.com/path).

The sandbox is single-database, so only the URL path is honored; unlike the production SDK, the host is not checked against the database namespace.

Parameters

ParameterType
dbDatabase
urlstring

Returns

DatabaseReference


remove()

function remove(r: DatabaseReference): Promise<void>;

remove(ref) — delete the subtree at the ref’s path.

RTDB invariant (oracle: rtdb-remove-vs-set-null.json): equivalent to set(ref, null). The sandbox backend dispatches remove through the same code path as set(_, null).

Parameters

ParameterType
rDatabaseReference

Returns

Promise<void>


runTransaction()

function runTransaction<T>(
   r: DatabaseReference,
   transactionUpdate: (current: T) => T,
options?: TransactionOptions): Promise<TransactionResult>;

runTransaction(ref, transactionUpdate, options?) — atomic read-modify-write.

Contract (oracle-locked):

  1. transactionUpdate is called with the CURRENT value at ref’s path. For an absent path the arg is null (NOT undefined); oracle: rtdb-modular-runtransaction-current-value-arg.jsonmissingFirstWasNull: true.
  2. Returning undefined from the update fn ABORTS the transaction: resolves { committed: false, snapshot } where the snapshot is the pre-transaction value; oracle: rtdb-modular-runtransaction-abort-undefined.jsoncommitted: false, snapVal: null.
  3. Returning any defined value WRITES that value (rules-checked); resolves { committed: true, snapshot } where snapshot.val() is the committed value; oracle: rtdb-modular-runtransaction-success.jsoncommittedNewValue: true and rtdb-modular-runtransaction-returns-committed-snapshot.json.
  4. If rules deny the write, the promise REJECTS with a plain Error whose message === 'permission_denied' and NO .code field (distinct from set/get’s 'PERMISSION_DENIED: Permission denied'); oracle: rtdb-modular-runtransaction-on-rules-denied-path.json.

options.applyLocally (default true): when false, the intermediate optimistic value is NOT fanned out to listeners — they see only the committed value. In a single-client harness this is usually invisible; we honor the flag for prod-parity. Oracle observation rtdb-modular-runtransaction-options-applylocally.json confirms both branches commit and end at the same value; the intermediate-fire difference isn’t observable from a single client.

A synchronous overlapping write during the update callback invalidates the read and retries the callback. Writes to unrelated paths do not conflict.

Type Parameters

Type Parameter
T

Parameters

ParameterType
rDatabaseReference
transactionUpdate(current: T) => T
options?TransactionOptions

Returns

Promise<TransactionResult>


serverTimestamp()

function serverTimestamp(): ServerTimestampSentinel;

serverTimestamp() — returns the { ".sv": "timestamp" } sentinel the wire encoder recognises. Resolves to Date.now() (epoch ms) on write — locked by the prod SDK’s resolved-as-number contract (oracle: rtdb-servertimestamp-resolves.json).

The sandbox backend recognises the marker.

Returns

ServerTimestampSentinel


set()

function set(r: DatabaseReference, value: unknown): Promise<void>;

set(ref, value) — replace the value at ref’s path. null deletes (matches the RTDB invariant — locked by oracle observation rtdb-remove-vs-set-null.json).

serverTimestamp() sentinels are resolved at write time.

Parameters

ParameterType
rDatabaseReference
valueunknown

Returns

Promise<void>


setPriority()

function setPriority(r: DatabaseReference, priority: string | number): Promise<void>;

Parameters

ParameterType
rDatabaseReference
prioritystring | number

Returns

Promise<void>


setWithPriority()

function setWithPriority(
   r: DatabaseReference,
   value: unknown,
priority: string | number): Promise<void>;

Parameters

ParameterType
rDatabaseReference
valueunknown
prioritystring | number

Returns

Promise<void>


startAfter()

function startAfter(value: JsonValue, key?: string): QueryConstraint;

startAfter(value, key?) — EXCLUSIVE lower bound. Locked by rtdb-modular-startafter-endbefore-exclusive.json.

Parameters

ParameterType
valueJsonValue
key?string

Returns

QueryConstraint


startAt()

function startAt(value: JsonValue, key?: string): QueryConstraint;

startAt(value, key?) — INCLUSIVE lower bound under the active ordering. Optional key is the tie-breaker when ordering by child/value and multiple children share the bound’s value.

Parameters

ParameterType
valueJsonValue
key?string

Returns

QueryConstraint


update()

function update(r: DatabaseReference, values: Record<string, unknown>): Promise<void>;

update(ref, values) — partial update.

  • When values keys contain /, the call is a multi-path atomic update: every listed path is written as one transaction (any denial fails the whole batch).
  • Otherwise it’s a shallow merge at the ref’s path: each top-level key replaces the corresponding child. null values delete.

Both behaviors are sandbox-implemented per the RtdbBackend’s update method (rtdb-modular-spec atomic claim, matrix row #23).

Parameters

ParameterType
rDatabaseReference
valuesRecord<string, unknown>

Returns

Promise<void>

References

AuthState

Re-exports AuthState


Sandbox

Re-exports Sandbox


SandboxContext

Re-exports SandboxContext