Classes
Database
Opaque RTDB handle. Routes via TARGET_SYMBOL.
Constructors
Constructor
new Database(target?: Target, app?: FirebaseApp): Database;
Parameters
| Parameter | Type |
|---|---|
target? | Target |
app? | FirebaseApp |
Returns
Properties
| Property | Modifier | Type | Default value |
|---|---|---|---|
[TARGET_SYMBOL] | readonly | Target | undefined |
app | readonly | FirebaseApp | undefined |
type | readonly | "database" | "database" |
DataSnapshot
Firebase-shaped RTDB snapshot runtime value.
Extended by
Constructors
Constructor
new DataSnapshot(implementation?: DataSnapshotImplementation): DataSnapshot;
Parameters
| Parameter | Type |
|---|---|
implementation? | DataSnapshotImplementation |
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
ref | readonly | DatabaseReference |
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
| Parameter | Type |
|---|---|
path | string |
Returns
exists()
exists(): boolean;
Returns
boolean
exportVal()
exportVal(): JsonValue;
Returns
forEach()
forEach(cb: (child: DataSnapshot) => boolean | void): boolean;
Parameters
| Parameter | Type |
|---|---|
cb | (child: DataSnapshot) => boolean | void |
Returns
boolean
hasChild()
hasChild(path: string): boolean;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
boolean
hasChildren()
hasChildren(): boolean;
Returns
boolean
toJSON()
toJSON(): JsonValue;
Returns
val()
val(): JsonValue;
Returns
OnDisconnect
Methods
cancel()
cancel(): Promise<void>;
Returns
Promise<void>
remove()
remove(): Promise<void>;
Returns
Promise<void>
set()
set(value: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
Returns
Promise<void>
setWithPriority()
setWithPriority(value: unknown, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
priority | string | number |
Returns
Promise<void>
update()
update(values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
values | Record<string, unknown> |
Returns
Promise<void>
QueryConstraint
Opaque constraint produced by the order/filter/limit query functions.
Constructors
Constructor
new QueryConstraint(type?: QueryConstraintType, internal?: Constraint): QueryConstraint;
Parameters
| Parameter | Type |
|---|---|
type? | QueryConstraintType |
internal? | Constraint |
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
[CONSTRAINT_SYMBOL] | readonly | Constraint |
type | readonly | QueryConstraintType |
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.json →
afterValOnServer: 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
| Parameter | Type |
|---|---|
committed? | boolean |
snapshot? | DataSnapshot |
Returns
Properties
| Property | Modifier | Type |
|---|---|---|
committed | readonly | boolean |
snapshot | readonly | DataSnapshot |
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
| Property | Modifier | Type |
|---|---|---|
[QUERY_SYMBOL] | readonly | true |
key | readonly | string |
parent | readonly | DatabaseReference |
ref | readonly | DatabaseReference |
root | readonly | DatabaseReference |
Methods
isEqual()
isEqual(other: Query): boolean;
Parameters
| Parameter | Type |
|---|---|
other | Query |
Returns
boolean
Inherited from
toJSON()
toJSON(): string;
Returns
string
Inherited from
toString()
toString(): string;
Returns
string
Inherited from
DataSnapshotImplementation
Properties
| Property | Modifier | Type |
|---|---|---|
key | readonly | string |
priority | readonly | string | number |
ref | readonly | DatabaseReference |
size | readonly | number |
Methods
child()
child(path: string): DataSnapshot;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
exists()
exists(): boolean;
Returns
boolean
exportVal()
exportVal(): JsonValue;
Returns
forEach()
forEach(cb: (child: DataSnapshot) => boolean | void): boolean;
Parameters
| Parameter | Type |
|---|---|
cb | (child: DataSnapshot) => boolean | void |
Returns
boolean
hasChild()
hasChild(path: string): boolean;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
boolean
hasChildren()
hasChildren(): boolean;
Returns
boolean
toJSON()
toJSON(): JsonValue;
Returns
val()
val(): JsonValue;
Returns
IteratedDataSnapshot
Child snapshot supplied during ordered iteration; its key is never null.
Extends
Properties
| Property | Modifier | Type | Overrides |
|---|---|---|---|
key | readonly | string | DataSnapshot.key |
ref | readonly | DatabaseReference | - |
Accessors
priority
Get Signature
get priority(): string | number;
Returns
string | number
Inherited from
size
Get Signature
get size(): number;
Returns
number
Inherited from
Methods
child()
child(path: string): DataSnapshot;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
Inherited from
exists()
exists(): boolean;
Returns
boolean
Inherited from
exportVal()
exportVal(): JsonValue;
Returns
Inherited from
forEach()
forEach(cb: (child: DataSnapshot) => boolean | void): boolean;
Parameters
| Parameter | Type |
|---|---|
cb | (child: DataSnapshot) => boolean | void |
Returns
boolean
Inherited from
hasChild()
hasChild(path: string): boolean;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
boolean
Inherited from
hasChildren()
hasChildren(): boolean;
Returns
boolean
Inherited from
toJSON()
toJSON(): JsonValue;
Returns
Inherited from
val()
val(): JsonValue;
Returns
Inherited from
ListenOptions
Properties
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
| Property | Modifier | Type |
|---|---|---|
[QUERY_SYMBOL] | readonly | true |
ref | readonly | DatabaseReference |
Methods
isEqual()
isEqual(other: Query): boolean;
Parameters
| Parameter | Type |
|---|---|
other | Query |
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
| Property | Modifier | Type |
|---|---|---|
[QUERY_SYMBOL] | readonly | true |
key | readonly | string |
parent | readonly | DatabaseReference |
ref | readonly | DatabaseReference |
root | readonly | DatabaseReference |
Methods
catch()
catch<TResult>(onrejected?: (reason: unknown) => TResult | PromiseLike<TResult>): Promise<DatabaseReference | TResult>;
Type Parameters
| Type Parameter | Default type |
|---|---|
TResult | never |
Parameters
| Parameter | Type |
|---|---|
onrejected? | (reason: unknown) => TResult | PromiseLike<TResult> |
Returns
Promise<DatabaseReference | TResult>
isEqual()
isEqual(other: Query): boolean;
Parameters
| Parameter | Type |
|---|---|
other | Query |
Returns
boolean
Inherited from
then()
then<TResult1, TResult2>(onfulfilled?: (value: DatabaseReference) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
Type Parameters
| Type Parameter | Default type |
|---|---|
TResult1 | DatabaseReference |
TResult2 | never |
Parameters
| Parameter | Type |
|---|---|
onfulfilled? | (value: DatabaseReference) => TResult1 | PromiseLike<TResult1> |
onrejected? | (reason: unknown) => TResult2 | PromiseLike<TResult2> |
Returns
Promise<TResult1 | TResult2>
toJSON()
toJSON(): string;
Returns
string
Inherited from
toString()
toString(): string;
Returns
string
Inherited from
TransactionOptions
Properties
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.
nullat any level erases that subtree. Locked by oracle observationpackages/conformance/observations/rtdb/rtdb-remove-vs-set-null.jsonwhich saysset(ref, null)andremove(ref)produce equivalent end states.- A read of an absent path returns
null(NOT an error). Matches theDataSnapshot.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
| Parameter | Type |
|---|---|
db | Database |
data | Record<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
| Parameter | Type |
|---|---|
db | Database |
rulesJson | { rules: Record<string, unknown>; } |
rulesJson.rules | Record<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
| Parameter | Type |
|---|---|
db | Database |
Returns
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
| Parameter | Type |
|---|---|
target | SandboxTarget | SandboxLiveTarget |
path | string |
Returns
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
| Parameter | Type |
|---|---|
parent | DatabaseReference |
path | string |
Returns
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
| Parameter | Type |
|---|---|
_db | Database |
_host | string |
_port | number |
_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
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
value | JsonValue |
key? | string |
Returns
endBefore()
function endBefore(value: JsonValue, key?: string): QueryConstraint;
endBefore(value, key?) — EXCLUSIVE upper bound. Locked by
rtdb-modular-startafter-endbefore-exclusive.json.
Parameters
| Parameter | Type |
|---|---|
value | JsonValue |
key? | string |
Returns
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
| Parameter | Type |
|---|---|
value | JsonValue |
key? | string |
Returns
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
| Parameter | Type |
|---|---|
r | Query | 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
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
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
| Parameter | Type |
|---|---|
ctx | SandboxContext |
Returns
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
| Parameter | Type |
|---|---|
app | FirebaseApp |
Returns
getDatabase()
Call Signature
function getDatabase(ctx: SandboxContext): Database;
Build a sandbox Database handle:
SandboxContext→ sandbox-backed, frozen identity.Sandbox→ sandbox-backed, live identity (per-opcurrentUser).
Parameters
| Parameter | Type |
|---|---|
ctx | SandboxContext |
Returns
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-opcurrentUser).
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
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-opcurrentUser).
Parameters
| Parameter | Type |
|---|---|
app | FirebaseApp |
Returns
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-opcurrentUser).
Returns
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
| Parameter | Type |
|---|---|
db | Database |
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
| Parameter | Type |
|---|---|
db | Database |
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
| Parameter | Type |
|---|---|
delta | number |
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
| Parameter | Type |
|---|---|
n | number |
Returns
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
| Parameter | Type |
|---|---|
n | number |
Returns
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 onlyvaluelisteners.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
| Parameter | Type |
|---|---|
r | Query | 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
| Parameter | Type |
|---|---|
r | Query | DatabaseReference |
cb | (snap: DataSnapshot, previousChildName: string) => void |
cancelCallbackOrOptions? | ListenOptions | (error: Error) => void |
options? | ListenOptions |
Returns
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
| Parameter | Type |
|---|---|
r | Query | DatabaseReference |
cb | (snap: DataSnapshot, previousChildName: string) => void |
cancelCallbackOrOptions? | ListenOptions | (error: Error) => void |
options? | ListenOptions |
Returns
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
| Parameter | Type |
|---|---|
r | Query | DatabaseReference |
cb | (snap: DataSnapshot, previousChildName: string) => void |
cancelCallbackOrOptions? | ListenOptions | (error: Error) => void |
options? | ListenOptions |
Returns
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)orset(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
| Parameter | Type |
|---|---|
r | Query | DatabaseReference |
cb | (snap: DataSnapshot, previousChildName: string) => void |
cancelCallbackOrOptions? | ListenOptions | (error: Error) => void |
options? | ListenOptions |
Returns
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
| Parameter | Type |
|---|---|
r | DatabaseReference |
Returns
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
| Parameter | Type |
|---|---|
r | Query | DatabaseReference |
cb | (snap: DataSnapshot) => void |
cancelCallbackOrOptions? | ListenOptions | (error: Error) => void |
options? | ListenOptions |
Returns
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
| Parameter | Type |
|---|---|
path | string |
Returns
orderByKey()
function orderByKey(): QueryConstraint;
orderByKey() — order children lexicographically by key string.
Locked by oracle observation rtdb-modular-orderbykey-window.json.
Returns
orderByPriority()
function orderByPriority(): QueryConstraint;
orderByPriority() — order children by their RTDB priority metadata,
with Firebase’s key ordering as the tie-breaker.
Returns
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
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
| Parameter | Type |
|---|---|
r | DatabaseReference |
value? | unknown |
Returns
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/endBeforeare EXCLUSIVE (rtdb-modular-startafter-endbefore-exclusive.json).
Parameters
| Parameter | Type |
|---|---|
refOrQuery | Query | DatabaseReference |
…constraints | QueryConstraint[] |
Returns
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
| Parameter | Type |
|---|---|
db | Database |
path? | string |
Returns
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
| Parameter | Type |
|---|---|
db | Database |
url | string |
Returns
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
| Parameter | Type |
|---|---|
r | DatabaseReference |
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):
transactionUpdateis called with the CURRENT value atref’s path. For an absent path the arg isnull(NOTundefined); oracle:rtdb-modular-runtransaction-current-value-arg.json→missingFirstWasNull: true.- Returning
undefinedfrom the update fn ABORTS the transaction: resolves{ committed: false, snapshot }where the snapshot is the pre-transaction value; oracle:rtdb-modular-runtransaction-abort-undefined.json→committed: false, snapVal: null. - Returning any defined value WRITES that value (rules-checked);
resolves
{ committed: true, snapshot }wheresnapshot.val()is the committed value; oracle:rtdb-modular-runtransaction-success.json→committedNewValue: trueandrtdb-modular-runtransaction-returns-committed-snapshot.json. - If rules deny the write, the promise REJECTS with a plain
Errorwhosemessage === 'permission_denied'and NO.codefield (distinct fromset/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
| Parameter | Type |
|---|---|
r | DatabaseReference |
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
| Parameter | Type |
|---|---|
r | DatabaseReference |
value | unknown |
Returns
Promise<void>
setPriority()
function setPriority(r: DatabaseReference, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
r | DatabaseReference |
priority | string | number |
Returns
Promise<void>
setWithPriority()
function setWithPriority(
r: DatabaseReference,
value: unknown,
priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
r | DatabaseReference |
value | unknown |
priority | string | 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
| Parameter | Type |
|---|---|
value | JsonValue |
key? | string |
Returns
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
| Parameter | Type |
|---|---|
value | JsonValue |
key? | string |
Returns
update()
function update(r: DatabaseReference, values: Record<string, unknown>): Promise<void>;
update(ref, values) — partial update.
- When
valueskeys 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.
nullvalues delete.
Both behaviors are sandbox-implemented per the RtdbBackend’s
update method (rtdb-modular-spec atomic claim, matrix row #23).
Parameters
| Parameter | Type |
|---|---|
r | DatabaseReference |
values | Record<string, unknown> |
Returns
Promise<void>
References
AuthState
Re-exports AuthState
Sandbox
Re-exports Sandbox
SandboxContext
Re-exports SandboxContext