@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/dist/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ClientError } from "@sanity/client";
2
+ import { ServerError } from "@sanity/client";
2
3
 
3
4
  export declare type Action = ReleaseAction | VersionAction | DocumentAction;
4
5
 
@@ -65,6 +66,13 @@ export declare interface CallRecord {
65
66
  dataset: string;
66
67
  /** The resource the call targeted, on a `resource`-configured handle. */
67
68
  resource?: TestClientResource;
69
+ /**
70
+ * The token of the handle that made the call, after `withConfig`
71
+ * overrides; absent on a handle without one.
72
+ */
73
+ token?: string;
74
+ /** The `apiVersion` of the handle that made the call, as its `config()` reports it. */
75
+ apiVersion?: string;
68
76
  }
69
77
 
70
78
  /** Outcome of a recorded call, reported once a (possibly async) result is known. */
@@ -731,6 +739,9 @@ export declare type Perspective =
731
739
  | (string & {})
732
740
  | string[];
733
741
 
742
+ /** A platform component {@link TestClient.simulateOutage} can take down: `"project-api"` is populus. */
743
+ export declare type PlatformComponent = "project-api";
744
+
734
745
  /**
735
746
  * The platform's refusal, as the `ClientError` `@sanity/client` throws for
736
747
  * the same response: the fake hands `ClientError` the response the client
@@ -765,6 +776,15 @@ declare interface PlatformResponseArgs {
765
776
  body: unknown;
766
777
  }
767
778
 
779
+ /**
780
+ * The platform's 5xx answer, as the `ServerError` `@sanity/client` throws
781
+ * for a status of 500 or more (`src/http/request.ts`); see
782
+ * {@link PlatformHttpError} for how the fields are derived.
783
+ */
784
+ export declare class PlatformServerError extends ServerError {
785
+ constructor(args: PlatformResponseArgs);
786
+ }
787
+
768
788
  /** One row of the `/projects/<projectId>` members response. */
769
789
  export declare interface ProjectMemberRecord {
770
790
  id: string;
@@ -1238,6 +1258,16 @@ export declare interface TestClient {
1238
1258
  * tokens throw.
1239
1259
  */
1240
1260
  revokeIdentity: (token: string) => void;
1261
+ /**
1262
+ * Take a platform component down, as in an outage: from the next request
1263
+ * on, every request it serves, on every handle of the family (siblings
1264
+ * made before and after the call), throws its 5xx answer. `"project-api"`
1265
+ * is populus: `request()` of `/users/me`, the project, organization and
1266
+ * Access APIs, resource lookup and ACLs throws {@link PlatformServerError}
1267
+ * 500. The Content Lake (queries, documents, mutations, actions, history)
1268
+ * keeps answering. The outage lasts for the rest of the family's life.
1269
+ */
1270
+ simulateOutage: (component: PlatformComponent) => void;
1241
1271
  /**
1242
1272
  * Every mutation committed through this client's registry, flattened
1243
1273
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ClientError } from "@sanity/client";
2
+ import { ServerError } from "@sanity/client";
2
3
 
3
4
  export declare type Action = ReleaseAction | VersionAction | DocumentAction;
4
5
 
@@ -65,6 +66,13 @@ export declare interface CallRecord {
65
66
  dataset: string;
66
67
  /** The resource the call targeted, on a `resource`-configured handle. */
67
68
  resource?: TestClientResource;
69
+ /**
70
+ * The token of the handle that made the call, after `withConfig`
71
+ * overrides; absent on a handle without one.
72
+ */
73
+ token?: string;
74
+ /** The `apiVersion` of the handle that made the call, as its `config()` reports it. */
75
+ apiVersion?: string;
68
76
  }
69
77
 
70
78
  /** Outcome of a recorded call, reported once a (possibly async) result is known. */
@@ -731,6 +739,9 @@ export declare type Perspective =
731
739
  | (string & {})
732
740
  | string[];
733
741
 
742
+ /** A platform component {@link TestClient.simulateOutage} can take down: `"project-api"` is populus. */
743
+ export declare type PlatformComponent = "project-api";
744
+
734
745
  /**
735
746
  * The platform's refusal, as the `ClientError` `@sanity/client` throws for
736
747
  * the same response: the fake hands `ClientError` the response the client
@@ -765,6 +776,15 @@ declare interface PlatformResponseArgs {
765
776
  body: unknown;
766
777
  }
767
778
 
779
+ /**
780
+ * The platform's 5xx answer, as the `ServerError` `@sanity/client` throws
781
+ * for a status of 500 or more (`src/http/request.ts`); see
782
+ * {@link PlatformHttpError} for how the fields are derived.
783
+ */
784
+ export declare class PlatformServerError extends ServerError {
785
+ constructor(args: PlatformResponseArgs);
786
+ }
787
+
768
788
  /** One row of the `/projects/<projectId>` members response. */
769
789
  export declare interface ProjectMemberRecord {
770
790
  id: string;
@@ -1238,6 +1258,16 @@ export declare interface TestClient {
1238
1258
  * tokens throw.
1239
1259
  */
1240
1260
  revokeIdentity: (token: string) => void;
1261
+ /**
1262
+ * Take a platform component down, as in an outage: from the next request
1263
+ * on, every request it serves, on every handle of the family (siblings
1264
+ * made before and after the call), throws its 5xx answer. `"project-api"`
1265
+ * is populus: `request()` of `/users/me`, the project, organization and
1266
+ * Access APIs, resource lookup and ACLs throws {@link PlatformServerError}
1267
+ * 500. The Content Lake (queries, documents, mutations, actions, history)
1268
+ * keeps answering. The outage lasts for the rest of the family's life.
1269
+ */
1270
+ simulateOutage: (component: PlatformComponent) => void;
1241
1271
  /**
1242
1272
  * Every mutation committed through this client's registry, flattened
1243
1273
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { parse, evaluate } from "groq-js";
2
- import { ClientError } from "@sanity/client";
2
+ import { ClientError, ServerError } from "@sanity/client";
3
3
  const ERR_PREFIX = "[client-fake-for-test]";
4
4
  function fakeError(message) {
5
5
  return new Error(`${ERR_PREFIX} ${message}`);
@@ -9,6 +9,11 @@ class PlatformHttpError extends ClientError {
9
9
  super(platformResponse(args)), this.name = "PlatformHttpError";
10
10
  }
11
11
  }
12
+ class PlatformServerError extends ServerError {
13
+ constructor(args) {
14
+ super(platformResponse(args)), this.name = "PlatformServerError";
15
+ }
16
+ }
12
17
  function platformResponse(args) {
13
18
  const { method, url, statusCode, statusMessage, body } = args;
14
19
  return {
@@ -79,7 +84,20 @@ const sessionNotFound = (request) => new PlatformHttpError({
79
84
  statusCode: 401,
80
85
  statusMessage: "Unauthorized",
81
86
  message: "User must be a member of this project to perform this operation"
82
- }), mediaLibraryReadRequired = (request) => accessApiError({
87
+ });
88
+ function projectApiDown(request) {
89
+ return new PlatformServerError({
90
+ ...request,
91
+ statusCode: 500,
92
+ statusMessage: "Internal Server Error",
93
+ body: {
94
+ statusCode: 500,
95
+ error: "Internal Server Error",
96
+ message: "An internal server error occurred"
97
+ }
98
+ });
99
+ }
100
+ const mediaLibraryReadRequired = (request) => accessApiError({
83
101
  request,
84
102
  statusCode: 401,
85
103
  statusMessage: "Unauthorized",
@@ -461,7 +479,22 @@ function createDocumentHistory() {
461
479
  function historyIds(list) {
462
480
  return list.split(",").map((id) => decodeURIComponent(id));
463
481
  }
464
- 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\/([^/]+)(\/.*)$/;
482
+ 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 = [
483
+ /^\/users\/me$/,
484
+ /^\/projects\/[^/]+$/,
485
+ /^\/projects\/[^/]+\/users\/[^/]+$/,
486
+ PROJECT_ROLES_PATH,
487
+ PROJECT_FEATURES_PATH,
488
+ MY_ATTRIBUTES_PATH,
489
+ ACCESS_PATH
490
+ ];
491
+ function servedByProjectApi(path) {
492
+ if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
493
+ const matched = matchResourcePath(path);
494
+ if (matched === void 0) return !1;
495
+ const row = capabilitiesOf(matched.resource.type);
496
+ return matched.rest === "" ? row.lookupAtBase : matched.rest === "/acl" && row.acl === "served";
497
+ }
465
498
  function page(data) {
466
499
  return { data, nextCursor: null };
467
500
  }
@@ -1684,7 +1717,7 @@ function createTransaction(executor) {
1684
1717
  }
1685
1718
  const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
1686
1719
  function normalizeTagPrefix(prefix) {
1687
- return prefix?.replace(/\.+$/, "") || void 0;
1720
+ return prefix ? prefix.replace(/\.+$/, "") : void 0;
1688
1721
  }
1689
1722
  function normalizeApiVersion(apiVersion) {
1690
1723
  const version = `${apiVersion}`.replace(/^v/, "");
@@ -1986,6 +2019,7 @@ function createTestClient(options = {}) {
1986
2019
  concurrentEdits: /* @__PURE__ */ new Map(),
1987
2020
  identities: new Map(Object.entries(options.identities ?? {})),
1988
2021
  revoked: /* @__PURE__ */ new Set(),
2022
+ outages: /* @__PURE__ */ new Set(),
1989
2023
  writeChain: Promise.resolve()
1990
2024
  }, registry = backend.registry;
1991
2025
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
@@ -2105,7 +2139,12 @@ function makeHandle(handleArgs) {
2105
2139
  const tokenProjectId = backend.identities.get(token)?.projectId;
2106
2140
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2107
2141
  throw sessionHostMismatch(request);
2108
- }, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
2142
+ }, withSession = (request) => async (opts) => {
2143
+ const sent = rawRequest(opts);
2144
+ if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2145
+ throw projectApiDown(sent);
2146
+ return request(opts);
2147
+ }, admitToLake = (request) => {
2109
2148
  refuseSession(request);
2110
2149
  const access = activeAccess();
2111
2150
  if (access === void 0) return;
@@ -2205,7 +2244,7 @@ function makeHandle(handleArgs) {
2205
2244
  mutations,
2206
2245
  ...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
2207
2246
  });
2208
- }, effectiveRequestTag = (tag) => requestTagPrefix === void 0 ? tag : tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2247
+ }, effectiveRequestTag = (tag) => requestTagPrefix ? tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix : tag, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2209
2248
  documents,
2210
2249
  results,
2211
2250
  transactionId,
@@ -2633,8 +2672,12 @@ function makeHandle(handleArgs) {
2633
2672
  resource: nextResource,
2634
2673
  accessControl: rebinds ? config.accessControl : accessControl,
2635
2674
  perspective: config.perspective ?? perspective,
2636
- // `requestTagPrefix: undefined` unsets the prefix, as in `@sanity/client`.
2637
- requestTagPrefix: "requestTagPrefix" in config ? normalizeTagPrefix(config.requestTagPrefix) : requestTagPrefix,
2675
+ // `requestTagPrefix: undefined` unsets the prefix, and an inherited
2676
+ // one is normalized again, as `@sanity/client` re-runs `initConfig`
2677
+ // on the merged config (`SanityClient.ts:1417`, `config.ts:239-244`).
2678
+ requestTagPrefix: normalizeTagPrefix(
2679
+ "requestTagPrefix" in config ? config.requestTagPrefix : requestTagPrefix
2680
+ ),
2638
2681
  mutationGuard,
2639
2682
  token: rebinds ? config.token : token,
2640
2683
  useProjectHostname: config.useProjectHostname ?? useProjectHostname,
@@ -2667,6 +2710,9 @@ function makeHandle(handleArgs) {
2667
2710
  revokeIdentity: (revokedToken) => {
2668
2711
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2669
2712
  },
2713
+ simulateOutage: (component) => {
2714
+ backend.outages.add(component);
2715
+ },
2670
2716
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
2671
2717
  transactions: () => [...backend.log],
2672
2718
  clearLog: () => {
@@ -2686,7 +2732,9 @@ function makeHandle(handleArgs) {
2686
2732
  args,
2687
2733
  projectId,
2688
2734
  dataset,
2689
- ...resource !== void 0 ? { resource } : {}
2735
+ ...resource !== void 0 ? { resource } : {},
2736
+ ...token !== void 0 ? { token } : {},
2737
+ apiVersion
2690
2738
  }, tag = OPTIONS_ARG_POSITION[method] === void 0 ? void 0 : effectiveRequestTag(tagFromArgs(method, args));
2691
2739
  return tag !== void 0 && (rec.tag = tag), backend.calls.push(rec), (outcome) => {
2692
2740
  "error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
@@ -2699,6 +2747,7 @@ export {
2699
2747
  ERR_PREFIX,
2700
2748
  GuardDeniedError,
2701
2749
  PlatformHttpError,
2750
+ PlatformServerError,
2702
2751
  SUPPORTED_SURFACE,
2703
2752
  UNSUPPORTED_MEMBERS,
2704
2753
  WriteAccessDeniedError,