@sanity/client 6.24.2 → 6.24.4

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
@@ -268,6 +268,112 @@ const initConfig = (config, prevConfig) => {
268
268
  const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
269
269
  return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
270
270
  };
271
+ class ConnectionFailedError extends Error {
272
+ name = "ConnectionFailedError";
273
+ }
274
+ class DisconnectError extends Error {
275
+ name = "DisconnectError";
276
+ reason;
277
+ constructor(message, reason, options = {}) {
278
+ super(message, options), this.reason = reason;
279
+ }
280
+ }
281
+ class ChannelError extends Error {
282
+ name = "ChannelError";
283
+ data;
284
+ constructor(message, data) {
285
+ super(message), this.data = data;
286
+ }
287
+ }
288
+ class MessageError extends Error {
289
+ name = "MessageError";
290
+ data;
291
+ constructor(message, data, options = {}) {
292
+ super(message, options), this.data = data;
293
+ }
294
+ }
295
+ class MessageParseError extends Error {
296
+ name = "MessageParseError";
297
+ }
298
+ const REQUIRED_EVENTS = ["channelError", "disconnect"];
299
+ function connectEventSource(initEventSource, events) {
300
+ return rxjs.defer(() => {
301
+ const es = initEventSource();
302
+ return rxjs.isObservable(es) ? es : rxjs.of(es);
303
+ }).pipe(rxjs.mergeMap((es) => connectWithESInstance(es, events)));
304
+ }
305
+ function connectWithESInstance(es, events) {
306
+ return new rxjs.Observable((observer) => {
307
+ const emitOpen = events.includes("open"), emitReconnect = events.includes("reconnect");
308
+ function onError(evt) {
309
+ if ("data" in evt) {
310
+ const [parseError, event] = parseEvent(evt);
311
+ observer.error(
312
+ parseError ? new MessageParseError("Unable to parse EventSource error message", { cause: event }) : new MessageError((event?.data).message, event)
313
+ );
314
+ return;
315
+ }
316
+ es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError("EventSource connection failed")) : emitReconnect && observer.next({ type: "reconnect" });
317
+ }
318
+ function onOpen() {
319
+ observer.next({ type: "open" });
320
+ }
321
+ function onMessage(message) {
322
+ const [parseError, event] = parseEvent(message);
323
+ if (parseError) {
324
+ observer.error(
325
+ new MessageParseError("Unable to parse EventSource message", { cause: parseError })
326
+ );
327
+ return;
328
+ }
329
+ if (message.type === "channelError") {
330
+ observer.error(new ChannelError(extractErrorMessage(event?.data), event.data));
331
+ return;
332
+ }
333
+ if (message.type === "disconnect") {
334
+ observer.error(
335
+ new DisconnectError(
336
+ `Server disconnected client: ${event.data?.reason || "unknown error"}`
337
+ )
338
+ );
339
+ return;
340
+ }
341
+ observer.next({
342
+ type: message.type,
343
+ id: message.lastEventId,
344
+ ...event.data ? { data: event.data } : {}
345
+ });
346
+ }
347
+ es.addEventListener("error", onError), emitOpen && es.addEventListener("open", onOpen);
348
+ const cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== "error" && type !== "open" && type !== "reconnect");
349
+ return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {
350
+ es.removeEventListener("error", onError), emitOpen && es.removeEventListener("open", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();
351
+ };
352
+ });
353
+ }
354
+ function parseEvent(message) {
355
+ try {
356
+ const data = typeof message.data == "string" && JSON.parse(message.data);
357
+ return [
358
+ null,
359
+ {
360
+ type: message.type,
361
+ id: message.lastEventId,
362
+ ...isEmptyObject(data) ? {} : { data }
363
+ }
364
+ ];
365
+ } catch (err) {
366
+ return [err, null];
367
+ }
368
+ }
369
+ function extractErrorMessage(err) {
370
+ return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
371
+ }
372
+ function isEmptyObject(data) {
373
+ for (const _ in data)
374
+ return !1;
375
+ return !0;
376
+ }
271
377
  function getSelection(sel) {
272
378
  if (typeof sel == "string")
273
379
  return { id: sel };
@@ -552,8 +658,8 @@ class Transaction extends BaseTransaction {
552
658
  );
553
659
  }
554
660
  patch(patchOrDocumentId, patchOps) {
555
- const isBuilder = typeof patchOps == "function";
556
- if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch)
661
+ const isBuilder = typeof patchOps == "function", isPatch = typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == "object" && ("query" in patchOrDocumentId || "id" in patchOrDocumentId);
662
+ if (isPatch)
557
663
  return this._add({ patch: patchOrDocumentId.serialize() });
558
664
  if (isBuilder) {
559
665
  const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));
@@ -561,6 +667,10 @@ class Transaction extends BaseTransaction {
561
667
  throw new Error("function passed to `patch()` must return the patch");
562
668
  return this._add({ patch: patch.serialize() });
563
669
  }
670
+ if (isMutationSelection) {
671
+ const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);
672
+ return this._add({ patch: patch.serialize() });
673
+ }
564
674
  return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
565
675
  }
566
676
  }
@@ -886,7 +996,18 @@ function optionsFromFile(opts, file) {
886
996
  );
887
997
  }
888
998
  var defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > "u" ? defaults2[prop] : obj[prop], target), {});
889
- const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), MAX_URL_LENGTH = 14800, possibleOptions = [
999
+ const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = rxjs.defer(() => import("@sanity/eventsource")).pipe(
1000
+ operators.map(({ default: EventSource2 }) => EventSource2),
1001
+ rxjs.shareReplay(1)
1002
+ );
1003
+ function reconnectOnConnectionFailure() {
1004
+ return function(source) {
1005
+ return source.pipe(
1006
+ rxjs.catchError((err, caught) => err instanceof ConnectionFailedError ? rxjs.concat(rxjs.of({ type: "reconnect" }), rxjs.timer(1e3).pipe(rxjs.mergeMap(() => caught))) : rxjs.throwError(() => err))
1007
+ );
1008
+ };
1009
+ }
1010
+ const MAX_URL_LENGTH = 14800, possibleOptions = [
890
1011
  "includePreviousRevision",
891
1012
  "includeResult",
892
1013
  "includeMutations",
@@ -899,68 +1020,23 @@ const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop]
899
1020
  function _listen(query, params, opts = {}) {
900
1021
  const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
901
1022
  if (uri.length > MAX_URL_LENGTH)
902
- return new rxjs.Observable((observer) => observer.error(new Error("Query too large for listener")));
903
- const listenFor = options.events ? options.events : ["mutation"], shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1, esOptions = {};
1023
+ return rxjs.throwError(() => new Error("Query too large for listener"));
1024
+ const listenFor = options.events ? options.events : ["mutation"], esOptions = {};
904
1025
  return (token || withCredentials) && (esOptions.withCredentials = !0), token && (esOptions.headers = {
905
1026
  Authorization: `Bearer ${token}`
906
- }), new rxjs.Observable((observer) => {
907
- let es, reconnectTimer, stopped = !1, unsubscribed = !1;
908
- open();
909
- function onError() {
910
- stopped || (emitReconnect(), !stopped && es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100)));
911
- }
912
- function onChannelError(err) {
913
- observer.error(cooerceError(err));
914
- }
915
- function onMessage(evt) {
916
- const event = parseEvent$1(evt);
917
- return event instanceof Error ? observer.error(event) : observer.next(event);
918
- }
919
- function onDisconnect() {
920
- stopped = !0, unsubscribe(), observer.complete();
921
- }
922
- function unsubscribe() {
923
- es && (es.removeEventListener("error", onError), es.removeEventListener("channelError", onChannelError), es.removeEventListener("disconnect", onDisconnect), listenFor.forEach((type) => es.removeEventListener(type, onMessage)), es.close());
924
- }
925
- function emitReconnect() {
926
- shouldEmitReconnect && observer.next({ type: "reconnect" });
927
- }
928
- async function getEventSource() {
929
- const { default: EventSource2 } = await import("@sanity/eventsource");
930
- if (unsubscribed)
931
- return;
932
- const evs = new EventSource2(uri, esOptions);
933
- return evs.addEventListener("error", onError), evs.addEventListener("channelError", onChannelError), evs.addEventListener("disconnect", onDisconnect), listenFor.forEach((type) => evs.addEventListener(type, onMessage)), evs;
934
- }
935
- function open() {
936
- getEventSource().then((eventSource) => {
937
- eventSource && (es = eventSource, unsubscribed && unsubscribe());
938
- }).catch((reason) => {
939
- observer.error(reason), stop();
940
- });
941
- }
942
- function stop() {
943
- stopped = !0, unsubscribe(), unsubscribed = !0;
944
- }
945
- return stop;
946
- });
947
- }
948
- function parseEvent$1(event) {
949
- try {
950
- const data = event.data && JSON.parse(event.data) || {};
951
- return Object.assign({ type: event.type }, data);
952
- } catch (err) {
953
- return err;
954
- }
955
- }
956
- function cooerceError(err) {
957
- if (err instanceof Error)
958
- return err;
959
- const evt = parseEvent$1(err);
960
- return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
961
- }
962
- function extractErrorMessage(err) {
963
- return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
1027
+ }), connectEventSource(() => (
1028
+ // use polyfill if there is no global EventSource or if we need to set headers
1029
+ (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : rxjs.of(EventSource)).pipe(operators.map((EventSource2) => new EventSource2(uri, esOptions)))
1030
+ ), listenFor).pipe(
1031
+ reconnectOnConnectionFailure(),
1032
+ operators.filter((event) => listenFor.includes(event.type)),
1033
+ operators.map(
1034
+ (event) => ({
1035
+ type: event.type,
1036
+ ..."data" in event ? event.data : {}
1037
+ })
1038
+ )
1039
+ );
964
1040
  }
965
1041
  const requiredApiVersion = "2021-03-26";
966
1042
  class LiveClient {
@@ -996,75 +1072,53 @@ class LiveClient {
996
1072
  );
997
1073
  const path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
998
1074
  tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true");
999
- const listenFor = ["restart", "message", "welcome", "reconnect"], esOptions = {};
1000
- return includeDrafts && token && (esOptions.headers = {
1075
+ const esOptions = {};
1076
+ includeDrafts && token && (esOptions.headers = {
1001
1077
  Authorization: `Bearer ${token}`
1002
- }), includeDrafts && withCredentials && (esOptions.withCredentials = !0), new rxjs.Observable((observer) => {
1003
- let es, reconnectTimer, stopped = !1, unsubscribed = !1;
1004
- open();
1005
- function onError(evt) {
1006
- if (!stopped) {
1007
- if ("data" in evt) {
1008
- const event = parseEvent(evt);
1009
- observer.error(new Error(event.message, { cause: event }));
1010
- }
1011
- es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100));
1012
- }
1013
- }
1014
- function onMessage(evt) {
1015
- const event = parseEvent(evt);
1016
- return event instanceof Error ? observer.error(event) : observer.next(event);
1017
- }
1018
- function unsubscribe() {
1019
- if (es) {
1020
- es.removeEventListener("error", onError);
1021
- for (const type of listenFor)
1022
- es.removeEventListener(type, onMessage);
1023
- es.close();
1024
- }
1025
- }
1026
- async function getEventSource() {
1027
- const EventSourceImplementation = typeof EventSource > "u" || esOptions.headers || esOptions.withCredentials ? (await import("@sanity/eventsource")).default : EventSource;
1028
- if (unsubscribed)
1029
- return;
1030
- try {
1031
- if (await fetch(url, {
1032
- method: "OPTIONS",
1033
- mode: "cors",
1034
- credentials: esOptions.withCredentials ? "include" : "omit",
1035
- headers: esOptions.headers
1036
- }), unsubscribed)
1037
- return;
1038
- } catch {
1039
- throw new CorsOriginError({ projectId: projectId2 });
1078
+ }), includeDrafts && withCredentials && (esOptions.withCredentials = !0);
1079
+ const events = connectEventSource(() => (
1080
+ // use polyfill if there is no global EventSource or if we need to set headers
1081
+ (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : rxjs.of(EventSource)).pipe(operators.map((EventSource2) => new EventSource2(url.href, esOptions)))
1082
+ ), [
1083
+ "message",
1084
+ "restart",
1085
+ "welcome",
1086
+ "reconnect"
1087
+ ]).pipe(
1088
+ reconnectOnConnectionFailure(),
1089
+ operators.map((event) => {
1090
+ if (event.type === "message") {
1091
+ const { data, ...rest } = event;
1092
+ return { ...rest, tags: data.tags };
1040
1093
  }
1041
- const evs = new EventSourceImplementation(url.toString(), esOptions);
1042
- evs.addEventListener("error", onError);
1043
- for (const type of listenFor)
1044
- evs.addEventListener(type, onMessage);
1045
- return evs;
1046
- }
1047
- function open() {
1048
- getEventSource().then((eventSource) => {
1049
- eventSource && (es = eventSource, unsubscribed && unsubscribe());
1050
- }).catch((reason) => {
1051
- observer.error(reason), stop();
1052
- });
1053
- }
1054
- function stop() {
1055
- stopped = !0, unsubscribe(), unsubscribed = !0;
1056
- }
1057
- return stop;
1058
- });
1094
+ return event;
1095
+ })
1096
+ ), checkCors = fetchObservable(url, {
1097
+ method: "OPTIONS",
1098
+ mode: "cors",
1099
+ credentials: esOptions.withCredentials ? "include" : "omit",
1100
+ headers: esOptions.headers
1101
+ }).pipe(
1102
+ rxjs.mergeMap(() => rxjs.EMPTY),
1103
+ rxjs.catchError(() => {
1104
+ throw new CorsOriginError({ projectId: projectId2 });
1105
+ })
1106
+ );
1107
+ return rxjs.concat(checkCors, events);
1059
1108
  }
1060
1109
  }
1061
- function parseEvent(event) {
1062
- try {
1063
- const data = event.data && JSON.parse(event.data) || {};
1064
- return { type: event.type, id: event.lastEventId, ...data };
1065
- } catch (err) {
1066
- return err;
1067
- }
1110
+ function fetchObservable(url, init) {
1111
+ return new rxjs.Observable((observer) => {
1112
+ const controller = new AbortController(), signal = controller.signal;
1113
+ return fetch(url, { ...init, signal: controller.signal }).then(
1114
+ (response) => {
1115
+ observer.next(response), observer.complete();
1116
+ },
1117
+ (err) => {
1118
+ signal.aborted || observer.error(err);
1119
+ }
1120
+ ), () => controller.abort();
1121
+ });
1068
1122
  }
1069
1123
  class ObservableDatasetsClient {
1070
1124
  #client;
@@ -1582,7 +1636,7 @@ function defineDeprecatedCreateClient(createClient2) {
1582
1636
  return printNoDefaultExport(), createClient2(config);
1583
1637
  };
1584
1638
  }
1585
- var name = "@sanity/client", version = "6.24.2";
1639
+ var name = "@sanity/client", version = "6.24.4";
1586
1640
  const middleware = [
1587
1641
  middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
1588
1642
  middleware$1.headers({ "User-Agent": `${name} ${version}` }),
@@ -1614,8 +1668,13 @@ Object.defineProperty(exports, "unstable__environment", {
1614
1668
  });
1615
1669
  exports.BasePatch = BasePatch;
1616
1670
  exports.BaseTransaction = BaseTransaction;
1671
+ exports.ChannelError = ChannelError;
1617
1672
  exports.ClientError = ClientError;
1673
+ exports.ConnectionFailedError = ConnectionFailedError;
1618
1674
  exports.CorsOriginError = CorsOriginError;
1675
+ exports.DisconnectError = DisconnectError;
1676
+ exports.MessageError = MessageError;
1677
+ exports.MessageParseError = MessageParseError;
1619
1678
  exports.ObservablePatch = ObservablePatch;
1620
1679
  exports.ObservableSanityClient = ObservableSanityClient;
1621
1680
  exports.ObservableTransaction = ObservableTransaction;
@@ -1623,6 +1682,7 @@ exports.Patch = Patch;
1623
1682
  exports.SanityClient = SanityClient;
1624
1683
  exports.ServerError = ServerError;
1625
1684
  exports.Transaction = Transaction;
1685
+ exports.connectEventSource = connectEventSource;
1626
1686
  exports.createClient = createClient;
1627
1687
  exports.default = deprecatedCreateClient;
1628
1688
  exports.requester = requester;