@sanity-labs/client-fake-for-test 0.31.0 → 0.32.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/README.md CHANGED
@@ -48,7 +48,8 @@ const approved = await client.fetch<{ _id: string }[]>(
48
48
  await client.patch("article-1").set({ state: "approved" }).commit();
49
49
 
50
50
  // transaction — atomic batch
51
- await client.transaction()
51
+ await client
52
+ .transaction()
52
53
  .patch("article-1", (p) => p.set({ reviewedBy: "alice" }))
53
54
  .patch("article-2", (p) => p.set({ reviewedBy: "alice" }))
54
55
  .commit();
@@ -65,36 +66,36 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
65
66
 
66
67
  ### Supported
67
68
 
68
- | Area | Method | Notes |
69
- | --- | --- | --- |
70
- | Read | `fetch<T>(query, params?, { filterResponse?, returnQuery? })` | GROQ via groq-js. `filterResponse: false` → `{ result, ms, query }` (`RawQueryResponse`), like the real client |
71
- | Read | `getDocument<T>(id)` | Returns `undefined` if missing (or hidden by ACL) — matches `@sanity/client` |
72
- | Read | `getDocuments<T>(ids)` | Element-wise `null` for missing |
73
- | Write | `create(doc, options?)` | Throws if `_id` already exists |
74
- | Write | `createOrReplace(doc, options?)` | Upsert |
75
- | Write | `createIfNotExists(doc, options?)` | No-op if `_id` exists |
76
- | Write | `delete(id, options?)` | Default `{ _id }` or `null`; id/array shapes via options |
77
- | Mutate | `mutate(operations, options?)` | Raw mutation array (`{create}`/`{patch}`/`{delete}`/…), or a `patch()` / `transaction()` builder. Atomic |
78
- | Patch | `patch(id)` chain → `.commit()` | Ops: `.set`, `.setIfMissing`, `.unset`, `.inc`, `.dec`, `.insert(position, anchor, items)`, `.ifRevisionId` |
79
- | Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
80
- | Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
81
- | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
82
- | Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname, apiHost, apiVersion, useCdn }`. `apiHost` (default `https://api.sanity.io`), `apiVersion` (default `"1"`, a leading `v` dropped) and `useCdn` (default `true`) are taken as `createTestClient` and `withConfig` options and only decide the URL an error names (see [Errors are `ClientError`s](#errors-are-clienterrors)). `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
83
- | Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
84
- | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname?, apiHost?, apiVersion?, useCdn? })` | Sibling handle into the same multi-resource registry; `resource` points it at a Media Library, Canvas, dashboard or dataset (see [Resource types](#resource-types-media-library-canvas-dashboard)); `token` binds a registered identity (see the token→identity registry below), `accessControl` rebinds it inline — the two are mutually exclusive; `useProjectHostname: false` mints a global-hosted sibling |
85
- | Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection |
86
- | HTTP | `request({ url? \| uri?, method?, body?, headers?, query? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)), and `POST /functions/<idOrName>/invoke` (see [Functions](#functions)). Calling it without one throws a guidance error. |
69
+ | Area | Method | Notes |
70
+ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
71
+ | Read | `fetch<T>(query, params?, { filterResponse?, returnQuery? })` | GROQ via groq-js. `filterResponse: false` → `{ result, ms, query }` (`RawQueryResponse`), like the real client |
72
+ | Read | `getDocument<T>(id)` | Returns `undefined` if missing (or hidden by ACL) — matches `@sanity/client` |
73
+ | Read | `getDocuments<T>(ids)` | Element-wise `null` for missing |
74
+ | Write | `create(doc, options?)` | Throws if `_id` already exists |
75
+ | Write | `createOrReplace(doc, options?)` | Upsert |
76
+ | Write | `createIfNotExists(doc, options?)` | No-op if `_id` exists |
77
+ | Write | `delete(id, options?)` | Default `{ _id }` or `null`; id/array shapes via options |
78
+ | Mutate | `mutate(operations, options?)` | Raw mutation array (`{create}`/`{patch}`/`{delete}`/…), or a `patch()` / `transaction()` builder. Atomic |
79
+ | Patch | `patch(id)` chain → `.commit()` | Ops: `.set`, `.setIfMissing`, `.unset`, `.inc`, `.dec`, `.insert(position, anchor, items)`, `.ifRevisionId` |
80
+ | Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
81
+ | Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
82
+ | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
83
+ | Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname, apiHost, apiVersion, useCdn }`. `apiHost` (default `https://api.sanity.io`), `apiVersion` (default `"1"`, a leading `v` dropped) and `useCdn` (default `true`) are taken as `createTestClient` and `withConfig` options and only decide the URL an error names (see [Errors are `ClientError`s](#errors-are-clienterrors)). `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
84
+ | Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
85
+ | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname?, apiHost?, apiVersion?, useCdn? })` | Sibling handle into the same multi-resource registry; `resource` points it at a Media Library, Canvas, dashboard or dataset (see [Resource types](#resource-types-media-library-canvas-dashboard)); `token` binds a registered identity (see the token→identity registry below), `accessControl` rebinds it inline — the two are mutually exclusive; `useProjectHostname: false` mints a global-hosted sibling |
86
+ | Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection |
87
+ | HTTP | `request({ url? \| uri?, method?, body?, headers?, query? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)), and `POST /functions/<idOrName>/invoke` (see [Functions](#functions)). Calling it without one throws a guidance error. |
87
88
 
88
89
  #### Mutation return shapes
89
90
 
90
91
  `create` / `createOrReplace` / `createIfNotExists` / `delete` / `mutate` / `transaction().commit()` honor `returnDocuments` / `returnFirst`, mirroring `@sanity/client`:
91
92
 
92
- | `returnDocuments` | `returnFirst` | Resolves to |
93
- | --- | --- | --- |
94
- | (default for create-family) | | the mutated document |
95
- | `true` | `false` | `SanityDocument[]` |
96
- | `false` | `true` (or default) | `SingleMutationResult` `{ transactionId, documentId, results }` |
97
- | `false` | `false` (default for `transaction` / `mutate`) | `MultipleMutationResult` `{ transactionId, documentIds, results }` |
93
+ | `returnDocuments` | `returnFirst` | Resolves to |
94
+ | --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------ |
95
+ | (default for create-family) | | the mutated document |
96
+ | `true` | `false` | `SanityDocument[]` |
97
+ | `false` | `true` (or default) | `SingleMutationResult` `{ transactionId, documentId, results }` |
98
+ | `false` | `false` (default for `transaction` / `mutate`) | `MultipleMutationResult` `{ transactionId, documentIds, results }` |
98
99
 
99
100
  > [!NOTE]
100
101
  > The static return type of `create` / `delete` reflects the **default** shape (the document / `{ _id } | null`). When you pass `returnDocuments: false` to get an id-shaped result, supply a type argument or cast — the runtime value is correct either way.
@@ -190,15 +191,15 @@ A bearer that is not a registered identity, has a JWT's three segments and verif
190
191
 
191
192
  The Content Lake refuses the token on every request it serves (queries, documents, mutations, actions, the History API), as gradient does (`pkg/server/httpapi/middlewares/sessions/session.go`), each as a `PlatformHttpError`:
192
193
 
193
- | Token | Answer |
194
- | --- | --- |
195
- | Signed by another key | 400 `{ error: { type: "httpBadRequest", description: 'invalid JWT token "<token>": crypto/rsa: verification error' } }` |
196
- | `alg` other than `RS256` | 400, `invalid JWT token "<token>": token uses algorithm "<alg>", expected "RS256"` |
197
- | A segment that is not base64url | 400, `invalid JWT token "<token>": illegal base64 data at input byte <n>` |
198
- | A grant the Content Lake cannot parse | 400, the grant's own `description` (no `invalid JWT token` prefix) |
194
+ | Token | Answer |
195
+ | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
196
+ | Signed by another key | 400 `{ error: { type: "httpBadRequest", description: 'invalid JWT token "<token>": crypto/rsa: verification error' } }` |
197
+ | `alg` other than `RS256` | 400, `invalid JWT token "<token>": token uses algorithm "<alg>", expected "RS256"` |
198
+ | A segment that is not base64url | 400, `invalid JWT token "<token>": illegal base64 data at input byte <n>` |
199
+ | A grant the Content Lake cannot parse | 400, the grant's own `description` (no `invalid JWT token` prefix) |
199
200
  | `x` that is not an int64 (`1.0`, `4.1e9`, over 2^63 - 1) | 400, `invalid expiry: expected int64: strconv.ParseInt: parsing "<x>": <reason>` (`invalid syntax` / `value out of range`) |
200
- | `i` that is not a string | 400, `token field "i" must be a string` |
201
- | `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
201
+ | `i` that is not a string | 400, `token field "i" must be a string` |
202
+ | `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
202
203
 
203
204
  A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake models that only for the [organization store lookup](#organization-stores), so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. A token with claims the Content Lake reads but the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`) binds, and throws a fake error on a Content Lake request instead of a guessed answer; `exp`, `iat`, `nbf` or a claims segment that is not a JSON object throw when the token binds. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
204
205
 
@@ -240,13 +241,13 @@ await client.request({ uri: "/internal/organization-stores", query: { organizati
240
241
 
241
242
  The first lookup for an organization without a store creates one `provisioning`, as populus does, and every later lookup answers the same store. In populus a background workflow then sets it `active`; in the fake `client.completeOrganizationStoreProvisioning("oAbc")` stands for that workflow finishing, and the next lookup answers `active`. A store whose provisioning never completes stays `provisioning`. The id is `os` and ten characters, derived from the organization id, so the same organization always gets the same id. Stores are shared by the whole `withConfig` family.
242
243
 
243
- | Request | Answer |
244
- | --- | --- |
245
- | A registered identity's token (a user or robot session), or an internal token that is not a service token | 401 `{ statusCode: 401, error: "Unauthorized", message: "A service session is required for this endpoint" }` |
246
- | An internal token without a signature, signed by another key, or past its `x` | 401, `jwt signature is required` / `invalid signature` / `Session expired` |
247
- | A missing, empty, repeated or unknown query parameter | 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { query: { source: "query", keys: [<key>], message: '"organizationId" is required' } } }` |
248
- | An organization other than `organizationId` | 404, `Organization <id> not found` |
249
- | While `simulateOutage("project-api")` is in effect | 500 (see [Platform outages](#platform-outages)); no store is created |
244
+ | Request | Answer |
245
+ | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
246
+ | A registered identity's token (a user or robot session), or an internal token that is not a service token | 401 `{ statusCode: 401, error: "Unauthorized", message: "A service session is required for this endpoint" }` |
247
+ | An internal token without a signature, signed by another key, or past its `x` | 401, `jwt signature is required` / `invalid signature` / `Session expired` |
248
+ | A missing, empty, repeated or unknown query parameter | 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { query: { source: "query", keys: [<key>], message: '"organizationId" is required' } } }` |
249
+ | An organization other than `organizationId` | 404, `Organization <id> not found` |
250
+ | While `simulateOutage("project-api")` is in effect | 500 (see [Platform outages](#platform-outages)); no store is created |
250
251
 
251
252
  Populus answers only `provisioning` and `active` stores, so the lookup never answers another status, and seeding another status throws. `request()` takes a `query` object as `@sanity/client` does, appended to the URL after the request tag; every route reads its parameters from that URL. A `tag` in `query`, and bracketed query keys such as `organizationId[]` (which Express parses into nested values), throw a fake error.
252
253
 
@@ -254,10 +255,10 @@ Populus answers only `provisioning` and `active` stores, so the lookup never ans
254
255
 
255
256
  Workflows keeps its definitions and instances in the organization's store (see [Organization stores](#organization-stores)). Kong serves that store on two routes, and `request()` answers both on a handle with an acting identity, so code that reads and writes a Workflows store runs against the fake as against the platform:
256
257
 
257
- | Route | Actions | Used by |
258
- | --- | --- | --- |
259
- | `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>` | the read route, for Studio, the SDK and engines |
260
- | `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`) | the Workflows service, which reads and commits there |
258
+ | Route | Actions | Used by |
259
+ | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
260
+ | `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>` | the read route, for Studio, the SDK and engines |
261
+ | `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`) | the Workflows service, which reads and commits there |
261
262
 
262
263
  ```ts
263
264
  const client = createTestClient({
@@ -276,21 +277,23 @@ await client.request({ url: "/workflows/organizations/oAbc/doc/wf.def,wf.none" }
276
277
  // { documents: [{ _id: "wf.def", … }], omitted: [{ id: "wf.none", reason: "existence" }] }
277
278
  ```
278
279
 
279
- The store is the organization's store from `organizationStores` or the lookup, and `client.organizationStore(organizationId)` hands out its documents to seed or inspect. Reads and writes act as the handle's token, with its grants, mutation guards, mutation log and history, as on any resource:
280
+ The store is the organization's store from `organizationStores` or the lookup, and `client.organizationStore(organizationId)` hands out its documents to seed or inspect. `organizationStoreId(organizationId)` is the id the lookup answers, for a test that addresses the store route without looking it up. Reads and writes act as the handle's token, with its grants, mutation guards, mutation log and history, as on any resource:
280
281
 
281
282
  - A query sees only the documents the token may read. `doc` omits a missing id with reason `existence` and one the token may not read with reason `permission` (gradient `pkg/server/httpapi/get_documents.go:25-33,140-162`).
282
283
  - `mutate` applies its mutations atomically and answers `{ transactionId, results: [{ id, operation, document? }] }`, `document` only with `returnDocuments=true` (gradient `pkg/server/httpapi/mutate_test.go:66-98`). A write the grants do not allow is refused with `WriteAccessDeniedError`.
284
+ - An identity with `organizationScope`, an organization-scoped token, is refused on another organization's store on both routes with 403 `{ error: { type: "permissionDeniedError", description: "Unauthorized organization access" } }` (gradient `pkg/system/session.go:71-94`).
285
+ - `mutate` refuses a body gradient cannot apply with gradient's answer, and writes nothing (`pkg/documents/mutation/patch.go:15-26,80-92`, `pkg/documents/errors.go:14-30`, `pkg/server/httpapi/error_test.go:208-265`): a `create` on an id the store holds is 409 `documentAlreadyExistsError` (`Document by ID "<id>" already exists`), a `patch` of an id it does not hold is 404 `documentNotFoundError` (`The document with the ID "<id>" was not found`), and a `patch` whose `ifRevisionID` is not the document's `_rev` is 409 `documentRevisionIDDoesNotMatchError` with `expectedRevisionID` and `currentRevisionID`. An `ifRevisionID` on a document an earlier mutation of the same body wrote throws a fake error.
283
286
  - A query that references a parameter it does not send answers the Content Lake's 400 (see [Unsent query parameters](#unsent-query-parameters)), and a revoked token its 401.
284
287
  - A request carries no perspective, so reads are raw whatever the calling handle's `perspective` is. A write is logged in `client.transactions()` with `organizationStore: { id, organizationId }`; `projectId` and `dataset` there are the calling handle's. `client.calls()` records the `request()` call only.
285
288
 
286
289
  Kong's answers, as staging gives them:
287
290
 
288
- | Request | Answer |
289
- | --- | --- |
290
- | An organization without a store, or with one still `provisioning` | 404 `{ statusCode: 404, error: "Dataset not found", message: 'Dataset for id "org:<organizationId>" not found' }` (kong `kong/sanity-utils/sanity_namespace_routing_key.lua:47-56`; populus makes a store routable before it sets it `active`) |
291
- | A store id that is not an `active` store | the same 404, naming the store id |
292
- | The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }` |
293
- | Any other `/vX/workflows…` path, such as `…/mutate` on the read route | Kong sends it to the Workflows service, which the fake does not serve: a fake error |
291
+ | Request | Answer |
292
+ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
293
+ | An organization without a store, or with one still `provisioning` | 404 `{ statusCode: 404, error: "Dataset not found", message: 'Dataset for id "org:<organizationId>" not found' }` (kong `kong/sanity-utils/sanity_namespace_routing_key.lua:47-56`; populus makes a store routable before it sets it `active`) |
294
+ | A store id that is not an `active` store | the same 404, naming the store id |
295
+ | The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }` |
296
+ | Any other `/vX/workflows…` path, such as `…/mutate` on the read route | Kong sends it to the Workflows service, which the fake does not serve: a fake error |
294
297
 
295
298
  The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does. `listen`, and the store route's `export`, `references`, `actions` and `history`, throw a fake error.
296
299
 
@@ -339,20 +342,20 @@ client.functionInvocations();
339
342
 
340
343
  `client.addFunction(fn)` deploys (or replaces) one more and `client.removeFunction(id)` removes one, for every handle of the family. `functionInvocations()` lists every accepted invocation, in order; a refused one is not recorded. The caller's permissions are read from its `access["<scopeType>:<scopeId>"].permissions`. Header names are case-insensitive, and `blueprintStackId` may also be in the `uri`'s own query string. A `POST` to any other path throws the fake's no-handler error. Refusals are `PlatformHttpError`s whose `response.body` is the Functions API's `{ error, message, details: { errors } }`, checked in the service's order:
341
344
 
342
- | Request | Answer |
343
- | --- | --- |
344
- | `apiVersion` `1` (the default) | 400 `BAD_REQUEST`, `Invalid API version in path`, `details.errors: { version: "v1" }` |
345
- | An internal token (a service-minted JWT has no `guid` claim) | 401 `INVALID_TOKEN`, `Missing required claim: guid` |
346
- | No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header | 400 `MISSING_SCOPE` |
347
- | A scope type other than `project` or `organization` | 400 `INVALID_SCOPE_TYPE` |
345
+ | Request | Answer |
346
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
347
+ | `apiVersion` `1` (the default) | 400 `BAD_REQUEST`, `Invalid API version in path`, `details.errors: { version: "v1" }` |
348
+ | An internal token (a service-minted JWT has no `guid` claim) | 401 `INVALID_TOKEN`, `Missing required claim: guid` |
349
+ | No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header | 400 `MISSING_SCOPE` |
350
+ | A scope type other than `project` or `organization` | 400 `INVALID_SCOPE_TYPE` |
348
351
  | A caller holding none of `sanity.project.functions.invoke`, `sanity.project.blueprints.deploy`, `sanity.project.deployStudio` on a project scope (organization: `sanity.organization.functions.invoke`, `sanity.blueprints.deploy`, `sanity.organization.tokens.create`) | 403 `FORBIDDEN`, `You do not have invoke access to project p1`, `details.errors: { required: [...] }` |
349
- | While `simulateOutage("project-api")` is in effect | 500 `ACCESS_ERROR`, `Failed to validate project access` |
350
- | A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false` | 400 `INVALID_INPUT`, `Validation error: …` |
351
- | Without `blueprintStackId`, an id under 10 characters | 400 `BAD_REQUEST`, `Invalid functionId` |
352
- | With `blueprintStackId`, a name the stack does not hold | 404 `FUNCTION_NOT_FOUND`, `Function "<name>" was not found in Blueprint Stack <stackId>` |
353
- | An unknown id, or a function outside the scope | 404 `FUNCTION_NOT_FOUND`, `function not found` |
354
- | A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"` | 400 `INVOKE_NOT_SUPPORTED` |
355
- | An asynchronous payload of 256 KiB or more | 413 `CONTENT_TOO_LARGE` |
352
+ | While `simulateOutage("project-api")` is in effect | 500 `ACCESS_ERROR`, `Failed to validate project access` |
353
+ | A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false` | 400 `INVALID_INPUT`, `Validation error: …` |
354
+ | Without `blueprintStackId`, an id under 10 characters | 400 `BAD_REQUEST`, `Invalid functionId` |
355
+ | With `blueprintStackId`, a name the stack does not hold | 404 `FUNCTION_NOT_FOUND`, `Function "<name>" was not found in Blueprint Stack <stackId>` |
356
+ | An unknown id, or a function outside the scope | 404 `FUNCTION_NOT_FOUND`, `function not found` |
357
+ | A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"` | 400 `INVOKE_NOT_SUPPORTED` |
358
+ | An asynchronous payload of 256 KiB or more | 413 `CONTENT_TOO_LARGE` |
356
359
 
357
360
  A function is in scope when the scope owns it, or when an organization scope invokes a project's function and that organization is the client's `organizationId` (every project of the family belongs to it); a project scope never reaches an organization's function. Invocations are asynchronous only: a synchronous one that passes every check throws a fake error, as does an `x-sanity-lineage` header (the recursion limit is not modelled). The payload size is measured on `{ data, invokedBySanityUserId, lineage }`, slightly smaller than the Lambda payload the service measures. The service's quota check is not modelled.
358
361
 
@@ -406,11 +409,11 @@ createTestClient({
406
409
 
407
410
  Such an identity is a member of `p1` only. Without `projectId` (the default, and how the fake behaved before) an identity is a member of every project and accepted on every host. A project-scoped identity is refused the way staging refuses an Editor robot of another project (EDEX-3204), each as a `PlatformHttpError`:
408
411
 
409
- | Request | Answer |
410
- | --- | --- |
411
- | Any request on another project's host: a handle with `projectId: "p2"`, project-hosted (queries, documents, writes, actions, `request()`) | 401 `{ statusCode: 401, errorCode: "SIO-401-AWH", error: "Unauthorized", message: "Session does not match project host" }` |
412
- | `GET /projects/<other or unknown project>/features` (global host) | 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be a member of this project to perform this operation" }` |
413
- | `/projects/<other project>` and `/projects/<other project>/users/<ids>` | The identity is not listed among the members |
412
+ | Request | Answer |
413
+ | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
414
+ | Any request on another project's host: a handle with `projectId: "p2"`, project-hosted (queries, documents, writes, actions, `request()`) | 401 `{ statusCode: 401, errorCode: "SIO-401-AWH", error: "Unauthorized", message: "Session does not match project host" }` |
415
+ | `GET /projects/<other or unknown project>/features` (global host) | 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be a member of this project to perform this operation" }` |
416
+ | `/projects/<other project>` and `/projects/<other project>/users/<ids>` | The identity is not listed among the members |
414
417
 
415
418
  Membership of a Media Library or Canvas is not a project matter; their ACLs answer as in [Resource types](#resource-types-media-library-canvas-dashboard).
416
419
 
@@ -425,7 +428,10 @@ const client = createTestClient({
425
428
  user: { id: "p-service" },
426
429
  grants: [
427
430
  { path: "prod.wf-instance.*", permissions: ["read", "create", "update"] },
428
- { path: "temp.system.guard.prod.wf-instance.**", permissions: ["read", "create", "update"] },
431
+ {
432
+ path: "temp.system.guard.prod.wf-instance.**",
433
+ permissions: ["read", "create", "update"],
434
+ },
429
435
  ],
430
436
  },
431
437
  },
@@ -435,16 +441,16 @@ const client = createTestClient({
435
441
 
436
442
  The Content Lake parses a token's path grants on every request it serves and refuses the whole request when one does not parse — whatever the request asks. The fake does the same for every handle acting as that identity, token-bound or inline `accessControl`: `fetch`, `getDocument(s)`, `releases.get` / `releases.fetchDocuments`, every mutation and action, and the History API throw a `PlatformHttpError` with `statusCode: 400` and body `{ error: { description, type: "httpBadRequest" } }`, where `description` is the Content Lake's message for the first grant it cannot parse. A route the resource does not mount still answers its 404 first (a Canvas's `/actions`), as the request never reaches the Content Lake.
437
443
 
438
- | Grant | `description` |
439
- | --- | --- |
440
- | `path: ""` | `path must contain at least one element` |
441
- | `path` starting with `.` | `path cannot begin with delimiter "."` |
442
- | `path` with an empty element (`a..b`, `a.`) | `path contains empty element` |
443
- | `path` over 128 UTF-8 bytes | `path exceeds maximum length of 128` |
444
- | `*` before the last element (`*.wf-instance.*`) | `wildcard must be last component` |
445
- | `**` before the last element | `descendant wildcard must be last component` |
446
- | an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted |
447
- | a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`) | `invalid permission "<permission>"`, Go-quoted |
444
+ | Grant | `description` |
445
+ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
446
+ | `path: ""` | `path must contain at least one element` |
447
+ | `path` starting with `.` | `path cannot begin with delimiter "."` |
448
+ | `path` with an empty element (`a..b`, `a.`) | `path contains empty element` |
449
+ | `path` over 128 UTF-8 bytes | `path exceeds maximum length of 128` |
450
+ | `*` before the last element (`*.wf-instance.*`) | `wildcard must be last component` |
451
+ | `**` before the last element | `descendant wildcard must be last component` |
452
+ | an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted |
453
+ | a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`) | `invalid permission "<permission>"`, Go-quoted |
448
454
 
449
455
  Filter grants come from the ACL, not the token, and are not checked. `/users/me`, the project API (`/projects/…`), the Access API and the ACL are not the Content Lake's and do not read a token's grants, so they keep answering.
450
456
 
@@ -500,23 +506,24 @@ await client.request({ url: client.getDataUrl("history", `documents/a?revision=$
500
506
  await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/c1/actions
501
507
  ```
502
508
 
503
- | Capability | dataset | media-library | canvas | dashboard |
504
- | --- | --- | --- | --- | --- |
505
- | `drafts.` / `versions.` ids, perspectives | ✅ | ✅ | ✅ | ✅ |
506
- | `/actions` (releases, version and document actions) | ✅ | ✅, except `release.create` → 403 `releaseLimitExceededError` | 404 `Cannot POST …/actions` | 404 `Cannot POST …/actions` |
507
- | History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
508
- | ACL `<data base>/acl` | ✅ | ✅ with `sanity.media-library.read`, else 401; unknown id 404 `Media library not found` | ✅; unknown id 404 `Resource not found` | 404 `Cannot GET …` |
509
- | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
510
- | Access API `…/users` | ✅ | ✅ | 403 | 403 |
511
- | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
512
- | Access API `…/roles`, `…/roles/<roleName>` | ✅ with `sanity.project.roles.read`, else 403 | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
513
- | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
514
- | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
509
+ | Capability | dataset | media-library | canvas | dashboard |
510
+ | --------------------------------------------------------------------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------- |
511
+ | `drafts.` / `versions.` ids, perspectives | ✅ | ✅ | ✅ | ✅ |
512
+ | `/actions` (releases, version and document actions) | ✅ | ✅, except `release.create` → 403 `releaseLimitExceededError` | 404 `Cannot POST …/actions` | 404 `Cannot POST …/actions` |
513
+ | History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
514
+ | ACL `<data base>/acl` | ✅ | ✅ with `sanity.media-library.read`, else 401; unknown id 404 `Media library not found` | ✅; unknown id 404 `Resource not found` | 404 `Cannot GET …` |
515
+ | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
516
+ | Access API `…/users` | ✅ | ✅ | 403 | 403 |
517
+ | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
518
+ | Access API `…/roles`, `…/roles/<roleName>` | ✅ with `sanity.project.roles.read`, else 403 | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
519
+ | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
520
+ | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
515
521
 
516
522
  - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. Populus mounts the Access API from API version `2025-07-11`, so a handle on an earlier `apiVersion`, the default `"1"` included, gets the 404 Express answers for a route that is not mounted (`Cannot GET /access/…`), as on the platform; `X` reaches it. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. An identity registered with `robot: true` is a robot, as populus flags an API token's principal: `/users/me` reports it with `provider: "sanity-token"`, users listings leave it out, and `…/robots/<id>` (keyed by its account-global id) answers `{ id, label, createdAt, memberships, networkPolicy: null }` with only its membership on the addressed resource, as populus's `getRobot` does. That read needs `sanity.<type>.tokens.read` on the actor's entry for the resource, else 403; an id with no robot holding a role there answers 404 `Robot not found`. `…/robots` lists every robot with a membership on the resource as `{ data, nextCursor }`, ordered by id, `limit` per page (default 100, at most 500) after the `nextCursor` id, with `nextCursor` the last id of a full page, else `null`, as populus's `listRobots` does. On an organization, `includeChildren=true` also lists the memberships each robot holds on the organization's Media Libraries, Canvases and dashboards, and the robots that hold only those. Populus serves robots only on `project` and `organization`, so both robots routes on any other type answer 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { params: { source: "params", keys: ["resourceType"], message: '"resourceType" must be one of [project, organization]' } } }`, before the permission check. The fake does not model tokens, so `tokenId`, `expiresAt`, `managedBy` and `lastSeenAt` are absent, `label` is the robot's name (else its id) and `createdAt` is the epoch. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
517
523
  - **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
518
524
  - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
519
525
  - **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
526
+ - **Organization permissions.** `/access/organization/<organizationId>/user-permissions/me` on the client's `organizationId` lists the permissions of every `access` entry the actor holds, the organization's and those on its projects, libraries, canvases and dashboards, each row naming its own resource, as populus selects grants by the role's `ownerOrganizationId` there (`src/services/access/permissions.ts:462-472`). A project robot whose only access in the organization is its project role lists that role's grants.
520
527
  - **Organization.** `/access/organization/<organizationId>/users` and `…/users/<sanityUserId>` (one row, or 404 `User not found` for a non-member) serve the members of the client's `organizationId`: identities with roles in their `"organization:<id>"` entry. Each row lists the organization membership, then the member's roles on every resource the client holds (its libraries, canvases, dashboards and projects), as the platform's organization row does. Like the platform, it needs `sanity.organization.members.read` in the actor's `"organization:<id>"` `permissions` (the built-in `member` role grants it), else 403. Another organization id answers 404 `Organization not found`; `…/roles` answers 403.
521
528
  - **User attributes.** `GET /organizations/<organizationId>/users/me/attributes` answers the caller's own attributes there: `{ sanityUserId, organizationId, attributes: [{ type, key, values: { saml?, sanity? }, activeSource, activeValue }] }`, ordered by key. Seed them as `attributes: [{ key, type, values }]` on the identity's `"organization:<id>"` entry; the Sanity value takes precedence over the SAML one for `activeSource` and `activeValue`, as on the platform. No permission is needed. `limit` (default 50) and `cursor` (the last key of the previous page) page the list. A member with no seeded attributes gets `attributes: []`; a caller without roles in the organization gets 404 `User not found`, and another organization id 404 `Organization not found`.
522
529
  - **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
@@ -529,11 +536,11 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
529
536
 
530
537
  Every error the fake throws for an HTTP answer of the platform is an instance of `@sanity/client`'s `ClientError`, so code that branches on `error instanceof ClientError` handles it as it handles production's:
531
538
 
532
- | Class | Answer |
533
- | --- | --- |
534
- | `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
535
- | `WriteAccessDeniedError` | a write the grants do not permit (403) |
536
- | `GuardDeniedError` | a write a mutation guard denies (403) |
539
+ | Class | Answer |
540
+ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
541
+ | `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
542
+ | `WriteAccessDeniedError` | a write the grants do not permit (403) |
543
+ | `GuardDeniedError` | a write a mutation guard denies (403) |
537
544
 
538
545
  A project API outage (see [Platform outages](#platform-outages)) throws `PlatformServerError` instead, an instance of `@sanity/client`'s `ServerError`, as the client raises a 500.
539
546
 
@@ -545,38 +552,39 @@ The fake hands `ClientError` the response the platform sends, and `ClientError`
545
552
 
546
553
  Useful in test bodies, but a giveaway that the code under test isn't using the real client. Keep them in the test file, not in the code being tested.
547
554
 
548
- | Method | Use |
549
- | --- | --- |
550
- | `client.snapshot()` | Read-only `readonly SanityDocument[]` of the current dataset |
551
- | `client.seed(documents)` | Replace the current dataset's contents |
552
- | `client.add(documents)` | Merge documents in without resetting |
553
- | `client.reset()` | Drop everything in the current dataset |
554
- | `client.store()` | Direct access to the underlying `TestStore` |
555
- | `client.datasets()` | `{ projectId, dataset }[]` known to the registry |
556
- | `client.resources()` | Every resource known to the registry, `{ type, id }[]` (datasets as `id: "<projectId>.<dataset>"`) |
557
- | `client.mutations()` | Every committed mutation, flattened and in order — assert exactly what writes your code submitted |
558
- | `client.transactions()` | Every committed transaction (a direct mutation is a one-mutation transaction), each tagged with `transactionId` + `(projectId, dataset)` |
559
- | `client.clearLog()` | Reset the mutation / transaction log |
560
- | `client.calls(method?)` | Every recorded method call, with args + result — a framework-agnostic spy (like `vi.fn().mock.calls`) |
561
- | `client.callCount(method?)` | Number of recorded calls, optionally filtered by method |
562
- | `client.clearCalls()` | Reset the call log |
563
- | `client.stub(name, handler)` | Register a handler for any unimplemented `@sanity/client` member (see below) |
564
- | `client.stubs()` | The currently-registered stubs |
565
- | `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
566
- | `client.identities()` | Snapshot of the registered token→identity entries |
567
- | `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
568
- | `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
569
- | `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
570
- | `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
571
- | `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
572
- | `client.organizationStore(organizationId)` | The documents of the organization's store, the Workflows store, to seed or inspect (see [Workflows store](#workflows-store)). Throws unless the organization has a store |
573
- | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
574
- | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
575
- | `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
555
+ | Method | Use |
556
+ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
557
+ | `client.snapshot()` | Read-only `readonly SanityDocument[]` of the current dataset |
558
+ | `client.seed(documents)` | Replace the current dataset's contents |
559
+ | `client.add(documents)` | Merge documents in without resetting |
560
+ | `client.reset()` | Drop everything in the current dataset |
561
+ | `client.store()` | Direct access to the underlying `TestStore` |
562
+ | `client.datasets()` | `{ projectId, dataset }[]` known to the registry |
563
+ | `client.resources()` | Every resource known to the registry, `{ type, id }[]` (datasets as `id: "<projectId>.<dataset>"`) |
564
+ | `client.mutations()` | Every committed mutation, flattened and in order — assert exactly what writes your code submitted |
565
+ | `client.transactions()` | Every committed transaction (a direct mutation is a one-mutation transaction), each tagged with `transactionId` + `(projectId, dataset)` |
566
+ | `client.clearLog()` | Reset the mutation / transaction log |
567
+ | `client.calls(method?)` | Every recorded method call, with args + result — a framework-agnostic spy (like `vi.fn().mock.calls`) |
568
+ | `client.callCount(method?)` | Number of recorded calls, optionally filtered by method |
569
+ | `client.clearCalls()` | Reset the call log |
570
+ | `client.stub(name, handler)` | Register a handler for any unimplemented `@sanity/client` member (see below) |
571
+ | `client.stubs()` | The currently-registered stubs |
572
+ | `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
573
+ | `client.identities()` | Snapshot of the registered token→identity entries |
574
+ | `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
575
+ | `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
576
+ | `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
577
+ | `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
578
+ | `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
579
+ | `client.requestHandler()` | A `requestHandler` for a real `@sanity/client`: each request is answered as `request()` answers it on a sibling bound to the request's bearer token, API host and API version, so code that builds its own client runs against the fake |
580
+ | `client.organizationStore(organizationId)` | The documents of the organization's store, the Workflows store, to seed or inspect (see [Workflows store](#workflows-store)). Throws unless the organization has a store |
581
+ | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
582
+ | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
583
+ | `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
576
584
 
577
585
  #### Two layers of observability
578
586
 
579
- The fake records at two levels, so you can assert on either *what your code did to the data* or *how it called the client*:
587
+ The fake records at two levels, so you can assert on either _what your code did to the data_ or _how it called the client_:
580
588
 
581
589
  - **Write effects** — `client.mutations()` / `client.transactions()`: the create/patch/delete/mutate operations that actually landed (rolled-back and `dryRun` writes excluded).
582
590
  - **API calls** — `client.calls()` / `client.callCount()`: every invocation of a `@sanity/client`-surface method (`fetch`, `getDocument`, `create`, `patch`, `mutate`, `releases.*`, …) with its `args`, resolved `result`, or thrown `error`. This is the spy layer — reach for it to assert read patterns (`fetch` called once, with these params) that the write log can't show.
@@ -601,10 +609,12 @@ const client = createTestClient({
601
609
  const serviceClient = client.withConfig({ token: "service-token" });
602
610
  await loadAs(client, serviceClient); // code under test reads with one or the other
603
611
 
604
- expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual([
605
- { token: "caller-token", apiVersion: "2025-02-19" },
606
- { token: "service-token", apiVersion: "2025-02-19" },
607
- ]);
612
+ expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual(
613
+ [
614
+ { token: "caller-token", apiVersion: "2025-02-19" },
615
+ { token: "service-token", apiVersion: "2025-02-19" },
616
+ ],
617
+ );
608
618
  ```
609
619
 
610
620
  > [!NOTE]
@@ -642,15 +652,15 @@ If this should be supported, open an issue: …
642
652
 
643
653
  Nested access reports the full path (`client.assets.upload(...)` → `client.assets.upload`). If you type the test variable as `TestClient`, TypeScript also catches the misuse at compile time.
644
654
 
645
- | Area | Status | Workaround |
646
- | --- | --- | --- |
647
- | `listen(...)` — real-time | ❌ Guarded | Test subscription logic separately, or `client.stub("listen", fn)` |
648
- | `clone()` | ❌ Guarded | `withConfig({})` returns a sibling handle |
649
- | `getUrl(uri)` — URL builder | ❌ Guarded | Hard-code in tests, or stub |
650
- | `request(...)` — generic HTTP | ⚠️ Only with an acting identity | Configure `accessControl` or bind a registered `token`, stub it, or use [MSW](https://mswjs.io) |
651
- | `agent.*` / `assets.*` / `projects.*` / `users.*` / `live.*` / `mediaLibrary.*` | ❌ Guarded | Seed docs directly, or `client.stub(name, fn)` |
652
- | `observable.*` — RxJS API | ❌ Guarded | Wrap the Promise API with `from()` if needed |
653
- | Patch ops: `.diffMatchPatch`, `.merge`, `.append`, `.prepend`, `.replace` | ❌ Absent | `.insert("after", "field[-1]", items)` for append; `.insert("before", "field[0]", items)` for prepend |
655
+ | Area | Status | Workaround |
656
+ | ------------------------------------------------------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------- |
657
+ | `listen(...)` — real-time | ❌ Guarded | Test subscription logic separately, or `client.stub("listen", fn)` |
658
+ | `clone()` | ❌ Guarded | `withConfig({})` returns a sibling handle |
659
+ | `getUrl(uri)` — URL builder | ❌ Guarded | Hard-code in tests, or stub |
660
+ | `request(...)` — generic HTTP | ⚠️ Only with an acting identity | Configure `accessControl` or bind a registered `token`, stub it, or use [MSW](https://mswjs.io) |
661
+ | `agent.*` / `assets.*` / `projects.*` / `users.*` / `live.*` / `mediaLibrary.*` | ❌ Guarded | Seed docs directly, or `client.stub(name, fn)` |
662
+ | `observable.*` — RxJS API | ❌ Guarded | Wrap the Promise API with `from()` if needed |
663
+ | Patch ops: `.diffMatchPatch`, `.merge`, `.append`, `.prepend`, `.replace` | ❌ Absent | `.insert("after", "field[-1]", items)` for append; `.insert("before", "field[0]", items)` for prepend |
654
664
 
655
665
  #### Registering stubs
656
666
 
@@ -666,7 +676,7 @@ Stubs fill gaps only — they don't shadow implemented methods like `fetch` or `
666
676
 
667
677
  ## Design constraints
668
678
 
669
- - **Closure-scoped isolation.** `createTestClient({ documents })` returns a client whose store is local to that closure. Two clients in two tests do not see each other's writes. Pass the *same* client to two consumers if they need to share a store.
679
+ - **Closure-scoped isolation.** `createTestClient({ documents })` returns a client whose store is local to that closure. Two clients in two tests do not see each other's writes. Pass the _same_ client to two consumers if they need to share a store.
670
680
  - **Structural compatibility, not nominal.** Methods accept the same arg shapes as `@sanity/client`, so any code typed against `SanityClient` (or a narrow subset) can take a `TestClient` without an adapter.
671
681
  - **groq-js directly.** Same GROQ evaluator the real client supports server-side, against the in-memory document set. What groq-js supports, this supports. What it doesn't (some `&&` short-circuit edge cases, custom functions), this doesn't either.
672
682