import { FieldPath, Firestore, QueryDocumentSnapshot } from 'firebase-admin/firestore'; import { DeepPartial, FieldPaths, OmitId } from '../utils/pathTypes.js'; import { CreateInput, CreateOutput, RepositorySchemaSet, RepositorySchemaSetFor, SentinelPolicy, UpdateInput, Validator } from './Validation.js'; import { z } from 'zod'; import { ValidationError } from './Errors.js'; import { type HookContext, type HookEvent } from './Hooks.js'; import { FirestoreQueryBuilder } from './QueryBuilder.js'; import { FirestoreCollectionGroup } from './CollectionGroup.js'; import type { FirestoreDocument } from './DocumentId.js'; import { type WithMetadata } from './SnapshotMetadata.js'; /** * Document-id string used throughout the public API (`getById`, write results, interceptors). * * This is intentionally a named alias of `string`, not a brand: consumers pass ordinary id * strings, and the alias is the stable name in `.d.ts` and docs. SonarJS treats that as a * redundant alias; renaming or inlining it would be a public-contract change. */ export type ID = string; /** * Commit metadata returned only by a **non-transactional** write called with `{ withMetadata: true }`. * * `writeTime` is the Admin SDK {@link FirebaseFirestore.WriteResult.writeTime} for that successful * commit — a receipt from the write RPC, **not** {@link DocumentMetadata.updateTime} (snapshot * provenance) and **not** a JSON-serialized server field on the document body. * * Transactional helpers never expose this type: `Transaction.set` / `update` / `delete` return the * transaction object, not a {@link FirebaseFirestore.WriteResult}. */ export type WriteMetadata = { readonly writeTime: FirebaseFirestore.Timestamp; }; /** * A write's ordinary result paired with its commit metadata. * * For id-returning single writes and fixed batches this is `{ id, writeTime }`. Prefer this * intersection over inventing a universal `{ result, metadata }` wrapper so default callers keep * reading `.id` without unwrapping. */ export type WriteResultWithMetadata = R & WriteMetadata; /** * Options bag for direct update/patch writes. `returnDoc` and `withMetadata` are mutually * exclusive — typed overloads reject the combination, and runtime validation rejects it for * JavaScript callers before any I/O. */ export type UpdateOptions = { merge?: boolean; returnDoc?: boolean; /** * When `true`, the write resolves to {@link WriteResultWithMetadata} carrying the commit * `writeTime`. Incompatible with `returnDoc: true` (a read-back document is not a commit receipt). * Absent from every `*InTransaction` helper — the Admin SDK does not expose per-op write results * inside a transaction. */ withMetadata?: boolean; /** * Optimistic-concurrency precondition. When supplied, the write is applied **only** if the * document's current `updateTime` is exactly this timestamp; otherwise Firestore rejects it and the * repository raises {@link PreconditionFailedError} with the stored document untouched. * * Read the token with {@link FirestoreRepository.getByIdWithUpdateTime}. It must be a * `FirebaseFirestore.Timestamp` instance — the Admin SDK rejects a `Date`/number client-side. * * Note this changes the missing-document outcome: a plain `update` on a deleted document raises * `NotFoundError` (gRPC 5), while a precondition-guarded one raises `PreconditionFailedError` * (Firestore reports the absent document as stored version 0, gRPC 9). */ lastUpdateTime?: FirebaseFirestore.Timestamp; }; /** Opt-in write-receipt options: `withMetadata: true` and never paired with `returnDoc: true`. */ type WriteMetadataOptions = { withMetadata: true; returnDoc?: false; }; /** Default / explicit-false write options: no commit receipt on the result. */ type NoWriteMetadataOptions = { withMetadata?: false; }; /** * The write verbs accepted by {@link FirestoreRepository.bulkWrite}. * * Each maps 1:1 onto a fixed-batch helper: `create` → {@link FirestoreRepository.bulkCreate} (or * {@link FirestoreRepository.bulkCreateWithIds} when `id` is supplied), `set` → the create branch of * {@link FirestoreRepository.upsert} minus its existence pre-read, `update` → * {@link FirestoreRepository.bulkUpdate}, `patch` → {@link FirestoreRepository.bulkPatch}, `delete` → * {@link FirestoreRepository.bulkDelete}. */ export type BulkWriteOperationKind = 'create' | 'set' | 'update' | 'patch' | 'delete'; /** * One entry in a {@link FirestoreRepository.bulkWrite} operation list. * * Discriminated on `op`, so each verb carries exactly the fields it supports: only `create` may omit * `id` (one is generated), and only the update/delete verbs accept a `lastUpdateTime` precondition. */ export type BulkWriteOperation = { op: 'create'; id?: ID; data: CreateInput; } | { op: 'set'; id: ID; data: CreateInput; } | { op: 'update'; id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; } | { op: 'patch'; id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; } | { op: 'delete'; id: ID; lastUpdateTime?: FirebaseFirestore.Timestamp; }; /** * Per-operation outcome from {@link FirestoreRepository.bulkWrite}, positional: `results[i]` * describes `operations[i]`, and `index` repeats that position so a filtered subset stays traceable. * * Discriminate on `ok`. A `BulkWriter` batch is **not** atomic, so a mixed array of successes and * failures is the normal outcome — never infer from one entry what happened to its siblings. */ export type BulkWriteResult = { index: number; id: ID; op: BulkWriteOperationKind; ok: true; writeTime: FirebaseFirestore.Timestamp; } | { index: number; id: ID; op: BulkWriteOperationKind; ok: false; /** * Normalized library error — `ValidationError` for a schema/payload rejection, * `InvalidDocumentIdError` for a malformed id, and the usual * `NotFoundError` / `ConflictError` / `PreconditionFailedError` mapping for a backend refusal * (gRPC 5 / 6 / 9). Anything unclassified is preserved as-is. */ error: Error; /** * How many times the SDK attempted this write before giving up. Present only for a failure the * backend reported (absent for a validation/id rejection, where no write was attempted). */ failedAttempts?: number; }; /** * Options for {@link FirestoreRepository.bulkWrite}. */ export type BulkWriteOptions = { /** * Acknowledge that this path runs **no lifecycle hooks**. Required when the repository has any * bulk hook registered — without it `bulkWrite` throws rather than silently skipping them. */ skipHooks?: boolean; /** * Forwarded verbatim to `db.bulkWriter({ throttling })`. Omit for the SDK default (ramping 500 * ops/second); `false` disables throttling. */ throttling?: NonNullable; }; /** * Result of a non-throwing read-boundary validation via {@link FirestoreRepository.safeValidate}. * * Mirrors Zod's `safeParse` shape, but normalizes failures to the library's {@link ValidationError} * (never a raw `ZodError`) so callers have one error type across write and read validation. */ export type SafeResult = { success: true; data: FirestoreDocument; } | { success: false; error: ValidationError; }; /** * Type-level surface for read-only / PITR transaction callbacks. * * Membership rule: a member belongs here iff it is **pure** or **transaction-scoped**. Anything that * performs I/O outside the transaction (`getById`, `getMany`, `getAll`, `query`, every write helper) * is excluded — on a full {@link FirestoreRepository} those silently bypass both the transaction and * any `readTime` snapshot. The narrowed callback type makes that footgun unrepresentable for * `{ readOnly: true }` / {@link FirestoreRepository.runReadOnlyAt} callers. * * At runtime the callback still receives a full cloned repository (write helpers exist and the SDK * rejects them client-side); the absence is compile-time only, matching the collection-group * "absent from the type" pattern (ADR-0024). * * The optional second type parameter `S` is the **stored** model used to type field-mask paths on * {@link getManyInTransaction} (mirroring `select()` / `where()`). It defaults to `T` so existing * single-argument uses of this exported type keep compiling. * * @see FirestoreRepository.runInTransaction * @see FirestoreRepository.runReadOnlyAt */ export interface ReadOnlyTransactionalRepository { /** * Batched multi-document read inside a transaction via `tx.getAll`. * * In a **read-write** transaction this takes pessimistic locks on **all** requested ids (one * round trip). In a **read-only** / PITR transaction it is lock-free. Results are positional: * `null` marks a missing document at `ids[i]`. See {@link FirestoreRepository.getMany} for the * full contract (order, duplicates, field mask, empty input). * * The `S = T` default keeps single-argument uses of this interface compiling; when `S !== T`, * `fieldMask` paths are typed against the stored model. */ getManyInTransaction(tx: FirebaseFirestore.Transaction, ids: ID[], options: { fieldMask: (FieldPaths> | FieldPath)[]; }): Promise<(FirestoreDocument> | null)[]>; getManyInTransaction(tx: FirebaseFirestore.Transaction, ids: ID[], options?: { fieldMask?: never; }): Promise<(FirestoreDocument | null)[]>; /** * Transaction-scoped document read. Takes a pessimistic lock in a read-write transaction; lock-free * in a read-only one. Renamed from `getForUpdateInTransaction` — locking is a property of the * transaction mode, not of this method. */ getInTransaction(tx: FirebaseFirestore.Transaction, id: ID): Promise | null>; /** * Mapping helper — the only route from a `tx.get(query)` snapshot back into the read model. * Required so query-shaped PITR reads satisfy the issue #32 acceptance criterion ("ORM mapping * helpers work for PITR reads"). */ fromSnapshot(snapshot: FirebaseFirestore.DocumentSnapshot): FirestoreDocument | null; /** * Pure read-boundary validator. Both overloads must be declared so a full repository satisfies * this interface structurally. */ validate(data: FirestoreDocument): FirestoreDocument; validate(data: FirestoreDocument[]): FirestoreDocument[]; /** Pure id boundary — needed to build an argument for {@link getInTransaction}. */ id(raw: string): ID; /** Pure auto-id generator (no write). */ newId(): ID; /** * Pure collection-path accessor. Required so the documented `tx.get(query)` escape hatch can * build a collection reference from the callback repo without hardcoding a path string or * reaching for an outer repository that may not be in scope. */ getCollectionPath(): string; /** Read-side schema accessors (getters on the repo; pure). */ readonly readSchema: z.ZodObject | undefined; readonly schemas: RepositorySchemaSet | undefined; } /** * A read-only converter: just the `fromFirestore` half of a Firestore `FirestoreDataConverter`. * * Given a raw `QueryDocumentSnapshot`, return the read-model shape (without `id` — the repository * overlays the document id afterward). The repository builds the full `FirestoreDataConverter` * internally (pairing this with a pass-through `toFirestore`) and applies it only to read * references, so `toFirestore` is never invoked on any write path. * * Because it runs on every read, the converter is also the seam for normalizing documents into the * current schema shape across schema changes — e.g. backfilling a default for a field added in a * later schema version — so reads stay current-shape without a data migration. See the "Normalizing * across schema changes" section of the Core Concepts guide. */ export type ReadConverter = (snapshot: QueryDocumentSnapshot) => T; export type { HookEvent } from './Hooks.js'; type BeforeCreateHookFn = (data: CreateInput & { readonly id?: ID; }, context: HookContext<'beforeCreate'>) => Promise | void; type AfterCreateHookFn = (data: CreateOutput & { readonly id: ID; }, context: HookContext<'afterCreate'>) => Promise | void; type BeforeUpdateHookFn = (data: UpdateInput & { readonly id: ID; }, context: HookContext<'beforeUpdate'>) => Promise | void; type AfterUpdateHookFn = (data: { readonly id: ID; }, context: HookContext<'afterUpdate'>) => Promise | void; type BeforeDeleteHookFn = (data: FirestoreDocument, context: HookContext<'beforeDelete'>) => Promise | void; type AfterDeleteHookFn = (data: FirestoreDocument, context: HookContext<'afterDelete'>) => Promise | void; type BeforeBulkCreateHookFn = (data: readonly (CreateInput & { readonly id: ID; })[], context: HookContext<'beforeBulkCreate'>) => Promise | void; type AfterBulkCreateHookFn = (data: readonly (CreateOutput & { readonly id: ID; })[], context: HookContext<'afterBulkCreate'>) => Promise | void; type BeforeBulkUpdateHookFn = (data: readonly { readonly id: ID; readonly data: UpdateInput; }[], context: HookContext<'beforeBulkUpdate'>) => Promise | void; type AfterBulkUpdateHookFn = (data: { readonly ids: readonly ID[]; }, context: HookContext<'afterBulkUpdate'>) => Promise | void; type BeforeBulkDeleteHookFn = (data: { readonly ids: readonly ID[]; readonly documents: readonly FirestoreDocument[]; }, context: HookContext<'beforeBulkDelete'>) => Promise | void; type AfterBulkDeleteHookFn = (data: { readonly ids: readonly ID[]; readonly documents: readonly FirestoreDocument[]; }, context: HookContext<'afterBulkDelete'>) => Promise | void; /** Event-to-callback map for correlated hook typing and the typed dispatcher. */ type HookFnMap = { beforeCreate: BeforeCreateHookFn; afterCreate: AfterCreateHookFn; beforeUpdate: BeforeUpdateHookFn; afterUpdate: AfterUpdateHookFn; beforeDelete: BeforeDeleteHookFn; afterDelete: AfterDeleteHookFn; beforeBulkCreate: BeforeBulkCreateHookFn; afterBulkCreate: AfterBulkCreateHookFn; beforeBulkUpdate: BeforeBulkUpdateHookFn; afterBulkUpdate: AfterBulkUpdateHookFn; beforeBulkDelete: BeforeBulkDeleteHookFn; afterBulkDelete: AfterBulkDeleteHookFn; }; /** * Payload type for hook event `E`, derived from the registered callback's first parameter. * * Exported so {@link FirestoreQueryBuilder}'s bound `RunHook` stays event-correlated with the * repository dispatcher (review N1). Not part of the public package barrel — deep-import only. */ export type HookDataFor = Parameters[E]>[0]; /** * Which repository write a {@link WriteInterceptor} is running for. * * `patch` and `upsert` are not kinds of their own: a patch is an `'update'`, and an upsert reports * whichever of `'create'` / `'update'` it actually performed. */ export type InterceptedWriteKind = 'create' | 'update' | 'delete'; /** * The staging surface shared by the Admin SDK's `WriteBatch` and `Transaction` — the one type this * repository stages every intercepted write through, so a group of writes is written once and lands * in whichever boundary the registered interceptors require. * * **These members must return `unknown`, and this type must not become a `Pick`.** * `create` / `set` / `update` / `delete` have byte-identical *parameter* lists on both SDK classes * but different *return* types (`WriteBatch` vs `Transaction`), so `Pick` type-checks against a `WriteBatch` and **rejects a `Transaction`**. * Returning `unknown` is what makes both assignable, and it is the compiler's only check that the * two boundaries really do accept the same calls — `tx as unknown as WriteBatch` would discard it. * `write-interceptors.type-test.ts` asserts both assignments so a regression fails `test:types`. * * Exported because the public {@link WriteGroup} names it in a declaration position, and it must * NOT carry an internal-marker JSDoc tag: `stripInternal` is on, so such a tag erases this type from * the emitted `.d.ts` while `WriteGroup` still references the name — a broken published `.d.ts` that * `build`, `test:types`, `check:package` and `check:consumer` all report as green (`check:consumer` * compiles with `skipLibCheck` by design). Only the declaration-emit gate leg catches it. Do not * write that tag name here even inside a code span: the compiler reads the tag out of the comment * regardless of markup, so mentioning it is enough to trigger the erasure. * * What keeps this type off the public API is simply that `src/index.ts` does not re-export it. */ export type StagingTarget = { create(ref: FirebaseFirestore.DocumentReference, data: any): unknown; set(ref: FirebaseFirestore.DocumentReference, data: any, options?: FirebaseFirestore.SetOptions): unknown; update(ref: FirebaseFirestore.DocumentReference, data: any, precondition?: FirebaseFirestore.Precondition): unknown; delete(ref: FirebaseFirestore.DocumentReference, precondition?: FirebaseFirestore.Precondition): unknown; }; /** * One **domain** write — the write the caller asked for — plus the interceptor writes that must * commit with it or not at all. * * `domain` is singular by construction: a group is the atomic unit {@link commitInChunks} refuses to * split across a chunk boundary, and the position of its receipt in the committed chunk is what * keeps `withMetadata` receipts 1:1 with the caller's documents. * * Not re-exported from the root entry point (see {@link StagingTarget}). */ export type WriteGroup = { readonly domain: (target: StagingTarget) => void; readonly interceptor: readonly ((target: StagingTarget) => void)[]; }; /** * The restricted reader handed to a {@link ReadCapableInterceptor}'s `read` phase. * * `get` joins the same transaction the domain write will be staged into, so what it returns is * consistent with what the write phase then stages. The target repository is positional and must be * built on the **same** `Firestore` instance as the intercepted repository — staging against another * instance is accepted by the SDK and lands nowhere, so it is refused up front. * * Reads are deliberately the only I/O an interceptor may do, and only here: Firestore requires every * read in a transaction to precede every write, so the `write` phase is synchronous by type. */ export interface InterceptorReader { get(repo: FirestoreRepository, id: ID): Promise | null>; } /** * The restricted writer handed to a {@link WriteInterceptor}'s `write` phase — the only way an * interceptor writes, and the reason its writes are guaranteed to share the domain write's boundary. * * Every member *stages* rather than commits: nothing here awaits, nothing here returns a receipt, and * the repository decides whether the staged writes land in a `WriteBatch` or a `Transaction`. Each * member is generic over the **target** repository's parameters, so a payload is type-checked against * that repository's write model, and each validates through that repository exactly as a direct call * would (id validation, schema validation, merge normalization, empty-payload rejection). * * The target repository must be built on the same `Firestore` instance as the intercepted repository * (see {@link InterceptorReader}). */ export interface InterceptorWriter { /** * Creates a sibling under a caller-supplied id, failing if one is already there — the staged * counterpart of {@link FirestoreRepository.createWithId}. A collision aborts the whole group, so * the domain write does not land either. */ createWithId(repo: FirestoreRepository, id: ID, data: CreateInput): void; /** * Writes a whole document: the target's **complete** write model, checked by its create validator. * * `set` is on this surface because it is the only member that can address a sibling which **may not * exist yet** — `update` fails the whole batch on a missing document, which is exactly the counter * and mirror cases interceptors exist for. `{ merge: true }` keeps fields the payload does not * mention instead of replacing the document wholesale. * * **The payload stays complete even under `merge`, and that is deliberate.** A `set` creates the * document when it is absent, and a partial payload cannot produce a document that satisfies its * own schema — you would be writing a record missing its required fields, which reads back typed * as complete because reads are not validated. If you want to touch a subset of fields, use * {@link InterceptorWriter.update}, which fails when the document is missing. That failure is the * guard rail, not a limitation. */ set(repo: FirestoreRepository, id: ID, data: CreateInput, options?: { merge?: boolean; }): void; /** * Updates fields on a sibling that must **already exist** — the staged counterpart of * {@link FirestoreRepository.update}. A missing document fails the whole group, which is the guard * rail against writing a record that does not satisfy its schema. */ update(repo: FirestoreRepository, id: ID, data: UpdateInput): void; /** * Merge-style partial update — the staged counterpart of {@link FirestoreRepository.patch}, and * exactly what `patch` is there: nested objects are normalized into field paths before validation, * so a partial nested object does not require its siblings. Also fails on a missing document. */ patch(repo: FirestoreRepository, id: ID, data: UpdateInput): void; delete(repo: FirestoreRepository, id: ID): void; } /** * The domain write an interceptor observes, discriminated on {@link InterceptedWriteKind}. * * Each member carries **what is actually being written**, after id validation, schema parsing and any * schema transforms — not the caller's raw argument. `'create'` carries the validated create output, * `'update'` the validated update payload, and `'delete'` the whole stored document rather than just * its id (sound because every delete path here pre-reads its document before staging the delete). * * ⚠ **On `'update'`, a merge write arrives DOT-PATH NORMALIZED.** `patch()`, * `update(…, { merge: true })` and `bulkPatch()` normalize nested objects into field paths *before* * validating, so that is the shape the interceptor sees — while a plain `update()` keeps the nested * object. Both report `kind: 'update'`, and `UpdateInput` admits dotted keys, so **TypeScript will * not warn you**: * * ```ts * repo.update(id, { address: { city: 'b' } }); // write.data === { address: { city: 'b' } } * repo.patch(id, { address: { city: 'c' } }); // write.data === { 'address.city': 'c' } * ``` * * So read a nested field as `write.data['address.city']`, not `write.data.address?.city` — the latter * is `undefined` under `patch()` and the interceptor silently mirrors nothing. A **flat** payload is * unaffected: normalization only rewrites nested objects. * * Pinned by two cases in `repository-write-interceptors.integration.test.ts` ("the payload an * interceptor observes…" and "bulkPatch hands the interceptor the same dot-path shape…"), each of * which fails on its own if the respective site stops normalizing. There is deliberately **no** * type-level guard: both spellings inhabit `UpdateInput`, which is precisely why this needs a * runtime test and a warning here. */ export type InterceptedWrite = { readonly kind: 'create'; readonly id: ID; readonly data: CreateOutput; } /** * A plain `update()` carries the caller's nested payload; `patch()` / * `update(…, { merge: true })` / `bulkPatch()` carry it **normalized to field paths**. See the * warning on {@link InterceptedWrite}. */ | { readonly kind: 'update'; readonly id: ID; readonly data: UpdateInput; } | { readonly kind: 'delete'; readonly id: ID; readonly document: FirestoreDocument; }; /** * A write-only interceptor: it declares **no** read phase, so its writes can be staged into a * `WriteBatch` alongside the domain write. * * This is the cheaper flavour, and the only one the fixed-batch helpers and query write terminals can * host (a transaction cannot be chunked). `read` is declared as `?: undefined` rather than simply * omitted so {@link FirestoreRepository.registerWriteInterceptor}'s overloads discriminate on it. */ export interface WriteOnlyInterceptor { readonly name: string; readonly read?: never; readonly write: (ctx: { readonly write: InterceptedWrite; readonly writer: InterceptorWriter; }) => void; } /** * A read-capable interceptor: it declares a `read` phase, which promotes every single-document write * on the repository to a **transaction** so the read and the writes share one boundary. * * `read` runs before any write is staged and its result is handed to `write` as `reads` (`R` is * inferred from `read`'s return type). `write` is synchronous by type: Firestore requires all reads * in a transaction to precede all writes, so there is nowhere else to put I/O. * * Registering one is what makes the fixed-batch helpers, the query write terminals, and * `{ withMetadata: true }` refuse — a transaction can neither be chunked nor produce a per-operation * write receipt. */ export interface ReadCapableInterceptor { readonly name: string; readonly read: (ctx: { readonly write: InterceptedWrite; readonly reader: InterceptorReader; }) => Promise; readonly write: (ctx: { readonly write: InterceptedWrite; readonly writer: InterceptorWriter; readonly reads: R; }) => void; } /** Either interceptor flavour — what {@link FirestoreRepository.registerWriteInterceptor} stores. */ export type WriteInterceptor = WriteOnlyInterceptor | ReadCapableInterceptor; /** * Type-safe Firestore repository with validation and lifecycle hooks. * Provides a clean API for common database operations with built-in error handling. * * Four data models are distinguished (see ADR-0018): * @template T - **read data** — the application/read shape (after any `readConverter`). `id` is NOT a * member; reads return {@link FirestoreDocument}`` with the authoritative document id overlaid. * @template W - **write input** — what create/update accept (from `z.input`). Defaults to `T`. * @template S - **stored data** — the at-rest Firestore shape; the source of query field paths. * Defaults to `T`. Differs from `T` only when a `readConverter` changes the field structure. * @template WO - **parsed write output** — the validated write payload (from `z.output`, * transforms/coercions/defaults applied) that `afterCreate`/`afterBulkCreate` observe. Defaults to `W`. * * @example * // Basic usage without validation * const userRepo = new FirestoreRepository(db, 'users'); * * @example * // With Zod schema validation (read type inferred from the schema value) * const userRepo = FirestoreRepository.withSchema(db, 'users', userSchema); * * @example * // With lifecycle hooks * const orderRepo = new FirestoreRepository(db, 'orders'); * orderRepo.on('afterCreate', async (order) => { * await sendOrderConfirmation(order); * }); */ /** True only when `A` and `B` are mutually assignable (the same type). */ type MutuallyAssignable = [A] extends [B] ? ([B] extends [A] ? true : false) : false; /** * Constructor argument tuple. The `validator` (a parser) is the ONLY thing that can produce a parsed * write output (`WO`) that differs from the write input (`W`). So it is **required** whenever `WO` * diverges from `W`, and optional when they match (the default and every schema-less repository). * This prevents a schema-less instance from promising a parsed output no parser produces (review S1). * * Exported so {@link FirestoreRepository.withSchemaArgs}'s return type stays in lockstep with the * constructor (ADR-0042) — subclasses that spread the helper into `super(...)` name the same tuple. * * `S` is the **stored** (at-rest) type. It reaches the tuple through the `schemas` slot * ({@link RepositorySchemaSetFor}), which is what makes a subclass's declared `S` checkable against * the `storedSchema` it actually passes instead of being an unverified hand-declaration. Defaults to * `any` so the erased 3-argument form keeps its previous meaning. */ export type RepositoryConstructorArgs = MutuallyAssignable extends true ? [ db: Firestore, collectionPath: string, validator?: Validator, parentPath?: string, readConverter?: ReadConverter, schemas?: RepositorySchemaSetFor, allowLegacyDatastoreIds?: boolean ] : [ db: Firestore, collectionPath: string, validator: Validator, parentPath?: string, readConverter?: ReadConverter, schemas?: RepositorySchemaSetFor, allowLegacyDatastoreIds?: boolean ]; export declare class FirestoreRepository { private hooks; /** * 1-based count of how many times the enclosing `runInTransaction` wrapper has entered the Admin * SDK callback for this per-invocation clone, or unset on repositories outside that wrapper. * Diagnostic only — not an idempotency key. Public `*InTransaction` helpers on a repo without this * field pass `attempt: null` to before-hooks. */ private transactionAttempt?; private readonly db; private readonly collectionPath; private readonly validator?; private readonly parentPath?; private readonly readConverter?; private readonly schemasInternal?; private readonly allowLegacyDatastoreIds; /** * Set to `true` on a **subclass** to silence the once-per-class write-override warning. * * Why this exists: overriding a write method looks like an enforced invariant but sibling paths * bypass it. The warning is permanent library behavior (not a transitional nag). Deliberate * partial overrides — e.g. logging on `update` only — should set this flag rather than live with * stderr noise. Must be set on the constructor before the first instance is constructed. * * Inheritance: this is a normal JS static. A subclass that sets `true` also silences further * subclasses that inherit the flag; redeclare `static suppressWriteOverrideWarning = false` on a * deeper class if that class's write overrides should warn again. * * @example * class LoggingUserRepository extends FirestoreRepository { * static suppressWriteOverrideWarning = true; * override async update(...args: Parameters['update']>) { * console.log('update', args[0]); * return super.update(...args); * } * } */ static readonly suppressWriteOverrideWarning = false; constructor(...args: RepositoryConstructorArgs); /** * Validates a caller-supplied document id against Firestore's id rules, honoring this repository's * `allowLegacyDatastoreIds` setting. Throws {@link InvalidDocumentIdError} before any I/O (review B1). */ private validateId; /** * Rejects a schema that declares a top-level `id` field (ADR-0018). `id` is repository-owned * metadata sourced from the Firestore document name (`snapshot.id`) and overlaid on reads as a * read-only `id`; schemas describe the document's own fields (read/write/stored models), which * must not compete with that identity. * * This replaces the old required-`id` probe (which parsed a hard-coded literal and wrongly rejected * refined id schemas — UUID/regex/branded — review B6). No probe value is parsed here; native ids * are validated at the `repo.id`/create/read boundaries against Firestore's actual rules. Nested * fields named `id` (e.g. `author.id`) are unaffected — only the top level is checked. */ private static assertSchemaHasNoTopLevelId; /** * Rejects a schema that declares a top-level `path` or `parentPath` when a **collection group** * query is requested (ADR-0024). A group result overlays full-path identity on top of the document * data, exactly as `id` is overlaid on every read, so a same-named field would be silently * replaced — and `CollectionGroupDocument` `Omit`s it from the type, making the caller's own * field unreachable. * * Both the **read** and the **stored** models are checked, because they fail differently and both * fail silently (review H1): * - a read-model `path` is replaced at materialization — the caller's value never survives; * - a stored-model `path` is what `where('path', …)` targets (query field paths derive from `S`), * so a filter can match on a value the result can never expose. With a `readConverter` there is * no replacement — the converter drops the stored field — but the filter/result mismatch * remains, so this rejects unconditionally. * * This mirrors the top-level-`id` invariant, which `withSchema` already enforces on the * `storedSchema` as well. Checked at `collectionGroup()` rather than at construction: the collision * only exists on the group surface, so an ordinary repository with a stored `path` field stays * perfectly usable. Unvalidated (raw) repositories have no schema to inspect — same limitation as * the `id` check, and the `Omit` in the result type is what surfaces it there. */ private static assertSchemaHasNoGroupIdentityFields; /** * Enforces, on the **schema factories** (`withSchema` / `subcollection` / `withSchemaArgs`), the * ADR-0018 invariant that a `readConverter` requires a `storedSchema` at RUNTIME, not only via the * TypeScript overloads (review R6). The overloads block the typed path, but a JavaScript caller of * a factory — or a TypeScript call crossing an `any` boundary — could otherwise construct a * structurally-unsound repository whose stored/query shape silently defaults to the read schema. * * This applies to the schema-inferred factories only. The unvalidated escape hatches (the raw * positional constructor and {@link FirestoreRepository.raw}) run no Zod validation and infer no * types from schemas, so there is no `storedSchema` to require — the caller owns the `StoredData` * generic directly and is responsible for setting it to the physical shape when a converter * restructures fields. */ private static assertConverterHasStoredSchema; /** * Single schema-argument assembler shared by {@link withSchemaArgs}, {@link withSchema}, and * {@link subcollection} (ADR-0042). `context` is the public entry-point name used in construction * errors so callers still see `withSchema` / `subcollection` / `withSchemaArgs` rather than a * shared-helper label that would change the observable message contract. * * `readSchemaContext` exists so the refactor is byte-identical in its observable messages: * `subcollection` takes its read schema as a POSITIONAL argument and has always named it * (`...subcollection(..., readSchema, ...)`), while `withSchema` / `withSchemaArgs` use the bare * context. Defaults to `context` for those two. */ private static buildWithSchemaArgs; /** * Defines the repository-owned `id` as a non-writable, non-configurable property on a before-hook * payload, so a hook can still mutate documented DATA fields but cannot repoint identity or forge * the id a later hook (or the after-event) observes (review R2/ADR-0018 Decision 7). Returns the * same object. The write target is always taken from a separately-captured id/ref, never from this * payload — this hardens lifecycle-accounting/audit integrity on top of that. */ private static withReadonlyId; /** * Exposes repository schemas in a read-only bundle. * - `read`: the consumer-provided canonical schema * - `create`: write schema derived by omitting `id` * - `update`: update schema derived from the create write schema */ get schemas(): RepositorySchemaSet | undefined; /** * Convenience getter for the canonical read schema, when validation is enabled. */ get readSchema(): z.ZodObject | undefined; /** * Convenience getter for the create write schema, when validation is enabled. */ get createSchema(): z.ZodObject | undefined; /** * Convenience getter for the update write schema, when validation is enabled. */ get updateSchema(): z.ZodObject | undefined; /** * Assemble the positional constructor arguments that {@link withSchema} would pass, so a * subclass can spread them into `super(...)` without re-deriving the read/write/stored schema * bundle by hand (ADR-0042 / issue #102). * * Why this exists: `withSchema` always returns a plain `FirestoreRepository`, so a subclass must * call the positional constructor itself. For a plain schema, `super(db, path, makeValidator(s))` * is fine — the constructor falls back to the validator's own bundle. For a **write overlay**, * `makeValidator(writeSchema)` alone is wrong: it would leave `schemas.read` as the write overlay, * and {@link validate} / {@link safeValidate} would then accept `FieldValue` sentinels a read * should reject. This helper performs the same assembly `withSchema` already does — validator from * the write base, `schemas.read` forced to the real read schema, `schemas.stored` always * populated — so the overlay hole is unreachable on the documented subclass path. * * Options match `withSchema` / `subcollection`, plus `parentPath` (needed when the subclass is a * subcollection and must thread parent tracking without positional `undefined`s for * `readConverter` / `allowLegacyDatastoreIds`). `parentPath` is a **marker**, not a parsed value: * only its presence is observed (by {@link isSubcollection}), and {@link getParentId} derives the * parent id from `collectionPath`. Pass the composed subcollection path, as `subcollection` does. * * **The stored generic `S` is checked, not merely assumed.** The returned tuple carries the stored * type in its `schemas` slot ({@link RepositorySchemaSetFor}), so a subclass whose * `extends FirestoreRepository` clause contradicts the `storedSchema` it passes fails * to compile at the `super(...)` call. Because Zod 4 declares `ZodType` covariantly, * the check rejects an unrelated `S` and a *wider* one — the unsound directions, since `S` types * {@link collectionGroup} and its field paths, and a wider `S` would invent paths that do not exist * at rest — while permitting a narrower `S`, which only under-reports paths. * * @param db - Firestore database instance * @param collectionPath - Collection path (top-level or already-composed subcollection path) * @param readSchema - Canonical read schema describing the **read model** (no top-level `id`) * @param options - Same bag as {@link withSchema}, plus optional `parentPath` * @returns A {@link RepositoryConstructorArgs} tuple ready to spread into `super(...)` / * `new FirestoreRepository(...)` * * @example * // Subclass with a write overlay — reads stay typed/validated by the read schema * class StrictUserRepository extends FirestoreRepository { * constructor(db: Firestore) { * super(...FirestoreRepository.withSchemaArgs(db, 'users', userSchema, { * writeSchema: userWrite, * sentinelPolicy: 'strict', * })); * } * } */ static withSchemaArgs, WS extends z.ZodObject = RS, SS extends z.ZodObject = RS>(db: Firestore, collectionPath: string, readSchema: RS, options?: { writeSchema?: WS; storedSchema?: SS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; parentPath?: string; readConverter?: never; }): RepositoryConstructorArgs, z.input, z.output, z.output>; static withSchemaArgs, SS extends z.ZodObject, WS extends z.ZodObject = RS>(db: Firestore, collectionPath: string, readSchema: RS, options: { readConverter: ReadConverter>; storedSchema: SS; writeSchema?: WS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; parentPath?: string; }): RepositoryConstructorArgs, z.input, z.output, z.output>; /** * Create a repository instance with Zod schema validation. * Automatically validates all create and update operations. * * Schemas must NOT declare a top-level `id` (ADR-0018) — the repository sources the document id * from the Firestore document name and returns it as a read-only `id` on every read * ({@link FirestoreDocument}). Types are inferred from schema values: * - The **read type** is `z.output`; reads return `FirestoreDocument`. * - The **write input** is `z.input` when a `writeSchema` overlay is supplied, * otherwise it is `z.input`. Build the overlay from the write combinators * (`zNumberWrite`/`zArrayWrite`/`zDateWrite`/`withDelete`/`zSentinel`) to accept native values * and `FieldValue` sentinels on `create`/`update` with no cast. * * Prefer {@link withSchemaArgs} when subclassing — `withSchema` always returns a plain * `FirestoreRepository` and cannot construct a subclass. * * @param db - Firestore database instance * @param collection - Collection path * @param readSchema - Canonical read schema describing the **read model** (no top-level `id`) * @param options - Optional settings: * - `writeSchema`: write-side overlay schema (write input = `z.input`). * - `storedSchema`: the at-rest/physical shape that query field paths derive from. Optional * without a `readConverter` (defaults to the read schema). **Required whenever a `readConverter` * is configured** — a converter can make the read model diverge from what is physically stored, * and the compiler cannot tell whether it does, so the at-rest query shape must be given * explicitly (enforced by the overloads and at runtime). * - `readConverter`: a read-only converter — the `fromFirestore(snapshot) => T` half only (returns * read data without `id`; the repository overlays the document id). For write-time * normalization use a `before*` hook. * - `sentinelPolicy`: defaults to `'strict'` (v3), which only accepts sentinels a field's schema * explicitly permits and always returns the parsed Zod output. Set `'permissive'` to opt into * the pre-v3 escape hatch that writes the raw input verbatim when parsing fails only at * sentinel paths (discards sibling coercions/defaults/transforms). * @returns Repository instance with validation enabled * * @example * const userSchema = z.object({ * name: z.string().min(1), * email: z.email(), * age: z.number().int().positive().optional(), * }); * * // reads return DocumentOf = z.output & { id } * const userRepo = FirestoreRepository.withSchema(db, 'users', userSchema); * * @example * // Cast-free combinator writes via a write overlay * const eventRead = z.object({ name: z.string(), happenedAt: z.date() }); * const eventWrite = z.object({ name: z.string(), happenedAt: zDateWrite() }); * const events = FirestoreRepository.withSchema(db, 'events', eventRead, { writeSchema: eventWrite }); * await events.update('id', { happenedAt: FieldValue.serverTimestamp() }); // no cast * * @example * // Validation errors are thrown automatically * try { * await userRepo.create({ name: '', email: 'invalid' }); * } catch (error) { * if (error instanceof ValidationError) { * console.log(error.issues); // Zod validation errors * } * } */ static withSchema, WS extends z.ZodObject = RS, SS extends z.ZodObject = RS>(db: Firestore, collection: string, readSchema: RS, options?: { writeSchema?: WS; storedSchema?: SS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; readConverter?: never; }): FirestoreRepository, z.input, z.output, z.output>; static withSchema, SS extends z.ZodObject, WS extends z.ZodObject = RS>(db: Firestore, collection: string, readSchema: RS, options: { readConverter: ReadConverter>; storedSchema: SS; writeSchema?: WS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; }): FirestoreRepository, z.input, z.output, z.output>; /** * Named entry point for an **unvalidated** (schema-less) repository. Prefer this over the positional * constructor when you need a raw repository with options — it makes a security-relevant flag like * `allowLegacyDatastoreIds` discoverable and hard to misplace, instead of a trailing positional * boolean after several `undefined`s (review R7). Types come from the explicit generic `T`; no Zod * validation runs (use {@link FirestoreRepository.withSchema} for that). * * @param db - Firestore database instance * @param collection - Collection path * @param options - Optional settings: * - `readConverter`: a read-only `fromFirestore(snapshot) => T` mapper (the repository overlays the * document id). Because this path runs no schema validation, there is no `storedSchema` to * require: if the converter RESTRUCTURES fields, supply the physical shape as the `StoredData` * generic yourself (`FirestoreRepository.raw(…)`) so query field paths are * correct — unlike {@link FirestoreRepository.withSchema}, this factory cannot infer it. * - `allowLegacyDatastoreIds`: opt in to the documented `__id[0-9]+__` Cloud Datastore-import * document-name form (document segments only; off by default). See ADR-0018 §6. * * @example * // A raw repository that can address imported Datastore numeric ids: * const repo = FirestoreRepository.raw(db, 'users', { allowLegacyDatastoreIds: true }); */ static raw(db: Firestore, collection: string, options?: { readConverter?: ReadConverter; allowLegacyDatastoreIds?: boolean; }): FirestoreRepository; /** * Access a subcollection under a specific parent document. * * Mirrors {@link FirestoreRepository.withSchema}: read/write types are inferred from schema values, * the `readSchema` describes the read model (no top-level `id`), and an optional `writeSchema` * overlay drives cast-free combinator writes. Read converters are read-only (a `fromFirestore(snapshot) => T` * mapper), explicit per repository instance, and never inherited from parent repositories — pass one * in `options.readConverter` when needed. The `parentId` and `subcollectionName` are validated as * single path segments (no slashes / reserved values). * * For an unvalidated subcollection, construct a repository directly against the full path, e.g. * `new FirestoreRepository(db, `${parentPath}/${parentId}/orders`)`. * * @param parentId - Parent document id (a single, valid path segment) * @param subcollectionName - Subcollection name (a single, valid collection segment) * @param readSchema - Canonical read schema describing the **read model** (no top-level `id`) * @param options - Optional `writeSchema` overlay, `storedSchema` (required with a `readConverter`), * `readConverter`, and `sentinelPolicy` (see {@link FirestoreRepository.withSchema}) * * @example * // Access orders for a specific user * const orderSchema = z.object({ product: z.string(), price: z.number() }); * const userOrders = userRepo.subcollection('user-123', 'orders', orderSchema); * await userOrders.create({ product: 'Widget', price: 99 }); * * @example * // With a write overlay (cast-free combinator writes) and a read-only converter. A `readConverter` * // requires a `storedSchema` describing the at-rest/physical document (ADR-0018). * const orderWrite = z.object({ product: z.string(), price: zNumberWrite() }); * const orderStored = z.object({ product: z.string(), priceCents: z.number() }); * const userOrders = userRepo.subcollection('user-123', 'orders', orderSchema, { * writeSchema: orderWrite, * readConverter: orderConverter, * storedSchema: orderStored, * }); * await userOrders.update('o1', { price: FieldValue.increment(5) }); // no cast * * @example * // Nested subcollections * const comments = postRepo * .subcollection('post-123', 'comments', commentSchema) * .subcollection('comment-456', 'replies', replySchema); */ subcollection, WS extends z.ZodObject = RS, SS extends z.ZodObject = RS>(parentId: ID, subcollectionName: string, readSchema: RS, options?: { writeSchema?: WS; storedSchema?: SS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; readConverter?: never; }): FirestoreRepository, z.input, z.output, z.output>; subcollection, SS extends z.ZodObject, WS extends z.ZodObject = RS>(parentId: ID, subcollectionName: string, readSchema: RS, options: { readConverter: ReadConverter>; storedSchema: SS; writeSchema?: WS; sentinelPolicy?: SentinelPolicy; allowLegacyDatastoreIds?: boolean; }): FirestoreRepository, z.input, z.output, z.output>; /** * Get the parent document ID if this is a subcollection. * Returns null for top-level collections. * * @returns Parent document ID or null * * @example * const userOrders = userRepo.subcollection('user-123', 'orders'); * console.log(userOrders.getParentId()); // 'user-123' * * @example * const topLevel = new FirestoreRepository(db, 'users'); * console.log(topLevel.getParentId()); // null */ getParentId(): ID | null; /** * Get the full Firestore path for this collection. * * @returns The collection path string * * @example * const repo = new FirestoreRepository(db, 'users'); * console.log(repo.getCollectionPath()); // 'users' * * @example * const orders = userRepo.subcollection('user-123', 'orders'); * console.log(orders.getCollectionPath()); // 'users/user-123/orders' */ getCollectionPath(): string; /** * Check if this repository represents a subcollection. * * @returns True if this is a subcollection, false if top-level * * @example * const users = new FirestoreRepository(db, 'users'); * console.log(users.isSubcollection()); // false * * @example * const orders = users.subcollection('user-123', 'orders'); * console.log(orders.isSubcollection()); // true */ isSubcollection(): boolean; /** * Register a lifecycle hook to run before or after operations. * Hooks allow you to add custom logic like logging, validation, or side effects. * * @param event - The lifecycle event to hook into * @param fn - Async or sync function to execute * * @example * // Log all creates * userRepo.on('afterCreate', (user) => { * console.log(`User created: ${user.id}`); * }); * * @example * // Send email on user creation * userRepo.on('afterCreate', async (user) => { * await sendWelcomeEmail(user.email); * }); * * @example * // Validate business logic before update * orderRepo.on('beforeUpdate', (data) => { * if (data.status === 'shipped' && !data.trackingNumber) { * throw new Error('Tracking number required for shipped orders'); * } * }); * * @example * // Bulk operation hooks * userRepo.on('afterBulkDelete', async ({ ids, documents }) => { * await auditLog.record('users_deleted', { count: ids.length }); * }); */ on(event: 'beforeCreate', fn: BeforeCreateHookFn): void; on(event: 'afterCreate', fn: AfterCreateHookFn): void; on(event: 'beforeUpdate', fn: BeforeUpdateHookFn): void; on(event: 'afterUpdate', fn: AfterUpdateHookFn): void; on(event: 'beforeDelete', fn: BeforeDeleteHookFn): void; on(event: 'afterDelete', fn: AfterDeleteHookFn): void; on(event: 'beforeBulkCreate', fn: BeforeBulkCreateHookFn): void; on(event: 'afterBulkCreate', fn: AfterBulkCreateHookFn): void; on(event: 'beforeBulkUpdate', fn: BeforeBulkUpdateHookFn): void; on(event: 'afterBulkUpdate', fn: AfterBulkUpdateHookFn): void; on(event: 'beforeBulkDelete', fn: BeforeBulkDeleteHookFn): void; on(event: 'afterBulkDelete', fn: AfterBulkDeleteHookFn): void; /** * Sequential, fail-fast hook dispatcher. Builds an event-correlated {@link HookContext} and wraps * hook failures as {@link WriteOutcomeError} with before/after outcome metadata owned by **this** * call's control-flow phase. A nested {@link WriteOutcomeError} from another repository call is * never returned as-is — it becomes `cause` of the outer phase outcome (review B1 / trap T2). */ private runHooks; /** * Classify a hook failure by **this** call's control-flow position (before vs after), not by the * cause's class. Nested {@link WriteOutcomeError} instances are preserved as `cause` via * {@link parseFirestoreError} so the outer outcome still describes the outer write. */ private writeOutcomeFromHookFailure; /** * Postcommit read-back for `{ returnDoc: true }` paths. The write has already committed; only the * converter/read model can fail here. Nested {@link WriteOutcomeError} values are re-wrapped so * the outer outcome stays `committed` / `read-back` (review B1). */ private readAfterCommit; private emitAfterCreate; private emitAfterBulkCreate; /** * Collection reference used by every **read** path. * * When a `readConverter` is configured, the repository builds a full * `FirestoreDataConverter` internally — the user-supplied `fromFirestore` half plus a pass-through * `toFirestore` — and applies it here so `fromFirestore` runs on reads. Because that converter is * only ever attached to the read ref, its `toFirestore` is never invoked (see * {@link FirestoreRepository.writeCol}). Subcollections do not inherit parent converters * automatically. */ private readCol; /** * Collection reference used by every **write** path. * * Deliberately raw (never `.withConverter(...)`) so a converter's * `toFirestore` is **never** invoked. The Admin SDK skips `toFirestore` on * `update`/`batch.update`/`tx.update` anyway, so routing all writes through the * raw ref removes that asymmetry — converters are strictly read-only. Use a * `before*` hook for write-time normalization. */ private writeCol; /** * Removes top-level undefined keys from update payloads. * This preserves prior behavior where undefined update values were ignored. */ private sanitizeUpdateData; /** * Rejects an update whose write payload is empty after validation/sanitization. An empty patch * previously skipped the Firestore write entirely, which meant a nonexistent document was reported * as successfully updated (the missing-doc NotFoundError comes from Firestore's own update()). * Rejecting keeps the documented "update throws for a missing document" contract intact and makes * every update surface behave identically. */ private assertNonEmptyUpdatePayload; /** * Builds the Admin SDK `Precondition` for an optional `lastUpdateTime`, or `undefined` when the * caller supplied none. * * HAZARD this exists to make unmissable: an explicit `undefined` must NEVER reach `update()`. * `DocumentReference.update` / `WriteBatch.update` / `Transaction.update` also accept an * alternating field/value overload, so `update(payload, undefined)` is parsed as a *field* * argument and throws "Input is not an object" — it is not treated as an omitted precondition. * (`delete(undefined)` happens to be tolerated, but every delete call site branches the same way * for one consistent rule.) An empty `{}` is also not a substitute: it is a valid no-op * precondition, so relying on it would quietly widen the SDK surface every write touches. * * Therefore every call site MUST branch on the result of this helper and call the one-argument * form when it is `undefined` — never forward it positionally. A unit test asserts that a * precondition-free `update` reaches the SDK with exactly one argument. */ private toPrecondition; /** * Rejects duplicate document ids in a bulk operation. Two actions targeting the same document in * one batch are ambiguous (for updates, which payload wins?) and inflate result counts, so require * the caller to deduplicate first rather than guessing intent. */ private assertNoDuplicateIds; /** * Normalize update payloads into dot-notation form for merge-style updates. * This keeps nested-object updates explicit at field-path level while allowing * callers to mix regular nested objects and pre-defined dot-notation keys. * * Precedence rule: explicit dot-notation keys always win over values derived * from flattening regular nested objects (e.g. profile.name overrides profile.name * generated from profile: { name: ... }). */ private normalizeUpdateDataForMerge; /** * Validate create payloads using configured schema when available. * Falls back to returning the original payload when validation is disabled. */ private validateCreateData; /** * Validate update payloads using configured schema when available. * Falls back to returning the original payload when validation is disabled. */ private validateUpdateData; /** * Removes top-level `id` from write payloads so document IDs are sourced exclusively * from Firestore document references and method parameters. */ private stripTopLevelId; /** * Rejects a `FieldValue.delete()` sentinel anywhere in a write payload, before any I/O. * * Firestore only honors a delete sentinel on update-like writes (`update()`, or * `set(..., { merge: true })`), so a delete on a plain `create`/`set` fails at commit. This is * called on the **final parsed output** (not the raw input) of every create chokepoint — `create`, * `bulkCreate`, `createInTransaction`, and the `upsert` create branch (all via * {@link validateCreateData}) — so a delete introduced by a schema transform/default is caught too * (review T1). `upsert` additionally rejects a delete on its **update** branch (and up front on the * raw input), so the same input is rejected whether or not the document already exists — the * existence-independent contract ADR-0019 requires. A direct `update()`/`patch()` still permits * delete. Other sentinel kinds (`increment`/`arrayUnion`/`arrayRemove`/`serverTimestamp`) are * backend-valid on create and pass through untouched. */ private assertNoDeleteSentinel; /** * Create a new document in the collection. * Runs validation if schema is configured. * * By default returns only `{ id }` (the generated document id) — the write path validates the * write model but does not read the document back, so it cannot honestly return the read model * `T` (which may differ when a `writeSchema` overlay or `readConverter` is configured). Pass * `{ returnDoc: true }` to read the created document back through the `readConverter` and return * the converted read model. Pass `{ withMetadata: true }` to keep `{ id }` and add the commit * receipt `writeTime` (Admin SDK {@link FirebaseFirestore.WriteResult.writeTime}). `returnDoc` and * `withMetadata` are mutually exclusive. Not available on transactional create helpers — the * Admin SDK exposes no per-op write receipt inside a transaction. * * Auto-id creation uses `CollectionReference.doc().set(...)` (not `add()`) so a * {@link FirebaseFirestore.WriteResult} is always available when metadata is requested; the id is * still client-generated before the write. * * @param data - Document data (without ID) * @param options - `{ returnDoc: true }` for the converted read model, or `{ withMetadata: true }` * for `{ id, writeTime }` * @returns `{ id }` by default; `FirestoreDocument` when `returnDoc` is true; `{ id, writeTime }` * when `withMetadata` is true * @throws {ValidationError} If schema validation fails * * @example * // Default: returns { id } * const { id } = await userRepo.create({ name: 'John Doe', email: 'john@example.com' }); * * @example * // Return the converted read model * const user = await userRepo.create( * { name: 'John Doe', email: 'john@example.com' }, * { returnDoc: true }, * ); * console.log(user.name); * * @example * // Opt-in commit receipt * const { id, writeTime } = await userRepo.create( * { name: 'John Doe', email: 'john@example.com' }, * { withMetadata: true }, * ); */ create(data: CreateInput, options: { returnDoc: true; } & NoWriteMetadataOptions): Promise>; create(data: CreateInput, options: WriteMetadataOptions): Promise>; create(data: CreateInput, options?: { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }>; /** * Create a document under a **caller-supplied id**, failing if that id is already taken. * * This is Firestore `DocumentReference.create()` semantics — a create-only write, not an * overwrite. It is the counterpart to {@link upsert}, which writes regardless of existence: * - `createWithId` → the document must NOT exist; a collision raises {@link ConflictError}. * - `upsert` → creates or updates, never conflicts. * * The check is performed by the backend as part of the write, so it is atomic: two concurrent * `createWithId` calls on the same id cannot both succeed — exactly one wins and the loser gets a * `ConflictError`. That is why this is the correct primitive for claiming an externally-derived * identifier (an email hash, an idempotency key, an upstream record id), where a * read-then-`upsert` would leave a race window open. * * Everything else matches {@link create}: `beforeCreate` / `afterCreate` fire with the caller's id, * the payload goes through the same create validation (dotted keys and `FieldValue.delete()` * sentinels are rejected), and the return contract is `{ id }` unless `{ returnDoc: true }` asks * for a read-back through the `readConverter`. * * @param id - Document ID to claim * @param data - Document data (without ID) * @param options - `{ returnDoc: true }` for the converted read model, or `{ withMetadata: true }` * for `{ id, writeTime }`. The two flags are mutually exclusive. Not available on * `createWithIdInTransaction`. * @returns `{ id }` by default, or the created document (`FirestoreDocument`) when `returnDoc` is true, * or `{ id, writeTime }` when `withMetadata` is true * @throws {InvalidDocumentIdError} If the id is not a single valid Firestore path segment * @throws {ValidationError} If schema validation fails, or the payload carries a delete sentinel * @throws {ConflictError} If a document already exists at that id * * @example * // Claim an externally-derived id exactly once * try { * await userRepo.createWithId('external-id-123', { name: 'John Doe' }); * } catch (error) { * if (error instanceof ConflictError) { * console.log('That id is already taken'); * } * } * * @example * // Return the converted read model * const user = await userRepo.createWithId('user-123', { name: 'Ada' }, { returnDoc: true }); * * @example * // Opt-in commit receipt * const { id, writeTime } = await userRepo.createWithId( * 'user-123', * { name: 'Ada' }, * { withMetadata: true }, * ); */ createWithId(id: ID, data: CreateInput, options: { returnDoc: true; } & NoWriteMetadataOptions): Promise>; createWithId(id: ID, data: CreateInput, options: WriteMetadataOptions): Promise>; createWithId(id: ID, data: CreateInput, options?: { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }>; /** * Create multiple documents in a single batched operation. * More efficient than calling create() in a loop. Uses Firestore batches (500 ops per batch). * * By default returns `{ id }[]` (one generated id per input, in order). Pass * `{ returnDoc: true }` to read every created document back through the `readConverter` and return * the converted read models — matching the single {@link create} contract. Pass * `{ withMetadata: true }` for positional `{ id, writeTime }[]` aligned to the input order across * 500-op chunk boundaries. `returnDoc` and `withMetadata` are mutually exclusive. * * @param dataArray - Array of documents to create * @param options - `{ returnDoc: true }` for converted read models, or `{ withMetadata: true }` for * commit receipts * @returns `{ id }[]` by default, `(FirestoreDocument)[]` when `returnDoc` is true, or * `{ id, writeTime }[]` when `withMetadata` is true * @throws {ValidationError} If any document fails validation * * @example * // Default: returns [{ id }, ...] * const ids = await userRepo.bulkCreate([ * { name: 'Alice', email: 'alice@example.com' }, * { name: 'Bob', email: 'bob@example.com' }, * ]); * * @example * // Return the converted read models * const users = await userRepo.bulkCreate(rows, { returnDoc: true }); * * @example * // Positional commit receipts * const receipts = await userRepo.bulkCreate(rows, { withMetadata: true }); */ bulkCreate(dataArray: CreateInput[], options: { returnDoc: true; } & NoWriteMetadataOptions): Promise[]>; bulkCreate(dataArray: CreateInput[], options: WriteMetadataOptions): Promise[]>; bulkCreate(dataArray: CreateInput[], options?: { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }[]>; /** * Create multiple documents under **caller-supplied ids** in a single batched operation, failing * if any of those ids is already taken. * * The bulk counterpart to {@link createWithId}: every write uses Firestore's create-only * semantics, so a single pre-existing id rejects the whole call with {@link ConflictError}. At or * below 500 entries the batch is atomic — when one create collides, **no** sibling in the batch * lands. Above 500 entries the existing chunked-commit caveat applies (earlier 500-op chunks stay * committed); use a transaction if you need all-or-nothing beyond that. * * Duplicate ids **within the input** are rejected up front, before any I/O. Firestore's own * insert-then-insert diagnostic for that case is an opaque `INVALID_ARGUMENT`, so catching it * locally is what produces an actionable message. * * @param entries - Array of `{ id, data }` pairs to create * @param options - `{ returnDoc: true }` for converted read models, or `{ withMetadata: true }` for * positional `{ id, writeTime }[]` * @returns `{ id }[]` by default, or the created documents when `returnDoc` is true, or * `{ id, writeTime }[]` when `withMetadata` is true * @throws {InvalidDocumentIdError} If any id is not a single valid Firestore path segment * @throws {Error} If the input contains duplicate ids * @throws {ValidationError} If any document fails validation * @throws {ConflictError} If any id already exists (nothing in the batch is written) * * @example * await userRepo.bulkCreateWithIds([ * { id: 'user-1', data: { name: 'Alice' } }, * { id: 'user-2', data: { name: 'Bob' } }, * ]); */ bulkCreateWithIds(entries: { id: ID; data: CreateInput; }[], options: { returnDoc: true; } & NoWriteMetadataOptions): Promise[]>; bulkCreateWithIds(entries: { id: ID; data: CreateInput; }[], options: WriteMetadataOptions): Promise[]>; bulkCreateWithIds(entries: { id: ID; data: CreateInput; }[], options?: { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }[]>; /** * Materialize one existing snapshot into the shape the caller's `withMetadata` flag selected. * * **Requires `snapshot.exists`.** Every caller narrows first; see {@link buildDocumentMetadata} * for why the metadata builder is unsound on a missing document. */ private toDocumentResult; /** * Metadata-carrying counterpart to {@link mapManySnapshots}. * * Deliberately a SEPARATE method rather than a flag on `mapManySnapshots`: that helper is shared * with `getManyInTransaction`, whose result shape is out of scope for issue #39 and whose * `ReadOnlyTransactionalRepository` overloads would not catch a shape change. */ private mapManySnapshotsWithMetadata; /** * Retrieve a document by its ID. * Returns null if the document doesn't exist. * * @param id - Document ID * @returns Document with ID or null if not found * * @example * // Get active user * const user = await userRepo.getById('user-123'); * if (user) { * console.log(user.name); * } * */ getById(id: ID, options: { withMetadata: true; }): Promise> | null>; getById(id: ID, options?: { withMetadata?: false; }): Promise | null>; /** * Retrieve a document by its ID **together with its Firestore `updateTime`** — the token that * drives optimistic-concurrency (compare-and-set) writes. * * This is the read half of the conditional-write flow: pass the returned `updateTime` back as * `lastUpdateTime` on {@link update} / {@link patch} / {@link delete} (or their bulk and * transaction variants) and the write commits only if nobody else changed the document in between. * * The result is a **pair** — `{ doc, updateTime }` — rather than an `updateTime` overlaid on the * document. Overlaying would shadow a stored field named `updateTime` and make it unreachable, * exactly the collision ADR-0018 avoids for `id`. Every other read on this repository keeps its * existing return type; nothing here changes {@link getById}. * * Reads go through `readCol()`, so a configured `readConverter` applies to `doc` and the `id` * overlay behaves identically to {@link getById}. A converter-applied snapshot still carries the * server's `updateTime`, and the token it yields is accepted on the (raw) write reference. * * @param id - Document ID * @returns `{ doc, updateTime }`, or `null` when the document does not exist * @throws {InvalidDocumentIdError} If the id is not a single valid Firestore path segment * * @example * // Precondition-guarded read-modify-write * const current = await userRepo.getByIdWithUpdateTime('user-123'); * if (current) { * await userRepo.update( * current.doc.id, * { name: current.doc.name.trim() }, * { lastUpdateTime: current.updateTime }, * ); * } */ getByIdWithUpdateTime(id: ID): Promise<{ doc: FirestoreDocument; updateTime: FirebaseFirestore.Timestamp; } | null>; /** * Retrieve a document by its ID and throw when it does not exist. * This method is useful when callers require strict existence guarantees and * do not want to branch on nullable results. * * @param id - Document ID * @returns Document with ID * @throws {NotFoundError} If no document exists for the provided id */ getByIdOrThrow(id: ID, options: { withMetadata: true; }): Promise>>; getByIdOrThrow(id: ID, options?: { withMetadata?: false; }): Promise>; /** * Map a `getAll` / `tx.getAll` snapshot array into positional `(doc | null)[]` results. * * WHAT: for each snapshot, either build a `FirestoreDocument` (overlaying `snapshot.id`) or * emit `null` when the document does not exist. * WHY: shared by {@link getMany} and {@link getManyInTransaction} so the existence test and * `.data()` call count stay in one place. Existence is gated on `snapshot.exists` (never on * `data() === undefined`) because an empty field mask yields `{}` for an existing document. * `.data()` is called exactly once per snapshot because a `readConverter`'s `fromFirestore` runs * lazily on every `.data()` invocation and is not memoized. */ private mapManySnapshots; /** * Batched multi-document read by id via a single `BatchGetDocuments` RPC (`db.getAll`). * * Prefer this over `query().whereId('in', ids)` for id lookups: * - No 30-value `in` operator cap (callers reading many thousands should still chunk themselves — * chunking trades away the single-snapshot guarantee; there is no library-enforced hard limit). * - Results are in **input order** (guaranteed client-side by the Admin SDK's re-sort against the * request array — not by the backend). * - Missing documents are marked with `null` in position (`ids[i]` is the missing id), instead of * being silently dropped. * - Empty input returns `[]` without contacting Firestore (`db.getAll()` with zero refs throws). * * Duplicate ids are allowed and return one entry per position (reads are idempotent). Bulk *write* * methods still reject duplicates via {@link assertNoDuplicateIds}. * * Billing: charged per **unique** document read — the SDK dedupes duplicate refs in the outbound * request — while the result still carries one entry per requested position. * * When `fieldMask` is supplied, the result narrows to `FirestoreDocument>` (mirroring * `select()`). The document `id` always survives the projection. `fieldMask: []` is a legal * ID-only projection (`{ id }` for each found document). * * ⚠ With a configured `readConverter`, `fromFirestore` receives the **masked** document. A converter * that dereferences a field the mask omitted will throw a raw `TypeError` — this cannot be fixed * in the library without knowing which fields the converter touches. Either omit the mask, widen * it to cover every field the converter reads, or make the converter defensive. * * @param ids - Document ids to fetch (order preserved; duplicates allowed) * @param options - Optional `{ fieldMask }` projection (paths typed against the stored model `S`) * @returns Positional `(FirestoreDocument | null)[]` aligned with `ids` * @throws {InvalidDocumentIdError} If any id is not a single valid Firestore path segment * (validated before any I/O) * * @example * // Positional results with a miss interleaved * const rows = await userRepo.getMany(['a', 'ghost', 'b']); * // rows[0] = doc a, rows[1] = null, rows[2] = doc b * * @example * // Field-mask projection (DeepPartial narrowing) * const projected = await userRepo.getMany(['a', 'b'], { * fieldMask: ['name', 'address.city'], * }); */ getMany(ids: ID[], options: { fieldMask: (FieldPaths> | FieldPath)[]; withMetadata: true; }): Promise<(WithMetadata>> | null)[]>; getMany(ids: ID[], options: { fieldMask?: never; withMetadata: true; }): Promise<(WithMetadata> | null)[]>; getMany(ids: ID[], options: { fieldMask: (FieldPaths> | FieldPath)[]; withMetadata?: false; }): Promise<(FirestoreDocument> | null)[]>; getMany(ids: ID[], options?: { fieldMask?: never; withMetadata?: false; }): Promise<(FirestoreDocument | null)[]>; /** * Reconstruct the read-typed document from a raw Firestore snapshot. * * This is for snapshots the repository did not read itself — most commonly the snapshot delivered * to a Firestore trigger cloud function (`onDocumentCreated` / `onDocumentUpdated` / * `onDocumentDeleted`). Such snapshots are **not** converter-applied (the Admin SDK only runs a * converter's `fromFirestore` for refs built via `withConverter`) and carry no `id` in * `snapshot.data()`, so a bare `snapshot.data() as T` cast is unsafe. `fromSnapshot` applies this * repository's `readConverter` `fromFirestore` when one is configured, then overlays the document `id` * from `snapshot.id` — mirroring exactly what a normal repository read returns. * * Does no Firestore I/O. Returns the read model `T` (not the write model `W`), and `null` when the * snapshot does not exist. Validation is not performed here (reads are not validated); to validate * at a trust boundary, narrow null then call {@link validate}, e.g. * `const doc = repo.fromSnapshot(snap); if (doc) repo.validate(doc);`. * * @param snapshot - A Firestore `DocumentSnapshot` / `QueryDocumentSnapshot` * @returns The document as `FirestoreDocument`, or `null` if the snapshot does not exist * * @example * // firebase-functions v2 trigger * export const onUserCreated = onDocumentCreated('users/{userId}', event => { * const user = event.data && userRepo.fromSnapshot(event.data); * if (!user) return; * // `user` is a fully reconstructed User & { id } * }); */ fromSnapshot(snapshot: FirebaseFirestore.DocumentSnapshot): FirestoreDocument | null; /** * Validate an already-read value against this repository's canonical read schema (`schemas.read`). * * Reads themselves are compile-time casts; this method is the explicit opt-in trust boundary. * Pass the *final* read shape (after `id` overlay and any `readConverter` transform) — e.g. the * result of `getByIdOrThrow`, `getAll`, or a non-null `fromSnapshot`. Validation therefore runs * against the converted shape, so write the read schema against converted types (e.g. a field a * millis converter exposes as a `number` is `z.number()`). Returns the **parsed** value (Zod * transforms/coercions apply), not the input; per Zod object parsing, keys not declared in the * read schema are stripped from the returned value (as on the write paths). * * On schema mismatch, catches `ZodError` and rethrows {@link ValidationError} — matching write * paths so callers handle one error type. The array overload is all-or-nothing: the first bad * element throws (its `ValidationError` carries that element's issues, without an array index). * Use {@link safeValidate} when one bad document should not fail the batch. * * Requires a schema-configured repository (`withSchema` / `subcollection`). Calling without a * schema is a programmer error and throws a plain `Error` (not `ValidationError`). * * @param data - A single read document, or an array of read documents * @returns The parsed document(s) as `FirestoreDocument` * @throws {ValidationError} If any document fails `schemas.read` validation * @throws {Error} If the repository was constructed without a schema * * @example * // Single read at a trust boundary * const user = repo.validate(await repo.getByIdOrThrow(id)); * * @example * // Trigger snapshot: reconstruct, then validate * const mapped = event.data && repo.fromSnapshot(event.data); * if (mapped) { * const user = repo.validate(mapped); * } * * @example * // List — all-or-nothing * const users = repo.validate(await repo.getAll()); */ validate(data: FirestoreDocument): FirestoreDocument; validate(data: FirestoreDocument[]): FirestoreDocument[]; /** * Non-throwing variant of {@link validate}: validate an already-read value against `schemas.read`. * * Never throws on data-shape mismatch. Mirrors Zod's `safeParse`, but normalizes failures to * {@link ValidationError} (not a raw `ZodError`). The array form returns **one result per * element**, so list callers can drop bad docs instead of losing the whole read: * * ```ts * const ok = repo * .safeValidate(await repo.getAll()) * .filter(r => r.success) * .map(r => r.data); * ``` * * Still throws a plain `Error` when the repository has no schema configured — that is a * programmer/config mistake, distinct from a data-shape failure. * * @param data - A single read document, or an array of read documents * @returns A {@link SafeResult} (or array of them) with parsed data or a `ValidationError` * @throws {Error} If the repository was constructed without a schema * * @example * const result = repo.safeValidate(await repo.getByIdOrThrow(id)); * if (result.success) { * console.log(result.data); * } else { * console.error(result.error.issues); * } */ safeValidate(data: FirestoreDocument): SafeResult; safeValidate(data: FirestoreDocument[]): SafeResult[]; /** * Resolve `schemas.read` for an explicit validate call, or throw a clear config error. * An explicit `validate()` / `safeValidate()` with no schema can only be a mistake — no silent * no-op. */ private requireReadSchemaForValidate; /** * Parse a single read value through `schemas.read`, returning the parsed output. * Wraps Zod failures as {@link ValidationError} to match write-path error handling. */ private parseReadValue; /** * Safe-parse a single read value through `schemas.read`, normalizing failures to ValidationError. */ private safeParseReadValue; /** * Update an existing document with partial data. * Supports both regular fields and dot notation for nested updates. * * @param id - Document ID to update * @param data - Partial document data (supports dot notation like 'address.city') * @param options - Optional update behavior (`merge`, `returnDoc`, `withMetadata`, * `lastUpdateTime`). `{ withMetadata: true }` resolves to `{ id, writeTime }` (Admin SDK commit * receipt). `returnDoc` and `withMetadata` are mutually exclusive. Not available on * `updateInTransaction`. * @returns `{ id }` by default; `FirestoreDocument` when `returnDoc` is true; `{ id, writeTime }` * when `withMetadata` is true * @throws {NotFoundError} If document doesn't exist and no `lastUpdateTime` was supplied * @throws {PreconditionFailedError} If `lastUpdateTime` no longer matches the stored version * (including when the document has been deleted — Firestore reports that as stored version 0) * @throws {ValidationError} If validation fails * * @example * // Regular update * await userRepo.update('user-123', { * email: 'newemail@example.com' * }); * * @example * // Conditional (compare-and-set) update — commits only if nobody wrote in between * const current = await userRepo.getByIdWithUpdateTime('user-123'); * if (current) { * await userRepo.update( * 'user-123', * { email: 'newemail@example.com' }, * { lastUpdateTime: current.updateTime }, * ); * } * * @example * // Dot notation for nested fields * await userRepo.update('user-123', { * 'address.city': 'Los Angeles', * 'address.zipCode': '90001', * name: 'John Doe' * }); * * @example * // Deep nesting * await repo.update('doc-123', { * 'settings.notifications.email': true, * 'settings.theme': 'dark' * }); * * @example * // Merge update while preserving existing fields * await userRepo.update( * 'user-123', * { 'profile.nickname': 'Johnny' }, * { merge: true } * ); */ update(id: ID, data: UpdateInput, options: UpdateOptions & { returnDoc: true; } & NoWriteMetadataOptions): Promise>; update(id: ID, data: UpdateInput, options: UpdateOptions & WriteMetadataOptions): Promise>; update(id: ID, data: UpdateInput, options?: UpdateOptions & { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }>; /** * Shared implementation for {@link update} and the `upsert` update branch. * * `rejectDeleteSentinels` is set only by `upsert`: it rejects a delete sentinel in the final parsed * update payload (after `beforeUpdate` hooks and schema transforms), so `upsert` behaves the same * whether the document exists (this branch) or not (the create branch, which rejects delete via * {@link validateCreateData}). A direct `update()` leaves it `false` — delete stays valid there * (review T1 / ADR-0019). */ private runUpdate; /** * Convenience alias for merge-style partial updates. * Equivalent to update(id, data, { merge: true }). * * Accepts the same optimistic-concurrency `lastUpdateTime` precondition as {@link update} — the * merge normalization happens before the write, so the precondition still guards the exact stored * version the caller read. Pass `{ withMetadata: true }` for `{ id, writeTime }`; `returnDoc` and * `withMetadata` are mutually exclusive. Not available on `patchInTransaction`. * * @example * const current = await userRepo.getByIdWithUpdateTime('user-123'); * if (current) { * await userRepo.patch( * 'user-123', * { 'profile.nickname': 'Johnny' }, * { lastUpdateTime: current.updateTime }, * ); * } */ patch(id: ID, data: UpdateInput, options: { returnDoc: true; lastUpdateTime?: FirebaseFirestore.Timestamp; } & NoWriteMetadataOptions): Promise>; patch(id: ID, data: UpdateInput, options: WriteMetadataOptions & { lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise>; patch(id: ID, data: UpdateInput, options?: { returnDoc?: false; lastUpdateTime?: FirebaseFirestore.Timestamp; } & NoWriteMetadataOptions): Promise<{ id: ID; }>; /** * Update multiple documents in a single batched operation. * Supports dot notation for nested field updates. * * Each entry may carry its own `lastUpdateTime` precondition. Preconditions are evaluated by the * backend at commit time, so at or below 500 operations the batch stays atomic: if any one * precondition fails, the whole batch is rejected and **nothing** changes. Above 500 operations the * existing chunked-commit caveat applies — earlier chunks are already committed when a later chunk * fails. * * Pass `{ withMetadata: true }` for positional `{ id, writeTime }[]` aligned to the input (and to * successfully committed chunk order above 500 ops). * * @param updates - Array of update operations with ID, data, and an optional `lastUpdateTime` * @param options - `{ withMetadata: true }` to include each write's commit `writeTime` * @returns Array of updated document IDs, or `{ id, writeTime }[]` when metadata is requested * @throws {NotFoundError} If any document doesn't exist * @throws {PreconditionFailedError} If any supplied `lastUpdateTime` no longer matches * @throws {ValidationError} If any validation fails * * @example * // Regular bulk update * await userRepo.bulkUpdate([ * { id: 'user-1', data: { status: 'active' } }, * { id: 'user-2', data: { status: 'active' } } * ]); * * @example * // With dot notation * await userRepo.bulkUpdate([ * { id: 'user-1', data: { 'profile.verified': true } }, * { id: 'user-2', data: { 'settings.theme': 'dark' } } * ]); * * @example * // Per-entry preconditions — all-or-nothing at or below 500 operations * await userRepo.bulkUpdate([ * { id: 'user-1', data: { status: 'active' }, lastUpdateTime: firstToken }, * { id: 'user-2', data: { status: 'active' }, lastUpdateTime: secondToken }, * ]); */ bulkUpdate(updates: { id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options: WriteMetadataOptions): Promise[]>; bulkUpdate(updates: { id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options?: NoWriteMetadataOptions): Promise<{ id: ID; }[]>; /** * Shared batched-write pipeline for {@link bulkUpdate} (replace) and {@link bulkPatch} (merge). * Merge mode normalizes nested objects into field paths BEFORE validating, so each leaf is * validated independently (a partial nested object doesn't require its siblings) — exactly the * order used by single-document `update`/`patch`, so the bulk and single-document variants stay * behaviorally identical. */ private runBulkBatchWrite; /** * Convenience alias for merge-style batched updates. * This method applies the same normalization behavior as patch(): * nested objects are flattened to dot-notation updates, explicit dot keys * take precedence over flattened keys, and writes execute via batch.update. * * Each entry may carry its own `lastUpdateTime` precondition, with the same atomicity behavior as * {@link bulkUpdate}. Pass `{ withMetadata: true }` for positional `{ id, writeTime }[]` aligned * across 500-op chunks. * * @param updates - Array of update operations with ID, data, and an optional `lastUpdateTime` * @param options - `{ withMetadata: true }` to include each write's commit `writeTime` * @returns Array of updated document IDs, or `{ id, writeTime }[]` when metadata is requested * @throws {NotFoundError} If any document doesn't exist * @throws {PreconditionFailedError} If any supplied `lastUpdateTime` no longer matches * @throws {ValidationError} If any validation fails * * @example * await userRepo.bulkPatch([ * { id: 'user-1', data: { profile: { settings: { theme: 'dark' } } } as any }, * { id: 'user-2', data: { 'profile.settings.notifications': true } as any }, * ]); */ bulkPatch(updates: { id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options: WriteMetadataOptions): Promise[]>; bulkPatch(updates: { id: ID; data: UpdateInput; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options?: NoWriteMetadataOptions): Promise<{ id: ID; }[]>; /** * Create a new document if it doesn't exist, or update it if it does. * Uses the provided ID instead of auto-generating one. * * Pass `{ returnDoc: true }` for the converted read model, or `{ withMetadata: true }` for * `{ id, writeTime }` on either the create or update branch. The two flags are mutually exclusive. * Not available inside a transaction helper. * * @param id - Document ID to upsert * @param data - Full document data * @param options - `{ returnDoc: true }` or `{ withMetadata: true }` * @returns `{ id }` by default; `FirestoreDocument` when `returnDoc` is true; `{ id, writeTime }` * when `withMetadata` is true * @throws {ValidationError} If validation fails * * @example * // Sync external data * await userRepo.upsert('external-id-123', { * name: 'John Doe', * email: 'john@example.com', * source: 'external-api' * }); * * @example * // Idempotent operations * await settingsRepo.upsert('app-config', { * theme: 'dark', * notifications: true * }); */ upsert(id: ID, data: CreateInput, options: { returnDoc: true; } & NoWriteMetadataOptions): Promise>; upsert(id: ID, data: CreateInput, options: WriteMetadataOptions): Promise>; upsert(id: ID, data: CreateInput, options?: { returnDoc?: false; } & NoWriteMetadataOptions): Promise<{ id: ID; }>; /** * Permanently delete a document from Firestore. * This is a hard delete - the document cannot be recovered. * * Optionally guarded by a `lastUpdateTime` precondition, so a document that changed since the * caller read it is not deleted out from under the newer writer. * * Note the interaction with this method's own existence pre-read: `delete(id, { lastUpdateTime })` * on an **already-missing** document raises {@link NotFoundError} (the pre-read throws first), not * `PreconditionFailedError`. Only a document that exists but has moved on reaches the backend * precondition. The pre-read is unconditional and unchanged — `delete(id)` without a precondition * behaves exactly as before, and this method never auto-preconditions on its own snapshot (that * would turn today's benign races into errors). * * @param id - Document ID to delete * @param options - `{ lastUpdateTime }` to delete only if the document is still at that version; * `{ withMetadata: true }` to resolve to `{ writeTime }` instead of `void`. Not available on * `deleteInTransaction`. * @returns `void` by default, or {@link WriteMetadata} when `withMetadata` is true * @throws {NotFoundError} If document doesn't exist * @throws {PreconditionFailedError} If `lastUpdateTime` no longer matches the stored version * * @example * // Delete a user permanently * await userRepo.delete('user-123'); * * @example * // Delete with error handling * try { * await userRepo.delete('user-123'); * console.log('User deleted successfully'); * } catch (error) { * if (error instanceof NotFoundError) { * console.log('User not found'); * } * } * * @example * // Conditional delete — only if the document has not changed since it was read * const current = await userRepo.getByIdWithUpdateTime('user-123'); * if (current) { * await userRepo.delete('user-123', { lastUpdateTime: current.updateTime }); * } * * @example * // Opt-in commit receipt * const { writeTime } = await userRepo.delete('user-123', { withMetadata: true }); */ delete(id: ID, options: { withMetadata: true; lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise; delete(id: ID, options?: { withMetadata?: false; lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise; /** * Permanently delete multiple documents in a batched operation. * This is a hard delete - documents cannot be recovered. * * Accepts either a plain array of ids or an array of `{ id, lastUpdateTime? }` entries, so * individual deletes can be guarded by an optimistic-concurrency precondition. The two forms are * separate overloads and cannot be mixed in one array. * * Preconditions do not change the "already gone → not counted" behavior: the existence pre-read * still filters missing documents out **before** the batch is built, so an entry whose document has * already been deleted is skipped rather than raising `PreconditionFailedError`. An empty input (or * an input where nothing exists) returns `0` without a commit. * * The existence pre-read is a single `db.getAll` (`BatchGetDocuments`) — one point-in-time-consistent * snapshot that the delete hooks observe — not N parallel `get()`s (which can span distinct * `readTime`s). An empty-id guard runs before `getAll` because the SDK rejects a zero-ref call. * * @param entries - Array of document IDs, or of `{ id, lastUpdateTime? }` entries * @param options - `{ withMetadata: true }` to resolve to `{ count, writeTimes }` for surviving * documents only (missing requested ids contribute neither a count nor a fabricated receipt) * @returns Number of documents actually deleted, or `{ count, writeTimes }` when metadata is * requested (`writeTimes.length === count`, aligned to surviving snapshot order) * @throws {PreconditionFailedError} If a supplied `lastUpdateTime` no longer matches (at or below * 500 operations the batch is atomic, so nothing is deleted) * * @example * // Delete multiple users * const deletedCount = await userRepo.bulkDelete([ * 'user-1', * 'user-2', * 'user-3' * ]); * console.log(`Deleted ${deletedCount} users`); * * @example * // Clean up test data * const testUserIds = await userRepo.query() * .where('email', 'array-contains', '@test.com') * .get() * .then(users => users.map(u => u.id)); * await userRepo.bulkDelete(testUserIds); * * @example * // Conditional bulk delete — each entry guarded by the version it was read at * await userRepo.bulkDelete([ * { id: 'user-1', lastUpdateTime: firstToken }, * { id: 'user-2' }, // unguarded entries may be mixed in as objects * ]); * * @example * // Opt-in receipts for surviving deletes only * const { count, writeTimes } = await userRepo.bulkDelete(ids, { withMetadata: true }); */ bulkDelete(ids: ID[], options: WriteMetadataOptions): Promise<{ count: number; writeTimes: FirebaseFirestore.Timestamp[]; }>; bulkDelete(ids: ID[], options?: NoWriteMetadataOptions): Promise; bulkDelete(entries: { id: ID; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options: WriteMetadataOptions): Promise<{ count: number; writeTimes: FirebaseFirestore.Timestamp[]; }>; bulkDelete(entries: { id: ID; lastUpdateTime?: FirebaseFirestore.Timestamp; }[], options?: NoWriteMetadataOptions): Promise; /** * Bulk hook events a fixed-batch helper would have run. {@link bulkWrite} runs none of them, so it * refuses to start when any is registered unless the caller passes `{ skipHooks: true }`. */ private static readonly BULK_HOOK_EVENTS; /** * Refuses a {@link bulkWrite} on a repository whose bulk hooks would silently not fire. * * A hook bypass is exactly the failure the scope docs warn about for raw batches: audit trails and * cache invalidation stop running with no error and no log. The fixed-batch helpers cannot be * reused here — `afterBulkUpdate({ ids })` promises an all-or-nothing set, and BulkWriter is * per-item — so the honest options are "no hooks, loudly" or "no hooks, silently". This is the loud * one. */ private assertNoBulkHooksRegistered; /** * Normalizes a per-item failure the same way every other write path normalizes a whole-call one: a * raw `ZodError` becomes {@link ValidationError}, everything else goes through * {@link parseFirestoreError}. */ private toBulkWriteItemError; /** * High-throughput, **non-atomic** writes backed by the Admin SDK's `BulkWriter`, with a result per * operation. * * This is a *separate contract* from the fixed-batch helpers * (`bulkCreate`/`bulkCreateWithIds`/`bulkUpdate`/`bulkPatch`/`bulkDelete`), not a faster version of * them. Pick deliberately: * * | | Fixed batch (`bulk*`) | `bulkWrite` | * | --- | --- | --- | * | Atomicity | atomic at or below 500 ops | **never** — each op succeeds or fails alone | * | Failure | first failure throws; nothing after it is applied | per-item result; siblings still land | * | Hooks | run | **none** (throws if any bulk hook is registered — see `skipHooks`) | * | Retries | none | SDK default: transient statuses, up to 10 attempts per op | * | Throughput | 500-op sequential commits | parallel, rate-limit ramped | * | Duplicate ids | rejected | rejected (see below) | * * Duplicate ids are rejected here for a **stronger** reason than on the fixed-batch helpers. The * SDK puts two writes to one document in separate batches, but those batches are dispatched * concurrently and their commits race — `BulkWriter`'s internal ordering chain is global, not * per-document — so which of the two lands last is genuinely undefined. Sequence such writes with * separate `bulkWrite` calls (or a transaction) instead. * * Results are **positional**: `results[i]` describes `operations[i]`. Because a failure is a * normal, expected outcome, nothing here throws for a bad *item* — a malformed id, a schema * rejection, an empty update payload, or a backend refusal all land as that item's * `{ ok: false, error }` while every other operation still writes. Only whole-call problems throw * (registered hooks without `skipHooks`). * * Validation is unchanged per verb: `create` / `set` validate as a full create (dot-notation keys * and `FieldValue.delete()` rejected, ADR-0019), `update` / `patch` as a partial update, and * `patch` normalizes nested objects into field paths first — exactly as * {@link bulkPatch} does. * * @param operations - Operations to apply, in enqueue order * @param options - `{ skipHooks }` to acknowledge the no-hooks contract, `{ throttling }` to * override the SDK's rate-limit ramp * @returns One {@link BulkWriteResult} per input operation, in input order * @throws {Error} If a bulk hook is registered and `skipHooks` is not `true`, or if two operations * target the same explicit id * * @example * // Mixed operations in one high-throughput pass * const results = await userRepo.bulkWrite([ * { op: 'create', data: { name: 'Ada' } }, * { op: 'update', id: 'user-1', data: { status: 'active' } }, * { op: 'delete', id: 'user-2' }, * ]); * * @example * // A 10k-row import where one bad row must not cost the other 9,999 * const results = await userRepo.bulkWrite(rows.map(data => ({ op: 'create', data }))); * const failed = results.filter(result => !result.ok); * console.log(`${results.length - failed.length} written, ${failed.length} rejected`); * for (const failure of failed) console.error(failure.index, failure.error.message); * * @example * // Cap the write rate, and acknowledge that hooks will not fire * await userRepo.bulkWrite(operations, { * skipHooks: true, * throttling: { maxOpsPerSecond: 200 }, * }); */ bulkWrite(operations: BulkWriteOperation[], options?: BulkWriteOptions): Promise; /** * **Destructive.** Permanently deletes the document at `id` **and every descendant** — all * subcollections, at any depth — via the Admin SDK's `Firestore.recursiveDelete()`. * * Separate from {@link delete} on purpose. `delete(id)` removes one document and *orphans* its * subcollections (they survive, unreachable through the parent); this removes the whole subtree and * cannot be undone. Nothing outside the subtree is touched: siblings survive, and so does a * collection whose id merely shares a prefix with one being deleted. * * Three contract differences from every other write on this class: * * 1. **No lifecycle hooks run** — not `beforeDelete`/`afterDelete` for the target, and nothing for * the descendants. The SDK streams name-only snapshots (`select(__name__)`), so there is no * document data to hand a hook, and descendants live in collections this repository does not * model. If your delete hooks are load-bearing, read + delete through concrete repositories * instead. * 2. **No count is returned.** The SDK reports none, and one cannot be synthesized honestly: a * delete of an already-absent document *succeeds*, so any tally would count delete operations * rather than documents that existed. * 3. **Partial failure is possible and is reported as a whole-call error.** Deletes are issued in * parallel with no atomicity across the subtree, so a rejection means "some deletes failed" — * the SDK's error states how many, and carries the *last* failure's status code. Documents * already deleted stay deleted; re-running is safe and idempotent. * * A missing document is **not** an error: there is simply nothing to delete, and the call resolves. * * @param id - Id of the document whose subtree is deleted * @throws {InvalidDocumentIdError} If `id` is not a single valid path segment * @throws {Error} If any delete in the subtree failed (message states the count; status code is the * last failure's) * * @example * // Delete a user and everything beneath them (posts, posts' comments, …) * await userRepo.recursiveDelete('user-123'); * * @example * // Works from a subcollection repository too — the subtree is scoped to that document * const postRepo = userRepo.subcollection('user-123', 'posts', postSchema); * await postRepo.recursiveDelete('post-1'); // deletes post-1 and its comments */ recursiveDelete(id: ID): Promise; /** * **Highly destructive.** Permanently deletes **every document in this repository's collection** * and every descendant subcollection, at any depth, via the Admin SDK's * `Firestore.recursiveDelete()`. * * This is deliberately separate from {@link recursiveDelete}, which removes one document subtree, * and {@link delete}, which removes one document but leaves its subcollections orphaned. When this * repository points at a subcollection, only that concrete subcollection is removed: its parent * document and sibling collections survive. A collection whose id merely shares this collection's * prefix also survives. * * No lifecycle hooks run and no count is returned. The SDK reads names only and descendants may * belong to collections this repository does not model. An empty collection resolves successfully; * re-running is safe. Deletes are non-atomic, so a rejection can mean some documents were already * removed; the SDK reports the failure count and last failure status. * * @returns Nothing after all discovered documents have been deleted * @throws {Error} If any descendant delete failed; already-deleted documents remain deleted * * @example * // Delete every user and every descendant beneath every user. * await userRepo.recursiveDeleteCollection(); * * @example * // Delete every post below one user; the user document and sibling subcollections survive. * const postRepo = userRepo.subcollection('user-123', 'posts', postSchema); * await postRepo.recursiveDeleteCollection(); */ recursiveDeleteCollection(): Promise; /** * Find documents by a specific field value. * Simple equality search on a single field. * * @param field - The field name to search on * @param value - The value to match * @returns Array of matching documents * * @example * // Find users by email * const users = await userRepo.findByField('email', 'john@example.com'); * * @example * // Find orders by status * const pendingOrders = await orderRepo.findByField('status', 'pending'); */ findByField(field: FieldPaths> | FieldPath, value: unknown, options: { withMetadata: true; }): Promise>[]>; findByField(field: FieldPaths> | FieldPath, value: unknown, options?: { withMetadata?: false; }): Promise[]>; /** * Find the first document that matches a specific field value. * This is a convenience helper when callers expect zero-or-one match semantics * and do not need the full array that `findByField(...)` returns. * * Behavior intentionally mirrors the legacy `getBy` pattern: * - returns the first matching document when one or more documents match * - returns `null` when no documents match * * @param field - The field name to search on * @param value - The value to match * @returns The first matching document or null when no match exists * * @example * // Find a user by email * const user = await userRepo.getOneByField('email', 'john@example.com'); * * @example * // Return null when no matching document exists * const missing = await orderRepo.getOneByField('externalId', 'missing-id'); * if (!missing) { * console.log('No order found'); * } */ getOneByField(field: FieldPaths> | FieldPath, value: unknown, options: { withMetadata: true; }): Promise> | null>; getOneByField(field: FieldPaths> | FieldPath, value: unknown, options?: { withMetadata?: false; }): Promise | null>; /** * Find exactly one document by field value and throw when strict constraints are not met. * This helper enforces both existence and uniqueness semantics for workflows that expect * one and only one matching document. * * @param field - The field name to search on * @param value - The value to match * @returns The matching document * @throws {NotFoundError} If no document matches the provided field/value * @throws {ConflictError} If more than one document matches the provided field/value */ getOneByFieldOrThrow(field: FieldPaths> | FieldPath, value: unknown, options: { withMetadata: true; }): Promise>>; getOneByFieldOrThrow(field: FieldPaths> | FieldPath, value: unknown, options?: { withMetadata?: false; }): Promise>; /** * Subscribe to real-time updates for a single document by id. * The callback receives the latest document state whenever Firestore emits changes. * * @param id - Document ID to observe * @param callback - Function invoked with the updated document * @param onError - Optional error handler for not-found and Firestore errors * @returns Unsubscribe function to stop listening */ listenOne(id: ID, callback: (item: FirestoreDocument) => void, onError?: (error: Error) => void): () => void; /** * Subscribe to real-time updates for a single document, **with snapshot metadata**. * * Identical to {@link listenOne} except that the callback receives `{ doc, metadata }` — the same * document under `doc`, plus its Firestore `ref` / `path` / `parentPath` / `createTime` / * `updateTime` / `readTime`. * * Deletion is reported the same way {@link listenOne} reports it: through * `onError(new NotFoundError(...))`, not as a callback emission. A deleted document's snapshot * carries no `createTime` / `updateTime`, so there is no metadata to deliver for it. * * @param id - Document ID to observe * @param callback - Function invoked with the updated document and its metadata * @param onError - Optional error handler for not-found and Firestore errors * @returns Unsubscribe function to stop listening * * @example * const unsubscribe = userRepo.listenOneDetailed( * 'user-123', * ({ doc, metadata }) => { * console.log(`${doc.name} last written ${metadata.updateTime.toDate().toISOString()}`); * }, * error => console.error(error), * ); */ listenOneDetailed(id: ID, callback: (item: WithMetadata>) => void, onError?: (error: Error) => void): () => void; /** * Get all documents in the collection. * This method intentionally performs an unbounded read, so callers should * prefer query().paginate() for large collections where incremental loading * is more appropriate. * * @returns Array of all documents in the collection * * @example * // Fetch the entire users collection * const users = await userRepo.getAll(); */ getAll(options: { withMetadata: true; }): Promise>[]>; getAll(options?: { withMetadata?: false; }): Promise[]>; /** * Create a query builder for complex queries. * Provides a fluent API for filtering, sorting, pagination, and more. * * @returns Query builder instance * * @example * // Simple query * const activeUsers = await userRepo.query() * .where('status', '==', 'active') * .get(); * * @example * // Complex query with multiple conditions * const results = await orderRepo.query() * .where('status', '==', 'pending') * .where('total', '>', 100) * .orderBy('createdAt', 'desc') * .limit(50) * .get(); * * @example * // Pagination * const page = await productRepo.query() * .where('category', '==', 'electronics') * .orderBy('price', 'desc') * .paginate(20, lastCursor); */ query(): FirestoreQueryBuilder; /** * Query the **collection group** this repository's collection belongs to — every collection with * the same id, at any depth in the database, including a same-named root collection. * * The group id is the last segment of this repository's collection path, so a repository for * `users/u1/posts` groups over `posts`. The returned {@link FirestoreCollectionGroup} carries this * repository's read model, stored (query-path) model, `readConverter`, and * `allowLegacyDatastoreIds` policy — a group query is typed and validated exactly like * {@link query}. * * **Read-only, and results carry full-path identity.** A collection group has no * `CollectionReference`, so there is no `create` / `getById` / `update` / `delete` surface, and * document ids are not unique across the group — reads return `CollectionGroupDocument`s with * `path` and `parentPath` alongside `id`. See ADR-0024. * * **Indexes:** Firestore's automatic single-field indexes are collection-scoped, so a * collection-group query that filters or orders on a field needs an explicitly created * collection-group-scoped index in production — even for a single `where(...)`. The emulator does * not enforce this. * * @throws {Error} If this repository's read **or stored** schema declares a top-level `path` or * `parentPath`, which the group identity overlay would shadow (or, for a stored-only field, * which `where('path', …)` could filter while the result can never expose). * * @example * // Every `posts` subcollection, across every user. * const postGroup = userRepo.subcollection('u1', 'posts', postSchema).collectionGroup(); * const drafts = await postGroup.query().where('status', '==', 'draft').get(); * drafts[0].path; // 'users/u7/posts/abc' * * @example * // No concrete parent handy? A top-level handle does no I/O at construction. * const postGroup = FirestoreRepository.withSchema(db, 'posts', postSchema).collectionGroup(); */ collectionGroup(): FirestoreCollectionGroup; /** * Validate an untrusted string as a document id for this repository, returning it for use with the * repository's id-taking methods. This is the explicit trust boundary for ids arriving from outside * (route params, queue payloads, external references): it throws {@link InvalidDocumentIdError} for * anything Firestore would reject, so callers can validate once at the edge. * * @example * const id = userRepo.id(req.params.userId); // throws InvalidDocumentIdError if malformed * const user = await userRepo.getById(id); */ id(raw: string): ID; /** * Generate a new, validated auto-id **without** writing a document. The id is independent of any * later write — `create()` (via `doc().set()`) and `createInTransaction()` each generate their * **own** fresh id — so persist under this id explicitly with `upsert(id, …)` or a transaction * `set`. Useful when you need the id before the write, e.g. to reference it elsewhere in the same * transaction. * * @example * const id = userRepo.newId(); * await userRepo.upsert(id, { name: 'Ada' }); // writes under exactly `id` */ newId(): ID; /** * Refuses an interceptor target built on a **different** `Firestore` instance. * * There is no SDK guard for this and no error either: staging a `DocumentReference` from another * `Firestore` into this instance's batch is accepted, `commit()` returns a real `writeTime`, and * the document is then readable through *neither* instance (measured — probe P8b). Interceptors are * the first API that makes a foreign repository reachable at a write boundary, so the guard lives * here, on every writer and reader member, and throws before anything is staged. */ private assertSameFirestoreInstance; /** * Builds the {@link InterceptorWriter} for one staging boundary. * * Every member stages into `target` — never commits — and runs the target repository's **own** * validation first, so an interceptor cannot write a payload a direct call would have rejected. * Reaching another repository's `private` members is deliberate and legal from inside this class * body; it is what lets a sibling write be validated by the repository that owns that collection. */ private buildInterceptorWriter; /** * Builds the {@link InterceptorReader} for one transaction. * * Reads join the caller's transaction, so what an interceptor reads is consistent with what it * then stages. Same instance-identity guard as the writer: a read through a foreign `Firestore` * would resolve against the wrong database. */ private buildInterceptorReader; /** Registered write interceptors, in registration order (ADR-0040 Decision 1: per instance). */ private interceptors; /** * Registers a write interceptor: writes it stages are **guaranteed** to commit in the same atomic * boundary as the repository write that triggered it, on every write path — or that path refuses * (ADR-0040). * * This is not another lifecycle hook. A hook is a notification that runs *outside* the write's * boundary and may be skipped; an interceptor's writes land with the domain write or nothing lands. * Where no shared boundary exists — `bulkWrite`, `recursiveDelete`, * `recursiveDeleteCollection` — the path **throws** rather than silently dropping the guarantee. * * **Registration is per repository instance and lives for the process**, like {@link on}. It is * carried into the repository handed to a {@link runInTransaction} callback, and deliberately *not* * into `subcollection()` / `withSchema()` / `withSchemaArgs()`, which model a different collection * whose write model this interceptor could not satisfy. * * **The mode is a union over registrations** (ADR-0040 Decision 7): with only write-only * interceptors registered, single-document writes commit as a `WriteBatch` and the fixed-batch * helpers and query write terminals keep working. Registering **one** interceptor with a `read` * phase promotes every single-document write to a transaction, and those bulk paths then refuse * (a transaction cannot be chunked), as does `{ withMetadata: true }` (a transaction exposes no * per-operation write receipt). * * Interceptors run in **registration order**, sequentially, and the first one to throw aborts the * whole write — nothing is committed, and no later interceptor runs. * * @param interceptor - `{ name, write }`, or `{ name, read, write }` for the read-capable flavour. * `name` must be unique on this repository: read results are keyed by it. * @throws {Error} If an interceptor with the same `name` is already registered * * @example * // Write-only: keep a counter document in step with every write, in one batch. * userRepo.registerWriteInterceptor({ * name: 'user-count-mirror', * write: ({ write, writer }) => { * writer.set(statsRepo, 'users', { lastTouchedId: write.id }, { merge: true }); * }, * }); * * @example * // Read-capable: every write on this repository now runs in a transaction. * userRepo.registerWriteInterceptor({ * name: 'audit-trail', * read: async ({ write, reader }) => await reader.get(auditRepo, write.id), * write: ({ write, writer, reads }) => { * writer.set(auditRepo, write.id, { revision: (reads?.revision ?? 0) + 1 }); * }, * }); */ registerWriteInterceptor(interceptor: WriteOnlyInterceptor): void; registerWriteInterceptor(interceptor: ReadCapableInterceptor): void; /** * Collects the writes every registered interceptor wants to stage alongside one domain write. * * Returns staging closures, never a committed write: the caller decides whether they land in a * `WriteBatch` or a `Transaction`. In transaction mode the read phases have already run (see * {@link runInterceptorReads}), because Firestore requires all reads before all writes. */ private collectInterceptorWrites; /** * Runs every read-capable interceptor's read phase, before any write is staged. * * Firestore requires all reads in a transaction to precede all writes, so this runs to completion * first and the write phases are synchronous by type. Results are keyed by interceptor name — which * {@link registerWriteInterceptor} requires to be unique — so each write phase receives its own. */ private runInterceptorReads; /** * Refuses a chunked-batch write path while a **read-capable** interceptor is registered. * * A transaction cannot be chunked into 500-operation batches, so these paths have no honest way to * host an interceptor that declares a read phase. Write-only interceptors are fine here — they * stage into the batch alongside the domain writes — which is why this is a narrower guard than * {@link assertNoInterceptorsRegistered}. * * Called as the **first statement** of each affected path, deliberately ahead of that path's * existence pre-read and its `beforeBulk*` hooks: a call that cannot proceed should not first * perform a batched read and fire user hooks that may have side effects of their own. */ private assertNoReadCapableInterceptor; /** * Refuses a write path that cannot host a shared atomic boundary, naming the interceptors that * would otherwise be silently skipped. * * Mirrors {@link assertNoBulkHooksRegistered}, with one deliberate difference: there is no * `{ skipHooks: true }`-style acknowledgement. A hook is a notification and may be waived; an * interceptor is a guarantee, so "skip it" is not an honest option (ADR-0040 Decision 4). */ private assertNoInterceptorsRegistered; /** * Rejects `{ withMetadata: true }` while a transaction-mode interceptor is active. * * A transaction exposes no per-operation receipt (`tx.create(...)` returns the `Transaction`), so * any `writeTime` here would be fabricated or transaction-level — the same reasoning that keeps * `withMetadata` off the `*InTransaction` helpers. The message names the interceptor that forced * the mode union, because the caller who hits this typically did not register it. * * Batch mode is deliberately unaffected: batch receipts are real and positional, so `withMetadata` * keeps working there. */ private assertNoWriteMetadataUnderTransactionMode; /** * Runs one single-document write through whichever boundary the registered interceptors require, * and returns the domain write's receipt when one exists. * * Three paths, and the first is the important one: * - `'none'` — calls `direct()`, which is the untouched pre-interceptor write. No batch, no * transaction, no behavior change for the overwhelming majority of repositories (ADR-0040 * Decision 8). * - `'batch'` — one {@link WriteGroup} through {@link commitInChunks}, so the returned receipt is * the **domain** receipt and `withMetadata` keeps working. * - `'transaction'` — reads first, then the domain write, then the interceptor writes, all inside * one `db.runTransaction`. Returns `undefined`: there is no per-operation receipt in a * transaction, which is why `withMetadata` is refused up front. * * @returns The domain write's `WriteResult`, or `undefined` in transaction mode */ private runInterceptedWrite; /** * Refuses a transaction-mode write when a transaction is already open on the SAME `Firestore` * instance, rather than silently opening a second, independent one (ADR-0040 Amendment, issue * #112). * * The hazard: a read-capable interceptor promotes every single-document write on its repository to * `db.runTransaction(...)` (ADR-0040 Decision 7). Calling such a write from inside another * `runInTransaction` callback — including the SAME repository's own tx-clone calling a plain write * method instead of its `*InTransaction` counterpart (T2) — would otherwise nest two independent * transactions, which can contend or deadlock on overlapping documents. * * Deliberately scoped to the same `Firestore` instance (T3) and to this promoted-write branch only * — an explicit, interceptor-free `runInTransaction` nested inside another one is unchanged (T4); * this refusal targets only the silent promotion ADR-0040 introduced. */ private assertNoAmbientTransaction; /** * Stages one domain write, plus every interceptor's writes, into the **caller's** transaction. * * The `*InTransaction` helpers already have the one thing interceptors need — a transaction — so * there is no mode branch here and no nested `runTransaction`: a write-only and a read-capable * interceptor behave identically, both joining the boundary the caller opened. `withMetadata` does * not exist on these helpers, so there is nothing to refuse either. * * The read phase runs before the domain write is staged, which is why this is the one place the * ordering lives rather than being repeated at four call sites. */ private stageInterceptedWrite; /** * Resolves which write boundary this repository's registrations require, as a **union** over every * registered interceptor (ADR-0040 Decision 7). * * `'none'` keeps every write path byte-identical to a repository with no interceptors (Decision 8). * A single read-capable registration promotes the whole repository to `'transaction'` — the mode is * per repository, not per interceptor, because one shared atomic boundary has to host all of them. */ private interceptorMode; /** * Commits {@link WriteGroup}s in sequential chunks of 500 operations (the Firestore batch limit). * * A group is one **domain** write plus the interceptor writes that must land with it, and a chunk * boundary never falls inside a group: the current batch commits *before* a group that would not * fit whole (ADR-0040 Decision 5). Without that, a domain write could commit in chunk N while its * interceptor write lands in chunk N+1 — losing the only guarantee interceptors sell, and only * above 500 operations. * * Returns **domain receipts only**, in enqueue order across chunks: every caller indexes the * result positionally against its own document list (`writeResults[index]!.writeTime`), and * `bulkDelete` documents `writeTimes.length === count`. Returning interceptor receipts too would * silently hand back another document's `writeTime` (trap T3). A failed chunk contributes no * fabricated receipts — only prior successful chunks appear in the returned array (and in * {@link WriteOutcomeError.committedWrites}). * * **Assumes its callers have already refused transaction mode.** That check lives in * {@link assertNoReadCapableInterceptor}, called as the *first statement* of each of the six bulk * paths — ahead of their existence pre-reads and `beforeBulk*` hooks, so a call that cannot proceed * performs no I/O and fires no hooks. It used to live here, which meant a refused `bulkDelete` had * already run `db.getAll` and fired its hook. Do not treat those six guards as belt-and-braces: * this method no longer refuses, so removing one stops that path refusing at all. * * IMPORTANT — non-atomic above 500 operations: each 500-op chunk commits independently, so an * operation set larger than 500 writes is NOT globally atomic. If a later chunk fails, earlier * chunks remain committed and the operation's after-hook does not run. Bulk operations at or below * 500 writes commit as a single atomic batch. Use a transaction if you need all-or-nothing * semantics across more than 500 documents. With `K` interceptors registered a chunk holds * `floor(500 / (1 + K))` documents, so that boundary is reached at proportionally fewer documents. */ private commitInChunks; /** * Rejects the impossible `{ returnDoc: true, withMetadata: true }` combination before any I/O. * Typed overloads already forbid it for TypeScript callers; this guards JavaScript callers so * the repository never invents an ambiguous combined result shape (trap T4 / D3). */ private assertExclusiveWriteResultOptions; /** * Execute a function within a Firestore transaction, optionally forwarding Admin SDK transaction * options (`maxAttempts`, `{ readOnly: true, readTime? }`). * * Overloads discriminate on `options.readOnly`: * - `{ readOnly: true }` → callback `repo` is {@link ReadOnlyTransactionalRepository} (read-safe * members only — write helpers and non-transactional reads are absent from the type). * - omitted / read-write options → callback `repo` is the full {@link FirestoreRepository}. * * Options are passed through unchanged to `db.runTransaction(fn, options)`. The SDK validates * `maxAttempts` client-side (integer in `[1, Infinity]`); the ORM does not re-validate. * * Prefer {@link runReadOnlyAt} when the only option you need is a PITR / time-travel `readTime`. * * @template R - Return type of the transaction function * @param fn - Transaction callback receiving `(tx, repo)` * @param options - Admin SDK transaction options (`FirebaseFirestore.ReadOnlyTransactionOptions` or * `FirebaseFirestore.ReadWriteTransactionOptions`) * @returns Result of the transaction function * * @example * // Transfer balance between accounts (read-write, default retries) * await accountRepo.runInTransaction(async (tx, repo) => { * const from = await repo.getInTransaction(tx, 'account-1'); * const to = await repo.getInTransaction(tx, 'account-2'); * * if (!from || from.balance < 100) { * throw new Error('Insufficient funds'); * } * * await repo.updateInTransaction(tx, from.id, { * balance: from.balance - 100 * }); * await repo.updateInTransaction(tx, to.id, { * balance: to.balance + 100 * }); * }); * * @example * // Cap contention retries on a read-write transaction * await counterRepo.runInTransaction(async (tx, repo) => { * const counter = await repo.getInTransaction(tx, 'global-counter'); * const newValue = (counter?.value || 0) + 1; * await repo.updateInTransaction(tx, 'global-counter', { value: newValue }); * return newValue; * }, { maxAttempts: 3 }); * * @example * // Read-only transaction — callback repo has no write helpers * const snap = await accountRepo.runInTransaction( * async (tx, repo) => repo.getInTransaction(tx, 'account-1'), * { readOnly: true }, * ); * * @example * // PITR / time-travel read (prefer runReadOnlyAt for this shape) * const historical = await accountRepo.runInTransaction( * async (tx, repo) => repo.getInTransaction(tx, 'account-1'), * { readOnly: true, readTime }, * ); */ runInTransaction(fn: (tx: FirebaseFirestore.Transaction, repo: ReadOnlyTransactionalRepository) => Promise, options: FirebaseFirestore.ReadOnlyTransactionOptions): Promise; runInTransaction(fn: (tx: FirebaseFirestore.Transaction, repo: FirestoreRepository) => Promise, options?: FirebaseFirestore.ReadWriteTransactionOptions): Promise; /** * Run a read-only transaction at a consistent `readTime` (PITR / time-travel when enabled on the * database, or within the ~60s window otherwise). * * Thin wrapper around {@link runInTransaction} with `{ readOnly: true, readTime }`. The callback * `repo` is {@link ReadOnlyTransactionalRepository} — only pure / transaction-scoped members. * * Note: the Firestore emulator accepts a `readTime` well past the 60s window without error, where * production rejects it absent PITR retention. Local success is not proof the production call will * succeed. * * @template R - Return type of the transaction function * @param readTime - Snapshot timestamp for the read-only transaction * @param fn - Read-only transaction callback * @returns Result of the transaction function * * @example * const historical = await accountRepo.runReadOnlyAt(readTime, async (tx, repo) => { * return repo.getInTransaction(tx, 'account-1'); * }); * * @example * // Query-shaped PITR via the Admin SDK escape hatch + fromSnapshot mapping. * // Build the collection from the callback repo so nested / dynamic paths stay correct. * await userRepo.runReadOnlyAt(readTime, async (tx, repo) => { * const snap = await tx.get( * db.collection(repo.getCollectionPath()).where('status', '==', 'active'), * ); * return snap.docs.map(d => repo.fromSnapshot(d)); * }); */ runReadOnlyAt(readTime: FirebaseFirestore.Timestamp, fn: (tx: FirebaseFirestore.Transaction, repo: ReadOnlyTransactionalRepository) => Promise): Promise; /** * Read a document inside a transaction. * * In a **read-write** transaction this takes a pessimistic lock (Firestore's default). In a * **read-only** / PITR transaction it is lock-free — locking is a property of the transaction * mode, not of this method. Uses `readCol()` so converters and the `id` overlay apply. * * @param tx - Firestore transaction object * @param id - Document ID * @returns Document or null if not found * * @example * await repo.runInTransaction(async (tx, repo) => { * const user = await repo.getInTransaction(tx, 'user-123'); * if (user) { * await repo.updateInTransaction(tx, user.id, { * loginCount: (user.loginCount || 0) + 1 * }); * } * }); */ getInTransaction(tx: FirebaseFirestore.Transaction, id: ID): Promise | null>; /** * Batched multi-document read inside a transaction via `tx.getAll`. * * Same positional / null-for-miss / field-mask / empty-input / duplicate-id contract as * {@link getMany}, but scoped to the transaction. In a **read-write** transaction this takes * pessimistic locks on **all** requested ids in one round trip; in a **read-only** / PITR * transaction it is lock-free. * * No `try/catch` here — matching {@link getInTransaction}. Transaction errors are parsed once by * {@link runInTransaction}'s own catch. * * ⚠ With a configured `readConverter`, `fromFirestore` receives the **masked** document when * `fieldMask` is supplied. A converter that dereferences an omitted field throws a raw * `TypeError` — see {@link getMany}. * * @param tx - Firestore transaction object * @param ids - Document ids to fetch (order preserved; duplicates allowed) * @param options - Optional `{ fieldMask }` projection (paths typed against the stored model `S`) * @returns Positional `(FirestoreDocument | null)[]` aligned with `ids` * @throws {InvalidDocumentIdError} If any id is not a single valid Firestore path segment * (validated before any I/O) * * @example * await userRepo.runInTransaction(async (tx, repo) => { * const [a, b] = await repo.getManyInTransaction(tx, ['a', 'b']); * if (a && b) { * await repo.updateInTransaction(tx, a.id, { linkedTo: b.id }); * } * }); */ getManyInTransaction(tx: FirebaseFirestore.Transaction, ids: ID[], options: { fieldMask: (FieldPaths> | FieldPath)[]; }): Promise<(FirestoreDocument> | null)[]>; getManyInTransaction(tx: FirebaseFirestore.Transaction, ids: ID[], options?: { fieldMask?: never; }): Promise<(FirestoreDocument | null)[]>; /** * Update a document within a transaction. * Supports dot notation for nested field updates. * Reads are optional in transactions, but callers may still use getInTransaction() * when business logic needs existing document state. * * @param tx - Firestore transaction object * @param id - Document ID * @param data - Partial data to update (supports dot notation) * A `lastUpdateTime` precondition may be supplied here too. A failed precondition does **not** * trigger a transaction retry — Firestore retries on contention, not on a rejected precondition — * so the callback runs exactly once and the whole transaction fails with * {@link PreconditionFailedError}. Inside a read-write transaction the transaction's own * pessimistic lock is usually the better tool; a precondition is for a token read *outside* the * transaction. * * @param options - Optional update behavior settings (`merge`, `lastUpdateTime`) * @throws {ValidationError} If validation fails * @throws {PreconditionFailedError} If `lastUpdateTime` no longer matches (transaction not retried) * * @example * await repo.runInTransaction(async (tx, repo) => { * const product = await repo.getInTransaction(tx, 'product-123'); * await repo.updateInTransaction(tx, 'product-123', { * stock: product.stock - quantity * }); * }); * * @example * // With dot notation in transaction * await repo.runInTransaction(async (tx, repo) => { * const user = await repo.getInTransaction(tx, 'user-123'); * await repo.updateInTransaction(tx, 'user-123', { * 'settings.notifications': true, * 'profile.lastLogin': new Date() * }); * }); * * @example * // Merge update in a transaction while preserving update semantics * await repo.runInTransaction(async (tx, transactionRepo) => { * await transactionRepo.updateInTransaction( * tx, * 'user-123', * { 'profile.nickname': 'Johnny' }, * { merge: true } * ); * }); */ updateInTransaction(tx: FirebaseFirestore.Transaction, id: ID, data: UpdateInput, options?: { merge?: boolean; lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise; /** * Convenience alias for merge-style transaction updates. * Equivalent to updateInTransaction(tx, id, data, { merge: true }). * * Accepts the same `lastUpdateTime` precondition, with the same no-retry behavior on failure. */ patchInTransaction(tx: FirebaseFirestore.Transaction, id: ID, data: UpdateInput, options?: { lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise; /** * Create a document within a transaction. * Must be used inside runInTransaction callback. * * Returns only `{ id }`: a transaction cannot read a document back after writing it (Firestore * requires all reads before writes and the write is not committed until the callback returns), so * there is no `returnDoc` option here. Read the document after the transaction completes if the * converted read model is needed. * * @param tx - Firestore transaction object * @param data - Document data * @returns `{ id }` — the generated document id * @throws {ValidationError} If validation fails * * @example * await repo.runInTransaction(async (tx, repo) => { * const { id } = await repo.createInTransaction(tx, { * userId: 'user-123', * total: 99.99, * status: 'pending' * }); * console.log('Order created:', id); * }); */ createInTransaction(tx: FirebaseFirestore.Transaction, data: CreateInput): Promise<{ id: ID; }>; /** * Create a document under a **caller-supplied id** within a transaction, failing if that id is * already taken. The transactional counterpart to {@link createWithId}. * * Returns only `{ id }` for the same reason as {@link createInTransaction}: a transaction cannot * read a document back after writing it, so there is no `returnDoc` option. * * A collision does **not** trigger a transaction retry. Firestore retries on contention, not on a * rejected create — the callback runs exactly once and the whole transaction fails with * {@link ConflictError}. Only `beforeCreate` fires; after-hooks never run inside a transaction * because the write is not committed until the callback returns (matching every other * `*InTransaction` helper). * * @param tx - Firestore transaction object * @param id - Document ID to claim * @param data - Document data * @returns `{ id }` — the caller-supplied document id * @throws {InvalidDocumentIdError} If the id is not a single valid Firestore path segment * @throws {ValidationError} If validation fails * @throws {ConflictError} If a document already exists at that id (raised when the transaction runs) * * @example * await repo.runInTransaction(async (tx, repo) => { * await repo.createWithIdInTransaction(tx, 'order-123', { * userId: 'user-123', * total: 99.99, * }); * }); */ createWithIdInTransaction(tx: FirebaseFirestore.Transaction, id: ID, data: CreateInput): Promise<{ id: ID; }>; /** * Delete a document within a transaction. * Must be used inside runInTransaction callback. * * Optionally guarded by a `lastUpdateTime` precondition. As with the transactional update, a * failed precondition fails the transaction outright rather than retrying it. Note this method's * own transactional existence read runs first, so a missing document still raises * {@link NotFoundError} regardless of any precondition. * * @param tx - Firestore transaction object * @param id - Document ID * @param options - `{ lastUpdateTime }` to delete only if the document is still at that version * @throws {NotFoundError} If document doesn't exist * @throws {PreconditionFailedError} If `lastUpdateTime` no longer matches (transaction not retried) * * @example * await repo.runInTransaction(async (tx, repo) => { * const item = await repo.getInTransaction(tx, 'item-123'); * if (item && item.quantity === 0) { * await repo.deleteInTransaction(tx, item.id); * } * }); */ deleteInTransaction(tx: FirebaseFirestore.Transaction, id: ID, options?: { lastUpdateTime?: FirebaseFirestore.Timestamp; }): Promise; } /** * Extracts a repository's **read data** type (`T`) — the application/read shape, with the synthetic * top-level `id` removed (review R5). Normalization is {@link OmitId}, not built-in `Omit<'id'>`: * `Omit` flattens an explicit-`id` + string-index intersection and loses declared siblings as typed * paths (issue #82). {@link OmitId} omits declared `id` from the path-facing key set while * reconstructing original index signatures, so a legacy/raw repository whose generic still carries * `id` is normalized without dropping value-position dynamic access. It is a no-op for validated * (schema-inferred) repositories that never declared `id`. A string index still makes value access * at `id` legal at the index value type — TypeScript cannot subtract one literal from a string * index domain — even though `id` is not a typed field path. */ export type DataOf = R extends FirestoreRepository ? OmitId : never; /** * Extracts a repository's **stored data** type (`S`) — the at-rest Firestore shape that query field * paths derive from, with the synthetic top-level `id` removed (review R5). Same {@link OmitId} * contract as {@link DataOf}: declared `id` is stripped from typed paths, original string/number * indexes are reconstructed for value-position access, and a string index still types `['id']` as * the index value rather than `never`. A no-op for validated repos whose stored generic never * declared `id`. */ export type StoredDataOf = R extends FirestoreRepository ? OmitId : never; /** * Extracts a repository's **document** result type — {@link FirestoreDocument}`>` (read * data plus the authoritative, read-only `id`). Name a returned document type without spelling the * repository generics. * * @example * const users = FirestoreRepository.withSchema(db, 'users', userSchema); * type User = DocumentOf; */ export type DocumentOf = R extends FirestoreRepository ? FirestoreDocument : never;