@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/dist/index.cjs CHANGED
@@ -1076,6 +1076,21 @@ async function readHistory(args) {
1076
1076
  }
1077
1077
  };
1078
1078
  }
1079
+ function permissionRecords(args) {
1080
+ const { ctx, resource } = args, entries = Object.entries(ctx.actorAccess() ?? {}), own = accessKey(resource.type, resource.id);
1081
+ return (resource.type === "organization" && resource.id === ctx.organizationId ? entries : entries.filter(([key]) => key === own)).flatMap(([key, entry]) => {
1082
+ const separator = key.indexOf(":"), resourceType = key.slice(0, separator), resourceId = key.slice(separator + 1);
1083
+ return (entry.permissions ?? []).map((permission) => {
1084
+ const dot = permission.lastIndexOf(".");
1085
+ return {
1086
+ type: permission.slice(0, dot),
1087
+ resourceType,
1088
+ resourceId,
1089
+ action: permission.slice(dot + 1)
1090
+ };
1091
+ });
1092
+ });
1093
+ }
1079
1094
  function serveGated(args) {
1080
1095
  const { capability, permission, held, request, serve } = args;
1081
1096
  return serveCapability(capability, request, () => {
@@ -1155,19 +1170,7 @@ function serveAccess(args) {
1155
1170
  value: usersPage(usersOn({ resource, registry, identities: ctx.identities() }))
1156
1171
  }));
1157
1172
  case "/user-permissions/me":
1158
- return {
1159
- value: page(
1160
- permissions.map((permission) => {
1161
- const dot = permission.lastIndexOf(".");
1162
- return {
1163
- type: permission.slice(0, dot),
1164
- resourceType: resource.type,
1165
- resourceId: id,
1166
- action: permission.slice(dot + 1)
1167
- };
1168
- })
1169
- )
1170
- };
1173
+ return { value: page(permissionRecords({ ctx, resource })) };
1171
1174
  default:
1172
1175
  return;
1173
1176
  }
@@ -2290,6 +2293,25 @@ function encodeGroqQuery(query, params = {}) {
2290
2293
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
2291
2294
  return `?${search}`;
2292
2295
  }
2296
+ function handledRequest(options) {
2297
+ const full = new URL(options.url ?? ""), [, version, ...path] = full.pathname.split("/");
2298
+ if (version === void 0 || !version.startsWith("v"))
2299
+ throw fakeError(`requestHandler(): "${options.url}" has no /v<apiVersion> segment.`);
2300
+ const entries = options.query instanceof URLSearchParams ? [...options.query] : Object.entries(options.query ?? {}), search = new URLSearchParams(full.search);
2301
+ let tag;
2302
+ for (const [key, value] of entries)
2303
+ key === "tag" && typeof value == "string" ? tag = value : value !== void 0 && search.append(key, String(value));
2304
+ const query = search.toString(), bearer = new Headers(options.headers).get("authorization") ?? void 0;
2305
+ return {
2306
+ apiHost: `${full.protocol}//${full.host}`,
2307
+ apiVersion: version.slice(1),
2308
+ url: `/${path.join("/")}${query === "" ? "" : `?${query}`}`,
2309
+ method: options.method?.toUpperCase() === "POST" ? "POST" : "GET",
2310
+ token: bearer?.replace(/^Bearer /, ""),
2311
+ body: options.body,
2312
+ tag
2313
+ };
2314
+ }
2293
2315
  const SIGNING_METHODS = /* @__PURE__ */ new Set([
2294
2316
  ...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
2295
2317
  "EdDSA",
@@ -2780,6 +2802,76 @@ function storeNotFound(request, identifier) {
2780
2802
  }
2781
2803
  });
2782
2804
  }
2805
+ function unauthorizedOrganization(request) {
2806
+ return new PlatformHttpError({
2807
+ ...request,
2808
+ statusCode: 403,
2809
+ statusMessage: "Forbidden",
2810
+ body: {
2811
+ error: { type: "permissionDeniedError", description: "Unauthorized organization access" }
2812
+ }
2813
+ });
2814
+ }
2815
+ function failingMutation(args) {
2816
+ const held = new Set(args.revisions.keys()), written = /* @__PURE__ */ new Set();
2817
+ for (const mutation of args.mutations) {
2818
+ const refusal2 = refusalOf({ ...args, held, written, mutation });
2819
+ if (refusal2 !== void 0) return refusal2;
2820
+ }
2821
+ }
2822
+ function refusalOf(args) {
2823
+ const { request, revisions, held, written, mutation } = args, created = mutation.create ?? mutation.createOrReplace ?? mutation.createIfNotExists;
2824
+ if (created !== void 0) {
2825
+ const id2 = String(created._id);
2826
+ if (mutation.create !== void 0 && held.has(id2))
2827
+ return mutationError(request, 409, {
2828
+ type: "documentAlreadyExistsError",
2829
+ description: `Document by ID ${goQuoted(id2)} already exists`,
2830
+ id: id2
2831
+ });
2832
+ held.add(id2), written.add(id2);
2833
+ return;
2834
+ }
2835
+ if (mutation.delete !== void 0) {
2836
+ held.delete(String(mutation.delete.id));
2837
+ return;
2838
+ }
2839
+ if (mutation.patch === void 0) return;
2840
+ const id = String(mutation.patch.id);
2841
+ if (!held.has(id))
2842
+ return mutationError(request, 404, {
2843
+ type: "documentNotFoundError",
2844
+ description: `The document with the ID ${goQuoted(id)} was not found`,
2845
+ id
2846
+ });
2847
+ const expected = mutation.patch.ifRevisionID;
2848
+ if (typeof expected == "string" && expected !== "") {
2849
+ if (written.has(id))
2850
+ throw fakeError(
2851
+ `request(): a mutate body patches "${id}" with ifRevisionID after writing it; the revision gradient gives a document mid-transaction is not modelled.`
2852
+ );
2853
+ const current = revisions.get(id) ?? "";
2854
+ if (expected !== current)
2855
+ return mutationError(request, 409, {
2856
+ type: "documentRevisionIDDoesNotMatchError",
2857
+ description: `Document ${goQuoted(id)} has unexpected revision ID (${goQuoted(current)}), expected ${goQuoted(expected)}`,
2858
+ expectedRevisionID: expected,
2859
+ currentRevisionID: current
2860
+ });
2861
+ }
2862
+ written.add(id);
2863
+ }
2864
+ function mutationError(request, statusCode, error) {
2865
+ return new PlatformHttpError({
2866
+ ...request,
2867
+ statusCode,
2868
+ statusMessage: statusCode === 404 ? "Not Found" : "Conflict",
2869
+ body: { error }
2870
+ });
2871
+ }
2872
+ function goQuoted(text) {
2873
+ return JSON.stringify(text);
2874
+ }
2783
2875
  const OPTIONS_ARG_POSITION = {
2784
2876
  fetch: 2,
2785
2877
  getDocument: 1,
@@ -2888,6 +2980,14 @@ async function serveStoreAction(args) {
2888
2980
  const body = opts.body;
2889
2981
  if (!Array.isArray(body?.mutations))
2890
2982
  throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
2983
+ const refusal2 = failingMutation({
2984
+ request: sent,
2985
+ revisions: new Map(
2986
+ client$1.store().all().map((doc) => [doc._id, doc._rev])
2987
+ ),
2988
+ mutations: body.mutations
2989
+ });
2990
+ if (refusal2 !== void 0) throw refusal2;
2891
2991
  const committed = await client$1.mutate(body.mutations, {
2892
2992
  returnDocuments: !1,
2893
2993
  returnFirst: !1,
@@ -3170,6 +3270,8 @@ function makeHandle(handleArgs) {
3170
3270
  throw fakeError(
3171
3271
  `request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
3172
3272
  );
3273
+ const scope = token === void 0 ? void 0 : backend.identities.get(token)?.organizationScope;
3274
+ if (scope !== void 0 && scope !== store2.organizationId) throw unauthorizedOrganization(sent);
3173
3275
  const onStore = makeHandle({
3174
3276
  ...handleArgs,
3175
3277
  resource: void 0,
@@ -3813,6 +3915,24 @@ function makeHandle(handleArgs) {
3813
3915
  );
3814
3916
  return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
3815
3917
  },
3918
+ requestHandler: () => (options) => {
3919
+ const sent = handledRequest(options), sibling = client2.withConfig({
3920
+ ...sent.token !== void 0 ? { token: sent.token } : {},
3921
+ apiHost: sent.apiHost,
3922
+ apiVersion: sent.apiVersion,
3923
+ useProjectHostname: !1
3924
+ });
3925
+ if (sibling.request === void 0)
3926
+ throw fakeError(
3927
+ "requestHandler(): the request carries no token the fake knows, so it has no `request()` to answer it."
3928
+ );
3929
+ return sibling.request({
3930
+ url: sent.url,
3931
+ method: sent.method,
3932
+ ...sent.body !== void 0 ? { body: sent.body } : {},
3933
+ ...sent.tag !== void 0 ? { tag: sent.tag } : {}
3934
+ });
3935
+ },
3816
3936
  addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3817
3937
  removeFunction: (id) => unregisterFunction(backend.functions, id),
3818
3938
  functionInvocations: () => structuredClone(backend.functions.invocations),
@@ -3866,6 +3986,7 @@ exports.isDraftId = isDraftId;
3866
3986
  exports.isReleaseDocId = isReleaseDocId;
3867
3987
  exports.isSystemId = isSystemId;
3868
3988
  exports.isVersionId = isVersionId;
3989
+ exports.organizationStoreId = organizationStoreId;
3869
3990
  exports.publishedIdOf = publishedIdOf;
3870
3991
  exports.releaseNameOf = releaseNameOf;
3871
3992
  exports.wrapWithGuards = wrapWithGuards;