@sanity/client 7.23.0 → 7.23.2

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.
@@ -906,11 +906,26 @@ export declare function connectEventSource<EventName extends string>(
906
906
 
907
907
  /**
908
908
  * @public
909
- * Thrown if the EventSource connection could not be established.
910
- * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
909
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
910
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
911
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
912
+ * stream with this class so consumers can react — check `status` for the rejection code.
911
913
  */
912
914
  export declare class ConnectionFailedError extends Error {
913
915
  readonly name = 'ConnectionFailedError'
916
+ /**
917
+ * HTTP status code of the rejected connection attempt, if known.
918
+ * Only set when the EventSource implementation exposes it — the polyfill used in
919
+ * Node.js and when custom headers (eg authorization) are required does, while
920
+ * native EventSource implementations (browser and Node.js) do not.
921
+ */
922
+ readonly status?: number
923
+ constructor(
924
+ message?: string,
925
+ options?: ErrorOptions & {
926
+ status?: number
927
+ },
928
+ )
914
929
  }
915
930
 
916
931
  /**
@@ -906,11 +906,26 @@ export declare function connectEventSource<EventName extends string>(
906
906
 
907
907
  /**
908
908
  * @public
909
- * Thrown if the EventSource connection could not be established.
910
- * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
909
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
910
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
911
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
912
+ * stream with this class so consumers can react — check `status` for the rejection code.
911
913
  */
912
914
  export declare class ConnectionFailedError extends Error {
913
915
  readonly name = 'ConnectionFailedError'
916
+ /**
917
+ * HTTP status code of the rejected connection attempt, if known.
918
+ * Only set when the EventSource implementation exposes it — the polyfill used in
919
+ * Node.js and when custom headers (eg authorization) are required does, while
920
+ * native EventSource implementations (browser and Node.js) do not.
921
+ */
922
+ readonly status?: number
923
+ constructor(
924
+ message?: string,
925
+ options?: ErrorOptions & {
926
+ status?: number
927
+ },
928
+ )
914
929
  }
915
930
 
916
931
  /**
package/dist/stega.d.cts CHANGED
@@ -906,11 +906,26 @@ export declare function connectEventSource<EventName extends string>(
906
906
 
907
907
  /**
908
908
  * @public
909
- * Thrown if the EventSource connection could not be established.
910
- * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
909
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
910
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
911
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
912
+ * stream with this class so consumers can react — check `status` for the rejection code.
911
913
  */
912
914
  export declare class ConnectionFailedError extends Error {
913
915
  readonly name = 'ConnectionFailedError'
916
+ /**
917
+ * HTTP status code of the rejected connection attempt, if known.
918
+ * Only set when the EventSource implementation exposes it — the polyfill used in
919
+ * Node.js and when custom headers (eg authorization) are required does, while
920
+ * native EventSource implementations (browser and Node.js) do not.
921
+ */
922
+ readonly status?: number
923
+ constructor(
924
+ message?: string,
925
+ options?: ErrorOptions & {
926
+ status?: number
927
+ },
928
+ )
914
929
  }
915
930
 
916
931
  /**
package/dist/stega.d.ts CHANGED
@@ -906,11 +906,26 @@ export declare function connectEventSource<EventName extends string>(
906
906
 
907
907
  /**
908
908
  * @public
909
- * Thrown if the EventSource connection could not be established.
910
- * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
909
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
910
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
911
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
912
+ * stream with this class so consumers can react — check `status` for the rejection code.
911
913
  */
912
914
  export declare class ConnectionFailedError extends Error {
913
915
  readonly name = 'ConnectionFailedError'
916
+ /**
917
+ * HTTP status code of the rejected connection attempt, if known.
918
+ * Only set when the EventSource implementation exposes it — the polyfill used in
919
+ * Node.js and when custom headers (eg authorization) are required does, while
920
+ * native EventSource implementations (browser and Node.js) do not.
921
+ */
922
+ readonly status?: number
923
+ constructor(
924
+ message?: string,
925
+ options?: ErrorOptions & {
926
+ status?: number
927
+ },
928
+ )
914
929
  }
915
930
 
916
931
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/client",
3
- "version": "7.23.0",
3
+ "version": "7.23.2",
4
4
  "description": "Client for retrieving, creating and patching data from Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -129,7 +129,7 @@
129
129
  "singleQuote": true
130
130
  },
131
131
  "dependencies": {
132
- "@sanity/eventsource": "^5.0.2",
132
+ "@sanity/eventsource": "^5.0.4",
133
133
  "get-it": "^8.8.0",
134
134
  "nanoid": "^3.3.11",
135
135
  "rxjs": "^7.0.0"
@@ -5,11 +5,25 @@ import {type Any} from '../types'
5
5
 
6
6
  /**
7
7
  * @public
8
- * Thrown if the EventSource connection could not be established.
9
- * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
8
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
9
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
10
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
11
+ * stream with this class so consumers can react — check `status` for the rejection code.
10
12
  */
11
13
  export class ConnectionFailedError extends Error {
12
14
  readonly name = 'ConnectionFailedError'
15
+ /**
16
+ * HTTP status code of the rejected connection attempt, if known.
17
+ * Only set when the EventSource implementation exposes it — the polyfill used in
18
+ * Node.js and when custom headers (eg authorization) are required does, while
19
+ * native EventSource implementations (browser and Node.js) do not.
20
+ */
21
+ readonly status?: number
22
+ constructor(message?: string, options: ErrorOptions & {status?: number} = {}) {
23
+ const {status, ...errorOptions} = options
24
+ super(message, errorOptions)
25
+ this.status = status
26
+ }
13
27
  }
14
28
 
15
29
  /**
@@ -147,6 +161,18 @@ function connectWithESInstance<EventTypeName extends string>(
147
161
  // automatically, but in some cases (like when a laptop lid is closed), it will trigger onError
148
162
  // if it can't reconnect.
149
163
  // see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
164
+ // The polyfills expose the HTTP status of a rejected connection on the error event
165
+ // (native EventSource implementations do not). A status means the server rejected the
166
+ // connection attempt, so error out regardless of readyState — the polyfills disagree
167
+ // on whether the connection closes before or after the error event is dispatched —
168
+ // and let `reconnectOnConnectionFailure` classify it (4xx fatal, otherwise retried).
169
+ const rawStatus = (evt as {status?: unknown}).status
170
+ const status = typeof rawStatus === 'number' ? rawStatus : undefined
171
+ if (status !== undefined) {
172
+ observer.error(new ConnectionFailedError('EventSource connection failed', {status}))
173
+ return
174
+ }
175
+
150
176
  if (es.readyState === es.CLOSED) {
151
177
  // In these cases we'll signal to consumers (via the error path) that a retry/reconnect is needed.
152
178
  observer.error(new ConnectionFailedError('EventSource connection failed'))
@@ -11,6 +11,8 @@ import {
11
11
 
12
12
  import {ConnectionFailedError} from './eventsource'
13
13
 
14
+ const RETRYABLE_STATUSES = new Set([408, 429])
15
+
14
16
  /**
15
17
  * Note: connection failure is not the same as network disconnect which may happen more frequent.
16
18
  * The EventSource instance will automatically reconnect in case of a network disconnect, however,
@@ -20,7 +22,19 @@ export function reconnectOnConnectionFailure<T>(): OperatorFunction<T, T | {type
20
22
  return function (source: Observable<T>) {
21
23
  return source.pipe(
22
24
  catchError((err, caught) => {
23
- if (err instanceof ConnectionFailedError) {
25
+ // Only reconnect on transient connection failures. A 4xx response is a
26
+ // rejection, not a transient failure — the server will keep rejecting
27
+ // (eg an expired token), so reconnecting would loop forever. The named
28
+ // exceptions are the explicitly transient 4xx statuses: 408 (request
29
+ // timeout) and 429 (rate limited). Anything else surfaces to the
30
+ // consumer instead.
31
+ if (
32
+ err instanceof ConnectionFailedError &&
33
+ (typeof err.status !== 'number' ||
34
+ err.status < 400 ||
35
+ err.status >= 500 ||
36
+ RETRYABLE_STATUSES.has(err.status))
37
+ ) {
24
38
  return concat(of({type: 'reconnect' as const}), timer(1000).pipe(mergeMap(() => caught)))
25
39
  }
26
40
  return throwError(() => err)
@@ -4,21 +4,6 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SanityClient = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- function _mergeNamespaces(n, m) {
8
- m.forEach(function (e) {
9
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
10
- if (k !== 'default' && !(k in n)) {
11
- var d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: function () { return e[k]; }
15
- });
16
- }
17
- });
18
- });
19
- return Object.freeze(n);
20
- }
21
-
22
7
  const e=!(typeof navigator>"u")&&"ReactNative"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,..."string"==typeof r?{url:r}:r};if(a.timeout=n$1(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf("?");if(-1===r)return {url:t,searchParams:new URLSearchParams};const n=t.slice(0,r),a=t.slice(r+1);if(!e)return {url:n,searchParams:new URLSearchParams(a)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of a.split("&")){const[t,r]=e.split("=");t&&s.append(o$1(t),o$1(r||""));}return {url:n,searchParams:s}}(a.url);for(const[e,o]of Object.entries(a.query)){if(void 0!==o)if(Array.isArray(o))for(const t of o)r.append(e,t);else r.append(e,o);const n=r.toString();n&&(a.url=`${t}?${n}`);}}return a.method=a.body&&!a.method?"POST":(a.method||"GET").toUpperCase(),a};function o$1(e){return decodeURIComponent(e.replace(/\+/g," "))}function n$1(e){if(false===e||0===e)return false;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?n$1(t.timeout):{connect:r,socket:r}}const a$2=/^https?:\/\//i,s$1=function(e){if(!a$2.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};function c$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}
23
8
 
24
9
  const o=["request","response","progress","error","abort"],n=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function s(r$1,i){const a=[],u=n.reduce((e,t)=>(e[t]=e[t]||[],e),{processOptions:[r],validateOptions:[s$1]});function c(e){const t="object"==typeof e&&e.callSiteStack?e.callSiteStack:void 0,r=t?void 0:new Error,n=o.reduce((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return {publish:function(t){for(const r in e)e[r](t);},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o];}}}}(),e),{}),s=(e=>function(t,r,...o){const n="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0, e[t][r])(s,...o),!n||s);r++);return s})(u),a=s("processOptions",e);s("validateOptions",a);const c={options:a,channels:n,applyMiddleware:s};let l;const h=n.request.subscribe(e=>{l=i(e,(o,i)=>((e,o,i)=>{let a=e,u=o;if(!a)try{u=s("onResponse",o,i);}catch(e){u=null,a=e;}if(a=a&&s("onError",a,i),a){if(a instanceof Error){const e=t?.stack||r?.stack;if("string"==typeof e){const r=e.split("\n").slice(t?1:2);r.length>0&&(a.stack+="\n"+r.join("\n"));}}n.error.publish(a);}else u&&n.response.publish(u);})(o,i,e));});n.abort.subscribe(()=>{h(),l&&l.abort();});const d=s("onReturn",n,c);return d===n&&n.request.publish(c),d}return c.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&u.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return n.forEach(t=>{e[t]&&u[t].push(e[t]);}),a.push(e),c},c.clone=()=>s(a,i),r$1.forEach(c.use),c}var i,a$1,u$2=/* @__PURE__ */c$2(function(){if(a$1)return i;a$1=1;var e=function(e){return e.replace(/^\s+|\s+$/g,"")},t=function(e){return "[object Array]"===Object.prototype.toString.call(e)};return i=function(r){if(!r)return {};for(var o=/* @__PURE__ */Object.create(null),n=e(r).split("\n"),s=0;s<n.length;s++){var i=n[s],a=i.indexOf(":"),u=e(i.slice(0,a)).toLowerCase(),c=e(i.slice(a+1));typeof o[u]>"u"?o[u]=c:t(o[u])?o[u].push(c):o[u]=[o[u],c];}return o}}());let c$1 = class c{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#o={};#n;#s={};#i;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#n=void 0;}abort(){this.#n&&this.#n.abort();}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#o[e]=t;}setInit(e,t=true){this.#s=e,this.#i=t;}send(e){const t="arraybuffer"!==this.responseType,r={...this.#s,method:this.#e,headers:this.#o,body:e};"function"==typeof AbortController&&this.#i&&(this.#n=new AbortController,typeof EventTarget<"u"&&this.#n.signal instanceof EventTarget&&(r.signal=this.#n.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then(e=>(e.headers.forEach((e,t)=>{this.#r+=`${t}: ${e}\r\n`;}),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer())).then(e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.();}).catch(e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.();});}};const l$2="function"==typeof XMLHttpRequest?"xhr":"fetch",h$1="xhr"===l$2?XMLHttpRequest:c$1,d$2=(e,t)=>{const r=e.options,o=e.applyMiddleware("finalizeOptions",r),n={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:l$2,context:e});if(s){const e=setTimeout(t,0,null,s);return {abort:()=>clearTimeout(e)}}let i=new h$1;i instanceof c$1&&"object"==typeof o.fetch&&i.setInit(o.fetch,o.useAbortSignal??true);const a=o.headers,d=o.timeout;let p=false,f=false,b=false;if(i.onerror=e=>{m(i instanceof c$1?e instanceof Error?e:new Error(`Request error while attempting to reach ${o.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},i.ontimeout=e=>{m(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},i.onabort=()=>{w(true),p=true;},i.onreadystatechange=function(){d&&(w(),n.socket=setTimeout(()=>y("ESOCKETTIMEDOUT"),d.socket)),!p&&i&&4===i.readyState&&0!==i.status&&function(){if(!(p||f||b)){if(0===i.status)return void m(new Error("Unknown XHR error"));w(),f=true,t(null,{body:i.response||(""===i.responseType||"text"===i.responseType?i.responseText:""),url:o.url,method:o.method,headers:u$2(i.getAllResponseHeaders()),statusCode:i.status,statusMessage:i.statusText});}}();},i.open(o.method,o.url,true),i.withCredentials=!!o.withCredentials,a&&i.setRequestHeader)for(const e in a)a.hasOwnProperty(e)&&i.setRequestHeader(e,a[e]);return o.rawBody&&(i.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:l$2,request:i,context:e}),i.send(o.body||null),d&&(n.connect=setTimeout(()=>y("ETIMEDOUT"),d.connect)),{abort:function(){p=true,i&&i.abort();}};function y(t){b=true,i.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r);}function w(e){(e||p||i&&i.readyState>=2&&n.connect)&&clearTimeout(n.connect),n.socket&&clearTimeout(n.socket);}function m(e){if(f)return;w(true),f=true,i=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=true,r.request=o,t(r);}},p$2=(e=[],t=d$2)=>s(e,t),f="browser";
@@ -2406,6 +2391,17 @@ ${codeFrame(query, { start, end }, description)}${withTag}${withTraceId}`;
2406
2391
  };
2407
2392
  class ConnectionFailedError extends Error {
2408
2393
  name = "ConnectionFailedError";
2394
+ /**
2395
+ * HTTP status code of the rejected connection attempt, if known.
2396
+ * Only set when the EventSource implementation exposes it — the polyfill used in
2397
+ * Node.js and when custom headers (eg authorization) are required does, while
2398
+ * native EventSource implementations (browser and Node.js) do not.
2399
+ */
2400
+ status;
2401
+ constructor(message, options = {}) {
2402
+ const { status, ...errorOptions } = options;
2403
+ super(message, errorOptions), this.status = status;
2404
+ }
2409
2405
  }
2410
2406
  class DisconnectError extends Error {
2411
2407
  name = "DisconnectError";
@@ -2449,6 +2445,11 @@ ${codeFrame(query, { start, end }, description)}${withTag}${withTraceId}`;
2449
2445
  );
2450
2446
  return;
2451
2447
  }
2448
+ const rawStatus = evt.status, status = typeof rawStatus == "number" ? rawStatus : void 0;
2449
+ if (status !== void 0) {
2450
+ observer.error(new ConnectionFailedError("EventSource connection failed", { status }));
2451
+ return;
2452
+ }
2452
2453
  es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError("EventSource connection failed")) : emitReconnect && observer.next({ type: "reconnect" });
2453
2454
  }
2454
2455
  function onOpen() {
@@ -3415,14 +3416,14 @@ ${selectionOpts}`);
3415
3416
  );
3416
3417
  }
3417
3418
  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), {});
3418
- const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = defer(() => Promise.resolve().then(function () { return browser$1; })).pipe(
3419
+ const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = defer(() => Promise.resolve().then(function () { return browser; })).pipe(
3419
3420
  map(({ default: EventSource2 }) => EventSource2),
3420
3421
  shareReplay(1)
3421
- );
3422
+ ), RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429]);
3422
3423
  function reconnectOnConnectionFailure() {
3423
3424
  return function(source) {
3424
3425
  return source.pipe(
3425
- catchError((err, caught) => err instanceof ConnectionFailedError ? concat(of({ type: "reconnect" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err))
3426
+ catchError((err, caught) => err instanceof ConnectionFailedError && (typeof err.status != "number" || err.status < 400 || err.status >= 500 || RETRYABLE_STATUSES.has(err.status)) ? concat(of({ type: "reconnect" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err))
3426
3427
  );
3427
3428
  };
3428
3429
  }
@@ -6472,23 +6473,23 @@ ${selectionOpts}`);
6472
6473
  return eventsource$1.exports;
6473
6474
  }
6474
6475
 
6475
- var browser$2;
6476
+ var browser$1;
6476
6477
  var hasRequiredBrowser;
6477
6478
 
6478
6479
  function requireBrowser () {
6479
- if (hasRequiredBrowser) return browser$2;
6480
+ if (hasRequiredBrowser) return browser$1;
6480
6481
  hasRequiredBrowser = 1;
6481
- browser$2 = requireEventsource().EventSourcePolyfill;
6482
- return browser$2;
6482
+ browser$1 = requireEventsource().EventSourcePolyfill;
6483
+ return browser$1;
6483
6484
  }
6484
6485
 
6485
6486
  var browserExports = /*@__PURE__*/ requireBrowser();
6486
- var browser = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
6487
+ var EventSourcePolyfill = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
6487
6488
 
6488
- var browser$1 = /*#__PURE__*/_mergeNamespaces({
6489
+ var browser = /*#__PURE__*/Object.freeze({
6489
6490
  __proto__: null,
6490
- default: browser
6491
- }, [browserExports]);
6491
+ default: EventSourcePolyfill
6492
+ });
6492
6493
 
6493
6494
  exports.BasePatch = BasePatch;
6494
6495
  exports.BaseTransaction = BaseTransaction;