Pyric
Navigate

API reference

pyric/rules

94 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

RulesAssertionError

Thrown by assertCase / a runner case’s run() when the simulated decision did not match the case’s expectation. The message is the rendered trace from explainCase, so a test runner surfaces the “why” without extra wiring.

Extends

  • Error

Constructors

Constructor
new RulesAssertionError(message: string): RulesAssertionError;
Parameters
ParameterType
messagestring
Returns

RulesAssertionError

Overrides
Error.constructor

RulesCompileError

Thrown by firestoreRules(source) / rtdbRules(...) when the source cannot compile. Carries the compile-blocking issues on .issues so a caller can surface them without re-parsing.

Extends

  • Error

Constructors

Constructor
new RulesCompileError(message: string, issues: RuleIssue[]): RulesCompileError;
Parameters
ParameterType
messagestring
issuesRuleIssue[]
Returns

RulesCompileError

Overrides
Error.constructor

Properties

PropertyModifierType
issuesreadonlyRuleIssue[]

RulesUnsupportedError

Thrown by assertCase / a runner case’s run() when the simulator abstained — it hit a feature it does not implement, so neither a pass nor a genuine failure can be asserted. Distinct from RulesAssertionError so a runner can choose to skip rather than fail on a known simulator gap.

Extends

  • Error

Constructors

Constructor
new RulesUnsupportedError(message: string): RulesUnsupportedError;
Parameters
ParameterType
messagestring
Returns

RulesUnsupportedError

Overrides
Error.constructor

Interfaces

CaseResult

The outcome of running one Firestore case through simulate. Never a thrown error — a denied or abstained case is data, not an exception.

Properties

PropertyTypeDescription
caseFirestoreCaseThe case that produced this result.
decision"UNSUPPORTED" | "ALLOW" | "DENY"The engine’s absolute verdict, independent of expectation.
descriptionstring-
expectation"ALLOW" | "DENY"-
notesstring[]Top-level diagnostic strings.
passedbooleantrue when decision matched expectation.
pathResolution?PathResolutionTraceWhich match blocks the resolver considered and where each fell apart.
traceRuleEvaluation[]Per-rule evaluation entries in source order.
unsupportedbooleantrue when the simulator abstained on a feature it does not implement — neither a pass nor a genuine failure.

EvaluatedRuleInfo

The DECIDING rule’s source position + sub-expression trace, projected from a TestResult — for BOTH verdicts: the allow rule that granted an ALLOW, or the rule responsible for a DENY. Additive companion to renderLegacyDebugMessages: that flattens the per-rule trace to strings (dropping line and expressionTrace); this preserves the structured detail a UI needs to point at the exact source line and step through the evaluation (“show the work”). Position/trace fields are optional so a partial trace projects honestly.

Properties

PropertyTypeDescription
citation?string-
col?number-
column?number-
expression?stringPretty-printed condition text of the deciding rule.
expressionTrace?ExprTraceEntry[]Per-sub-expression evaluation trace of the deciding rule.
file?string-
line?number1-indexed source line of the deciding allow rule.
verdict"allow" | "deny"The verdict the deciding rule produced for the op.

Explanation

The structured account of why one Firestore case resolved as it did.

Properties

PropertyTypeDescription
deciding?EvaluatedRuleInfoThe deciding allow rule (line, condition text, sub-expression trace), when one was evaluated. Absent on default-deny / abstain.
decision"UNSUPPORTED" | "ALLOW" | "DENY"-
expectation"ALLOW" | "DENY"-
notesstring[]-
passedboolean-
pathResolution?PathResolutionTrace-
traceRuleEvaluation[]-
unsupportedboolean-

ExprTraceEntry

One entry in a per-rule expression trace, emitted in evaluation order.

Properties

PropertyType
error?string
inlinedFrom?{ name: string; }
inlinedFrom.namestring
kind| "literal" | "identifier" | "memberAccess" | "methodCall" | "bracketAccess" | "sliceAccess" | "binaryOp" | "unaryOp" | "ternary" | "inExpr" | "isExpr" | "listLiteral" | "mapLiteral" | "pathLiteral" | "functionCall"
letBinding?{ name: string; }
letBinding.namestring
parentnumber
skipped?boolean
sourcestring
value?unknown

FirestoreCase

One Firestore rules case: a single request plus the outcome it should produce. Structurally identical to the engine’s TestCase — re-exported here under the public name so callers never reach into the engine seam.

Properties

PropertyTypeDescription
auth?{ token?: Record<string, unknown>; uid: string; }Auth context; null/omitted for unauthenticated.
auth.token?Record<string, unknown>-
auth.uidstring-
data?Record<string, unknown>request.resource.data for write operations.
descriptionstringHuman-readable description of what this case verifies.
expectation"ALLOW" | "DENY"Expected outcome.
functionMocks?{ function: "get" | "exists"; path: string; result: boolean | Record<string, unknown>; }[]Mock get() / exists() calls the rules make.
method"delete" | "get" | "list" | "create" | "update"Firestore method under test.
pathstringDocument path, e.g. "users/alice".
query?{ limit?: number; offset?: number; orderBy?: string; }request.query payload (list ops only): limit/offset/orderBy.
query.limit?number-
query.offset?number-
query.orderBy?string-
requestTime?stringOverride for request.time (ISO-8601). Defaults to wallclock.
resource?Record<string, unknown>Existing document data (resource.data).
writeMode?| { kind: "create"; } | { kind: "set"; merge: boolean; } | { kind: "update"; } | { kind: "delete"; }Explicit write semantics — controls update-merge and getAfter() projection. Omit to treat data as the full after-state.

FirestoreRuleset

Methods

explain()
explain(oneCase: FirestoreCase): Explanation;

The structured account of why one case resolved as it did.

Parameters
ParameterType
oneCaseFirestoreCase
Returns

Explanation

lint()
lint(): RuleIssue[];

Structural, security, and budget findings on the compiled ruleset. No parse errors — the source already compiled.

Returns

RuleIssue[]

simulate()
simulate(cases: FirestoreCase[]): SimulationSummary;

Run every case. Never throws on a rule outcome: a denied or abstained case is reported in the returned summary.

Parameters
ParameterType
casesFirestoreCase[]
Returns

SimulationSummary

toJSON()
toJSON(): FirestoreRules;

The parsed ruleset as plain data (the AST).

Returns

FirestoreRules


PathDef

Definition of rules for a single database path.

Properties

PropertyType
children?Record<string, PathDef>
fieldConstraints?Record<string, Expr[]>
indexOn?string[]
read?string
schema?ZodObject<any>
validate?string
write?string

PathResolutionEntry

One match block the simulator considered while resolving the request path. Together, PathResolutionTrace.attempts forms a complete picture of “what did the resolver try, and where did each attempt fall apart?” — useful for the agent when a request lands in the default-deny path because no block matched.

Recorded only by the local simulator; the production Test API client doesn’t expose path-resolution internals.

Properties

PropertyTypeDescription
bindingsRecord<string, string>Wildcard / recursive bindings the block produced (even when the overall match failed — the partial bindings are still diagnostic).
blockPathstringRaw match path as written in the source, e.g. '/users/{uid}/messages/{mId}'.
line?numberSource line of the match keyword. Absent when the parser didn’t populate loc (programmatically-constructed blocks).
matchedbooleanTrue for a block that fully resolved (no remaining request segments AND every nested match either completed or wasn’t needed). MULTIPLE entries may be matched: true in one trace: a request path can match several overlapping match blocks (e.g. /docs/{doc} and a sibling /{document=**}), and every matching block’s allows OR-combine. Container blocks whose children completed the resolution are also flagged matched.
matchedSegmentsnumberHow many of the block’s path segments matched against the request path before the resolver gave up or completed.
reason?"literal-mismatch" | "request-shorter" | "no-matching-child"Why the resolver moved on. Absent when matched: true. - 'literal-mismatch' — a literal segment in the block didn’t match the corresponding request segment. - 'request-shorter' — block path had more segments than the request supplied (e.g. block is /a/{b}/c, request is /a/x). - 'no-matching-child' — block matched its own segments but remaining request segments weren’t covered by any child block.
totalSegmentsnumberTotal segments in the block’s path pattern.

PathResolutionTrace

Properties

PropertyTypeDescription
attemptsPathResolutionEntry[]One entry per match block the resolver considered, in the order it tried them. attempts[i].matched: true marks a block that fully resolved; one or more per trace, since overlapping blocks all match and OR-combine.
requestPathstringThe request path that was resolved, verbatim from TestCase.path.

RtdbCase

One Realtime Database rules case. expectation is required so a simulate run can partition cases into passed/failed the same way Firestore does — the RTDB simulator otherwise returns only a raw allow/deny with no notion of an expectation.

Properties

PropertyTypeDescription
auth?| string | { token?: Record<string, unknown>; uid: string; }Auth context; a bare uid string, a full identity, or null.
data?Record<string, unknown>Existing tree data the rule reads (data).
description?stringHuman-readable description of what this case verifies.
expectation"ALLOW" | "DENY"Expected outcome.
newData?unknownProposed write value (newData), for write/validate cases.
operation"read" | "write" | "validate"RTDB rule kind under test.
pathstringAbsolute, root-relative tree path, e.g. "/users/alice".

RtdbCaseResult

The outcome of running one RTDB case through simulate.

Properties

PropertyTypeDescription
caseRtdbCase-
decision"UNSUPPORTED" | "ALLOW" | "DENY"-
description?string-
expectation"ALLOW" | "DENY"-
matchedPathstringThe tree path whose rule decided the request.
matchedRulestringWhich rule kind (.read / .write / .validate) decided.
passedboolean-
reasonstringEngine-provided reason string.
unsupportedboolean-

RtdbExplanation

Properties

PropertyType
decision"UNSUPPORTED" | "ALLOW" | "DENY"
expectation"ALLOW" | "DENY"
matchedPathstring
matchedRulestring
passedboolean
reasonstring
unsupportedboolean

RtdbRulesCheckResult

Properties

PropertyType
errorsRtdbRulesFinding[]
okboolean
warningsRtdbRulesFinding[]

RtdbRulesDefinition

Properties

PropertyType
paths| Record<string, PathDef> | (ctx: RulesetContext) => void

RtdbRulesDocument

The authored RTDB rules artifact defineRtdbRules returns.

Deliberately INERT on the public surface: it exposes no methods. It is a value you author and hand to rtdbRules(), which is the one analysis surface (lint / simulate / explain / toJSON). The brand is type-level only; nothing exists at runtime.

Properties

PropertyModifierType
[RTDB_RULES_DOCUMENT_BRAND]?readonlynever

RtdbRuleset

Methods

explain()
explain(oneCase: RtdbCase): RtdbExplanation;

The structured account of why one case resolved as it did.

Parameters
ParameterType
oneCaseRtdbCase
Returns

RtdbExplanation

lint()
lint(): RuleIssue[];

Structural findings on the compiled ruleset (from check()).

Returns

RuleIssue[]

simulate()
simulate(cases: RtdbCase[]): RtdbSimulationSummary;

Run every case. Never throws on a rule outcome.

Parameters
ParameterType
casesRtdbCase[]
Returns

RtdbSimulationSummary

toJSON()
toJSON(): RtdbRulesJson;

The compiled rules.json.

Returns

RtdbRulesJson


RtdbRulesFinding

Properties

PropertyType
codestring
messagestring
pathstring
ruleRtdbRulesFindingRule

RtdbSimulationSummary

Properties

PropertyType
casesRtdbCaseResult[]
failednumber
passednumber
unsupportednumber

RuleEvaluation

Per-rule evaluation entry produced by the local simulator. Each entry corresponds to one allow declaration the simulator evaluated, in source order.

Populated only by the internal simulator (which has the parsed AST in hand); the production Test API client (TestFirestoreRulesHandler) returns an empty trace and surfaces the wire text on TestResult.notes.

Properties

PropertyTypeDescription
citation?string-
col?number-
column?number-
conditionText?stringPretty-printed condition expression. Use this verbatim in agent-facing summaries — derived from the AST via printExpression, so it survives comment removal and whitespace re-flow in the source.
expressionTrace?ExprTraceEntry[]Per-sub-expression evaluation trace for this rule’s condition. Flat, in evaluation order; reconstruct the tree via the parent index on each entry. Populated by the local simulator when the caller enables tracing — currently always on for the simulator so agents can see why a rule’s condition resolved as it did (which disjunct was true, which let binding the value flowed through, which method call threw). Absent on entries that came from the production Test API client (no AST visibility).
file?string-
line?number1-indexed source line of the allow keyword. Populated when the rule’s loc was set by the parser.
matchPath?stringSource-rendered path of the match block this rule belongs to, e.g. '/docs/{docId}' or '/{document=**}'. Populated when the request path matches MORE THAN ONE overlapping match block: allows OR-combine across every matching block (production semantics — there is no first-match-wins), so a DENY trace can carry entries from several blocks. This field keeps them unambiguous — which block did this rule live in. Absent for the common single-block case.
message?stringHuman-readable diagnostic — populated for UNSUPPORTED (which sim surface is missing) and ERROR (which runtime error caused the rule to abort).
operations("read" | "write" | "delete" | "get" | "list" | "create" | "update")[]Operations declared on the allow rule (read, write, get, …).
ruleIndexnumberPosition of the allow declaration within its match block, 0-indexed in source order.
verdict"ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"Outcome for this single rule. The TestResult’s overall decision is derived from the trace under OR semantics (any 'ALLOW' ⇒ ALLOW, else any 'UNSUPPORTED' ⇒ UNSUPPORTED, else DENY).

RuleIssue

Properties

PropertyTypeDescription
codestringStable machine code, e.g. 'PARSE_ERROR', 'SEC-4', 'GET_BUDGET'.
fix?stringSuggested remediation, verbatim, when the producing stage offers one.
line?number1-indexed source line, when known.
messagestringHuman-readable description.
originRuleIssueOrigin-
path?stringRules path the issue applies to, when known (e.g. '/users/{uid}').
severityRuleIssueSeverity-

RulesetContext

Context passed to the callback overload of ruleset().

Properties

PropertyType
path(path: string, def: PathDef) => void

SchemaRulesResult

Properties

PropertyType
childrenRecord<string, { children?: Record<string, { validate: Expr; }>; validate: Expr; }>
validatestring

SimulationSummary

Aggregate of a simulate(cases) run. Counts partition the cases: passed + failed + unsupported === cases.length.

Properties

PropertyType
casesCaseResult[]
failednumber
passednumber
unsupportednumber

Type Aliases

Expr

type Expr = string;

Type alias for RTDB rule expression strings.


FirestoreMethod

type FirestoreMethod = typeof FIRESTORE_METHODS[number];

RtdbRulesFindingRule

type RtdbRulesFindingRule = ".read" | ".write" | ".validate" | "ruleset";

RtdbRulesJson

type RtdbRulesJson = {
  rules: Record<string, unknown>;
};

Properties

PropertyType
rulesRecord<string, unknown>

RtdbRulesSimulationAuth

type RtdbRulesSimulationAuth =
  | string
  | {
  token?: Record<string, unknown>;
  uid: string;
}
  | null;

RtdbRulesSimulationInput

type RtdbRulesSimulationInput = Omit<SimulationInput, "auth" | "mockData"> & {
  auth?: RtdbRulesSimulationAuth;
  data?: Record<string, unknown>;
  mockData?: Record<string, unknown>;
};

Type Declaration

auth?
optional auth: RtdbRulesSimulationAuth;
data?
optional data: Record<string, unknown>;
mockData?
optional mockData: Record<string, unknown>;

RuleIssueOrigin

type RuleIssueOrigin = "parse" | "validate" | "lint";

The stage that produced the issue.

  • parse — the source did not parse; nothing downstream ran.
  • validate — a structural/security finding on a parsed ruleset.
  • lint — a budget/quality/hallucination warning.

RuleIssueSeverity

type RuleIssueSeverity = "error" | "warning" | "info";

Ordered by decreasing urgency. info is advisory.


Segment

type Segment =
  | string
  | {
  $: string;
};

A path segment: string for literal, { $: name } for path variable.

Variables

all()

const all: (...exprs: Expr[]) => Expr;

All conditions must be true (AND).

Parameters

ParameterType
exprsExpr[]

Returns

Expr


allow()

const allow: () => Expr;

Always allow (true). Readable alias for always().

Returns

Expr


always()

const always: () => Expr;

Always allow (true).

Returns

Expr


any()

const any: (...exprs: Expr[]) => Expr;

At least one condition must be true (OR).

Parameters

ParameterType
exprsExpr[]

Returns

Expr


AUTH_UID

const AUTH_UID: Segment;

auth.uid as a comparison value (unquoted in expressions)


authenticated()

const authenticated: () => Expr;

Returns

Expr


dataExists()

const dataExists: (path?: string) => Expr;

Check if data exists at current node or a child path

Parameters

ParameterType
path?string

Returns

Expr


dataParentVal()

const dataParentVal: (depth: number, field: string) => Expr;

Navigate up from data snapshot, then read a child field’s value

Parameters

ParameterType
depthnumber
fieldstring

Returns

Expr


dataVal()

const dataVal: (path?: string) => Expr;

Read data value at current node or a child path (pre-write state)

Parameters

ParameterType
path?string

Returns

Expr


deny()

const deny: () => Expr;

Always deny (false).

Returns

Expr


eq()

const eq: (left: Expr, right: CompareValue) => Expr;

Strict equality: left === right (right is a literal value or runtime ref)

Parameters

ParameterType
leftExpr
rightCompareValue

Returns

Expr


expr()

const expr: (raw: string) => Expr;

Create an Expr from a raw expression string.

Parameters

ParameterType
rawstring

Returns

Expr


fieldEnum()

const fieldEnum: (field: string, values: string[]) => Expr;

Field must be one of the allowed string values

Parameters

ParameterType
fieldstring
valuesstring[]

Returns

Expr


fieldIsBoolean()

const fieldIsBoolean: (field: string) => Expr;

Field must be a boolean

Parameters

ParameterType
fieldstring

Returns

Expr


fieldIsNumber()

const fieldIsNumber: (field: string) => Expr;

Field must be a number

Parameters

ParameterType
fieldstring

Returns

Expr


fieldIsString()

const fieldIsString: (field: string) => Expr;

Field must be a string

Parameters

ParameterType
fieldstring

Returns

Expr


fieldOwnerOnly()

const fieldOwnerOnly: (field: string) => Expr;

Only the field owner (auth.uid === data.child(field).val()) can access

Parameters

ParameterType
fieldstring

Returns

Expr


gt()

const gt: (left: Expr, right: number) => Expr;

Greater than: left > right

Parameters

ParameterType
leftExpr
rightnumber

Returns

Expr


hasChild()

const hasChild: (field: string) => Expr;

Incoming data must have a specific child field

Parameters

ParameterType
fieldstring

Returns

Expr


hasChildren()

const hasChildren: () => Expr;

Incoming data must be an object with at least one child

Returns

Expr


hasRole()

const hasRole: (segments: Segment[], role: string) => Expr;

Cross-path role check via root lookup

Parameters

ParameterType
segmentsSegment[]
rolestring

Returns

Expr


immutable()

const immutable: (field: string) => Expr;

Field can be set on creation but never changed after

Parameters

ParameterType
fieldstring

Returns

Expr


immutableSelf()

const immutableSelf: () => Expr;

This node’s own value can be set on creation but never changed

Returns

Expr


isMember()

const isMember: (listName: string, pathVarName: string) => Expr;

Cross-path membership check: root.child(list).child($var).child(auth.uid).exists()

Parameters

ParameterType
listNamestring
pathVarNamestring

Returns

Expr


isNew()

const isNew: () => Expr;

Data at this path doesn’t exist yet (creation check)

Returns

Expr


lte()

const lte: (left: Expr, right: number) => Expr;

Less than or equal: left <= right

Parameters

ParameterType
leftExpr
rightnumber

Returns

Expr


neq()

const neq: (left: Expr, right: CompareValue) => Expr;

Strict inequality: left !== right

Parameters

ParameterType
leftExpr
rightCompareValue

Returns

Expr


newDataExists()

const newDataExists: (path?: string) => Expr;

Check if incoming data exists at current node or a child path

Parameters

ParameterType
path?string

Returns

Expr


newDataIs()

const newDataIs: (type: "String" | "Number" | "Boolean") => Expr;

Check incoming data type at current node

Parameters

ParameterType
type"String" | "Number" | "Boolean"

Returns

Expr


newDataParentExists()

const newDataParentExists: (depth: number, field: string) => Expr;

Navigate up from newData snapshot, then check if a child field exists

Parameters

ParameterType
depthnumber
fieldstring

Returns

Expr


newDataParentVal()

const newDataParentVal: (depth: number, field: string) => Expr;

Navigate up from newData snapshot, then read a child field’s value

Parameters

ParameterType
depthnumber
fieldstring

Returns

Expr


newDataVal()

const newDataVal: (path?: string) => Expr;

Read incoming data value at current node or a child path (post-write state)

Parameters

ParameterType
path?string

Returns

Expr


not()

const not: (e: Expr) => Expr;

Negate a condition.

Parameters

ParameterType
eExpr

Returns

Expr


ownerOrNew()

const ownerOrNew: (field: string) => Expr;

Anyone authenticated can create; only the field owner can edit

Parameters

ParameterType
fieldstring

Returns

Expr


ownField()

const ownField: (field: string) => Expr;

Field-based ownership: auth.uid matches a value stored in a data field

Parameters

ParameterType
fieldstring

Returns

Expr


ownPath()

const ownPath: (pathVar: string) => Expr;

Path-based ownership: auth.uid matches a URL path variable

Parameters

ParameterType
pathVarstring

Returns

Expr


pathOwnerOnly()

const pathOwnerOnly: (pathVar: string) => Expr;

Only the path owner (auth.uid === $pathVar) can access

Parameters

ParameterType
pathVarstring

Returns

Expr


required()

const required: (...fields: string[]) => Expr;

All specified fields must be present in the incoming data

Parameters

ParameterType
fieldsstring[]

Returns

Expr


rootEquals()

const rootEquals: (segments: Segment[], value: string) => Expr;

Check if a path’s value equals a specific string (via root)

Parameters

ParameterType
segmentsSegment[]
valuestring

Returns

Expr


rootExists()

const rootExists: (segments: Segment[]) => Expr;

Check if a path exists in the database (via root)

Parameters

ParameterType
segmentsSegment[]

Returns

Expr


transition()

const transition: (field: string, allowed: [string, string][]) => Expr;

State machine: only allowed transitions on a field

Parameters

ParameterType
fieldstring
allowed[string, string][]

Returns

Expr

Functions

assertCase()

Call Signature

function assertCase(result: CaseResult | RtdbCaseResult): void;

Throw when a case result did not pass. A simulator abstention throws RulesUnsupportedError; a genuine expectation mismatch throws RulesAssertionError. Both carry the explainCase trace as their message. Returns void on a passing result.

Parameters
ParameterType
resultCaseResult | RtdbCaseResult
Returns

void

Call Signature

function assertCase(ruleset: FirestoreRuleset, oneCase: FirestoreCase): void;

Simulate one case against a ruleset and throw on a miss — the runner form: for (const c of cases) test(c.description, () => assertCase(ruleset, c)).

Parameters
ParameterType
rulesetFirestoreRuleset
oneCaseFirestoreCase
Returns

void

Call Signature

function assertCase(ruleset: RtdbRuleset, oneCase: RtdbCase): void;

Throw when a case result did not pass. A simulator abstention throws RulesUnsupportedError; a genuine expectation mismatch throws RulesAssertionError. Both carry the explainCase trace as their message. Returns void on a passing result.

Parameters
ParameterType
rulesetRtdbRuleset
oneCaseRtdbCase
Returns

void

Call Signature

function assertCase(source: string, oneCase: FirestoreCase): void;

Convenience: compile Firestore source and assert one case against it.

Parameters
ParameterType
sourcestring
oneCaseFirestoreCase
Returns

void


bytes()

function bytes(input: string | Uint8Array<ArrayBufferLike>): Bytes;

A bytes value.

  • string → UTF-8 encoded
  • Uint8Array → used verbatim

Parameters

ParameterType
inputstring | Uint8Array<ArrayBufferLike>

Returns

Bytes


defineRtdbRules()

function defineRtdbRules(definition: RtdbRulesDefinition): RtdbRulesDocument;

Parameters

ParameterType
definitionRtdbRulesDefinition

Returns

RtdbRulesDocument


duration()

function duration(value: number, unit?: string): Duration;

A duration value. unit is one of the Firestore duration units ('w' | 'd' | 'h' | 'm' | 's' | 'ms' | 'ns'); defaults to seconds.

Parameters

ParameterType
valuenumber
unit?string

Returns

Duration


explainCase()

function explainCase(result: CaseResult | RtdbCaseResult): string;

Render a case result as a human-readable trace. The single sanctioned trace renderer — used as the message of the error assertCase throws, and available directly for logging a result without asserting.

Parameters

ParameterType
resultCaseResult | RtdbCaseResult

Returns

string


firestoreRules()

function firestoreRules(source: string): FirestoreRuleset;

Compile Firestore rules source into a deep, safe-by-default handle.

Parameters

ParameterType
sourcestring

Returns

FirestoreRuleset

Throws

when the source does not parse. The thrown error carries the compile-blocking issues on .issues.


flip()

function flip(marks: string[]): string;

Turn flip: validates a turn field alternates between marks. First mark is the initial value on creation. Supports 2+ players with circular rotation.

Parameters

ParameterTypeDescription
marksstring[]ordered list of marks (e.g., [“X”, “O”])

Returns

string


latlng()

function latlng(lat: number, lng: number): LatLng;

A latlng geographic point.

Parameters

ParameterType
latnumber
lngnumber

Returns

LatLng


lint()

function lint(source: string): RuleIssue[];

Lint Firestore rules source. Accepts anything — including empty or syntactically broken source — and always returns an issue list.

Parameters

ParameterType
sourcestring

Returns

RuleIssue[]


reference()

function reference(path: string): Reference;

A reference to a document, by its path (e.g. "users/alice").

Parameters

ParameterType
pathstring

Returns

Reference


rtdbRules()

function rtdbRules(input: RtdbRulesInput): RtdbRuleset;

Build a deep handle on a Realtime Database ruleset from a definition, a compiled document, or compiled { rules } JSON.

Parameters

ParameterType
inputRtdbRulesInput

Returns

RtdbRuleset


ruleset()

function ruleset(input:
  | Record<string, PathDef>
  | (ctx: RulesetContext) => void): RtdbNode;

Compile a declarative rules definition into an environment-independent tree.

Parameters

ParameterType
input| Record<string, PathDef> | (ctx: RulesetContext) => void

Returns

RtdbNode


schemaRules()

function schemaRules(schema: ZodObject<any>, fieldConstraints?: Record<string, Expr[]>): SchemaRulesResult;

Generate RTDB validate rules from a Zod object schema. Optional fieldConstraints are AND-composed with the schema type check.

Parameters

ParameterType
schemaZodObject<any>
fieldConstraints?Record<string, Expr[]>

Returns

SchemaRulesResult


serverTimestamp()

function serverTimestamp(): {
};

The server-timestamp sentinel — the case-data equivalent of FieldValue.serverTimestamp(). The simulator resolves it to the request time, so a rule comparing data.createdAt == request.time sees a match.

Returns

{
}

timestamp()

function timestamp(input:
  | string
  | number
  | {
  nanos?: number;
  seconds: number;
}): Timestamp;

A Firestore timestamp value.

  • number → milliseconds since the epoch
  • string → ISO-8601
  • object → explicit { seconds, nanos }

Parameters

ParameterType
input| string | number | { nanos?: number; seconds: number; }

Returns

Timestamp


turnGuard()

function turnGuard(
   turnField: string,
   players: Record<string, string>,
   statusField?: string,
   playingValue?: string): string;

Turn enforcement: only the current turn’s player can write. Uses data (pre-write) for the turn check — NOT newData.

Parameters

ParameterTypeDescription
turnFieldstringthe field that stores whose turn it is (e.g., “currentTurn”)
playersRecord<string, string>map of mark → player field (e.g., { X: “playerX”, O: “playerO” })
statusField?stringoptional field that must equal playingValue for moves to be allowed
playingValue?stringthe value of statusField during active play (e.g., “playing”)

Returns

string


vector()

function vector(values: readonly number[]): Vector;

A vector value from its numeric components.

Parameters

ParameterType
valuesreadonly number[]

Returns

Vector


winCheckHelper()

function winCheckHelper(
   mark: string,
   lines: number[][],
   boardPath?: string): string;

Win check helper: validates a boolean field against winning lines on a board. If true, at least one winning line must exist. If false, no winning line can exist. Uses the “client claims, rules verify” pattern.

Parameters

ParameterTypeDescription
markstringthe player mark to check (e.g., “X”)
linesnumber[][]array of winning line coordinates (e.g., [[0,1,2], [3,4,5], …])
boardPath?stringthe path to the board relative to the parent (default “board”)

Returns

string