@sanity/client 7.22.0 → 7.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.cjs CHANGED
@@ -188,14 +188,11 @@ function sliceWithEllipsis(str, max) {
188
188
  class CorsOriginError extends Error {
189
189
  projectId;
190
190
  addOriginUrl;
191
- constructor({ projectId }) {
192
- super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId;
193
- const url = new URL(`https://sanity.io/manage/project/${projectId}/api`);
194
- if (typeof location < "u") {
195
- const { origin } = location;
196
- url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;
197
- } else
198
- this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`;
191
+ constructor({ projectId, credentials } = {}) {
192
+ if (super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId, projectId && typeof location < "u") {
193
+ const url = new URL(`https://sanity.io/manage/project/${projectId}/api`), { origin } = location;
194
+ url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), credentials && url.searchParams.set("credentials", ""), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;
195
+ } else projectId ? this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api` : this.message = "The current origin is not allowed to connect to the Live Content API.";
199
196
  }
200
197
  }
201
198
  const httpError = {
@@ -800,6 +797,35 @@ function _getDocuments(client, httpRequest, ids, opts = {}) {
800
797
  })
801
798
  );
802
799
  }
800
+ const DOCUMENTS_EXISTS_BATCH_SIZE = 100;
801
+ function _documentsExists(client, httpRequest, ids, opts = {}) {
802
+ if (ids.length === 0)
803
+ return rxjs.of(/* @__PURE__ */ new Set());
804
+ const batches = [];
805
+ for (let i = 0; i < ids.length; i += DOCUMENTS_EXISTS_BATCH_SIZE)
806
+ batches.push(ids.slice(i, i + DOCUMENTS_EXISTS_BATCH_SIZE));
807
+ const fetchBatch = (batchIds) => _requestObservable(client, httpRequest, {
808
+ uri: _getDataUrl(client, "doc", batchIds.map(encodeURIComponent).join(",")),
809
+ tag: opts.tag,
810
+ signal: opts.signal,
811
+ query: { excludeContent: !0 }
812
+ }).pipe(
813
+ operators.filter(isResponse),
814
+ operators.map((event) => {
815
+ const missing = /* @__PURE__ */ new Set();
816
+ for (const omitted of event.body.omitted || [])
817
+ omitted.reason === "existence" && missing.add(omitted.id);
818
+ return new Set(batchIds.filter((id) => !missing.has(id)));
819
+ })
820
+ );
821
+ return rxjs.from(batches).pipe(
822
+ operators.concatMap(fetchBatch),
823
+ operators.reduce((acc, set) => {
824
+ for (const id of set) acc.add(id);
825
+ return acc;
826
+ }, /* @__PURE__ */ new Set())
827
+ );
828
+ }
803
829
  function _getReleaseDocuments(client, httpRequest, releaseId, opts = {}) {
804
830
  return _dataRequest(
805
831
  client,
@@ -936,7 +962,7 @@ const hasDataConfig = (client) => {
936
962
  return config2.dataset !== void 0 && config2.projectId !== void 0 || config2.resource !== void 0;
937
963
  }, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "query")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "mutate")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "doc", "")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "listen")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "history", "")), isData = (client, uri) => uri.startsWith("/data/") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);
938
964
  function _requestObservable(client, httpRequest, options) {
939
- const uri = options.url || options.uri, config$1 = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn;
965
+ const callSiteStack = new Error(), uri = options.url || options.uri, config$1 = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn;
940
966
  let useCdn = (options.useCdn ?? config$1.useCdn) && canUseCdn;
941
967
  const tag = options.tag && config$1.requestTagPrefix ? [config$1.requestTagPrefix, options.tag].join(".") : options.tag || config$1.requestTagPrefix;
942
968
  if (tag && options.tag !== null && (options.query = { tag: config.requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
@@ -952,7 +978,8 @@ function _requestObservable(client, httpRequest, options) {
952
978
  const reqOptions = requestOptions(
953
979
  config$1,
954
980
  Object.assign({}, options, {
955
- url: _getUrl(client, uri, useCdn)
981
+ url: _getUrl(client, uri, useCdn),
982
+ callSiteStack
956
983
  })
957
984
  ), request = new rxjs.Observable(
958
985
  (subscriber) => httpRequest(reqOptions, config$1.requester).subscribe(subscriber)
@@ -1330,19 +1357,14 @@ class LiveClient {
1330
1357
  "welcome",
1331
1358
  "reconnect",
1332
1359
  "goaway"
1333
- ]), checkCors = fetchObservable(url, {
1334
- method: "OPTIONS",
1335
- mode: "cors",
1336
- credentials: esOptions.withCredentials ? "include" : "omit",
1337
- headers: esOptions.headers
1338
- }).pipe(
1339
- rxjs.catchError(() => {
1340
- throw new CorsOriginError({ projectId });
1341
- })
1360
+ ]), checkCors = checkCorsObservable(
1361
+ new URL(this.#client.getUrl("/check/cors", !1)),
1362
+ projectId,
1363
+ esOptions.withCredentials === !0
1342
1364
  ), observable = events.pipe(
1343
1365
  reconnectOnConnectionFailure(),
1344
1366
  rxjs.mergeMap((event) => event.type === "reconnect" ? checkCors.pipe(rxjs.mergeMap(() => rxjs.of(event))) : rxjs.of(event)),
1345
- rxjs.catchError((err) => checkCors.pipe(
1367
+ rxjs.catchError((err) => err instanceof CorsOriginError ? rxjs.throwError(() => err) : checkCors.pipe(
1346
1368
  rxjs.mergeMap(() => {
1347
1369
  throw err;
1348
1370
  })
@@ -1363,17 +1385,27 @@ class LiveClient {
1363
1385
  return eventsCache.set(key, observable), observable;
1364
1386
  }
1365
1387
  }
1366
- function fetchObservable(url, init) {
1388
+ function checkCorsObservable(url, projectId, requireCredentials) {
1367
1389
  return new rxjs.Observable((observer) => {
1368
- const controller = new AbortController(), signal = controller.signal;
1369
- return fetch(url, { ...init, signal: controller.signal }).then(
1370
- (response) => {
1371
- observer.next(response), observer.complete();
1372
- },
1373
- (err) => {
1374
- signal.aborted || observer.error(err);
1390
+ const controller = new AbortController(), { signal } = controller;
1391
+ return fetch(url, { method: "GET", mode: "cors", credentials: "omit", signal }).then((response) => {
1392
+ if (!(signal.aborted || !response.ok))
1393
+ return response.json();
1394
+ }).then((body) => {
1395
+ if (!signal.aborted) {
1396
+ if (requireCredentials && body?.result?.withCredentials === !1) {
1397
+ observer.error(new CorsOriginError({ projectId, credentials: !0 }));
1398
+ return;
1399
+ }
1400
+ if (body?.result?.allowed === !1) {
1401
+ observer.error(new CorsOriginError({ projectId, credentials: requireCredentials }));
1402
+ return;
1403
+ }
1404
+ observer.next(), observer.complete();
1375
1405
  }
1376
- ), () => controller.abort();
1406
+ }).catch(() => {
1407
+ signal.aborted || observer.closed || (observer.next(), observer.complete());
1408
+ }), () => controller.abort();
1377
1409
  });
1378
1410
  }
1379
1411
  const eventsCache = /* @__PURE__ */ new Map();
@@ -2301,6 +2333,16 @@ class ObservableSanityClient {
2301
2333
  getDocuments(ids, options) {
2302
2334
  return _getDocuments(this, this.#httpRequest, ids, options);
2303
2335
  }
2336
+ /**
2337
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2338
+ * Returns a set of the IDs that exist.
2339
+ *
2340
+ * @param ids - Document IDs to check
2341
+ * @param options - Request options
2342
+ */
2343
+ documentsExists(ids, options) {
2344
+ return _documentsExists(this, this.#httpRequest, ids, options);
2345
+ }
2304
2346
  create(document, options) {
2305
2347
  return _create(this, this.#httpRequest, document, "create", options);
2306
2348
  }
@@ -2578,6 +2620,16 @@ class SanityClient {
2578
2620
  getDocuments(ids, options) {
2579
2621
  return rxjs.lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));
2580
2622
  }
2623
+ /**
2624
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2625
+ * Returns a set of the IDs that exist.
2626
+ *
2627
+ * @param ids - Document IDs to check
2628
+ * @param options - Request options
2629
+ */
2630
+ documentsExists(ids, options) {
2631
+ return rxjs.lastValueFrom(_documentsExists(this, this.#httpRequest, ids, options));
2632
+ }
2581
2633
  create(document, options) {
2582
2634
  return rxjs.lastValueFrom(
2583
2635
  _create(this, this.#httpRequest, document, "create", options)
@@ -2800,7 +2852,7 @@ function defineDeprecatedCreateClient(createClient2) {
2800
2852
  return config.printNoDefaultExport(), createClient2(config$1);
2801
2853
  };
2802
2854
  }
2803
- var name = "@sanity/client", version = "7.22.0";
2855
+ var name = "@sanity/client", version = "7.23.0";
2804
2856
  const middleware = [
2805
2857
  middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
2806
2858
  middleware$1.headers({ "User-Agent": `${name} ${version}` }),