@sanity-labs/client-fake-for-test 0.20.0 → 0.22.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
@@ -79,9 +79,9 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
79
79
  | Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
80
80
  | Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
81
81
  | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
82
- | Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname }`. `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
82
+ | Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname, apiHost, apiVersion, useCdn }`. `apiHost` (default `https://api.sanity.io`), `apiVersion` (default `"1"`, a leading `v` dropped) and `useCdn` (default `true`) are taken as `createTestClient` and `withConfig` options and only decide the URL an error names (see [Errors are `ClientError`s](#errors-are-clienterrors)). `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
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
- | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname? })` | 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 |
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
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. |
87
87
 
@@ -165,7 +165,7 @@ The refusal is the platform's answer, probed on staging and production, raised a
165
165
  statusCode: 401,
166
166
  statusMessage: "Unauthorized",
167
167
  method: "GET", // or "POST" for mutations and actions
168
- url: "/data/query/test", // the API path, without host or version
168
+ url: "https://test.apicdn.sanity.io/v1/data/query/test?query=*&returnQuery=false", // the URL @sanity/client requests
169
169
  headers: { "content-type": "application/json; charset=utf-8" },
170
170
  body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
171
171
  },
@@ -315,6 +315,8 @@ Every error the fake throws for an HTTP answer of the platform is an instance of
315
315
  | `WriteAccessDeniedError` | a write the grants do not permit (403) |
316
316
  | `GuardDeniedError` | a write a mutation guard denies (403) |
317
317
 
318
+ `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
+
318
320
  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`).
319
321
 
320
322
  ### Test-only helpers (not on real `SanityClient`)
@@ -360,6 +362,23 @@ expect(client.calls("fetch")[0]?.args).toEqual([`*[_type=="article"]`, {}]);
360
362
  expect(client.calls("getDocument")[0]?.result).toMatchObject({ _id: "a" });
361
363
  ```
362
364
 
365
+ 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:
366
+
367
+ ```ts
368
+ const client = createTestClient({
369
+ token: "caller-token",
370
+ identities: { "caller-token": caller, "service-token": service },
371
+ apiVersion: "2025-02-19",
372
+ });
373
+ const serviceClient = client.withConfig({ token: "service-token" });
374
+ await loadAs(client, serviceClient); // code under test reads with one or the other
375
+
376
+ expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual([
377
+ { token: "caller-token", apiVersion: "2025-02-19" },
378
+ { token: "service-token", apiVersion: "2025-02-19" },
379
+ ]);
380
+ ```
381
+
363
382
  > [!NOTE]
364
383
  > 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.
365
384
 
package/dist/index.cjs CHANGED
@@ -11,10 +11,10 @@ class PlatformHttpError extends client.ClientError {
11
11
  }
12
12
  }
13
13
  function platformResponse(args) {
14
- const { method, path, statusCode, statusMessage, body } = args;
14
+ const { method, url, statusCode, statusMessage, body } = args;
15
15
  return {
16
16
  body,
17
- url: path,
17
+ url,
18
18
  method,
19
19
  headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
20
20
  statusCode,
@@ -35,9 +35,13 @@ function transactionRefused(request, cause) {
35
35
  }
36
36
  });
37
37
  }
38
- const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
38
+ const DEFAULT_WRITE = {
39
+ method: "POST",
40
+ path: "/data/mutate",
41
+ url: "/data/mutate"
42
+ }, notMounted = ({ method, path, url }) => new PlatformHttpError({
39
43
  method,
40
- path,
44
+ url,
41
45
  statusCode: 404,
42
46
  statusMessage: "Not Found",
43
47
  body: `Cannot ${method} ${path}`
@@ -103,9 +107,9 @@ function notFound(name) {
103
107
  message: `${name} not found`
104
108
  });
105
109
  }
106
- const releaseLimitExceeded = ({ method, path }) => new PlatformHttpError({
110
+ const releaseLimitExceeded = ({ method, url }) => new PlatformHttpError({
107
111
  method,
108
- path,
112
+ url,
109
113
  statusCode: 403,
110
114
  statusMessage: "Forbidden",
111
115
  body: {
@@ -466,8 +470,8 @@ function usersPage(data) {
466
470
  return { ...page(data), totalCount: data.length };
467
471
  }
468
472
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
469
- async function servePlatformRequest(ctx, url) {
470
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), query = new URLSearchParams(queryStart === -1 ? "" : url.slice(queryStart + 1)), request = { method: "GET", path }, myAttributes = path.match(MY_ATTRIBUTES_PATH);
473
+ async function servePlatformRequest(ctx, uri, request) {
474
+ const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
471
475
  if (myAttributes !== null) {
472
476
  const organizationId = decodeURIComponent(myAttributes[1]);
473
477
  return serveMyAttributes({ ctx, request, organizationId, query });
@@ -507,10 +511,10 @@ async function servePlatformRequest(ctx, url) {
507
511
  if (rest.startsWith("/history/"))
508
512
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
509
513
  }
510
- function refuseAclRequest(ctx, url) {
511
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
514
+ function refuseAclRequest(ctx, request) {
515
+ const matched = matchResourcePath(request.path);
512
516
  if (matched?.rest !== "/acl") return;
513
- const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
517
+ const row = capabilitiesOf(matched.resource.type);
514
518
  serveCapability(
515
519
  row.acl,
516
520
  request,
@@ -880,13 +884,13 @@ function serveProject(args) {
880
884
  };
881
885
  }
882
886
  function makeRequestImpl(ctx) {
883
- const { getAccess, useProjectHostname, listIdentities, organizationId, platform } = ctx;
887
+ const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
884
888
  return async (opts) => {
885
889
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
886
890
  if (path === "/users/me")
887
891
  return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
888
892
  if (path !== void 0 && path === accessControl.aclPath)
889
- return refuseAclRequest(platform, path), accessControl.grants;
893
+ return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
890
894
  const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
891
895
  if (pathProjectId !== void 0 && requestedIds !== void 0)
892
896
  return serveProjectUsers({
@@ -901,7 +905,7 @@ function makeRequestImpl(ctx) {
901
905
  identities: listIdentities(),
902
906
  organizationId
903
907
  });
904
- const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
908
+ const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
905
909
  if (served !== void 0) return served.value;
906
910
  throw fakeError(
907
911
  `request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
@@ -1548,7 +1552,11 @@ async function createVersionFromBase(store, action, request) {
1548
1552
  }, promoted = promote(copy);
1549
1553
  return store.put(promoted), { transactionId: cryptoRandomKey() };
1550
1554
  }
1551
- const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
1555
+ const ACTIONS_REQUEST = {
1556
+ method: "POST",
1557
+ path: "/data/actions",
1558
+ url: "/data/actions"
1559
+ };
1552
1560
  function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
1553
1561
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1554
1562
  throw actualRev === void 0 ? new PlatformHttpError({
@@ -1675,6 +1683,48 @@ function createTransaction(executor) {
1675
1683
  };
1676
1684
  return handle;
1677
1685
  }
1686
+ const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
1687
+ function normalizeTagPrefix(prefix) {
1688
+ return prefix ? prefix.replace(/\.+$/, "") : void 0;
1689
+ }
1690
+ function normalizeApiVersion(apiVersion) {
1691
+ const version = `${apiVersion}`.replace(/^v/, "");
1692
+ if (version === "1" || version === "X") return version;
1693
+ const date = new Date(version);
1694
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(version) || !(date.getTime() > 0))
1695
+ throw fakeError(
1696
+ `Invalid API version string, expected \`1\` or date in format \`YYYY-MM-DD\` (got ${JSON.stringify(apiVersion)}), the same rule @sanity/client applies to \`apiVersion\`.`
1697
+ );
1698
+ return version;
1699
+ }
1700
+ function apiBaseUrls(args) {
1701
+ const { apiHost, apiVersion, projectId } = args;
1702
+ if (projectId === void 0) {
1703
+ const url = `${apiHost}/v${apiVersion}`;
1704
+ return { url, cdnUrl: url };
1705
+ }
1706
+ const [protocol, host] = apiHost.split("://", 2), cdnHost = apiHost === DEFAULT_API_HOST ? DEFAULT_CDN_HOST : host;
1707
+ return {
1708
+ url: `${protocol}://${projectId}.${host}/v${apiVersion}`,
1709
+ cdnUrl: `${protocol}://${projectId}.${cdnHost}/v${apiVersion}`
1710
+ };
1711
+ }
1712
+ function requestUrl(base, uri, query = []) {
1713
+ const url = `${base}/${uri.replace(/^\//, "")}`, params = new URLSearchParams();
1714
+ for (const [key, value] of query)
1715
+ value !== void 0 && params.append(key, `${value}`);
1716
+ const search = params.toString();
1717
+ if (search === "") return url;
1718
+ const fragmentStart = url.indexOf("#"), beforeFragment = fragmentStart === -1 ? url : url.slice(0, fragmentStart), fragment = fragmentStart === -1 ? "" : url.slice(fragmentStart);
1719
+ return `${beforeFragment}${beforeFragment.includes("?") ? "&" : "?"}${search}${fragment}`;
1720
+ }
1721
+ function encodeGroqQuery(query, params = {}) {
1722
+ const search = new URLSearchParams();
1723
+ search.append("query", query);
1724
+ for (const [key, value] of Object.entries(params))
1725
+ value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1726
+ return `?${search}`;
1727
+ }
1678
1728
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1679
1729
  "fetch",
1680
1730
  "getDocument",
@@ -1958,11 +2008,15 @@ function createTestClient(options = {}) {
1958
2008
  resource: options.resource,
1959
2009
  accessControl: options.accessControl,
1960
2010
  perspective: options.perspective ?? "raw",
1961
- requestTagPrefix: options.requestTagPrefix,
2011
+ requestTagPrefix: normalizeTagPrefix(options.requestTagPrefix),
1962
2012
  mutationGuard: options.mutationGuard,
1963
2013
  token: options.token,
1964
2014
  useProjectHostname: options.useProjectHostname ?? !0,
1965
- hasProjectId: options.projectId !== void 0
2015
+ hasProjectId: options.projectId !== void 0,
2016
+ apiHost: options.apiHost ?? DEFAULT_API_HOST,
2017
+ apiVersion: normalizeApiVersion(options.apiVersion ?? DEFAULT_API_VERSION),
2018
+ useCdn: options.useCdn !== !1,
2019
+ configuredPerspective: options.perspective
1966
2020
  });
1967
2021
  }
1968
2022
  function dedupeIds(results) {
@@ -2024,7 +2078,11 @@ function makeHandle(handleArgs) {
2024
2078
  requestTagPrefix,
2025
2079
  mutationGuard,
2026
2080
  token,
2027
- useProjectHostname
2081
+ useProjectHostname,
2082
+ apiHost,
2083
+ apiVersion,
2084
+ useCdn,
2085
+ configuredPerspective
2028
2086
  } = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
2029
2087
  if (token === void 0) return accessControl;
2030
2088
  const identity = backend.identities.get(token);
@@ -2048,13 +2106,61 @@ function makeHandle(handleArgs) {
2048
2106
  const tokenProjectId = backend.identities.get(token)?.projectId;
2049
2107
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2050
2108
  throw sessionHostMismatch(request);
2051
- }, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
2109
+ }, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
2052
2110
  refuseSession(request);
2053
2111
  const access = activeAccess();
2054
2112
  if (access === void 0) return;
2055
2113
  const refusal = refusedToken(request, access.grants);
2056
2114
  if (refusal !== void 0) throw refusal;
2057
- }, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
2115
+ }, baseUrls = apiBaseUrls({
2116
+ apiHost,
2117
+ apiVersion,
2118
+ projectId: projectHosted ? projectId : void 0
2119
+ }), dataPath = (operation, path) => dataUrl({ resource, dataset, operation, path }), addresses = (uri, operation) => (hasProjectId || resource !== void 0) && uri.startsWith(dataPath(operation)), isDataUri = (uri) => uri.startsWith("/data/") || ["query", "mutate", "doc", "listen", "history"].some((operation) => addresses(uri, operation)), platformRequest = (args) => {
2120
+ const { method, uri, tag } = args, query = [...args.query ?? []];
2121
+ let cdn = useCdn && (args.canUseCdn ?? (method === "GET" && isDataUri(uri)));
2122
+ const effectiveTag = tag && requestTagPrefix ? `${requestTagPrefix}.${tag}` : tag || requestTagPrefix;
2123
+ if (effectiveTag && tag !== null && query.unshift(["tag", effectiveTag]), addresses(uri, "query")) {
2124
+ const perspectiveOption = args.perspective || configuredPerspective;
2125
+ if (perspectiveOption !== void 0) {
2126
+ const value = Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption;
2127
+ query.unshift(["perspective", value]), (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && (cdn = !1);
2128
+ }
2129
+ args.returnQuery === !1 && query.unshift(["returnQuery", "false"]);
2130
+ }
2131
+ const queryStart = uri.indexOf("?");
2132
+ return {
2133
+ method,
2134
+ path: queryStart === -1 ? uri : uri.slice(0, queryStart),
2135
+ url: requestUrl(cdn ? baseUrls.cdnUrl : baseUrls.url, uri, query)
2136
+ };
2137
+ }, docRequest = (ids, tag) => platformRequest({ method: "GET", uri: dataPath("doc", ids), tag }), queryRequest = (args) => {
2138
+ const encoded = encodeGroqQuery(args.query, args.params), useGet = encoded.length < QUERY_SIZE_LIMIT;
2139
+ return platformRequest({
2140
+ method: useGet ? "GET" : "POST",
2141
+ uri: dataPath("query", useGet ? encoded : ""),
2142
+ tag: args.tag,
2143
+ canUseCdn: !0,
2144
+ perspective: args.perspective,
2145
+ returnQuery: args.returnQuery
2146
+ });
2147
+ }, mutateRequest = (options = {}) => {
2148
+ const { returnDocuments } = options;
2149
+ return platformRequest({
2150
+ method: "POST",
2151
+ uri: dataPath("mutate"),
2152
+ tag: options.tag,
2153
+ canUseCdn: !1,
2154
+ query: [
2155
+ ["dryRun", options.dryRun],
2156
+ ["returnIds", !0],
2157
+ ["returnDocuments", returnDocuments === !1 ? void 0 : returnDocuments ?? !0],
2158
+ ["visibility", options.visibility || "sync"],
2159
+ ["autoGenerateArrayKeys", options.autoGenerateArrayKeys],
2160
+ ["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
2161
+ ]
2162
+ });
2163
+ }, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
2058
2164
  ...backend.identities.values(),
2059
2165
  ...token === void 0 && accessControl !== void 0 ? [
2060
2166
  {
@@ -2081,7 +2187,7 @@ function makeHandle(handleArgs) {
2081
2187
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
2082
2188
  };
2083
2189
  let beforeWrite, writeRequest = DEFAULT_WRITE;
2084
- const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
2190
+ const write = (run, request) => serializeWrite(backend, async () => {
2085
2191
  admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
2086
2192
  try {
2087
2193
  return await run();
@@ -2100,7 +2206,7 @@ function makeHandle(handleArgs) {
2100
2206
  mutations,
2101
2207
  ...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
2102
2208
  });
2103
- }, effectiveRequestTag = (tag) => requestTagPrefix === void 0 ? tag : tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2209
+ }, effectiveRequestTag = (tag) => requestTagPrefix ? tag ? `${requestTagPrefix}.${tag}` : requestTagPrefix : tag, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
2104
2210
  documents,
2105
2211
  results,
2106
2212
  transactionId,
@@ -2243,8 +2349,13 @@ function makeHandle(handleArgs) {
2243
2349
  txnOptions?.returnDocuments ?? !1,
2244
2350
  txnOptions?.returnFirst ?? !1
2245
2351
  );
2246
- }, runAction = async (actions) => {
2247
- const request = lakeRequest("POST", "actions");
2352
+ }, runAction = async (actions, tag) => {
2353
+ const request = platformRequest({
2354
+ method: "POST",
2355
+ uri: dataPath("actions"),
2356
+ tag,
2357
+ canUseCdn: !1
2358
+ });
2248
2359
  if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2249
2360
  return write(async () => {
2250
2361
  for (const action of Array.isArray(actions) ? actions : [actions]) {
@@ -2266,7 +2377,15 @@ function makeHandle(handleArgs) {
2266
2377
  return applyPerspective(accessible, override ?? perspective);
2267
2378
  }, client2 = {
2268
2379
  fetch: async (query, params, opts) => {
2269
- admitToLake(lakeRequest("GET", "query"));
2380
+ admitToLake(
2381
+ queryRequest({
2382
+ query,
2383
+ params,
2384
+ tag: opts?.tag,
2385
+ perspective: opts?.perspective,
2386
+ returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
2387
+ })
2388
+ );
2270
2389
  const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
2271
2390
  dataset: await visibleDocs(opts?.perspective),
2272
2391
  ...params !== void 0 ? { params } : {}
@@ -2278,7 +2397,7 @@ function makeHandle(handleArgs) {
2278
2397
  return result;
2279
2398
  },
2280
2399
  getDocument: async (id, opts) => {
2281
- admitToLake(lakeRequest("GET", "doc", id));
2400
+ admitToLake(docRequest(id, opts?.tag));
2282
2401
  const effective = opts?.perspective ?? perspective;
2283
2402
  if (effective === "raw") {
2284
2403
  const doc = store.get(id);
@@ -2288,7 +2407,7 @@ function makeHandle(handleArgs) {
2288
2407
  return resolveDocument(view, id, effective) ?? void 0;
2289
2408
  },
2290
2409
  getDocuments: async (ids, opts) => {
2291
- admitToLake(lakeRequest("GET", "doc", ids.join(",")));
2410
+ admitToLake(docRequest(ids.join(","), opts?.tag));
2292
2411
  const effective = opts?.perspective ?? perspective;
2293
2412
  if (effective === "raw") {
2294
2413
  const result = [];
@@ -2301,7 +2420,7 @@ function makeHandle(handleArgs) {
2301
2420
  const view = await visibleDocs(effective);
2302
2421
  return ids.map((id) => resolveDocument(view, id, effective) ?? null);
2303
2422
  },
2304
- getDataUrl: (operation, path) => dataUrl({ resource, dataset, operation, path }),
2423
+ getDataUrl: dataPath,
2305
2424
  create: (doc, opts) => write(async () => {
2306
2425
  if (checkRevision(doc._id, opts?.ifRevisionId), store.get(doc._id) !== void 0)
2307
2426
  throw fakeError(
@@ -2316,7 +2435,7 @@ function makeHandle(handleArgs) {
2316
2435
  transactionId,
2317
2436
  opts
2318
2437
  );
2319
- }),
2438
+ }, mutateRequest(opts)),
2320
2439
  createOrReplace: (doc, opts) => write(async () => {
2321
2440
  checkRevision(doc._id, opts?.ifRevisionId);
2322
2441
  const promoted = promote2(doc), existing = store.get(doc._id);
@@ -2330,7 +2449,7 @@ function makeHandle(handleArgs) {
2330
2449
  transactionId,
2331
2450
  opts
2332
2451
  );
2333
- }),
2452
+ }, mutateRequest(opts)),
2334
2453
  createIfNotExists: (doc, opts) => write(async () => {
2335
2454
  checkRevision(doc._id, opts?.ifRevisionId);
2336
2455
  const existing = store.get(doc._id), transactionId = opts?.transactionId ?? cryptoRandomKey();
@@ -2348,7 +2467,7 @@ function makeHandle(handleArgs) {
2348
2467
  transactionId,
2349
2468
  opts
2350
2469
  );
2351
- }),
2470
+ }, mutateRequest(opts)),
2352
2471
  delete: (id, opts) => write(async () => {
2353
2472
  checkRevision(id, opts?.ifRevisionId);
2354
2473
  const existing = store.get(id);
@@ -2362,7 +2481,7 @@ function makeHandle(handleArgs) {
2362
2481
  opts.returnDocuments ?? !0,
2363
2482
  opts.returnFirst ?? !0
2364
2483
  );
2365
- }),
2484
+ }, mutateRequest(opts)),
2366
2485
  patch: (documentId) => createPatch(documentId, {
2367
2486
  apply: (docId, ops, ifRev, options) => write(async () => {
2368
2487
  const doc = await applyPatch(docId, ops, ifRev);
@@ -2378,16 +2497,20 @@ function makeHandle(handleArgs) {
2378
2497
  ],
2379
2498
  options?.tag
2380
2499
  ), doc;
2381
- })
2500
+ }, mutateRequest(options))
2382
2501
  }),
2383
2502
  transaction: () => createTransaction({
2384
- apply: (mutations, txnOptions) => write(() => applyTransaction(mutations, txnOptions))
2503
+ apply: (mutations, txnOptions) => write(
2504
+ () => applyTransaction(mutations, txnOptions),
2505
+ // `Transaction.commit()` asks for ids unless told otherwise.
2506
+ mutateRequest({ ...txnOptions, returnDocuments: txnOptions?.returnDocuments ?? !1 })
2507
+ )
2385
2508
  }),
2386
- mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options)),
2509
+ mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options), mutateRequest(options)),
2387
2510
  // Synchronous writes still take the lock: an action landing while a
2388
2511
  // guarded patch is parked in its gate would otherwise be clobbered
2389
2512
  // when that patch resumes over its pre-action snapshot.
2390
- action: (action) => runAction(action),
2513
+ action: (action, options) => runAction(action, options?.tag),
2391
2514
  releases: {
2392
2515
  create: async ({ releaseId, metadata }) => {
2393
2516
  const result = await runAction({
@@ -2404,12 +2527,20 @@ function makeHandle(handleArgs) {
2404
2527
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2405
2528
  // `@sanity/client` reads a release by id and its documents by query.
2406
2529
  get: async ({ releaseId }) => {
2407
- admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
2530
+ admitToLake(docRequest(`_.releases.${releaseId}`, void 0));
2408
2531
  const doc = store.get(`_.releases.${releaseId}`);
2409
2532
  return doc !== void 0 && await canRead(doc) ? doc : void 0;
2410
2533
  },
2411
2534
  fetchDocuments: async ({ releaseId }) => {
2412
- admitToLake(lakeRequest("GET", "query"));
2535
+ admitToLake(
2536
+ queryRequest({
2537
+ query: "*[sanity::partOfRelease($releaseId)]",
2538
+ params: { releaseId },
2539
+ tag: void 0,
2540
+ perspective: void 0,
2541
+ returnQuery: void 0
2542
+ })
2543
+ );
2413
2544
  const prefix = `versions.${releaseId}.`;
2414
2545
  return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2415
2546
  },
@@ -2452,6 +2583,7 @@ function makeHandle(handleArgs) {
2452
2583
  request: withSession(
2453
2584
  makeRequestImpl({
2454
2585
  getAccess: requireActiveAccess,
2586
+ requestFor: rawRequest,
2455
2587
  useProjectHostname: projectHosted,
2456
2588
  organizationId: backend.organizationId,
2457
2589
  listIdentities: members,
@@ -2487,7 +2619,10 @@ function makeHandle(handleArgs) {
2487
2619
  perspective,
2488
2620
  ...requestTagPrefix !== void 0 ? { requestTagPrefix } : {},
2489
2621
  ...token !== void 0 ? { token } : {},
2490
- useProjectHostname
2622
+ useProjectHostname,
2623
+ apiHost,
2624
+ apiVersion,
2625
+ useCdn
2491
2626
  }),
2492
2627
  withConfig: (config) => {
2493
2628
  rejectAmbiguousIdentity("withConfig()", config), config.token !== void 0 && requireIdentity(backend, config.token, "withConfig()");
@@ -2499,11 +2634,20 @@ function makeHandle(handleArgs) {
2499
2634
  resource: nextResource,
2500
2635
  accessControl: rebinds ? config.accessControl : accessControl,
2501
2636
  perspective: config.perspective ?? perspective,
2502
- requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
2637
+ // `requestTagPrefix: undefined` unsets the prefix, and an inherited
2638
+ // one is normalized again, as `@sanity/client` re-runs `initConfig`
2639
+ // on the merged config (`SanityClient.ts:1417`, `config.ts:239-244`).
2640
+ requestTagPrefix: normalizeTagPrefix(
2641
+ "requestTagPrefix" in config ? config.requestTagPrefix : requestTagPrefix
2642
+ ),
2503
2643
  mutationGuard,
2504
2644
  token: rebinds ? config.token : token,
2505
2645
  useProjectHostname: config.useProjectHostname ?? useProjectHostname,
2506
- hasProjectId: hasProjectId || config.projectId !== void 0
2646
+ hasProjectId: hasProjectId || config.projectId !== void 0,
2647
+ apiHost: config.apiHost ?? apiHost,
2648
+ apiVersion: config.apiVersion !== void 0 ? normalizeApiVersion(config.apiVersion) : apiVersion,
2649
+ useCdn: config.useCdn ?? useCdn,
2650
+ configuredPerspective: config.perspective ?? configuredPerspective
2507
2651
  });
2508
2652
  },
2509
2653
  seed: (documents) => publicStore.seed(documents),
@@ -2547,7 +2691,9 @@ function makeHandle(handleArgs) {
2547
2691
  args,
2548
2692
  projectId,
2549
2693
  dataset,
2550
- ...resource !== void 0 ? { resource } : {}
2694
+ ...resource !== void 0 ? { resource } : {},
2695
+ ...token !== void 0 ? { token } : {},
2696
+ apiVersion
2551
2697
  }, tag = OPTIONS_ARG_POSITION[method] === void 0 ? void 0 : effectiveRequestTag(tagFromArgs(method, args));
2552
2698
  return tag !== void 0 && (rec.tag = tag), backend.calls.push(rec), (outcome) => {
2553
2699
  "error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;