Classes
PersistenceSchemaError
Extends
Error
Constructors
Constructor
new PersistenceSchemaError(message: string): PersistenceSchemaError;
Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
Overrides
Error.constructor
SandboxClock
One sandbox’s clock. Owned by the sandbox and shared by every service on it,
so set / advance / reset move all of them at once.
Constructors
Constructor
new SandboxClock(): SandboxClock;
Returns
Accessors
mode
Get Signature
get mode(): SandboxClockMode;
Which of the three modes the clock is in.
Returns
Methods
advance()
advance(ms: number): void;
Move the clock forward (or, with a negative delta, back) by ms. A frozen
clock stays frozen at the new instant; a wall or offset clock keeps
flowing, shifted.
Parameters
| Parameter | Type |
|---|---|
ms | number |
Returns
void
capture()
capture(): SandboxClockState;
This clock’s whole state, as a value a checkpoint or branch can hold.
Returns
date()
date(): Date;
The sandbox’s current time as a Date.
Returns
Date
now()
now(): number;
The sandbox’s current time, in epoch milliseconds.
Returns
number
onChange()
onChange(listener: (state: SandboxClockState) => void): () => void;
Watch for a move. A sandbox hosted behind a transport (the SharedWorker
host, say) has readers in another realm that cannot call now()
synchronously, so they mirror this state instead and need to be told when
it changes. Returns the function that stops watching.
Parameters
| Parameter | Type |
|---|---|
listener | (state: SandboxClockState) => void |
Returns
(): void;
Returns
void
reset()
reset(): void;
Return to the wall clock, discarding any pin or offset.
Returns
void
restore()
restore(state: SandboxClockState): void;
Adopt a captured state wholesale.
Parameters
| Parameter | Type |
|---|---|
state | SandboxClockState |
Returns
void
set()
set(epochMs: number): void;
Pin the clock to epochMs and freeze it there. Every subsequent now()
returns exactly epochMs until the clock is advanced, set again, or reset.
Parameters
| Parameter | Type |
|---|---|
epochMs | number |
Returns
void
SandboxContextImpl
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.
Implements
Constructors
Constructor
new SandboxContextImpl(
sandbox: Sandbox,
auth: {
tenant?: string;
token?: Record<string, unknown>;
uid: string;
},
operationContext?: OperationContext): SandboxContextImpl;
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | string |
auth.token? | Record<string, unknown> |
auth.uid? | string |
operationContext? | OperationContext |
Returns
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
auth | readonly | { tenant?: string; token?: Record<string, unknown>; uid: string; } | The identity rules evaluate under for operations through this context. |
auth.tenant? | public | string | - |
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: {
tenant?: string;
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 | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | string |
auth.token? | Record<string, unknown> |
auth.uid | string |
Returns
Implementation of
Interfaces
ActiveListener
One listener that has attached and not yet detached or errored.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
actor | readonly | EventActor | - |
attachedAt | readonly | number | - |
authLens | readonly | AuthLens | - |
clientListenerId? | readonly | string | The id the page’s own client gave this subscription, when the host stamped it on the attach as the activity listener id. A page that observes a delivery knows only this id, so it is how a page-side observation finds the listener the sandbox recorded. |
deliveryCount | readonly | number | - |
id | readonly | string | - |
lastDeliveryAt? | readonly | number | - |
owners? | readonly | readonly ListenerOwner[] | Who owns the listener, as its attach event recorded it (a creation frame, an explicit tag) and as its deliveries revealed it (the DOM regions its callback changed). Absent when the emitter recorded nothing. |
query? | readonly | unknown | The query the attach recorded, when the listener watches a query rather than one record: Firestore’s constraint projection, or the Realtime Database’s query spec. Absent for a document or a bare path. |
service | readonly | "firestore" | "database" | - |
suppressedCount | readonly | number | - |
target | readonly | ActiveListenerTarget | - |
ActivityEventProvenance
Provenance consumed only by the firestore activity diagnostics. Bundled in one optional record so the shared operation type carries a single activity-owned seam rather than loose per-feature fields.
Properties
AuthAccountsState
The auth account store: the users and the provider configuration over them.
Properties
| Property | Type | Description |
|---|---|---|
history? | AuthAccountHistory | Each account’s refresh-token revocation time and the uids whose record was deleted. Production keeps both on the account, so restoring the state does not bring a revoked or deleted session back (#2021). Optional: a state written before it restores with every revocation and deletion forgotten, as it always did. |
providers | Record<string, boolean> | Which sign-in providers are enabled, by provider id. |
users | SeedUser[] | Every account the auth sandbox exports, in the seedUsers shape: uid, email, password, and the optional displayName, customClaims, photoUrl, phoneNumber, emailVerified, disabled, tenantId, providerId and account timestamps. Anonymous accounts are included in the same export contract. |
Branch
An isolated experiment seeded from a FullSandboxState.
A branch owns its own LocalSandbox, fully isolated from the source: separate environment, separate event history, separate service backends.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
base | readonly | FullSandboxState | The full state this branch was forked from. The baseline a promotion is a delta against. |
candidateRules | readonly | BranchCandidateRules | The candidate rules the fork installed, so a store can rebuild the branch. |
discarded | public | boolean | Set by discard and by a completed promote. |
events | readonly | SandboxEvent[] | Events applied since the fork, in order. |
sandbox | readonly | LocalSandbox | The branch’s own sandbox. Read it directly, or through captureFullState. |
BranchCandidateRules
Rule sources a fork installs on the branch in place of the ones the state carries. Each is independent: naming one replaces that service’s rules and leaves the other two as the forked state had them.
Properties
| Property | Type | Description |
|---|---|---|
database? | DatabaseRuleset | Realtime Database ruleset to run the branch under. |
firestore? | string | Firestore Security Rules source to run the branch under. |
storage? | string | Storage Security Rules source to run the branch under. |
BroadcastChannelLike
Minimal interface that BroadcastChannel satisfies. Provided as an
injectable seam so tests can run without a real browser channel.
The real BroadcastChannel global satisfies this interface out of the
box — pass it directly:
sandbox.enableTabSync({
channel: new BroadcastChannel('pyric:tabsync'),
});
For SSR / Node environments, the default channel construction is guarded
(typeof BroadcastChannel !== 'undefined') so the call site doesn’t need
to branch — a missing global just means no sync, which is fine for server
renders that only care about initial data.
Methods
addEventListener()
addEventListener(type: "message", listener: (ev: {
data: unknown;
}) => void): void;
Parameters
| Parameter | Type |
|---|---|
type | "message" |
listener | (ev: { data: unknown; }) => void |
Returns
void
close()
close(): void;
Returns
void
postMessage()
postMessage(message: unknown): void;
Parameters
| Parameter | Type |
|---|---|
message | unknown |
Returns
void
removeEventListener()
removeEventListener(type: "message", listener: (ev: {
data: unknown;
}) => void): void;
Parameters
| Parameter | Type |
|---|---|
type | "message" |
listener | (ev: { data: unknown; }) => void |
Returns
void
DatabaseRuleset
A Realtime Database ruleset, in the { rules: ... } envelope the SDK takes.
Properties
DenialContext
Structured denial context emitted alongside a permission-denied
error. Real Firebase strips this server-side for security; the
sandbox can expose it because it’s a development tool.
auth and reasons are populated whenever the sandbox raises a
permission-denied error. rule (line + expression) requires
source-position tracking in the rules AST and is deferred — see
design rationale “Open questions” for the follow-up.
failedFields will be filled in once the evaluator surfaces field-
reference traces.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
auth? | public | { tenant?: string; token?: Record<string, unknown>; uid: string; } | Auth identity that was active when the denial fired. |
auth.tenant? | public | string | - |
auth.token? | public | Record<string, unknown> | - |
auth.uid | public | string | - |
engine? | public | "firestore" | Engine discriminator. An RTDB denial carries RtdbDenialContext instead. |
failedFields? | public | string[] | Field paths in request.resource.data that the rule referenced and that failed. |
query? | public | { limit?: number; offset?: number; orderBy?: string; where?: readonly { field: string; op: string; value: | string | number | boolean | readonly (string | number | boolean)[]; }[]; } | Machine-readable descriptor of the denied query’s where/orderBy/limit shape (RULES-B11). Populated when a list/query is denied as statically unprovable (“rules are not filters”), so consumers can render the exact query the engine rejected without re-deriving it. Absent for single-doc and non-query denials. |
query.limit? | readonly | number | - |
query.offset? | readonly | number | - |
query.orderBy? | readonly | string | - |
query.where? | readonly | readonly { field: string; op: string; value: | string | number | boolean | readonly (string | number | boolean)[]; }[] | - |
queryProof? | public | QueryProofDiagnostic | - |
reasons? | public | string[] | Raw simulator reasoning lines (the underlying engine’s debugMessages). Always present on permission-denied. Stable enough for log surfacing; not stable as machine-parseable data. |
repro? | public | QueryRepro | Ready-to-run repro (CLI command + fixture TestCase) for a rejected unprovable list query (#371). |
request? | public | { method: "delete" | "get" | "list" | "create" | "update"; path: string; resourceData?: Record<string, unknown>; updateMask?: string[][]; } | Eval-time request shape — what the rule saw on request.*. Lets callers render a “why did this deny” frame (auth, method, path, request.resource.data with sentinels resolved) without re-deriving any of it from out-of-band state. |
request.method | public | "delete" | "get" | "list" | "create" | "update" | - |
request.path | public | string | - |
request.resourceData? | public | Record<string, unknown> | The user’s proposed request.resource.data — pre-resolution. FieldValue.* sentinels are preserved as their marker shapes ({ __type: 'serverTimestamp' }, etc.). The rule engine evaluated against the resolved form; what surfaces here is the caller’s INTENT so consumers see what they tried to write. Absent for reads (no proposed write) and for delete (no payload). |
request.updateMask? | public | string[][] | A non-merge update’s field paths as segment vectors; a segment may contain .. |
resource? | public | { data: Record<string, unknown>; exists: boolean; } | Eval-time existing-document snapshot — what the rule saw on resource.data. null data with exists: false mirrors how the rule sees an absent doc. Absent for collection ops (list). |
resource.data | public | Record<string, unknown> | - |
resource.exists | public | boolean | - |
rule? | public | { citation?: string; col?: number; column?: number; expression?: string; file?: string; line?: number; } | The rule whose evaluation produced the denial (#370). |
rule.citation? | public | string | - |
rule.col? | public | number | - |
rule.column? | public | number | - |
rule.expression? | public | string | - |
rule.file? | public | string | - |
rule.line? | public | number | - |
DenialEvent
Eval-time payload emitted to Sandbox.onDenial subscribers.
Mirrors the structured fields DenialContext carries (request
resource+reasons+auth) so a host environment that wants to surface denials independent of try/catch behavior gets the same frame either way.
Properties
EventCaller
Which connection to the sandbox sent the operation behind an event. A host stamps it from the connection the frame arrived on, never from the frame.
page: a browser page.pageIdnames the page, one id per tab, and the host hands each page its own id on its event subscription, so a page can tell its own requests from another tab’s.node: a server process using the client SDK, such as a script undernode --import @pyric/cli/registeror server-rendered code.admin: server code usingfirebase-adminorpyric-admin.mcp: an agent’s MCP tool call.studio: Pyric Studio.
clientId names the client behind the connection: a browser profile,
which every tab of that profile shares, a service worker realm, or one
Node process. A page or service worker declares it; a Node process is
named by its connection. A label, never an authority.
Absent on events a host did not stamp, such as those of an in-page sandbox, where every request is the page’s own.
Properties
| Property | Type |
|---|---|
clientId? | string |
kind | "admin" | "studio" | "page" | "node" | "mcp" | "service-worker" |
pageId? | string |
EventProvenance
Compatibility provenance carried by sandbox events while producers and
consumers migrate to the canonical operationContext.
Properties
| Property | Type | Description |
|---|---|---|
activity? | ActivityEventProvenance | Firestore activity-diagnostics provenance; absent outside that flow. |
actor? | EventActor | - |
authLens? | AuthLens | - |
caller? | EventCaller | The connection that sent the operation; see EventCaller. |
observedAt? | number | Wall-clock observation time, independent of the simulated service clock. |
operationContext? | OperationContext | - |
planId? | string | Set when the op is part of an agent plan. |
service? | EventService | - |
FullSandboxState
Everything one sandbox holds, as one plain JSON value.
Properties
| Property | Type | Description |
|---|---|---|
auth | AuthAccountsState | The auth account store. |
clock? | SandboxClockState | The sandbox clock’s state at capture. A checkpoint restore and a branch fork both carry it, so a forked branch reaches the same request.time verdict its base reached and a restored checkpoint stamps the same serverTimestamp() the sandbox was stamping when it was taken. Optional: a state written before the clock existed, or by a producer that does not model time, restores the sandbox to the wall clock. |
database | JsonValue | The Realtime Database persistence envelope: the tree and its priorities. The database’s rules travel in SandboxRuleSources instead, so the two can never disagree about which ruleset the state carries. |
firestore | Record<string, Record<string, unknown>> | Firestore documents by full path. |
firestoreEncoding? | "pyric/firestore-values/1" | Declared value encoding; absent in legacy states that carry plain document maps. |
rules | SandboxRuleSources | The three rule sources. |
storage | StorageObjectState[] | Every Storage object in the default bucket, ordered by path. |
FullStateCaptureOptions
How a capture records Storage bytes.
Properties
| Property | Type | Description |
|---|---|---|
storage? | "reference" | "inline" | inline (the default) carries every object’s bytes; reference names them by hash. |
ListenerLifecycleEvent
Listener lifecycle event — attach, detach, or errored. Errored
supersedes the prior onSnapshotError channel; error is populated
on the errored phase only.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
error? | { code: "permission-denied"; message: string; reasons?: string[]; } | Populated on listener_errored only. |
error.code | "permission-denied" | - |
error.message | string | - |
error.reasons? | string[] | - |
id | string | - |
kind | "listener_attach" | "listener_detach" | "listener_errored" | - |
listenerId | string | - |
owners? | ListenerOwner[] | Attribution recorded on listener_attach: the creation frame and, when the caller supplied one, the tag. |
target | | { kind: "doc"; path: string; } | { collection: string; collectionGroup?: true; kind: "query"; query?: unknown; } | - |
LocalSandbox
An in-process sandbox created by initializeSandbox.
Service controls whose implementation requires synchronous access to local state accept this type. Remote worker handles remain Sandboxs, but are deliberately not assignable to this local-only interface.
Extends
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
[LOCAL_SANDBOX] | readonly | true | - |
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 | { tenant?: string; 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.tenant? | public | string | - |
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>
Inherited from
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
Inherited from
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>
Inherited from
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();
Inherited from
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>
Inherited from
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
Inherited from
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
Inherited from
onCurrentUserChanged()
onCurrentUserChanged(cb: (user: {
tenant?: string;
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: { tenant?: string; token?: Record<string, unknown>; uid: string; }) => void |
Returns
(): void;
Returns
void
Inherited from
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
Inherited from
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
Inherited from
Sandbox.registerPersistableService
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
Inherited from
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[];
}>
Inherited from
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
branch on whether the method exists and call fn() once either way;
runWithProvenance?.(prov, fn) ?? fn() runs fn twice when it
returns undefined.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
provenance | EventProvenance |
fn | () => T |
Returns
T
Inherited from
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
Inherited from
withAuth()
withAuth(auth: {
tenant?: string;
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 | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | 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));
Inherited from
ObservedAccount
The signed-in account a call ran as: the account id, the names of its
token claims, and their values. Never the token. The values stay in the
host’s memory so the local rules can read request.auth.token; no event
holds them.
Properties
| Property | Type | Description |
|---|---|---|
claimNames? | string[] | - |
claims? | Record<string, unknown> | The token’s claims by name, as JSON values. Absent when the client did not send them. |
uid | string | - |
ObservedCall
One observed call, as a client sends it to a host.
Properties
| Property | Type | Description |
|---|---|---|
account? | ObservedAccount | Absent when the call ran signed out. |
ai? | ObservedAi | Required on every ai call, and refused on any other. |
at | number | When the app made the call, in ms since epoch. |
billedDocuments? | number | On a listener delivery: the documents production billed it for, those added, changed or removed, and at least one on the listener’s first snapshot. Zero for a snapshot only its metadata changed, which production does not bill. Absent when the recorder could not count them, and then a delivery counts once. |
bucket? | string | storage only: the bucket the reference named, as a bare bucket name (my-project.firebasestorage.app), never a gs:// URL. Required on every Storage call and refused on any other; the event carries it as detail.bucket, the key the sandbox’s own Storage events use. |
document? | Record<string, unknown> | firestore or storage (getMetadata): the fields or metadata of the stored document/object an allowed read returned, so local rules can inspect resource.data or resource. Memory only; no event holds them. |
durationMs? | number | How long production took to answer, in ms. |
instance? | string | rtdb only: the name of the database instance the call went to, as the SDK’s namespace names it (my-project-default-rtdb, my-project-named). Required on every RTDB call, the default instance included, and refused on any other; the event leaves it out for the project’s default instance. |
listener? | ObservedListener | firestore and rtdb only: a listener’s attach or detach. Refused on any other call and on an error outcome. Such a record becomes a listener event, not an operation event. |
listenerId? | string | firestore and rtdb client deliveries only: the subscription id minted on the listener’s attach, so the host can correlate each delivered snapshot with its attached listener. Refused on any other service, on an Admin call, on an error outcome, or alongside listener. |
method | string | The SDK function the app called, such as getDoc or signInWithEmailAndPassword. An Admin call names its class and method, such as DocumentReference.get or Auth.verifyIdToken. |
outcome | ObservedOutcome | - |
path? | string | The document or collection path the call named, when it named one. On an rtdb call, the reference’s path, such as /items/a. On a storage call, the reference’s fullPath, absent for the bucket’s root. Never on an ai call, whose event path is its model, or a messaging call. |
projectId? | string | The project the app’s Firebase config named for this call (app.options.projectId): where the call actually went. Absent when the recorder could not read it. |
query? | ObservedQuery | firestore only: the shape of the query a list or listener ran. Refused on any other call; the event carries it as request.query. |
requests? | ObservedRequest[] | messaging only: the Installations and FCM registration requests a getToken or deleteToken made, at most four, in the order they started. Refused on any other call; the event carries them as detail.requests. |
sdk? | "admin" | 'admin' when a server process made the call through the Admin SDK, which bypasses Security Rules; absent for the client SDK. Taken only on firestore, rtdb, storage and auth calls; the event carries it as detail.sdk. |
service | ObservedCallService | - |
usage? | ObservedUsage | What production billed or moved for the call, when the recorder measured it. |
writeData? | ObservedWriteValue | firestore (setDoc, updateDoc, addDoc), rtdb (set, setWithPriority, update, push), or storage (uploadBytes, uploadString, uploadBytesResumable, updateMetadata): the written JSON value or object metadata so local rules can inspect request.resource / newData. Memory only; no event holds them. |
ObservedDeliverySummary
Validated path-level summary of one observed live listener delivery, stored
on event.detail.delivery without field values.
snapshot:pathslists the current top-level child paths (full-nodeonValuedeliveries).delta:pathslists added or modified paths andremovedPathslists deleted paths (onSnapshotdocChangesand RTDBonChild*callbacks).
Properties
ObservedProduction
The production side of an observed operation event. Its presence means
production served the call and pyric only watched it.
Properties
| Property | Type | Description |
|---|---|---|
billedDocuments? | number | A listener delivery’s ObservedCall.billedDocuments, when the recorder counted them. |
claimNames? | string[] | The account’s claim names; the account id is the event’s auth.uid. |
local? | LocalVerdict | What the local rules files say about the same request, when the host evaluated it. Production decided the call: this never changes the event’s result or Rules disposition. |
outcome | ProductionOutcome | - |
usage? | ObservedUsage | The call’s ObservedCall.usage, when the recorder measured it. |
ObservedUsage
What production billed or moved for a call, as the recorder measured it from the SDK’s answer: document reads, writes and deletes, payload and transfer bytes, and how many parts it could not measure. Counts only, each a non-negative safe integer; never a document, a value or a payload.
Properties
OperationContext
Immutable operation provenance, bound where an operation is issued. Source and auth lens are deliberately orthogonal: Studio may evaluate rules as a user, while an app or agent may use an admin lens.
Properties
| Property | Modifier | Type |
|---|---|---|
authLens | readonly | AuthLens |
planId? | readonly | string |
source | readonly | EventActor |
OperationRecord
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
at | readonly | number | - |
auth | readonly | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | public | string | - |
auth.token? | public | Record<string, unknown> | - |
auth.uid | public | string | - |
context | readonly | OperationContext | - |
eventKind | readonly | "request" | "listener" | "operation" | - |
id | readonly | string | - |
method | readonly | string | - |
observation? | readonly | RequestObservation | - |
path? | readonly | string | - |
production? | readonly | ObservedProduction | What production answered, for a call production served and pyric observed. |
queryProof? | readonly | QueryProofDiagnostic | - |
result? | readonly | "allow" | "deny" | "error" | "unsupported" | "not-applicable" | - |
rules | readonly | RulesDisposition | - |
service | readonly | EventService | - |
OwnerStackFrame
One application stack frame kept on a frame owner’s stack.
Properties
| Property | Type | Description |
|---|---|---|
column? | number | 1-based column, when the runtime’s stack format carried one. |
file | string | Path or URL of the application file. |
function? | string | Enclosing function name, when the runtime’s stack format named one. |
line | number | 1-based line number within file. |
PersistableService
Contract for a service that can contribute its state to the sandbox
persistence layer. Services (auth, storage, database) register
themselves via Sandbox.registerPersistableService so the
sandbox core stays service-agnostic — the sandbox doesn’t know what
auth or storage look like; it just calls snapshot() / restore().
subscribe is optional but strongly recommended: without it, a
service’s changes (e.g. new users created via auth) only reach the
persisted blob on the next Firestore write. With subscribe, the
controller debounces a flush on every user-DB change — same latency
as Firestore writes.
Properties
Methods
reset()?
optional reset(): void | Promise<void>;
Optional: clear this service’s state to empty. Called by
Sandbox.resetAll after the Firestore environment swap, so a
single sandbox-owned call wipes EVERY registered service (auth users,
RTDB tree, storage objects) — a consumer (Pyric Studio’s reset) can’t
forget a service it never knew about. May be async (storage clears an
IndexedDB store); resetAll awaits it. A service that omits reset
is skipped — its state deliberately survives resetAll (e.g. the
per-app auth-session hooks, whose signed-in identity the sandbox core
already clears in reset()).
Returns
void | Promise<void>
restore()
restore(data: unknown): void;
Restore previously snapshotted state. Called once during
enablePersistence, AFTER Firestore docs have been restored (so
any service that needs Firestore to be hydrated first can rely on
that ordering). Guard against bad data — the blob came from disk
and may be stale or from a schema migration.
Parameters
| Parameter | Type |
|---|---|
data | unknown |
Returns
void
snapshot()
snapshot(): unknown;
Return a plain-JSON-serializable snapshot of this service’s state.
Called when the service changes, or on every flush when subscribe
is omitted. The return value is stored under the service’s registered name in the
services map of the persisted blob.
Returns
unknown
PersistenceBackend
Backend contract: read/write/list/delete RECORDS under a key. The controller partitions a snapshot into structured-clone bucket records (chunk-format.ts) so the backend stores many small records natively, never one keyspace-sized blob. Record values are structured-clone-safe objects; the backend never interprets them. (v2 and earlier used a single string blob; v3 is record-shaped.)
Properties
| Property | Type | Description |
|---|---|---|
retryFailedFlush? | boolean | False when a failed durable write requires operator repair and restart. |
Methods
applyChanges()?
optional applyChanges(
key: string,
changed: ReadonlyMap<string, unknown>,
removed: readonly string[]): Promise<void>;
Commit changed and removed records atomically when the backend supports it.
Parameters
| Parameter | Type |
|---|---|
key | string |
changed | ReadonlyMap<string, unknown> |
removed | readonly string[] |
Returns
Promise<void>
clear()
clear(key: string): Promise<void>;
Remove ALL records under key. No-op if none exist.
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
Promise<void>
deleteRecords()
deleteRecords(key: string, recordIds: readonly string[]): Promise<void>;
Delete the given record ids under key. No-op for ids that don’t exist.
Parameters
| Parameter | Type |
|---|---|
key | string |
recordIds | readonly string[] |
Returns
Promise<void>
estimate()?
optional estimate(): Promise<{
quota: number;
usage: number;
}>;
Best-effort storage usage estimate (bytes used + the quota ceiling), or
null when the backend can’t report it. Surfaced by the metadata API so a
host can show how close the sandbox is to its storage limit. Optional: a
backend that can’t estimate simply omits it.
Returns
Promise<{
quota: number;
usage: number;
}>
getRecord()
getRecord(key: string, recordId: string): Promise<unknown>;
Read one record by id under key. Resolves null when absent.
Parameters
| Parameter | Type |
|---|---|
key | string |
recordId | string |
Returns
Promise<unknown>
listRecords()
listRecords(key: string): Promise<string[]>;
List all record ids under key, any order.
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
Promise<string[]>
putRecords()
putRecords(key: string, records: ReadonlyMap<string, unknown>): Promise<void>;
Write each [recordId, value] under key, replacing any prior value.
Parameters
| Parameter | Type |
|---|---|
key | string |
records | ReadonlyMap<string, unknown> |
Returns
Promise<void>
PersistenceController
Properties
| Property | Modifier | Type |
|---|---|---|
options | readonly | Readonly<SandboxPersistenceOptions> |
Methods
clear()
clear(): Promise<void>;
Wipe persisted state. In-memory state is untouched.
Returns
Promise<void>
dispose()
dispose(): void;
Detach event subscription + beforeunload listener.
Returns
void
flush()
flush(): Promise<void>;
Force a flush of the current sandbox state to the backend.
Returns
Promise<void>
RemoteSandbox
A branded remote sandbox handle. Structurally a Sandbox — it can
be passed anywhere a Sandbox is accepted (notably
pyric-admin/app’s initializeApp({ sandbox })) — but sync-only members
that cannot be mirrored over the wire (admin, snapshot(),
history(), …) throw a remediating error. Consumers with a remote arm
dispatch on isRemoteSandbox and use channel instead.
Extends
Extended by
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
[REMOTE_SANDBOX] | readonly | true | - |
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. |
channel | readonly | RemoteSandboxChannel | The raw worker op/sub relay channel. |
currentUser | public | { tenant?: string; 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.tenant? | public | string | - |
currentUser.token? | public | Record<string, unknown> | - |
currentUser.uid | public | string | - |
serveUrl | readonly | string | Base URL of the pyric sandbox this handle is attached to (used in error guidance: “open |
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>
Inherited from
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
Inherited from
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>
Inherited from
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();
Inherited from
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>
Inherited from
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
Inherited from
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
Inherited from
onCurrentUserChanged()
onCurrentUserChanged(cb: (user: {
tenant?: string;
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: { tenant?: string; token?: Record<string, unknown>; uid: string; }) => void |
Returns
(): void;
Returns
void
Inherited from
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
Inherited from
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
Inherited from
Sandbox.registerPersistableService
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
Inherited from
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[];
}>
Inherited from
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
branch on whether the method exists and call fn() once either way;
runWithProvenance?.(prov, fn) ?? fn() runs fn twice when it
returns undefined.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
provenance | EventProvenance |
fn | () => T |
Returns
T
Inherited from
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
Inherited from
withAuth()
withAuth(auth: {
tenant?: string;
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 | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | 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));
Inherited from
RemoteSandboxChannel
The minimal worker-relay channel a remote sandbox handle carries.
Structural mirror of @pyric/cli/remote’s RemoteSandboxChannel: one
method to dispatch any SharedWorker-protocol op, one to register a
snap-delivering subscription. Payloads are typed openly here (the real
discriminated unions live in @pyric/cli’ worker protocol); callers in
pyric-admin spell the concrete op objects (rtdb.set, auth.listUsers,
…) and pin their own actAs lens — nothing is pinned by the channel.
Methods
byteRoute()?
optional byteRoute(): Promise<RemoteByteRoute>;
The host’s HTTP byte route for Storage bytes, once the channel is attached, or undefined when the host has none and takes bytes as frames.
Returns
Promise<RemoteByteRoute>
op()
op(op: {
method: string;
} & Record<string, unknown>): Promise<unknown>;
Dispatch one worker op. Resolves with the worker’s result value;
rejects with an Error carrying a .code (including the fail-fast
“no browser tab is connected — open
Parameters
| Parameter | Type |
|---|---|
op | { method: string; } & Record<string, unknown> |
Returns
Promise<unknown>
subscribe()
subscribe(
sub: {
target: unknown;
} & Record<string, unknown>,
onSnap: (value: unknown) => void,
onError?: (err: Error & {
code: string;
}) => void): () => void;
Register a worker subscription (e.g. an RTDB value listener:
{ target: { service: 'rtdb', path } }). onSnap receives every snap
value (initial + updates — and re-delivered fresh after peer
replacement); an establishment failure routes to onError instead.
Returns the unsubscribe function.
Parameters
| Parameter | Type |
|---|---|
sub | { target: unknown; } & Record<string, unknown> |
onSnap | (value: unknown) => void |
onError? | (err: Error & { code: string; }) => void |
Returns
(): void;
Returns
void
RemoteSandboxFactoryOptions
Options accepted by the ambient remote-sandbox factory.
Properties
ReplayOptions
Properties
ReplayResult
Properties
| Property | Type | Description |
|---|---|---|
divergences | Divergence[] | Field- and path-level differences between original and replayed state, classified. |
pathAliases | Map<string, string> | Maps captured auto-id paths → freshly-minted replay paths. The diff classifier uses this to skip autoid-alias paths when computing field-level differences. |
sandbox | LocalSandbox | Fresh sandbox with the captured writes re-applied. |
RequestEvent
Eval-time payload emitted to Sandbox.onRequest subscribers — one per evaluated op, regardless of outcome.
Issue #307: the playground today only renders denials, but every op
the simulator evaluates is a request worth seeing. This event is the
source of truth; DenialEvent is a filtered projection over
the result === 'deny' subset.
Origin tells the consumer who initiated the eval:
usersingle op via the data-plane adapter (admin / firestore).batchpart of a multi-op batch — sharesgroupIdwith siblings.transactionpart of a transaction commit — sharesgroupId.listenera write ordeployRulestriggered a snapshot listener to re-evaluate. CarriestriggeredBynaming the originating user op (when knowable).
evalMs measures the wall-clock duration of the simulator’s
simulate(...) call. Sub-millisecond is normal for simple rules;
rule-engine-heavy rules (deep boolean chains, many get() calls) can
reach tens of milliseconds; a traffic-monitor validation probe measured
connect-four rules at ~95ms p99. Surface this in your UI when it matters.
Listener throws are swallowed by the dispatcher so a faulty subscriber can’t change rule semantics or hide other events.
See
traffic-monitor-decision.md for the field-by-field rationale.
Properties
| Property | Type | Description |
|---|---|---|
at | number | Wall-clock at op start, ms since epoch. |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
detail? | { admin?: boolean; } & Record<string, unknown> | Free-form operation metadata. admin: true marks a rules-bypassing setup/admin operation so fixture tooling can exclude it from protected behavior while still preserving it as replay context. |
evalMs | number | Wall-clock duration of the simulator.simulate(…) call, in ms. |
evaluatedRule? | EvaluatedRuleInfo | For query-proof failures this is the actual residual evaluation, not the primary explanation; consult queryProof. Otherwise, the deciding rule’s verdict + 1-indexed source line + full sub-expression trace, projected from the simulator’s structured RuleEvaluation (additive: present on `result: ‘allow' |
groupId? | string | Shared across ops in one batch or transaction. Opaque to consumers. |
groupKind? | "transaction" | "batch" | Disambiguates `origin: ‘transaction' |
id | string | Unique within a sandbox process. Useful for React list keys. |
kind | "request" | Discriminator. |
matchedRule? | { operations: string[]; ruleIndex: number; } | Parsed from the simulator’s “Rule #N → …” debug line. Absent when no rule matched (e.g. no allow rules at the path — implicit deny). |
matchedRule.operations | string[] | - |
matchedRule.ruleIndex | number | - |
method | "delete" | "get" | "list" | "create" | "update" | "set" | - |
origin | "transaction" | "user" | "listener" | "batch" | - |
path | string | - |
queryProof? | QueryProofDiagnostic | Primary static-proof explanation; evaluatedRule is secondary when present. |
reasons | string[] | Simulator debug messages — the per-rule trace (Rule #0 (read) → ALLOW). Same shape as DenialEvent.reasons so consumer code can share rendering. |
request? | { merge?: | boolean | { mergeFields: string[]; }; resourceData?: Record<string, unknown>; updateMask?: string[][]; } | Proposed write payload, for create/update/set. Absent on reads + delete. Pre-resolution: FieldValue.* sentinels are preserved as their marker shapes ({ __type: 'serverTimestamp' }, etc.) so the replay engine can re-resolve them. The rule engine evaluated against the resolved form internally; that resolved form lives on WriteSandboxEvent.nextState, not here. For an update, resourceData holds the fields the update writes as nested maps ({'board.c1r1': 'x'} reads { board: { c1r1: 'x' } }), and updateMask lists the update’s field paths as segment vectors. A segment may contain .: new FieldPath('a.b') is [['a.b']]. |
request.merge? | | boolean | { mergeFields: string[]; } | - |
request.resourceData? | Record<string, unknown> | - |
request.updateMask? | string[][] | - |
resourceAfter? | { data: Record<string, unknown>; exists: boolean; } | Projected document state after the write. Absent on reads. |
resourceAfter.data | Record<string, unknown> | - |
resourceAfter.exists | boolean | - |
resourceBefore? | { data: Record<string, unknown>; exists: boolean; } | Existing document state before the write (or read target for get). |
resourceBefore.data | Record<string, unknown> | - |
resourceBefore.exists | boolean | - |
result | "allow" | "deny" | "unsupported" | Local operational outcome. A proof-limited deny does not establish Firebase denial. |
rulesDisposition? | RulesDisposition | Canonical statement of whether Security Rules evaluated this request. Added by the sandbox event recorder when an older emitter omits it. |
rulesEvidence? | RulesEvidence | - |
rulesEvidenceExpired? | boolean | - |
triggeredBy? | { method: string; path: string; } | For listener re-evals: the originating user op that triggered this re-evaluation. Absent on the initial-snapshot fire. |
triggeredBy.method | string | - |
triggeredBy.path | string | - |
RtdbDenialContext
Structured denial context attached to a sandbox Realtime Database
permission error. Production RTDB reports only PERMISSION_DENIED; the
sandbox adds the rule evaluation that produced the denial. The error that
carries it stays a plain Error with production’s code and message.
Properties
SandboxClockState
A clock’s whole state as one plain value. Captured into a checkpoint or a branch’s full state so a restore or a fork carries the virtual time it was taken under, and safe to serialize as JSON.
Properties
| Property | Type | Description |
|---|---|---|
fixedAt | number | The frozen instant, in epoch milliseconds. Only meaningful when mode is fixed. |
mode | SandboxClockMode | - |
offsetMs | number | Milliseconds added to the wall clock. Only meaningful when mode is offset. |
SandboxCommitEvent
Canonical committed mutation event. Unlike operation, this fires only when
state actually changed. Replay and branch tooling should eventually consume
these service adapters instead of filtering Firestore-only write events.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
data? | unknown | - |
detail? | Record<string, unknown> | - |
groupId? | string | - |
groupKind? | "transaction" | "batch" | - |
id | string | - |
instance? | string | RTDB only: the name of the database instance the commit changed. Absent for the default instance, as the worker protocol’s instance field is. |
kind | "commit" | - |
method | string | - |
nextState? | unknown | - |
path? | string | - |
priorState? | unknown | - |
replay? | { autoId?: string; requestTime?: number; sentinels?: { field: string; kind: string; }[]; } | - |
replay.autoId? | string | - |
replay.requestTime? | number | - |
replay.sentinels? | { field: string; kind: string; }[] | - |
service | EventService | - |
SandboxConfig
Initialization config for a sandbox. All fields are optional; an empty config produces a sandbox with no rules and no seeded data.
No auth field. Identity belongs to SandboxContext, not
the sandbox. Service handles always require an explicit context.
SandboxListenerEvent
Canonical listener lifecycle/delivery event. Firestore’s existing snapshot delivery/lifecycle variants are preserved; this shape gives RTDB and future service listeners the same debuggable surface.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
detail? | Record<string, unknown> | - |
error? | { code?: string; message: string; reasons?: string[]; } | - |
error.code? | string | - |
error.message | string | - |
error.reasons? | string[] | - |
id | string | - |
instance? | string | RTDB only: the name of the database instance the listener reads. Absent for the default instance, as the worker protocol’s instance field is. |
kind | "listener" | - |
listenerId | string | - |
owners? | ListenerOwner[] | Attribution for this listener. attach carries the creation frame and any caller-supplied tag; delivery carries the regions the callback mutated. |
phase | "attach" | "detach" | "delivery" | "suppressed" | "errored" | - |
reason? | string | - |
reasons? | string[] | - |
result? | "allow" | "deny" | "error" | "unsupported" | - |
rules? | { engine: "firestore" | "rtdb" | "storage"; errorCode?: string; matchedPath?: string; matchedRule?: string; operations?: string[]; pathVariableBindings?: Record<string, string>; reason?: string; rtdbTrace?: { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[]; ruleIndex?: number; } | - |
rules.engine | "firestore" | "rtdb" | "storage" | - |
rules.errorCode? | string | - |
rules.matchedPath? | string | - |
rules.matchedRule? | string | - |
rules.operations? | string[] | - |
rules.pathVariableBindings? | Record<string, string> | - |
rules.reason? | string | - |
rules.rtdbTrace? | { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[] | RTDB only: every .read, .write and .validate rule the engine evaluated for the request, in evaluation order. |
rules.ruleIndex? | number | - |
rulesDisposition? | RulesDisposition | - |
sample? | unknown | - |
service | EventService | - |
size? | number | - |
target | { kind: string; path?: string; query?: unknown; } | - |
target.kind | string | - |
target.path? | string | - |
target.query? | unknown | - |
triggeredBy? | { method: string; path?: string; } | - |
triggeredBy.method | string | - |
triggeredBy.path? | string | - |
SandboxObservationGapEvent
A delivery failure, not a failed sandbox operation. Source IDs delimit the omitted batch.
Properties
| Property | Type |
|---|---|
at | number |
firstEventId | string |
id | string |
kind | "observation_gap" |
lastEventId | string |
omittedCount | number |
reason | "frame-limit" | "history-limit" |
SandboxOperationEvent
Canonical service operation event. This is the service-neutral successor to
Firestore’s request traffic shape: every user-visible operation can be
represented here, whether it is backed by security rules (Firestore/RTDB/
Storage) or by a service control plane (Auth).
Existing Firestore request events remain for compatibility. New cross-
service consumers should prefer operation because it carries an explicit
service discriminator and does not require RTDB/Storage/Auth to pretend
their state is a Firestore document.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
detail? | Record<string, unknown> | - |
durationMs? | number | - |
groupId? | string | - |
groupKind? | "transaction" | "batch" | - |
id | string | - |
instance? | string | RTDB only: the name of the database instance the operation hit. Absent for the default instance, as the worker protocol’s instance field is. |
kind | "operation" | - |
method | string | - |
observation? | RequestObservation | - |
origin | "transaction" | "admin" | "user" | "system" | "listener" | "batch" | - |
path? | string | - |
production? | ObservedProduction | Present when production served the call and a client reported what it answered; pyric did not run it. See observed-call.ts. |
reasons? | string[] | - |
request? | { data?: unknown; query?: unknown; resourceData?: unknown; } | - |
request.data? | unknown | - |
request.query? | unknown | - |
request.resourceData? | unknown | - |
resourceAfter? | { data: unknown; exists: boolean; } | - |
resourceAfter.data | unknown | - |
resourceAfter.exists | boolean | - |
resourceBefore? | { data: unknown; exists: boolean; } | - |
resourceBefore.data | unknown | - |
resourceBefore.exists | boolean | - |
result | "allow" | "deny" | "error" | "unsupported" | "not-applicable" | - |
rules? | { engine: "firestore" | "rtdb" | "storage"; errorCode?: string; matchedPath?: string; matchedRule?: string; operations?: string[]; pathVariableBindings?: Record<string, string>; reason?: string; rtdbTrace?: { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[]; ruleIndex?: number; } | - |
rules.engine | "firestore" | "rtdb" | "storage" | - |
rules.errorCode? | string | - |
rules.matchedPath? | string | - |
rules.matchedRule? | string | - |
rules.operations? | string[] | - |
rules.pathVariableBindings? | Record<string, string> | - |
rules.reason? | string | - |
rules.rtdbTrace? | { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[] | RTDB only: every .read, .write and .validate rule the engine evaluated for the request, in evaluation order. |
rules.ruleIndex? | number | - |
rulesDisposition? | RulesDisposition | Canonical statement of whether Security Rules evaluated this operation. Service emitters may provide it directly; the recorder normalizes legacy operation shapes at the unified stream seam. |
service | EventService | - |
triggeredBy? | { method: string; path?: string; } | - |
triggeredBy.method | string | - |
triggeredBy.path? | string | - |
SandboxPersistenceOptions
Controller options. See Sandbox.enablePersistence.
Properties
| Property | Type | Description |
|---|---|---|
backend? | "memory" | "indexedDB" | Storage backend. indexedDB requires a browser environment; in non-browser hosts (Bun, Node, tests) the controller falls back to memory automatically unless an injectedBackend is supplied. Default: indexedDB. |
flushIntervalMs? | number | Debounce window before write events are flushed to the backend. Buffers rapid bursts (e.g., a batch of seed writes) into one flush. Default: 250ms. |
injectedBackend? | PersistenceBackend | Override the backend with an injected implementation. Used by tests and hosts that have their own storage adapter. When set, backend is ignored. |
key | string | IndexedDB database name (or generic bucket key for other backends). Different keys persist to different storage locations — use one key per logical sandbox if you run several in parallel. |
sessionStorage? | { local: WebStorageLike; session: WebStorageLike; } | Optional web-storage pair for current-session persistence. When provided, the controller reads and writes the signed-in uid here (honoring the auth setPersistence mode) so page reloads restore the signed-in user — exactly like browserLocalPersistence in prod Firebase. When omitted, the user DATABASE still persists (Phase 1), but the CURRENT SESSION is not restored on reload. This is the honest no-fake-durability choice for environments where web storage isn’t available (Bun tests, Node servers, etc.). local maps to localStorage semantics (survives reload + restart); session maps to sessionStorage semantics (survives reload, cleared on tab close). The controller picks which store to write based on the auth setPersistence mode recorded on the backend: LOCAL → local (default; matches Firebase’s default) SESSION → session NONE → neither (uid is not stored) Both storages are read on restore (mode-agnostic — a prior session may have used a different mode). Exactly one store holds the uid at any time; a mode change migrates the uid to the new store. |
sessionStorage.local | WebStorageLike | - |
sessionStorage.session | WebStorageLike | - |
SandboxRuleSources
The three rule sources a sandbox evaluates against.
Properties
| Property | Type | Description |
|---|---|---|
database | DatabaseRuleset | Realtime Database rules, or null when the sandbox runs without them. |
databaseInstances? | Record<string, DatabaseRuleset | null> | Secondary Realtime Database rulesets by instance name; omitted when none are installed. |
firestore | string | Firestore Security Rules source. The empty source when none is installed. |
storage | string | Storage Security Rules source, or null when the sandbox runs without them. |
storageCrossServiceIam? | "granted" | "denied" | Cross-service IAM posture for Storage firestore.get() / firestore.exists(); omitted when 'granted'. |
SandboxRuntimeErrorEvent
Canonical non-rules operational failure.
Properties
| Property | Type |
|---|---|
at | number |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | string |
auth.token? | Record<string, unknown> |
auth.uid | string |
detail? | Record<string, unknown> |
error | { code?: string; message: string; } |
error.code? | string |
error.message | string |
id | string |
kind | "runtime_error" |
method | string |
path? | string |
service | EventService |
SandboxSnapshot
Sandbox-level snapshot — a coarse capture of every service’s state
keyed by service name. The firestore key is always present; the
services map holds one entry per registered persistable service
(auth users, future storage objects, etc.). Service-specific
snapshot types live in their service modules; /app keeps the index
structural so it stays decoupled from service implementations.
v2 shape — services was added when the persistable-service registry
landed. Prior { firestore } v1 blobs are treated as having an empty
services map on restore.
Properties
| Property | Type | Description |
|---|---|---|
firestore | Record<string, Record<string, unknown>> | Firestore documents, keyed by full path. Always present — empty {} for a fresh or just-reset sandbox. Per-document values are the post-resolution state the keyspace stored. |
firestoreRules? | string | Deployed Firestore Security Rules source when non-default rules are active. Restored by Sandbox.loadSnapshot so clobber-restoring a snapshot does not silently revert Firestore rules to default open rules. |
services | Record<string, unknown> | Per-service opaque state, keyed by service name (e.g. 'auth'). Each entry is whatever the service’s PersistableService.snapshot() returned. May be {} when no services are registered. |
ServiceEventRecord
One service’s declaration of its slice of the event stream.
Type Parameters
| Type Parameter | Default type |
|---|---|
Service extends string | string |
Operation extends string | string |
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
operations | readonly | readonly Operation[] | Every operation this service emits, in no significant order. |
service | readonly | Service | The service name that appears on the event and in its provenance. |
target | readonly | ServiceEventTarget | What the event’s path addresses. |
ServiceEventTarget
What a service event’s path addresses, in that service’s own scheme.
Properties
SessionBoundaryEvent
Session boundary — emitted before sandbox.reset() swaps the env,
and before sandbox.dispose() tears it down. Lets consumers segment
a persisted event stream into “session N pre-reset” / “session N+1
post-reset” runs.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
id | string | - |
kind | "session_boundary" | - |
phase | "reset" | "dispose" | - |
priorOpCount | number | Total events emitted on this sandbox before the boundary. |
SnapshotDeliveryEvent
Snapshot delivered to a onSnapshot listener’s user callback.
Fires AFTER the no-op suppression check — every snapshot_delivery
event corresponds to an actual user-callback invocation. Listener
re-evals that resolved to no-ops emit SnapshotSuppressedEvent
instead.
sample carries best-effort serializable views of the docs the
callback received; consumers truncate before persisting if the
scenario produces large snapshots.
Properties
| Property | Type | Description |
|---|---|---|
addedCount | number | - |
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
id | string | - |
kind | "snapshot_delivery" | - |
listenerId | string | Opaque listener id assigned at attach time. |
modifiedCount | number | - |
owners? | ListenerOwner[] | Attribution for this delivery: the regions owner naming the elements the callback mutated during its own synchronous run. The frame and tag owners live on the matching listener_attach event; correlate on listenerId rather than repeating them on every delivery. |
removedCount | number | - |
sample? | { docs: { data: Record<string, unknown>; path: string; }[]; } | Doc payloads, in the order the user callback saw them. |
sample.docs | { data: Record<string, unknown>; path: string; }[] | - |
size | number | 1 for doc-kind (exists) / 0 (deleted), n for query-kind. |
target | | { kind: "doc"; path: string; } | { collection: string; collectionGroup?: true; kind: "query"; } | - |
triggeredBy? | { method: string; path: string; } | The user op that triggered this re-eval. Absent on initial fire and on deployRules-driven re-evals. |
triggeredBy.method | string | - |
triggeredBy.path | string | - |
SnapshotErrorEvent
Eval-time payload emitted to Sandbox.onSnapshotError subscribers.
Stream-level error from a Firestore onSnapshot listener — the
listener has been silently terminated and will deliver no further
snapshots (matches production: a stream error is once-per-stream and
the listener stays “subscribed” from the consumer’s perspective but
receives nothing further). Carries the target so the host UI can
attribute the error to a specific watch.
Currently permission-denied is the only code the sandbox produces
(production also emits unavailable, aborted, resource-exhausted
— none of which have a sandbox analog: no network stream to drop, no
quota, no concurrent transactions to conflict). Documented divergence
from production; new codes can be added if a sandbox-specific
scenario surfaces them.
A query target with collectionGroup set is a collection-group
listener, and collection holds the collection id; the same holds for
the delivery, suppressed and lifecycle events below.
Properties
SnapshotSuppressedEvent
Listener re-eval that was suppressed before delivery — the re-eval ran but produced no observable change vs the prior snapshot, so the user callback wasn’t invoked.
Useful for “why didn’t my listener fire” debugging. Default UIs should filter these out; only the inspector-style consumer needs them.
Properties
TabSyncOptions
Options for sandbox.enableTabSync(options?). All fields are optional;
the defaults provide a ready-to-use configuration for browser environments.
Properties
| Property | Type | Description |
|---|---|---|
channel? | BroadcastChannelLike | The broadcast channel to use. Defaults to new BroadcastChannel('pyric:tabsync') when omitted and BroadcastChannel is available in the global scope. Pass a custom implementation for tests or Node environments. |
originId? | string | A string that uniquely identifies this tab’s sandbox instance. Used for echo suppression (messages with origin === originId are silently dropped) and for directing state replies to the requesting tab. Defaults to crypto.randomUUID() when available, otherwise a counter + process-uptime string (no Date.now() or Math.random() — those change every call and can collide in fast tests). |
TreeChange
One change to the Realtime Database tree, at the shallowest path that differs.
Properties
WebStorageLike
Minimal web-storage-like contract the session persistence controller
reads/writes. Matches the localStorage / sessionStorage browser
API subset that pyric sandbox’s SessionStore already uses, so
browsers pass real storages and tests pass in-memory Map-backed fakes.
Why the minimal subset (get/set/remove) instead of the full
Storage interface: this library targets multiple environments
(browser, Bun, Node) and the full Storage interface carries
length + key() + clear() that aren’t needed here — narrowing the
contract keeps tests simple and Node/Bun hosts from having to
implement a complete polyfill.
Methods
getItem()
getItem(key: string): string;
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
string
removeItem()
removeItem(key: string): void;
Parameters
| Parameter | Type |
|---|---|
key | string |
Returns
void
setItem()
setItem(key: string, value: string): void;
Parameters
| Parameter | Type |
|---|---|
key | string |
value | string |
Returns
void
WriteSandboxEvent
Committed write — a create/update/set/delete that the rule
engine allowed AND that the keyspace successfully applied. Includes
pre- and post-state so consumers can render diffs and (in a future
sandbox.history() API) reconstruct state by replay.
Fires AFTER the corresponding kind: 'request' event for the same
op. A denied or rolled-back write surfaces as a request-deny only;
write events only fire for committed writes.
sentinels and autoId are placeholders for the eventual replay
engine — v1 of the unified channel leaves them undefined. The shape
is locked so consumers can build against it without churn when
sentinel/auto-id capture lands.
Properties
| Property | Type | Description |
|---|---|---|
at | number | - |
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } | - |
auth.tenant? | string | - |
auth.token? | Record<string, unknown> | - |
auth.uid | string | - |
autoId? | string | Minted document ID when this write came from collection.add() / LocalEnvironment.createWithAutoId. The replay engine aliases the path’s last segment to a fresh mint on replay (rather than preserving the original auto-ID). |
data? | Record<string, unknown> | Pre-resolution write payload — FieldValue.* sentinels preserved as marker shapes ({ __type: 'serverTimestamp' }, etc.) so the replay engine can re-resolve them. The rule engine evaluated against the resolved form internally; the resolved form lives on nextState. Absent on delete. For an update, the fields the update writes as nested maps, with the field paths in updateMask. |
detail? | { admin?: boolean; } & Record<string, unknown> | Free-form write metadata. admin: true marks a rules-bypassing setup/admin commit so replay can apply it as context without asking candidate rules to permit it. |
groupId? | string | - |
groupKind? | "transaction" | "batch" | - |
id | string | - |
kind | "write" | - |
merge? | | true | { mergeFields: string[]; } | Present when the write was a set(..., { merge }): true for merge: true, or the listed mergeFields. Replay re-issues the write with the same merge so it lands the same document. Absent on events recorded before this field existed; replay then treats the write as it always did. |
method | "delete" | "create" | "update" | "set" | - |
nextState | Record<string, unknown> | State AFTER this write. null on delete. |
path | string | - |
priorState | Record<string, unknown> | State BEFORE this write. null for a non-existent doc. |
requestTime | { nanoseconds: number; seconds: number; } | Server time at which the rule engine evaluated this write — pinned per op (or shared across sub-ops in a batch / transaction). The replay engine re-issues this exact value when re-resolving serverTimestamp() sentinels so resolved fields are bit-identical on replay. Shape mirrors the Firestore Web SDK Timestamp ({ seconds, nanoseconds }). |
requestTime.nanoseconds | number | - |
requestTime.seconds | number | - |
sentinels? | { field: string; kind: | "delete" | "serverTimestamp" | "increment" | "arrayUnion" | "arrayRemove"; }[] | FieldValue sentinels (serverTimestamp / increment / arrayUnion / arrayRemove / deleteField → ‘delete’) extracted from the pre-resolution write payload. The replay engine consumes this to re-issue the same sentinels at replay time without consulting resolved values that would have drifted. Path syntax: dotted with bracket-indices (‘a.b[0].c’). Absent when the write contained no sentinels. |
updateMask? | string[][] | An update’s field paths as segment vectors; a segment may contain .. |
Type Aliases
ActiveListenerTarget
type ActiveListenerTarget =
| string
| {
collection: string;
query?: unknown;
};
The two families of target a listener watches.
AnyDenialContext
type AnyDenialContext =
| DenialContext
| RtdbDenialContext;
A sandbox denial context from either rules engine, discriminated by engine.
BranchDivergence
type BranchDivergence = Extract<Divergence, {
kind: "real-divergence";
}> & {
instance?: string;
service: SandboxService;
};
One divergence, tagged with the service whose state it concerns.
Always a real-divergence. The replay engine’s other kinds classify drift a
captured write licenses, and a branch carries no such metadata, so state
against state has only the one honest classification.
Type Declaration
instance?
optional instance: string;
Secondary Realtime Database instance name; omitted for the default instance and non-RTDB services.
service
service: SandboxService;
DiffTarget
type DiffTarget = LocalSandbox | FullSandboxState;
What a branch can be compared against: a live sandbox, or a captured state.
Divergence
type Divergence =
| {
after: unknown;
before: unknown;
field: string;
kind: "sentinel-drift";
path: string;
sentinelKind: | "serverTimestamp"
| "increment"
| "arrayUnion"
| "arrayRemove"
| "delete";
}
| {
kind: "autoid-alias";
originalPath: string;
replayedPath: string;
}
| {
after: unknown;
before: unknown;
field: string;
kind: "time-drift";
path: string;
}
| {
after: unknown;
before: unknown;
field?: string;
kind: "real-divergence";
path: string;
};
EventActor
type EventActor =
| {
journeyId?: string;
kind: "app";
}
| {
kind: "studio";
}
| {
kind: "agent";
name: string;
}
| {
kind: "app-builder";
}
| {
kind: "unattributed";
};
Who initiated the operation behind an event. Missing source is represented
explicitly as unattributed; it is never silently promoted to app traffic.
EventService
type EventService =
| "firestore"
| "runtime"
| MutationEventService;
Which sandbox service emitted an event. Firestore is named directly because
it rides its own rule-eval-shaped request/write path rather than the
cross-service mutation envelope; every other service reaches this union by
declaring an event record beside its own code.
ListenerOwner
type ListenerOwner =
| {
column?: number;
file: string;
function?: string;
kind: "frame";
line: number;
stack?: OwnerStackFrame[];
}
| {
element?: string;
kind: "tag";
name: string;
}
| {
kind: "regions";
selectors: string[];
}
| {
element?: string;
kind: "component";
name: string;
path?: string[];
tag?: string;
};
Type Declaration
{
column?: number;
file: string;
function?: string;
kind: "frame";
line: number;
stack?: OwnerStackFrame[];
}
column?
optional column: number;
1-based column, when the runtime’s stack format carried one.
file
file: string;
Path or URL of the application file that created the listener.
function?
optional function: string;
Enclosing function name, when the runtime’s stack format named one.
kind
kind: "frame";
line
line: number;
1-based line number within file.
stack?
optional stack: OwnerStackFrame[];
The application frames around this one, innermost first, when more than one was kept. This frame is one of them: the first outside the project’s skipped wrapper modules. Any skipped frames before it come first, then up to the configured number of frames from it outward.
{
element?: string;
kind: "tag";
name: string;
}
element?
optional element: string;
Selector that re-identifies the element the caller named.
kind
kind: "tag";
name
name: string;
Caller-supplied name, or the element’s lower-case tag name.
{
kind: "regions";
selectors: string[];
}
kind
kind: "regions";
selectors
selectors: string[];
Selectors of the elements the snapshot callback mutated.
{
element?: string;
kind: "component";
name: string;
path?: string[];
tag?: string;
}
element?
optional element: string;
Selector that re-identifies the component’s root DOM element, once
the consumer has attached the returned ref to it.
kind
kind: "component";
name
name: string;
The component function’s name, read from the render-phase stack. A minified production build mangles this like any other identifier; the consuming UI states that rather than guessing at the original name.
path?
optional path: string[];
The chain of enclosing component frames, outermost first, best effort. Absent when only one component frame was found.
tag?
optional tag: string;
The root element’s tag name, lower case, so a consumer can show the
element as nav#conversations when the selector is id-only.
ListenerPhase
type ListenerPhase = "attach" | "detach" | "delivery" | "suppressed" | "errored";
The five phases a listener passes through, whatever variant carried it.
MutationEventService
type MutationEventService = keyof typeof SERVICE_EVENT_RECORDS;
Every service that emits the cross-service mutation envelope.
ObservedCallService
type ObservedCallService = "firestore" | "auth" | "rtdb" | "ai" | "storage" | "messaging";
The services a client may report observed calls for.
ObservedOutcome
type ObservedOutcome =
| {
status: "ok";
}
| {
code: string;
failure?: "missing-index";
message?: string;
status: "error";
};
What production answered, as a client reports it: a ProductionOutcome
whose error may also carry production’s own message, as the SDK’s error
held it (Missing or insufficient permissions.). The message is at most
500 characters, and one shaped like a token is dropped. Only the host’s
terminal prints it: the event’s production.outcome holds the status and
code alone.
failure is the reader’s, never a client’s: missing-index when the code
is failed-precondition and the message says the query requires an index.
The reader decides it before it drops a token-shaped message, since the
console link in production’s index message often reads as one. The event
carries it as detail.failure, as a sandbox RTDB query’s missing index does.
ProductionOutcome
type ProductionOutcome =
| {
status: "ok";
}
| {
code: string;
status: "error";
};
What production answered: success, or the error code it returned.
RemoteSandboxFactory()
type RemoteSandboxFactory = (opts?: RemoteSandboxFactoryOptions) => RemoteSandbox;
The factory @pyric/cli/register installs at
globalThis[REMOTE_SANDBOX_FACTORY]. SYNCHRONOUS by contract:
initializeApp() is sync in firebase-admin, so the factory must return
the branded handle without awaiting (connection establishment may be
lazy inside the handle’s channel).
Parameters
| Parameter | Type |
|---|---|
opts? | RemoteSandboxFactoryOptions |
Returns
RulesDisposition
type RulesDisposition =
| {
kind: "evaluated";
verdict: "allow" | "deny";
}
| {
kind: "bypassed";
reason: "admin";
}
| {
kind: "not-evaluated";
reason: | "no-rules"
| "unsupported"
| "not-a-rules-operation"
| "runtime-error"
| "external-execution";
};
An evaluated/deny disposition records a local rejection, not proof completeness
or Firebase parity. Consumers must also inspect accompanying queryProof.
What happened at the Security Rules seam. Admin is a lens; bypassed is
the rules disposition.
Type Declaration
{
kind: "evaluated";
verdict: "allow" | "deny";
}
kind
kind: "evaluated";
verdict
verdict: "allow" | "deny";
{
kind: "bypassed";
reason: "admin";
}
kind
kind: "bypassed";
reason
reason: "admin";
{
kind: "not-evaluated";
reason: | "no-rules"
| "unsupported"
| "not-a-rules-operation"
| "runtime-error"
| "external-execution";
}
kind
kind: "not-evaluated";
reason
reason:
| "no-rules"
| "unsupported"
| "not-a-rules-operation"
| "runtime-error"
| "external-execution";
External execution supplies an SDK outcome, without a local rules evaluation.
SandboxClockMode
type SandboxClockMode = "wall" | "fixed" | "offset";
How the clock is currently deriving now(). See the module header for what
each mode promises.
SandboxErrorCode
type SandboxErrorCode =
| "invalid-argument"
| "permission-denied"
| "not-found"
| "already-exists"
| "failed-precondition"
| "aborted"
| "unavailable"
| "unimplemented"
| "not-seeded"
| "rules-not-loaded";
Error codes raised by the sandbox layer.
The first batch matches Firebase / gRPC conventions so existing
if (e.code === 'permission-denied') code from production paths
keeps working. The second batch is sandbox-specific and exists so
agents can distinguish “sandbox doesn’t simulate this” from “your
code is wrong” without parsing message strings.
SandboxEvent
type SandboxEvent =
| RequestEvent
| WriteSandboxEvent
| SnapshotDeliveryEvent
| SnapshotSuppressedEvent
| ListenerLifecycleEvent
| SessionBoundaryEvent
| ServiceMutationEvent
| SandboxOperationEvent
| SandboxCommitEvent
| SandboxListenerEvent
| SandboxRuntimeErrorEvent
| SandboxObservationGapEvent & EventProvenance;
Discriminated union of every event the sandbox emits to Sandbox.onEvent subscribers.
Issue #307 — replaces the prior three-channel surface
(onRequest / onDenial / onSnapshotError). Filter on kind
to recover the subset each old channel covered:
- request:
kind === 'request' - denial:
kind === 'request' && result === 'deny' - snapshotError:
kind === 'listener_errored'
See the design rationale for the field-by-field rationale.
SandboxService
type SandboxService = typeof SANDBOX_SERVICES[number];
One service a full state carries.
ServiceEventOperation
type ServiceEventOperation<Service> = typeof SERVICE_EVENT_RECORDS[Service]["operations"][number];
The operations one service declared.
Type Parameters
| Type Parameter |
|---|
Service extends MutationEventService |
ServiceMutationEvent
type ServiceMutationEvent = { [Service in MutationEventService]: ServiceMutationEventOf<Service> }[MutationEventService];
The cross-service mutation envelope, as the union over every service that
declared an event record. Narrowing on service narrows op to that
service’s own operations.
ServiceMutationEventFields
type ServiceMutationEventFields = { [Service in MutationEventService]: Omit<ServiceMutationEventOf<Service>, "kind" | "id"> }[MutationEventService];
The fields a caller supplies to build a ServiceMutationEvent; kind
and id are the emitter’s. Distributed per service so op stays bound to
the service beside it.
StorageObjectState
type StorageObjectState = StorageObjectFields &
| {
contentBase64: string;
}
| {
sha256: string;
size: number;
};
One Storage object, with everything a reader of it can observe. Its bytes are either inline as base64, or named by SHA-256 in the backend that holds them: a capture by reference writes the second form, and only a backend that keeps content-addressed files can apply it.
Variables
MUTATION_EVENT_SERVICES
const MUTATION_EVENT_SERVICES: MutationEventService[];
Every declared service name, as a runtime list.
REMOTE_SANDBOX
const REMOTE_SANDBOX: unique symbol;
Brand stamped (value true) on every remote sandbox handle.
Symbol.for — registered globally so pyric-admin’s check matches the
stamp even if two copies of pyric end up in one process.
REMOTE_SANDBOX_FACTORY
const REMOTE_SANDBOX_FACTORY: unique symbol;
Well-known global key under which @pyric/cli/register installs the
remote-sandbox factory: globalThis[REMOTE_SANDBOX_FACTORY].
This is the AMBIENT-INIT seam (adoption experience, layer 3): when
pyric-admin/app’s bare initializeApp() sees PYRIC_SANDBOX=remote[:url]
it reads this global and calls the installed RemoteSandboxFactory
to obtain the branded handle — without importing @pyric/cli (which is
a devDependency of the app, not of pyric-admin). Symbol.for so the
installer and the reader agree even across duplicated copies of pyric.
SERVICE_EVENT_RECORDS
const SERVICE_EVENT_RECORDS: {
ai: {
operations: readonly ["generate_content", "stream_generate_content", "count_tokens", "request_rejected", "response_blocked", "model_substituted"];
service: "ai";
target: {
always: false;
description: "The model name the call named, e.g. gemini-2.5-flash.";
name: "model";
};
};
auth: {
operations: readonly ["user_create", "user_update", "user_delete", "users_clear", "sign_in", "sign_out", "provider_config_update"];
service: "auth";
target: {
always: false;
description: "The mutated user's uid, or '*' when every user was cleared.";
name: "uid";
};
};
functions: {
operations: readonly ["trigger_discovered", "handler_fired", "execution_finished"];
service: "functions";
target: {
always: false;
description: "The trigger's reference pattern on discovery, and the synthetic event's concrete path once a handler fires.";
name: "ref";
};
};
messaging: {
operations: readonly ["token_minted", "token_deleted", "subscription_changed", "message_accepted", "message_rejected", "delivery_routed", "message_delivered", "delivery_acknowledged"];
service: "messaging";
target: {
always: false;
description: "The registration token a token or subscription operation addressed.";
name: "token";
};
};
rtdb: {
operations: readonly ["set", "update", "remove", "transaction", "setPriority"];
service: "rtdb";
target: {
always: true;
description: "The database path the call targeted, e.g. /rooms/r1/messages.";
name: "path";
};
};
storage: {
operations: readonly ["object_put", "object_delete", "metadata_update"];
service: "storage";
target: {
always: true;
description: "The object's full path within the bucket, e.g. avatars/alice.png.";
name: "fullPath";
};
};
};
Keyed by the service name each record declares.
Type Declaration
ai
readonly ai: {
operations: readonly ["generate_content", "stream_generate_content", "count_tokens", "request_rejected", "response_blocked", "model_substituted"];
service: "ai";
target: {
always: false;
description: "The model name the call named, e.g. gemini-2.5-flash.";
name: "model";
};
};
ai.operations
readonly operations: readonly ["generate_content", "stream_generate_content", "count_tokens", "request_rejected", "response_blocked", "model_substituted"];
ai.service
readonly service: "ai";
ai.target
readonly target: {
always: false;
description: "The model name the call named, e.g. gemini-2.5-flash.";
name: "model";
};
ai.target.always
readonly always: false;
ai.target.description
readonly description: "The model name the call named, e.g. gemini-2.5-flash.";
ai.target.name
readonly name: "model";
auth
readonly auth: {
operations: readonly ["user_create", "user_update", "user_delete", "users_clear", "sign_in", "sign_out", "provider_config_update"];
service: "auth";
target: {
always: false;
description: "The mutated user's uid, or '*' when every user was cleared.";
name: "uid";
};
};
auth.operations
readonly operations: readonly ["user_create", "user_update", "user_delete", "users_clear", "sign_in", "sign_out", "provider_config_update"];
auth.service
readonly service: "auth";
auth.target
readonly target: {
always: false;
description: "The mutated user's uid, or '*' when every user was cleared.";
name: "uid";
};
auth.target.always
readonly always: false;
auth.target.description
readonly description: "The mutated user's uid, or '*' when every user was cleared.";
auth.target.name
readonly name: "uid";
functions
readonly functions: {
operations: readonly ["trigger_discovered", "handler_fired", "execution_finished"];
service: "functions";
target: {
always: false;
description: "The trigger's reference pattern on discovery, and the synthetic event's concrete path once a handler fires.";
name: "ref";
};
};
functions.operations
readonly operations: readonly ["trigger_discovered", "handler_fired", "execution_finished"];
functions.service
readonly service: "functions";
functions.target
readonly target: {
always: false;
description: "The trigger's reference pattern on discovery, and the synthetic event's concrete path once a handler fires.";
name: "ref";
};
functions.target.always
readonly always: false;
functions.target.description
readonly description: "The trigger's reference pattern on discovery, and the synthetic event's concrete path once a handler fires.";
functions.target.name
readonly name: "ref";
messaging
readonly messaging: {
operations: readonly ["token_minted", "token_deleted", "subscription_changed", "message_accepted", "message_rejected", "delivery_routed", "message_delivered", "delivery_acknowledged"];
service: "messaging";
target: {
always: false;
description: "The registration token a token or subscription operation addressed.";
name: "token";
};
};
messaging.operations
readonly operations: readonly ["token_minted", "token_deleted", "subscription_changed", "message_accepted", "message_rejected", "delivery_routed", "message_delivered", "delivery_acknowledged"];
messaging.service
readonly service: "messaging";
messaging.target
readonly target: {
always: false;
description: "The registration token a token or subscription operation addressed.";
name: "token";
};
messaging.target.always
readonly always: false;
messaging.target.description
readonly description: "The registration token a token or subscription operation addressed.";
messaging.target.name
readonly name: "token";
rtdb
readonly rtdb: {
operations: readonly ["set", "update", "remove", "transaction", "setPriority"];
service: "rtdb";
target: {
always: true;
description: "The database path the call targeted, e.g. /rooms/r1/messages.";
name: "path";
};
};
rtdb.operations
readonly operations: readonly ["set", "update", "remove", "transaction", "setPriority"];
rtdb.service
readonly service: "rtdb";
rtdb.target
readonly target: {
always: true;
description: "The database path the call targeted, e.g. /rooms/r1/messages.";
name: "path";
};
rtdb.target.always
readonly always: true;
rtdb.target.description
readonly description: "The database path the call targeted, e.g. /rooms/r1/messages.";
rtdb.target.name
readonly name: "path";
storage
readonly storage: {
operations: readonly ["object_put", "object_delete", "metadata_update"];
service: "storage";
target: {
always: true;
description: "The object's full path within the bucket, e.g. avatars/alice.png.";
name: "fullPath";
};
};
storage.operations
readonly operations: readonly ["object_put", "object_delete", "metadata_update"];
storage.service
readonly service: "storage";
storage.target
readonly target: {
always: true;
description: "The object's full path within the bucket, e.g. avatars/alice.png.";
name: "fullPath";
};
storage.target.always
readonly always: true;
storage.target.description
readonly description: "The object's full path within the bucket, e.g. avatars/alice.png.";
storage.target.name
readonly name: "fullPath";
Functions
activeListeners()
function activeListeners(events: readonly SandboxEvent[]): readonly ActiveListener[];
Every listener the sandbox holds attached right now, folded from its whole event history. Order is attach order; a listener that detached and reattached under the same id is folded from its most recent attach.
Parameters
| Parameter | Type |
|---|---|
events | readonly SandboxEvent[] |
Returns
readonly ActiveListener[]
activeListenerTargetStartsWith()
function activeListenerTargetStartsWith(target: ActiveListenerTarget, prefix: string): boolean;
Whether a listener’s target starts with a caller-supplied prefix. A query-shaped target is matched on its collection.
Parameters
| Parameter | Type |
|---|---|
target | ActiveListenerTarget |
prefix | string |
Returns
boolean
apply()
function apply(branch: Branch, events: readonly SandboxEvent[]): Branch;
Parameters
| Parameter | Type |
|---|---|
branch | Branch |
events | readonly SandboxEvent[] |
Returns
applyFullState()
function applyFullState(sandbox: LocalSandbox, state: FullSandboxState): Promise<void>;
Replace one sandbox’s entire state with state.
A total replace, not a merge: state the target holds and the capture does
not is removed. After this returns, every read captureFullState
covers answers exactly what state holds.
Parameters
| Parameter | Type |
|---|---|
sandbox | LocalSandbox |
state | FullSandboxState |
Returns
Promise<void>
attachPersistence()
function attachPersistence(sandbox: Sandbox, rawOptions: SandboxPersistenceOptions): Promise<PersistenceController>;
Construct a controller, restore any prior snapshot, and wire the
auto-flush subscription. Returns once restore has completed (callers
can await sandbox.enablePersistence(...) and be sure the in-memory
state reflects the persisted blob).
Late service registration: services (e.g. auth) may register with the
sandbox AFTER this call returns (the user calls enablePersistence
then later getAuth(sandbox) which triggers registerPersistableService).
We handle this in two parts:
restore()returns the rawservicesblob map so the controller can apply it to late-arriving services.setServiceRegistrationHookfires on each registration — we immediately apply the saved blob data (if any) AND subscribe the service’s change notifier for future flushes.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
rawOptions | SandboxPersistenceOptions |
Returns
Promise<PersistenceController>
attachTabSync()
function attachTabSync(sandbox: LocalSandbox, options?: TabSyncOptions): () => void;
Attach cross-tab sync to a sandbox. Called by SandboxImpl.enableTabSync;
kept in a separate module so sandbox-impl.ts stays thin.
Returns a disable function: calling it unsubscribes the onEvent listener,
removes the channel message listener, and closes the channel.
Parameters
| Parameter | Type | Description |
|---|---|---|
sandbox | LocalSandbox | The sandbox to sync. Must expose onEvent, admin, and snapshot. |
options? | TabSyncOptions | Optional channel and origin override. |
Returns
(): void;
Returns
void
bundleRecords()
function bundleRecords(records: ReadonlyMap<string, unknown>): string;
Bundle v3 records into one committable JSON string, for single-blob stores
(serve’s exportable .pyric/state file, an HTTP state endpoint). Inverse of
parseBundle. This deliberately collapses the chunking into one blob:
it is the single-artifact EXPORT shape, not the scale path (that is the
record-shaped backend).
Parameters
| Parameter | Type |
|---|---|
records | ReadonlyMap<string, unknown> |
Returns
string
captureFullState()
function captureFullState(sandbox: LocalSandbox, options?: FullStateCaptureOptions): Promise<FullSandboxState>;
Read one sandbox’s entire state.
A pure read: every service is reached through its own export seam, nothing is written, and two captures with no intervening write are identical values.
Parameters
| Parameter | Type |
|---|---|
sandbox | LocalSandbox |
options? | FullStateCaptureOptions |
Returns
Promise<FullSandboxState>
createIndexedDBBackend()
function createIndexedDBBackend(): PersistenceBackend;
Build an IndexedDB-backed PersistenceBackend. Throws synchronously when
called outside a browser (no indexedDB global) so callers can detect the
absence and fall back to memory.
Returns
createMemoryBackend()
function createMemoryBackend(): PersistenceBackend;
Returns
deserializeFromBuckets()
function deserializeFromBuckets(records: Iterable<[string, unknown]>, options?: {
skipInvalidDocuments?: boolean;
}): {
firestore: Record<string, Record<string, unknown>>;
services: Record<string, unknown>;
};
Reassemble a firestore snapshot + services from v3 records (any iterable of [recordId, record] pairs). Rehydrates wrapper types from their markers.
Parameters
| Parameter | Type |
|---|---|
records | Iterable<[string, unknown]> |
options? | { skipInvalidDocuments?: boolean; } |
options.skipInvalidDocuments? | boolean |
Returns
{
firestore: Record<string, Record<string, unknown>>;
services: Record<string, unknown>;
}
firestore
firestore: Record<string, Record<string, unknown>>;
services
services: Record<string, unknown>;
diff()
function diff(branch: Branch, target: DiffTarget): Promise<BranchDivergence[]>;
Every difference between a branch’s current state and a reference, across
every service. Each record names its service and the path or uid it
concerns, with the reference’s value as before and the branch’s as
after.
Parameters
| Parameter | Type | Description |
|---|---|---|
branch | Branch | The experiment. |
target | DiffTarget | A live sandbox, or a state captured from one. |
Returns
Promise<BranchDivergence[]>
diffFullStates()
function diffFullStates(before: FullSandboxState, after: FullSandboxState): BranchDivergence[];
Every difference between two full sandbox states, ordered service by service: Firestore, then the Realtime Database, then Storage, then auth, then rules.
before is the reference and after is the state being described, so a
record’s before and after read the way a caller asking “what would
landing this change do” expects.
Parameters
| Parameter | Type |
|---|---|
before | FullSandboxState |
after | FullSandboxState |
Returns
discard()
function discard(branch: Branch): void;
Discard a branch: drop its sandbox and mark it spent. The target is never touched, because nothing was promoted. Idempotent.
Parameters
| Parameter | Type |
|---|---|
branch | Branch |
Returns
void
fork()
function fork(base: FullSandboxState, candidate?: string | BranchCandidateRules): Promise<Branch>;
Fork a new branch from a captured full state.
The branch’s sandbox reads identically to the state it was forked from in every service, and writes on it never reach the source.
Parameters
| Parameter | Type | Description |
|---|---|---|
base | FullSandboxState | The baseline, typically await captureFullState(live). |
candidate? | string | BranchCandidateRules | Rule sources to run the branch under in place of the baseline’s. A string is read as a Realtime Database ruleset when it parses as JSON with a rules key, and as Firestore rules otherwise. An object names each service explicitly. |
Returns
Promise<Branch>
getClock()
function getClock(sandbox: Sandbox): SandboxClock;
Resolve one sandbox’s clock. The clock is the sandbox’s whole notion of
time: every serverTimestamp(), request.time, token iat, and event stamp
on that sandbox reads it, so moving it here moves all of them.
The clock survives sandbox.reset(), which swaps the Firestore environment
but not the sandbox: a pinned instant is a property of the session, not of
the data in it.
Throws if sandbox was not produced by initializeSandbox(), the same guard
getInternalEnv applies.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
holdsBytesInline()
function holdsBytesInline(object: StorageObjectState): object is StorageObjectState & { contentBase64: string };
Whether a Storage entry carries its bytes inline.
Parameters
| Parameter | Type |
|---|---|
object | StorageObjectState |
Returns
object is StorageObjectState & { contentBase64: string }
initializeSandbox()
function initializeSandbox(_config?: SandboxConfig): LocalSandbox;
Create a sandbox.
Identity is not part of init — call sandbox.withAuth(...) to
derive a SandboxContext for service operations. Service-
specific configuration (rules, seed data) happens through service-specific
sandbox controls — for example, setRules(sandbox, source) from
pyric/sandbox/firestore.
Parameters
| Parameter | Type |
|---|---|
_config? | SandboxConfig |
Returns
Example
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore } from 'pyric-admin/firestore';
const sandbox = initializeSandbox();
const dbAlice = getFirestore(sandbox.withAuth({ uid: 'alice' }));
const dbAnon = getFirestore(sandbox.withAuth(null));
isOperationEvent()
function isOperationEvent(event: SandboxEvent): event is OperationEvent;
Parameters
| Parameter | Type |
|---|---|
event | SandboxEvent |
Returns
event is OperationEvent
isRemoteSandbox()
function isRemoteSandbox(sandbox: Sandbox): sandbox is RemoteSandbox;
Is this sandbox a remote handle? Backend dispatch guard for consumers
(e.g. pyric-admin’s RTDB/Auth sandbox backends) that must route a
remote sandbox’s operations through RemoteSandbox.channel rather
than into process-local state.
Parameters
| Parameter | Type |
|---|---|
sandbox | Sandbox |
Returns
sandbox is RemoteSandbox
normalizeAuthState()
function normalizeAuthState(auth: {
tenant?: string;
token?: Record<string, unknown>;
uid: string;
}): {
tenant?: string;
token?: Record<string, unknown>;
uid: string;
};
Normalize an AuthState before rules read it.
Automatically projects top-level tenant into token.firebase.tenant
while preserving custom claims and explicit nested token overrides.
Never mutates original input.
Parameters
| Parameter | Type |
|---|---|
auth | { tenant?: string; token?: Record<string, unknown>; uid: string; } |
auth.tenant? | string |
auth.token? | Record<string, unknown> |
auth.uid | string |
Returns
{
tenant?: string;
token?: Record<string, unknown>;
uid: string;
}
tenant?
optional tenant: string;
token?
optional token: Record<string, unknown>;
uid
uid: string;
operationContextFor()
function operationContextFor(event: Pick<EventProvenance, "operationContext" | "actor" | "authLens" | "planId">): OperationContext;
The canonical context on a recorded event. Old/pre-context events are explicitly unattributed rather than silently asserted to be app traffic.
Parameters
| Parameter | Type |
|---|---|
event | Pick<EventProvenance, "operationContext" | "actor" | "authLens" | "planId"> |
Returns
parseBundle()
function parseBundle(blob: string): Map<string, unknown>;
Parse a v3 bundle blob back into records. Returns an empty map for an unrecognized blob (e.g. a legacy v2 single-blob snapshot); migrate-on-open (a later commit) handles converting a v2 blob to v3 records.
Parameters
| Parameter | Type |
|---|---|
blob | string |
Returns
Map<string, unknown>
promote()
function promote(branch: Branch, target: LocalSandbox): Promise<void>;
Land a branch’s changes on a target, across every service.
Atomic from the caller’s point of view: the target’s full state is captured before the first write, and any throw restores that capture, rethrows the original error, and leaves the branch undiscarded so the caller can inspect or retry it. On success the branch is spent and its sandbox is disposed.
When the restore itself throws the target is not atomic any more, and the error says so: it carries the promotion’s message first and the restore’s after it, because a caller reading it needs to know both what failed and that the target still holds part of the change.
Parameters
| Parameter | Type |
|---|---|
branch | Branch |
target | LocalSandbox |
Returns
Promise<void>
promoteFullState()
function promoteFullState(
target: LocalSandbox,
base: FullSandboxState,
next: FullSandboxState): Promise<void>;
Write onto target everything that differs between the state a branch was
forked from and the state it holds now.
Not atomic on its own: a write that throws leaves the target part way
through. The caller that owns the target’s rollback is promote in
engine.ts, which captures the target first and restores it on any throw.
Parameters
| Parameter | Type |
|---|---|
target | LocalSandbox |
base | FullSandboxState |
next | FullSandboxState |
Returns
Promise<void>
recordBackendOverBlob()
function recordBackendOverBlob(io: {
clear: Promise<void>;
read: Promise<string>;
write: Promise<void>;
}): PersistenceBackend;
A record-shaped backend over a single-blob store (read/write/clear ONE blob). The whole record set is bundled into that blob, for serve’s committable export file / HTTP state endpoint and any single-key store. It loses chunking’s scale benefit by design (the blob IS the single artifact). The blob is loaded once and cached, so a restore (list + per-record get) costs one read, not one per record.
Parameters
| Parameter | Type |
|---|---|
io | { clear: Promise<void>; read: Promise<string>; write: Promise<void>; } |
io.clear | |
io.read | |
io.write |
Returns
rehydrateDocValue()
function rehydrateDocValue(value: unknown): unknown;
Restore persisted marker trees to rules values, including nested maps and arrays.
Parameters
| Parameter | Type |
|---|---|
value | unknown |
Returns
unknown
replay()
function replay(
events: readonly SandboxEvent[],
rules: string,
options?: ReplayOptions,
originalState?: Record<string, DocData>): ReplayResult;
Replay a captured SandboxEvent stream on a fresh sandbox.
The originalState snapshot is optional — when provided, the engine
diffs the replayed sandbox’s final state against it and returns
classified divergences. When omitted, divergences is [] (you still
get the replayed sandbox; you can inspect its state manually).
Parameters
| Parameter | Type |
|---|---|
events | readonly SandboxEvent[] |
rules | string |
options? | ReplayOptions |
originalState? | Record<string, DocData> |
Returns
rulesDispositionFor()
function rulesDispositionFor(event: OperationEvent): RulesDisposition;
Normalize the legacy per-service markers exactly once, at the sandbox
stream seam. Consumers must not inspect detail.admin, origin, or the
presence of a trace themselves.
Parameters
| Parameter | Type |
|---|---|
event | OperationEvent |
Returns
serializeToBuckets()
function serializeToBuckets(
firestore: Record<string, Record<string, unknown>>,
services: Record<string, unknown>,
savedAt: number): Map<string, BucketRecord | MetaRecord>;
Partition a firestore doc map into v3 records: one bucket record per occupied
bucket plus the meta record. The returned map’s keys are record ids; values
are structured-clone-safe.
Parameters
| Parameter | Type |
|---|---|
firestore | Record<string, Record<string, unknown>> |
services | Record<string, unknown> |
savedAt | number |
Returns
Map<string, BucketRecord | MetaRecord>
toListenerRecord()
function toListenerRecord(event: SandboxEvent): OperationRecord;
Project one listener lifecycle event into the canonical record, with the
phase as the record’s method.
Firestore reports lifecycle through its own listener_attach /
listener_detach / listener_errored / snapshot_delivery /
snapshot_suppressed variants; every other service reports it through the
canonical listener variant. Both arrive here as the same five phases, so a
caller paging listener activity never has to know which service produced it.
Returns null for anything that is not listener lifecycle.
Parameters
| Parameter | Type |
|---|---|
event | SandboxEvent |
Returns
toOperationRecord()
function toOperationRecord(input: SandboxEvent): OperationRecord;
Project either traffic event family into the canonical record.
Parameters
| Parameter | Type |
|---|---|
input | SandboxEvent |
Returns
trafficOperationEvent()
function trafficOperationEvent(event: SandboxEvent): OperationEvent;
Auth changes have no rules seam; normalize their recorded outcome alongside data operations.
Parameters
| Parameter | Type |
|---|---|
event | SandboxEvent |
Returns
OperationEvent
validateAuthState()
function validateAuthState(auth: unknown): asserts auth is { tenant?: string; token?: Record<string, unknown>; uid: string };
Reject undefined and other clearly-malformed inputs at the
withAuth call site. null is valid (anonymous);
{ uid: 'someUid' } is valid; everything else throws so the
mistake surfaces at the boundary instead of leaking into rule
eval as a confusing denial.
Shared between Sandbox.withAuth and SandboxContext.withAuth
so both entries enforce the same validation.
Parameters
| Parameter | Type |
|---|---|
auth | unknown |
Returns
asserts auth is { tenant?: string; token?: Record<string, unknown>; uid: string }
wallClockState()
function wallClockState(): SandboxClockState;
The state a clock that has never been moved reports.
Returns
References
AuthLens
Re-exports AuthLens
AuthState
Re-exports AuthState
Sandbox
Re-exports Sandbox
SandboxContext
Re-exports SandboxContext
SandboxError
Re-exports SandboxError