@sanity/preview-kit
Advanced tools
Comparing version 5.1.1 to 5.1.2
@@ -1,1 +0,6 @@ | ||
import{createContext as o}from"react";const r=o(null);export{r as d};//# sourceMappingURL=context.js.map | ||
import { createContext } from "react"; | ||
const defineStoreContext = createContext(null); | ||
export { | ||
defineStoreContext | ||
}; | ||
//# sourceMappingURL=context.js.map |
@@ -1,1 +0,1249 @@ | ||
var t=Object.defineProperty,e=t=>{throw TypeError(t)},i=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),s=(t,i,s)=>i.has(t)||e("Cannot "+s),n=(t,e,i)=>(s(t,e,"read from private field"),i?i.call(t):e.get(t)),o=(t,i,s)=>i.has(t)?e("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(t):i.set(t,s),h=(t,e,i,n)=>(s(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),r=(t,e,i)=>(s(t,e,"access private method"),i),l=(t,e,i,s)=>({set _(s){h(t,e,s,i)},get _(){return n(t,e,s)}});import{jsxs as a,jsx as c,Fragment as u}from"react/jsx-runtime";import{applySourceDocuments as f}from"@sanity/client/csm";import{useRevalidate as d,useDocumentsInUse as p}from"@sanity/preview-kit-compat";import{applyPatch as g}from"mendoza";import{memo as w,useState as v,useEffect as m,useCallback as S,startTransition as b,useMemo as y}from"react";import{d as _}from"./context.js";var O={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},A={0:8203,1:8204,2:8205,3:65279};new Array(4).fill(String.fromCodePoint(A[0])).join(""),Object.fromEntries(Object.entries(A).map((t=>t.reverse()))),Object.fromEntries(Object.entries(O).map((t=>t.reverse())));var W=`${Object.values(O).map((t=>`\\u{${t.toString(16)}}`)).join("")}`,F=new RegExp(`[${W}]{4,}`,"gu");function M(t){var e;return{cleaned:t.replace(F,""),encoded:(null==(e=t.match(F))?void 0:e[0])||""}}const E="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,T=new Set,z="object"==typeof process&&process?process:{},k=(t,e,i,s)=>{"function"==typeof z.emitWarning?z.emitWarning(t,e,i,s):console.error(`[${i}] ${e}: ${t}`)};let x=globalThis.AbortController,C=globalThis.AbortSignal;var R;if(typeof x>"u"){C=class{constructor(){i(this,"onabort"),i(this,"_onabort",[]),i(this,"reason"),i(this,"aborted",!1)}addEventListener(t,e){this._onabort.push(e)}},x=class{constructor(){i(this,"signal",new C),e()}abort(t){var e,i;if(!this.signal.aborted){this.signal.reason=t,this.signal.aborted=!0;for(const e of this.signal._onabort)e(t);null==(i=(e=this.signal).onabort)||i.call(e,t)}}};let t="1"!==(null==(R=z.env)?void 0:R.LRU_CACHE_IGNORE_AC_WARNING);const e=()=>{t&&(t=!1,k("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}const j=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),D=t=>j(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?I:null:null;class I extends Array{constructor(t){super(t),this.fill(0)}}var L;const G=class t{constructor(e,s){if(i(this,"heap"),i(this,"length"),!n(t,L))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new s(e),this.length=0}static create(e){const i=D(e);if(!i)return[];h(t,L,!0);const s=new t(e,i);return h(t,L,!1),s}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}};L=new WeakMap,o(G,L,!1);let U=G;var N,$,P,q,H,J,B,K,V,Q,X,Y,Z,tt,et,it,st,nt,ot,ht,rt,lt,at,ct,ut,ft,dt,pt,gt,wt,vt,mt,St,bt,yt,_t,Ot,At,Wt,Ft,Mt,Et,Tt,zt,kt;const xt=class t{constructor(e){o(this,ft),o(this,P),o(this,q),o(this,H),o(this,J),o(this,B),o(this,K),i(this,"ttl"),i(this,"ttlResolution"),i(this,"ttlAutopurge"),i(this,"updateAgeOnGet"),i(this,"updateAgeOnHas"),i(this,"allowStale"),i(this,"noDisposeOnSet"),i(this,"noUpdateTTL"),i(this,"maxEntrySize"),i(this,"sizeCalculation"),i(this,"noDeleteOnFetchRejection"),i(this,"noDeleteOnStaleGet"),i(this,"allowStaleOnFetchAbort"),i(this,"allowStaleOnFetchRejection"),i(this,"ignoreFetchAbort"),o(this,V),o(this,Q),o(this,X),o(this,Y),o(this,Z),o(this,tt),o(this,et),o(this,it),o(this,st),o(this,nt),o(this,ot),o(this,ht),o(this,rt),o(this,lt),o(this,at),o(this,ct),o(this,ut),o(this,pt,(()=>{})),o(this,gt,(()=>{})),o(this,wt,(()=>{})),o(this,vt,(()=>!1)),o(this,St,(t=>{})),o(this,bt,((t,e,i)=>{})),o(this,yt,((t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),i(this,N,"LRUCache");const{max:s=0,ttl:l,ttlResolution:a=1,ttlAutopurge:c,updateAgeOnGet:u,updateAgeOnHas:f,allowStale:d,dispose:p,disposeAfter:g,noDisposeOnSet:w,noUpdateTTL:v,maxSize:m=0,maxEntrySize:S=0,sizeCalculation:b,fetchMethod:y,memoMethod:_,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:W,allowStaleOnFetchAbort:F,ignoreFetchAbort:M}=e;if(0!==s&&!j(s))throw new TypeError("max option must be a nonnegative integer");const E=s?D(s):Array;if(!E)throw new Error("invalid max value: "+s);if(h(this,P,s),h(this,q,m),this.maxEntrySize=S||n(this,q),this.sizeCalculation=b,this.sizeCalculation){if(!n(this,q)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==_&&"function"!=typeof _)throw new TypeError("memoMethod must be a function if defined");if(h(this,K,_),void 0!==y&&"function"!=typeof y)throw new TypeError("fetchMethod must be a function if specified");if(h(this,B,y),h(this,ct,!!y),h(this,X,new Map),h(this,Y,new Array(s).fill(void 0)),h(this,Z,new Array(s).fill(void 0)),h(this,tt,new E(s)),h(this,et,new E(s)),h(this,it,0),h(this,st,0),h(this,nt,U.create(s)),h(this,V,0),h(this,Q,0),"function"==typeof p&&h(this,H,p),"function"==typeof g?(h(this,J,g),h(this,ot,[])):(h(this,J,void 0),h(this,ot,void 0)),h(this,at,!!n(this,H)),h(this,ut,!!n(this,J)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!W,this.allowStaleOnFetchAbort=!!F,this.ignoreFetchAbort=!!M,0!==this.maxEntrySize){if(0!==n(this,q)&&!j(n(this,q)))throw new TypeError("maxSize must be a positive integer if specified");if(!j(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");r(this,ft,mt).call(this)}if(this.allowStale=!!d,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!u,this.updateAgeOnHas=!!f,this.ttlResolution=j(a)||0===a?a:1,this.ttlAutopurge=!!c,this.ttl=l||0,this.ttl){if(!j(this.ttl))throw new TypeError("ttl must be a positive integer if specified");r(this,ft,dt).call(this)}if(0===n(this,P)&&0===this.ttl&&0===n(this,q))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,P)&&!n(this,q)){const e="LRU_CACHE_UNBOUNDED";(t=>!T.has(t))(e)&&(T.add(e),k("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,t))}}static unsafeExposeInternals(t){return{starts:n(t,rt),ttls:n(t,lt),sizes:n(t,ht),keyMap:n(t,X),keyList:n(t,Y),valList:n(t,Z),next:n(t,tt),prev:n(t,et),get head(){return n(t,it)},get tail(){return n(t,st)},free:n(t,nt),isBackgroundFetch:e=>{var i;return r(i=t,ft,Mt).call(i,e)},backgroundFetch:(e,i,s,n)=>{var o;return r(o=t,ft,Ft).call(o,e,i,s,n)},moveToTail:e=>{var i;return r(i=t,ft,Tt).call(i,e)},indexes:e=>{var i;return r(i=t,ft,_t).call(i,e)},rindexes:e=>{var i;return r(i=t,ft,Ot).call(i,e)},isStale:e=>{var i;return n(i=t,vt).call(i,e)}}}get max(){return n(this,P)}get maxSize(){return n(this,q)}get calculatedSize(){return n(this,Q)}get size(){return n(this,V)}get fetchMethod(){return n(this,B)}get memoMethod(){return n(this,K)}get dispose(){return n(this,H)}get disposeAfter(){return n(this,J)}getRemainingTTL(t){return n(this,X).has(t)?1/0:0}*entries(){for(const t of r(this,ft,_t).call(this))void 0!==n(this,Z)[t]&&void 0!==n(this,Y)[t]&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield[n(this,Y)[t],n(this,Z)[t]])}*rentries(){for(const t of r(this,ft,Ot).call(this))void 0!==n(this,Z)[t]&&void 0!==n(this,Y)[t]&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield[n(this,Y)[t],n(this,Z)[t]])}*keys(){for(const t of r(this,ft,_t).call(this)){const e=n(this,Y)[t];void 0!==e&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield e)}}*rkeys(){for(const t of r(this,ft,Ot).call(this)){const e=n(this,Y)[t];void 0!==e&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield e)}}*values(){for(const t of r(this,ft,_t).call(this))void 0!==n(this,Z)[t]&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield n(this,Z)[t])}*rvalues(){for(const t of r(this,ft,Ot).call(this))void 0!==n(this,Z)[t]&&!r(this,ft,Mt).call(this,n(this,Z)[t])&&(yield n(this,Z)[t])}[($=Symbol.iterator,N=Symbol.toStringTag,$)](){return this.entries()}find(t,e={}){for(const i of r(this,ft,_t).call(this)){const s=n(this,Z)[i],o=r(this,ft,Mt).call(this,s)?s.__staleWhileFetching:s;if(void 0!==o&&t(o,n(this,Y)[i],this))return this.get(n(this,Y)[i],e)}}forEach(t,e=this){for(const i of r(this,ft,_t).call(this)){const s=n(this,Z)[i],o=r(this,ft,Mt).call(this,s)?s.__staleWhileFetching:s;void 0!==o&&t.call(e,o,n(this,Y)[i],this)}}rforEach(t,e=this){for(const i of r(this,ft,Ot).call(this)){const s=n(this,Z)[i],o=r(this,ft,Mt).call(this,s)?s.__staleWhileFetching:s;void 0!==o&&t.call(e,o,n(this,Y)[i],this)}}purgeStale(){let t=!1;for(const e of r(this,ft,Ot).call(this,{allowStale:!0}))n(this,vt).call(this,e)&&(r(this,ft,zt).call(this,n(this,Y)[e],"expire"),t=!0);return t}info(t){const e=n(this,X).get(t);if(void 0===e)return;const i=n(this,Z)[e],s=r(this,ft,Mt).call(this,i)?i.__staleWhileFetching:i;if(void 0===s)return;const o={value:s};if(n(this,lt)&&n(this,rt)){const t=n(this,lt)[e],i=n(this,rt)[e];if(t&&i){const e=t-(E.now()-i);o.ttl=e,o.start=Date.now()}}return n(this,ht)&&(o.size=n(this,ht)[e]),o}dump(){const t=[];for(const e of r(this,ft,_t).call(this,{allowStale:!0})){const i=n(this,Y)[e],s=n(this,Z)[e],o=r(this,ft,Mt).call(this,s)?s.__staleWhileFetching:s;if(void 0===o||void 0===i)continue;const h={value:o};if(n(this,lt)&&n(this,rt)){h.ttl=n(this,lt)[e];const t=E.now()-n(this,rt)[e];h.start=Math.floor(Date.now()-t)}n(this,ht)&&(h.size=n(this,ht)[e]),t.unshift([i,h])}return t}load(t){this.clear();for(const[e,i]of t){if(i.start){const t=Date.now()-i.start;i.start=E.now()-t}this.set(e,i.value,i)}}set(t,e,i={}){var s,o,a,c,u;if(void 0===e)return this.delete(t),this;const{ttl:f=this.ttl,start:d,noDisposeOnSet:p=this.noDisposeOnSet,sizeCalculation:g=this.sizeCalculation,status:w}=i;let{noUpdateTTL:v=this.noUpdateTTL}=i;const m=n(this,yt).call(this,t,e,i.size||0,g);if(this.maxEntrySize&&m>this.maxEntrySize)return w&&(w.set="miss",w.maxEntrySizeExceeded=!0),r(this,ft,zt).call(this,t,"set"),this;let S=0===n(this,V)?void 0:n(this,X).get(t);if(void 0===S)S=0===n(this,V)?n(this,st):0!==n(this,nt).length?n(this,nt).pop():n(this,V)===n(this,P)?r(this,ft,Wt).call(this,!1):n(this,V),n(this,Y)[S]=t,n(this,Z)[S]=e,n(this,X).set(t,S),n(this,tt)[n(this,st)]=S,n(this,et)[S]=n(this,st),h(this,st,S),l(this,V)._++,n(this,bt).call(this,S,m,w),w&&(w.set="add"),v=!1;else{r(this,ft,Tt).call(this,S);const i=n(this,Z)[S];if(e!==i){if(n(this,ct)&&r(this,ft,Mt).call(this,i)){i.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:e}=i;void 0!==e&&!p&&(n(this,at)&&(null==(s=n(this,H))||s.call(this,e,t,"set")),n(this,ut)&&(null==(o=n(this,ot))||o.push([e,t,"set"])))}else p||(n(this,at)&&(null==(a=n(this,H))||a.call(this,i,t,"set")),n(this,ut)&&(null==(c=n(this,ot))||c.push([i,t,"set"])));if(n(this,St).call(this,S),n(this,bt).call(this,S,m,w),n(this,Z)[S]=e,w){w.set="replace";const t=i&&r(this,ft,Mt).call(this,i)?i.__staleWhileFetching:i;void 0!==t&&(w.oldValue=t)}}else w&&(w.set="update")}if(0!==f&&!n(this,lt)&&r(this,ft,dt).call(this),n(this,lt)&&(v||n(this,wt).call(this,S,f,d),w&&n(this,gt).call(this,w,S)),!p&&n(this,ut)&&n(this,ot)){const t=n(this,ot);let e;for(;e=null==t?void 0:t.shift();)null==(u=n(this,J))||u.call(this,...e)}return this}pop(){var t;try{for(;n(this,V);){const t=n(this,Z)[n(this,it)];if(r(this,ft,Wt).call(this,!0),r(this,ft,Mt).call(this,t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(void 0!==t)return t}}finally{if(n(this,ut)&&n(this,ot)){const e=n(this,ot);let i;for(;i=null==e?void 0:e.shift();)null==(t=n(this,J))||t.call(this,...i)}}}has(t,e={}){const{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,o=n(this,X).get(t);if(void 0!==o){const t=n(this,Z)[o];if(r(this,ft,Mt).call(this,t)&&void 0===t.__staleWhileFetching)return!1;if(!n(this,vt).call(this,o))return i&&n(this,pt).call(this,o),s&&(s.has="hit",n(this,gt).call(this,s,o)),!0;s&&(s.has="stale",n(this,gt).call(this,s,o))}else s&&(s.has="miss");return!1}peek(t,e={}){const{allowStale:i=this.allowStale}=e,s=n(this,X).get(t);if(void 0===s||!i&&n(this,vt).call(this,s))return;const o=n(this,Z)[s];return r(this,ft,Mt).call(this,o)?o.__staleWhileFetching:o}async fetch(t,e={}){const{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:w,forceRefresh:v=!1,status:m,signal:S}=e;if(!n(this,ct))return m&&(m.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:o,status:m});const b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:o,ttl:h,noDisposeOnSet:l,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:m,signal:S};let y=n(this,X).get(t);if(void 0===y){m&&(m.fetch="miss");const e=r(this,ft,Ft).call(this,t,y,b,w);return e.__returned=e}{const e=n(this,Z)[y];if(r(this,ft,Mt).call(this,e)){const t=i&&void 0!==e.__staleWhileFetching;return m&&(m.fetch="inflight",t&&(m.returnedStale=!0)),t?e.__staleWhileFetching:e.__returned=e}const o=n(this,vt).call(this,y);if(!v&&!o)return m&&(m.fetch="hit"),r(this,ft,Tt).call(this,y),s&&n(this,pt).call(this,y),m&&n(this,gt).call(this,m,y),e;const h=r(this,ft,Ft).call(this,t,y,b,w),l=void 0!==h.__staleWhileFetching&&i;return m&&(m.fetch=o?"stale":"refresh",l&&o&&(m.returnedStale=!0)),l?h.__staleWhileFetching:h.__returned=h}}async forceFetch(t,e={}){const i=await this.fetch(t,e);if(void 0===i)throw new Error("fetch() returned undefined");return i}memo(t,e={}){const i=n(this,K);if(!i)throw new Error("no memoMethod provided to constructor");const{context:s,forceRefresh:o,...h}=e,r=this.get(t,h);if(!o&&void 0!==r)return r;const l=i(t,r,{options:h,context:s});return this.set(t,l,h),l}get(t,e={}){const{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:h}=e,l=n(this,X).get(t);if(void 0!==l){const e=n(this,Z)[l],a=r(this,ft,Mt).call(this,e);return h&&n(this,gt).call(this,h,l),n(this,vt).call(this,l)?(h&&(h.get="stale"),a?(h&&i&&void 0!==e.__staleWhileFetching&&(h.returnedStale=!0),i?e.__staleWhileFetching:void 0):(o||r(this,ft,zt).call(this,t,"expire"),h&&i&&(h.returnedStale=!0),i?e:void 0)):(h&&(h.get="hit"),a?e.__staleWhileFetching:(r(this,ft,Tt).call(this,l),s&&n(this,pt).call(this,l),e))}h&&(h.get="miss")}delete(t){return r(this,ft,zt).call(this,t,"delete")}clear(){return r(this,ft,kt).call(this,"delete")}};P=new WeakMap,q=new WeakMap,H=new WeakMap,J=new WeakMap,B=new WeakMap,K=new WeakMap,V=new WeakMap,Q=new WeakMap,X=new WeakMap,Y=new WeakMap,Z=new WeakMap,tt=new WeakMap,et=new WeakMap,it=new WeakMap,st=new WeakMap,nt=new WeakMap,ot=new WeakMap,ht=new WeakMap,rt=new WeakMap,lt=new WeakMap,at=new WeakMap,ct=new WeakMap,ut=new WeakMap,ft=new WeakSet,dt=function(){const t=new I(n(this,P)),e=new I(n(this,P));h(this,lt,t),h(this,rt,e),h(this,wt,((i,s,o=E.now())=>{if(e[i]=0!==s?o:0,t[i]=s,0!==s&&this.ttlAutopurge){const t=setTimeout((()=>{n(this,vt).call(this,i)&&r(this,ft,zt).call(this,n(this,Y)[i],"expire")}),s+1);t.unref&&t.unref()}})),h(this,pt,(i=>{e[i]=0!==t[i]?E.now():0})),h(this,gt,((n,o)=>{if(t[o]){const h=t[o],r=e[o];if(!h||!r)return;n.ttl=h,n.start=r,n.now=i||s();const l=n.now-r;n.remainingTTL=h-l}}));let i=0;const s=()=>{const t=E.now();if(this.ttlResolution>0){i=t;const e=setTimeout((()=>i=0),this.ttlResolution);e.unref&&e.unref()}return t};this.getRemainingTTL=o=>{const h=n(this,X).get(o);if(void 0===h)return 0;const r=t[h],l=e[h];if(!r||!l)return 1/0;return r-((i||s())-l)},h(this,vt,(n=>{const o=e[n],h=t[n];return!!h&&!!o&&(i||s())-o>h}))},pt=new WeakMap,gt=new WeakMap,wt=new WeakMap,vt=new WeakMap,mt=function(){const t=new I(n(this,P));h(this,Q,0),h(this,ht,t),h(this,St,(e=>{h(this,Q,n(this,Q)-t[e]),t[e]=0})),h(this,yt,((t,e,i,s)=>{if(r(this,ft,Mt).call(this,e))return 0;if(!j(i)){if(!s)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof s)throw new TypeError("sizeCalculation must be a function");if(i=s(e,t),!j(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return i})),h(this,bt,((e,i,s)=>{if(t[e]=i,n(this,q)){const i=n(this,q)-t[e];for(;n(this,Q)>i;)r(this,ft,Wt).call(this,!0)}h(this,Q,n(this,Q)+t[e]),s&&(s.entrySize=i,s.totalCalculatedSize=n(this,Q))}))},St=new WeakMap,bt=new WeakMap,yt=new WeakMap,_t=function*({allowStale:t=this.allowStale}={}){if(n(this,V))for(let e=n(this,st);r(this,ft,At).call(this,e)&&((t||!n(this,vt).call(this,e))&&(yield e),e!==n(this,it));)e=n(this,et)[e]},Ot=function*({allowStale:t=this.allowStale}={}){if(n(this,V))for(let e=n(this,it);r(this,ft,At).call(this,e)&&((t||!n(this,vt).call(this,e))&&(yield e),e!==n(this,st));)e=n(this,tt)[e]},At=function(t){return void 0!==t&&n(this,X).get(n(this,Y)[t])===t},Wt=function(t){var e,i;const s=n(this,it),o=n(this,Y)[s],a=n(this,Z)[s];return n(this,ct)&&r(this,ft,Mt).call(this,a)?a.__abortController.abort(new Error("evicted")):(n(this,at)||n(this,ut))&&(n(this,at)&&(null==(e=n(this,H))||e.call(this,a,o,"evict")),n(this,ut)&&(null==(i=n(this,ot))||i.push([a,o,"evict"]))),n(this,St).call(this,s),t&&(n(this,Y)[s]=void 0,n(this,Z)[s]=void 0,n(this,nt).push(s)),1===n(this,V)?(h(this,it,h(this,st,0)),n(this,nt).length=0):h(this,it,n(this,tt)[s]),n(this,X).delete(o),l(this,V)._--,s},Ft=function(t,e,i,s){const o=void 0===e?void 0:n(this,Z)[e];if(r(this,ft,Mt).call(this,o))return o;const h=new x,{signal:l}=i;null==l||l.addEventListener("abort",(()=>h.abort(l.reason)),{signal:h.signal});const a={signal:h.signal,options:i,context:s},c=(s,o=!1)=>{const{aborted:l}=h.signal,c=i.ignoreFetchAbort&&void 0!==s;if(i.status&&(l&&!o?(i.status.fetchAborted=!0,i.status.fetchError=h.signal.reason,c&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!c&&!o)return u(h.signal.reason);const d=f;return n(this,Z)[e]===f&&(void 0===s?d.__staleWhileFetching?n(this,Z)[e]=d.__staleWhileFetching:r(this,ft,zt).call(this,t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,s,a.options))),s},u=s=>{const{aborted:o}=h.signal,l=o&&i.allowStaleOnFetchAbort,a=l||i.allowStaleOnFetchRejection,c=a||i.noDeleteOnFetchRejection,u=f;if(n(this,Z)[e]===f&&(c&&void 0!==u.__staleWhileFetching?l||(n(this,Z)[e]=u.__staleWhileFetching):r(this,ft,zt).call(this,t,"fetch")),a)return i.status&&void 0!==u.__staleWhileFetching&&(i.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw s};i.status&&(i.status.fetchDispatched=!0);const f=new Promise(((e,s)=>{var r;const l=null==(r=n(this,B))?void 0:r.call(this,t,o,a);l&&l instanceof Promise&&l.then((t=>e(void 0===t?void 0:t)),s),h.signal.addEventListener("abort",(()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(e(void 0),i.allowStaleOnFetchAbort&&(e=t=>c(t,!0)))}))})).then(c,(t=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=t),u(t)))),d=Object.assign(f,{__abortController:h,__staleWhileFetching:o,__returned:void 0});return void 0===e?(this.set(t,d,{...a.options,status:void 0}),e=n(this,X).get(t)):n(this,Z)[e]=d,d},Mt=function(t){if(!n(this,ct))return!1;const e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof x},Et=function(t,e){n(this,et)[e]=t,n(this,tt)[t]=e},Tt=function(t){t!==n(this,st)&&(t===n(this,it)?h(this,it,n(this,tt)[t]):r(this,ft,Et).call(this,n(this,et)[t],n(this,tt)[t]),r(this,ft,Et).call(this,n(this,st),t),h(this,st,t))},zt=function(t,e){var i,s,o,a;let c=!1;if(0!==n(this,V)){const o=n(this,X).get(t);if(void 0!==o)if(c=!0,1===n(this,V))r(this,ft,kt).call(this,e);else{n(this,St).call(this,o);const a=n(this,Z)[o];if(r(this,ft,Mt).call(this,a)?a.__abortController.abort(new Error("deleted")):(n(this,at)||n(this,ut))&&(n(this,at)&&(null==(i=n(this,H))||i.call(this,a,t,e)),n(this,ut)&&(null==(s=n(this,ot))||s.push([a,t,e]))),n(this,X).delete(t),n(this,Y)[o]=void 0,n(this,Z)[o]=void 0,o===n(this,st))h(this,st,n(this,et)[o]);else if(o===n(this,it))h(this,it,n(this,tt)[o]);else{const t=n(this,et)[o];n(this,tt)[t]=n(this,tt)[o];const e=n(this,tt)[o];n(this,et)[e]=n(this,et)[o]}l(this,V)._--,n(this,nt).push(o)}}if(n(this,ut)&&null!=(o=n(this,ot))&&o.length){const t=n(this,ot);let e;for(;e=null==t?void 0:t.shift();)null==(a=n(this,J))||a.call(this,...e)}return c},kt=function(t){var e,i,s;for(const s of r(this,ft,Ot).call(this,{allowStale:!0})){const o=n(this,Z)[s];if(r(this,ft,Mt).call(this,o))o.__abortController.abort(new Error("deleted"));else{const h=n(this,Y)[s];n(this,at)&&(null==(e=n(this,H))||e.call(this,o,h,t)),n(this,ut)&&(null==(i=n(this,ot))||i.push([o,h,t]))}}if(n(this,X).clear(),n(this,Z).fill(void 0),n(this,Y).fill(void 0),n(this,lt)&&n(this,rt)&&(n(this,lt).fill(0),n(this,rt).fill(0)),n(this,ht)&&n(this,ht).fill(0),h(this,it,0),h(this,st,0),n(this,nt).length=0,h(this,Q,0),h(this,V,0),n(this,ut)&&n(this,ot)){const t=n(this,ot);let e;for(;e=null==t?void 0:t.shift();)null==(s=n(this,J))||s.call(this,...e)}};const Ct=new xt({max:500}),Rt=w((function(t){const{children:e,refreshInterval:i=1e4,token:s}=t;if(!t.client)throw new Error("Missing a `client` prop with a configured Sanity client instance");const[n]=v((()=>{const{requestTagPrefix:e,resultSourceMap:i}=t.client.config();return t.client.withConfig({requestTagPrefix:e||"sanity.preview-kit",resultSourceMap:"withKeyArraySelector"!==i||"withKeyArraySelector",...s&&{token:s,useCdn:!1,perspective:"previewDrafts",ignoreBrowserTokenWarning:!0}})})),[o]=v((()=>t.logger));m((()=>{o&&o.log(`[@sanity/preview-kit]: With the current configuration you can expect that: Updates that can be traced using Content Source Maps will be applied in real-time. Other updates will be applied every ${i}ms.`)}),[o,i]);const[h,r]=v([]),[l]=v((()=>new Map)),u=function(t){const[e]=v((()=>new Map)),i=S(((i,s,n,o)=>{e.has(i)||(e.set(i,{query:s,params:n,listeners:new Set}),b((()=>t((t=>t.includes(i)?t:[...t,i])))));const h=e.get(i);if(!h||!h.listeners)throw new TypeError("Inconsistent cache for key: "+i);const{listeners:r}=h;return r.add(o),()=>{r.delete(o),0===r.size&&(e.delete(i),b((()=>t((t=>t.includes(i)?t.filter((t=>t!==i)):t)))))}}),[e,t]);return y((()=>({cache:e,subscribe:i})),[e,i])}(r),[f]=v((()=>function(t,e,i){const s=Nt(e,i);return l.has(s)||l.set(s,{result:t,resultSourceMap:{}}),{subscribe:t=>{const n=u.subscribe(s,e,i,t);return()=>n()},getSnapshot:()=>{var t;return null==(t=l.get(s))?void 0:t.result}}})),[d,p]=v([]),[g]=v((()=>new Map)),w=S((t=>{var e;const i=new Set;if(g.clear(),null!=(e=t.documents)&&e.length)for(const e of t.documents)i.add(e._id),g.set(e._id,e);b((()=>p((t=>{const e=Array.from(new Set([...t,...i]));return JSON.stringify(e.sort())===JSON.stringify(t.sort())?t:e}))))}),[g]);return a(_.Provider,{value:f,children:[e,c(It,{cache:u.cache,client:n,setTurboIds:p,snapshots:l,turboIds:d,docsInUse:g}),h.map((t=>{if(!u.cache.has(t))return null;const{query:e,params:s,listeners:o}=u.cache.get(t);return c(jt,{client:n,listeners:o,params:s,query:e,refreshInterval:i,snapshots:l,turboIdsFromSourceMap:w},t)}))]})}));Rt.displayName="LiveStoreProvider";const jt=w((function(t){const{client:e,refreshInterval:i,query:s,params:n,listeners:o,snapshots:h,turboIdsFromSourceMap:r}=t,{projectId:l,dataset:a}=y((()=>{const{projectId:t,dataset:i}=e.config();return{projectId:t,dataset:i}}),[e]),[c,u]=v(null);if(c)throw c;const[f,p]=d({refreshInterval:i}),g="refresh"===f||"inflight"===f;return m((()=>{if(!g)return;let t=!1;const i=new AbortController;const c=p();return async function(){const{signal:c}=i,{result:u,resultSourceMap:f}=await e.fetch(s,n,{signal:c,filterResponse:!1});if(!c.aborted){h.set(Nt(s,n),{result:Ut(l,a,u,f),resultSourceMap:null!=f?f:{}}),f&&r(f);for(const t of o.values())t();t=!0}}().catch((t=>{"AbortError"!==t.name&&u(t)})).finally(c),()=>{t||i.abort()}}),[e,a,o,n,l,s,g,h,p,r]),null}));function Dt(t,e,i){return`${t}-${e}-${i}`}jt.displayName="QuerySubscription";const It=w((function(t){const{client:e,snapshots:i,cache:s,turboIds:n,setTurboIds:o,docsInUse:h}=t,{projectId:r,dataset:l}=y((()=>{const{projectId:t,dataset:i}=e.config();return{projectId:t,dataset:i}}),[e]);m((()=>{var t,e;const r=new Set;h.clear();for(const{query:n,params:o}of s.values()){const s=Nt(n,o),l=i.get(s);if(l&&null!=(e=null==(t=l.resultSourceMap)?void 0:t.documents)&&e.length)for(const t of l.resultSourceMap.documents)r.add(t._id),h.set(t._id,t)}const l=[...r].sort();JSON.stringify(n)!==JSON.stringify(l)&&b((()=>o(l)))}),[s,o,i,n,h]),p(h,r,l);const[a,f]=v([]);m((()=>{const t=new Set(a.flat()),e=new Set;for(const i of n)!t.has(i)&&!Ct.has(Dt(r,l,i))&&e.add(i);const i=[...e].slice(0,100);0!==i.length&&b((()=>f((t=>[...t.slice(-100),i]))))}),[a,l,r,n]);const[d,w]=v();return m((()=>{const t=e.listen("*",{},{events:["mutation"],effectFormat:"mendoza",includePreviousRevision:!1,includeResult:!1,tag:"turbo"}).subscribe((t=>{var e,i;if("mutation"!==t.type||null==(i=null==(e=t.effects)?void 0:e.apply)||!i.length)return;const s=Dt(r,l,t.documentId),n=Ct.peek(s);if(n){const e={...n};delete e._rev;const i=g(e,t.effects.apply);Ct.set(s,i)}b((()=>w(t.documentId)))}));return()=>t.unsubscribe()}),[e,l,r]),m((()=>{var t,e,o;if(!d||!n.includes(d))return;const h=[];for(const[s,n]of i.entries())null!=(e=null==(t=n.resultSourceMap)?void 0:t.documents)&&e.length&&(n.result=Ut(r,l,n.result,n.resultSourceMap),h.push(s));for(const t of h){const e=null==(o=s.get(t))?void 0:o.listeners;if(e)for(const t of e)t()}b((()=>w(void 0)))}),[s,l,d,r,i,n]),c(u,{children:a.map((t=>c(Lt,{client:e,projectId:r,dataset:l,ids:t},JSON.stringify(t))))})}));It.displayName="Turbo";const Lt=w((function(t){const{client:e,projectId:i,dataset:s,ids:n}=t;return m((()=>{const t=n.filter((t=>!Ct.has(Dt(i,s,t))));0!==t.length&&e.getDocuments(t).then((t=>{for(const e of t)e&&null!=e&&e._id&&Ct.set(Dt(i,s,e._id),e)}),console.error)}),[e,s,n,i]),null}));Lt.displayName="GetDocuments";let Gt=!1;function Ut(t,e,i,s){return s?f(i,s,(i=>{if(!i._projectId)return Ct.get(Dt(t,e,i._id));Gt||(console.warn("Cross dataset references are not supported yet, ignoring source document",i),Gt=!0)}),((t,{previousValue:e})=>{if("string"==typeof t&&"string"==typeof e){const{encoded:i}=M(e),{cleaned:s}=M(t);return`${i}${s}`}return t}),"previewDrafts"):i}function Nt(t,e){return`${t}-${JSON.stringify(e)}`}export{Rt as default};//# sourceMappingURL=LiveQueryProvider.js.map | ||
var __defProp = Object.defineProperty; | ||
var __typeError = (msg) => { | ||
throw TypeError(msg); | ||
}; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value; | ||
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value), __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); | ||
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); | ||
var __privateWrapper = (obj, member, setter, getter) => ({ | ||
set _(value) { | ||
__privateSet(obj, member, value, setter); | ||
}, | ||
get _() { | ||
return __privateGet(obj, member, getter); | ||
} | ||
}); | ||
import { jsxs, jsx, Fragment } from "react/jsx-runtime"; | ||
import { applySourceDocuments } from "@sanity/client/csm"; | ||
import { useRevalidate, useDocumentsInUse } from "@sanity/preview-kit-compat"; | ||
import { applyPatch } from "mendoza"; | ||
import { memo, useState, useEffect, useCallback, startTransition, useMemo } from "react"; | ||
import { defineStoreContext } from "./context.js"; | ||
var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }; | ||
new Array(4).fill(String.fromCodePoint(c[0])).join(""); | ||
Object.fromEntries(Object.entries(c).map((t) => t.reverse())); | ||
Object.fromEntries(Object.entries(s).map((t) => t.reverse())); | ||
var S = `${Object.values(s).map((t) => `\\u{${t.toString(16)}}`).join("")}`, f = new RegExp(`[${S}]{4,}`, "gu"); | ||
function _(t) { | ||
var e; | ||
return { cleaned: t.replace(f, ""), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || "" }; | ||
} | ||
const perf = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date, warned = /* @__PURE__ */ new Set(), PROCESS = typeof process == "object" && process ? process : {}, emitWarning = (msg, type, code, fn) => { | ||
typeof PROCESS.emitWarning == "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`); | ||
}; | ||
let AC = globalThis.AbortController, AS = globalThis.AbortSignal; | ||
var _a; | ||
if (typeof AC > "u") { | ||
AS = class { | ||
constructor() { | ||
__publicField(this, "onabort"); | ||
__publicField(this, "_onabort", []); | ||
__publicField(this, "reason"); | ||
__publicField(this, "aborted", !1); | ||
} | ||
addEventListener(_2, fn) { | ||
this._onabort.push(fn); | ||
} | ||
}, AC = class { | ||
constructor() { | ||
__publicField(this, "signal", new AS()); | ||
warnACPolyfill(); | ||
} | ||
abort(reason) { | ||
var _a3, _b2; | ||
if (!this.signal.aborted) { | ||
this.signal.reason = reason, this.signal.aborted = !0; | ||
for (const fn of this.signal._onabort) | ||
fn(reason); | ||
(_b2 = (_a3 = this.signal).onabort) == null || _b2.call(_a3, reason); | ||
} | ||
} | ||
}; | ||
let printACPolyfillWarning = ((_a = PROCESS.env) == null ? void 0 : _a.LRU_CACHE_IGNORE_AC_WARNING) !== "1"; | ||
const warnACPolyfill = () => { | ||
printACPolyfillWarning && (printACPolyfillWarning = !1, emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill)); | ||
}; | ||
} | ||
const shouldWarn = (code) => !warned.has(code), isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n), getUintArray = (max) => isPosInt(max) ? max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null : null; | ||
class ZeroArray extends Array { | ||
constructor(size) { | ||
super(size), this.fill(0); | ||
} | ||
} | ||
var _constructing; | ||
const _Stack = class _Stack { | ||
constructor(max, HeapCls) { | ||
__publicField(this, "heap"); | ||
__publicField(this, "length"); | ||
if (!__privateGet(_Stack, _constructing)) | ||
throw new TypeError("instantiate Stack using Stack.create(n)"); | ||
this.heap = new HeapCls(max), this.length = 0; | ||
} | ||
static create(max) { | ||
const HeapCls = getUintArray(max); | ||
if (!HeapCls) | ||
return []; | ||
__privateSet(_Stack, _constructing, !0); | ||
const s2 = new _Stack(max, HeapCls); | ||
return __privateSet(_Stack, _constructing, !1), s2; | ||
} | ||
push(n) { | ||
this.heap[this.length++] = n; | ||
} | ||
pop() { | ||
return this.heap[--this.length]; | ||
} | ||
}; | ||
_constructing = new WeakMap(), // private constructor | ||
__privateAdd(_Stack, _constructing, !1); | ||
let Stack = _Stack; | ||
var _a2, _b, _max, _maxSize, _dispose, _disposeAfter, _fetchMethod, _memoMethod, _size, _calculatedSize, _keyMap, _keyList, _valList, _next, _prev, _head, _tail, _free, _disposed, _sizes, _starts, _ttls, _hasDispose, _hasFetchMethod, _hasDisposeAfter, _LRUCache_instances, initializeTTLTracking_fn, _updateItemAge, _statusTTL, _setItemTTL, _isStale, initializeSizeTracking_fn, _removeItemSize, _addItemSize, _requireSize, indexes_fn, rindexes_fn, isValidIndex_fn, evict_fn, backgroundFetch_fn, isBackgroundFetch_fn, connect_fn, moveToTail_fn, delete_fn, clear_fn; | ||
const _LRUCache = class _LRUCache { | ||
constructor(options) { | ||
__privateAdd(this, _LRUCache_instances); | ||
// options that cannot be changed without disaster | ||
__privateAdd(this, _max); | ||
__privateAdd(this, _maxSize); | ||
__privateAdd(this, _dispose); | ||
__privateAdd(this, _disposeAfter); | ||
__privateAdd(this, _fetchMethod); | ||
__privateAdd(this, _memoMethod); | ||
/** | ||
* {@link LRUCache.OptionsBase.ttl} | ||
*/ | ||
__publicField(this, "ttl"); | ||
/** | ||
* {@link LRUCache.OptionsBase.ttlResolution} | ||
*/ | ||
__publicField(this, "ttlResolution"); | ||
/** | ||
* {@link LRUCache.OptionsBase.ttlAutopurge} | ||
*/ | ||
__publicField(this, "ttlAutopurge"); | ||
/** | ||
* {@link LRUCache.OptionsBase.updateAgeOnGet} | ||
*/ | ||
__publicField(this, "updateAgeOnGet"); | ||
/** | ||
* {@link LRUCache.OptionsBase.updateAgeOnHas} | ||
*/ | ||
__publicField(this, "updateAgeOnHas"); | ||
/** | ||
* {@link LRUCache.OptionsBase.allowStale} | ||
*/ | ||
__publicField(this, "allowStale"); | ||
/** | ||
* {@link LRUCache.OptionsBase.noDisposeOnSet} | ||
*/ | ||
__publicField(this, "noDisposeOnSet"); | ||
/** | ||
* {@link LRUCache.OptionsBase.noUpdateTTL} | ||
*/ | ||
__publicField(this, "noUpdateTTL"); | ||
/** | ||
* {@link LRUCache.OptionsBase.maxEntrySize} | ||
*/ | ||
__publicField(this, "maxEntrySize"); | ||
/** | ||
* {@link LRUCache.OptionsBase.sizeCalculation} | ||
*/ | ||
__publicField(this, "sizeCalculation"); | ||
/** | ||
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} | ||
*/ | ||
__publicField(this, "noDeleteOnFetchRejection"); | ||
/** | ||
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet} | ||
*/ | ||
__publicField(this, "noDeleteOnStaleGet"); | ||
/** | ||
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} | ||
*/ | ||
__publicField(this, "allowStaleOnFetchAbort"); | ||
/** | ||
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} | ||
*/ | ||
__publicField(this, "allowStaleOnFetchRejection"); | ||
/** | ||
* {@link LRUCache.OptionsBase.ignoreFetchAbort} | ||
*/ | ||
__publicField(this, "ignoreFetchAbort"); | ||
// computed properties | ||
__privateAdd(this, _size); | ||
__privateAdd(this, _calculatedSize); | ||
__privateAdd(this, _keyMap); | ||
__privateAdd(this, _keyList); | ||
__privateAdd(this, _valList); | ||
__privateAdd(this, _next); | ||
__privateAdd(this, _prev); | ||
__privateAdd(this, _head); | ||
__privateAdd(this, _tail); | ||
__privateAdd(this, _free); | ||
__privateAdd(this, _disposed); | ||
__privateAdd(this, _sizes); | ||
__privateAdd(this, _starts); | ||
__privateAdd(this, _ttls); | ||
__privateAdd(this, _hasDispose); | ||
__privateAdd(this, _hasFetchMethod); | ||
__privateAdd(this, _hasDisposeAfter); | ||
// conditionally set private methods related to TTL | ||
__privateAdd(this, _updateItemAge, () => { | ||
}); | ||
__privateAdd(this, _statusTTL, () => { | ||
}); | ||
__privateAdd(this, _setItemTTL, () => { | ||
}); | ||
/* c8 ignore stop */ | ||
__privateAdd(this, _isStale, () => !1); | ||
__privateAdd(this, _removeItemSize, (_i) => { | ||
}); | ||
__privateAdd(this, _addItemSize, (_i, _s, _st) => { | ||
}); | ||
__privateAdd(this, _requireSize, (_k, _v, size, sizeCalculation) => { | ||
if (size || sizeCalculation) | ||
throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache"); | ||
return 0; | ||
}); | ||
/** | ||
* A String value that is used in the creation of the default string | ||
* description of an object. Called by the built-in method | ||
* `Object.prototype.toString`. | ||
*/ | ||
__publicField(this, _a2, "LRUCache"); | ||
const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options; | ||
if (max !== 0 && !isPosInt(max)) | ||
throw new TypeError("max option must be a nonnegative integer"); | ||
const UintArray = max ? getUintArray(max) : Array; | ||
if (!UintArray) | ||
throw new Error("invalid max value: " + max); | ||
if (__privateSet(this, _max, max), __privateSet(this, _maxSize, maxSize), this.maxEntrySize = maxEntrySize || __privateGet(this, _maxSize), this.sizeCalculation = sizeCalculation, this.sizeCalculation) { | ||
if (!__privateGet(this, _maxSize) && !this.maxEntrySize) | ||
throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize"); | ||
if (typeof this.sizeCalculation != "function") | ||
throw new TypeError("sizeCalculation set to non-function"); | ||
} | ||
if (memoMethod !== void 0 && typeof memoMethod != "function") | ||
throw new TypeError("memoMethod must be a function if defined"); | ||
if (__privateSet(this, _memoMethod, memoMethod), fetchMethod !== void 0 && typeof fetchMethod != "function") | ||
throw new TypeError("fetchMethod must be a function if specified"); | ||
if (__privateSet(this, _fetchMethod, fetchMethod), __privateSet(this, _hasFetchMethod, !!fetchMethod), __privateSet(this, _keyMap, /* @__PURE__ */ new Map()), __privateSet(this, _keyList, new Array(max).fill(void 0)), __privateSet(this, _valList, new Array(max).fill(void 0)), __privateSet(this, _next, new UintArray(max)), __privateSet(this, _prev, new UintArray(max)), __privateSet(this, _head, 0), __privateSet(this, _tail, 0), __privateSet(this, _free, Stack.create(max)), __privateSet(this, _size, 0), __privateSet(this, _calculatedSize, 0), typeof dispose == "function" && __privateSet(this, _dispose, dispose), typeof disposeAfter == "function" ? (__privateSet(this, _disposeAfter, disposeAfter), __privateSet(this, _disposed, [])) : (__privateSet(this, _disposeAfter, void 0), __privateSet(this, _disposed, void 0)), __privateSet(this, _hasDispose, !!__privateGet(this, _dispose)), __privateSet(this, _hasDisposeAfter, !!__privateGet(this, _disposeAfter)), this.noDisposeOnSet = !!noDisposeOnSet, this.noUpdateTTL = !!noUpdateTTL, this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection, this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection, this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort, this.ignoreFetchAbort = !!ignoreFetchAbort, this.maxEntrySize !== 0) { | ||
if (__privateGet(this, _maxSize) !== 0 && !isPosInt(__privateGet(this, _maxSize))) | ||
throw new TypeError("maxSize must be a positive integer if specified"); | ||
if (!isPosInt(this.maxEntrySize)) | ||
throw new TypeError("maxEntrySize must be a positive integer if specified"); | ||
__privateMethod(this, _LRUCache_instances, initializeSizeTracking_fn).call(this); | ||
} | ||
if (this.allowStale = !!allowStale, this.noDeleteOnStaleGet = !!noDeleteOnStaleGet, this.updateAgeOnGet = !!updateAgeOnGet, this.updateAgeOnHas = !!updateAgeOnHas, this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1, this.ttlAutopurge = !!ttlAutopurge, this.ttl = ttl || 0, this.ttl) { | ||
if (!isPosInt(this.ttl)) | ||
throw new TypeError("ttl must be a positive integer if specified"); | ||
__privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this); | ||
} | ||
if (__privateGet(this, _max) === 0 && this.ttl === 0 && __privateGet(this, _maxSize) === 0) | ||
throw new TypeError("At least one of max, maxSize, or ttl is required"); | ||
if (!this.ttlAutopurge && !__privateGet(this, _max) && !__privateGet(this, _maxSize)) { | ||
const code = "LRU_CACHE_UNBOUNDED"; | ||
shouldWarn(code) && (warned.add(code), emitWarning("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", code, _LRUCache)); | ||
} | ||
} | ||
/** | ||
* Do not call this method unless you need to inspect the | ||
* inner workings of the cache. If anything returned by this | ||
* object is modified in any way, strange breakage may occur. | ||
* | ||
* These fields are private for a reason! | ||
* | ||
* @internal | ||
*/ | ||
static unsafeExposeInternals(c2) { | ||
return { | ||
// properties | ||
starts: __privateGet(c2, _starts), | ||
ttls: __privateGet(c2, _ttls), | ||
sizes: __privateGet(c2, _sizes), | ||
keyMap: __privateGet(c2, _keyMap), | ||
keyList: __privateGet(c2, _keyList), | ||
valList: __privateGet(c2, _valList), | ||
next: __privateGet(c2, _next), | ||
prev: __privateGet(c2, _prev), | ||
get head() { | ||
return __privateGet(c2, _head); | ||
}, | ||
get tail() { | ||
return __privateGet(c2, _tail); | ||
}, | ||
free: __privateGet(c2, _free), | ||
// methods | ||
isBackgroundFetch: (p) => { | ||
var _a3; | ||
return __privateMethod(_a3 = c2, _LRUCache_instances, isBackgroundFetch_fn).call(_a3, p); | ||
}, | ||
backgroundFetch: (k, index, options, context) => { | ||
var _a3; | ||
return __privateMethod(_a3 = c2, _LRUCache_instances, backgroundFetch_fn).call(_a3, k, index, options, context); | ||
}, | ||
moveToTail: (index) => { | ||
var _a3; | ||
return __privateMethod(_a3 = c2, _LRUCache_instances, moveToTail_fn).call(_a3, index); | ||
}, | ||
indexes: (options) => { | ||
var _a3; | ||
return __privateMethod(_a3 = c2, _LRUCache_instances, indexes_fn).call(_a3, options); | ||
}, | ||
rindexes: (options) => { | ||
var _a3; | ||
return __privateMethod(_a3 = c2, _LRUCache_instances, rindexes_fn).call(_a3, options); | ||
}, | ||
isStale: (index) => { | ||
var _a3; | ||
return __privateGet(_a3 = c2, _isStale).call(_a3, index); | ||
} | ||
}; | ||
} | ||
// Protected read-only members | ||
/** | ||
* {@link LRUCache.OptionsBase.max} (read-only) | ||
*/ | ||
get max() { | ||
return __privateGet(this, _max); | ||
} | ||
/** | ||
* {@link LRUCache.OptionsBase.maxSize} (read-only) | ||
*/ | ||
get maxSize() { | ||
return __privateGet(this, _maxSize); | ||
} | ||
/** | ||
* The total computed size of items in the cache (read-only) | ||
*/ | ||
get calculatedSize() { | ||
return __privateGet(this, _calculatedSize); | ||
} | ||
/** | ||
* The number of items stored in the cache (read-only) | ||
*/ | ||
get size() { | ||
return __privateGet(this, _size); | ||
} | ||
/** | ||
* {@link LRUCache.OptionsBase.fetchMethod} (read-only) | ||
*/ | ||
get fetchMethod() { | ||
return __privateGet(this, _fetchMethod); | ||
} | ||
get memoMethod() { | ||
return __privateGet(this, _memoMethod); | ||
} | ||
/** | ||
* {@link LRUCache.OptionsBase.dispose} (read-only) | ||
*/ | ||
get dispose() { | ||
return __privateGet(this, _dispose); | ||
} | ||
/** | ||
* {@link LRUCache.OptionsBase.disposeAfter} (read-only) | ||
*/ | ||
get disposeAfter() { | ||
return __privateGet(this, _disposeAfter); | ||
} | ||
/** | ||
* Return the number of ms left in the item's TTL. If item is not in cache, | ||
* returns `0`. Returns `Infinity` if item is in cache without a defined TTL. | ||
*/ | ||
getRemainingTTL(key) { | ||
return __privateGet(this, _keyMap).has(key) ? 1 / 0 : 0; | ||
} | ||
/** | ||
* Return a generator yielding `[key, value]` pairs, | ||
* in order from most recently used to least recently used. | ||
*/ | ||
*entries() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) | ||
__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]]); | ||
} | ||
/** | ||
* Inverse order version of {@link LRUCache.entries} | ||
* | ||
* Return a generator yielding `[key, value]` pairs, | ||
* in order from least recently used to most recently used. | ||
*/ | ||
*rentries() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) | ||
__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]]); | ||
} | ||
/** | ||
* Return a generator yielding the keys in the cache, | ||
* in order from most recently used to least recently used. | ||
*/ | ||
*keys() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) { | ||
const k = __privateGet(this, _keyList)[i]; | ||
k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield k); | ||
} | ||
} | ||
/** | ||
* Inverse order version of {@link LRUCache.keys} | ||
* | ||
* Return a generator yielding the keys in the cache, | ||
* in order from least recently used to most recently used. | ||
*/ | ||
*rkeys() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) { | ||
const k = __privateGet(this, _keyList)[i]; | ||
k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield k); | ||
} | ||
} | ||
/** | ||
* Return a generator yielding the values in the cache, | ||
* in order from most recently used to least recently used. | ||
*/ | ||
*values() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) | ||
__privateGet(this, _valList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield __privateGet(this, _valList)[i]); | ||
} | ||
/** | ||
* Inverse order version of {@link LRUCache.values} | ||
* | ||
* Return a generator yielding the values in the cache, | ||
* in order from least recently used to most recently used. | ||
*/ | ||
*rvalues() { | ||
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) | ||
__privateGet(this, _valList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i]) && (yield __privateGet(this, _valList)[i]); | ||
} | ||
/** | ||
* Iterating over the cache itself yields the same results as | ||
* {@link LRUCache.entries} | ||
*/ | ||
[(_b = Symbol.iterator, _a2 = Symbol.toStringTag, _b)]() { | ||
return this.entries(); | ||
} | ||
/** | ||
* Find a value for which the supplied fn method returns a truthy value, | ||
* similar to `Array.find()`. fn is called as `fn(value, key, cache)`. | ||
*/ | ||
find(fn, getOptions = {}) { | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) { | ||
const v = __privateGet(this, _valList)[i], value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
if (value !== void 0 && fn(value, __privateGet(this, _keyList)[i], this)) | ||
return this.get(__privateGet(this, _keyList)[i], getOptions); | ||
} | ||
} | ||
/** | ||
* Call the supplied function on each item in the cache, in order from most | ||
* recently used to least recently used. | ||
* | ||
* `fn` is called as `fn(value, key, cache)`. | ||
* | ||
* If `thisp` is provided, function will be called in the `this`-context of | ||
* the provided object, or the cache if no `thisp` object is provided. | ||
* | ||
* Does not update age or recenty of use, or iterate over stale values. | ||
*/ | ||
forEach(fn, thisp = this) { | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) { | ||
const v = __privateGet(this, _valList)[i], value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
value !== void 0 && fn.call(thisp, value, __privateGet(this, _keyList)[i], this); | ||
} | ||
} | ||
/** | ||
* The same as {@link LRUCache.forEach} but items are iterated over in | ||
* reverse order. (ie, less recently used items are iterated over first.) | ||
*/ | ||
rforEach(fn, thisp = this) { | ||
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) { | ||
const v = __privateGet(this, _valList)[i], value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
value !== void 0 && fn.call(thisp, value, __privateGet(this, _keyList)[i], this); | ||
} | ||
} | ||
/** | ||
* Delete any stale entries. Returns true if anything was removed, | ||
* false otherwise. | ||
*/ | ||
purgeStale() { | ||
let deleted = !1; | ||
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: !0 })) | ||
__privateGet(this, _isStale).call(this, i) && (__privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[i], "expire"), deleted = !0); | ||
return deleted; | ||
} | ||
/** | ||
* Get the extended info about a given entry, to get its value, size, and | ||
* TTL info simultaneously. Returns `undefined` if the key is not present. | ||
* | ||
* Unlike {@link LRUCache#dump}, which is designed to be portable and survive | ||
* serialization, the `start` value is always the current timestamp, and the | ||
* `ttl` is a calculated remaining time to live (negative if expired). | ||
* | ||
* Always returns stale values, if their info is found in the cache, so be | ||
* sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) | ||
* if relevant. | ||
*/ | ||
info(key) { | ||
const i = __privateGet(this, _keyMap).get(key); | ||
if (i === void 0) | ||
return; | ||
const v = __privateGet(this, _valList)[i], value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
if (value === void 0) | ||
return; | ||
const entry = { value }; | ||
if (__privateGet(this, _ttls) && __privateGet(this, _starts)) { | ||
const ttl = __privateGet(this, _ttls)[i], start = __privateGet(this, _starts)[i]; | ||
if (ttl && start) { | ||
const remain = ttl - (perf.now() - start); | ||
entry.ttl = remain, entry.start = Date.now(); | ||
} | ||
} | ||
return __privateGet(this, _sizes) && (entry.size = __privateGet(this, _sizes)[i]), entry; | ||
} | ||
/** | ||
* Return an array of [key, {@link LRUCache.Entry}] tuples which can be | ||
* passed to {@link LRLUCache#load}. | ||
* | ||
* The `start` fields are calculated relative to a portable `Date.now()` | ||
* timestamp, even if `performance.now()` is available. | ||
* | ||
* Stale entries are always included in the `dump`, even if | ||
* {@link LRUCache.OptionsBase.allowStale} is false. | ||
* | ||
* Note: this returns an actual array, not a generator, so it can be more | ||
* easily passed around. | ||
*/ | ||
dump() { | ||
const arr = []; | ||
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this, { allowStale: !0 })) { | ||
const key = __privateGet(this, _keyList)[i], v = __privateGet(this, _valList)[i], value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
if (value === void 0 || key === void 0) | ||
continue; | ||
const entry = { value }; | ||
if (__privateGet(this, _ttls) && __privateGet(this, _starts)) { | ||
entry.ttl = __privateGet(this, _ttls)[i]; | ||
const age = perf.now() - __privateGet(this, _starts)[i]; | ||
entry.start = Math.floor(Date.now() - age); | ||
} | ||
__privateGet(this, _sizes) && (entry.size = __privateGet(this, _sizes)[i]), arr.unshift([key, entry]); | ||
} | ||
return arr; | ||
} | ||
/** | ||
* Reset the cache and load in the items in entries in the order listed. | ||
* | ||
* The shape of the resulting cache may be different if the same options are | ||
* not used in both caches. | ||
* | ||
* The `start` fields are assumed to be calculated relative to a portable | ||
* `Date.now()` timestamp, even if `performance.now()` is available. | ||
*/ | ||
load(arr) { | ||
this.clear(); | ||
for (const [key, entry] of arr) { | ||
if (entry.start) { | ||
const age = Date.now() - entry.start; | ||
entry.start = perf.now() - age; | ||
} | ||
this.set(key, entry.value, entry); | ||
} | ||
} | ||
/** | ||
* Add a value to the cache. | ||
* | ||
* Note: if `undefined` is specified as a value, this is an alias for | ||
* {@link LRUCache#delete} | ||
* | ||
* Fields on the {@link LRUCache.SetOptions} options param will override | ||
* their corresponding values in the constructor options for the scope | ||
* of this single `set()` operation. | ||
* | ||
* If `start` is provided, then that will set the effective start | ||
* time for the TTL calculation. Note that this must be a previous | ||
* value of `performance.now()` if supported, or a previous value of | ||
* `Date.now()` if not. | ||
* | ||
* Options object may also include `size`, which will prevent | ||
* calling the `sizeCalculation` function and just use the specified | ||
* number if it is a positive integer, and `noDisposeOnSet` which | ||
* will prevent calling a `dispose` function in the case of | ||
* overwrites. | ||
* | ||
* If the `size` (or return value of `sizeCalculation`) for a given | ||
* entry is greater than `maxEntrySize`, then the item will not be | ||
* added to the cache. | ||
* | ||
* Will update the recency of the entry. | ||
* | ||
* If the value is `undefined`, then this is an alias for | ||
* `cache.delete(key)`. `undefined` is never stored in the cache. | ||
*/ | ||
set(k, v, setOptions = {}) { | ||
var _a3, _b2, _c, _d, _e; | ||
if (v === void 0) | ||
return this.delete(k), this; | ||
const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions; | ||
let { noUpdateTTL = this.noUpdateTTL } = setOptions; | ||
const size = __privateGet(this, _requireSize).call(this, k, v, setOptions.size || 0, sizeCalculation); | ||
if (this.maxEntrySize && size > this.maxEntrySize) | ||
return status && (status.set = "miss", status.maxEntrySizeExceeded = !0), __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "set"), this; | ||
let index = __privateGet(this, _size) === 0 ? void 0 : __privateGet(this, _keyMap).get(k); | ||
if (index === void 0) | ||
index = __privateGet(this, _size) === 0 ? __privateGet(this, _tail) : __privateGet(this, _free).length !== 0 ? __privateGet(this, _free).pop() : __privateGet(this, _size) === __privateGet(this, _max) ? __privateMethod(this, _LRUCache_instances, evict_fn).call(this, !1) : __privateGet(this, _size), __privateGet(this, _keyList)[index] = k, __privateGet(this, _valList)[index] = v, __privateGet(this, _keyMap).set(k, index), __privateGet(this, _next)[__privateGet(this, _tail)] = index, __privateGet(this, _prev)[index] = __privateGet(this, _tail), __privateSet(this, _tail, index), __privateWrapper(this, _size)._++, __privateGet(this, _addItemSize).call(this, index, size, status), status && (status.set = "add"), noUpdateTTL = !1; | ||
else { | ||
__privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index); | ||
const oldVal = __privateGet(this, _valList)[index]; | ||
if (v !== oldVal) { | ||
if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal)) { | ||
oldVal.__abortController.abort(new Error("replaced")); | ||
const { __staleWhileFetching: s2 } = oldVal; | ||
s2 !== void 0 && !noDisposeOnSet && (__privateGet(this, _hasDispose) && ((_a3 = __privateGet(this, _dispose)) == null || _a3.call(this, s2, k, "set")), __privateGet(this, _hasDisposeAfter) && ((_b2 = __privateGet(this, _disposed)) == null || _b2.push([s2, k, "set"]))); | ||
} else noDisposeOnSet || (__privateGet(this, _hasDispose) && ((_c = __privateGet(this, _dispose)) == null || _c.call(this, oldVal, k, "set")), __privateGet(this, _hasDisposeAfter) && ((_d = __privateGet(this, _disposed)) == null || _d.push([oldVal, k, "set"]))); | ||
if (__privateGet(this, _removeItemSize).call(this, index), __privateGet(this, _addItemSize).call(this, index, size, status), __privateGet(this, _valList)[index] = v, status) { | ||
status.set = "replace"; | ||
const oldValue = oldVal && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal) ? oldVal.__staleWhileFetching : oldVal; | ||
oldValue !== void 0 && (status.oldValue = oldValue); | ||
} | ||
} else status && (status.set = "update"); | ||
} | ||
if (ttl !== 0 && !__privateGet(this, _ttls) && __privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this), __privateGet(this, _ttls) && (noUpdateTTL || __privateGet(this, _setItemTTL).call(this, index, ttl, start), status && __privateGet(this, _statusTTL).call(this, status, index)), !noDisposeOnSet && __privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) { | ||
const dt = __privateGet(this, _disposed); | ||
let task; | ||
for (; task = dt == null ? void 0 : dt.shift(); ) | ||
(_e = __privateGet(this, _disposeAfter)) == null || _e.call(this, ...task); | ||
} | ||
return this; | ||
} | ||
/** | ||
* Evict the least recently used item, returning its value or | ||
* `undefined` if cache is empty. | ||
*/ | ||
pop() { | ||
var _a3; | ||
try { | ||
for (; __privateGet(this, _size); ) { | ||
const val = __privateGet(this, _valList)[__privateGet(this, _head)]; | ||
if (__privateMethod(this, _LRUCache_instances, evict_fn).call(this, !0), __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, val)) { | ||
if (val.__staleWhileFetching) | ||
return val.__staleWhileFetching; | ||
} else if (val !== void 0) | ||
return val; | ||
} | ||
} finally { | ||
if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) { | ||
const dt = __privateGet(this, _disposed); | ||
let task; | ||
for (; task = dt == null ? void 0 : dt.shift(); ) | ||
(_a3 = __privateGet(this, _disposeAfter)) == null || _a3.call(this, ...task); | ||
} | ||
} | ||
} | ||
/** | ||
* Check if a key is in the cache, without updating the recency of use. | ||
* Will return false if the item is stale, even though it is technically | ||
* in the cache. | ||
* | ||
* Check if a key is in the cache, without updating the recency of | ||
* use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set | ||
* to `true` in either the options or the constructor. | ||
* | ||
* Will return `false` if the item is stale, even though it is technically in | ||
* the cache. The difference can be determined (if it matters) by using a | ||
* `status` argument, and inspecting the `has` field. | ||
* | ||
* Will not update item age unless | ||
* {@link LRUCache.OptionsBase.updateAgeOnHas} is set. | ||
*/ | ||
has(k, hasOptions = {}) { | ||
const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions, index = __privateGet(this, _keyMap).get(k); | ||
if (index !== void 0) { | ||
const v = __privateGet(this, _valList)[index]; | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) && v.__staleWhileFetching === void 0) | ||
return !1; | ||
if (__privateGet(this, _isStale).call(this, index)) | ||
status && (status.has = "stale", __privateGet(this, _statusTTL).call(this, status, index)); | ||
else return updateAgeOnHas && __privateGet(this, _updateItemAge).call(this, index), status && (status.has = "hit", __privateGet(this, _statusTTL).call(this, status, index)), !0; | ||
} else status && (status.has = "miss"); | ||
return !1; | ||
} | ||
/** | ||
* Like {@link LRUCache#get} but doesn't update recency or delete stale | ||
* items. | ||
* | ||
* Returns `undefined` if the item is stale, unless | ||
* {@link LRUCache.OptionsBase.allowStale} is set. | ||
*/ | ||
peek(k, peekOptions = {}) { | ||
const { allowStale = this.allowStale } = peekOptions, index = __privateGet(this, _keyMap).get(k); | ||
if (index === void 0 || !allowStale && __privateGet(this, _isStale).call(this, index)) | ||
return; | ||
const v = __privateGet(this, _valList)[index]; | ||
return __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v; | ||
} | ||
async fetch(k, fetchOptions = {}) { | ||
const { | ||
// get options | ||
allowStale = this.allowStale, | ||
updateAgeOnGet = this.updateAgeOnGet, | ||
noDeleteOnStaleGet = this.noDeleteOnStaleGet, | ||
// set options | ||
ttl = this.ttl, | ||
noDisposeOnSet = this.noDisposeOnSet, | ||
size = 0, | ||
sizeCalculation = this.sizeCalculation, | ||
noUpdateTTL = this.noUpdateTTL, | ||
// fetch exclusive options | ||
noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, | ||
allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, | ||
ignoreFetchAbort = this.ignoreFetchAbort, | ||
allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, | ||
context, | ||
forceRefresh = !1, | ||
status, | ||
signal | ||
} = fetchOptions; | ||
if (!__privateGet(this, _hasFetchMethod)) | ||
return status && (status.fetch = "get"), this.get(k, { | ||
allowStale, | ||
updateAgeOnGet, | ||
noDeleteOnStaleGet, | ||
status | ||
}); | ||
const options = { | ||
allowStale, | ||
updateAgeOnGet, | ||
noDeleteOnStaleGet, | ||
ttl, | ||
noDisposeOnSet, | ||
size, | ||
sizeCalculation, | ||
noUpdateTTL, | ||
noDeleteOnFetchRejection, | ||
allowStaleOnFetchRejection, | ||
allowStaleOnFetchAbort, | ||
ignoreFetchAbort, | ||
status, | ||
signal | ||
}; | ||
let index = __privateGet(this, _keyMap).get(k); | ||
if (index === void 0) { | ||
status && (status.fetch = "miss"); | ||
const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options, context); | ||
return p.__returned = p; | ||
} else { | ||
const v = __privateGet(this, _valList)[index]; | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) { | ||
const stale = allowStale && v.__staleWhileFetching !== void 0; | ||
return status && (status.fetch = "inflight", stale && (status.returnedStale = !0)), stale ? v.__staleWhileFetching : v.__returned = v; | ||
} | ||
const isStale = __privateGet(this, _isStale).call(this, index); | ||
if (!forceRefresh && !isStale) | ||
return status && (status.fetch = "hit"), __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index), updateAgeOnGet && __privateGet(this, _updateItemAge).call(this, index), status && __privateGet(this, _statusTTL).call(this, status, index), v; | ||
const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options, context), staleVal = p.__staleWhileFetching !== void 0 && allowStale; | ||
return status && (status.fetch = isStale ? "stale" : "refresh", staleVal && isStale && (status.returnedStale = !0)), staleVal ? p.__staleWhileFetching : p.__returned = p; | ||
} | ||
} | ||
async forceFetch(k, fetchOptions = {}) { | ||
const v = await this.fetch(k, fetchOptions); | ||
if (v === void 0) | ||
throw new Error("fetch() returned undefined"); | ||
return v; | ||
} | ||
memo(k, memoOptions = {}) { | ||
const memoMethod = __privateGet(this, _memoMethod); | ||
if (!memoMethod) | ||
throw new Error("no memoMethod provided to constructor"); | ||
const { context, forceRefresh, ...options } = memoOptions, v = this.get(k, options); | ||
if (!forceRefresh && v !== void 0) | ||
return v; | ||
const vv = memoMethod(k, v, { | ||
options, | ||
context | ||
}); | ||
return this.set(k, vv, options), vv; | ||
} | ||
/** | ||
* Return a value from the cache. Will update the recency of the cache | ||
* entry found. | ||
* | ||
* If the key is not found, get() will return `undefined`. | ||
*/ | ||
get(k, getOptions = {}) { | ||
const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions, index = __privateGet(this, _keyMap).get(k); | ||
if (index !== void 0) { | ||
const value = __privateGet(this, _valList)[index], fetching = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, value); | ||
return status && __privateGet(this, _statusTTL).call(this, status, index), __privateGet(this, _isStale).call(this, index) ? (status && (status.get = "stale"), fetching ? (status && allowStale && value.__staleWhileFetching !== void 0 && (status.returnedStale = !0), allowStale ? value.__staleWhileFetching : void 0) : (noDeleteOnStaleGet || __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "expire"), status && allowStale && (status.returnedStale = !0), allowStale ? value : void 0)) : (status && (status.get = "hit"), fetching ? value.__staleWhileFetching : (__privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index), updateAgeOnGet && __privateGet(this, _updateItemAge).call(this, index), value)); | ||
} else status && (status.get = "miss"); | ||
} | ||
/** | ||
* Deletes a key out of the cache. | ||
* | ||
* Returns true if the key was deleted, false otherwise. | ||
*/ | ||
delete(k) { | ||
return __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "delete"); | ||
} | ||
/** | ||
* Clear the cache entirely, throwing away all values. | ||
*/ | ||
clear() { | ||
return __privateMethod(this, _LRUCache_instances, clear_fn).call(this, "delete"); | ||
} | ||
}; | ||
_max = new WeakMap(), _maxSize = new WeakMap(), _dispose = new WeakMap(), _disposeAfter = new WeakMap(), _fetchMethod = new WeakMap(), _memoMethod = new WeakMap(), _size = new WeakMap(), _calculatedSize = new WeakMap(), _keyMap = new WeakMap(), _keyList = new WeakMap(), _valList = new WeakMap(), _next = new WeakMap(), _prev = new WeakMap(), _head = new WeakMap(), _tail = new WeakMap(), _free = new WeakMap(), _disposed = new WeakMap(), _sizes = new WeakMap(), _starts = new WeakMap(), _ttls = new WeakMap(), _hasDispose = new WeakMap(), _hasFetchMethod = new WeakMap(), _hasDisposeAfter = new WeakMap(), _LRUCache_instances = new WeakSet(), initializeTTLTracking_fn = function() { | ||
const ttls = new ZeroArray(__privateGet(this, _max)), starts = new ZeroArray(__privateGet(this, _max)); | ||
__privateSet(this, _ttls, ttls), __privateSet(this, _starts, starts), __privateSet(this, _setItemTTL, (index, ttl, start = perf.now()) => { | ||
if (starts[index] = ttl !== 0 ? start : 0, ttls[index] = ttl, ttl !== 0 && this.ttlAutopurge) { | ||
const t = setTimeout(() => { | ||
__privateGet(this, _isStale).call(this, index) && __privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[index], "expire"); | ||
}, ttl + 1); | ||
t.unref && t.unref(); | ||
} | ||
}), __privateSet(this, _updateItemAge, (index) => { | ||
starts[index] = ttls[index] !== 0 ? perf.now() : 0; | ||
}), __privateSet(this, _statusTTL, (status, index) => { | ||
if (ttls[index]) { | ||
const ttl = ttls[index], start = starts[index]; | ||
if (!ttl || !start) | ||
return; | ||
status.ttl = ttl, status.start = start, status.now = cachedNow || getNow(); | ||
const age = status.now - start; | ||
status.remainingTTL = ttl - age; | ||
} | ||
}); | ||
let cachedNow = 0; | ||
const getNow = () => { | ||
const n = perf.now(); | ||
if (this.ttlResolution > 0) { | ||
cachedNow = n; | ||
const t = setTimeout(() => cachedNow = 0, this.ttlResolution); | ||
t.unref && t.unref(); | ||
} | ||
return n; | ||
}; | ||
this.getRemainingTTL = (key) => { | ||
const index = __privateGet(this, _keyMap).get(key); | ||
if (index === void 0) | ||
return 0; | ||
const ttl = ttls[index], start = starts[index]; | ||
if (!ttl || !start) | ||
return 1 / 0; | ||
const age = (cachedNow || getNow()) - start; | ||
return ttl - age; | ||
}, __privateSet(this, _isStale, (index) => { | ||
const s2 = starts[index], t = ttls[index]; | ||
return !!t && !!s2 && (cachedNow || getNow()) - s2 > t; | ||
}); | ||
}, _updateItemAge = new WeakMap(), _statusTTL = new WeakMap(), _setItemTTL = new WeakMap(), _isStale = new WeakMap(), initializeSizeTracking_fn = function() { | ||
const sizes = new ZeroArray(__privateGet(this, _max)); | ||
__privateSet(this, _calculatedSize, 0), __privateSet(this, _sizes, sizes), __privateSet(this, _removeItemSize, (index) => { | ||
__privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) - sizes[index]), sizes[index] = 0; | ||
}), __privateSet(this, _requireSize, (k, v, size, sizeCalculation) => { | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) | ||
return 0; | ||
if (!isPosInt(size)) | ||
if (sizeCalculation) { | ||
if (typeof sizeCalculation != "function") | ||
throw new TypeError("sizeCalculation must be a function"); | ||
if (size = sizeCalculation(v, k), !isPosInt(size)) | ||
throw new TypeError("sizeCalculation return invalid (expect positive integer)"); | ||
} else | ||
throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set."); | ||
return size; | ||
}), __privateSet(this, _addItemSize, (index, size, status) => { | ||
if (sizes[index] = size, __privateGet(this, _maxSize)) { | ||
const maxSize = __privateGet(this, _maxSize) - sizes[index]; | ||
for (; __privateGet(this, _calculatedSize) > maxSize; ) | ||
__privateMethod(this, _LRUCache_instances, evict_fn).call(this, !0); | ||
} | ||
__privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) + sizes[index]), status && (status.entrySize = size, status.totalCalculatedSize = __privateGet(this, _calculatedSize)); | ||
}); | ||
}, _removeItemSize = new WeakMap(), _addItemSize = new WeakMap(), _requireSize = new WeakMap(), indexes_fn = function* ({ allowStale = this.allowStale } = {}) { | ||
if (__privateGet(this, _size)) | ||
for (let i = __privateGet(this, _tail); !(!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i) || ((allowStale || !__privateGet(this, _isStale).call(this, i)) && (yield i), i === __privateGet(this, _head))); ) | ||
i = __privateGet(this, _prev)[i]; | ||
}, rindexes_fn = function* ({ allowStale = this.allowStale } = {}) { | ||
if (__privateGet(this, _size)) | ||
for (let i = __privateGet(this, _head); !(!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i) || ((allowStale || !__privateGet(this, _isStale).call(this, i)) && (yield i), i === __privateGet(this, _tail))); ) | ||
i = __privateGet(this, _next)[i]; | ||
}, isValidIndex_fn = function(index) { | ||
return index !== void 0 && __privateGet(this, _keyMap).get(__privateGet(this, _keyList)[index]) === index; | ||
}, evict_fn = function(free) { | ||
var _a3, _b2; | ||
const head = __privateGet(this, _head), k = __privateGet(this, _keyList)[head], v = __privateGet(this, _valList)[head]; | ||
return __privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__abortController.abort(new Error("evicted")) : (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) && (__privateGet(this, _hasDispose) && ((_a3 = __privateGet(this, _dispose)) == null || _a3.call(this, v, k, "evict")), __privateGet(this, _hasDisposeAfter) && ((_b2 = __privateGet(this, _disposed)) == null || _b2.push([v, k, "evict"]))), __privateGet(this, _removeItemSize).call(this, head), free && (__privateGet(this, _keyList)[head] = void 0, __privateGet(this, _valList)[head] = void 0, __privateGet(this, _free).push(head)), __privateGet(this, _size) === 1 ? (__privateSet(this, _head, __privateSet(this, _tail, 0)), __privateGet(this, _free).length = 0) : __privateSet(this, _head, __privateGet(this, _next)[head]), __privateGet(this, _keyMap).delete(k), __privateWrapper(this, _size)._--, head; | ||
}, backgroundFetch_fn = function(k, index, options, context) { | ||
const v = index === void 0 ? void 0 : __privateGet(this, _valList)[index]; | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) | ||
return v; | ||
const ac = new AC(), { signal } = options; | ||
signal == null || signal.addEventListener("abort", () => ac.abort(signal.reason), { | ||
signal: ac.signal | ||
}); | ||
const fetchOpts = { | ||
signal: ac.signal, | ||
options, | ||
context | ||
}, cb = (v2, updateCache = !1) => { | ||
const { aborted } = ac.signal, ignoreAbort = options.ignoreFetchAbort && v2 !== void 0; | ||
if (options.status && (aborted && !updateCache ? (options.status.fetchAborted = !0, options.status.fetchError = ac.signal.reason, ignoreAbort && (options.status.fetchAbortIgnored = !0)) : options.status.fetchResolved = !0), aborted && !ignoreAbort && !updateCache) | ||
return fetchFail(ac.signal.reason); | ||
const bf2 = p; | ||
return __privateGet(this, _valList)[index] === p && (v2 === void 0 ? bf2.__staleWhileFetching ? __privateGet(this, _valList)[index] = bf2.__staleWhileFetching : __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch") : (options.status && (options.status.fetchUpdated = !0), this.set(k, v2, fetchOpts.options))), v2; | ||
}, eb = (er) => (options.status && (options.status.fetchRejected = !0, options.status.fetchError = er), fetchFail(er)), fetchFail = (er) => { | ||
const { aborted } = ac.signal, allowStaleAborted = aborted && options.allowStaleOnFetchAbort, allowStale = allowStaleAborted || options.allowStaleOnFetchRejection, noDelete = allowStale || options.noDeleteOnFetchRejection, bf2 = p; | ||
if (__privateGet(this, _valList)[index] === p && (!noDelete || bf2.__staleWhileFetching === void 0 ? __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch") : allowStaleAborted || (__privateGet(this, _valList)[index] = bf2.__staleWhileFetching)), allowStale) | ||
return options.status && bf2.__staleWhileFetching !== void 0 && (options.status.returnedStale = !0), bf2.__staleWhileFetching; | ||
if (bf2.__returned === bf2) | ||
throw er; | ||
}, pcall = (res, rej) => { | ||
var _a3; | ||
const fmp = (_a3 = __privateGet(this, _fetchMethod)) == null ? void 0 : _a3.call(this, k, v, fetchOpts); | ||
fmp && fmp instanceof Promise && fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej), ac.signal.addEventListener("abort", () => { | ||
(!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) && (res(void 0), options.allowStaleOnFetchAbort && (res = (v2) => cb(v2, !0))); | ||
}); | ||
}; | ||
options.status && (options.status.fetchDispatched = !0); | ||
const p = new Promise(pcall).then(cb, eb), bf = Object.assign(p, { | ||
__abortController: ac, | ||
__staleWhileFetching: v, | ||
__returned: void 0 | ||
}); | ||
return index === void 0 ? (this.set(k, bf, { ...fetchOpts.options, status: void 0 }), index = __privateGet(this, _keyMap).get(k)) : __privateGet(this, _valList)[index] = bf, bf; | ||
}, isBackgroundFetch_fn = function(p) { | ||
if (!__privateGet(this, _hasFetchMethod)) | ||
return !1; | ||
const b = p; | ||
return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC; | ||
}, connect_fn = function(p, n) { | ||
__privateGet(this, _prev)[n] = p, __privateGet(this, _next)[p] = n; | ||
}, moveToTail_fn = function(index) { | ||
index !== __privateGet(this, _tail) && (index === __privateGet(this, _head) ? __privateSet(this, _head, __privateGet(this, _next)[index]) : __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _prev)[index], __privateGet(this, _next)[index]), __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _tail), index), __privateSet(this, _tail, index)); | ||
}, delete_fn = function(k, reason) { | ||
var _a3, _b2, _c, _d; | ||
let deleted = !1; | ||
if (__privateGet(this, _size) !== 0) { | ||
const index = __privateGet(this, _keyMap).get(k); | ||
if (index !== void 0) | ||
if (deleted = !0, __privateGet(this, _size) === 1) | ||
__privateMethod(this, _LRUCache_instances, clear_fn).call(this, reason); | ||
else { | ||
__privateGet(this, _removeItemSize).call(this, index); | ||
const v = __privateGet(this, _valList)[index]; | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__abortController.abort(new Error("deleted")) : (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) && (__privateGet(this, _hasDispose) && ((_a3 = __privateGet(this, _dispose)) == null || _a3.call(this, v, k, reason)), __privateGet(this, _hasDisposeAfter) && ((_b2 = __privateGet(this, _disposed)) == null || _b2.push([v, k, reason]))), __privateGet(this, _keyMap).delete(k), __privateGet(this, _keyList)[index] = void 0, __privateGet(this, _valList)[index] = void 0, index === __privateGet(this, _tail)) | ||
__privateSet(this, _tail, __privateGet(this, _prev)[index]); | ||
else if (index === __privateGet(this, _head)) | ||
__privateSet(this, _head, __privateGet(this, _next)[index]); | ||
else { | ||
const pi = __privateGet(this, _prev)[index]; | ||
__privateGet(this, _next)[pi] = __privateGet(this, _next)[index]; | ||
const ni = __privateGet(this, _next)[index]; | ||
__privateGet(this, _prev)[ni] = __privateGet(this, _prev)[index]; | ||
} | ||
__privateWrapper(this, _size)._--, __privateGet(this, _free).push(index); | ||
} | ||
} | ||
if (__privateGet(this, _hasDisposeAfter) && ((_c = __privateGet(this, _disposed)) != null && _c.length)) { | ||
const dt = __privateGet(this, _disposed); | ||
let task; | ||
for (; task = dt == null ? void 0 : dt.shift(); ) | ||
(_d = __privateGet(this, _disposeAfter)) == null || _d.call(this, ...task); | ||
} | ||
return deleted; | ||
}, clear_fn = function(reason) { | ||
var _a3, _b2, _c; | ||
for (const index of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: !0 })) { | ||
const v = __privateGet(this, _valList)[index]; | ||
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) | ||
v.__abortController.abort(new Error("deleted")); | ||
else { | ||
const k = __privateGet(this, _keyList)[index]; | ||
__privateGet(this, _hasDispose) && ((_a3 = __privateGet(this, _dispose)) == null || _a3.call(this, v, k, reason)), __privateGet(this, _hasDisposeAfter) && ((_b2 = __privateGet(this, _disposed)) == null || _b2.push([v, k, reason])); | ||
} | ||
} | ||
if (__privateGet(this, _keyMap).clear(), __privateGet(this, _valList).fill(void 0), __privateGet(this, _keyList).fill(void 0), __privateGet(this, _ttls) && __privateGet(this, _starts) && (__privateGet(this, _ttls).fill(0), __privateGet(this, _starts).fill(0)), __privateGet(this, _sizes) && __privateGet(this, _sizes).fill(0), __privateSet(this, _head, 0), __privateSet(this, _tail, 0), __privateGet(this, _free).length = 0, __privateSet(this, _calculatedSize, 0), __privateSet(this, _size, 0), __privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) { | ||
const dt = __privateGet(this, _disposed); | ||
let task; | ||
for (; task = dt == null ? void 0 : dt.shift(); ) | ||
(_c = __privateGet(this, _disposeAfter)) == null || _c.call(this, ...task); | ||
} | ||
}; | ||
let LRUCache = _LRUCache; | ||
const DEFAULT_TAG = "sanity.preview-kit", documentsCache = new LRUCache({ | ||
// Max 500 documents in memory, no big deal if a document is evicted it just means the eventual consistency might take longer | ||
max: 500 | ||
}), LiveStoreProvider = memo(function(props) { | ||
const { children, refreshInterval = 1e4, token } = props; | ||
if (!props.client) | ||
throw new Error("Missing a `client` prop with a configured Sanity client instance"); | ||
const [client] = useState(() => { | ||
const { requestTagPrefix, resultSourceMap } = props.client.config(); | ||
return props.client.withConfig({ | ||
requestTagPrefix: requestTagPrefix || DEFAULT_TAG, | ||
resultSourceMap: resultSourceMap === "withKeyArraySelector" ? "withKeyArraySelector" : !0, | ||
// Set the recommended defaults, this is a convenience to make it easier to share a client config from a server component to the client component | ||
...token && { | ||
token, | ||
useCdn: !1, | ||
perspective: "previewDrafts", | ||
ignoreBrowserTokenWarning: !0 | ||
} | ||
}); | ||
}), [logger] = useState(() => props.logger); | ||
useEffect(() => { | ||
logger && logger.log( | ||
`[@sanity/preview-kit]: With the current configuration you can expect that: Updates that can be traced using Content Source Maps will be applied in real-time. Other updates will be applied every ${refreshInterval}ms.` | ||
); | ||
}, [logger, refreshInterval]); | ||
const [subscriptions, setSubscriptions] = useState([]), [snapshots] = useState(() => /* @__PURE__ */ new Map()), hooks = useHooks(setSubscriptions), [context] = useState(() => function(initialSnapshot, query, params) { | ||
const key = getQueryCacheKey(query, params); | ||
return snapshots.has(key) || snapshots.set(key, { | ||
result: initialSnapshot, | ||
resultSourceMap: {} | ||
}), { subscribe: (onStoreChange) => { | ||
const unsubscribe = hooks.subscribe(key, query, params, onStoreChange); | ||
return () => unsubscribe(); | ||
}, getSnapshot: () => { | ||
var _a3; | ||
return (_a3 = snapshots.get(key)) == null ? void 0 : _a3.result; | ||
} }; | ||
}), [turboIds, setTurboIds] = useState([]), [docsInUse] = useState(() => /* @__PURE__ */ new Map()), turboIdsFromSourceMap = useCallback( | ||
(contentSourceMap) => { | ||
var _a3; | ||
const nextTurboIds = /* @__PURE__ */ new Set(); | ||
if (docsInUse.clear(), (_a3 = contentSourceMap.documents) != null && _a3.length) | ||
for (const document of contentSourceMap.documents) | ||
nextTurboIds.add(document._id), docsInUse.set(document._id, document); | ||
startTransition( | ||
() => setTurboIds((prevTurboIds) => { | ||
const mergedTurboIds = Array.from(/* @__PURE__ */ new Set([...prevTurboIds, ...nextTurboIds])); | ||
return JSON.stringify(mergedTurboIds.sort()) === JSON.stringify(prevTurboIds.sort()) ? prevTurboIds : mergedTurboIds; | ||
}) | ||
); | ||
}, | ||
[docsInUse] | ||
); | ||
return /* @__PURE__ */ jsxs(defineStoreContext.Provider, { value: context, children: [ | ||
children, | ||
/* @__PURE__ */ jsx( | ||
Turbo, | ||
{ | ||
cache: hooks.cache, | ||
client, | ||
setTurboIds, | ||
snapshots, | ||
turboIds, | ||
docsInUse | ||
} | ||
), | ||
subscriptions.map((key) => { | ||
if (!hooks.cache.has(key)) return null; | ||
const { query, params, listeners } = hooks.cache.get(key); | ||
return /* @__PURE__ */ jsx( | ||
QuerySubscription, | ||
{ | ||
client, | ||
listeners, | ||
params, | ||
query, | ||
refreshInterval, | ||
snapshots, | ||
turboIdsFromSourceMap | ||
}, | ||
key | ||
); | ||
}) | ||
] }); | ||
}); | ||
LiveStoreProvider.displayName = "LiveStoreProvider"; | ||
const QuerySubscription = memo(function(props) { | ||
const { client, refreshInterval, query, params, listeners, snapshots, turboIdsFromSourceMap } = props, { projectId, dataset } = useMemo(() => { | ||
const { projectId: projectId2, dataset: dataset2 } = client.config(); | ||
return { projectId: projectId2, dataset: dataset2 }; | ||
}, [client]), [error, setError] = useState(null); | ||
if (error) throw error; | ||
const [revalidate, startRefresh] = useRevalidate({ refreshInterval }), shouldRefetch = revalidate === "refresh" || revalidate === "inflight"; | ||
return useEffect(() => { | ||
if (!shouldRefetch) | ||
return; | ||
let fulfilled = !1; | ||
const controller = new AbortController(); | ||
async function effect() { | ||
const { signal } = controller, { result, resultSourceMap } = await client.fetch(query, params, { | ||
signal, | ||
filterResponse: !1 | ||
}); | ||
if (!signal.aborted) { | ||
snapshots.set(getQueryCacheKey(query, params), { | ||
result: turboChargeResultIfSourceMap(projectId, dataset, result, resultSourceMap), | ||
resultSourceMap: resultSourceMap != null ? resultSourceMap : {} | ||
}), resultSourceMap && turboIdsFromSourceMap(resultSourceMap); | ||
for (const listener of listeners.values()) | ||
listener(); | ||
fulfilled = !0; | ||
} | ||
} | ||
const onFinally = startRefresh(); | ||
return effect().catch((error2) => { | ||
error2.name !== "AbortError" && setError(error2); | ||
}).finally(onFinally), () => { | ||
fulfilled || controller.abort(); | ||
}; | ||
}, [ | ||
client, | ||
dataset, | ||
listeners, | ||
params, | ||
projectId, | ||
query, | ||
shouldRefetch, | ||
snapshots, | ||
startRefresh, | ||
turboIdsFromSourceMap | ||
]), null; | ||
}); | ||
QuerySubscription.displayName = "QuerySubscription"; | ||
function getTurboCacheKey(projectId, dataset, _id) { | ||
return `${projectId}-${dataset}-${_id}`; | ||
} | ||
function useHooks(setSubscriptions) { | ||
const [cache] = useState(() => /* @__PURE__ */ new Map()), subscribe = useCallback( | ||
(key, query, params, listener) => { | ||
cache.has(key) || (cache.set(key, { query, params, listeners: /* @__PURE__ */ new Set() }), startTransition( | ||
() => setSubscriptions((prevSubscriptions) => prevSubscriptions.includes(key) ? prevSubscriptions : [...prevSubscriptions, key]) | ||
)); | ||
const hook = cache.get(key); | ||
if (!hook || !hook.listeners) | ||
throw new TypeError("Inconsistent cache for key: " + key); | ||
const { listeners } = hook; | ||
return listeners.add(listener), () => { | ||
listeners.delete(listener), listeners.size === 0 && (cache.delete(key), startTransition( | ||
() => setSubscriptions((prevSubscriptions) => prevSubscriptions.includes(key) ? prevSubscriptions.filter((sub) => sub !== key) : prevSubscriptions) | ||
)); | ||
}; | ||
}, | ||
[cache, setSubscriptions] | ||
); | ||
return useMemo(() => ({ cache, subscribe }), [cache, subscribe]); | ||
} | ||
const Turbo = memo(function(props) { | ||
const { client, snapshots, cache, turboIds, setTurboIds, docsInUse } = props, { projectId, dataset } = useMemo(() => { | ||
const { projectId: projectId2, dataset: dataset2 } = client.config(); | ||
return { projectId: projectId2, dataset: dataset2 }; | ||
}, [client]); | ||
useEffect(() => { | ||
var _a3, _b2; | ||
const nextTurboIds = /* @__PURE__ */ new Set(); | ||
docsInUse.clear(); | ||
for (const { query, params } of cache.values()) { | ||
const key = getQueryCacheKey(query, params), snapshot = snapshots.get(key); | ||
if (snapshot && (_b2 = (_a3 = snapshot.resultSourceMap) == null ? void 0 : _a3.documents) != null && _b2.length) | ||
for (const document of snapshot.resultSourceMap.documents) | ||
nextTurboIds.add(document._id), docsInUse.set(document._id, document); | ||
} | ||
const nextTurboIdsSnapshot = [...nextTurboIds].sort(); | ||
JSON.stringify(turboIds) !== JSON.stringify(nextTurboIdsSnapshot) && startTransition(() => setTurboIds(nextTurboIdsSnapshot)); | ||
}, [cache, setTurboIds, snapshots, turboIds, docsInUse]), useDocumentsInUse(docsInUse, projectId, dataset); | ||
const [batch, setBatch] = useState([]); | ||
useEffect(() => { | ||
const batchSet = new Set(batch.flat()), nextBatch = /* @__PURE__ */ new Set(); | ||
for (const turboId of turboIds) | ||
!batchSet.has(turboId) && !documentsCache.has(getTurboCacheKey(projectId, dataset, turboId)) && nextBatch.add(turboId); | ||
const nextBatchSlice = [...nextBatch].slice(0, 100); | ||
nextBatchSlice.length !== 0 && startTransition(() => setBatch((prevBatch) => [...prevBatch.slice(-100), nextBatchSlice])); | ||
}, [batch, dataset, projectId, turboIds]); | ||
const [lastMutatedDocumentId, setLastMutatedDocumentId] = useState(); | ||
return useEffect(() => { | ||
const subscription = client.listen( | ||
"*", | ||
{}, | ||
{ | ||
events: ["mutation"], | ||
effectFormat: "mendoza", | ||
includePreviousRevision: !1, | ||
includeResult: !1, | ||
tag: "turbo" | ||
} | ||
).subscribe((update) => { | ||
var _a3, _b2; | ||
if (update.type !== "mutation" || !((_b2 = (_a3 = update.effects) == null ? void 0 : _a3.apply) != null && _b2.length)) return; | ||
const key = getTurboCacheKey(projectId, dataset, update.documentId), cachedDocument = documentsCache.peek(key); | ||
if (cachedDocument) { | ||
const patchDoc = { ...cachedDocument }; | ||
delete patchDoc._rev; | ||
const patchedDocument = applyPatch(patchDoc, update.effects.apply); | ||
documentsCache.set(key, patchedDocument); | ||
} | ||
startTransition(() => setLastMutatedDocumentId(update.documentId)); | ||
}); | ||
return () => subscription.unsubscribe(); | ||
}, [client, dataset, projectId]), useEffect(() => { | ||
var _a3, _b2, _c; | ||
if (!lastMutatedDocumentId || !turboIds.includes(lastMutatedDocumentId)) return; | ||
const updatedKeys = []; | ||
for (const [key, snapshot] of snapshots.entries()) | ||
(_b2 = (_a3 = snapshot.resultSourceMap) == null ? void 0 : _a3.documents) != null && _b2.length && (snapshot.result = turboChargeResultIfSourceMap( | ||
projectId, | ||
dataset, | ||
snapshot.result, | ||
snapshot.resultSourceMap | ||
), updatedKeys.push(key)); | ||
for (const updatedKey of updatedKeys) { | ||
const listeners = (_c = cache.get(updatedKey)) == null ? void 0 : _c.listeners; | ||
if (listeners) | ||
for (const listener of listeners) | ||
listener(); | ||
} | ||
startTransition(() => setLastMutatedDocumentId(void 0)); | ||
}, [cache, dataset, lastMutatedDocumentId, projectId, snapshots, turboIds]), /* @__PURE__ */ jsx(Fragment, { children: batch.map((ids) => /* @__PURE__ */ jsx( | ||
GetDocuments, | ||
{ | ||
client, | ||
projectId, | ||
dataset, | ||
ids | ||
}, | ||
JSON.stringify(ids) | ||
)) }); | ||
}); | ||
Turbo.displayName = "Turbo"; | ||
const GetDocuments = memo(function(props) { | ||
const { client, projectId, dataset, ids } = props; | ||
return useEffect(() => { | ||
const missingIds = ids.filter( | ||
(id) => !documentsCache.has(getTurboCacheKey(projectId, dataset, id)) | ||
); | ||
missingIds.length !== 0 && client.getDocuments(missingIds).then((documents) => { | ||
for (const doc of documents) | ||
doc && doc != null && doc._id && documentsCache.set(getTurboCacheKey(projectId, dataset, doc._id), doc); | ||
}, console.error); | ||
}, [client, dataset, ids, projectId]), null; | ||
}); | ||
GetDocuments.displayName = "GetDocuments"; | ||
let warnedAboutCrossDatasetReference = !1; | ||
function turboChargeResultIfSourceMap(projectId, dataset, result, resultSourceMap) { | ||
return resultSourceMap ? applySourceDocuments( | ||
result, | ||
resultSourceMap, | ||
(sourceDocument) => { | ||
if (sourceDocument._projectId) { | ||
warnedAboutCrossDatasetReference || (console.warn( | ||
"Cross dataset references are not supported yet, ignoring source document", | ||
sourceDocument | ||
), warnedAboutCrossDatasetReference = !0); | ||
return; | ||
} | ||
return documentsCache.get(getTurboCacheKey(projectId, dataset, sourceDocument._id)); | ||
}, | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
(changedValue, { previousValue }) => { | ||
if (typeof changedValue == "string" && typeof previousValue == "string") { | ||
const { encoded } = _(previousValue), { cleaned } = _(changedValue); | ||
return `${encoded}${cleaned}`; | ||
} | ||
return changedValue; | ||
}, | ||
"previewDrafts" | ||
) : result; | ||
} | ||
function getQueryCacheKey(query, params) { | ||
return `${query}-${JSON.stringify(params)}`; | ||
} | ||
export { | ||
LiveStoreProvider as default | ||
}; | ||
//# sourceMappingURL=LiveQueryProvider.js.map |
@@ -1,1 +0,77 @@ | ||
import{createClient as e}from"@sanity/client";const r=r=>{var o,a;const{encodeSourceMap:c=t(),encodeSourceMapAtPath:i,studioUrl:u=n(),logger:l,...s}=r;let p=!0===c;if("auto"===c&&(p=function(){try{return"preview"===import.meta.env.VERCEL_ENV}catch{}try{return"preview"===process.env.VERCEL_ENV}catch{}return!1}()),"string"==typeof c&&"auto"!==c)throw new Error(`Invalid value for encodeSourceMap: ${c}. Did you mean 'auto'?`);try{if(p&&!1!==r.resultSourceMap)return u?(null==(a=null==l?void 0:l.debug)||a.call(l,"[@sanity/preview-kit]: Creating source map enabled client"),e({...s,resultSourceMap:r.resultSourceMap?r.resultSourceMap:"withKeyArraySelector",stega:{enabled:!0,studioUrl:u,logger:l,filter:i?e=>i({path:e.sourcePath,filterDefault:()=>e.filterDefault(e)}):void 0}})):(null==(o=null==l?void 0:l.error)||o.call(l,"[@sanity/preview-kit]: Content source map enabled client is enabled, but no studioUrl is provided. Falling back to @sanity/client"),e(s))}catch(e){console.error("[@sanity/preview-kit]: Error creating client",e,"falling back to non-embedded sourcemap mode")}return e(s)};function t(){try{return"true"===import.meta.env.SANITY_SOURCE_MAP}catch{}try{return"true"===process.env.SANITY_SOURCE_MAP}catch{}return!1}function n(){try{return import.meta.env.SANITY_STUDIO_URL}catch{}try{return process.env.SANITY_STUDIO_URL}catch{}}export{r as createClient};//# sourceMappingURL=client.js.map | ||
import { createClient as createClient$1 } from "@sanity/client"; | ||
const createClient = (config) => { | ||
var _a, _b; | ||
const { | ||
encodeSourceMap = detectEnableSourceMap(), | ||
encodeSourceMapAtPath, | ||
studioUrl = detectStudioUrl(), | ||
logger, | ||
...options | ||
} = config; | ||
let shouldEncodeSourceMap = encodeSourceMap === !0; | ||
if (encodeSourceMap === "auto" && (shouldEncodeSourceMap = isVercelPreviewEnvironment()), typeof encodeSourceMap == "string" && encodeSourceMap !== "auto") | ||
throw new Error(`Invalid value for encodeSourceMap: ${encodeSourceMap}. Did you mean 'auto'?`); | ||
try { | ||
if (shouldEncodeSourceMap && config.resultSourceMap !== !1) | ||
return studioUrl ? ((_b = logger == null ? void 0 : logger.debug) == null || _b.call(logger, "[@sanity/preview-kit]: Creating source map enabled client"), createClient$1({ | ||
...options, | ||
// Source maps by Content Lake are required in order to know where to insert the encoded source maps into strings | ||
resultSourceMap: config.resultSourceMap ? config.resultSourceMap : "withKeyArraySelector", | ||
stega: { | ||
enabled: !0, | ||
studioUrl, | ||
logger, | ||
filter: encodeSourceMapAtPath ? (props) => encodeSourceMapAtPath({ | ||
path: props.sourcePath, | ||
filterDefault: () => props.filterDefault(props) | ||
}) : void 0 | ||
} | ||
})) : ((_a = logger == null ? void 0 : logger.error) == null || _a.call( | ||
logger, | ||
"[@sanity/preview-kit]: Content source map enabled client is enabled, but no studioUrl is provided. Falling back to @sanity/client" | ||
), createClient$1(options)); | ||
} catch (err) { | ||
console.error( | ||
"[@sanity/preview-kit]: Error creating client", | ||
err, | ||
"falling back to non-embedded sourcemap mode" | ||
); | ||
} | ||
return createClient$1(options); | ||
}; | ||
function isVercelPreviewEnvironment() { | ||
try { | ||
return import.meta.env.VERCEL_ENV === "preview"; | ||
} catch { | ||
} | ||
try { | ||
return process.env.VERCEL_ENV === "preview"; | ||
} catch { | ||
} | ||
return !1; | ||
} | ||
function detectEnableSourceMap() { | ||
try { | ||
return import.meta.env.SANITY_SOURCE_MAP === "true"; | ||
} catch { | ||
} | ||
try { | ||
return process.env.SANITY_SOURCE_MAP === "true"; | ||
} catch { | ||
} | ||
return !1; | ||
} | ||
function detectStudioUrl() { | ||
try { | ||
return import.meta.env.SANITY_STUDIO_URL; | ||
} catch { | ||
} | ||
try { | ||
return process.env.SANITY_STUDIO_URL; | ||
} catch { | ||
} | ||
} | ||
export { | ||
createClient | ||
}; | ||
//# sourceMappingURL=client.js.map |
@@ -1,19 +0,222 @@ | ||
import{useQueryParams as e}from"@sanity/preview-kit-compat";import r,{useContext as t,useMemo as n,useState as u,useCallback as o,lazy as i}from"react";import{d as a}from"./_chunks-es/context.js";function f(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s=typeof Element<"u",c="function"==typeof Map,l="function"==typeof Set,p="function"==typeof ArrayBuffer&&!!ArrayBuffer.isView;function v(e,r){if(e===r)return!0;if(e&&r&&"object"==typeof e&&"object"==typeof r){if(e.constructor!==r.constructor)return!1;var t,n,u,o;if(Array.isArray(e)){if((t=e.length)!=r.length)return!1;for(n=t;0!=n--;)if(!v(e[n],r[n]))return!1;return!0}if(c&&e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(o=e.entries();!(n=o.next()).done;)if(!r.has(n.value[0]))return!1;for(o=e.entries();!(n=o.next()).done;)if(!v(n.value[1],r.get(n.value[0])))return!1;return!0}if(l&&e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(o=e.entries();!(n=o.next()).done;)if(!r.has(n.value[0]))return!1;return!0}if(p&&ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){if((t=e.length)!=r.length)return!1;for(n=t;0!=n--;)if(e[n]!==r[n])return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf&&"function"==typeof e.valueOf&&"function"==typeof r.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString&&"function"==typeof e.toString&&"function"==typeof r.toString)return e.toString()===r.toString();if((t=(u=Object.keys(e)).length)!==Object.keys(r).length)return!1;for(n=t;0!=n--;)if(!Object.prototype.hasOwnProperty.call(r,u[n]))return!1;if(s&&e instanceof Element)return!1;for(n=t;0!=n--;)if(("_owner"!==u[n]&&"__v"!==u[n]&&"__o"!==u[n]||!e.$$typeof)&&!v(e[u[n]],r[u[n]]))return!1;return!0}return e!=e&&r!=r}var O,_=f((function(e,r){try{return v(e,r)}catch(e){if((e.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw e}})),y={exports:{}},S={}; | ||
import { useQueryParams } from "@sanity/preview-kit-compat"; | ||
import require$$0, { useContext, useMemo, useState, useCallback, lazy } from "react"; | ||
import { defineStoreContext } from "./_chunks-es/context.js"; | ||
function getDefaultExportFromCjs(x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x; | ||
} | ||
var hasElementType = typeof Element < "u", hasMap = typeof Map == "function", hasSet = typeof Set == "function", hasArrayBuffer = typeof ArrayBuffer == "function" && !!ArrayBuffer.isView; | ||
function equal(a, b) { | ||
if (a === b) return !0; | ||
if (a && b && typeof a == "object" && typeof b == "object") { | ||
if (a.constructor !== b.constructor) return !1; | ||
var length, i, keys; | ||
if (Array.isArray(a)) { | ||
if (length = a.length, length != b.length) return !1; | ||
for (i = length; i-- !== 0; ) | ||
if (!equal(a[i], b[i])) return !1; | ||
return !0; | ||
} | ||
var it; | ||
if (hasMap && a instanceof Map && b instanceof Map) { | ||
if (a.size !== b.size) return !1; | ||
for (it = a.entries(); !(i = it.next()).done; ) | ||
if (!b.has(i.value[0])) return !1; | ||
for (it = a.entries(); !(i = it.next()).done; ) | ||
if (!equal(i.value[1], b.get(i.value[0]))) return !1; | ||
return !0; | ||
} | ||
if (hasSet && a instanceof Set && b instanceof Set) { | ||
if (a.size !== b.size) return !1; | ||
for (it = a.entries(); !(i = it.next()).done; ) | ||
if (!b.has(i.value[0])) return !1; | ||
return !0; | ||
} | ||
if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { | ||
if (length = a.length, length != b.length) return !1; | ||
for (i = length; i-- !== 0; ) | ||
if (a[i] !== b[i]) return !1; | ||
return !0; | ||
} | ||
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; | ||
if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf == "function" && typeof b.valueOf == "function") return a.valueOf() === b.valueOf(); | ||
if (a.toString !== Object.prototype.toString && typeof a.toString == "function" && typeof b.toString == "function") return a.toString() === b.toString(); | ||
if (keys = Object.keys(a), length = keys.length, length !== Object.keys(b).length) return !1; | ||
for (i = length; i-- !== 0; ) | ||
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1; | ||
if (hasElementType && a instanceof Element) return !1; | ||
for (i = length; i-- !== 0; ) | ||
if (!((keys[i] === "_owner" || keys[i] === "__v" || keys[i] === "__o") && a.$$typeof) && !equal(a[keys[i]], b[keys[i]])) | ||
return !1; | ||
return !0; | ||
} | ||
return a !== a && b !== b; | ||
} | ||
var reactFastCompare = function(a, b) { | ||
try { | ||
return equal(a, b); | ||
} catch (error) { | ||
if ((error.message || "").match(/stack|recursion/i)) | ||
return console.warn("react-fast-compare cannot handle circular refs"), !1; | ||
throw error; | ||
} | ||
}, isFastEqual = /* @__PURE__ */ getDefaultExportFromCjs(reactFastCompare), withSelector = { exports: {} }, useSyncExternalStoreWithSelector_production_min = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-with-selector.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/var h,d={}; | ||
* @license React | ||
* use-sync-external-store-with-selector.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredUseSyncExternalStoreWithSelector_production_min; | ||
function requireUseSyncExternalStoreWithSelector_production_min() { | ||
if (hasRequiredUseSyncExternalStoreWithSelector_production_min) return useSyncExternalStoreWithSelector_production_min; | ||
hasRequiredUseSyncExternalStoreWithSelector_production_min = 1; | ||
var g = require$$0; | ||
function n(a, b) { | ||
return a === b && (a !== 0 || 1 / a === 1 / b) || a !== a && b !== b; | ||
} | ||
var p = typeof Object.is == "function" ? Object.is : n, q = g.useSyncExternalStore, r = g.useRef, t = g.useEffect, u = g.useMemo, v = g.useDebugValue; | ||
return useSyncExternalStoreWithSelector_production_min.useSyncExternalStoreWithSelector = function(a, b, e, l, h) { | ||
var c = r(null); | ||
if (c.current === null) { | ||
var f = { hasValue: !1, value: null }; | ||
c.current = f; | ||
} else f = c.current; | ||
c = u(function() { | ||
function a2(a3) { | ||
if (!c2) { | ||
if (c2 = !0, d2 = a3, a3 = l(a3), h !== void 0 && f.hasValue) { | ||
var b2 = f.value; | ||
if (h(b2, a3)) return k = b2; | ||
} | ||
return k = a3; | ||
} | ||
if (b2 = k, p(d2, a3)) return b2; | ||
var e2 = l(a3); | ||
return h !== void 0 && h(b2, e2) ? b2 : (d2 = a3, k = e2); | ||
} | ||
var c2 = !1, d2, k, m = e === void 0 ? null : e; | ||
return [function() { | ||
return a2(b()); | ||
}, m === null ? void 0 : function() { | ||
return a2(m()); | ||
}]; | ||
}, [b, e, l, h]); | ||
var d = q(a, c[0], c[1]); | ||
return t(function() { | ||
f.hasValue = !0, f.value = d; | ||
}, [d]), v(d), d; | ||
}, useSyncExternalStoreWithSelector_production_min; | ||
} | ||
var useSyncExternalStoreWithSelector_development = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-with-selector.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/"production"===process.env.NODE_ENV?y.exports=function(){if(O)return S;O=1;var e=r,t="function"==typeof Object.is?Object.is:function(e,r){return e===r&&(0!==e||1/e==1/r)||e!=e&&r!=r},n=e.useSyncExternalStore,u=e.useRef,o=e.useEffect,i=e.useMemo,a=e.useDebugValue;return S.useSyncExternalStoreWithSelector=function(e,r,f,s,c){var l=u(null);if(null===l.current){var p={hasValue:!1,value:null};l.current=p}else p=l.current;l=i((function(){function e(e){if(!o){if(o=!0,n=e,e=s(e),void 0!==c&&p.hasValue){var r=p.value;if(c(r,e))return u=r}return u=e}if(r=u,t(n,e))return r;var i=s(e);return void 0!==c&&c(r,i)?r:(n=e,u=i)}var n,u,o=!1,i=void 0===f?null:f;return[function(){return e(r())},null===i?void 0:function(){return e(i())}]}),[r,f,s,c]);var v=n(e,l[0],l[1]);return o((function(){p.hasValue=!0,p.value=v}),[v]),a(v),v},S}():y.exports=(h||(h=1,"production"!==process.env.NODE_ENV&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var e=r,t="function"==typeof Object.is?Object.is:function(e,r){return e===r&&(0!==e||1/e==1/r)||e!=e&&r!=r},n=e.useSyncExternalStore,u=e.useRef,o=e.useEffect,i=e.useMemo,a=e.useDebugValue;d.useSyncExternalStoreWithSelector=function(e,r,f,s,c){var l,p=u(null);null===p.current?(l={hasValue:!1,value:null},p.current=l):l=p.current;var v=i((function(){var e,n,u=!1,o=function(r){if(!u){u=!0,e=r;var o=s(r);if(void 0!==c&&l.hasValue){var i=l.value;if(c(i,o))return n=i,i}return n=o,o}var a=n;if(t(e,r))return a;var f=s(r);return void 0!==c&&c(a,f)?a:(e=r,n=f,f)},i=void 0===f?null:f;return[function(){return o(r())},null===i?void 0:function(){return o(i())}]}),[r,f,s,c]),O=v[0],_=v[1],y=n(e,O,_);return o((function(){l.hasValue=!0,l.value=y}),[y]),a(y),y},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),d);var E=y.exports;function g(r,i,f,s){const{isEqual:c=_}=s||{},l=t(a),p=e(f),v=n((()=>({subscribe:()=>()=>{},getSnapshot:()=>r})),[r]),O=n((()=>(null==l?void 0:l(r,i,p))||{subscribe:()=>()=>{},getSnapshot:()=>r}),[l,r,p,i]),[y]=u((()=>{if(void 0===r)throw new Error("initialSnapshot can't be undefined, if you don't want an initial value use null instead");try{return JSON.parse(JSON.stringify(r))}catch(e){return console.warn("Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable",{initialSnapshot:r,error:e}),r}})),S=o((()=>y),[y]),h=o((e=>e),[]),d=E.useSyncExternalStoreWithSelector((null==O?void 0:O.subscribe)||v.subscribe,(null==O?void 0:O.getSnapshot)||v.getSnapshot,S,h,c),g=null!==l;return[d,g&&y===d,g]}function b(){return null!==t(a)}const L=i((()=>import("./_chunks-es/LiveQueryProvider.js")));function V(e){return L}export{L as LiveQueryProvider,V as createLiveQueryProvider,L as default,b as useIsEnabled,g as useLiveQuery};//# sourceMappingURL=index.js.map | ||
* @license React | ||
* use-sync-external-store-with-selector.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredUseSyncExternalStoreWithSelector_development; | ||
function requireUseSyncExternalStoreWithSelector_development() { | ||
return hasRequiredUseSyncExternalStoreWithSelector_development || (hasRequiredUseSyncExternalStoreWithSelector_development = 1, process.env.NODE_ENV !== "production" && function() { | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); | ||
var React = require$$0; | ||
function is(x, y) { | ||
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; | ||
} | ||
var objectIs = typeof Object.is == "function" ? Object.is : is, useSyncExternalStore = React.useSyncExternalStore, useRef = React.useRef, useEffect = React.useEffect, useMemo2 = React.useMemo, useDebugValue = React.useDebugValue; | ||
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual2) { | ||
var instRef = useRef(null), inst; | ||
instRef.current === null ? (inst = { | ||
hasValue: !1, | ||
value: null | ||
}, instRef.current = inst) : inst = instRef.current; | ||
var _useMemo = useMemo2(function() { | ||
var hasMemo = !1, memoizedSnapshot, memoizedSelection, memoizedSelector = function(nextSnapshot) { | ||
if (!hasMemo) { | ||
hasMemo = !0, memoizedSnapshot = nextSnapshot; | ||
var _nextSelection = selector(nextSnapshot); | ||
if (isEqual2 !== void 0 && inst.hasValue) { | ||
var currentSelection = inst.value; | ||
if (isEqual2(currentSelection, _nextSelection)) | ||
return memoizedSelection = currentSelection, currentSelection; | ||
} | ||
return memoizedSelection = _nextSelection, _nextSelection; | ||
} | ||
var prevSnapshot = memoizedSnapshot, prevSelection = memoizedSelection; | ||
if (objectIs(prevSnapshot, nextSnapshot)) | ||
return prevSelection; | ||
var nextSelection = selector(nextSnapshot); | ||
return isEqual2 !== void 0 && isEqual2(prevSelection, nextSelection) ? prevSelection : (memoizedSnapshot = nextSnapshot, memoizedSelection = nextSelection, nextSelection); | ||
}, maybeGetServerSnapshot = getServerSnapshot === void 0 ? null : getServerSnapshot, getSnapshotWithSelector = function() { | ||
return memoizedSelector(getSnapshot()); | ||
}, getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? void 0 : function() { | ||
return memoizedSelector(maybeGetServerSnapshot()); | ||
}; | ||
return [getSnapshotWithSelector, getServerSnapshotWithSelector]; | ||
}, [getSnapshot, getServerSnapshot, selector, isEqual2]), getSelection = _useMemo[0], getServerSelection = _useMemo[1], value = useSyncExternalStore(subscribe, getSelection, getServerSelection); | ||
return useEffect(function() { | ||
inst.hasValue = !0, inst.value = value; | ||
}, [value]), useDebugValue(value), value; | ||
} | ||
useSyncExternalStoreWithSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); | ||
}()), useSyncExternalStoreWithSelector_development; | ||
} | ||
process.env.NODE_ENV === "production" ? withSelector.exports = requireUseSyncExternalStoreWithSelector_production_min() : withSelector.exports = requireUseSyncExternalStoreWithSelector_development(); | ||
var withSelectorExports = withSelector.exports; | ||
function useLiveQuery(initialData, query, queryParams, options) { | ||
const { isEqual: isEqual2 = isFastEqual } = options || {}, defineStore = useContext(defineStoreContext), params = useQueryParams(queryParams), noStore = useMemo( | ||
() => ({ | ||
subscribe: () => () => { | ||
}, | ||
getSnapshot: () => initialData | ||
}), | ||
[initialData] | ||
), store = useMemo( | ||
() => (defineStore == null ? void 0 : defineStore(initialData, query, params)) || { | ||
subscribe: () => () => { | ||
}, | ||
getSnapshot: () => initialData | ||
}, | ||
[defineStore, initialData, params, query] | ||
), [serverSnapshot] = useState(() => { | ||
if (initialData === void 0) | ||
throw new Error( | ||
"initialSnapshot can't be undefined, if you don't want an initial value use null instead" | ||
); | ||
try { | ||
return JSON.parse(JSON.stringify(initialData)); | ||
} catch (error) { | ||
return console.warn( | ||
"Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable", | ||
{ initialSnapshot: initialData, error } | ||
), initialData; | ||
} | ||
}), getServerSnapshot = useCallback(() => serverSnapshot, [serverSnapshot]), selector = useCallback((snapshot2) => snapshot2, []), snapshot = withSelectorExports.useSyncExternalStoreWithSelector( | ||
(store == null ? void 0 : store.subscribe) || noStore.subscribe, | ||
(store == null ? void 0 : store.getSnapshot) || noStore.getSnapshot, | ||
getServerSnapshot, | ||
selector, | ||
isEqual2 | ||
), enabled = defineStore !== null; | ||
return [snapshot, enabled && serverSnapshot === snapshot, enabled]; | ||
} | ||
function useIsEnabled() { | ||
return useContext(defineStoreContext) !== null; | ||
} | ||
const LiveQueryProvider = lazy(() => import("./_chunks-es/LiveQueryProvider.js")); | ||
function createLiveQueryProvider(_options) { | ||
return LiveQueryProvider; | ||
} | ||
export { | ||
LiveQueryProvider, | ||
createLiveQueryProvider, | ||
LiveQueryProvider as default, | ||
useIsEnabled, | ||
useLiveQuery | ||
}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,1 +0,39 @@ | ||
import{jsx as r}from"react/jsx-runtime";import{lazy as i,Children as e,isValidElement as n}from"react";const a=i((()=>import("@sanity/preview-kit/live-query/client-component"))),t={};function o(i){if(!i.enabled)return i.children;const{query:o,params:l=t,initialData:s,as:c}=i;if(c){if(e.count(i.children)>1)throw new Error("LiveQuery: `as` prop can only be used with a single child");if(!n(i.children))throw new Error("LiveQuery: `as` prop requires a valid `children` prop");return r(a,{initialData:s,query:o,params:l,throwOnMissingProvider:i.throwOnMissingProvider,children:r(c,{...i.children.props})})}return r(a,{initialData:s,query:o,params:l,children:i.children})}o.displayName="LiveQuery";export{o as LiveQuery,o as default};//# sourceMappingURL=live-query.js.map | ||
import { jsx } from "react/jsx-runtime"; | ||
import { lazy, Children, isValidElement } from "react"; | ||
const ClientComponent = lazy(() => import("@sanity/preview-kit/live-query/client-component")), DEFAULT_PARAMS = {}; | ||
function LiveQuery(props) { | ||
if (!props.enabled) | ||
return props.children; | ||
const { query, params = DEFAULT_PARAMS, initialData, as: LiveComponent } = props; | ||
if (LiveComponent) { | ||
if (Children.count(props.children) > 1) | ||
throw new Error("LiveQuery: `as` prop can only be used with a single child"); | ||
if (!isValidElement(props.children)) | ||
throw new Error("LiveQuery: `as` prop requires a valid `children` prop"); | ||
return /* @__PURE__ */ jsx( | ||
ClientComponent, | ||
{ | ||
initialData, | ||
query, | ||
params, | ||
throwOnMissingProvider: props.throwOnMissingProvider, | ||
children: /* @__PURE__ */ jsx(LiveComponent, { ...props.children.props }) | ||
} | ||
); | ||
} | ||
return /* @__PURE__ */ jsx( | ||
ClientComponent, | ||
{ | ||
initialData, | ||
query, | ||
params, | ||
children: props.children | ||
} | ||
); | ||
} | ||
LiveQuery.displayName = "LiveQuery"; | ||
export { | ||
LiveQuery, | ||
LiveQuery as default | ||
}; | ||
//# sourceMappingURL=live-query.js.map |
@@ -1,1 +0,56 @@ | ||
"use client";import{useContext as n,useMemo as r,useState as t,useCallback as i,useSyncExternalStore as e,memo as o,isValidElement as a,cloneElement as s,Children as l}from"react";import{useQueryParams as u}from"@sanity/preview-kit-compat";import{d as p}from"../_chunks-es/context.js";function d(){return()=>{}}function c(o){const{initialData:c,query:h,params:f,children:v,throwOnMissingProvider:y=!0}=o,[m,w]=function(o,a,s){const l=n(p),c=u(s),h=r((()=>null==l?void 0:l(o,a,c)),[l,o,c,a]),[f]=t((()=>{if(void 0===o)throw new Error("initialSnapshot can't be undefined, if you don't want an initial value use null instead");try{return JSON.parse(JSON.stringify(o))}catch(n){return console.warn("Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable",{initialSnapshot:o,error:n}),o}})),v=i((()=>f),[f]);return[e((null==h?void 0:h.subscribe)||d,(null==h?void 0:h.getSnapshot)||v,v),null!==l]}(c,h,f);if(y&&!w)throw new Error("<LiveQuery> require you to wrap them in a parent <LiveQueryProvider> when its 'enabled' prop is true, or set the 'throwOnMissingProvider' prop to 'false' to ignore this error");return a(v)?s(v,{...v.props,data:m,ref:v.ref}):l.count(v)>1?l.only(null):null}c.displayName="LiveQueryClientComponent";const h=o(c);export{h as default};//# sourceMappingURL=client-component.js.map | ||
"use client"; | ||
import { useContext, useMemo, useState, useCallback, useSyncExternalStore, memo, isValidElement, cloneElement, Children } from "react"; | ||
import { useQueryParams } from "@sanity/preview-kit-compat"; | ||
import { defineStoreContext } from "../_chunks-es/context.js"; | ||
function useLiveQuery(initialData, query, queryParams2) { | ||
const defineStore = useContext(defineStoreContext), queryParams = useQueryParams(queryParams2), store = useMemo( | ||
() => defineStore == null ? void 0 : defineStore(initialData, query, queryParams), | ||
[defineStore, initialData, queryParams, query] | ||
), [serverSnapshot] = useState(() => { | ||
if (initialData === void 0) | ||
throw new Error( | ||
"initialSnapshot can't be undefined, if you don't want an initial value use null instead" | ||
); | ||
try { | ||
return JSON.parse(JSON.stringify(initialData)); | ||
} catch (error) { | ||
return console.warn( | ||
"Failed to deep clone initialSnapshot, this is likely an error and an indication that the snapshot isn't JSON serializable", | ||
{ initialSnapshot: initialData, error } | ||
), initialData; | ||
} | ||
}), getServerSnapshot = useCallback(() => serverSnapshot, [serverSnapshot]); | ||
return [ | ||
useSyncExternalStore( | ||
(store == null ? void 0 : store.subscribe) || noop, | ||
(store == null ? void 0 : store.getSnapshot) || getServerSnapshot, | ||
getServerSnapshot | ||
), | ||
defineStore !== null | ||
]; | ||
} | ||
function noop() { | ||
return () => { | ||
}; | ||
} | ||
function LiveQueryClientComponent(props) { | ||
const { initialData, query, params, children, throwOnMissingProvider = !0 } = props, [data, enabled] = useLiveQuery(initialData, query, params); | ||
if (throwOnMissingProvider && !enabled) | ||
throw new Error( | ||
"<LiveQuery> require you to wrap them in a parent <LiveQueryProvider> when its 'enabled' prop is true, or set the 'throwOnMissingProvider' prop to 'false' to ignore this error" | ||
); | ||
return isValidElement(children) ? cloneElement(children, { | ||
...children.props, | ||
// all child props should override, except for `data` | ||
data, | ||
// eslint-disable-next-line no-warning-comments | ||
// @ts-expect-error -- @todo fix the typings | ||
ref: children.ref | ||
}) : Children.count(children) > 1 ? Children.only(null) : null; | ||
} | ||
LiveQueryClientComponent.displayName = "LiveQueryClientComponent"; | ||
const LiveQueryClientComponentMemo = memo(LiveQueryClientComponent); | ||
export { | ||
LiveQueryClientComponentMemo as default | ||
}; | ||
//# sourceMappingURL=client-component.js.map |
{ | ||
"name": "@sanity/preview-kit", | ||
"version": "5.1.1", | ||
"version": "5.1.2", | ||
"description": "General purpose utils for live content and visual editing", | ||
@@ -94,3 +94,3 @@ "keywords": [ | ||
"@sanity/pkg-utils": "6.9.0", | ||
"@sanity/prettier-config": "^1.0.2", | ||
"@sanity/prettier-config": "^1.0.3", | ||
"@sanity/semantic-release-preset": "^5.0.0", | ||
@@ -97,0 +97,0 @@ "@types/node": "^18.18.6", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
518480
3645
0
1