@sanity-labs/client-fake-for-test 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -35,6 +35,32 @@ export declare function applyPerspective(
35
35
  perspective: Perspective,
36
36
  ): SanityDocument[];
37
37
 
38
+ /**
39
+ * One recorded invocation of a client method — the spy layer behind
40
+ * `client.calls()` / `client.callCount()`. `result` holds the resolved
41
+ * value (awaited, for async methods); `error` holds the thrown/rejected
42
+ * value. Builder-returning methods (`patch`, `transaction`) record the
43
+ * builder as `result`; their eventual writes show up in the mutation log.
44
+ */
45
+ export declare interface CallRecord {
46
+ /** Method name; namespace methods are dotted, e.g. `releases.create`. */
47
+ method: string;
48
+ /** Arguments as passed (stored by reference, like `vi.fn`). */
49
+ args: unknown[];
50
+ /** Resolved/returned value, set once the call settles successfully. */
51
+ result?: unknown;
52
+ /** Thrown or rejected value, set if the call failed. */
53
+ error?: unknown;
54
+ projectId: string;
55
+ dataset: string;
56
+ }
57
+
58
+ /** Outcome of a recorded call, reported once a (possibly async) result is known. */
59
+ export declare type CallSettler = (outcome: {
60
+ result?: unknown;
61
+ error?: unknown;
62
+ }) => void;
63
+
38
64
  export declare function createPatch(
39
65
  documentId: string,
40
66
  executor: PatchExecutor,
@@ -84,6 +110,15 @@ export declare interface CreateTestClientOptions {
84
110
  * unconditionally — the legacy behavior.
85
111
  */
86
112
  accessControl?: TestClientAccessControl;
113
+ /**
114
+ * Pluggable write interceptor — runs on each write through the document
115
+ * mutation API (create/patch/delete/transaction; not the release/version
116
+ * action API) before the store changes, and may throw to reject it. The
117
+ * client has no opinion about the policy; callers (e.g. a workflow test bench
118
+ * enforcing lake mutation guards) supply it. Inherited by `withConfig`
119
+ * siblings. See {@link MutationGuard}.
120
+ */
121
+ mutationGuard?: MutationGuard;
87
122
  /**
88
123
  * Default perspective applied to reads. Per-fetch `options.perspective`
89
124
  * overrides this. `withConfig({ perspective })` returns a sibling
@@ -142,6 +177,19 @@ export declare interface DocumentBody {
142
177
 
143
178
  export declare type DocumentValuePermission = "create" | "read" | "update";
144
179
 
180
+ /**
181
+ * Error helpers shared across the fake.
182
+ *
183
+ * Every error the fake throws is prefixed with {@link ERR_PREFIX} so it's
184
+ * unmistakably attributable to *this fake* — not to `@sanity/client`,
185
+ * groq-js, or the code under test — and carries enough context to fix
186
+ * the problem without reading the fake's source. Short, bare messages
187
+ * ("not found", "invalid id") are a poor developer experience in a test
188
+ * double: prefer stating what happened, the offending value, and what to
189
+ * do about it.
190
+ */
191
+ export declare const ERR_PREFIX = "[client-fake-for-test]";
192
+
145
193
  /**
146
194
  * Resolve whether `grants` allow `permission` on `document` for the
147
195
  * given user. Same logic the engine uses in `permissions.grantsPermissionOn`
@@ -163,6 +211,47 @@ export declare function evaluateWriteAccess(args: {
163
211
  matchingGrants: number;
164
212
  }>;
165
213
 
214
+ /** Build a prefixed Error. Pass a fully-formed, dev-facing message. */
215
+ export declare function fakeError(message: string): Error;
216
+
217
+ /**
218
+ * A single mutation in the raw array form accepted by `mutate()` — the
219
+ * same shape `@sanity/client` accepts. The inline `patch` form mirrors
220
+ * the real client's keyed patch object.
221
+ */
222
+ export declare type FakeMutation =
223
+ | {
224
+ create: SanityDocumentLike;
225
+ }
226
+ | {
227
+ createOrReplace: SanityDocumentLike;
228
+ }
229
+ | {
230
+ createIfNotExists: SanityDocumentLike;
231
+ }
232
+ | {
233
+ delete: {
234
+ id: string;
235
+ };
236
+ }
237
+ | {
238
+ patch: {
239
+ id: string;
240
+ ifRevisionID?: string;
241
+ set?: Record<string, unknown>;
242
+ setIfMissing?: Record<string, unknown>;
243
+ unset?: string[];
244
+ inc?: Record<string, number>;
245
+ dec?: Record<string, number>;
246
+ insert?: {
247
+ before?: string;
248
+ after?: string;
249
+ replace?: string;
250
+ items: unknown[];
251
+ };
252
+ };
253
+ };
254
+
166
255
  /**
167
256
  * Data-plane subset of `@sanity/client`'s surface, with multi-dataset support.
168
257
  *
@@ -188,6 +277,21 @@ export declare function evaluateWriteAccess(args: {
188
277
  export declare interface FetchOptions {
189
278
  /** Override the client's configured perspective for this read. */
190
279
  perspective?: Perspective;
280
+ /**
281
+ * When `false`, resolve to a {@link RawQueryResponse} (`{ query, ms,
282
+ * result }`) instead of the bare result — mirrors `@sanity/client`.
283
+ * Defaults to `true`.
284
+ */
285
+ filterResponse?: boolean;
286
+ /**
287
+ * With `filterResponse: false`, set to `false` to omit `query` from the
288
+ * raw response. Ignored when `filterResponse` is not `false`.
289
+ */
290
+ returnQuery?: boolean;
291
+ /** Accepted for signature parity; not simulated. */
292
+ tag?: string;
293
+ /** Accepted for signature parity; not simulated. */
294
+ signal?: AbortSignal;
191
295
  }
192
296
 
193
297
  export declare interface Grant {
@@ -195,6 +299,27 @@ export declare interface Grant {
195
299
  permissions: DocumentValuePermission[];
196
300
  }
197
301
 
302
+ export declare interface GuardConfig {
303
+ /**
304
+ * Resolve a registered stub for an unimplemented member, or `undefined`.
305
+ * Checked only for members the client doesn't already implement, so
306
+ * stubs fill gaps without shadowing core behaviour.
307
+ */
308
+ getStub: (name: string) => unknown;
309
+ /**
310
+ * Called synchronously when a recorded method is invoked, with the
311
+ * method name and its arguments. Returns a settler the wrapper invokes
312
+ * once the result (or rejection) is known. Omit to disable recording.
313
+ */
314
+ onCall?: (method: string, args: unknown[]) => CallSettler;
315
+ /**
316
+ * Top-level member names whose calls are recorded via `onCall`. A
317
+ * recorded member that resolves to a namespace object (e.g. `releases`)
318
+ * has each of its methods recorded as `name.method`.
319
+ */
320
+ recorded?: Set<string>;
321
+ }
322
+
198
323
  export declare const isDraftId: (id: string) => boolean;
199
324
 
200
325
  export declare const isReleaseDocId: (id: string) => boolean;
@@ -203,8 +328,103 @@ export declare const isSystemId: (id: string) => boolean;
203
328
 
204
329
  export declare const isVersionId: (id: string) => boolean;
205
330
 
331
+ /** Result of a mutation when ids are requested for all affected documents. */
332
+ export declare interface MultipleMutationResult {
333
+ transactionId: string;
334
+ documentIds: string[];
335
+ results: {
336
+ id: string;
337
+ operation: MutationOperation;
338
+ }[];
339
+ }
340
+
341
+ /**
342
+ * A pluggable write interceptor, configured via
343
+ * `createTestClient({ mutationGuard })`. It runs on each write through the
344
+ * document mutation API — `create` / `createOrReplace` / `createIfNotExists` /
345
+ * `patch` / `delete` and the equivalent `transaction()` operations — before the
346
+ * store changes; **throw to reject the write** (the throw propagates out of the
347
+ * client call, exactly as a real lake rejection would). The release/version
348
+ * action API (`client.action`, `client.releases.*`, `createVersion`) is **not**
349
+ * intercepted.
350
+ *
351
+ * The client itself has no opinion about *what* a guard is — it only provides
352
+ * the seam and the before/after/identity context. Callers (e.g. a workflow test
353
+ * bench) supply the policy: evaluate lake mutation guards, enforce field locks,
354
+ * etc. Keeping the policy in the caller avoids duplicating guard-evaluation
355
+ * logic the client has no business owning.
356
+ */
357
+ export declare type MutationGuard = (
358
+ context: MutationGuardContext,
359
+ ) => void | Promise<void>;
360
+
361
+ /** The kind of write a {@link MutationGuard} is asked to vet. */
362
+ export declare type MutationGuardAction = "create" | "update" | "delete";
363
+
364
+ /**
365
+ * The before/after image of a single document write, handed to a
366
+ * {@link MutationGuard} before it is applied.
367
+ *
368
+ * - `before` is null on create; `after` is null on delete.
369
+ * - `identity` is the acting user — the id bound to the client's token
370
+ * (its `accessControl.currentUser`), or undefined when the client has no
371
+ * identity configured.
372
+ *
373
+ * Treat `before`/`after` as read-only — they are the live store images, not
374
+ * copies; a guard that mutates them corrupts the store.
375
+ */
376
+ export declare interface MutationGuardContext {
377
+ action: MutationGuardAction;
378
+ before:
379
+ | (SanityDocumentLike & {
380
+ _id: string;
381
+ _type: string;
382
+ })
383
+ | null;
384
+ after:
385
+ | (SanityDocumentLike & {
386
+ _id: string;
387
+ _type: string;
388
+ })
389
+ | null;
390
+ identity: string | undefined;
391
+ }
392
+
393
+ /** Append-only record of one committed transaction (a single mutation is a 1-entry transaction). */
394
+ export declare interface MutationLogEntry {
395
+ transactionId: string;
396
+ projectId: string;
397
+ dataset: string;
398
+ mutations: TxnMutation[];
399
+ }
400
+
401
+ /** The operation recorded per affected document, matching `@sanity/client`. */
402
+ export declare type MutationOperation = "create" | "update" | "delete" | "none";
403
+
206
404
  export declare interface MutationOptions {
207
405
  ifRevisionId?: string;
406
+ /**
407
+ * Shape the resolved value, mirroring `@sanity/client`:
408
+ * - default → the mutated document
409
+ * - `returnDocuments: false` → an id-shaped mutation result
410
+ * ({@link SingleMutationResult} / {@link MultipleMutationResult})
411
+ * - `returnFirst: false` with documents → an array
412
+ *
413
+ * The static return type reflects the default (the document); pass a
414
+ * type argument or cast when requesting an id-shaped result.
415
+ */
416
+ returnDocuments?: boolean;
417
+ returnFirst?: boolean;
418
+ /** Override the synthetic transaction id used in the result and log. */
419
+ transactionId?: string;
420
+ /** When `true`, validate + shape the result but don't persist. */
421
+ dryRun?: boolean;
422
+ /** Accepted for signature parity; not simulated. */
423
+ visibility?: "sync" | "async" | "deferred";
424
+ /** Accepted for signature parity; not simulated. */
425
+ autoGenerateArrayKeys?: boolean;
426
+ /** Accepted for signature parity; not simulated. */
427
+ tag?: string;
208
428
  }
209
429
 
210
430
  export declare interface PatchExecutor {
@@ -275,6 +495,17 @@ export declare type Perspective = "raw" | "published" | "drafts" | string[];
275
495
  /** Strip `drafts.` / `versions.<name>.` prefix to recover the published id. */
276
496
  export declare function publishedIdOf(id: string): string;
277
497
 
498
+ /**
499
+ * Shape returned by `fetch` when `filterResponse: false`. Matches
500
+ * `@sanity/client`'s `RawQueryResponse`. `query` is omitted when the
501
+ * caller also passes `returnQuery: false`.
502
+ */
503
+ export declare interface RawQueryResponse<R> {
504
+ query?: string;
505
+ ms: number;
506
+ result: R;
507
+ }
508
+
278
509
  export declare type ReleaseAction =
279
510
  | {
280
511
  actionType: "sanity.action.release.create";
@@ -400,6 +631,37 @@ declare interface SanityDocumentLike {
400
631
  [key: string]: unknown;
401
632
  }
402
633
 
634
+ /** Result of a mutation when `returnFirst` resolves true and ids are requested. */
635
+ export declare interface SingleMutationResult {
636
+ transactionId: string;
637
+ documentId: string;
638
+ results: {
639
+ id: string;
640
+ operation: MutationOperation;
641
+ }[];
642
+ }
643
+
644
+ /** Members this fake actually implements — surfaced in error messages. */
645
+ export declare const SUPPORTED_SURFACE: readonly [
646
+ "fetch",
647
+ "getDocument",
648
+ "getDocuments",
649
+ "create",
650
+ "createOrReplace",
651
+ "createIfNotExists",
652
+ "delete",
653
+ "patch",
654
+ "transaction",
655
+ "mutate",
656
+ "action",
657
+ "releases",
658
+ "createVersion",
659
+ "unpublishVersion",
660
+ "request (only with accessControl)",
661
+ "config",
662
+ "withConfig",
663
+ ];
664
+
403
665
  export declare interface SystemFields {
404
666
  _rev: string;
405
667
  _createdAt: string;
@@ -415,7 +677,7 @@ export declare interface TestClient {
415
677
  getDocument: <T = SanityDocument>(
416
678
  id: string,
417
679
  options?: FetchOptions,
418
- ) => Promise<T | null>;
680
+ ) => Promise<T | undefined>;
419
681
  getDocuments: <T = SanityDocument>(
420
682
  ids: string[],
421
683
  options?: FetchOptions,
@@ -458,6 +720,17 @@ export declare interface TestClient {
458
720
  } | null>;
459
721
  patch: (documentId: string) => PatchHandle;
460
722
  transaction: () => TransactionHandle;
723
+ /**
724
+ * Apply a batch of mutations in the raw array form (or a `patch()` /
725
+ * `transaction()` builder) — mirrors `@sanity/client`'s `mutate()`.
726
+ * Atomic: any failure rolls the whole batch back. The resolved shape
727
+ * follows `options.returnDocuments` / `returnFirst` exactly like the
728
+ * real client (default → {@link MultipleMutationResult}).
729
+ */
730
+ mutate: (
731
+ operations: FakeMutation[] | PatchHandle | TransactionHandle,
732
+ options?: TxnCommitOptions,
733
+ ) => Promise<TxnCommitResult>;
461
734
  /**
462
735
  * Dispatch one or more release / version actions against the store.
463
736
  * Returns a synthetic `transactionId`. Multi-action arrays are applied
@@ -494,6 +767,12 @@ export declare interface TestClient {
494
767
  projectId: string;
495
768
  dataset: string;
496
769
  perspective: Perspective;
770
+ /**
771
+ * Rebind the acting identity (and its grants) on a sibling that shares
772
+ * the same store — the test analogue of a token-scoped client. Lets two
773
+ * actors write the same dataset, e.g. for `identity()`-based guards.
774
+ */
775
+ accessControl: TestClientAccessControl;
497
776
  }>,
498
777
  ) => TestClient;
499
778
  /** Replace the current dataset with the given documents. */
@@ -511,6 +790,46 @@ export declare interface TestClient {
511
790
  projectId: string;
512
791
  dataset: string;
513
792
  }[];
793
+ /**
794
+ * Register a handler for a `@sanity/client` member the fake doesn't
795
+ * implement (e.g. `listen`, `assets`). Accessing that member on the
796
+ * client then returns the handler instead of throwing the
797
+ * "not implemented" guard error. Shared across sibling `withConfig`
798
+ * handles. Stubs fill gaps only — they don't shadow implemented methods.
799
+ */
800
+ stub: (name: string, handler: unknown) => void;
801
+ /** The currently-registered stubs, keyed by member name. */
802
+ stubs: () => Record<string, unknown>;
803
+ /**
804
+ * Every mutation committed through this client's registry, flattened
805
+ * and in order — `create` / `createOrReplace` / `createIfNotExists` /
806
+ * `delete` / `patch`, whether issued directly, via `transaction()`, or
807
+ * via `mutate()`. The spy hook for "assert exactly what writes my code
808
+ * submitted".
809
+ */
810
+ mutations: () => TxnMutation[];
811
+ /**
812
+ * Every committed transaction, in order. A direct mutation is recorded
813
+ * as a one-mutation transaction. Each entry carries its synthetic
814
+ * `transactionId` and the `(projectId, dataset)` it targeted.
815
+ */
816
+ transactions: () => MutationLogEntry[];
817
+ /** Clear the recorded mutation / transaction log. */
818
+ clearLog: () => void;
819
+ /**
820
+ * Every recorded method call, in order — the spy layer for "was `fetch`
821
+ * called, how many times, and with what params". Records the
822
+ * `@sanity/client`-surface methods (`fetch`, `getDocument`, `create`,
823
+ * `patch`, `mutate`, `releases.*`, …), not the test-only helpers.
824
+ * Pass a method name to filter (e.g. `calls("fetch")`); namespace
825
+ * methods are dotted (`calls("releases.create")`). Shared across
826
+ * `withConfig` siblings.
827
+ */
828
+ calls: (method?: string) => CallRecord[];
829
+ /** Number of recorded calls, optionally filtered by method name. */
830
+ callCount: (method?: string) => number;
831
+ /** Clear the recorded call log. */
832
+ clearCalls: () => void;
514
833
  }
515
834
 
516
835
  export declare interface TestClientAccessControl {
@@ -569,20 +888,22 @@ export declare interface TransactionHandle {
569
888
  }
570
889
 
571
890
  export declare interface TxnCommitOptions {
572
- /** If true, returns the resulting documents instead of just ids. */
891
+ /**
892
+ * Shape the resolved value (mirrors `@sanity/client`):
893
+ * - default (both unset) → {@link MultipleMutationResult}
894
+ * - `returnDocuments: true` → the resulting document(s)
895
+ * - `returnFirst: true` with `returnDocuments` → a single document
896
+ * - `returnDocuments: false` → an id-shaped mutation result
897
+ */
573
898
  returnDocuments?: boolean;
574
- /** With `returnDocuments`, return only the first updated doc. */
575
899
  returnFirst?: boolean;
900
+ /** Override the synthetic transaction id (mirrors `client.transaction(undefined, { transactionId })`). */
901
+ transactionId?: string;
576
902
  }
577
903
 
578
904
  export declare type TxnCommitResult =
579
- | {
580
- transactionId: string;
581
- results: {
582
- id: string;
583
- operation: "create" | "update" | "delete";
584
- }[];
585
- }
905
+ | MultipleMutationResult
906
+ | SingleMutationResult
586
907
  | SanityDocument
587
908
  | SanityDocument[];
588
909
 
@@ -624,6 +945,20 @@ export declare type TxnMutation =
624
945
  ifRev?: string;
625
946
  };
626
947
 
948
+ /**
949
+ * Curated map of real `@sanity/client` members the fake deliberately omits.
950
+ * Keyed by the top-level property name; nested access (e.g.
951
+ * `assets.upload`) is reported with the full dotted path.
952
+ */
953
+ export declare const UNSUPPORTED_MEMBERS: Record<string, UnsupportedEntry>;
954
+
955
+ declare interface UnsupportedEntry {
956
+ /** What the real member is. */
957
+ what: string;
958
+ /** What to do instead. */
959
+ workaround: string;
960
+ }
961
+
627
962
  export declare type VersionAction =
628
963
  | {
629
964
  actionType: "sanity.action.document.version.create";
@@ -645,6 +980,18 @@ export declare type VersionAction =
645
980
  publishedId: string;
646
981
  };
647
982
 
983
+ /**
984
+ * Wrap a client object so unimplemented members fail informatively,
985
+ * registered stubs are served, and recorded methods report their calls.
986
+ *
987
+ * @param client - the fully-built client object (plain literal).
988
+ * @param config - stub resolver plus optional call-recording hooks.
989
+ */
990
+ export declare function wrapWithGuards<T extends object>(
991
+ client: T,
992
+ config: GuardConfig,
993
+ ): T;
994
+
648
995
  /**
649
996
  * Sanity-style 403 raised when a configured-grants check rejects a
650
997
  * write. The thrown object carries the doc id, the attempted