@sanity-labs/client-fake-for-test 0.19.0 → 0.21.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.js CHANGED
@@ -10,10 +10,10 @@ class PlatformHttpError extends ClientError {
10
10
  }
11
11
  }
12
12
  function platformResponse(args) {
13
- const { method, path, statusCode, statusMessage, body } = args;
13
+ const { method, url, statusCode, statusMessage, body } = args;
14
14
  return {
15
15
  body,
16
- url: path,
16
+ url,
17
17
  method,
18
18
  headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
19
19
  statusCode,
@@ -34,9 +34,13 @@ function transactionRefused(request, cause) {
34
34
  }
35
35
  });
36
36
  }
37
- const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
37
+ const DEFAULT_WRITE = {
38
+ method: "POST",
39
+ path: "/data/mutate",
40
+ url: "/data/mutate"
41
+ }, notMounted = ({ method, path, url }) => new PlatformHttpError({
38
42
  method,
39
- path,
43
+ url,
40
44
  statusCode: 404,
41
45
  statusMessage: "Not Found",
42
46
  body: `Cannot ${method} ${path}`
@@ -102,9 +106,9 @@ function notFound(name) {
102
106
  message: `${name} not found`
103
107
  });
104
108
  }
105
- const releaseLimitExceeded = ({ method, path }) => new PlatformHttpError({
109
+ const releaseLimitExceeded = ({ method, url }) => new PlatformHttpError({
106
110
  method,
107
- path,
111
+ url,
108
112
  statusCode: 403,
109
113
  statusMessage: "Forbidden",
110
114
  body: {
@@ -465,8 +469,8 @@ function usersPage(data) {
465
469
  return { ...page(data), totalCount: data.length };
466
470
  }
467
471
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
468
- async function servePlatformRequest(ctx, url) {
469
- 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);
472
+ async function servePlatformRequest(ctx, uri, request) {
473
+ const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
470
474
  if (myAttributes !== null) {
471
475
  const organizationId = decodeURIComponent(myAttributes[1]);
472
476
  return serveMyAttributes({ ctx, request, organizationId, query });
@@ -506,10 +510,10 @@ async function servePlatformRequest(ctx, url) {
506
510
  if (rest.startsWith("/history/"))
507
511
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
508
512
  }
509
- function refuseAclRequest(ctx, url) {
510
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
513
+ function refuseAclRequest(ctx, request) {
514
+ const matched = matchResourcePath(request.path);
511
515
  if (matched?.rest !== "/acl") return;
512
- const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
516
+ const row = capabilitiesOf(matched.resource.type);
513
517
  serveCapability(
514
518
  row.acl,
515
519
  request,
@@ -879,13 +883,13 @@ function serveProject(args) {
879
883
  };
880
884
  }
881
885
  function makeRequestImpl(ctx) {
882
- const { getAccess, useProjectHostname, listIdentities, organizationId, platform } = ctx;
886
+ const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
883
887
  return async (opts) => {
884
888
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
885
889
  if (path === "/users/me")
886
890
  return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
887
891
  if (path !== void 0 && path === accessControl.aclPath)
888
- return refuseAclRequest(platform, path), accessControl.grants;
892
+ return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
889
893
  const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
890
894
  if (pathProjectId !== void 0 && requestedIds !== void 0)
891
895
  return serveProjectUsers({
@@ -900,7 +904,7 @@ function makeRequestImpl(ctx) {
900
904
  identities: listIdentities(),
901
905
  organizationId
902
906
  });
903
- const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
907
+ const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
904
908
  if (served !== void 0) return served.value;
905
909
  throw fakeError(
906
910
  `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.`
@@ -1547,7 +1551,11 @@ async function createVersionFromBase(store, action, request) {
1547
1551
  }, promoted = promote(copy);
1548
1552
  return store.put(promoted), { transactionId: cryptoRandomKey() };
1549
1553
  }
1550
- const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
1554
+ const ACTIONS_REQUEST = {
1555
+ method: "POST",
1556
+ path: "/data/actions",
1557
+ url: "/data/actions"
1558
+ };
1551
1559
  function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
1552
1560
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1553
1561
  throw actualRev === void 0 ? new PlatformHttpError({
@@ -1674,6 +1682,48 @@ function createTransaction(executor) {
1674
1682
  };
1675
1683
  return handle;
1676
1684
  }
1685
+ const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
1686
+ function normalizeTagPrefix(prefix) {
1687
+ return prefix?.replace(/\.+$/, "") || void 0;
1688
+ }
1689
+ function normalizeApiVersion(apiVersion) {
1690
+ const version = `${apiVersion}`.replace(/^v/, "");
1691
+ if (version === "1" || version === "X") return version;
1692
+ const date = new Date(version);
1693
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(version) || !(date.getTime() > 0))
1694
+ throw fakeError(
1695
+ `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\`.`
1696
+ );
1697
+ return version;
1698
+ }
1699
+ function apiBaseUrls(args) {
1700
+ const { apiHost, apiVersion, projectId } = args;
1701
+ if (projectId === void 0) {
1702
+ const url = `${apiHost}/v${apiVersion}`;
1703
+ return { url, cdnUrl: url };
1704
+ }
1705
+ const [protocol, host] = apiHost.split("://", 2), cdnHost = apiHost === DEFAULT_API_HOST ? DEFAULT_CDN_HOST : host;
1706
+ return {
1707
+ url: `${protocol}://${projectId}.${host}/v${apiVersion}`,
1708
+ cdnUrl: `${protocol}://${projectId}.${cdnHost}/v${apiVersion}`
1709
+ };
1710
+ }
1711
+ function requestUrl(base, uri, query = []) {
1712
+ const url = `${base}/${uri.replace(/^\//, "")}`, params = new URLSearchParams();
1713
+ for (const [key, value] of query)
1714
+ value !== void 0 && params.append(key, `${value}`);
1715
+ const search = params.toString();
1716
+ if (search === "") return url;
1717
+ const fragmentStart = url.indexOf("#"), beforeFragment = fragmentStart === -1 ? url : url.slice(0, fragmentStart), fragment = fragmentStart === -1 ? "" : url.slice(fragmentStart);
1718
+ return `${beforeFragment}${beforeFragment.includes("?") ? "&" : "?"}${search}${fragment}`;
1719
+ }
1720
+ function encodeGroqQuery(query, params = {}) {
1721
+ const search = new URLSearchParams();
1722
+ search.append("query", query);
1723
+ for (const [key, value] of Object.entries(params))
1724
+ value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1725
+ return `?${search}`;
1726
+ }
1677
1727
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1678
1728
  "fetch",
1679
1729
  "getDocument",
@@ -1914,7 +1964,16 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
1914
1964
  function ensureEntry(registry, resource) {
1915
1965
  const key = registryKey(resource);
1916
1966
  let entry = registry.get(key);
1917
- return entry === void 0 && (entry = { resource, store: createTestStore(), history: createDocumentHistory() }, registry.set(key, entry)), entry;
1967
+ return entry === void 0 && (entry = {
1968
+ resource,
1969
+ store: createTestStore(),
1970
+ history: createDocumentHistory(),
1971
+ exists: !1
1972
+ }, registry.set(key, entry)), entry;
1973
+ }
1974
+ function seedEntry(registry, resource, documents) {
1975
+ const entry = ensureEntry(registry, resource);
1976
+ entry.store.seed(documents), entry.exists = !0;
1918
1977
  }
1919
1978
  function createTestClient(options = {}) {
1920
1979
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
@@ -1931,16 +1990,16 @@ function createTestClient(options = {}) {
1931
1990
  }, registry = backend.registry;
1932
1991
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
1933
1992
  const root = options.resource ?? datasetResource(defaultProjectId, defaultDataset);
1934
- ensureEntry(registry, root).store.seed(options.documents);
1993
+ seedEntry(registry, root, options.documents);
1935
1994
  }
1936
1995
  if (options.datasets)
1937
1996
  for (const [key, docs] of Object.entries(options.datasets)) {
1938
1997
  const { projectId, dataset } = parseDatasetKey(key);
1939
- ensureEntry(registry, datasetResource(projectId, dataset)).store.seed(docs);
1998
+ seedEntry(registry, datasetResource(projectId, dataset), docs);
1940
1999
  }
1941
2000
  if (options.resources)
1942
2001
  for (const [key, docs] of Object.entries(options.resources))
1943
- ensureEntry(registry, parseResourceKey(key)).store.seed(docs);
2002
+ seedEntry(registry, parseResourceKey(key), docs);
1944
2003
  return makeHandle({
1945
2004
  backend,
1946
2005
  projectId: defaultProjectId,
@@ -1948,11 +2007,15 @@ function createTestClient(options = {}) {
1948
2007
  resource: options.resource,
1949
2008
  accessControl: options.accessControl,
1950
2009
  perspective: options.perspective ?? "raw",
1951
- requestTagPrefix: options.requestTagPrefix,
2010
+ requestTagPrefix: normalizeTagPrefix(options.requestTagPrefix),
1952
2011
  mutationGuard: options.mutationGuard,
1953
2012
  token: options.token,
1954
2013
  useProjectHostname: options.useProjectHostname ?? !0,
1955
- hasProjectId: options.projectId !== void 0
2014
+ hasProjectId: options.projectId !== void 0,
2015
+ apiHost: options.apiHost ?? DEFAULT_API_HOST,
2016
+ apiVersion: normalizeApiVersion(options.apiVersion ?? DEFAULT_API_VERSION),
2017
+ useCdn: options.useCdn !== !1,
2018
+ configuredPerspective: options.perspective
1956
2019
  });
1957
2020
  }
1958
2021
  function dedupeIds(results) {
@@ -2014,7 +2077,11 @@ function makeHandle(handleArgs) {
2014
2077
  requestTagPrefix,
2015
2078
  mutationGuard,
2016
2079
  token,
2017
- useProjectHostname
2080
+ useProjectHostname,
2081
+ apiHost,
2082
+ apiVersion,
2083
+ useCdn,
2084
+ configuredPerspective
2018
2085
  } = 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 = () => {
2019
2086
  if (token === void 0) return accessControl;
2020
2087
  const identity = backend.identities.get(token);
@@ -2038,13 +2105,61 @@ function makeHandle(handleArgs) {
2038
2105
  const tokenProjectId = backend.identities.get(token)?.projectId;
2039
2106
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2040
2107
  throw sessionHostMismatch(request);
2041
- }, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
2108
+ }, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
2042
2109
  refuseSession(request);
2043
2110
  const access = activeAccess();
2044
2111
  if (access === void 0) return;
2045
2112
  const refusal = refusedToken(request, access.grants);
2046
2113
  if (refusal !== void 0) throw refusal;
2047
- }, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
2114
+ }, baseUrls = apiBaseUrls({
2115
+ apiHost,
2116
+ apiVersion,
2117
+ projectId: projectHosted ? projectId : void 0
2118
+ }), 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) => {
2119
+ const { method, uri, tag } = args, query = [...args.query ?? []];
2120
+ let cdn = useCdn && (args.canUseCdn ?? (method === "GET" && isDataUri(uri)));
2121
+ const effectiveTag = tag && requestTagPrefix ? `${requestTagPrefix}.${tag}` : tag || requestTagPrefix;
2122
+ if (effectiveTag && tag !== null && query.unshift(["tag", effectiveTag]), addresses(uri, "query")) {
2123
+ const perspectiveOption = args.perspective || configuredPerspective;
2124
+ if (perspectiveOption !== void 0) {
2125
+ const value = Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption;
2126
+ query.unshift(["perspective", value]), (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && (cdn = !1);
2127
+ }
2128
+ args.returnQuery === !1 && query.unshift(["returnQuery", "false"]);
2129
+ }
2130
+ const queryStart = uri.indexOf("?");
2131
+ return {
2132
+ method,
2133
+ path: queryStart === -1 ? uri : uri.slice(0, queryStart),
2134
+ url: requestUrl(cdn ? baseUrls.cdnUrl : baseUrls.url, uri, query)
2135
+ };
2136
+ }, docRequest = (ids, tag) => platformRequest({ method: "GET", uri: dataPath("doc", ids), tag }), queryRequest = (args) => {
2137
+ const encoded = encodeGroqQuery(args.query, args.params), useGet = encoded.length < QUERY_SIZE_LIMIT;
2138
+ return platformRequest({
2139
+ method: useGet ? "GET" : "POST",
2140
+ uri: dataPath("query", useGet ? encoded : ""),
2141
+ tag: args.tag,
2142
+ canUseCdn: !0,
2143
+ perspective: args.perspective,
2144
+ returnQuery: args.returnQuery
2145
+ });
2146
+ }, mutateRequest = (options = {}) => {
2147
+ const { returnDocuments } = options;
2148
+ return platformRequest({
2149
+ method: "POST",
2150
+ uri: dataPath("mutate"),
2151
+ tag: options.tag,
2152
+ canUseCdn: !1,
2153
+ query: [
2154
+ ["dryRun", options.dryRun],
2155
+ ["returnIds", !0],
2156
+ ["returnDocuments", returnDocuments === !1 ? void 0 : returnDocuments ?? !0],
2157
+ ["visibility", options.visibility || "sync"],
2158
+ ["autoGenerateArrayKeys", options.autoGenerateArrayKeys],
2159
+ ["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
2160
+ ]
2161
+ });
2162
+ }, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
2048
2163
  ...backend.identities.values(),
2049
2164
  ...token === void 0 && accessControl !== void 0 ? [
2050
2165
  {
@@ -2054,13 +2169,24 @@ function makeHandle(handleArgs) {
2054
2169
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2055
2170
  }
2056
2171
  ] : []
2057
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), { store, history } = ensureEntry(registry, target), concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2172
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
2173
+ ...store,
2174
+ seed: (documents) => {
2175
+ store.seed(documents), targetEntry.exists = !0;
2176
+ },
2177
+ add: (documents) => {
2178
+ store.add(documents), targetEntry.exists = !0;
2179
+ },
2180
+ put: (doc) => {
2181
+ store.put(doc), targetEntry.exists = !0;
2182
+ }
2183
+ }, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2058
2184
  const access = activeAccess();
2059
2185
  if (access !== void 0)
2060
2186
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
2061
2187
  };
2062
2188
  let beforeWrite, writeRequest = DEFAULT_WRITE;
2063
- const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
2189
+ const write = (run, request) => serializeWrite(backend, async () => {
2064
2190
  admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
2065
2191
  try {
2066
2192
  return await run();
@@ -2068,7 +2194,7 @@ function makeHandle(handleArgs) {
2068
2194
  beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
2069
2195
  }
2070
2196
  }), commitHistory = (transactionId) => {
2071
- beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
2197
+ beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
2072
2198
  }, record = (transactionId, mutations, tag) => {
2073
2199
  const effectiveTag = effectiveRequestTag(tag);
2074
2200
  commitHistory(transactionId), backend.log.push({
@@ -2222,8 +2348,13 @@ function makeHandle(handleArgs) {
2222
2348
  txnOptions?.returnDocuments ?? !1,
2223
2349
  txnOptions?.returnFirst ?? !1
2224
2350
  );
2225
- }, runAction = async (actions) => {
2226
- const request = lakeRequest("POST", "actions");
2351
+ }, runAction = async (actions, tag) => {
2352
+ const request = platformRequest({
2353
+ method: "POST",
2354
+ uri: dataPath("actions"),
2355
+ tag,
2356
+ canUseCdn: !1
2357
+ });
2227
2358
  if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2228
2359
  return write(async () => {
2229
2360
  for (const action of Array.isArray(actions) ? actions : [actions]) {
@@ -2245,7 +2376,15 @@ function makeHandle(handleArgs) {
2245
2376
  return applyPerspective(accessible, override ?? perspective);
2246
2377
  }, client = {
2247
2378
  fetch: async (query, params, opts) => {
2248
- admitToLake(lakeRequest("GET", "query"));
2379
+ admitToLake(
2380
+ queryRequest({
2381
+ query,
2382
+ params,
2383
+ tag: opts?.tag,
2384
+ perspective: opts?.perspective,
2385
+ returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
2386
+ })
2387
+ );
2249
2388
  const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
2250
2389
  dataset: await visibleDocs(opts?.perspective),
2251
2390
  ...params !== void 0 ? { params } : {}
@@ -2257,7 +2396,7 @@ function makeHandle(handleArgs) {
2257
2396
  return result;
2258
2397
  },
2259
2398
  getDocument: async (id, opts) => {
2260
- admitToLake(lakeRequest("GET", "doc", id));
2399
+ admitToLake(docRequest(id, opts?.tag));
2261
2400
  const effective = opts?.perspective ?? perspective;
2262
2401
  if (effective === "raw") {
2263
2402
  const doc = store.get(id);
@@ -2267,7 +2406,7 @@ function makeHandle(handleArgs) {
2267
2406
  return resolveDocument(view, id, effective) ?? void 0;
2268
2407
  },
2269
2408
  getDocuments: async (ids, opts) => {
2270
- admitToLake(lakeRequest("GET", "doc", ids.join(",")));
2409
+ admitToLake(docRequest(ids.join(","), opts?.tag));
2271
2410
  const effective = opts?.perspective ?? perspective;
2272
2411
  if (effective === "raw") {
2273
2412
  const result = [];
@@ -2280,7 +2419,7 @@ function makeHandle(handleArgs) {
2280
2419
  const view = await visibleDocs(effective);
2281
2420
  return ids.map((id) => resolveDocument(view, id, effective) ?? null);
2282
2421
  },
2283
- getDataUrl: (operation, path) => dataUrl({ resource, dataset, operation, path }),
2422
+ getDataUrl: dataPath,
2284
2423
  create: (doc, opts) => write(async () => {
2285
2424
  if (checkRevision(doc._id, opts?.ifRevisionId), store.get(doc._id) !== void 0)
2286
2425
  throw fakeError(
@@ -2295,7 +2434,7 @@ function makeHandle(handleArgs) {
2295
2434
  transactionId,
2296
2435
  opts
2297
2436
  );
2298
- }),
2437
+ }, mutateRequest(opts)),
2299
2438
  createOrReplace: (doc, opts) => write(async () => {
2300
2439
  checkRevision(doc._id, opts?.ifRevisionId);
2301
2440
  const promoted = promote2(doc), existing = store.get(doc._id);
@@ -2309,7 +2448,7 @@ function makeHandle(handleArgs) {
2309
2448
  transactionId,
2310
2449
  opts
2311
2450
  );
2312
- }),
2451
+ }, mutateRequest(opts)),
2313
2452
  createIfNotExists: (doc, opts) => write(async () => {
2314
2453
  checkRevision(doc._id, opts?.ifRevisionId);
2315
2454
  const existing = store.get(doc._id), transactionId = opts?.transactionId ?? cryptoRandomKey();
@@ -2327,7 +2466,7 @@ function makeHandle(handleArgs) {
2327
2466
  transactionId,
2328
2467
  opts
2329
2468
  );
2330
- }),
2469
+ }, mutateRequest(opts)),
2331
2470
  delete: (id, opts) => write(async () => {
2332
2471
  checkRevision(id, opts?.ifRevisionId);
2333
2472
  const existing = store.get(id);
@@ -2341,7 +2480,7 @@ function makeHandle(handleArgs) {
2341
2480
  opts.returnDocuments ?? !0,
2342
2481
  opts.returnFirst ?? !0
2343
2482
  );
2344
- }),
2483
+ }, mutateRequest(opts)),
2345
2484
  patch: (documentId) => createPatch(documentId, {
2346
2485
  apply: (docId, ops, ifRev, options) => write(async () => {
2347
2486
  const doc = await applyPatch(docId, ops, ifRev);
@@ -2357,16 +2496,20 @@ function makeHandle(handleArgs) {
2357
2496
  ],
2358
2497
  options?.tag
2359
2498
  ), doc;
2360
- })
2499
+ }, mutateRequest(options))
2361
2500
  }),
2362
2501
  transaction: () => createTransaction({
2363
- apply: (mutations, txnOptions) => write(() => applyTransaction(mutations, txnOptions))
2502
+ apply: (mutations, txnOptions) => write(
2503
+ () => applyTransaction(mutations, txnOptions),
2504
+ // `Transaction.commit()` asks for ids unless told otherwise.
2505
+ mutateRequest({ ...txnOptions, returnDocuments: txnOptions?.returnDocuments ?? !1 })
2506
+ )
2364
2507
  }),
2365
- mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options)),
2508
+ mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options), mutateRequest(options)),
2366
2509
  // Synchronous writes still take the lock: an action landing while a
2367
2510
  // guarded patch is parked in its gate would otherwise be clobbered
2368
2511
  // when that patch resumes over its pre-action snapshot.
2369
- action: (action) => runAction(action),
2512
+ action: (action, options) => runAction(action, options?.tag),
2370
2513
  releases: {
2371
2514
  create: async ({ releaseId, metadata }) => {
2372
2515
  const result = await runAction({
@@ -2383,12 +2526,20 @@ function makeHandle(handleArgs) {
2383
2526
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2384
2527
  // `@sanity/client` reads a release by id and its documents by query.
2385
2528
  get: async ({ releaseId }) => {
2386
- admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
2529
+ admitToLake(docRequest(`_.releases.${releaseId}`, void 0));
2387
2530
  const doc = store.get(`_.releases.${releaseId}`);
2388
2531
  return doc !== void 0 && await canRead(doc) ? doc : void 0;
2389
2532
  },
2390
2533
  fetchDocuments: async ({ releaseId }) => {
2391
- admitToLake(lakeRequest("GET", "query"));
2534
+ admitToLake(
2535
+ queryRequest({
2536
+ query: "*[sanity::partOfRelease($releaseId)]",
2537
+ params: { releaseId },
2538
+ tag: void 0,
2539
+ perspective: void 0,
2540
+ returnQuery: void 0
2541
+ })
2542
+ );
2392
2543
  const prefix = `versions.${releaseId}.`;
2393
2544
  return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2394
2545
  },
@@ -2431,6 +2582,7 @@ function makeHandle(handleArgs) {
2431
2582
  request: withSession(
2432
2583
  makeRequestImpl({
2433
2584
  getAccess: requireActiveAccess,
2585
+ requestFor: rawRequest,
2434
2586
  useProjectHostname: projectHosted,
2435
2587
  organizationId: backend.organizationId,
2436
2588
  listIdentities: members,
@@ -2452,7 +2604,9 @@ function makeHandle(handleArgs) {
2452
2604
  actorAccess: () => requireActiveAccess().access,
2453
2605
  actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
2454
2606
  identities: members,
2455
- resources: () => [...registry.values()].map((entry) => entry.resource)
2607
+ // A dataset stands for its project, and every project exists in
2608
+ // the fake, so a dataset handle still counts as before.
2609
+ resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
2456
2610
  }
2457
2611
  })
2458
2612
  )
@@ -2464,7 +2618,10 @@ function makeHandle(handleArgs) {
2464
2618
  perspective,
2465
2619
  ...requestTagPrefix !== void 0 ? { requestTagPrefix } : {},
2466
2620
  ...token !== void 0 ? { token } : {},
2467
- useProjectHostname
2621
+ useProjectHostname,
2622
+ apiHost,
2623
+ apiVersion,
2624
+ useCdn
2468
2625
  }),
2469
2626
  withConfig: (config) => {
2470
2627
  rejectAmbiguousIdentity("withConfig()", config), config.token !== void 0 && requireIdentity(backend, config.token, "withConfig()");
@@ -2476,18 +2633,23 @@ function makeHandle(handleArgs) {
2476
2633
  resource: nextResource,
2477
2634
  accessControl: rebinds ? config.accessControl : accessControl,
2478
2635
  perspective: config.perspective ?? perspective,
2479
- requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
2636
+ // `requestTagPrefix: undefined` unsets the prefix, as in `@sanity/client`.
2637
+ requestTagPrefix: "requestTagPrefix" in config ? normalizeTagPrefix(config.requestTagPrefix) : requestTagPrefix,
2480
2638
  mutationGuard,
2481
2639
  token: rebinds ? config.token : token,
2482
2640
  useProjectHostname: config.useProjectHostname ?? useProjectHostname,
2483
- hasProjectId: hasProjectId || config.projectId !== void 0
2641
+ hasProjectId: hasProjectId || config.projectId !== void 0,
2642
+ apiHost: config.apiHost ?? apiHost,
2643
+ apiVersion: config.apiVersion !== void 0 ? normalizeApiVersion(config.apiVersion) : apiVersion,
2644
+ useCdn: config.useCdn ?? useCdn,
2645
+ configuredPerspective: config.perspective ?? configuredPerspective
2484
2646
  });
2485
2647
  },
2486
- seed: (documents) => store.seed(documents),
2487
- add: (documents) => store.add(documents),
2648
+ seed: (documents) => publicStore.seed(documents),
2649
+ add: (documents) => publicStore.add(documents),
2488
2650
  reset: () => store.reset(),
2489
2651
  snapshot: () => store.snapshot(),
2490
- store: () => store,
2652
+ store: () => publicStore,
2491
2653
  simulateConcurrentEdit: (id, count = 1) => {
2492
2654
  const editKey = concurrentEditKey(id);
2493
2655
  backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);