@sanity-labs/client-fake-for-test 0.21.0 → 0.23.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
@@ -174,6 +174,26 @@ The refusal is the platform's answer, probed on staging and production, raised a
174
174
 
175
175
  The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
176
176
 
177
+ #### Platform outages
178
+
179
+ `client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
180
+
181
+ ```ts
182
+ {
183
+ statusCode: 500,
184
+ message: "Internal Server Error - An internal server error occurred",
185
+ response: {
186
+ statusCode: 500,
187
+ statusMessage: "Internal Server Error",
188
+ url: "https://p1.api.sanity.io/v2025-02-19/projects/p1/features", // the URL @sanity/client requests
189
+ body: { statusCode: 500, error: "Internal Server Error", message: "An internal server error occurred" },
190
+ // method, headers
191
+ },
192
+ }
193
+ ```
194
+
195
+ That is the body populus sends for an unexpected error: its error handler sends Boom's payload, and Boom hides the error's own message behind a fixed one. The Content Lake keeps answering (queries, documents, mutations, actions, the History API), as does a route a resource does not mount (Express's 404). A token without a session is still refused with its 401 first, as the gateway checks the session before it routes. The call is recorded in `client.calls()` with its error. `"project-api"` is the only component so far, and an outage lasts for the rest of the family's life; create a new client for a healthy platform.
196
+
177
197
  #### Project-scoped tokens: membership and refusals
178
198
 
179
199
  A robot token belongs to the project that issued it. Model one with `projectId` on the identity:
@@ -315,6 +335,8 @@ Every error the fake throws for an HTTP answer of the platform is an instance of
315
335
  | `WriteAccessDeniedError` | a write the grants do not permit (403) |
316
336
  | `GuardDeniedError` | a write a mutation guard denies (403) |
317
337
 
338
+ 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.
339
+
318
340
  `response.url` is the URL `@sanity/client` would have requested, as its errors carry it: the project host (`https://<projectId>.api.sanity.io`, or `apicdn` for a GET of the data API with `useCdn` on) or the global host for a `resource` or `useProjectHostname: false` client, then `/v<apiVersion>`, the path, and the query string the client sends (the tag with its `requestTagPrefix`, a GROQ query and its params, the perspective, the mutation options). A JSON body keeps it out of `message`, as in `@sanity/client`; a text body's message names it. For example, `createTestClient({ projectId: "p1", dataset: "production", apiVersion: "2025-02-19", useCdn: false })` names `https://p1.api.sanity.io/v2025-02-19/data/doc/production/x?tag=t` for a refused `getDocument("x", { tag: "t" })`.
319
341
 
320
342
  The fake hands `ClientError` the response the platform sends, and `ClientError` derives `statusCode`, `message`, `responseBody` and `details` from it, exactly as for a real response. `instanceof` needs the fake and your code to share one `@sanity/client`, so it is a peer dependency (7.21 or later, or 8); with several copies installed, dedupe them. Mistakes in a test's setup (an unknown token, a document without `_id`, an unimplemented member) stay plain `Error`s prefixed `[client-fake-for-test]`, as do refusals whose platform answer the fake does not model yet (a mutation's existing id, missing target or `ifRevisionId` mismatch, an unknown id at `/projects/<projectId>/users/<id>`, which carries `statusCode: 404`).
@@ -343,6 +365,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
343
365
  | `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
344
366
  | `client.identities()` | Snapshot of the registered token→identity entries |
345
367
  | `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)) |
368
+ | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
346
369
  | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
347
370
  | `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
348
371
 
@@ -362,6 +385,23 @@ expect(client.calls("fetch")[0]?.args).toEqual([`*[_type=="article"]`, {}]);
362
385
  expect(client.calls("getDocument")[0]?.result).toMatchObject({ _id: "a" });
363
386
  ```
364
387
 
388
+ Each record also carries the `token` (absent when the handle has none) and `apiVersion` of the handle that made the call, after `withConfig` overrides. That answers "which token and API version did this read use" without intercepting HTTP:
389
+
390
+ ```ts
391
+ const client = createTestClient({
392
+ token: "caller-token",
393
+ identities: { "caller-token": caller, "service-token": service },
394
+ apiVersion: "2025-02-19",
395
+ });
396
+ const serviceClient = client.withConfig({ token: "service-token" });
397
+ await loadAs(client, serviceClient); // code under test reads with one or the other
398
+
399
+ expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual([
400
+ { token: "caller-token", apiVersion: "2025-02-19" },
401
+ { token: "service-token", apiVersion: "2025-02-19" },
402
+ ]);
403
+ ```
404
+
365
405
  > [!NOTE]
366
406
  > Builder-returning methods (`patch`, `transaction`) record the call at builder-creation time (`patch("a")` → `args: ["a"]`); the chained ops/commit show up in the mutation log, not as extra calls. Test-only helpers (`snapshot`, `mutations`, `calls`, …) are never recorded.
367
407
 
package/dist/index.cjs CHANGED
@@ -10,6 +10,11 @@ class PlatformHttpError extends client.ClientError {
10
10
  super(platformResponse(args)), this.name = "PlatformHttpError";
11
11
  }
12
12
  }
13
+ class PlatformServerError extends client.ServerError {
14
+ constructor(args) {
15
+ super(platformResponse(args)), this.name = "PlatformServerError";
16
+ }
17
+ }
13
18
  function platformResponse(args) {
14
19
  const { method, url, statusCode, statusMessage, body } = args;
15
20
  return {
@@ -80,7 +85,20 @@ const sessionNotFound = (request) => new PlatformHttpError({
80
85
  statusCode: 401,
81
86
  statusMessage: "Unauthorized",
82
87
  message: "User must be a member of this project to perform this operation"
83
- }), mediaLibraryReadRequired = (request) => accessApiError({
88
+ });
89
+ function projectApiDown(request) {
90
+ return new PlatformServerError({
91
+ ...request,
92
+ statusCode: 500,
93
+ statusMessage: "Internal Server Error",
94
+ body: {
95
+ statusCode: 500,
96
+ error: "Internal Server Error",
97
+ message: "An internal server error occurred"
98
+ }
99
+ });
100
+ }
101
+ const mediaLibraryReadRequired = (request) => accessApiError({
84
102
  request,
85
103
  statusCode: 401,
86
104
  statusMessage: "Unauthorized",
@@ -462,7 +480,22 @@ function createDocumentHistory() {
462
480
  function historyIds(list) {
463
481
  return list.split(",").map((id) => decodeURIComponent(id));
464
482
  }
465
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
483
+ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, PROJECT_API_PATHS = [
484
+ /^\/users\/me$/,
485
+ /^\/projects\/[^/]+$/,
486
+ /^\/projects\/[^/]+\/users\/[^/]+$/,
487
+ PROJECT_ROLES_PATH,
488
+ PROJECT_FEATURES_PATH,
489
+ MY_ATTRIBUTES_PATH,
490
+ ACCESS_PATH
491
+ ];
492
+ function servedByProjectApi(path) {
493
+ if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
494
+ const matched = matchResourcePath(path);
495
+ if (matched === void 0) return !1;
496
+ const row = capabilitiesOf(matched.resource.type);
497
+ return matched.rest === "" ? row.lookupAtBase : matched.rest === "/acl" && row.acl === "served";
498
+ }
466
499
  function page(data) {
467
500
  return { data, nextCursor: null };
468
501
  }
@@ -1685,7 +1718,7 @@ function createTransaction(executor) {
1685
1718
  }
1686
1719
  const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
1687
1720
  function normalizeTagPrefix(prefix) {
1688
- return prefix?.replace(/\.+$/, "") || void 0;
1721
+ return prefix ? prefix.replace(/\.+$/, "") : void 0;
1689
1722
  }
1690
1723
  function normalizeApiVersion(apiVersion) {
1691
1724
  const version = `${apiVersion}`.replace(/^v/, "");
@@ -1987,6 +2020,7 @@ function createTestClient(options = {}) {
1987
2020
  concurrentEdits: /* @__PURE__ */ new Map(),
1988
2021
  identities: new Map(Object.entries(options.identities ?? {})),
1989
2022
  revoked: /* @__PURE__ */ new Set(),
2023
+ outages: /* @__PURE__ */ new Set(),
1990
2024
  writeChain: Promise.resolve()
1991
2025
  }, registry = backend.registry;
1992
2026
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
@@ -2106,7 +2140,12 @@ function makeHandle(handleArgs) {
2106
2140
  const tokenProjectId = backend.identities.get(token)?.projectId;
2107
2141
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2108
2142
  throw sessionHostMismatch(request);
2109
- }, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
2143
+ }, withSession = (request) => async (opts) => {
2144
+ const sent = rawRequest(opts);
2145
+ if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2146
+ throw projectApiDown(sent);
2147
+ return request(opts);
2148
+ }, admitToLake = (request) => {
2110
2149
  refuseSession(request);
2111
2150
  const access = activeAccess();
2112
2151
  if (access === void 0) return;
@@ -2206,7 +2245,7 @@ function makeHandle(handleArgs) {
2206
2245
  mutations,
2207
2246
  ...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
2208
2247
  });
2209
- }, effectiveRequestTag = (tag) => requestTagPrefix === void 0 ? tag : tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2248
+ }, effectiveRequestTag = (tag) => requestTagPrefix ? tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix : tag, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2210
2249
  documents,
2211
2250
  results,
2212
2251
  transactionId,
@@ -2634,8 +2673,12 @@ function makeHandle(handleArgs) {
2634
2673
  resource: nextResource,
2635
2674
  accessControl: rebinds ? config.accessControl : accessControl,
2636
2675
  perspective: config.perspective ?? perspective,
2637
- // `requestTagPrefix: undefined` unsets the prefix, as in `@sanity/client`.
2638
- requestTagPrefix: "requestTagPrefix" in config ? normalizeTagPrefix(config.requestTagPrefix) : requestTagPrefix,
2676
+ // `requestTagPrefix: undefined` unsets the prefix, and an inherited
2677
+ // one is normalized again, as `@sanity/client` re-runs `initConfig`
2678
+ // on the merged config (`SanityClient.ts:1417`, `config.ts:239-244`).
2679
+ requestTagPrefix: normalizeTagPrefix(
2680
+ "requestTagPrefix" in config ? config.requestTagPrefix : requestTagPrefix
2681
+ ),
2639
2682
  mutationGuard,
2640
2683
  token: rebinds ? config.token : token,
2641
2684
  useProjectHostname: config.useProjectHostname ?? useProjectHostname,
@@ -2668,6 +2711,9 @@ function makeHandle(handleArgs) {
2668
2711
  revokeIdentity: (revokedToken) => {
2669
2712
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2670
2713
  },
2714
+ simulateOutage: (component) => {
2715
+ backend.outages.add(component);
2716
+ },
2671
2717
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
2672
2718
  transactions: () => [...backend.log],
2673
2719
  clearLog: () => {
@@ -2687,7 +2733,9 @@ function makeHandle(handleArgs) {
2687
2733
  args,
2688
2734
  projectId,
2689
2735
  dataset,
2690
- ...resource !== void 0 ? { resource } : {}
2736
+ ...resource !== void 0 ? { resource } : {},
2737
+ ...token !== void 0 ? { token } : {},
2738
+ apiVersion
2691
2739
  }, tag = OPTIONS_ARG_POSITION[method] === void 0 ? void 0 : effectiveRequestTag(tagFromArgs(method, args));
2692
2740
  return tag !== void 0 && (rec.tag = tag), backend.calls.push(rec), (outcome) => {
2693
2741
  "error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
@@ -2699,6 +2747,7 @@ function makeHandle(handleArgs) {
2699
2747
  exports.ERR_PREFIX = ERR_PREFIX;
2700
2748
  exports.GuardDeniedError = GuardDeniedError;
2701
2749
  exports.PlatformHttpError = PlatformHttpError;
2750
+ exports.PlatformServerError = PlatformServerError;
2702
2751
  exports.SUPPORTED_SURFACE = SUPPORTED_SURFACE;
2703
2752
  exports.UNSUPPORTED_MEMBERS = UNSUPPORTED_MEMBERS;
2704
2753
  exports.WriteAccessDeniedError = WriteAccessDeniedError;