Navigate

API reference

pyric/rules

126 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

RtdbExpressionSyntaxError

Why canonicalRtdbExpression could not read its input.

Extends

  • Error

Constructors

Constructor
new RtdbExpressionSyntaxError(raw: string, message: string): RtdbExpressionSyntaxError;
Parameters
ParameterType
rawstring
messagestring
Returns

RtdbExpressionSyntaxError

Overrides
Error.constructor

Properties

PropertyModifierType
rawreadonlystring

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-
evaluatedExpressionsnumberExpressions the request evaluated, in the unit of production’s per-request limit of 1000, across every allow rule and match block it reached. 1000 - evaluatedExpressions is the request’s margin. See TestResult.evaluatedExpressions for the unit.
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.
queryProof?ListQueryProofReportStatic list-query proof verdict for list cases, separate from per-document decision (#371).
resourceLimit?RulesResourceLimitThe per-request limit that stopped the request, when one did. A request past 1000 expressions is DENY with kind: 'expressions' and production’s message.
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.

DiffRtdbRulesOptions

Properties

PropertyTypeDescription
ignoreEquivalent?booleanTreat two .read, .write or .validate expressions as the same rule when their canonicalRtdbExpression texts are equal: spellings that cannot change any decision, such as === for == or child('a/' + $id) for child('a').child($id). A changed entry still reports both expressions as written. An expression that does not parse is compared as written. Default false: expressions compare as text.

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"-
evaluatedExpressionsnumberExpressions the request evaluated; see CaseResult.evaluatedExpressions.
expectation"ALLOW" | "DENY"-
notesstring[]-
passedboolean-
pathResolution?PathResolutionTrace-
queryProof?ListQueryProofReportStatic list-query proof verdict for list cases, separate from per-document decision (#371).
resourceLimit?RulesResourceLimitThe per-request limit that stopped the request, when one did.
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
operator?string
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?{ tenant?: string; token?: Record<string, unknown>; uid: string; }Auth context; null/omitted for unauthenticated.
auth.tenant?string-
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 | Record<string, "ASC" | "DESC">; where?: { field: string; op: string; value: string | number | boolean | (string | number | boolean)[]; }[]; }request.query payload (list ops only): limit/offset/orderBy.
query.limit?number-
query.offset?number-
query.orderBy?string | Record<string, "ASC" | "DESC">-
query.where?{ field: string; op: string; value: string | number | boolean | (string | number | boolean)[]; }[]-
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


ListQueryProofReport

Separate static list-query proof verdict reported alongside per-document evaluation on TestResult / CaseResult / Explanation (#371).

Properties

PropertyTypeDescription
failuresQueryProofFailure[]Rules rejected by static query proof, in source order.
kind| "provable" | "no-rule" | "unsupported-predicate" | "unsupported-path" | "constraints-not-satisfied"Specific proof classification ('provable', 'no-rule', or the primary failure kind).
provablebooleanTrue when the rules can statically prove every document the query could return is readable.
reason?stringHuman-readable explanation when verdict === 'UNPROVABLE'.
remediation?stringNarrowing where(...) remediation when verdict === 'UNPROVABLE' and equalities can discharge the rule.
residual?QueryProofResidualStructured account of missing/mismatched where(...) equalities when verdict === 'UNPROVABLE'.
rule?EvaluatedRuleInfoSource location and expression of the primary unprovable rule when verdict === 'UNPROVABLE'.
verdict"PROVABLE" | "UNPROVABLE" | "NO_RULE"Static list-query proof verdict, separate from per-document decision.

PathDef

Definition of rules for a single database path.

Properties

PropertyTypeDescription
children?Record<string, PathDef>-
fieldConstraints?Record<string, Expr[]>-
indexOn?string[]Fields to emit under .indexOn for the container node. May be declared directly on a container path (e.g. "/jobs") or on a $wildcard child path (e.g. "/jobs/$jobId"), which lifts .indexOn onto its parent.
read?string | booleanAn expression, or a boolean as database.rules.json spells it: false denies, true allows.
schema?ZodObject<any>-
validate?string | boolean-
write?string | boolean-

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.

QueryProofFailure

Local proof evidence. These categories do not claim a Firebase decision.

Properties

PropertyTypeDescription
kind| "unsupported-predicate" | "unsupported-path" | "constraints-not-satisfied"-
predicate?{ citation?: string; col?: number; column?: number; expression?: string; file?: string; line?: number; }Location of the rejected predicate, which may be inside a helper.
predicate.citation?string-
predicate.col?number-
predicate.column?number-
predicate.expression?string-
predicate.file?string-
predicate.line?number-
reasonstring-
residualQueryProofResidual-
rule?{ citation?: string; col?: number; column?: number; expression?: string; file?: string; line?: number; }-
rule.citation?string-
rule.col?number-
rule.column?number-
rule.expression?string-
rule.file?string-
rule.line?number-

QueryProofResidual

Structured account of why a doc-dependent query is unprovable. Empty missing and mismatched with outOfScope set means the rule’s doc-dependence is a shape equality analysis cannot discharge, so no query constraint could prove it.

Properties

PropertyTypeDescription
mismatchedQueryProofMismatch[]-
missingQueryProofMissing[]-
outOfScope?string-
predicate?stringInlined predicate that stopped proof, not a runtime evaluation.
predicateLoc?SourceLoc-

QueryRepro

Ready-to-run repro for a rejected list query (#371).

Properties

PropertyTypeDescription
commandstringReady-to-run CLI command that simulates the rejected list query.
testCase{ auth: { token?: Record<string, unknown>; uid: string; }; description: string; expectation: "ALLOW"; method: "list"; path: string; query?: { limit?: number; offset?: number; orderBy?: string | Record<string, "ASC" | "DESC">; where?: { field: string; op: string; value: string | number | boolean | (string | number | boolean)[]; }[]; }; }Copy-pasteable TestCase / FirestoreCase fixture object for simulate().
testCase.auth{ token?: Record<string, unknown>; uid: string; }-
testCase.auth.token?Record<string, unknown>-
testCase.auth.uidstring-
testCase.descriptionstring-
testCase.expectation"ALLOW"-
testCase.method"list"-
testCase.pathstring-
testCase.query?{ limit?: number; offset?: number; orderBy?: string | Record<string, "ASC" | "DESC">; where?: { field: string; op: string; value: string | number | boolean | (string | number | boolean)[]; }[]; }-
testCase.query.limit?number-
testCase.query.offset?number-
testCase.query.orderBy?string | Record<string, "ASC" | "DESC">-
testCase.query.where?{ field: string; op: string; value: string | number | boolean | (string | number | boolean)[]; }[]-

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 | { tenant?: string; token?: Record<string, unknown>; uid: string; }Auth context; a bare uid string, a full identity, or null.
data?| Record<string, unknown> | RtdbInstancesDataExisting data the rules read: the instance’s tree, or one tree per instance as { instances: { "<name>": tree } }. The per-instance form applies when the case names an instance or the ruleset holds rules per instance (rtdbRules.fromFirebaseJson); otherwise an object whose one key is instances is a tree with an /instances child, as before.
description?stringHuman-readable description of what this case verifies.
expectation"ALLOW" | "DENY"Expected outcome.
instance?stringThe database instance the request goes to, by name, such as "demo-app-shard-1". Omit it for the default instance. A rule’s root and data read only this instance’s tree.
newData?unknownProposed write value (newData), for write/validate cases. Any JSON value: a scalar such as 5 or true is a scalar write. For an update case it is the patch, an object keyed by paths relative to path, such as { "rooms/r1/title": "x", "rooms/r2/title": "y" }. Its keys are checked as the SDK checks update() keys: an invalid key, or a key that is an ancestor or duplicate of another, makes the case UNSUPPORTED.
now?numberThe instant now reports in this case, in epoch milliseconds. A caller hosting a sandbox passes its sandbox clock so a now-gated rule moves with the sandbox rather than the wall clock. Omit to evaluate at the real current instant.
operation"read" | "write" | "update" | "validate"RTDB rule kind under test. update is a multi-path update(): every path in newData is written together and each is judged against the tree the whole update produces.
pathstringAbsolute, root-relative tree path, e.g. "/users/alice". A path the SDK refuses, one holding ., #, $, [ or ], is UNSUPPORTED.
query?RtdbCaseQueryThe query a read case carries, so query.* rule expressions evaluate. Omit it to simulate a plain read of path.
updates?{ path: string; value: unknown; }[]For a 'write' or 'validate' case, the full set of paths written together in one atomic multi-path update(), so path’s rules evaluate against the shared post-write tree projection. It lists path, with newData as its value when the case gives newData, and no path in it is an ancestor or duplicate of another; a case that breaks either is UNSUPPORTED.

RtdbCaseQuery

The query a Realtime Database read carries, in the members rules read as query.*. At most one orderBy* member and at most one limit may be set, as in the SDK.

Properties

PropertyType
endAt?string | number | boolean
equalTo?string | number | boolean
limitToFirst?number
limitToLast?number
orderByChild?string
orderByKey?true
orderByValue?true
startAt?string | number | boolean

RtdbCaseResult

The outcome of running one RTDB case through simulate.

Properties

PropertyTypeDescription
caseRtdbCase-
decision"UNSUPPORTED" | "ALLOW" | "DENY"-
description?string-
expectation"ALLOW" | "DENY"-
instance?stringThe database instance the case ran on: the one it named, or the default instance of a ruleset that holds rules per instance. Absent when neither applies.
matchedPathstringThe tree path whose rule decided the request.
matchedRulestringThe expression of the rule that decided, such as auth != null. Empty when no rule on the path decided, as for a request denied by default or one the engine could not evaluate.
passedboolean-
reasonstringEngine-provided reason string.
trace{ conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[]Every .read, .write and .validate rule the engine evaluated, in evaluation order. Empty when no rule of the operation’s kind exists on the path, or when the engine could not evaluate the case.
unsupportedboolean-

RtdbCoverageOptions

Properties

PropertyTypeDescription
file?stringNames the rules file in files.
source?stringThe text of database.rules.json. Each row gains the 1-indexed line of its rule key, located with locateRtdbTrace. A row whose key the text does not contain, or text that is not valid JSON with comments, leaves line unset.

RtdbCoverageSummary

Properties

PropertyTypeDescription
filesRtdbFileCoverage[]-
missingIndexes{ file?: string; index: string; path: string; }[]Queries that needed an index no loaded node declares, with the rules file when the summary covers several files.
rulesRtdbRuleCoverage[]-
uncoveredstring[]"<path> .<kind>" for each node never evaluated, in tree order; "<file> <path> .<kind>" when the summary covers several files.

RtdbExplanation

Properties

PropertyTypeDescription
decision"UNSUPPORTED" | "ALLOW" | "DENY"-
expectation"ALLOW" | "DENY"-
instance?stringSee RtdbCaseResult.instance.
matchedPathstring-
matchedRulestring-
passedboolean-
reasonstring-
trace{ conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[]See RtdbCaseResult.trace.
unsupportedboolean-

RtdbFileCoverage

Properties

PropertyTypeDescription
byKindRecord<RtdbCoverageKind, { covered: number; total: number; unsupported: number; }>-
coverednumberNodes with at least one evaluation.
filestringThe rules file the nodes came from, or null when none was named.
neverEvaluatednumber-
totalnumber-
unsupportednumberNodes the simulator could not evaluate, every time it reached them. covered + neverEvaluated + unsupported is total.

RtdbFirebaseJsonOptions

Reads the Realtime Database rules a project’s firebase.json deploys to each instance, for rtdbRules.fromFirebaseJson.

BROWSER-CLEAN: no static node imports. pyric/rules is reachable from browser graphs, so node:fs and node:path are acquired lazily through process.getBuiltinModule; in a browser the loader throws saying it needs a file system.

Properties

PropertyTypeDescription
projectId?stringThe project id, which names the default instance <projectId>-default-rtdb and selects the .firebaserc deploy-target mappings. Defaults to projects.default in the .firebaserc beside firebase.json.

RtdbRuleChange

One rule expression that differs. deployed is absent for added and local is absent for removed: the change is what deploying the local ruleset would do to the deployed one.

Properties

PropertyType
change"added" | "removed" | "changed"
deployed?string
kindRtdbRuleKind
local?string
pathstring

RtdbRuleCoverage

Properties

PropertyTypeDescription
allownumber-
denynumber-
errornumber-
evaluatednumberEvaluations that produced a verdict: allow + deny + error.
expressionstringThe rule expression, or the declared index list for indexOn.
file?stringThe rules file holding the node, when the summary covers several files.
kindRtdbCoverageKind-
line?number1-indexed line in the rules file, when a line lookup was supplied.
pathstringThe rule node’s path, such as /rooms/$roomId.
statusRtdbCoverageStatus-
unsupportednumber-

RtdbRulesCheckResult

Properties

PropertyType
errorsRtdbRulesFinding[]
okboolean
warningsRtdbRulesFinding[]

RtdbRulesConstructor()

rtdbRules: call it with one ruleset, or call rtdbRules.fromFirebaseJson for the rules a project’s firebase.json deploys to each database instance.

RtdbRulesConstructor(input: string | RtdbRulesInput): RtdbRuleset;

Build a deep handle on a Realtime Database ruleset from the text of a database.rules.json file, a definition, a compiled document, or compiled { rules } JSON.

Parameters

ParameterType
inputstring | RtdbRulesInput

Returns

RtdbRuleset

Throws

when rules text is not JSON (after comments and trailing commas) or has no top-level rules object.

Methods

fromFirebaseJson()
fromFirebaseJson(firebaseJsonPath: string, options?: RtdbFirebaseJsonOptions): RtdbRuleset;

Build a handle on the Realtime Database rules a project’s firebase.json deploys, one ruleset per database instance, as firebase deploy resolves them: a single database object deploys to the default instance, and each entry of a database array deploys to its instance, or to the instances .firebaserc maps its target to. Each rules file is read as rtdbRules reads rules text, comments and trailing commas included.

A case runs on the instance it names, or on the default instance <projectId>-default-rtdb, which <projectId> also names; the project id is options.projectId, else projects.default in the .firebaserc beside firebase.json. A case that names an instance firebase.json deploys no rules to is UNSUPPORTED, with a reason naming the instances it does.

Node-only: it reads files.

Parameters
ParameterType
firebaseJsonPathstring
options?RtdbFirebaseJsonOptions
Returns

RtdbRuleset

Throws

when a rules file is not rules text.

Throws

when a file cannot be read, firebase.json deploys no Realtime Database rules, or a deploy target maps to no instance.


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

coverage()
coverage(results: readonly RtdbCaseResult[], options?: RtdbCoverageOptions): RtdbCoverageSummary;

Which .read, .write, .validate and .indexOn nodes the given case results evaluated, and which they never reached. simulate returns this for its own cases; call it to merge several runs or to attach a file name and line numbers. A ruleset from rtdbRules.fromFirebaseJson reports each rules file under the name firebase.json gives it, with lines located in its text, and takes no options.

Parameters
ParameterType
resultsreadonly RtdbCaseResult[]
options?RtdbCoverageOptions
Returns

RtdbCoverageSummary

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()). On a ruleset from rtdbRules.fromFirebaseJson, each rules file’s findings, once per file, with its file.

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. On a ruleset from rtdbRules.fromFirebaseJson, the default instance’s rules; it throws when firebase.json deploys none to the default instance.

Returns

RtdbRulesJson


RtdbRulesFinding

Properties

PropertyType
codestring
messagestring
pathstring
ruleRtdbRulesFindingRule

RtdbSimulationSummary

Properties

PropertyTypeDescription
casesRtdbCaseResult[]-
coverageRtdbCoverageSummaryWhich rule nodes the cases evaluated, and which they never reached.
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.
evaluatedExpressions?numberExpressions the request had evaluated when this rule’s evaluation ended, counting every earlier rule and match block (see TestResult.evaluatedExpressions for the unit). Populated by the local simulator; absent on production Test API results.
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'.
file?stringThe Realtime Database rules file the issue is in, as firebase.json names it, for a ruleset read with rtdbRules.fromFirebaseJson.
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}').
rule?".read" | ".write" | ".validate"The Realtime Database rule at path the issue applies to. Absent for Firestore issues and for an RTDB issue about the whole ruleset.
severityRuleIssueSeverity-

RulesetContext

Context passed to the callback overload of ruleset().

Properties

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

RulesResourceLimit

A per-request rules limit the local simulator enforces.

  • expressions: 1000 evaluated expressions (see TestResult.evaluatedExpressions). message is production’s own: “Unable to evaluate the expression as the maximum of 1000 expressions to evaluate has been reached.”
  • document-lookups: 10 distinct get(), exists(), getAfter() and existsAfter() document accesses.

line and column place an expressions limit where production reports it: the 1-based line and column, in the evaluated source, of the expression the request was evaluating when the budget ran out.

Properties

PropertyType
column?number
kind"expressions" | "document-lookups"
limitnumber
line?number
messagestring

SchemaRulesResult

Properties

PropertyType
childrenRecord<string, SchemaFieldRule>
validatestring

ShapeOptions

Properties

PropertyTypeDescription
open?booleanLeave children outside the spec unchecked. Defaults to false: any other child is refused.
required?string[]Fields the record must have. Defaults to every field in the spec.

ShapeResult

Properties

PropertyType
childrenRecord<string, PathDef>
validate?string

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.


FieldRule

type FieldRule = "string" | "number" | "boolean" | Expr | PathDef;

A field’s rule in shape: a type name, an expression for its .validate, or a full path definition.


FirestoreMethod

type FirestoreMethod = typeof FIRESTORE_METHODS[number];

ListQuery

type ListQuery = z.infer<typeof ListQuerySchema>;

ListQueryWhereConstraint

type ListQueryWhereConstraint = z.infer<typeof ListQueryWhereConstraintSchema>;

RtdbCoverageKind

type RtdbCoverageKind = "read" | "write" | "validate" | "indexOn";

RtdbCoverageStatus

type RtdbCoverageStatus = "allow" | "deny" | "error" | "mixed" | "unsupported" | "never-evaluated";
  • allow, deny, error: every evaluation of the node had that outcome.
  • mixed: the node had more than one of those outcomes.
  • unsupported: the node’s expression could not be evaluated, every time.
  • never-evaluated: no request in the run reached the node.

RtdbInstancesData

type RtdbInstancesData = {
  instances: Record<string, Record<string, unknown>>;
};

A case’s data as one tree per database instance, keyed by instance name.

Properties

PropertyType
instancesRecord<string, Record<string, unknown>>

RtdbRuleEvaluation

type RtdbRuleEvaluation = z.infer<typeof RtdbRuleEvaluationSchema>;

RtdbRuleKind

type RtdbRuleKind = ".read" | ".write" | ".validate" | ".indexOn";

RtdbRulesFindingRule

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

RtdbRulesJson

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

Properties

PropertyType
rulesRecord<string, unknown>

RtdbRulesSimulationAuth

type RtdbRulesSimulationAuth =
  | string
  | {
  tenant?: 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>;

RtdbStdlib

type RtdbStdlib = typeof rtdbStdlib;

RuleIssueOrigin

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

The stage that produced the issue.

  • parse — the source did not parse, or broke a production compile limit; 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

allow()

const allow: () => Expr;

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

Returns

Expr


always()

const always: () => Expr;

Always allow (true).

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;

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


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;

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


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


pathOwnerOnly()

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

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

Parameters

ParameterType
pathVarstring

Returns

Expr


ref()

const ref: (expression: string) => Segment;

Wrap a runtime rule expression so comparisons emit it unquoted

Parameters

ParameterType
expressionstring

Returns

Segment


required()

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

All specified fields must be present in the incoming data. Single keys are checked together with newData.hasChildren([...]); a nested path such as ‘puck/x’ is checked with newData.hasChild('puck/x'), joined with &&. Every segment of every field must be a valid RTDB key.

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


rtdbRules

const rtdbRules: RtdbRulesConstructor;

Build a deep handle on a Realtime Database ruleset from the text of a database.rules.json file, a definition, a compiled document, or compiled { rules } JSON.

Throws

when rules text is not JSON (after comments and trailing commas) or has no top-level rules object.


rtdbStdlib

const rtdbStdlib: Readonly<{
  auth: typeof auth;
  collections: typeof collections;
  counters: typeof counters;
  lifecycle: typeof lifecycle;
  lobby: typeof lobby;
  membership: typeof membership;
  presence: typeof presence;
  results: typeof results;
  timing: typeof timing;
  turns: typeof turns;
  validation: typeof validation;
}>;

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

all()

function all(...exprs: string[]): string;

All conditions must be true (AND). An operand is parenthesized only when it holds a top-level || or ternary, which binds looser than &&. Empty and whitespace-only operands are dropped; with none left it throws, since an empty conjunction would allow everything. Use always for that.

Parameters

ParameterType
…exprsstring[]

Returns

string


any()

function any(...exprs: string[]): string;

At least one condition must be true (OR). An operand with a top-level && is parenthesized for the reader, and one with a ternary for the parser. Empty and whitespace-only operands are dropped; with none left it throws, since an empty disjunction would deny everything. Use deny for that.

Parameters

ParameterType
…exprsstring[]

Returns

string


assertCase()

Call Signature

function assertCase(result: RtdbCaseResult | CaseResult): 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
resultRtdbCaseResult | CaseResult
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


canonicalRtdbExpression()

function canonicalRtdbExpression(raw: string): string;

Canonical text of an RTDB rule expression: two expressions with equal canonical texts evaluate identically for every request. Deterministic and idempotent. Throws RtdbExpressionSyntaxError for text that is not a rule expression.

Parameters

ParameterType
rawstring

Returns

string


defineRtdbRules()

function defineRtdbRules(definition: RtdbRulesDefinition): RtdbRulesDocument;

Parameters

ParameterType
definitionRtdbRulesDefinition

Returns

RtdbRulesDocument


diffRtdbRules()

function diffRtdbRules(
   deployed: Record<string, unknown>,
   local: Record<string, unknown>,
   options?: DiffRtdbRulesOptions): RtdbRuleChange[];

Node-level diff of two rules trees, ordered by path then rule kind.

Parameters

ParameterType
deployedRecord<string, unknown>
localRecord<string, unknown>
options?DiffRtdbRulesOptions

Returns

RtdbRuleChange[]


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: RtdbCaseResult | CaseResult): 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
resultRtdbCaseResult | CaseResult

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, names a service other than cloud.firestore, declares one service twice, or breaks one of production’s compile limits. 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


isMember()

function isMember(listName: string, pathVarName: string): string;

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

Parameters

ParameterType
listNamestring
pathVarNamestring

Returns

string


latlng()

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

A latlng geographic point.

Parameters

ParameterType
latnumber
lngnumber

Returns

LatLng

Throws

for a latitude outside -90 to 90 or a longitude outside -180 to 180.


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[]


lit()

function lit(value: Literal): string;

A rules literal: a single-quoted string with \ and ' escaped, a finite number, a boolean, or null. Every builder writes its literals through this, so compiled rules use one quote style.

The quote and backslash escapes match Pyric’s rules simulator. A string with a newline or another control character is refused: Pyric does not model escapes for those, and production behavior for them is not captured.

Parameters

ParameterType
valueLiteral

Returns

string


not()

function not(e: string): string;

Negate a condition. A member chain such as data.child('a').exists() needs no parentheses.

Parameters

ParameterType
estring

Returns

string


ownPath()

function ownPath(pathVar: string): string;

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

Parameters

ParameterType
pathVarstring

Returns

string


reference()

function reference(path: string): Reference;

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

Parameters

ParameterType
pathstring

Returns

Reference


renderRtdbCoverage()

function renderRtdbCoverage(summary: RtdbCoverageSummary): string;

One line per rule node, then the per-file totals and the nodes never evaluated.

Parameters

ParameterType
summaryRtdbCoverageSummary

Returns

string


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() and serverTimestamp(). The simulator resolves it to the request time (request.time in Firestore, now in Realtime Database), so a rule comparing a timestamp field to the server clock sees a match.

Returns

{
}

timestamp()

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

A Firestore timestamp value.

  • number → milliseconds since the epoch
  • string → ISO-8601 with Z or an explicit offset
  • Date → its instant
  • object → explicit { seconds, nanos }

Parameters

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

Returns

Timestamp

Throws

for an input that names no instant, such as 'nope', an ISO string without an offset, an invalid Date, or NaN.


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

Throws

for a component that is not a finite number.


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