@sanity-labs/client-fake-for-test 0.22.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
 
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
  }
@@ -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;
@@ -2672,6 +2711,9 @@ function makeHandle(handleArgs) {
2672
2711
  revokeIdentity: (revokedToken) => {
2673
2712
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2674
2713
  },
2714
+ simulateOutage: (component) => {
2715
+ backend.outages.add(component);
2716
+ },
2675
2717
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
2676
2718
  transactions: () => [...backend.log],
2677
2719
  clearLog: () => {
@@ -2705,6 +2747,7 @@ function makeHandle(handleArgs) {
2705
2747
  exports.ERR_PREFIX = ERR_PREFIX;
2706
2748
  exports.GuardDeniedError = GuardDeniedError;
2707
2749
  exports.PlatformHttpError = PlatformHttpError;
2750
+ exports.PlatformServerError = PlatformServerError;
2708
2751
  exports.SUPPORTED_SURFACE = SUPPORTED_SURFACE;
2709
2752
  exports.UNSUPPORTED_MEMBERS = UNSUPPORTED_MEMBERS;
2710
2753
  exports.WriteAccessDeniedError = WriteAccessDeniedError;