@sanity-labs/client-fake-for-test 0.29.0 → 0.31.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 +130 -1
- package/dist/index.cjs +661 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +89 -0
- package/dist/index.d.ts +89 -0
- package/dist/index.js +661 -23
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
83
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
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
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? })` | 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)). Calling it without one throws a guidance error. |
|
|
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. |
|
|
87
87
|
|
|
88
88
|
#### Mutation return shapes
|
|
89
89
|
|
|
@@ -250,6 +250,132 @@ The first lookup for an organization without a store creates one `provisioning`,
|
|
|
250
250
|
|
|
251
251
|
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
252
|
|
|
253
|
+
#### Workflows store
|
|
254
|
+
|
|
255
|
+
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
|
+
| 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 |
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
const client = createTestClient({
|
|
264
|
+
useProjectHostname: false,
|
|
265
|
+
apiVersion: "X",
|
|
266
|
+
organizationId: "oAbc",
|
|
267
|
+
organizationStores: { oAbc: "active" },
|
|
268
|
+
identities: { "t-editor": { user: { id: "gEditor" }, grants } },
|
|
269
|
+
token: "t-editor",
|
|
270
|
+
});
|
|
271
|
+
client.organizationStore("oAbc").seed([{ _id: "wf.def", _type: "sanity.workflow.definition" }]);
|
|
272
|
+
|
|
273
|
+
await client.request({ url: "/workflows/organizations/oAbc/query?query=count(*)" });
|
|
274
|
+
// { query: "count(*)", result: 1, ms: … }
|
|
275
|
+
await client.request({ url: "/workflows/organizations/oAbc/doc/wf.def,wf.none" });
|
|
276
|
+
// { documents: [{ _id: "wf.def", … }], omitted: [{ id: "wf.none", reason: "existence" }] }
|
|
277
|
+
```
|
|
278
|
+
|
|
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
|
+
|
|
281
|
+
- 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
|
+
- `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`.
|
|
283
|
+
- 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
|
+
- 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
|
+
|
|
286
|
+
Kong's answers, as staging gives them:
|
|
287
|
+
|
|
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 |
|
|
294
|
+
|
|
295
|
+
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
|
+
|
|
297
|
+
#### Functions
|
|
298
|
+
|
|
299
|
+
`createTestClient({ functions })` deploys functions as the Functions API (sanity-io/functions) holds them, and `request()` invokes them as `POST /v<apiVersion>/functions/<idOrName>/invoke` does:
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
const client = createTestClient({
|
|
303
|
+
projectId: "p1",
|
|
304
|
+
apiVersion: "2025-07-30", // the Functions API serves vX and dated versions only
|
|
305
|
+
organizationId: "oAbc",
|
|
306
|
+
identities: {
|
|
307
|
+
"t-editor": {
|
|
308
|
+
user: { id: "p-editor" },
|
|
309
|
+
globalUser: { id: "gEditor" },
|
|
310
|
+
grants: [],
|
|
311
|
+
access: { "project:p1": { roles: [], permissions: ["sanity.project.functions.invoke"] } },
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
token: "t-editor",
|
|
315
|
+
functions: [
|
|
316
|
+
{
|
|
317
|
+
id: "fn0123456789",
|
|
318
|
+
name: "advance",
|
|
319
|
+
type: "sanity.function.pubsub",
|
|
320
|
+
blueprintStackId: "ST-0123456789",
|
|
321
|
+
resourceType: "project",
|
|
322
|
+
resourceId: "p1",
|
|
323
|
+
},
|
|
324
|
+
],
|
|
325
|
+
});
|
|
326
|
+
await client.request({
|
|
327
|
+
uri: "/functions/advance/invoke",
|
|
328
|
+
method: "POST",
|
|
329
|
+
query: { blueprintStackId: "ST-0123456789" }, // by name; omit to invoke by id
|
|
330
|
+
headers: { "X-Sanity-Scope-Type": "project", "X-Sanity-Scope-Id": "p1" },
|
|
331
|
+
body: { event: { data: { instanceId: "wf-1" } } },
|
|
332
|
+
});
|
|
333
|
+
// undefined: the API's 202 has an empty body
|
|
334
|
+
client.functionInvocations();
|
|
335
|
+
// [{ functionId: "fn0123456789", name: "advance", blueprintStackId: "ST-0123456789",
|
|
336
|
+
// scopeType: "project", scopeId: "p1", sync: false,
|
|
337
|
+
// event: { data: { instanceId: "wf-1" } }, invokedBy: { userId: "gEditor" } }]
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
`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
|
+
|
|
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` |
|
|
348
|
+
| 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` |
|
|
356
|
+
|
|
357
|
+
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
|
+
|
|
359
|
+
#### Unsent query parameters
|
|
360
|
+
|
|
361
|
+
A query that references a parameter the request does not send is refused before it runs, as the Content Lake refuses it (gradient parses with go-groq, `parser/internal/parserv2/parser.go:105-121`; staging, 2026-11-30). `fetch` throws a `PlatformHttpError`:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
await client.fetch("*[_id == $x][0]"); // no $x sent
|
|
365
|
+
// statusCode: 400
|
|
366
|
+
// response.body: {
|
|
367
|
+
// error: {
|
|
368
|
+
// description: "param $x referenced, but not provided",
|
|
369
|
+
// end: 10,
|
|
370
|
+
// query: "*[_id == $x][0]",
|
|
371
|
+
// start: 9,
|
|
372
|
+
// type: "queryParseError",
|
|
373
|
+
// },
|
|
374
|
+
// }
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
It names the first unsent parameter in the query's text, even one in a branch the query never evaluates (`select(false => $x, 1)`). `start` and `end` are code-point offsets of the `$name`, and `start` is left out when it is 0. A parameter sent as `null` is sent; one whose value is `undefined` is not, as `@sanity/client` leaves it out of the request. A `$` in a string or a comment, and a custom function's own parameters, are not query parameters. A syntax error earlier in the query is answered first, as groq-js raises it, and so is a string with an escape the Content Lake refuses (`\q`, `\x41`, `\u{…}`, a lone surrogate), though groq-js accepts some of those; a token's 401 and a missing dataset's 404 come before the refusal.
|
|
378
|
+
|
|
253
379
|
#### Missing datasets
|
|
254
380
|
|
|
255
381
|
`createTestClient({ missingDatasets: ["p1:staged"] })` names datasets the platform does not have, as `"<projectId>:<dataset>"` keys. Every Content Lake request on one (queries, documents, mutations, actions, the History API) throws the `PlatformHttpError` the Content Lake answers for a missing dataset, on every handle of the family:
|
|
@@ -440,7 +566,10 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
440
566
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
441
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)) |
|
|
442
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)) |
|
|
443
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 |
|
|
444
573
|
| `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
|
|
445
574
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
446
575
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|