import { z } from 'zod'; import { FieldValue, UpdateData, WithFieldValue } from 'firebase-admin/firestore'; /** * The repository's schema bundle, parameterized by the **stored** (at-rest) type `S`. * * `S` exists so the constructor can *check* it: `RepositoryConstructorArgs` places this type in the * `schemas` slot, so a subclass whose `extends FirestoreRepository` clause contradicts * the `storedSchema` it passes fails to compile (ADR-0042). Zod 4 declares `ZodType` * covariantly, so the check rejects an unrelated or *wider* `S` — the unsound directions, which would * invent query field paths that do not exist at rest — and permits a narrower one, which is merely * under-permissive. Use the erased {@link RepositorySchemaSet} alias where the stored type is * irrelevant. */ export type RepositorySchemaSetFor = Readonly<{ read: z.ZodObject; create: z.ZodObject; update: z.ZodObject; /** * The **stored** (at-rest) shape that query field paths derive from — the fourth model of * ADR-0018. Set by `withSchema` / `subcollection` to the supplied `storedSchema`, or to the read * schema when none was given (the stored model defaults to the read model). * * Optional because the low-level constructor accepts a hand-rolled bundle, and because a * `Validator`'s own schema set describes only the write side. This is the runtime counterpart of * the repository's `S` generic, used by `collectionGroup()` to reject a stored shape that collides * with collection-group identity; `StoredDataOf` reads the same shape as a type off an * existing instance. The `& z.ZodType` half is what lets the constructor cross-check `S`. */ stored?: z.ZodObject & z.ZodType; }>; /** * Stored-shape-erased alias, and the public name. Kept so existing consumer annotations * (`RepositorySchemaSet`) continue to mean exactly what they meant before the `S` parameter existed. */ export type RepositorySchemaSet = RepositorySchemaSetFor; /** * Validates write payloads and carries the schema set. The repository models a **single write shape** * — `W`/`WO` serve both create and update — so the validator has two dimensions: `Input` is what a * caller passes (`z.input` of the write schema, pre-transform) and `Output` is the parsed result the * SDK persists and after-create hooks observe (`z.output`, transforms/coercions/defaults applied). * `parseCreate` returns the **exact** parsed create output (`CreateOutput`, no `WithFieldValue` * widening — a schema that genuinely emits a sentinel already types it in its output); `parseUpdate` * keeps the widened `UpdateInput` shape (dot-notation paths and `FieldValue` are legitimate on the * update path). Both default so `Validator` ≡ `Validator` — single-parameter references * remain valid. A custom update schema passed to `makeValidator` must be input/output-compatible with * the read/create schema (review S2); a type-divergent one is rejected at `makeValidator`, so every * produced validator is attachable to a `FirestoreRepository<…, W, …, WO>`. */ export type Validator = { parseCreate(input: CreateInput): CreateOutput; parseUpdate(input: UpdateInput): UpdateInput; schemas: RepositorySchemaSet; }; /** * Input accepted by create-family operations (`create`, `bulkCreate`, `upsert`, * `createInTransaction`). `id` is not a member: the repository sources the document id itself * (auto-generated on create, or the explicit `id` argument on `upsert`) and returns it as the * read-only `id` on the resulting {@link FirestoreDocument}. The distributive `Omit` defends the * contract even for a directly-typed (unvalidated) repository whose `T` happens to carry an `id`, * and keeps each branch of a union write model independently writable (ADR-0028). */ export type CreateInput = T extends unknown ? WithFieldValue> : never; /** * The parsed output of a create write — what the SDK persists and what after-create hooks observe. * Unlike {@link CreateInput}, this is the **exact** parsed shape with no `WithFieldValue` widening: * the value has already been validated/transformed, so a field is only `T | FieldValue` when its own * schema output type is (e.g. a `zSentinel`-annotated field). `id` is omitted; the repository * overlays the authoritative read-only `id` on the after-create payload. (review R4) */ export type CreateOutput = T extends unknown ? Omit : never; /** * Input accepted by update-family operations (`update`, `patch`, `bulkUpdate`, `bulkPatch`, * `updateInTransaction`, `patchInTransaction`, `query().update()`). * * Reuses the Admin SDK's `UpdateData`, which types Firestore dot-notation field paths (e.g. * `'address.city'`, `'profile.settings.theme'`) with the correct per-leaf value type and allows a * `FieldValue` sentinel at every level — so nested updates no longer need an `as any` cast. `id` is * omitted so it is never a writable top-level key (the repository sources the id from the document * ref / method argument and strips any `id` at runtime). */ export type UpdateInput = T extends unknown ? UpdateData> : never; /** * Controls how FieldValue sentinels are validated against a schema on write. * * - `'strict'` (default as of v3): the sentinel escape hatch is disabled. Only sentinels that a * field's schema explicitly permits (see {@link zNumberWrite}, {@link zArrayWrite}, * {@link zDateWrite}, {@link withDelete}, {@link zSentinel}) pass; every other Zod failure * throws. Because parsing succeeds normally, the full Zod output — coercions, defaults, unknown-key * stripping, and transforms — is always returned. * - `'permissive'` (opt-in; the pre-v3 default): when Zod validation fails only at paths that hold a * sentinel, the errors are waived and the **raw input** is written verbatim. This discards every * successful Zod coercion/default/transform elsewhere in the same payload, so prefer `'strict'` * with the write combinators and enable this only as a migration shim. */ export type SentinelPolicy = 'permissive' | 'strict'; /** * A classified Firestore write sentinel kind. `'unknown'` means the value is a sentinel we * could not classify (or is not a sentinel at all). */ export type FieldValueKind = 'delete' | 'serverTimestamp' | 'arrayUnion' | 'arrayRemove' | 'increment' | 'vector' | 'unknown'; type PathSegment = string | number; type Path = PathSegment[]; /** * Checks whether a value is a Firestore FieldValue sentinel instance. * * FlintFire targets the firebase-admin SDK, so detection relies on the exported * `FieldValue` class identity (`instanceof`) plus a structural check for `VectorValue` * (which is a standalone class, not a `FieldValue` subclass). Web-SDK / dual-package * structural detection is intentionally out of scope. */ export declare function isFieldValueSentinel(value: unknown): boolean; /** * Classifies a Firestore write sentinel into its {@link FieldValueKind}. * * Admin-native and minimal: every admin sentinel subclasses the exported `FieldValue` and * exposes a stable `methodName` getter (e.g. `"FieldValue.increment"`), so classification * reads that getter. `methodName` is preferred over `constructor.name` because it survives * minification and cleanly distinguishes `arrayUnion` from `arrayRemove`. */ export declare function whichFieldValue(value: unknown): FieldValueKind; /** * Recursively collects all object paths where a FieldValue sentinel is present. */ export declare function collectSentinelPaths(input: unknown, basePath?: Path): Path[]; /** * Collects every path in a write payload that holds a `FieldValue.delete()` sentinel. * * Firestore honors a delete sentinel only on update-like writes (`update()`, or * `set(..., { merge: true })`) — never on a plain `create`/`set`. Create chokepoints use this to * reject a delete sentinel *before* any I/O, so the failure is fast, consistent, and specific * instead of a confusing commit-time error whose outcome (for `upsert`) would otherwise depend on * whether the document already exists (ADR-0019). The other sentinel kinds (`increment`, * `arrayUnion`, `arrayRemove`, `serverTimestamp`) are accepted by the backend on `set`/`create` and * are intentionally left untouched. Reuses {@link collectSentinelPaths} to locate sentinels, then * keeps only those {@link whichFieldValue} classifies as `'delete'`. */ export declare function collectDeleteSentinelPaths(input: unknown): Path[]; /** * A Zod schema matching a Firestore sentinel of one of the given {@link FieldValueKind}s. * Use it to widen a field schema so it also accepts specific approved sentinels, e.g. * `z.union([z.string(), zSentinel('serverTimestamp')])`. */ export declare function zSentinel(...kinds: FieldValueKind[]): z.ZodType; /** * Write schema for a number field that may also be written with `FieldValue.increment()` * (and optionally `FieldValue.delete()`). */ export declare function zNumberWrite(opts?: { allowDelete?: boolean; }): z.ZodUnion>]>; /** * Write schema for an array field that may also be written with `FieldValue.arrayUnion()` / * `FieldValue.arrayRemove()` (and optionally `FieldValue.delete()`). */ export declare function zArrayWrite(elem: T, opts?: { allowDelete?: boolean; }): z.ZodUnion, z.ZodType>]>; /** * Write schema for a Date field that may also be written with `FieldValue.serverTimestamp()` * (and optionally `FieldValue.delete()`). For fields stored as ISO strings, compose the base * type with `zSentinel('serverTimestamp')` directly. */ export declare function zDateWrite(opts?: { allowDelete?: boolean; }): z.ZodUnion>]>; /** * Widens any field schema so it additionally accepts `FieldValue.delete()` — useful for * updates / merges that clear a field. */ export declare function withDelete(schema: T): z.ZodUnion>]>; /** * The outcome of resolving a dot-notation path against a schema: * - `leaf`: the path resolves to a concrete field schema — validate the value against it. * - `passthrough`: the path descends into a dynamic container (`z.record` / `z.map` / `z.any` / * `z.unknown`, or a loose/`catchall` object) that accepts arbitrary keys, so it cannot be * validated against a fixed shape and is written as-is. * - `unknown`: a segment is definitively absent from a known object shape, or descends into a scalar * or array that has no addressable subfields — the path is invalid, so the write must fail loud. */ export type PathResolution = { kind: 'leaf'; schema: z.ZodType; } | { kind: 'passthrough'; } | { kind: 'unknown'; }; /** * Resolves the Zod schema governing a dot-notation field path (e.g. `['address', 'city']`) by * walking nested object shapes. See {@link PathResolution} for the outcomes. */ export declare function resolveSchemaAtPath(root: z.ZodType, segments: string[]): PathResolution; /** * Constrains a custom update schema `U` so the validator it produces is HONEST against the single * write shape the repository assigns to updates (review S2/T1). The repository types every update * method from the create/read write shape and, at runtime, validates against `U` and writes the * parsed result. Both directions must hold: * * - **Input** — the shared declared input must be able to inhabit `U` * (`z.input` assignable to `z.input`), so a value the update method's type accepts is not * categorically rejected by the runtime schema. Without this, an input-divergent schema (create * input `number`, update input `string`) attaches but contradicts itself: `update({ score: 7 })` * type-checks yet throws, while the string the schema really wants is a compile error (T1). * - **Output** — `U`'s parsed output must be assignable to the create output, **per field and * allowing omission** (updates are inherently partial; restricting updatable fields via `.pick` is * supported). * * `.pick(...)` (narrower fields) and coercions like `z.coerce.number()` (input broad enough to accept * the shared numeric input, output still `number`) satisfy both; `z.string().transform(Number)` over * a numeric create schema is rejected (its input `string` cannot accept the shared `number`), even * though its output happens to be numeric. A rejected schema collapses `U` to `never`, a compile * error at `makeValidator`. * * Note: an update schema that WIDENS a field's output (e.g. `withDelete`/`zNumberWrite` to allow a * `FieldValue` sentinel on the update path only) is also rejected (output not assignable to the * narrower create output). Put the combinator on the shared write schema — the derived * `create.partial()` update inherits it — rather than only on a custom update schema. */ type UpdateCompatible, U extends z.ZodObject> = [ z.input ] extends [z.input] ? [z.output] extends [Partial>] ? U : never : never; export declare function makeValidator, U extends z.ZodObject = T>(readSchema: T, updateSchema?: UpdateCompatible, opts?: { sentinelPolicy?: SentinelPolicy; }): Validator, z.output>; export {};