@clerk/shared
Advanced tools
Comparing version 0.11.4 to 0.11.5-staging.0
@@ -1,2 +0,1110 @@ | ||
import{A as tr,B as rr,C as nr,D as ir,E as ar,F as or,G as sr,H as ur,I as lr,J as fr,K as cr,L as dr,M as vr,N as gr,O as mr,P as hr,Q as pr,R as br,S as Or,T as yr,U as Cr,V as zr,c as St,d as Pt,e as kt,f as Ut,g as At,h as Dt,i as Vt,j as Ft,k as Wt,l as _t,m as Nt,n as Kt,o as $t,p as Ht,q as Gt,r as qt,s as jt,t as Jt,u as Yt,v as Bt,w as Zt,x as Qt,y as Xt,z as er}from"./chunk-PWBOXFOC.js";var tt=Object.freeze({InvalidFrontendApiErrorMessage:"The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})",InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.dev/last-active?path=api-keys."});function Rr({packageName:e,customMessages:i}){let t=e,n={...tt,...i};function a(r,o){if(!o)return`${t}: ${r}`;let l=r,d=r.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);for(let s of d){let f=(o[s[1]]||"").toString();l=l.replace(`{{${s[1]}}}`,f)}return`${t}: ${l}`}return{setPackageName({packageName:r}){return typeof r=="string"&&(t=r),this},setMessages({customMessages:r}){return Object.assign(n,r||{}),this},throwInvalidPublishableKeyError(r){throw new Error(a(n.InvalidPublishableKeyErrorMessage,r))},throwInvalidFrontendApiError(r){throw new Error(a(n.InvalidFrontendApiErrorMessage,r))},throwInvalidProxyUrl(r){throw new Error(a(n.InvalidProxyUrlErrorMessage,r))},throwMissingPublishableKeyError(){throw new Error(a(n.MissingPublishableKeyErrorMessage))}}}import de from"react";function rt(e,i){if(!e)throw typeof i=="string"?new Error(i):new Error(`${i.displayName} not found`)}var H=(e,i)=>{let{assertCtxFn:t=rt}=i||{},n=de.createContext(void 0);return n.displayName=e,[n,()=>{let o=de.useContext(n);return t(o,`${e} not found`),o.value},()=>{let o=de.useContext(n);return o?o.value:{}}]};var[Ir,G]=H("ClerkInstanceContext"),[Sr,Ie]=H("UserContext"),[Pr,kr]=H("ClientContext"),[Ur,Se]=H("SessionContext"),[Ar,Pe]=H("OrganizationContext");import{useEffect as nt,useLayoutEffect as it,createContext as at,useContext as De,useState as Ve,createElement as ot,useRef as W,useCallback as me,useDebugValue as st}from"react";function Fe(e,i,t,n){function a(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function l(f){try{s(n.next(f))}catch(v){o(v)}}function d(f){try{s(n.throw(f))}catch(v){o(v)}}function s(f){f.done?r(f.value):a(f.value).then(l,d)}s((n=n.apply(e,i||[])).next())})}function We(e,i){var t={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},n,a,r,o;return o={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function l(s){return function(f){return d([s,f])}}function d(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,a&&(r=s[0]&2?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[s[0]&2,r.value]),s[0]){case 0:case 1:r=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,a=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(r=t.trys,!(r=r.length>0&&r[r.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!r||s[1]>r[0]&&s[1]<r[3])){t.label=s[1];break}if(s[0]===6&&t.label<r[1]){t.label=r[1],r=s;break}if(r&&t.label<r[2]){t.label=r[2],t.ops.push(s);break}r[2]&&t.ops.pop(),t.trys.pop();continue}s=i.call(e,t)}catch(f){s=[6,f],a=0}finally{n=r=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var M=function(){},h=M(),Q=Object,b=function(e){return e===h},U=function(e){return typeof e=="function"},S=function(e,i){return Q.assign({},e,i)},Ce="undefined",ze=function(){return typeof window!=Ce},ut=function(){return typeof document!=Ce},lt=function(){return ze()&&typeof window.requestAnimationFrame!=Ce},ie=new WeakMap,ft=0,te=function(e){var i=typeof e,t=e&&e.constructor,n=t==Date,a,r;if(Q(e)===e&&!n&&t!=RegExp){if(a=ie.get(e),a)return a;if(a=++ft+"~",ie.set(e,a),t==Array){for(a="@",r=0;r<e.length;r++)a+=te(e[r])+",";ie.set(e,a)}if(t==Q){a="#";for(var o=Q.keys(e).sort();!b(r=o.pop());)b(e[r])||(a+=r+":"+te(e[r])+",");ie.set(e,a)}}else a=n?e.toJSON():i=="symbol"?e.toString():i=="string"?JSON.stringify(e):""+e;return a},he=!0,ct=function(){return he},_e=ze(),Re=ut(),pe=_e&&window.addEventListener?window.addEventListener.bind(window):M,dt=Re?document.addEventListener.bind(document):M,be=_e&&window.removeEventListener?window.removeEventListener.bind(window):M,vt=Re?document.removeEventListener.bind(document):M,gt=function(){var e=Re&&document.visibilityState;return b(e)||e!=="hidden"},mt=function(e){return dt("visibilitychange",e),pe("focus",e),function(){vt("visibilitychange",e),be("focus",e)}},ht=function(e){var i=function(){he=!0,e()},t=function(){he=!1};return pe("online",i),pe("offline",t),function(){be("online",i),be("offline",t)}},pt={isOnline:ct,isVisible:gt},bt={initFocus:mt,initReconnect:ht},ae=!ze()||"Deno"in window,Ot=function(e){return lt()?window.requestAnimationFrame(e):setTimeout(e,1)},X=ae?nt:it,ve=typeof navigator<"u"&&navigator.connection,ke=!ae&&ve&&(["slow-2g","2g"].includes(ve.effectiveType)||ve.saveData),Ne=function(e){if(U(e))try{e=e()}catch{e=""}var i=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?te(e):"";var t=e?"$swr$"+e:"";return[e,i,t]},_=new WeakMap,Ke=0,$e=1,He=2,ee=function(e,i,t,n,a,r,o){o===void 0&&(o=!0);var l=_.get(e),d=l[0],s=l[1],f=l[3],v=d[i],c=s[i];if(o&&c)for(var z=0;z<c.length;++z)c[z](t,n,a);return r&&(delete f[i],v&&v[0])?v[0](He).then(function(){return e.get(i)}):e.get(i)},yt=0,Oe=function(){return++yt},Ge=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return Fe(void 0,void 0,void 0,function(){var t,n,a,r,o,l,d,s,f,v,c,z,N,O,g,u,q,A,T,E,D;return We(this,function(P){switch(P.label){case 0:if(t=e[0],n=e[1],a=e[2],r=e[3],o=typeof r=="boolean"?{revalidate:r}:r||{},l=b(o.populateCache)?!0:o.populateCache,d=o.revalidate!==!1,s=o.rollbackOnError!==!1,f=o.optimisticData,v=Ne(n),c=v[0],z=v[2],!c)return[2];if(N=_.get(t),O=N[2],e.length<3)return[2,ee(t,c,t.get(c),h,h,d,!0)];if(g=a,q=Oe(),O[c]=[q,0],A=!b(f),T=t.get(c),A&&(E=U(f)?f(T):f,t.set(c,E),ee(t,c,E)),U(g))try{g=g(t.get(c))}catch(V){u=V}return g&&U(g.then)?[4,g.catch(function(V){u=V})]:[3,2];case 1:if(g=P.sent(),q!==O[c][0]){if(u)throw u;return[2,g]}else u&&A&&s&&(l=!0,g=T,t.set(c,T));P.label=2;case 2:return l&&(u||(U(l)&&(g=l(g,T)),t.set(c,g)),t.set(z,S(t.get(z),{error:u}))),O[c][1]=Oe(),[4,ee(t,c,g,u,h,d,!!l)];case 3:if(D=P.sent(),u)throw u;return[2,l?D:g]}})})},Ue=function(e,i){for(var t in e)e[t][0]&&e[t][0](i)},qe=function(e,i){if(!_.has(e)){var t=S(bt,i),n={},a=Ge.bind(h,e),r=M;if(_.set(e,[n,{},{},{},a]),!ae){var o=t.initFocus(setTimeout.bind(h,Ue.bind(h,n,Ke))),l=t.initReconnect(setTimeout.bind(h,Ue.bind(h,n,$e)));r=function(){o&&o(),l&&l(),_.delete(e)}}return[e,a,r]}return[e,_.get(e)[4]]},Ct=function(e,i,t,n,a){var r=t.errorRetryCount,o=a.retryCount,l=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!b(r)&&o>r||setTimeout(n,l,a)},je=qe(new Map),Je=je[0],zt=je[1],Ye=S({onLoadingSlow:M,onSuccess:M,onError:M,onErrorRetry:Ct,onDiscarded:M,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:ke?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:ke?5e3:3e3,compare:function(e,i){return te(e)==te(i)},isPaused:function(){return!1},cache:Je,mutate:zt,fallback:{}},pt),Be=function(e,i){var t=S(e,i);if(i){var n=e.use,a=e.fallback,r=i.use,o=i.fallback;n&&r&&(t.use=n.concat(r)),a&&o&&(t.fallback=S(a,o))}return t},ye=at({}),Rt=function(e){var i=e.value,t=Be(De(ye),i),n=i&&i.provider,a=Ve(function(){return n?qe(n(t.cache||Je),i):h})[0];return a&&(t.cache=a[0],t.mutate=a[1]),X(function(){return a?a[2]:h},[]),ot(ye.Provider,S(e,{value:t}))},xt=function(e,i){var t=Ve({})[1],n=W(e),a=W({data:!1,error:!1,isValidating:!1}),r=me(function(o){var l=!1,d=n.current;for(var s in o){var f=s;d[f]!==o[f]&&(d[f]=o[f],a.current[f]&&(l=!0))}l&&!i.current&&t({})},[]);return X(function(){n.current=e}),[n,a.current,r]},Et=function(e){return U(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},wt=function(){return S(Ye,De(ye))},Lt=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var a=wt(),r=Et(t),o=r[0],l=r[1],d=r[2],s=Be(a,d),f=e,v=s.use;if(v)for(var c=v.length;c-- >0;)f=v[c](f);return f(o,l||s.fetcher,s)}},Ae=function(e,i,t){var n=i[e]||(i[e]=[]);return n.push(t),function(){var a=n.indexOf(t);a>=0&&(n[a]=n[n.length-1],n.pop())}},ge={dedupe:!0},Mt=function(e,i,t){var n=t.cache,a=t.compare,r=t.fallbackData,o=t.suspense,l=t.revalidateOnMount,d=t.refreshInterval,s=t.refreshWhenHidden,f=t.refreshWhenOffline,v=_.get(n),c=v[0],z=v[1],N=v[2],O=v[3],g=Ne(e),u=g[0],q=g[1],A=g[2],T=W(!1),E=W(!1),D=W(u),P=W(i),V=W(t),m=function(){return V.current},oe=function(){return m().isVisible()&&m().isOnline()},re=function(R){return n.set(A,S(n.get(A),R))},Ee=n.get(u),Qe=b(r)?t.fallback[u]:r,I=b(Ee)?Qe:Ee,we=n.get(A)||{},j=we.error,Le=!T.current,Me=function(){return Le&&!b(l)?l:m().isPaused()?!1:o?b(I)?!1:t.revalidateIfStale:b(I)||t.revalidateIfStale},Xe=function(){return!u||!i?!1:we.isValidating?!0:Le&&Me()},se=Xe(),ue=xt({data:I,error:j,isValidating:se},E),K=ue[0],le=ue[1],ne=ue[2],F=me(function(R){return Fe(void 0,void 0,void 0,function(){var y,C,x,J,Y,w,p,k,L,fe,B,$,ce;return We(this,function(Z){switch(Z.label){case 0:if(y=P.current,!u||!y||E.current||m().isPaused())return[2,!1];J=!0,Y=R||{},w=!O[u]||!Y.dedupe,p=function(){return!E.current&&u===D.current&&T.current},k=function(){var Te=O[u];Te&&Te[1]===x&&delete O[u]},L={isValidating:!1},fe=function(){re({isValidating:!1}),p()&&ne(L)},re({isValidating:!0}),ne({isValidating:!0}),Z.label=1;case 1:return Z.trys.push([1,3,,4]),w&&(ee(n,u,K.current.data,K.current.error,!0),t.loadingTimeout&&!n.get(u)&&setTimeout(function(){J&&p()&&m().onLoadingSlow(u,t)},t.loadingTimeout),O[u]=[y.apply(void 0,q),Oe()]),ce=O[u],C=ce[0],x=ce[1],[4,C];case 2:return C=Z.sent(),w&&setTimeout(k,t.dedupingInterval),!O[u]||O[u][1]!==x?(w&&p()&&m().onDiscarded(u),[2,!1]):(re({error:h}),L.error=h,B=N[u],!b(B)&&(x<=B[0]||x<=B[1]||B[1]===0)?(fe(),w&&p()&&m().onDiscarded(u),[2,!1]):(a(K.current.data,C)?L.data=K.current.data:L.data=C,a(n.get(u),C)||n.set(u,C),w&&p()&&m().onSuccess(C,u,t),[3,4]));case 3:return $=Z.sent(),k(),m().isPaused()||(re({error:$}),L.error=$,w&&p()&&(m().onError($,u,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||U(t.shouldRetryOnError)&&t.shouldRetryOnError($))&&oe()&&m().onErrorRetry($,u,t,F,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return J=!1,fe(),p()&&w&&ee(n,u,L.data,L.error,!1),[2,!0]}})})},[u]),et=me(Ge.bind(h,n,function(){return D.current}),[]);if(X(function(){P.current=i,V.current=t}),X(function(){if(!!u){var R=u!==D.current,y=F.bind(h,ge),C=function(p,k,L){ne(S({error:k,isValidating:L},a(K.current.data,p)?h:{data:p}))},x=0,J=function(p){if(p==Ke){var k=Date.now();m().revalidateOnFocus&&k>x&&oe()&&(x=k+m().focusThrottleInterval,y())}else if(p==$e)m().revalidateOnReconnect&&oe()&&y();else if(p==He)return F()},Y=Ae(u,z,C),w=Ae(u,c,J);return E.current=!1,D.current=u,T.current=!0,R&&ne({data:I,error:j,isValidating:se}),Me()&&(b(I)||ae?y():Ot(y)),function(){E.current=!0,Y(),w()}}},[u,F]),X(function(){var R;function y(){var x=U(d)?d(I):d;x&&R!==-1&&(R=setTimeout(C,x))}function C(){!K.current.error&&(s||m().isVisible())&&(f||m().isOnline())?F(ge).then(y):y()}return y(),function(){R&&(clearTimeout(R),R=-1)}},[d,s,f,F]),st(I),o&&b(I)&&u)throw P.current=i,V.current=t,E.current=!1,b(j)?F(ge):j;return{mutate:et,get data(){return le.data=!0,I},get error(){return le.error=!0,j},get isValidating(){return le.isValidating=!0,se}}},Fr=Q.defineProperty(Rt,"default",{value:Ye});var xe=Lt(Mt);var Kr=e=>{let{invitationList:i,membershipList:t}=e||{},{organization:n,lastOrganizationMember:a,lastOrganizationInvitation:r}=Pe(),o=Se(),l=G(),d=l.loaded&&o&&n,s=l.loaded?()=>l.organization?.getPendingInvitations(i):()=>[],f=l.loaded?()=>l.organization?.getMemberships(t):()=>[],{data:v,isValidating:c,mutate:z}=xe(d&&i?Ze("invites",n,r,i):null,s),{data:N,isValidating:O,mutate:g}=xe(d&&t?Ze("memberships",n,a,t):null,f);return n===void 0?{isLoaded:!1,organization:void 0,invitationList:void 0,membershipList:void 0,membership:void 0}:n===null?{isLoaded:!0,organization:null,invitationList:null,membershipList:null,membership:null}:!l.loaded&&n?{isLoaded:!0,organization:n,invitationList:void 0,membershipList:void 0,membership:void 0}:{isLoaded:!O&&!c,organization:n,membershipList:N,membership:Tt(o.user.organizationMemberships,n.id),invitationList:v,unstable__mutate:()=>{g(),z()}}};function Tt(e,i){return e.find(t=>t.organization.id===i)}function Ze(e,i,t,n){return[e,i.id,t?.id,t?.updatedAt,n.offset,n.limit].filter(Boolean).join("-")}var Gr=()=>{let e=G(),i=Ie();return!e.loaded||!i?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:It(i.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function It(e){return e.map(i=>({membership:i,organization:i.organization}))}var Jr=()=>{let e=G();return e.loaded?{isLoaded:!0,createOrganization:e.createOrganization,getOrganizationMemberships:e.getOrganizationMemberships,getOrganization:e.getOrganization}:{isLoaded:!1,createOrganization:void 0,getOrganizationMemberships:void 0,getOrganization:void 0}};export{Ir as ClerkInstanceContext,Pr as ClientContext,ar as LocalStorageBroadcastChannel,Ar as OrganizationContext,mr as Poller,Ur as SessionContext,Sr as UserContext,Zt as addYears,rt as assertContextExists,Rr as buildErrorThrower,er as buildPublishableKey,cr as camelToSnake,Ht as colorToSameTypeString,H as createContextAndHook,qt as createCookieHandler,zr as createDeferredPromise,gr as createWorkerTimers,jt as dateTo12HourTime,dr as deepCamelToSnake,vr as deepSnakeToCamel,kt as detectUserAgentRobot,Jt as differenceInCalendarDays,or as extension,Bt as formatRelative,Nt as hasAlpha,Gt as hexStringToRgbaColor,Pt as inBrowser,Or as inClientSide,Wt as isHSLColor,ur as isIPV4Address,nr as isLegacyFrontendApiKey,pr as isProxyUrlRelative,rr as isPublishableKey,Ft as isRGBColor,ir as isRetinaDisplay,_t as isTransparent,Ut as isValidBrowserOnline,At as isValidHexString,Vt as isValidHslaString,hr as isValidProxyUrl,Dt as isValidRgbaString,Xt as isomorphicAtob,sr as noop,Yt as normalizeDate,tr as parsePublishableKey,yr as parseSearchParams,br as proxyUrlToAbsoluteURL,Qt as readJSONFile,Cr as runWithExponentialBackOff,fr as snakeToCamel,Kt as stringToHslaColor,$t as stringToSameTypeColor,lr as titleize,St as toSentence,G as useClerkInstanceContext,kr as useClientContext,Kr as useOrganization,Pe as useOrganizationContext,Gr as useOrganizationList,Jr as useOrganizations,Se as useSessionContext,Ie as useUserContext}; | ||
import { | ||
LocalStorageBroadcastChannel, | ||
Poller, | ||
addYears, | ||
buildPublishableKey, | ||
camelToSnake, | ||
colorToSameTypeString, | ||
createCookieHandler, | ||
createDeferredPromise, | ||
createWorkerTimers, | ||
dateTo12HourTime, | ||
deepCamelToSnake, | ||
deepSnakeToCamel, | ||
detectUserAgentRobot, | ||
differenceInCalendarDays, | ||
extension, | ||
formatRelative, | ||
hasAlpha, | ||
hexStringToRgbaColor, | ||
inBrowser, | ||
inClientSide, | ||
isHSLColor, | ||
isHttpOrHttps, | ||
isIPV4Address, | ||
isLegacyFrontendApiKey, | ||
isProxyUrlRelative, | ||
isPublishableKey, | ||
isRGBColor, | ||
isRetinaDisplay, | ||
isTransparent, | ||
isValidBrowserOnline, | ||
isValidHexString, | ||
isValidHslaString, | ||
isValidProxyUrl, | ||
isValidRgbaString, | ||
isomorphicAtob, | ||
noop, | ||
normalizeDate, | ||
parsePublishableKey, | ||
parseSearchParams, | ||
proxyUrlToAbsoluteURL, | ||
readJSONFile, | ||
runWithExponentialBackOff, | ||
snakeToCamel, | ||
stringToHslaColor, | ||
stringToSameTypeColor, | ||
titleize, | ||
toSentence | ||
} from "./chunk-NF4BDGZ5.js"; | ||
// src/errors/thrower.ts | ||
var DefaultMessages = Object.freeze({ | ||
InvalidFrontendApiErrorMessage: `The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})`, | ||
InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`, | ||
InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})`, | ||
MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.dev/last-active?path=api-keys.` | ||
}); | ||
function buildErrorThrower({ packageName, customMessages }) { | ||
let pkg = packageName; | ||
const messages = { | ||
...DefaultMessages, | ||
...customMessages | ||
}; | ||
function buildMessage(rawMessage, replacements) { | ||
if (!replacements) { | ||
return `${pkg}: ${rawMessage}`; | ||
} | ||
let msg = rawMessage; | ||
const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g); | ||
for (const match of matches) { | ||
const replacement = (replacements[match[1]] || "").toString(); | ||
msg = msg.replace(`{{${match[1]}}}`, replacement); | ||
} | ||
return `${pkg}: ${msg}`; | ||
} | ||
return { | ||
setPackageName({ packageName: packageName2 }) { | ||
if (typeof packageName2 === "string") { | ||
pkg = packageName2; | ||
} | ||
return this; | ||
}, | ||
setMessages({ customMessages: customMessages2 }) { | ||
Object.assign(messages, customMessages2 || {}); | ||
return this; | ||
}, | ||
throwInvalidPublishableKeyError(params) { | ||
throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params)); | ||
}, | ||
throwInvalidFrontendApiError(params) { | ||
throw new Error(buildMessage(messages.InvalidFrontendApiErrorMessage, params)); | ||
}, | ||
throwInvalidProxyUrl(params) { | ||
throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params)); | ||
}, | ||
throwMissingPublishableKeyError() { | ||
throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage)); | ||
} | ||
}; | ||
} | ||
// src/hooks/createContextAndHook.ts | ||
import React from "react"; | ||
function assertContextExists(contextVal, msgOrCtx) { | ||
if (!contextVal) { | ||
throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`); | ||
} | ||
} | ||
var createContextAndHook = (displayName, options) => { | ||
const { assertCtxFn = assertContextExists } = options || {}; | ||
const Ctx = React.createContext(void 0); | ||
Ctx.displayName = displayName; | ||
const useCtx = () => { | ||
const ctx = React.useContext(Ctx); | ||
assertCtxFn(ctx, `${displayName} not found`); | ||
return ctx.value; | ||
}; | ||
const useCtxWithoutGuarantee = () => { | ||
const ctx = React.useContext(Ctx); | ||
return ctx ? ctx.value : {}; | ||
}; | ||
return [Ctx, useCtx, useCtxWithoutGuarantee]; | ||
}; | ||
// src/hooks/contexts.tsx | ||
var [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext"); | ||
var [UserContext, useUserContext] = createContextAndHook("UserContext"); | ||
var [ClientContext, useClientContext] = createContextAndHook("ClientContext"); | ||
var [SessionContext, useSessionContext] = createContextAndHook( | ||
"SessionContext" | ||
); | ||
var [OrganizationContext, useOrganizationContext] = createContextAndHook("OrganizationContext"); | ||
// ../../node_modules/swr/dist/index.mjs | ||
import { useEffect, useLayoutEffect, createContext, useContext, useState, createElement, useRef, useCallback, useDebugValue } from "react"; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function(resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
return new (P || (P = Promise))(function(resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { | ||
if (t[0] & 1) | ||
throw t[1]; | ||
return t[1]; | ||
}, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { | ||
return this; | ||
}), g; | ||
function verb(n) { | ||
return function(v) { | ||
return step([n, v]); | ||
}; | ||
} | ||
function step(op) { | ||
if (f) | ||
throw new TypeError("Generator is already executing."); | ||
while (_) | ||
try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) | ||
return t; | ||
if (y = 0, t) | ||
op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: | ||
case 1: | ||
t = op; | ||
break; | ||
case 4: | ||
_.label++; | ||
return { value: op[1], done: false }; | ||
case 5: | ||
_.label++; | ||
y = op[1]; | ||
op = [0]; | ||
continue; | ||
case 7: | ||
op = _.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { | ||
_ = 0; | ||
continue; | ||
} | ||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { | ||
_.label = op[1]; | ||
break; | ||
} | ||
if (op[0] === 6 && _.label < t[1]) { | ||
_.label = t[1]; | ||
t = op; | ||
break; | ||
} | ||
if (t && _.label < t[2]) { | ||
_.label = t[2]; | ||
_.ops.push(op); | ||
break; | ||
} | ||
if (t[2]) | ||
_.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { | ||
op = [6, e]; | ||
y = 0; | ||
} finally { | ||
f = t = 0; | ||
} | ||
if (op[0] & 5) | ||
throw op[1]; | ||
return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
var noop2 = function() { | ||
}; | ||
var UNDEFINED = noop2(); | ||
var OBJECT = Object; | ||
var isUndefined = function(v) { | ||
return v === UNDEFINED; | ||
}; | ||
var isFunction = function(v) { | ||
return typeof v == "function"; | ||
}; | ||
var mergeObjects = function(a, b) { | ||
return OBJECT.assign({}, a, b); | ||
}; | ||
var STR_UNDEFINED = "undefined"; | ||
var hasWindow = function() { | ||
return typeof window != STR_UNDEFINED; | ||
}; | ||
var hasDocument = function() { | ||
return typeof document != STR_UNDEFINED; | ||
}; | ||
var hasRequestAnimationFrame = function() { | ||
return hasWindow() && typeof window["requestAnimationFrame"] != STR_UNDEFINED; | ||
}; | ||
var table = /* @__PURE__ */ new WeakMap(); | ||
var counter = 0; | ||
var stableHash = function(arg) { | ||
var type = typeof arg; | ||
var constructor = arg && arg.constructor; | ||
var isDate = constructor == Date; | ||
var result; | ||
var index; | ||
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) { | ||
result = table.get(arg); | ||
if (result) | ||
return result; | ||
result = ++counter + "~"; | ||
table.set(arg, result); | ||
if (constructor == Array) { | ||
result = "@"; | ||
for (index = 0; index < arg.length; index++) { | ||
result += stableHash(arg[index]) + ","; | ||
} | ||
table.set(arg, result); | ||
} | ||
if (constructor == OBJECT) { | ||
result = "#"; | ||
var keys = OBJECT.keys(arg).sort(); | ||
while (!isUndefined(index = keys.pop())) { | ||
if (!isUndefined(arg[index])) { | ||
result += index + ":" + stableHash(arg[index]) + ","; | ||
} | ||
} | ||
table.set(arg, result); | ||
} | ||
} else { | ||
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg; | ||
} | ||
return result; | ||
}; | ||
var online = true; | ||
var isOnline = function() { | ||
return online; | ||
}; | ||
var hasWin = hasWindow(); | ||
var hasDoc = hasDocument(); | ||
var onWindowEvent = hasWin && window.addEventListener ? window.addEventListener.bind(window) : noop2; | ||
var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop2; | ||
var offWindowEvent = hasWin && window.removeEventListener ? window.removeEventListener.bind(window) : noop2; | ||
var offDocumentEvent = hasDoc ? document.removeEventListener.bind(document) : noop2; | ||
var isVisible = function() { | ||
var visibilityState = hasDoc && document.visibilityState; | ||
return isUndefined(visibilityState) || visibilityState !== "hidden"; | ||
}; | ||
var initFocus = function(callback) { | ||
onDocumentEvent("visibilitychange", callback); | ||
onWindowEvent("focus", callback); | ||
return function() { | ||
offDocumentEvent("visibilitychange", callback); | ||
offWindowEvent("focus", callback); | ||
}; | ||
}; | ||
var initReconnect = function(callback) { | ||
var onOnline = function() { | ||
online = true; | ||
callback(); | ||
}; | ||
var onOffline = function() { | ||
online = false; | ||
}; | ||
onWindowEvent("online", onOnline); | ||
onWindowEvent("offline", onOffline); | ||
return function() { | ||
offWindowEvent("online", onOnline); | ||
offWindowEvent("offline", onOffline); | ||
}; | ||
}; | ||
var preset = { | ||
isOnline, | ||
isVisible | ||
}; | ||
var defaultConfigOptions = { | ||
initFocus, | ||
initReconnect | ||
}; | ||
var IS_SERVER = !hasWindow() || "Deno" in window; | ||
var rAF = function(f) { | ||
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1); | ||
}; | ||
var useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect; | ||
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection; | ||
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData); | ||
var serialize = function(key) { | ||
if (isFunction(key)) { | ||
try { | ||
key = key(); | ||
} catch (err) { | ||
key = ""; | ||
} | ||
} | ||
var args = [].concat(key); | ||
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : ""; | ||
var infoKey = key ? "$swr$" + key : ""; | ||
return [key, args, infoKey]; | ||
}; | ||
var SWRGlobalState = /* @__PURE__ */ new WeakMap(); | ||
var FOCUS_EVENT = 0; | ||
var RECONNECT_EVENT = 1; | ||
var MUTATE_EVENT = 2; | ||
var broadcastState = function(cache2, key, data, error, isValidating, revalidate, broadcast) { | ||
if (broadcast === void 0) { | ||
broadcast = true; | ||
} | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], FETCH = _a2[3]; | ||
var revalidators = EVENT_REVALIDATORS[key]; | ||
var updaters = STATE_UPDATERS[key]; | ||
if (broadcast && updaters) { | ||
for (var i = 0; i < updaters.length; ++i) { | ||
updaters[i](data, error, isValidating); | ||
} | ||
} | ||
if (revalidate) { | ||
delete FETCH[key]; | ||
if (revalidators && revalidators[0]) { | ||
return revalidators[0](MUTATE_EVENT).then(function() { | ||
return cache2.get(key); | ||
}); | ||
} | ||
} | ||
return cache2.get(key); | ||
}; | ||
var __timestamp = 0; | ||
var getTimestamp = function() { | ||
return ++__timestamp; | ||
}; | ||
var internalMutate = function() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var cache2, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, customOptimisticData, _a2, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasCustomOptimisticData, rollbackData, optimisticData, res; | ||
return __generator(this, function(_c) { | ||
switch (_c.label) { | ||
case 0: | ||
cache2 = args[0], _key = args[1], _data = args[2], _opts = args[3]; | ||
options = typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {}; | ||
populateCache = isUndefined(options.populateCache) ? true : options.populateCache; | ||
revalidate = options.revalidate !== false; | ||
rollbackOnError = options.rollbackOnError !== false; | ||
customOptimisticData = options.optimisticData; | ||
_a2 = serialize(_key), key = _a2[0], keyInfo = _a2[2]; | ||
if (!key) | ||
return [2]; | ||
_b = SWRGlobalState.get(cache2), MUTATION = _b[2]; | ||
if (args.length < 3) { | ||
return [2, broadcastState(cache2, key, cache2.get(key), UNDEFINED, UNDEFINED, revalidate, true)]; | ||
} | ||
data = _data; | ||
beforeMutationTs = getTimestamp(); | ||
MUTATION[key] = [beforeMutationTs, 0]; | ||
hasCustomOptimisticData = !isUndefined(customOptimisticData); | ||
rollbackData = cache2.get(key); | ||
if (hasCustomOptimisticData) { | ||
optimisticData = isFunction(customOptimisticData) ? customOptimisticData(rollbackData) : customOptimisticData; | ||
cache2.set(key, optimisticData); | ||
broadcastState(cache2, key, optimisticData); | ||
} | ||
if (isFunction(data)) { | ||
try { | ||
data = data(cache2.get(key)); | ||
} catch (err) { | ||
error = err; | ||
} | ||
} | ||
if (!(data && isFunction(data.then))) | ||
return [3, 2]; | ||
return [ | ||
4, | ||
data.catch(function(err) { | ||
error = err; | ||
}) | ||
]; | ||
case 1: | ||
data = _c.sent(); | ||
if (beforeMutationTs !== MUTATION[key][0]) { | ||
if (error) | ||
throw error; | ||
return [2, data]; | ||
} else if (error && hasCustomOptimisticData && rollbackOnError) { | ||
populateCache = true; | ||
data = rollbackData; | ||
cache2.set(key, rollbackData); | ||
} | ||
_c.label = 2; | ||
case 2: | ||
if (populateCache) { | ||
if (!error) { | ||
if (isFunction(populateCache)) { | ||
data = populateCache(data, rollbackData); | ||
} | ||
cache2.set(key, data); | ||
} | ||
cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), { error })); | ||
} | ||
MUTATION[key][1] = getTimestamp(); | ||
return [ | ||
4, | ||
broadcastState(cache2, key, data, error, UNDEFINED, revalidate, !!populateCache) | ||
]; | ||
case 3: | ||
res = _c.sent(); | ||
if (error) | ||
throw error; | ||
return [2, populateCache ? res : data]; | ||
} | ||
}); | ||
}); | ||
}; | ||
var revalidateAllKeys = function(revalidators, type) { | ||
for (var key in revalidators) { | ||
if (revalidators[key][0]) | ||
revalidators[key][0](type); | ||
} | ||
}; | ||
var initCache = function(provider, options) { | ||
if (!SWRGlobalState.has(provider)) { | ||
var opts = mergeObjects(defaultConfigOptions, options); | ||
var EVENT_REVALIDATORS = {}; | ||
var mutate2 = internalMutate.bind(UNDEFINED, provider); | ||
var unmount = noop2; | ||
SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate2]); | ||
if (!IS_SERVER) { | ||
var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT))); | ||
var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT))); | ||
unmount = function() { | ||
releaseFocus_1 && releaseFocus_1(); | ||
releaseReconnect_1 && releaseReconnect_1(); | ||
SWRGlobalState.delete(provider); | ||
}; | ||
} | ||
return [provider, mutate2, unmount]; | ||
} | ||
return [provider, SWRGlobalState.get(provider)[4]]; | ||
}; | ||
var onErrorRetry = function(_, __, config, revalidate, opts) { | ||
var maxRetryCount = config.errorRetryCount; | ||
var currentRetryCount = opts.retryCount; | ||
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval; | ||
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) { | ||
return; | ||
} | ||
setTimeout(revalidate, timeout, opts); | ||
}; | ||
var _a = initCache(/* @__PURE__ */ new Map()); | ||
var cache = _a[0]; | ||
var mutate = _a[1]; | ||
var defaultConfig = mergeObjects( | ||
{ | ||
onLoadingSlow: noop2, | ||
onSuccess: noop2, | ||
onError: noop2, | ||
onErrorRetry, | ||
onDiscarded: noop2, | ||
revalidateOnFocus: true, | ||
revalidateOnReconnect: true, | ||
revalidateIfStale: true, | ||
shouldRetryOnError: true, | ||
errorRetryInterval: slowConnection ? 1e4 : 5e3, | ||
focusThrottleInterval: 5 * 1e3, | ||
dedupingInterval: 2 * 1e3, | ||
loadingTimeout: slowConnection ? 5e3 : 3e3, | ||
compare: function(currentData, newData) { | ||
return stableHash(currentData) == stableHash(newData); | ||
}, | ||
isPaused: function() { | ||
return false; | ||
}, | ||
cache, | ||
mutate, | ||
fallback: {} | ||
}, | ||
preset | ||
); | ||
var mergeConfigs = function(a, b) { | ||
var v = mergeObjects(a, b); | ||
if (b) { | ||
var u1 = a.use, f1 = a.fallback; | ||
var u2 = b.use, f2 = b.fallback; | ||
if (u1 && u2) { | ||
v.use = u1.concat(u2); | ||
} | ||
if (f1 && f2) { | ||
v.fallback = mergeObjects(f1, f2); | ||
} | ||
} | ||
return v; | ||
}; | ||
var SWRConfigContext = createContext({}); | ||
var SWRConfig$1 = function(props) { | ||
var value = props.value; | ||
var extendedConfig = mergeConfigs(useContext(SWRConfigContext), value); | ||
var provider = value && value.provider; | ||
var cacheContext = useState(function() { | ||
return provider ? initCache(provider(extendedConfig.cache || cache), value) : UNDEFINED; | ||
})[0]; | ||
if (cacheContext) { | ||
extendedConfig.cache = cacheContext[0]; | ||
extendedConfig.mutate = cacheContext[1]; | ||
} | ||
useIsomorphicLayoutEffect(function() { | ||
return cacheContext ? cacheContext[2] : UNDEFINED; | ||
}, []); | ||
return createElement(SWRConfigContext.Provider, mergeObjects(props, { | ||
value: extendedConfig | ||
})); | ||
}; | ||
var useStateWithDeps = function(state, unmountedRef) { | ||
var rerender = useState({})[1]; | ||
var stateRef = useRef(state); | ||
var stateDependenciesRef = useRef({ | ||
data: false, | ||
error: false, | ||
isValidating: false | ||
}); | ||
var setState = useCallback( | ||
function(payload) { | ||
var shouldRerender = false; | ||
var currentState = stateRef.current; | ||
for (var _ in payload) { | ||
var k = _; | ||
if (currentState[k] !== payload[k]) { | ||
currentState[k] = payload[k]; | ||
if (stateDependenciesRef.current[k]) { | ||
shouldRerender = true; | ||
} | ||
} | ||
} | ||
if (shouldRerender && !unmountedRef.current) { | ||
rerender({}); | ||
} | ||
}, | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
stateRef.current = state; | ||
}); | ||
return [stateRef, stateDependenciesRef.current, setState]; | ||
}; | ||
var normalize = function(args) { | ||
return isFunction(args[1]) ? [args[0], args[1], args[2] || {}] : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}]; | ||
}; | ||
var useSWRConfig = function() { | ||
return mergeObjects(defaultConfig, useContext(SWRConfigContext)); | ||
}; | ||
var withArgs = function(hook) { | ||
return function useSWRArgs() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var fallbackConfig = useSWRConfig(); | ||
var _a2 = normalize(args), key = _a2[0], fn = _a2[1], _config = _a2[2]; | ||
var config = mergeConfigs(fallbackConfig, _config); | ||
var next = hook; | ||
var use = config.use; | ||
if (use) { | ||
for (var i = use.length; i-- > 0; ) { | ||
next = use[i](next); | ||
} | ||
} | ||
return next(key, fn || config.fetcher, config); | ||
}; | ||
}; | ||
var subscribeCallback = function(key, callbacks, callback) { | ||
var keyedRevalidators = callbacks[key] || (callbacks[key] = []); | ||
keyedRevalidators.push(callback); | ||
return function() { | ||
var index = keyedRevalidators.indexOf(callback); | ||
if (index >= 0) { | ||
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1]; | ||
keyedRevalidators.pop(); | ||
} | ||
}; | ||
}; | ||
var WITH_DEDUPE = { dedupe: true }; | ||
var useSWRHandler = function(_key, fetcher, config) { | ||
var cache2 = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline; | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], MUTATION = _a2[2], FETCH = _a2[3]; | ||
var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2]; | ||
var initialMountedRef = useRef(false); | ||
var unmountedRef = useRef(false); | ||
var keyRef = useRef(key); | ||
var fetcherRef = useRef(fetcher); | ||
var configRef = useRef(config); | ||
var getConfig = function() { | ||
return configRef.current; | ||
}; | ||
var isActive = function() { | ||
return getConfig().isVisible() && getConfig().isOnline(); | ||
}; | ||
var patchFetchInfo = function(info2) { | ||
return cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), info2)); | ||
}; | ||
var cached = cache2.get(key); | ||
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData; | ||
var data = isUndefined(cached) ? fallback : cached; | ||
var info = cache2.get(keyInfo) || {}; | ||
var error = info.error; | ||
var isInitialMount = !initialMountedRef.current; | ||
var shouldRevalidate = function() { | ||
if (isInitialMount && !isUndefined(revalidateOnMount)) | ||
return revalidateOnMount; | ||
if (getConfig().isPaused()) | ||
return false; | ||
if (suspense) | ||
return isUndefined(data) ? false : config.revalidateIfStale; | ||
return isUndefined(data) || config.revalidateIfStale; | ||
}; | ||
var resolveValidating = function() { | ||
if (!key || !fetcher) | ||
return false; | ||
if (info.isValidating) | ||
return true; | ||
return isInitialMount && shouldRevalidate(); | ||
}; | ||
var isValidating = resolveValidating(); | ||
var _c = useStateWithDeps({ | ||
data, | ||
error, | ||
isValidating | ||
}, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2]; | ||
var revalidate = useCallback( | ||
function(revalidateOpts) { | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1; | ||
var _a3; | ||
return __generator(this, function(_b2) { | ||
switch (_b2.label) { | ||
case 0: | ||
currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return [2, false]; | ||
} | ||
loading = true; | ||
opts = revalidateOpts || {}; | ||
shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
isCurrentKeyMounted = function() { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
}; | ||
cleanupState = function() { | ||
var requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
newState = { isValidating: false }; | ||
finishRequestAndUpdateState = function() { | ||
patchFetchInfo({ isValidating: false }); | ||
if (isCurrentKeyMounted()) { | ||
setState(newState); | ||
} | ||
}; | ||
patchFetchInfo({ | ||
isValidating: true | ||
}); | ||
setState({ isValidating: true }); | ||
_b2.label = 1; | ||
case 1: | ||
_b2.trys.push([1, 3, , 4]); | ||
if (shouldStartNewRequest) { | ||
broadcastState(cache2, key, stateRef.current.data, stateRef.current.error, true); | ||
if (config.loadingTimeout && !cache2.get(key)) { | ||
setTimeout(function() { | ||
if (loading && isCurrentKeyMounted()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()]; | ||
} | ||
_a3 = FETCH[key], newData = _a3[0], startAt = _a3[1]; | ||
return [4, newData]; | ||
case 2: | ||
newData = _b2.sent(); | ||
if (shouldStartNewRequest) { | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
patchFetchInfo({ | ||
error: UNDEFINED | ||
}); | ||
newState.error = UNDEFINED; | ||
mutationInfo = MUTATION[key]; | ||
if (!isUndefined(mutationInfo) && (startAt <= mutationInfo[0] || startAt <= mutationInfo[1] || mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
if (!compare(stateRef.current.data, newData)) { | ||
newState.data = newData; | ||
} else { | ||
newState.data = stateRef.current.data; | ||
} | ||
if (!compare(cache2.get(key), newData)) { | ||
cache2.set(key, newData); | ||
} | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
return [3, 4]; | ||
case 3: | ||
err_1 = _b2.sent(); | ||
cleanupState(); | ||
if (!getConfig().isPaused()) { | ||
patchFetchInfo({ error: err_1 }); | ||
newState.error = err_1; | ||
if (shouldStartNewRequest && isCurrentKeyMounted()) { | ||
getConfig().onError(err_1, key, config); | ||
if (typeof config.shouldRetryOnError === "boolean" && config.shouldRetryOnError || isFunction(config.shouldRetryOnError) && config.shouldRetryOnError(err_1)) { | ||
if (isActive()) { | ||
getConfig().onErrorRetry(err_1, key, config, revalidate, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
return [3, 4]; | ||
case 4: | ||
loading = false; | ||
finishRequestAndUpdateState(); | ||
if (isCurrentKeyMounted() && shouldStartNewRequest) { | ||
broadcastState(cache2, key, newState.data, newState.error, false); | ||
} | ||
return [2, true]; | ||
} | ||
}); | ||
}); | ||
}, | ||
[key] | ||
); | ||
var boundMutate = useCallback( | ||
internalMutate.bind(UNDEFINED, cache2, function() { | ||
return keyRef.current; | ||
}), | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
}); | ||
useIsomorphicLayoutEffect(function() { | ||
if (!key) | ||
return; | ||
var keyChanged = key !== keyRef.current; | ||
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE); | ||
var onStateUpdate = function(updatedData, updatedError, updatedIsValidating) { | ||
setState(mergeObjects( | ||
{ | ||
error: updatedError, | ||
isValidating: updatedIsValidating | ||
}, | ||
compare(stateRef.current.data, updatedData) ? UNDEFINED : { | ||
data: updatedData | ||
} | ||
)); | ||
}; | ||
var nextFocusRevalidatedAt = 0; | ||
var onRevalidate = function(type) { | ||
if (type == FOCUS_EVENT) { | ||
var now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == MUTATE_EVENT) { | ||
return revalidate(); | ||
} | ||
return; | ||
}; | ||
var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate); | ||
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
if (keyChanged) { | ||
setState({ | ||
data, | ||
error, | ||
isValidating | ||
}); | ||
} | ||
if (shouldRevalidate()) { | ||
if (isUndefined(data) || IS_SERVER) { | ||
softRevalidate(); | ||
} else { | ||
rAF(softRevalidate); | ||
} | ||
} | ||
return function() { | ||
unmountedRef.current = true; | ||
unsubUpdate(); | ||
unsubEvents(); | ||
}; | ||
}, [key, revalidate]); | ||
useIsomorphicLayoutEffect(function() { | ||
var timer; | ||
function next() { | ||
var interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval; | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
if (!stateRef.current.error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
next(); | ||
} | ||
} | ||
next(); | ||
return function() { | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]); | ||
useDebugValue(data); | ||
if (suspense && isUndefined(data) && key) { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error; | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data() { | ||
stateDependencies.data = true; | ||
return data; | ||
}, | ||
get error() { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating() { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
} | ||
}; | ||
}; | ||
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "default", { | ||
value: defaultConfig | ||
}); | ||
var useSWR = withArgs(useSWRHandler); | ||
// src/hooks/useOrganization.tsx | ||
var useOrganization = (params) => { | ||
const { invitationList: invitationListParams, membershipList: membershipListParams } = params || {}; | ||
const { organization, lastOrganizationMember, lastOrganizationInvitation } = useOrganizationContext(); | ||
const session = useSessionContext(); | ||
const clerk = useClerkInstanceContext(); | ||
const shouldFetch = clerk.loaded && session && organization; | ||
const pendingInvitations = !clerk.loaded ? () => [] : () => clerk.organization?.getPendingInvitations(invitationListParams); | ||
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => clerk.organization?.getMemberships(membershipListParams); | ||
const { | ||
data: invitationList, | ||
isValidating: isInvitationsLoading, | ||
mutate: mutateInvitationList | ||
} = useSWR( | ||
shouldFetch && invitationListParams ? cacheKey("invites", organization, lastOrganizationInvitation, invitationListParams) : null, | ||
pendingInvitations | ||
); | ||
const { | ||
data: membershipList, | ||
isValidating: isMembershipsLoading, | ||
mutate: mutateMembershipList | ||
} = useSWR( | ||
shouldFetch && membershipListParams ? cacheKey("memberships", organization, lastOrganizationMember, membershipListParams) : null, | ||
currentOrganizationMemberships | ||
); | ||
if (organization === void 0) { | ||
return { | ||
isLoaded: false, | ||
organization: void 0, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
if (organization === null) { | ||
return { | ||
isLoaded: true, | ||
organization: null, | ||
invitationList: null, | ||
membershipList: null, | ||
membership: null | ||
}; | ||
} | ||
if (!clerk.loaded && organization) { | ||
return { | ||
isLoaded: true, | ||
organization, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: !isMembershipsLoading && !isInvitationsLoading, | ||
organization, | ||
membershipList, | ||
membership: getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id), | ||
invitationList, | ||
unstable__mutate: () => { | ||
void mutateMembershipList(); | ||
void mutateInvitationList(); | ||
} | ||
}; | ||
}; | ||
function getCurrentOrganizationMembership(organizationMemberships, activeOrganizationId) { | ||
return organizationMemberships.find( | ||
(organizationMembership) => organizationMembership.organization.id === activeOrganizationId | ||
); | ||
} | ||
function cacheKey(type, organization, resource, pagination) { | ||
return [type, organization.id, resource?.id, resource?.updatedAt, pagination.offset, pagination.limit].filter(Boolean).join("-"); | ||
} | ||
// src/hooks/useOrganizationList.tsx | ||
var useOrganizationList = () => { | ||
const clerk = useClerkInstanceContext(); | ||
const user = useUserContext(); | ||
if (!clerk.loaded || !user) { | ||
return { isLoaded: false, organizationList: void 0, createOrganization: void 0, setActive: void 0 }; | ||
} | ||
return { | ||
isLoaded: true, | ||
organizationList: createOrganizationList(user.organizationMemberships), | ||
setActive: clerk.setActive, | ||
createOrganization: clerk.createOrganization | ||
}; | ||
}; | ||
function createOrganizationList(organizationMemberships) { | ||
return organizationMemberships.map((organizationMembership) => ({ | ||
membership: organizationMembership, | ||
organization: organizationMembership.organization | ||
})); | ||
} | ||
// src/hooks/useOrganizations.tsx | ||
var useOrganizations = () => { | ||
const clerk = useClerkInstanceContext(); | ||
if (!clerk.loaded) { | ||
return { | ||
isLoaded: false, | ||
createOrganization: void 0, | ||
getOrganizationMemberships: void 0, | ||
getOrganization: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: true, | ||
createOrganization: clerk.createOrganization, | ||
getOrganizationMemberships: clerk.getOrganizationMemberships, | ||
getOrganization: clerk.getOrganization | ||
}; | ||
}; | ||
export { | ||
ClerkInstanceContext, | ||
ClientContext, | ||
LocalStorageBroadcastChannel, | ||
OrganizationContext, | ||
Poller, | ||
SessionContext, | ||
UserContext, | ||
addYears, | ||
assertContextExists, | ||
buildErrorThrower, | ||
buildPublishableKey, | ||
camelToSnake, | ||
colorToSameTypeString, | ||
createContextAndHook, | ||
createCookieHandler, | ||
createDeferredPromise, | ||
createWorkerTimers, | ||
dateTo12HourTime, | ||
deepCamelToSnake, | ||
deepSnakeToCamel, | ||
detectUserAgentRobot, | ||
differenceInCalendarDays, | ||
extension, | ||
formatRelative, | ||
hasAlpha, | ||
hexStringToRgbaColor, | ||
inBrowser, | ||
inClientSide, | ||
isHSLColor, | ||
isHttpOrHttps, | ||
isIPV4Address, | ||
isLegacyFrontendApiKey, | ||
isProxyUrlRelative, | ||
isPublishableKey, | ||
isRGBColor, | ||
isRetinaDisplay, | ||
isTransparent, | ||
isValidBrowserOnline, | ||
isValidHexString, | ||
isValidHslaString, | ||
isValidProxyUrl, | ||
isValidRgbaString, | ||
isomorphicAtob, | ||
noop, | ||
normalizeDate, | ||
parsePublishableKey, | ||
parseSearchParams, | ||
proxyUrlToAbsoluteURL, | ||
readJSONFile, | ||
runWithExponentialBackOff, | ||
snakeToCamel, | ||
stringToHslaColor, | ||
stringToSameTypeColor, | ||
titleize, | ||
toSentence, | ||
useClerkInstanceContext, | ||
useClientContext, | ||
useOrganization, | ||
useOrganizationContext, | ||
useOrganizationList, | ||
useOrganizations, | ||
useSessionContext, | ||
useUserContext | ||
}; | ||
/*! ***************************************************************************** | ||
@@ -3,0 +1111,0 @@ Copyright (c) Microsoft Corporation. |
@@ -1,2 +0,38 @@ | ||
import{G as o,a as n,b as e}from"../chunk-PWBOXFOC.js";var t={};n(t,{noop:()=>o,render:()=>m,userEvent:()=>p});var r={};n(r,{noop:()=>o,render:()=>m,userEvent:()=>p});import"@testing-library/jest-dom/extend-expect";import{render as a}from"@testing-library/react";e(r,R);import*as R from"@testing-library/react";import{default as p}from"@testing-library/user-event";var m=(i,s)=>a(i,s);e(t,r);export{o as noop,m as render,p as userEvent}; | ||
import { | ||
__export, | ||
__reExport, | ||
noop | ||
} from "../chunk-NF4BDGZ5.js"; | ||
// src/testUtils/index.ts | ||
var testUtils_exports2 = {}; | ||
__export(testUtils_exports2, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => default2 | ||
}); | ||
// src/testUtils/testUtils.ts | ||
var testUtils_exports = {}; | ||
__export(testUtils_exports, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => default2 | ||
}); | ||
import "@testing-library/jest-dom/extend-expect"; | ||
import { render } from "@testing-library/react"; | ||
__reExport(testUtils_exports, react_star); | ||
import * as react_star from "@testing-library/react"; | ||
import { default as default2 } from "@testing-library/user-event"; | ||
var customRender = (ui, options) => { | ||
return render(ui, options); | ||
}; | ||
// src/testUtils/index.ts | ||
__reExport(testUtils_exports2, testUtils_exports); | ||
export { | ||
noop, | ||
customRender as render, | ||
default2 as userEvent | ||
}; | ||
//# sourceMappingURL=index.js.map |
1897
dist/index.js
@@ -1,3 +0,1896 @@ | ||
"use strict";var Mt=Object.create;var ae=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Dt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var Ut=(e,r)=>{for(var t in r)ae(e,t,{get:r[t],enumerable:!0})},Ze=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Dt(r))!_t.call(e,o)&&o!==t&&ae(e,o,{get:()=>r[o],enumerable:!(n=Pt(r,o))||n.enumerable});return e};var Wt=(e,r,t)=>(t=e!=null?Mt(At(e)):{},Ze(r||!e||!e.__esModule?ae(t,"default",{value:e,enumerable:!0}):t,e)),Ft=e=>Ze(ae({},"__esModule",{value:!0}),e);var mn={};Ut(mn,{ClerkInstanceContext:()=>Ht,ClientContext:()=>Kt,LocalStorageBroadcastChannel:()=>He,OrganizationContext:()=>jt,Poller:()=>nn,SessionContext:()=>Gt,UserContext:()=>Nt,addYears:()=>Vr,assertContextExists:()=>Qe,buildErrorThrower:()=>$t,buildPublishableKey:()=>Nr,camelToSnake:()=>Ke,colorToSameTypeString:()=>yt,createContextAndHook:()=>$,createCookieHandler:()=>Ur,createDeferredPromise:()=>pn,createWorkerTimers:()=>he,dateTo12HourTime:()=>Wr,deepCamelToSnake:()=>Qr,deepSnakeToCamel:()=>en,detectUserAgentRobot:()=>bt,differenceInCalendarDays:()=>wt,extension:()=>Yr,formatRelative:()=>Fr,hasAlpha:()=>kr,hexStringToRgbaColor:()=>xt,inBrowser:()=>ht,inClientSide:()=>sn,isHSLColor:()=>Fe,isIPV4Address:()=>qr,isLegacyFrontendApiKey:()=>Br,isProxyUrlRelative:()=>Ge,isPublishableKey:()=>Et,isRGBColor:()=>We,isRetinaDisplay:()=>Gr,isTransparent:()=>fe,isValidBrowserOnline:()=>Cr,isValidHexString:()=>ne,isValidHslaString:()=>de,isValidProxyUrl:()=>on,isValidRgbaString:()=>ce,isomorphicAtob:()=>ve,noop:()=>G,normalizeDate:()=>ge,parsePublishableKey:()=>Kr,parseSearchParams:()=>un,proxyUrlToAbsoluteURL:()=>an,readJSONFile:()=>$r,runWithExponentialBackOff:()=>fn,snakeToCamel:()=>Ne,stringToHslaColor:()=>zr,stringToSameTypeColor:()=>Lr,titleize:()=>Zr,toSentence:()=>xr,useClerkInstanceContext:()=>H,useClientContext:()=>Bt,useOrganization:()=>gr,useOrganizationContext:()=>Ee,useOrganizationList:()=>hr,useOrganizations:()=>yr,useSessionContext:()=>Oe,useUserContext:()=>we});module.exports=Ft(mn);var Vt=Object.freeze({InvalidFrontendApiErrorMessage:"The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})",InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.dev/last-active?path=api-keys."});function $t({packageName:e,customMessages:r}){let t=e,n={...Vt,...r};function o(i,a){if(!a)return`${t}: ${i}`;let u=i,f=i.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);for(let s of f){let c=(a[s[1]]||"").toString();u=u.replace(`{{${s[1]}}}`,c)}return`${t}: ${u}`}return{setPackageName({packageName:i}){return typeof i=="string"&&(t=i),this},setMessages({customMessages:i}){return Object.assign(n,i||{}),this},throwInvalidPublishableKeyError(i){throw new Error(o(n.InvalidPublishableKeyErrorMessage,i))},throwInvalidFrontendApiError(i){throw new Error(o(n.InvalidFrontendApiErrorMessage,i))},throwInvalidProxyUrl(i){throw new Error(o(n.InvalidProxyUrlErrorMessage,i))},throwMissingPublishableKeyError(){throw new Error(o(n.MissingPublishableKeyErrorMessage))}}}var se=Wt(require("react"));function Qe(e,r){if(!e)throw typeof r=="string"?new Error(r):new Error(`${r.displayName} not found`)}var $=(e,r)=>{let{assertCtxFn:t=Qe}=r||{},n=se.default.createContext(void 0);return n.displayName=e,[n,()=>{let a=se.default.useContext(n);return t(a,`${e} not found`),a.value},()=>{let a=se.default.useContext(n);return a?a.value:{}}]};var[Ht,H]=$("ClerkInstanceContext"),[Nt,we]=$("UserContext"),[Kt,Bt]=$("ClientContext"),[Gt,Oe]=$("SessionContext"),[jt,Ee]=$("OrganizationContext");var p=require("react");function nt(e,r,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(c){try{s(n.next(c))}catch(m){a(m)}}function f(c){try{s(n.throw(c))}catch(m){a(m)}}function s(c){c.done?i(c.value):o(c.value).then(u,f)}s((n=n.apply(e,r||[])).next())})}function it(e,r){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(s){return function(c){return f([s,c])}}function f(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=r.call(e,t)}catch(c){s=[6,c],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var z=function(){},b=z(),Q=Object,x=function(e){return e===b},_=function(e){return typeof e=="function"},P=function(e,r){return Q.assign({},e,r)},De="undefined",Ae=function(){return typeof window!=De},Xt=function(){return typeof document!=De},Yt=function(){return Ae()&&typeof window.requestAnimationFrame!=De},ue=new WeakMap,Jt=0,re=function(e){var r=typeof e,t=e&&e.constructor,n=t==Date,o,i;if(Q(e)===e&&!n&&t!=RegExp){if(o=ue.get(e),o)return o;if(o=++Jt+"~",ue.set(e,o),t==Array){for(o="@",i=0;i<e.length;i++)o+=re(e[i])+",";ue.set(e,o)}if(t==Q){o="#";for(var a=Q.keys(e).sort();!x(i=a.pop());)x(e[i])||(o+=i+":"+re(e[i])+",");ue.set(e,o)}}else o=n?e.toJSON():r=="symbol"?e.toString():r=="string"?JSON.stringify(e):""+e;return o},Ie=!0,qt=function(){return Ie},ot=Ae(),_e=Xt(),ze=ot&&window.addEventListener?window.addEventListener.bind(window):z,Zt=_e?document.addEventListener.bind(document):z,Le=ot&&window.removeEventListener?window.removeEventListener.bind(window):z,Qt=_e?document.removeEventListener.bind(document):z,er=function(){var e=_e&&document.visibilityState;return x(e)||e!=="hidden"},tr=function(e){return Zt("visibilitychange",e),ze("focus",e),function(){Qt("visibilitychange",e),Le("focus",e)}},rr=function(e){var r=function(){Ie=!0,e()},t=function(){Ie=!1};return ze("online",r),ze("offline",t),function(){Le("online",r),Le("offline",t)}},nr={isOnline:qt,isVisible:er},ir={initFocus:tr,initReconnect:rr},le=!Ae()||"Deno"in window,or=function(e){return Yt()?window.requestAnimationFrame(e):setTimeout(e,1)},ee=le?p.useEffect:p.useLayoutEffect,ke=typeof navigator<"u"&&navigator.connection,et=!le&&ke&&(["slow-2g","2g"].includes(ke.effectiveType)||ke.saveData),at=function(e){if(_(e))try{e=e()}catch{e=""}var r=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?re(e):"";var t=e?"$swr$"+e:"";return[e,r,t]},N=new WeakMap,st=0,ut=1,lt=2,te=function(e,r,t,n,o,i,a){a===void 0&&(a=!0);var u=N.get(e),f=u[0],s=u[1],c=u[3],m=f[r],l=s[r];if(a&&l)for(var v=0;v<l.length;++v)l[v](t,n,o);return i&&(delete c[r],m&&m[0])?m[0](lt).then(function(){return e.get(r)}):e.get(r)},ar=0,Me=function(){return++ar},ct=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return nt(void 0,void 0,void 0,function(){var t,n,o,i,a,u,f,s,c,m,l,v,C,T,g,d,j,U,L,k,W;return it(this,function(D){switch(D.label){case 0:if(t=e[0],n=e[1],o=e[2],i=e[3],a=typeof i=="boolean"?{revalidate:i}:i||{},u=x(a.populateCache)?!0:a.populateCache,f=a.revalidate!==!1,s=a.rollbackOnError!==!1,c=a.optimisticData,m=at(n),l=m[0],v=m[2],!l)return[2];if(C=N.get(t),T=C[2],e.length<3)return[2,te(t,l,t.get(l),b,b,f,!0)];if(g=o,j=Me(),T[l]=[j,0],U=!x(c),L=t.get(l),U&&(k=_(c)?c(L):c,t.set(l,k),te(t,l,k)),_(g))try{g=g(t.get(l))}catch(F){d=F}return g&&_(g.then)?[4,g.catch(function(F){d=F})]:[3,2];case 1:if(g=D.sent(),j!==T[l][0]){if(d)throw d;return[2,g]}else d&&U&&s&&(u=!0,g=L,t.set(l,L));D.label=2;case 2:return u&&(d||(_(u)&&(g=u(g,L)),t.set(l,g)),t.set(v,P(t.get(v),{error:d}))),T[l][1]=Me(),[4,te(t,l,g,d,b,f,!!u)];case 3:if(W=D.sent(),d)throw d;return[2,u?W:g]}})})},tt=function(e,r){for(var t in e)e[t][0]&&e[t][0](r)},dt=function(e,r){if(!N.has(e)){var t=P(ir,r),n={},o=ct.bind(b,e),i=z;if(N.set(e,[n,{},{},{},o]),!le){var a=t.initFocus(setTimeout.bind(b,tt.bind(b,n,st))),u=t.initReconnect(setTimeout.bind(b,tt.bind(b,n,ut)));i=function(){a&&a(),u&&u(),N.delete(e)}}return[e,o,i]}return[e,N.get(e)[4]]},sr=function(e,r,t,n,o){var i=t.errorRetryCount,a=o.retryCount,u=~~((Math.random()+.5)*(1<<(a<8?a:8)))*t.errorRetryInterval;!x(i)&&a>i||setTimeout(n,u,o)},ft=dt(new Map),pt=ft[0],ur=ft[1],mt=P({onLoadingSlow:z,onSuccess:z,onError:z,onErrorRetry:sr,onDiscarded:z,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:et?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:et?5e3:3e3,compare:function(e,r){return re(e)==re(r)},isPaused:function(){return!1},cache:pt,mutate:ur,fallback:{}},nr),gt=function(e,r){var t=P(e,r);if(r){var n=e.use,o=e.fallback,i=r.use,a=r.fallback;n&&i&&(t.use=n.concat(i)),o&&a&&(t.fallback=P(o,a))}return t},Pe=(0,p.createContext)({}),lr=function(e){var r=e.value,t=gt((0,p.useContext)(Pe),r),n=r&&r.provider,o=(0,p.useState)(function(){return n?dt(n(t.cache||pt),r):b})[0];return o&&(t.cache=o[0],t.mutate=o[1]),ee(function(){return o?o[2]:b},[]),(0,p.createElement)(Pe.Provider,P(e,{value:t}))},cr=function(e,r){var t=(0,p.useState)({})[1],n=(0,p.useRef)(e),o=(0,p.useRef)({data:!1,error:!1,isValidating:!1}),i=(0,p.useCallback)(function(a){var u=!1,f=n.current;for(var s in a){var c=s;f[c]!==a[c]&&(f[c]=a[c],o.current[c]&&(u=!0))}u&&!r.current&&t({})},[]);return ee(function(){n.current=e}),[n,o.current,i]},dr=function(e){return _(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},fr=function(){return P(mt,(0,p.useContext)(Pe))},pr=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var o=fr(),i=dr(t),a=i[0],u=i[1],f=i[2],s=gt(o,f),c=e,m=s.use;if(m)for(var l=m.length;l-- >0;)c=m[l](c);return c(a,u||s.fetcher,s)}},rt=function(e,r,t){var n=r[e]||(r[e]=[]);return n.push(t),function(){var o=n.indexOf(t);o>=0&&(n[o]=n[n.length-1],n.pop())}},Se={dedupe:!0},mr=function(e,r,t){var n=t.cache,o=t.compare,i=t.fallbackData,a=t.suspense,u=t.revalidateOnMount,f=t.refreshInterval,s=t.refreshWhenHidden,c=t.refreshWhenOffline,m=N.get(n),l=m[0],v=m[1],C=m[2],T=m[3],g=at(e),d=g[0],j=g[1],U=g[2],L=(0,p.useRef)(!1),k=(0,p.useRef)(!1),W=(0,p.useRef)(d),D=(0,p.useRef)(r),F=(0,p.useRef)(t),h=function(){return F.current},be=function(){return h().isVisible()&&h().isOnline()},ie=function(O){return n.set(U,P(n.get(U),O))},je=n.get(d),It=x(i)?t.fallback[d]:i,M=x(je)?It:je,Xe=n.get(U)||{},X=Xe.error,Ye=!L.current,Je=function(){return Ye&&!x(u)?u:h().isPaused()?!1:a?x(M)?!1:t.revalidateIfStale:x(M)||t.revalidateIfStale},zt=function(){return!d||!r?!1:Xe.isValidating?!0:Ye&&Je()},ye=zt(),xe=cr({data:M,error:X,isValidating:ye},k),K=xe[0],Ce=xe[1],oe=xe[2],V=(0,p.useCallback)(function(O){return nt(void 0,void 0,void 0,function(){var R,w,E,Y,J,S,y,A,I,Te,q,B,Re;return it(this,function(Z){switch(Z.label){case 0:if(R=D.current,!d||!R||k.current||h().isPaused())return[2,!1];Y=!0,J=O||{},S=!T[d]||!J.dedupe,y=function(){return!k.current&&d===W.current&&L.current},A=function(){var qe=T[d];qe&&qe[1]===E&&delete T[d]},I={isValidating:!1},Te=function(){ie({isValidating:!1}),y()&&oe(I)},ie({isValidating:!0}),oe({isValidating:!0}),Z.label=1;case 1:return Z.trys.push([1,3,,4]),S&&(te(n,d,K.current.data,K.current.error,!0),t.loadingTimeout&&!n.get(d)&&setTimeout(function(){Y&&y()&&h().onLoadingSlow(d,t)},t.loadingTimeout),T[d]=[R.apply(void 0,j),Me()]),Re=T[d],w=Re[0],E=Re[1],[4,w];case 2:return w=Z.sent(),S&&setTimeout(A,t.dedupingInterval),!T[d]||T[d][1]!==E?(S&&y()&&h().onDiscarded(d),[2,!1]):(ie({error:b}),I.error=b,q=C[d],!x(q)&&(E<=q[0]||E<=q[1]||q[1]===0)?(Te(),S&&y()&&h().onDiscarded(d),[2,!1]):(o(K.current.data,w)?I.data=K.current.data:I.data=w,o(n.get(d),w)||n.set(d,w),S&&y()&&h().onSuccess(w,d,t),[3,4]));case 3:return B=Z.sent(),A(),h().isPaused()||(ie({error:B}),I.error=B,S&&y()&&(h().onError(B,d,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||_(t.shouldRetryOnError)&&t.shouldRetryOnError(B))&&be()&&h().onErrorRetry(B,d,t,V,{retryCount:(J.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return Y=!1,Te(),y()&&S&&te(n,d,I.data,I.error,!1),[2,!0]}})})},[d]),Lt=(0,p.useCallback)(ct.bind(b,n,function(){return W.current}),[]);if(ee(function(){D.current=r,F.current=t}),ee(function(){if(!!d){var O=d!==W.current,R=V.bind(b,Se),w=function(y,A,I){oe(P({error:A,isValidating:I},o(K.current.data,y)?b:{data:y}))},E=0,Y=function(y){if(y==st){var A=Date.now();h().revalidateOnFocus&&A>E&&be()&&(E=A+h().focusThrottleInterval,R())}else if(y==ut)h().revalidateOnReconnect&&be()&&R();else if(y==lt)return V()},J=rt(d,v,w),S=rt(d,l,Y);return k.current=!1,W.current=d,L.current=!0,O&&oe({data:M,error:X,isValidating:ye}),Je()&&(x(M)||le?R():or(R)),function(){k.current=!0,J(),S()}}},[d,V]),ee(function(){var O;function R(){var E=_(f)?f(M):f;E&&O!==-1&&(O=setTimeout(w,E))}function w(){!K.current.error&&(s||h().isVisible())&&(c||h().isOnline())?V(Se).then(R):R()}return R(),function(){O&&(clearTimeout(O),O=-1)}},[f,s,c,V]),(0,p.useDebugValue)(M),a&&x(M)&&d)throw D.current=r,F.current=t,k.current=!1,x(X)?V(Se):X;return{mutate:Lt,get data(){return Ce.data=!0,M},get error(){return Ce.error=!0,X},get isValidating(){return Ce.isValidating=!0,ye}}},Tn=Q.defineProperty(lr,"default",{value:mt});var Ue=pr(mr);var gr=e=>{let{invitationList:r,membershipList:t}=e||{},{organization:n,lastOrganizationMember:o,lastOrganizationInvitation:i}=Ee(),a=Oe(),u=H(),f=u.loaded&&a&&n,s=u.loaded?()=>u.organization?.getPendingInvitations(r):()=>[],c=u.loaded?()=>u.organization?.getMemberships(t):()=>[],{data:m,isValidating:l,mutate:v}=Ue(f&&r?vt("invites",n,i,r):null,s),{data:C,isValidating:T,mutate:g}=Ue(f&&t?vt("memberships",n,o,t):null,c);return n===void 0?{isLoaded:!1,organization:void 0,invitationList:void 0,membershipList:void 0,membership:void 0}:n===null?{isLoaded:!0,organization:null,invitationList:null,membershipList:null,membership:null}:!u.loaded&&n?{isLoaded:!0,organization:n,invitationList:void 0,membershipList:void 0,membership:void 0}:{isLoaded:!T&&!l,organization:n,membershipList:C,membership:vr(a.user.organizationMemberships,n.id),invitationList:m,unstable__mutate:()=>{g(),v()}}};function vr(e,r){return e.find(t=>t.organization.id===r)}function vt(e,r,t,n){return[e,r.id,t?.id,t?.updatedAt,n.offset,n.limit].filter(Boolean).join("-")}var hr=()=>{let e=H(),r=we();return!e.loaded||!r?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:br(r.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function br(e){return e.map(r=>({membership:r,organization:r.organization}))}var yr=()=>{let e=H();return e.loaded?{isLoaded:!0,createOrganization:e.createOrganization,getOrganizationMemberships:e.getOrganizationMemberships,getOrganization:e.getOrganization}:{isLoaded:!1,createOrganization:void 0,getOrganizationMemberships:void 0,getOrganization:void 0}};var xr=e=>{if(e.length==0)return"";if(e.length==1)return e[0];let r=e.slice(0,-1).join(", ");return r+=`, or ${e.slice(-1)}`,r};function ht(){return typeof window<"u"}function bt(e){return new RegExp([/bot/,/spider/,/crawl/,/APIs-Google/,/AdsBot/,/Googlebot/,/mediapartners/,/Google Favicon/,/FeedFetcher/,/Google-Read-Aloud/,/DuplexWeb-Google/,/googleweblight/,/bing/,/yandex/,/baidu/,/duckduck/,/yahoo/,/ecosia/,/ia_archiver/,/facebook/,/instagram/,/pinterest/,/reddit/,/slack/,/twitter/,/whatsapp/,/youtube/,/semrush/].map(t=>t.source).join("|"),"i").test(e)}function Cr(){let e=window?.navigator;if(!ht()||!e)return!1;let r=bt(e?.userAgent),t=e?.webdriver,n=e?.onLine,o=e?.connection?.rtt!==0&&e?.connection?.downlink!==0;return!r&&!t&&o&&n}var Tr=/^#?([A-F0-9]{6}|[A-F0-9]{3})$/i,Rr=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i,wr=/^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i,Or=/^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i,Er=/^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i,ne=e=>!!e.match(Tr),ce=e=>!!(e.match(Rr)||e.match(wr)),de=e=>!!e.match(Or)||!!e.match(Er),We=e=>typeof e!="string"&&"r"in e,Fe=e=>typeof e!="string"&&"h"in e,fe=e=>e==="transparent",kr=e=>typeof e!="string"&&e.a!=null&&e.a<1;var Sr=/[hsla()]/g,Ir=/[rgba()]/g,zr=e=>e==="transparent"?{h:0,s:0,l:0,a:0}:ne(e)?Dr(e):de(e)?Rt(e):ce(e)?Ct(e):null,Lr=e=>(e=e.trim(),ne(e)?e.startsWith("#")?e:`#${e}`:ce(e)?Tt(e):de(e)?Rt(e):fe(e)?e:""),yt=e=>typeof e=="string"&&(ne(e)||fe(e))?e:We(e)?Mr(e):Fe(e)?Pr(e):"",xt=e=>{e=e.replace("#","");let r=parseInt(e.substring(0,2),16),t=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16);return{r,g:t,b:n}},Mr=e=>{let{a:r,b:t,g:n,r:o}=e;return e.a===0?"transparent":e.a!=null?`rgba(${o},${n},${t},${r})`:`rgb(${o},${n},${t})`},Pr=e=>{let{h:r,s:t,l:n,a:o}=e,i=Math.round(t*100),a=Math.round(n*100);return e.a===0?"transparent":e.a!=null?`hsla(${r},${i}%,${a}%,${o})`:`hsl(${r},${i}%,${a}%)`},Dr=e=>{let r=yt(xt(e));return Ct(r)},Ct=e=>{let r=Tt(e),t=r.r/255,n=r.g/255,o=r.b/255,i=Math.max(t,n,o),a=Math.min(t,n,o),u,f,s=(i+a)/2;if(i==a)u=f=0;else{let l=i-a;switch(f=s>=.5?l/(2-(i+a)):l/(i+a),i){case t:u=(n-o)/l*60;break;case n:u=((o-t)/l+2)*60;break;default:u=((t-n)/l+4)*60;break}}let c={h:Math.round(u),s:f,l:s},m=r.a;return m!=null&&(c.a=m),c},Tt=e=>{let[r,t,n,o]=e.replace(Ir,"").split(",").map(i=>Number.parseFloat(i));return{r,g:t,b:n,a:o}},Rt=e=>{let[r,t,n,o]=e.replace(Sr,"").split(",").map(i=>Number.parseFloat(i));return{h:r,s:t/100,l:n/100,a:o}};function pe(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)e[n]=t[n]}return e}var Ar={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Ve(e,r){function t(o,i,a){if(!(typeof document>"u")){a=pe({},r,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in a)!a[f]||(u+="; "+f,a[f]!==!0&&(u+="="+a[f].split(";")[0]));return document.cookie=o+"="+e.write(i,o)+u}}function n(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var i=document.cookie?document.cookie.split("; "):[],a={},u=0;u<i.length;u++){var f=i[u].split("="),s=f.slice(1).join("=");try{var c=decodeURIComponent(f[0]);if(a[c]=e.read(s,c),o===c)break}catch{}}return o?a[o]:a}}return Object.create({set:t,get:n,remove:function(o,i){t(o,"",pe({},i,{expires:-1}))},withAttributes:function(o){return Ve(this.converter,pe({},this.attributes,o))},withConverter:function(o){return Ve(pe({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}var _r=Ve(Ar,{path:"/"}),me=_r;function Ur(e){return{get(){return me.get(e)},set(r,t={}){return me.set(e,r,t)},remove(r){me.remove(e,r)}}}function Wr(e){return e?e.toLocaleString("en-US",{hour:"2-digit",minute:"numeric",hour12:!0}):""}function wt(e,r,{absolute:t=!0}={}){if(!e||!r)return 0;let n=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),o=Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()),i=Math.floor((o-n)/864e5);return t?Math.abs(i):i}function ge(e){try{return new Date(e||new Date)}catch{return new Date}}function Fr(e){let{date:r,relativeTo:t}=e;if(!r||!t)return null;let n=ge(r),o=ge(t),i=wt(o,n,{absolute:!1});return i<-6?{relativeDateCase:"other",date:n}:i<-1?{relativeDateCase:"previous6Days",date:n}:i===-1?{relativeDateCase:"lastDay",date:n}:i===0?{relativeDateCase:"sameDay",date:n}:i===1?{relativeDateCase:"nextDay",date:n}:i<7?{relativeDateCase:"next6Days",date:n}:{relativeDateCase:"other",date:n}}function Vr(e,r){let t=ge(e);return t.setFullYear(t.getFullYear()+r),t}function $r(e){return new Promise((r,t)=>{let n=new FileReader;n.addEventListener("load",function(){let o=JSON.parse(n.result);r(o)}),n.addEventListener("error",t),n.readAsText(e)})}var ve=e=>typeof atob<"u"&&typeof atob=="function"?atob(e):typeof Buffer<"u"?new Buffer(e,"base64").toString():e;var $e="pk_live_",Ot="pk_test_",Hr=/^(([a-z]+)-){2}([0-9]{1,2})\.clerk\.accounts([a-z.]*)(dev|com)$/i;function Nr(e){return`${Hr.test(e)?Ot:$e}${btoa(`${e}$`)}`}function Kr(e){if(e=e||"",!Et(e))return null;let r=e.startsWith($e)?"production":"development",t=ve(e.split("_")[2]);return t.endsWith("$")?(t=t.slice(0,-1),{instanceType:r,frontendApi:t}):null}function Et(e){e=e||"";let r=e.startsWith($e)||e.startsWith(Ot),t=ve(e.split("_")[2]||"").endsWith("$");return r&&t}function Br(e){return e=e||"",e.startsWith("clerk.")}function Gr(){if(!window.matchMedia)return!1;let e=window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");return e&&e.matches||window.devicePixelRatio>1}var jr="__lsbc__",He=class{constructor(r){this.eventTarget=window;this.postMessage=r=>{try{localStorage.setItem(this.channelKey,JSON.stringify(r)),localStorage.removeItem(this.channelKey)}catch{}};this.addEventListener=(r,t)=>{this.eventTarget.addEventListener(this.prefixEventName(r),n=>{t(n)})};this.setupLocalStorageListener=()=>{let r=t=>{if(!(t.key!==this.channelKey||!t.newValue))try{let n=JSON.parse(t.newValue||""),o=new MessageEvent(this.prefixEventName("message"),{data:n});this.eventTarget.dispatchEvent(o)}catch{}};window.addEventListener("storage",r)};this.channelKey=jr+r,this.setupLocalStorageListener()}prefixEventName(r){return this.channelKey+r}};var Xr=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"}),Yr=e=>Xr[e];var G=(...e)=>{};var Jr=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;function qr(e){return Jr.test(e||"")}function Zr(e){let r=e||"";return r.charAt(0).toUpperCase()+r.slice(1)}function Ne(e){return e?e.replace(/([-_][a-z])/g,r=>r.toUpperCase().replace(/-|_/,"")):""}function Ke(e){return e?e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`):""}var kt=e=>{let r=t=>{if(!t)return t;if(Array.isArray(t))return t.map(i=>typeof i=="object"||Array.isArray(i)?r(i):i);let n={...t},o=Object.keys(n);for(let i of o){let a=e(i.toString());a!==i&&(n[a]=n[i],delete n[i]),typeof n[a]=="object"&&(n[a]=r(n[a]))}return n};return r},Qr=kt(Ke),en=kt(Ne);var Be=`const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id})},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}}); | ||
`;var St=(e,r={})=>{if(typeof Worker>"u")return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=globalThis.URL.createObjectURL(t);return new Worker(n,r)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},rn=()=>{let e=globalThis.setTimeout.bind(globalThis),r=globalThis.setInterval.bind(globalThis),t=globalThis.clearTimeout.bind(globalThis),n=globalThis.clearInterval.bind(globalThis);return{setTimeout:e,setInterval:r,clearTimeout:t,clearInterval:n,cleanup:G}},he=()=>{let e=0,r=()=>e++,t=new Map,n=(l,v)=>l?.postMessage(v),o=l=>{t.get(l.data.id)?.()},i=St(Be,{name:"clerk-timers"});if(i?.addEventListener("message",o),!i)return rn();let a=()=>{i||(i=St(Be,{name:"clerk-timers"}),i?.addEventListener("message",o))};return{setTimeout:(l,v)=>{a();let C=r();return t.set(C,l),n(i,{type:"setTimeout",id:C,ms:v}),C},setInterval:(l,v)=>{a();let C=r();return t.set(C,l),n(i,{type:"setInterval",id:C,ms:v}),C},clearTimeout:l=>{a(),t.delete(l),n(i,{type:"clearTimeout",id:l})},clearInterval:l=>{a(),t.delete(l),n(i,{type:"clearInterval",id:l})},cleanup:()=>{i&&(i.terminate(),i=null,t.clear())}}};function nn({delayInMs:e}={delayInMs:1e3}){let r=he(),t,n=!1,o=()=>{t&&(r.clearTimeout(t),r.cleanup()),n=!0},i=async a=>{n=!1,await a(o),!n&&(t=r.setTimeout(()=>{i(a)},e))};return{run:i,stop:o}}function on(e){return e?e.startsWith("https://")||Ge(e):!0}function Ge(e){return e.startsWith("/")}function an(e){return e?Ge(e)?new URL(e,window.location.origin).toString():e:""}var sn=()=>typeof window<"u";function un(e=""){return e.startsWith("?")&&(e=e.slice(1)),new URLSearchParams(e)}var ln={maxRetries:10,firstDelay:125,timeMultiple:2,shouldRetry:()=>!0},cn=async e=>new Promise(r=>setTimeout(r,e)),dn=e=>{let r=0,t=()=>{let n=e.firstDelay,o=e.timeMultiple;return n*Math.pow(o,r)};return async()=>{await cn(t()),r++}},fn=async(e,r={})=>{let t=0,{maxRetries:n,shouldRetry:o,firstDelay:i,timeMultiple:a}={...ln,...r},u=()=>t===n,f=dn({firstDelay:i,timeMultiple:a});for(;!u();)try{return await e()}catch(s){if(t++,!o(s,t)||u())throw s;await f()}throw new Error("Something went wrong")};var pn=()=>{let e=G,r=G;return{promise:new Promise((n,o)=>{e=n,r=o}),resolve:e,reject:r}};0&&(module.exports={ClerkInstanceContext,ClientContext,LocalStorageBroadcastChannel,OrganizationContext,Poller,SessionContext,UserContext,addYears,assertContextExists,buildErrorThrower,buildPublishableKey,camelToSnake,colorToSameTypeString,createContextAndHook,createCookieHandler,createDeferredPromise,createWorkerTimers,dateTo12HourTime,deepCamelToSnake,deepSnakeToCamel,detectUserAgentRobot,differenceInCalendarDays,extension,formatRelative,hasAlpha,hexStringToRgbaColor,inBrowser,inClientSide,isHSLColor,isIPV4Address,isLegacyFrontendApiKey,isProxyUrlRelative,isPublishableKey,isRGBColor,isRetinaDisplay,isTransparent,isValidBrowserOnline,isValidHexString,isValidHslaString,isValidProxyUrl,isValidRgbaString,isomorphicAtob,noop,normalizeDate,parsePublishableKey,parseSearchParams,proxyUrlToAbsoluteURL,readJSONFile,runWithExponentialBackOff,snakeToCamel,stringToHslaColor,stringToSameTypeColor,titleize,toSentence,useClerkInstanceContext,useClientContext,useOrganization,useOrganizationContext,useOrganizationList,useOrganizations,useSessionContext,useUserContext}); | ||
"use strict"; | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
// src/index.ts | ||
var src_exports = {}; | ||
__export(src_exports, { | ||
ClerkInstanceContext: () => ClerkInstanceContext, | ||
ClientContext: () => ClientContext, | ||
LocalStorageBroadcastChannel: () => LocalStorageBroadcastChannel, | ||
OrganizationContext: () => OrganizationContext, | ||
Poller: () => Poller, | ||
SessionContext: () => SessionContext, | ||
UserContext: () => UserContext, | ||
addYears: () => addYears, | ||
assertContextExists: () => assertContextExists, | ||
buildErrorThrower: () => buildErrorThrower, | ||
buildPublishableKey: () => buildPublishableKey, | ||
camelToSnake: () => camelToSnake, | ||
colorToSameTypeString: () => colorToSameTypeString, | ||
createContextAndHook: () => createContextAndHook, | ||
createCookieHandler: () => createCookieHandler, | ||
createDeferredPromise: () => createDeferredPromise, | ||
createWorkerTimers: () => createWorkerTimers, | ||
dateTo12HourTime: () => dateTo12HourTime, | ||
deepCamelToSnake: () => deepCamelToSnake, | ||
deepSnakeToCamel: () => deepSnakeToCamel, | ||
detectUserAgentRobot: () => detectUserAgentRobot, | ||
differenceInCalendarDays: () => differenceInCalendarDays, | ||
extension: () => extension, | ||
formatRelative: () => formatRelative, | ||
hasAlpha: () => hasAlpha, | ||
hexStringToRgbaColor: () => hexStringToRgbaColor, | ||
inBrowser: () => inBrowser, | ||
inClientSide: () => inClientSide, | ||
isHSLColor: () => isHSLColor, | ||
isHttpOrHttps: () => isHttpOrHttps, | ||
isIPV4Address: () => isIPV4Address, | ||
isLegacyFrontendApiKey: () => isLegacyFrontendApiKey, | ||
isProxyUrlRelative: () => isProxyUrlRelative, | ||
isPublishableKey: () => isPublishableKey, | ||
isRGBColor: () => isRGBColor, | ||
isRetinaDisplay: () => isRetinaDisplay, | ||
isTransparent: () => isTransparent, | ||
isValidBrowserOnline: () => isValidBrowserOnline, | ||
isValidHexString: () => isValidHexString, | ||
isValidHslaString: () => isValidHslaString, | ||
isValidProxyUrl: () => isValidProxyUrl, | ||
isValidRgbaString: () => isValidRgbaString, | ||
isomorphicAtob: () => isomorphicAtob, | ||
noop: () => noop2, | ||
normalizeDate: () => normalizeDate, | ||
parsePublishableKey: () => parsePublishableKey, | ||
parseSearchParams: () => parseSearchParams, | ||
proxyUrlToAbsoluteURL: () => proxyUrlToAbsoluteURL, | ||
readJSONFile: () => readJSONFile, | ||
runWithExponentialBackOff: () => runWithExponentialBackOff, | ||
snakeToCamel: () => snakeToCamel, | ||
stringToHslaColor: () => stringToHslaColor, | ||
stringToSameTypeColor: () => stringToSameTypeColor, | ||
titleize: () => titleize, | ||
toSentence: () => toSentence, | ||
useClerkInstanceContext: () => useClerkInstanceContext, | ||
useClientContext: () => useClientContext, | ||
useOrganization: () => useOrganization, | ||
useOrganizationContext: () => useOrganizationContext, | ||
useOrganizationList: () => useOrganizationList, | ||
useOrganizations: () => useOrganizations, | ||
useSessionContext: () => useSessionContext, | ||
useUserContext: () => useUserContext | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
// src/errors/thrower.ts | ||
var DefaultMessages = Object.freeze({ | ||
InvalidFrontendApiErrorMessage: `The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})`, | ||
InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`, | ||
InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.dev/last-active?path=api-keys. (key={{key}})`, | ||
MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.dev/last-active?path=api-keys.` | ||
}); | ||
function buildErrorThrower({ packageName, customMessages }) { | ||
let pkg = packageName; | ||
const messages = { | ||
...DefaultMessages, | ||
...customMessages | ||
}; | ||
function buildMessage(rawMessage, replacements) { | ||
if (!replacements) { | ||
return `${pkg}: ${rawMessage}`; | ||
} | ||
let msg = rawMessage; | ||
const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g); | ||
for (const match of matches) { | ||
const replacement = (replacements[match[1]] || "").toString(); | ||
msg = msg.replace(`{{${match[1]}}}`, replacement); | ||
} | ||
return `${pkg}: ${msg}`; | ||
} | ||
return { | ||
setPackageName({ packageName: packageName2 }) { | ||
if (typeof packageName2 === "string") { | ||
pkg = packageName2; | ||
} | ||
return this; | ||
}, | ||
setMessages({ customMessages: customMessages2 }) { | ||
Object.assign(messages, customMessages2 || {}); | ||
return this; | ||
}, | ||
throwInvalidPublishableKeyError(params) { | ||
throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params)); | ||
}, | ||
throwInvalidFrontendApiError(params) { | ||
throw new Error(buildMessage(messages.InvalidFrontendApiErrorMessage, params)); | ||
}, | ||
throwInvalidProxyUrl(params) { | ||
throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params)); | ||
}, | ||
throwMissingPublishableKeyError() { | ||
throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage)); | ||
} | ||
}; | ||
} | ||
// src/hooks/createContextAndHook.ts | ||
var import_react = __toESM(require("react")); | ||
function assertContextExists(contextVal, msgOrCtx) { | ||
if (!contextVal) { | ||
throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`); | ||
} | ||
} | ||
var createContextAndHook = (displayName, options) => { | ||
const { assertCtxFn = assertContextExists } = options || {}; | ||
const Ctx = import_react.default.createContext(void 0); | ||
Ctx.displayName = displayName; | ||
const useCtx = () => { | ||
const ctx = import_react.default.useContext(Ctx); | ||
assertCtxFn(ctx, `${displayName} not found`); | ||
return ctx.value; | ||
}; | ||
const useCtxWithoutGuarantee = () => { | ||
const ctx = import_react.default.useContext(Ctx); | ||
return ctx ? ctx.value : {}; | ||
}; | ||
return [Ctx, useCtx, useCtxWithoutGuarantee]; | ||
}; | ||
// src/hooks/contexts.tsx | ||
var [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext"); | ||
var [UserContext, useUserContext] = createContextAndHook("UserContext"); | ||
var [ClientContext, useClientContext] = createContextAndHook("ClientContext"); | ||
var [SessionContext, useSessionContext] = createContextAndHook( | ||
"SessionContext" | ||
); | ||
var [OrganizationContext, useOrganizationContext] = createContextAndHook("OrganizationContext"); | ||
// ../../node_modules/swr/dist/index.mjs | ||
var import_react2 = require("react"); | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function(resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
return new (P || (P = Promise))(function(resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { | ||
if (t[0] & 1) | ||
throw t[1]; | ||
return t[1]; | ||
}, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { | ||
return this; | ||
}), g; | ||
function verb(n) { | ||
return function(v) { | ||
return step([n, v]); | ||
}; | ||
} | ||
function step(op) { | ||
if (f) | ||
throw new TypeError("Generator is already executing."); | ||
while (_) | ||
try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) | ||
return t; | ||
if (y = 0, t) | ||
op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: | ||
case 1: | ||
t = op; | ||
break; | ||
case 4: | ||
_.label++; | ||
return { value: op[1], done: false }; | ||
case 5: | ||
_.label++; | ||
y = op[1]; | ||
op = [0]; | ||
continue; | ||
case 7: | ||
op = _.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { | ||
_ = 0; | ||
continue; | ||
} | ||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { | ||
_.label = op[1]; | ||
break; | ||
} | ||
if (op[0] === 6 && _.label < t[1]) { | ||
_.label = t[1]; | ||
t = op; | ||
break; | ||
} | ||
if (t && _.label < t[2]) { | ||
_.label = t[2]; | ||
_.ops.push(op); | ||
break; | ||
} | ||
if (t[2]) | ||
_.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { | ||
op = [6, e]; | ||
y = 0; | ||
} finally { | ||
f = t = 0; | ||
} | ||
if (op[0] & 5) | ||
throw op[1]; | ||
return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
var noop = function() { | ||
}; | ||
var UNDEFINED = noop(); | ||
var OBJECT = Object; | ||
var isUndefined = function(v) { | ||
return v === UNDEFINED; | ||
}; | ||
var isFunction = function(v) { | ||
return typeof v == "function"; | ||
}; | ||
var mergeObjects = function(a, b) { | ||
return OBJECT.assign({}, a, b); | ||
}; | ||
var STR_UNDEFINED = "undefined"; | ||
var hasWindow = function() { | ||
return typeof window != STR_UNDEFINED; | ||
}; | ||
var hasDocument = function() { | ||
return typeof document != STR_UNDEFINED; | ||
}; | ||
var hasRequestAnimationFrame = function() { | ||
return hasWindow() && typeof window["requestAnimationFrame"] != STR_UNDEFINED; | ||
}; | ||
var table = /* @__PURE__ */ new WeakMap(); | ||
var counter = 0; | ||
var stableHash = function(arg) { | ||
var type = typeof arg; | ||
var constructor = arg && arg.constructor; | ||
var isDate = constructor == Date; | ||
var result; | ||
var index; | ||
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) { | ||
result = table.get(arg); | ||
if (result) | ||
return result; | ||
result = ++counter + "~"; | ||
table.set(arg, result); | ||
if (constructor == Array) { | ||
result = "@"; | ||
for (index = 0; index < arg.length; index++) { | ||
result += stableHash(arg[index]) + ","; | ||
} | ||
table.set(arg, result); | ||
} | ||
if (constructor == OBJECT) { | ||
result = "#"; | ||
var keys = OBJECT.keys(arg).sort(); | ||
while (!isUndefined(index = keys.pop())) { | ||
if (!isUndefined(arg[index])) { | ||
result += index + ":" + stableHash(arg[index]) + ","; | ||
} | ||
} | ||
table.set(arg, result); | ||
} | ||
} else { | ||
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg; | ||
} | ||
return result; | ||
}; | ||
var online = true; | ||
var isOnline = function() { | ||
return online; | ||
}; | ||
var hasWin = hasWindow(); | ||
var hasDoc = hasDocument(); | ||
var onWindowEvent = hasWin && window.addEventListener ? window.addEventListener.bind(window) : noop; | ||
var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop; | ||
var offWindowEvent = hasWin && window.removeEventListener ? window.removeEventListener.bind(window) : noop; | ||
var offDocumentEvent = hasDoc ? document.removeEventListener.bind(document) : noop; | ||
var isVisible = function() { | ||
var visibilityState = hasDoc && document.visibilityState; | ||
return isUndefined(visibilityState) || visibilityState !== "hidden"; | ||
}; | ||
var initFocus = function(callback) { | ||
onDocumentEvent("visibilitychange", callback); | ||
onWindowEvent("focus", callback); | ||
return function() { | ||
offDocumentEvent("visibilitychange", callback); | ||
offWindowEvent("focus", callback); | ||
}; | ||
}; | ||
var initReconnect = function(callback) { | ||
var onOnline = function() { | ||
online = true; | ||
callback(); | ||
}; | ||
var onOffline = function() { | ||
online = false; | ||
}; | ||
onWindowEvent("online", onOnline); | ||
onWindowEvent("offline", onOffline); | ||
return function() { | ||
offWindowEvent("online", onOnline); | ||
offWindowEvent("offline", onOffline); | ||
}; | ||
}; | ||
var preset = { | ||
isOnline, | ||
isVisible | ||
}; | ||
var defaultConfigOptions = { | ||
initFocus, | ||
initReconnect | ||
}; | ||
var IS_SERVER = !hasWindow() || "Deno" in window; | ||
var rAF = function(f) { | ||
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1); | ||
}; | ||
var useIsomorphicLayoutEffect = IS_SERVER ? import_react2.useEffect : import_react2.useLayoutEffect; | ||
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection; | ||
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData); | ||
var serialize = function(key) { | ||
if (isFunction(key)) { | ||
try { | ||
key = key(); | ||
} catch (err) { | ||
key = ""; | ||
} | ||
} | ||
var args = [].concat(key); | ||
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : ""; | ||
var infoKey = key ? "$swr$" + key : ""; | ||
return [key, args, infoKey]; | ||
}; | ||
var SWRGlobalState = /* @__PURE__ */ new WeakMap(); | ||
var FOCUS_EVENT = 0; | ||
var RECONNECT_EVENT = 1; | ||
var MUTATE_EVENT = 2; | ||
var broadcastState = function(cache2, key, data, error, isValidating, revalidate, broadcast) { | ||
if (broadcast === void 0) { | ||
broadcast = true; | ||
} | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], FETCH = _a2[3]; | ||
var revalidators = EVENT_REVALIDATORS[key]; | ||
var updaters = STATE_UPDATERS[key]; | ||
if (broadcast && updaters) { | ||
for (var i = 0; i < updaters.length; ++i) { | ||
updaters[i](data, error, isValidating); | ||
} | ||
} | ||
if (revalidate) { | ||
delete FETCH[key]; | ||
if (revalidators && revalidators[0]) { | ||
return revalidators[0](MUTATE_EVENT).then(function() { | ||
return cache2.get(key); | ||
}); | ||
} | ||
} | ||
return cache2.get(key); | ||
}; | ||
var __timestamp = 0; | ||
var getTimestamp = function() { | ||
return ++__timestamp; | ||
}; | ||
var internalMutate = function() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var cache2, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, customOptimisticData, _a2, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasCustomOptimisticData, rollbackData, optimisticData, res; | ||
return __generator(this, function(_c) { | ||
switch (_c.label) { | ||
case 0: | ||
cache2 = args[0], _key = args[1], _data = args[2], _opts = args[3]; | ||
options = typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {}; | ||
populateCache = isUndefined(options.populateCache) ? true : options.populateCache; | ||
revalidate = options.revalidate !== false; | ||
rollbackOnError = options.rollbackOnError !== false; | ||
customOptimisticData = options.optimisticData; | ||
_a2 = serialize(_key), key = _a2[0], keyInfo = _a2[2]; | ||
if (!key) | ||
return [2]; | ||
_b = SWRGlobalState.get(cache2), MUTATION = _b[2]; | ||
if (args.length < 3) { | ||
return [2, broadcastState(cache2, key, cache2.get(key), UNDEFINED, UNDEFINED, revalidate, true)]; | ||
} | ||
data = _data; | ||
beforeMutationTs = getTimestamp(); | ||
MUTATION[key] = [beforeMutationTs, 0]; | ||
hasCustomOptimisticData = !isUndefined(customOptimisticData); | ||
rollbackData = cache2.get(key); | ||
if (hasCustomOptimisticData) { | ||
optimisticData = isFunction(customOptimisticData) ? customOptimisticData(rollbackData) : customOptimisticData; | ||
cache2.set(key, optimisticData); | ||
broadcastState(cache2, key, optimisticData); | ||
} | ||
if (isFunction(data)) { | ||
try { | ||
data = data(cache2.get(key)); | ||
} catch (err) { | ||
error = err; | ||
} | ||
} | ||
if (!(data && isFunction(data.then))) | ||
return [3, 2]; | ||
return [ | ||
4, | ||
data.catch(function(err) { | ||
error = err; | ||
}) | ||
]; | ||
case 1: | ||
data = _c.sent(); | ||
if (beforeMutationTs !== MUTATION[key][0]) { | ||
if (error) | ||
throw error; | ||
return [2, data]; | ||
} else if (error && hasCustomOptimisticData && rollbackOnError) { | ||
populateCache = true; | ||
data = rollbackData; | ||
cache2.set(key, rollbackData); | ||
} | ||
_c.label = 2; | ||
case 2: | ||
if (populateCache) { | ||
if (!error) { | ||
if (isFunction(populateCache)) { | ||
data = populateCache(data, rollbackData); | ||
} | ||
cache2.set(key, data); | ||
} | ||
cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), { error })); | ||
} | ||
MUTATION[key][1] = getTimestamp(); | ||
return [ | ||
4, | ||
broadcastState(cache2, key, data, error, UNDEFINED, revalidate, !!populateCache) | ||
]; | ||
case 3: | ||
res = _c.sent(); | ||
if (error) | ||
throw error; | ||
return [2, populateCache ? res : data]; | ||
} | ||
}); | ||
}); | ||
}; | ||
var revalidateAllKeys = function(revalidators, type) { | ||
for (var key in revalidators) { | ||
if (revalidators[key][0]) | ||
revalidators[key][0](type); | ||
} | ||
}; | ||
var initCache = function(provider, options) { | ||
if (!SWRGlobalState.has(provider)) { | ||
var opts = mergeObjects(defaultConfigOptions, options); | ||
var EVENT_REVALIDATORS = {}; | ||
var mutate2 = internalMutate.bind(UNDEFINED, provider); | ||
var unmount = noop; | ||
SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate2]); | ||
if (!IS_SERVER) { | ||
var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT))); | ||
var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT))); | ||
unmount = function() { | ||
releaseFocus_1 && releaseFocus_1(); | ||
releaseReconnect_1 && releaseReconnect_1(); | ||
SWRGlobalState.delete(provider); | ||
}; | ||
} | ||
return [provider, mutate2, unmount]; | ||
} | ||
return [provider, SWRGlobalState.get(provider)[4]]; | ||
}; | ||
var onErrorRetry = function(_, __, config, revalidate, opts) { | ||
var maxRetryCount = config.errorRetryCount; | ||
var currentRetryCount = opts.retryCount; | ||
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval; | ||
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) { | ||
return; | ||
} | ||
setTimeout(revalidate, timeout, opts); | ||
}; | ||
var _a = initCache(/* @__PURE__ */ new Map()); | ||
var cache = _a[0]; | ||
var mutate = _a[1]; | ||
var defaultConfig = mergeObjects( | ||
{ | ||
onLoadingSlow: noop, | ||
onSuccess: noop, | ||
onError: noop, | ||
onErrorRetry, | ||
onDiscarded: noop, | ||
revalidateOnFocus: true, | ||
revalidateOnReconnect: true, | ||
revalidateIfStale: true, | ||
shouldRetryOnError: true, | ||
errorRetryInterval: slowConnection ? 1e4 : 5e3, | ||
focusThrottleInterval: 5 * 1e3, | ||
dedupingInterval: 2 * 1e3, | ||
loadingTimeout: slowConnection ? 5e3 : 3e3, | ||
compare: function(currentData, newData) { | ||
return stableHash(currentData) == stableHash(newData); | ||
}, | ||
isPaused: function() { | ||
return false; | ||
}, | ||
cache, | ||
mutate, | ||
fallback: {} | ||
}, | ||
preset | ||
); | ||
var mergeConfigs = function(a, b) { | ||
var v = mergeObjects(a, b); | ||
if (b) { | ||
var u1 = a.use, f1 = a.fallback; | ||
var u2 = b.use, f2 = b.fallback; | ||
if (u1 && u2) { | ||
v.use = u1.concat(u2); | ||
} | ||
if (f1 && f2) { | ||
v.fallback = mergeObjects(f1, f2); | ||
} | ||
} | ||
return v; | ||
}; | ||
var SWRConfigContext = (0, import_react2.createContext)({}); | ||
var SWRConfig$1 = function(props) { | ||
var value = props.value; | ||
var extendedConfig = mergeConfigs((0, import_react2.useContext)(SWRConfigContext), value); | ||
var provider = value && value.provider; | ||
var cacheContext = (0, import_react2.useState)(function() { | ||
return provider ? initCache(provider(extendedConfig.cache || cache), value) : UNDEFINED; | ||
})[0]; | ||
if (cacheContext) { | ||
extendedConfig.cache = cacheContext[0]; | ||
extendedConfig.mutate = cacheContext[1]; | ||
} | ||
useIsomorphicLayoutEffect(function() { | ||
return cacheContext ? cacheContext[2] : UNDEFINED; | ||
}, []); | ||
return (0, import_react2.createElement)(SWRConfigContext.Provider, mergeObjects(props, { | ||
value: extendedConfig | ||
})); | ||
}; | ||
var useStateWithDeps = function(state, unmountedRef) { | ||
var rerender = (0, import_react2.useState)({})[1]; | ||
var stateRef = (0, import_react2.useRef)(state); | ||
var stateDependenciesRef = (0, import_react2.useRef)({ | ||
data: false, | ||
error: false, | ||
isValidating: false | ||
}); | ||
var setState = (0, import_react2.useCallback)( | ||
function(payload) { | ||
var shouldRerender = false; | ||
var currentState = stateRef.current; | ||
for (var _ in payload) { | ||
var k = _; | ||
if (currentState[k] !== payload[k]) { | ||
currentState[k] = payload[k]; | ||
if (stateDependenciesRef.current[k]) { | ||
shouldRerender = true; | ||
} | ||
} | ||
} | ||
if (shouldRerender && !unmountedRef.current) { | ||
rerender({}); | ||
} | ||
}, | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
stateRef.current = state; | ||
}); | ||
return [stateRef, stateDependenciesRef.current, setState]; | ||
}; | ||
var normalize = function(args) { | ||
return isFunction(args[1]) ? [args[0], args[1], args[2] || {}] : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}]; | ||
}; | ||
var useSWRConfig = function() { | ||
return mergeObjects(defaultConfig, (0, import_react2.useContext)(SWRConfigContext)); | ||
}; | ||
var withArgs = function(hook) { | ||
return function useSWRArgs() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var fallbackConfig = useSWRConfig(); | ||
var _a2 = normalize(args), key = _a2[0], fn = _a2[1], _config = _a2[2]; | ||
var config = mergeConfigs(fallbackConfig, _config); | ||
var next = hook; | ||
var use = config.use; | ||
if (use) { | ||
for (var i = use.length; i-- > 0; ) { | ||
next = use[i](next); | ||
} | ||
} | ||
return next(key, fn || config.fetcher, config); | ||
}; | ||
}; | ||
var subscribeCallback = function(key, callbacks, callback) { | ||
var keyedRevalidators = callbacks[key] || (callbacks[key] = []); | ||
keyedRevalidators.push(callback); | ||
return function() { | ||
var index = keyedRevalidators.indexOf(callback); | ||
if (index >= 0) { | ||
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1]; | ||
keyedRevalidators.pop(); | ||
} | ||
}; | ||
}; | ||
var WITH_DEDUPE = { dedupe: true }; | ||
var useSWRHandler = function(_key, fetcher, config) { | ||
var cache2 = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline; | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], MUTATION = _a2[2], FETCH = _a2[3]; | ||
var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2]; | ||
var initialMountedRef = (0, import_react2.useRef)(false); | ||
var unmountedRef = (0, import_react2.useRef)(false); | ||
var keyRef = (0, import_react2.useRef)(key); | ||
var fetcherRef = (0, import_react2.useRef)(fetcher); | ||
var configRef = (0, import_react2.useRef)(config); | ||
var getConfig = function() { | ||
return configRef.current; | ||
}; | ||
var isActive = function() { | ||
return getConfig().isVisible() && getConfig().isOnline(); | ||
}; | ||
var patchFetchInfo = function(info2) { | ||
return cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), info2)); | ||
}; | ||
var cached = cache2.get(key); | ||
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData; | ||
var data = isUndefined(cached) ? fallback : cached; | ||
var info = cache2.get(keyInfo) || {}; | ||
var error = info.error; | ||
var isInitialMount = !initialMountedRef.current; | ||
var shouldRevalidate = function() { | ||
if (isInitialMount && !isUndefined(revalidateOnMount)) | ||
return revalidateOnMount; | ||
if (getConfig().isPaused()) | ||
return false; | ||
if (suspense) | ||
return isUndefined(data) ? false : config.revalidateIfStale; | ||
return isUndefined(data) || config.revalidateIfStale; | ||
}; | ||
var resolveValidating = function() { | ||
if (!key || !fetcher) | ||
return false; | ||
if (info.isValidating) | ||
return true; | ||
return isInitialMount && shouldRevalidate(); | ||
}; | ||
var isValidating = resolveValidating(); | ||
var _c = useStateWithDeps({ | ||
data, | ||
error, | ||
isValidating | ||
}, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2]; | ||
var revalidate = (0, import_react2.useCallback)( | ||
function(revalidateOpts) { | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1; | ||
var _a3; | ||
return __generator(this, function(_b2) { | ||
switch (_b2.label) { | ||
case 0: | ||
currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return [2, false]; | ||
} | ||
loading = true; | ||
opts = revalidateOpts || {}; | ||
shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
isCurrentKeyMounted = function() { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
}; | ||
cleanupState = function() { | ||
var requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
newState = { isValidating: false }; | ||
finishRequestAndUpdateState = function() { | ||
patchFetchInfo({ isValidating: false }); | ||
if (isCurrentKeyMounted()) { | ||
setState(newState); | ||
} | ||
}; | ||
patchFetchInfo({ | ||
isValidating: true | ||
}); | ||
setState({ isValidating: true }); | ||
_b2.label = 1; | ||
case 1: | ||
_b2.trys.push([1, 3, , 4]); | ||
if (shouldStartNewRequest) { | ||
broadcastState(cache2, key, stateRef.current.data, stateRef.current.error, true); | ||
if (config.loadingTimeout && !cache2.get(key)) { | ||
setTimeout(function() { | ||
if (loading && isCurrentKeyMounted()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()]; | ||
} | ||
_a3 = FETCH[key], newData = _a3[0], startAt = _a3[1]; | ||
return [4, newData]; | ||
case 2: | ||
newData = _b2.sent(); | ||
if (shouldStartNewRequest) { | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
patchFetchInfo({ | ||
error: UNDEFINED | ||
}); | ||
newState.error = UNDEFINED; | ||
mutationInfo = MUTATION[key]; | ||
if (!isUndefined(mutationInfo) && (startAt <= mutationInfo[0] || startAt <= mutationInfo[1] || mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
if (!compare(stateRef.current.data, newData)) { | ||
newState.data = newData; | ||
} else { | ||
newState.data = stateRef.current.data; | ||
} | ||
if (!compare(cache2.get(key), newData)) { | ||
cache2.set(key, newData); | ||
} | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
return [3, 4]; | ||
case 3: | ||
err_1 = _b2.sent(); | ||
cleanupState(); | ||
if (!getConfig().isPaused()) { | ||
patchFetchInfo({ error: err_1 }); | ||
newState.error = err_1; | ||
if (shouldStartNewRequest && isCurrentKeyMounted()) { | ||
getConfig().onError(err_1, key, config); | ||
if (typeof config.shouldRetryOnError === "boolean" && config.shouldRetryOnError || isFunction(config.shouldRetryOnError) && config.shouldRetryOnError(err_1)) { | ||
if (isActive()) { | ||
getConfig().onErrorRetry(err_1, key, config, revalidate, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
return [3, 4]; | ||
case 4: | ||
loading = false; | ||
finishRequestAndUpdateState(); | ||
if (isCurrentKeyMounted() && shouldStartNewRequest) { | ||
broadcastState(cache2, key, newState.data, newState.error, false); | ||
} | ||
return [2, true]; | ||
} | ||
}); | ||
}); | ||
}, | ||
[key] | ||
); | ||
var boundMutate = (0, import_react2.useCallback)( | ||
internalMutate.bind(UNDEFINED, cache2, function() { | ||
return keyRef.current; | ||
}), | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
}); | ||
useIsomorphicLayoutEffect(function() { | ||
if (!key) | ||
return; | ||
var keyChanged = key !== keyRef.current; | ||
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE); | ||
var onStateUpdate = function(updatedData, updatedError, updatedIsValidating) { | ||
setState(mergeObjects( | ||
{ | ||
error: updatedError, | ||
isValidating: updatedIsValidating | ||
}, | ||
compare(stateRef.current.data, updatedData) ? UNDEFINED : { | ||
data: updatedData | ||
} | ||
)); | ||
}; | ||
var nextFocusRevalidatedAt = 0; | ||
var onRevalidate = function(type) { | ||
if (type == FOCUS_EVENT) { | ||
var now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == MUTATE_EVENT) { | ||
return revalidate(); | ||
} | ||
return; | ||
}; | ||
var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate); | ||
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
if (keyChanged) { | ||
setState({ | ||
data, | ||
error, | ||
isValidating | ||
}); | ||
} | ||
if (shouldRevalidate()) { | ||
if (isUndefined(data) || IS_SERVER) { | ||
softRevalidate(); | ||
} else { | ||
rAF(softRevalidate); | ||
} | ||
} | ||
return function() { | ||
unmountedRef.current = true; | ||
unsubUpdate(); | ||
unsubEvents(); | ||
}; | ||
}, [key, revalidate]); | ||
useIsomorphicLayoutEffect(function() { | ||
var timer; | ||
function next() { | ||
var interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval; | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
if (!stateRef.current.error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
next(); | ||
} | ||
} | ||
next(); | ||
return function() { | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]); | ||
(0, import_react2.useDebugValue)(data); | ||
if (suspense && isUndefined(data) && key) { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error; | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data() { | ||
stateDependencies.data = true; | ||
return data; | ||
}, | ||
get error() { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating() { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
} | ||
}; | ||
}; | ||
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "default", { | ||
value: defaultConfig | ||
}); | ||
var useSWR = withArgs(useSWRHandler); | ||
// src/hooks/useOrganization.tsx | ||
var useOrganization = (params) => { | ||
const { invitationList: invitationListParams, membershipList: membershipListParams } = params || {}; | ||
const { organization, lastOrganizationMember, lastOrganizationInvitation } = useOrganizationContext(); | ||
const session = useSessionContext(); | ||
const clerk = useClerkInstanceContext(); | ||
const shouldFetch = clerk.loaded && session && organization; | ||
const pendingInvitations = !clerk.loaded ? () => [] : () => clerk.organization?.getPendingInvitations(invitationListParams); | ||
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => clerk.organization?.getMemberships(membershipListParams); | ||
const { | ||
data: invitationList, | ||
isValidating: isInvitationsLoading, | ||
mutate: mutateInvitationList | ||
} = useSWR( | ||
shouldFetch && invitationListParams ? cacheKey("invites", organization, lastOrganizationInvitation, invitationListParams) : null, | ||
pendingInvitations | ||
); | ||
const { | ||
data: membershipList, | ||
isValidating: isMembershipsLoading, | ||
mutate: mutateMembershipList | ||
} = useSWR( | ||
shouldFetch && membershipListParams ? cacheKey("memberships", organization, lastOrganizationMember, membershipListParams) : null, | ||
currentOrganizationMemberships | ||
); | ||
if (organization === void 0) { | ||
return { | ||
isLoaded: false, | ||
organization: void 0, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
if (organization === null) { | ||
return { | ||
isLoaded: true, | ||
organization: null, | ||
invitationList: null, | ||
membershipList: null, | ||
membership: null | ||
}; | ||
} | ||
if (!clerk.loaded && organization) { | ||
return { | ||
isLoaded: true, | ||
organization, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: !isMembershipsLoading && !isInvitationsLoading, | ||
organization, | ||
membershipList, | ||
membership: getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id), | ||
invitationList, | ||
unstable__mutate: () => { | ||
void mutateMembershipList(); | ||
void mutateInvitationList(); | ||
} | ||
}; | ||
}; | ||
function getCurrentOrganizationMembership(organizationMemberships, activeOrganizationId) { | ||
return organizationMemberships.find( | ||
(organizationMembership) => organizationMembership.organization.id === activeOrganizationId | ||
); | ||
} | ||
function cacheKey(type, organization, resource, pagination) { | ||
return [type, organization.id, resource?.id, resource?.updatedAt, pagination.offset, pagination.limit].filter(Boolean).join("-"); | ||
} | ||
// src/hooks/useOrganizationList.tsx | ||
var useOrganizationList = () => { | ||
const clerk = useClerkInstanceContext(); | ||
const user = useUserContext(); | ||
if (!clerk.loaded || !user) { | ||
return { isLoaded: false, organizationList: void 0, createOrganization: void 0, setActive: void 0 }; | ||
} | ||
return { | ||
isLoaded: true, | ||
organizationList: createOrganizationList(user.organizationMemberships), | ||
setActive: clerk.setActive, | ||
createOrganization: clerk.createOrganization | ||
}; | ||
}; | ||
function createOrganizationList(organizationMemberships) { | ||
return organizationMemberships.map((organizationMembership) => ({ | ||
membership: organizationMembership, | ||
organization: organizationMembership.organization | ||
})); | ||
} | ||
// src/hooks/useOrganizations.tsx | ||
var useOrganizations = () => { | ||
const clerk = useClerkInstanceContext(); | ||
if (!clerk.loaded) { | ||
return { | ||
isLoaded: false, | ||
createOrganization: void 0, | ||
getOrganizationMemberships: void 0, | ||
getOrganization: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: true, | ||
createOrganization: clerk.createOrganization, | ||
getOrganizationMemberships: clerk.getOrganizationMemberships, | ||
getOrganization: clerk.getOrganization | ||
}; | ||
}; | ||
// src/utils/array.ts | ||
var toSentence = (items) => { | ||
if (items.length == 0) { | ||
return ""; | ||
} | ||
if (items.length == 1) { | ||
return items[0]; | ||
} | ||
let sentence = items.slice(0, -1).join(", "); | ||
sentence += `, or ${items.slice(-1)}`; | ||
return sentence; | ||
}; | ||
// src/utils/browser.ts | ||
function inBrowser() { | ||
return typeof window !== "undefined"; | ||
} | ||
function detectUserAgentRobot(userAgent) { | ||
const robots = new RegExp( | ||
[ | ||
/bot/, | ||
/spider/, | ||
/crawl/, | ||
/APIs-Google/, | ||
/AdsBot/, | ||
/Googlebot/, | ||
/mediapartners/, | ||
/Google Favicon/, | ||
/FeedFetcher/, | ||
/Google-Read-Aloud/, | ||
/DuplexWeb-Google/, | ||
/googleweblight/, | ||
/bing/, | ||
/yandex/, | ||
/baidu/, | ||
/duckduck/, | ||
/yahoo/, | ||
/ecosia/, | ||
/ia_archiver/, | ||
/facebook/, | ||
/instagram/, | ||
/pinterest/, | ||
/reddit/, | ||
/slack/, | ||
/twitter/, | ||
/whatsapp/, | ||
/youtube/, | ||
/semrush/ | ||
].map((r) => r.source).join("|"), | ||
"i" | ||
); | ||
return robots.test(userAgent); | ||
} | ||
function isValidBrowserOnline() { | ||
const navigator2 = window?.navigator; | ||
if (!inBrowser() || !navigator2) { | ||
return false; | ||
} | ||
const isUserAgentRobot = detectUserAgentRobot(navigator2?.userAgent); | ||
const isWebDriver = navigator2?.webdriver; | ||
const isNavigatorOnline = navigator2?.onLine; | ||
const isExperimentalConnectionOnline = navigator2?.connection?.rtt !== 0 && navigator2?.connection?.downlink !== 0; | ||
return !isUserAgentRobot && !isWebDriver && isExperimentalConnectionOnline && isNavigatorOnline; | ||
} | ||
// src/utils/color/predicates.ts | ||
var IS_HEX_COLOR_REGEX = /^#?([A-F0-9]{6}|[A-F0-9]{3})$/i; | ||
var IS_RGB_COLOR_REGEX = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i; | ||
var IS_RGBA_COLOR_REGEX = /^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i; | ||
var IS_HSL_COLOR_REGEX = /^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i; | ||
var IS_HSLA_COLOR_REGEX = /^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i; | ||
var isValidHexString = (s) => { | ||
return !!s.match(IS_HEX_COLOR_REGEX); | ||
}; | ||
var isValidRgbaString = (s) => { | ||
return !!(s.match(IS_RGB_COLOR_REGEX) || s.match(IS_RGBA_COLOR_REGEX)); | ||
}; | ||
var isValidHslaString = (s) => { | ||
return !!s.match(IS_HSL_COLOR_REGEX) || !!s.match(IS_HSLA_COLOR_REGEX); | ||
}; | ||
var isRGBColor = (c) => { | ||
return typeof c !== "string" && "r" in c; | ||
}; | ||
var isHSLColor = (c) => { | ||
return typeof c !== "string" && "h" in c; | ||
}; | ||
var isTransparent = (c) => { | ||
return c === "transparent"; | ||
}; | ||
var hasAlpha = (color) => { | ||
return typeof color !== "string" && color.a != void 0 && color.a < 1; | ||
}; | ||
// src/utils/color/cssColorUtils.ts | ||
var CLEAN_HSLA_REGEX = /[hsla()]/g; | ||
var CLEAN_RGBA_REGEX = /[rgba()]/g; | ||
var stringToHslaColor = (value) => { | ||
if (value === "transparent") { | ||
return { h: 0, s: 0, l: 0, a: 0 }; | ||
} | ||
if (isValidHexString(value)) { | ||
return hexStringToHslaColor(value); | ||
} | ||
if (isValidHslaString(value)) { | ||
return parseHslaString(value); | ||
} | ||
if (isValidRgbaString(value)) { | ||
return rgbaStringToHslaColor(value); | ||
} | ||
return null; | ||
}; | ||
var stringToSameTypeColor = (value) => { | ||
value = value.trim(); | ||
if (isValidHexString(value)) { | ||
return value.startsWith("#") ? value : `#${value}`; | ||
} | ||
if (isValidRgbaString(value)) { | ||
return parseRgbaString(value); | ||
} | ||
if (isValidHslaString(value)) { | ||
return parseHslaString(value); | ||
} | ||
if (isTransparent(value)) { | ||
return value; | ||
} | ||
return ""; | ||
}; | ||
var colorToSameTypeString = (color) => { | ||
if (typeof color === "string" && (isValidHexString(color) || isTransparent(color))) { | ||
return color; | ||
} | ||
if (isRGBColor(color)) { | ||
return rgbaColorToRgbaString(color); | ||
} | ||
if (isHSLColor(color)) { | ||
return hslaColorToHslaString(color); | ||
} | ||
return ""; | ||
}; | ||
var hexStringToRgbaColor = (hex) => { | ||
hex = hex.replace("#", ""); | ||
const r = parseInt(hex.substring(0, 2), 16); | ||
const g = parseInt(hex.substring(2, 4), 16); | ||
const b = parseInt(hex.substring(4, 6), 16); | ||
return { r, g, b }; | ||
}; | ||
var rgbaColorToRgbaString = (color) => { | ||
const { a, b, g, r } = color; | ||
return color.a === 0 ? "transparent" : color.a != void 0 ? `rgba(${r},${g},${b},${a})` : `rgb(${r},${g},${b})`; | ||
}; | ||
var hslaColorToHslaString = (color) => { | ||
const { h, s, l, a } = color; | ||
const sPerc = Math.round(s * 100); | ||
const lPerc = Math.round(l * 100); | ||
return color.a === 0 ? "transparent" : color.a != void 0 ? `hsla(${h},${sPerc}%,${lPerc}%,${a})` : `hsl(${h},${sPerc}%,${lPerc}%)`; | ||
}; | ||
var hexStringToHslaColor = (hex) => { | ||
const rgbaString = colorToSameTypeString(hexStringToRgbaColor(hex)); | ||
return rgbaStringToHslaColor(rgbaString); | ||
}; | ||
var rgbaStringToHslaColor = (rgba) => { | ||
const rgbaColor = parseRgbaString(rgba); | ||
const r = rgbaColor.r / 255; | ||
const g = rgbaColor.g / 255; | ||
const b = rgbaColor.b / 255; | ||
const max = Math.max(r, g, b), min = Math.min(r, g, b); | ||
let h, s; | ||
const l = (max + min) / 2; | ||
if (max == min) { | ||
h = s = 0; | ||
} else { | ||
const d = max - min; | ||
s = l >= 0.5 ? d / (2 - (max + min)) : d / (max + min); | ||
switch (max) { | ||
case r: | ||
h = (g - b) / d * 60; | ||
break; | ||
case g: | ||
h = ((b - r) / d + 2) * 60; | ||
break; | ||
default: | ||
h = ((r - g) / d + 4) * 60; | ||
break; | ||
} | ||
} | ||
const res = { h: Math.round(h), s, l }; | ||
const a = rgbaColor.a; | ||
if (a != void 0) { | ||
res.a = a; | ||
} | ||
return res; | ||
}; | ||
var parseRgbaString = (str) => { | ||
const [r, g, b, a] = str.replace(CLEAN_RGBA_REGEX, "").split(",").map((c) => Number.parseFloat(c)); | ||
return { r, g, b, a }; | ||
}; | ||
var parseHslaString = (str) => { | ||
const [h, s, l, a] = str.replace(CLEAN_HSLA_REGEX, "").split(",").map((c) => Number.parseFloat(c)); | ||
return { h, s: s / 100, l: l / 100, a }; | ||
}; | ||
// ../../node_modules/js-cookie/dist/js.cookie.mjs | ||
function assign(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
return target; | ||
} | ||
var defaultConverter = { | ||
read: function(value) { | ||
if (value[0] === '"') { | ||
value = value.slice(1, -1); | ||
} | ||
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); | ||
}, | ||
write: function(value) { | ||
return encodeURIComponent(value).replace( | ||
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, | ||
decodeURIComponent | ||
); | ||
} | ||
}; | ||
function init(converter, defaultAttributes) { | ||
function set(key, value, attributes) { | ||
if (typeof document === "undefined") { | ||
return; | ||
} | ||
attributes = assign({}, defaultAttributes, attributes); | ||
if (typeof attributes.expires === "number") { | ||
attributes.expires = new Date(Date.now() + attributes.expires * 864e5); | ||
} | ||
if (attributes.expires) { | ||
attributes.expires = attributes.expires.toUTCString(); | ||
} | ||
key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); | ||
var stringifiedAttributes = ""; | ||
for (var attributeName in attributes) { | ||
if (!attributes[attributeName]) { | ||
continue; | ||
} | ||
stringifiedAttributes += "; " + attributeName; | ||
if (attributes[attributeName] === true) { | ||
continue; | ||
} | ||
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0]; | ||
} | ||
return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes; | ||
} | ||
function get(key) { | ||
if (typeof document === "undefined" || arguments.length && !key) { | ||
return; | ||
} | ||
var cookies = document.cookie ? document.cookie.split("; ") : []; | ||
var jar = {}; | ||
for (var i = 0; i < cookies.length; i++) { | ||
var parts = cookies[i].split("="); | ||
var value = parts.slice(1).join("="); | ||
try { | ||
var foundKey = decodeURIComponent(parts[0]); | ||
jar[foundKey] = converter.read(value, foundKey); | ||
if (key === foundKey) { | ||
break; | ||
} | ||
} catch (e) { | ||
} | ||
} | ||
return key ? jar[key] : jar; | ||
} | ||
return Object.create( | ||
{ | ||
set, | ||
get, | ||
remove: function(key, attributes) { | ||
set( | ||
key, | ||
"", | ||
assign({}, attributes, { | ||
expires: -1 | ||
}) | ||
); | ||
}, | ||
withAttributes: function(attributes) { | ||
return init(this.converter, assign({}, this.attributes, attributes)); | ||
}, | ||
withConverter: function(converter2) { | ||
return init(assign({}, this.converter, converter2), this.attributes); | ||
} | ||
}, | ||
{ | ||
attributes: { value: Object.freeze(defaultAttributes) }, | ||
converter: { value: Object.freeze(converter) } | ||
} | ||
); | ||
} | ||
var api = init(defaultConverter, { path: "/" }); | ||
var js_cookie_default = api; | ||
// src/utils/cookies.ts | ||
function createCookieHandler(cookieName) { | ||
return { | ||
get() { | ||
return js_cookie_default.get(cookieName); | ||
}, | ||
set(newValue, options = {}) { | ||
return js_cookie_default.set(cookieName, newValue, options); | ||
}, | ||
remove(locationAttributes) { | ||
js_cookie_default.remove(cookieName, locationAttributes); | ||
} | ||
}; | ||
} | ||
// src/utils/date.ts | ||
var MILLISECONDS_IN_DAY = 864e5; | ||
function dateTo12HourTime(date) { | ||
if (!date) { | ||
return ""; | ||
} | ||
return date.toLocaleString("en-US", { | ||
hour: "2-digit", | ||
minute: "numeric", | ||
hour12: true | ||
}); | ||
} | ||
function differenceInCalendarDays(a, b, { absolute = true } = {}) { | ||
if (!a || !b) { | ||
return 0; | ||
} | ||
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()); | ||
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()); | ||
const diff = Math.floor((utcB - utcA) / MILLISECONDS_IN_DAY); | ||
return absolute ? Math.abs(diff) : diff; | ||
} | ||
function normalizeDate(d) { | ||
try { | ||
return new Date(d || new Date()); | ||
} catch (e) { | ||
return new Date(); | ||
} | ||
} | ||
function formatRelative(props) { | ||
const { date, relativeTo } = props; | ||
if (!date || !relativeTo) { | ||
return null; | ||
} | ||
const a = normalizeDate(date); | ||
const b = normalizeDate(relativeTo); | ||
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false }); | ||
if (differenceInDays < -6) { | ||
return { relativeDateCase: "other", date: a }; | ||
} | ||
if (differenceInDays < -1) { | ||
return { relativeDateCase: "previous6Days", date: a }; | ||
} | ||
if (differenceInDays === -1) { | ||
return { relativeDateCase: "lastDay", date: a }; | ||
} | ||
if (differenceInDays === 0) { | ||
return { relativeDateCase: "sameDay", date: a }; | ||
} | ||
if (differenceInDays === 1) { | ||
return { relativeDateCase: "nextDay", date: a }; | ||
} | ||
if (differenceInDays < 7) { | ||
return { relativeDateCase: "next6Days", date: a }; | ||
} | ||
return { relativeDateCase: "other", date: a }; | ||
} | ||
function addYears(initialDate, yearsToAdd) { | ||
const date = normalizeDate(initialDate); | ||
date.setFullYear(date.getFullYear() + yearsToAdd); | ||
return date; | ||
} | ||
// src/utils/file.ts | ||
function readJSONFile(file) { | ||
return new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.addEventListener("load", function() { | ||
const result = JSON.parse(reader.result); | ||
resolve(result); | ||
}); | ||
reader.addEventListener("error", reject); | ||
reader.readAsText(file); | ||
}); | ||
} | ||
// src/utils/isomorphicAtob.ts | ||
var isomorphicAtob = (data) => { | ||
if (typeof atob !== "undefined" && typeof atob === "function") { | ||
return atob(data); | ||
} else if (typeof Buffer !== "undefined") { | ||
return new Buffer(data, "base64").toString(); | ||
} | ||
return data; | ||
}; | ||
// src/utils/keys.ts | ||
var PUBLISHABLE_KEY_LIVE_PREFIX = "pk_live_"; | ||
var PUBLISHABLE_KEY_TEST_PREFIX = "pk_test_"; | ||
var PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\.clerk\.accounts([a-z.]*)(dev|com)$/i; | ||
function buildPublishableKey(frontendApi) { | ||
const keyPrefix = PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX; | ||
return `${keyPrefix}${btoa(`${frontendApi}$`)}`; | ||
} | ||
function parsePublishableKey(key) { | ||
key = key || ""; | ||
if (!isPublishableKey(key)) { | ||
return null; | ||
} | ||
const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? "production" : "development"; | ||
let frontendApi = isomorphicAtob(key.split("_")[2]); | ||
if (!frontendApi.endsWith("$")) { | ||
return null; | ||
} | ||
frontendApi = frontendApi.slice(0, -1); | ||
return { | ||
instanceType, | ||
frontendApi | ||
}; | ||
} | ||
function isPublishableKey(key) { | ||
key = key || ""; | ||
const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX); | ||
const hasValidFrontendApiPostfix = isomorphicAtob(key.split("_")[2] || "").endsWith("$"); | ||
return hasValidPrefix && hasValidFrontendApiPostfix; | ||
} | ||
function isLegacyFrontendApiKey(key) { | ||
key = key || ""; | ||
return key.startsWith("clerk."); | ||
} | ||
// src/utils/isRetinaDisplay.ts | ||
function isRetinaDisplay() { | ||
if (!window.matchMedia) { | ||
return false; | ||
} | ||
const mq = window.matchMedia( | ||
"only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)" | ||
); | ||
return mq && mq.matches || window.devicePixelRatio > 1; | ||
} | ||
// src/utils/localStorageBroadcastChannel.ts | ||
var KEY_PREFIX = "__lsbc__"; | ||
var LocalStorageBroadcastChannel = class { | ||
constructor(name) { | ||
this.eventTarget = window; | ||
this.postMessage = (data) => { | ||
try { | ||
localStorage.setItem(this.channelKey, JSON.stringify(data)); | ||
localStorage.removeItem(this.channelKey); | ||
} catch (e) { | ||
} | ||
}; | ||
this.addEventListener = (eventName, listener) => { | ||
this.eventTarget.addEventListener(this.prefixEventName(eventName), (e) => { | ||
listener(e); | ||
}); | ||
}; | ||
this.setupLocalStorageListener = () => { | ||
const notifyListeners = (e) => { | ||
if (e.key !== this.channelKey || !e.newValue) { | ||
return; | ||
} | ||
try { | ||
const data = JSON.parse(e.newValue || ""); | ||
const event = new MessageEvent(this.prefixEventName("message"), { | ||
data | ||
}); | ||
this.eventTarget.dispatchEvent(event); | ||
} catch (e2) { | ||
} | ||
}; | ||
window.addEventListener("storage", notifyListeners); | ||
}; | ||
this.channelKey = KEY_PREFIX + name; | ||
this.setupLocalStorageListener(); | ||
} | ||
prefixEventName(eventName) { | ||
return this.channelKey + eventName; | ||
} | ||
}; | ||
// src/utils/mimeTypeExtensions.ts | ||
var MimeTypeToExtensionMap = Object.freeze({ | ||
"image/png": "png", | ||
"image/jpeg": "jpg", | ||
"image/gif": "gif", | ||
"image/webp": "webp", | ||
"image/x-icon": "ico", | ||
"image/vnd.microsoft.icon": "ico" | ||
}); | ||
var extension = (mimeType) => { | ||
return MimeTypeToExtensionMap[mimeType]; | ||
}; | ||
// src/utils/noop.ts | ||
var noop2 = (..._args) => { | ||
}; | ||
// src/utils/string.ts | ||
var IP_V4_ADDRESS_REGEX = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; | ||
function isIPV4Address(str) { | ||
return IP_V4_ADDRESS_REGEX.test(str || ""); | ||
} | ||
function titleize(str) { | ||
const s = str || ""; | ||
return s.charAt(0).toUpperCase() + s.slice(1); | ||
} | ||
function snakeToCamel(str) { | ||
return str ? str.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, "")) : ""; | ||
} | ||
function camelToSnake(str) { | ||
return str ? str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`) : ""; | ||
} | ||
// src/utils/object.ts | ||
var createDeepObjectTransformer = (transform) => { | ||
const deepTransform = (obj) => { | ||
if (!obj) { | ||
return obj; | ||
} | ||
if (Array.isArray(obj)) { | ||
return obj.map((el) => { | ||
if (typeof el === "object" || Array.isArray(el)) { | ||
return deepTransform(el); | ||
} | ||
return el; | ||
}); | ||
} | ||
const copy = { ...obj }; | ||
const keys = Object.keys(copy); | ||
for (const oldName of keys) { | ||
const newName = transform(oldName.toString()); | ||
if (newName !== oldName) { | ||
copy[newName] = copy[oldName]; | ||
delete copy[oldName]; | ||
} | ||
if (typeof copy[newName] === "object") { | ||
copy[newName] = deepTransform(copy[newName]); | ||
} | ||
} | ||
return copy; | ||
}; | ||
return deepTransform; | ||
}; | ||
var deepCamelToSnake = createDeepObjectTransformer(camelToSnake); | ||
var deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel); | ||
// src/utils/workerTimers/workerTimers.worker.ts | ||
var workerTimers_worker_default = 'const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id})},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n'; | ||
// src/utils/workerTimers/createWorkerTimers.ts | ||
var createWebWorker = (source, opts = {}) => { | ||
if (typeof Worker === "undefined") { | ||
return null; | ||
} | ||
try { | ||
const blob = new Blob([source], { type: "application/javascript; charset=utf-8" }); | ||
const workerScript = globalThis.URL.createObjectURL(blob); | ||
return new Worker(workerScript, opts); | ||
} catch (e) { | ||
console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"); | ||
return null; | ||
} | ||
}; | ||
var fallbackTimers = () => { | ||
const setTimeout2 = globalThis.setTimeout.bind(globalThis); | ||
const setInterval = globalThis.setInterval.bind(globalThis); | ||
const clearTimeout2 = globalThis.clearTimeout.bind(globalThis); | ||
const clearInterval = globalThis.clearInterval.bind(globalThis); | ||
return { setTimeout: setTimeout2, setInterval, clearTimeout: clearTimeout2, clearInterval, cleanup: noop2 }; | ||
}; | ||
var createWorkerTimers = () => { | ||
let id = 0; | ||
const generateId = () => id++; | ||
const callbacks = /* @__PURE__ */ new Map(); | ||
const post = (w, p) => w?.postMessage(p); | ||
const handleMessage = (e) => { | ||
callbacks.get(e.data.id)?.(); | ||
}; | ||
let worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" }); | ||
worker?.addEventListener("message", handleMessage); | ||
if (!worker) { | ||
return fallbackTimers(); | ||
} | ||
const init2 = () => { | ||
if (!worker) { | ||
worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" }); | ||
worker?.addEventListener("message", handleMessage); | ||
} | ||
}; | ||
const cleanup = () => { | ||
if (worker) { | ||
worker.terminate(); | ||
worker = null; | ||
callbacks.clear(); | ||
} | ||
}; | ||
const setTimeout2 = (cb, ms) => { | ||
init2(); | ||
const id2 = generateId(); | ||
callbacks.set(id2, cb); | ||
post(worker, { type: "setTimeout", id: id2, ms }); | ||
return id2; | ||
}; | ||
const setInterval = (cb, ms) => { | ||
init2(); | ||
const id2 = generateId(); | ||
callbacks.set(id2, cb); | ||
post(worker, { type: "setInterval", id: id2, ms }); | ||
return id2; | ||
}; | ||
const clearTimeout2 = (id2) => { | ||
init2(); | ||
callbacks.delete(id2); | ||
post(worker, { type: "clearTimeout", id: id2 }); | ||
}; | ||
const clearInterval = (id2) => { | ||
init2(); | ||
callbacks.delete(id2); | ||
post(worker, { type: "clearInterval", id: id2 }); | ||
}; | ||
return { setTimeout: setTimeout2, setInterval, clearTimeout: clearTimeout2, clearInterval, cleanup }; | ||
}; | ||
// src/utils/poller.ts | ||
function Poller({ delayInMs } = { delayInMs: 1e3 }) { | ||
const workerTimers = createWorkerTimers(); | ||
let timerId; | ||
let stopped = false; | ||
const stop = () => { | ||
if (timerId) { | ||
workerTimers.clearTimeout(timerId); | ||
workerTimers.cleanup(); | ||
} | ||
stopped = true; | ||
}; | ||
const run = async (cb) => { | ||
stopped = false; | ||
await cb(stop); | ||
if (stopped) { | ||
return; | ||
} | ||
timerId = workerTimers.setTimeout(() => { | ||
void run(cb); | ||
}, delayInMs); | ||
}; | ||
return { run, stop }; | ||
} | ||
// src/utils/proxy.ts | ||
function isValidProxyUrl(key) { | ||
if (!key) { | ||
return true; | ||
} | ||
return isHttpOrHttps(key) || isProxyUrlRelative(key); | ||
} | ||
function isHttpOrHttps(key) { | ||
return key?.startsWith("https://") || key?.startsWith("http://") || false; | ||
} | ||
function isProxyUrlRelative(key) { | ||
return key.startsWith("/"); | ||
} | ||
function proxyUrlToAbsoluteURL(url) { | ||
if (!url) { | ||
return ""; | ||
} | ||
return isProxyUrlRelative(url) ? new URL(url, window.location.origin).toString() : url; | ||
} | ||
// src/utils/ssr.ts | ||
var inClientSide = () => { | ||
return typeof window !== "undefined"; | ||
}; | ||
// src/utils/url.ts | ||
function parseSearchParams(queryString = "") { | ||
if (queryString.startsWith("?")) { | ||
queryString = queryString.slice(1); | ||
} | ||
return new URLSearchParams(queryString); | ||
} | ||
// src/utils/runWithExponentialBackOff.ts | ||
var defaultOptions = { | ||
maxRetries: 10, | ||
firstDelay: 125, | ||
timeMultiple: 2, | ||
shouldRetry: () => true | ||
}; | ||
var sleep = async (ms) => new Promise((s) => setTimeout(s, ms)); | ||
var createExponentialDelayAsyncFn = (opts) => { | ||
let timesCalled = 0; | ||
const calculateDelayInMs = () => { | ||
const constant = opts.firstDelay; | ||
const base = opts.timeMultiple; | ||
return constant * Math.pow(base, timesCalled); | ||
}; | ||
return async () => { | ||
await sleep(calculateDelayInMs()); | ||
timesCalled++; | ||
}; | ||
}; | ||
var runWithExponentialBackOff = async (callback, options = {}) => { | ||
let iterationsCount = 0; | ||
const { maxRetries, shouldRetry, firstDelay, timeMultiple } = { | ||
...defaultOptions, | ||
...options | ||
}; | ||
const maxRetriesReached = () => iterationsCount === maxRetries; | ||
const delay = createExponentialDelayAsyncFn({ firstDelay, timeMultiple }); | ||
while (!maxRetriesReached()) { | ||
try { | ||
return await callback(); | ||
} catch (e) { | ||
iterationsCount++; | ||
if (!shouldRetry(e, iterationsCount) || maxRetriesReached()) { | ||
throw e; | ||
} | ||
await delay(); | ||
} | ||
} | ||
throw new Error("Something went wrong"); | ||
}; | ||
// src/utils/createDeferredPromise.ts | ||
var createDeferredPromise = () => { | ||
let resolve = noop2; | ||
let reject = noop2; | ||
const promise = new Promise((res, rej) => { | ||
resolve = res; | ||
reject = rej; | ||
}); | ||
return { promise, resolve, reject }; | ||
}; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
ClerkInstanceContext, | ||
ClientContext, | ||
LocalStorageBroadcastChannel, | ||
OrganizationContext, | ||
Poller, | ||
SessionContext, | ||
UserContext, | ||
addYears, | ||
assertContextExists, | ||
buildErrorThrower, | ||
buildPublishableKey, | ||
camelToSnake, | ||
colorToSameTypeString, | ||
createContextAndHook, | ||
createCookieHandler, | ||
createDeferredPromise, | ||
createWorkerTimers, | ||
dateTo12HourTime, | ||
deepCamelToSnake, | ||
deepSnakeToCamel, | ||
detectUserAgentRobot, | ||
differenceInCalendarDays, | ||
extension, | ||
formatRelative, | ||
hasAlpha, | ||
hexStringToRgbaColor, | ||
inBrowser, | ||
inClientSide, | ||
isHSLColor, | ||
isHttpOrHttps, | ||
isIPV4Address, | ||
isLegacyFrontendApiKey, | ||
isProxyUrlRelative, | ||
isPublishableKey, | ||
isRGBColor, | ||
isRetinaDisplay, | ||
isTransparent, | ||
isValidBrowserOnline, | ||
isValidHexString, | ||
isValidHslaString, | ||
isValidProxyUrl, | ||
isValidRgbaString, | ||
isomorphicAtob, | ||
noop, | ||
normalizeDate, | ||
parsePublishableKey, | ||
parseSearchParams, | ||
proxyUrlToAbsoluteURL, | ||
readJSONFile, | ||
runWithExponentialBackOff, | ||
snakeToCamel, | ||
stringToHslaColor, | ||
stringToSameTypeColor, | ||
titleize, | ||
toSentence, | ||
useClerkInstanceContext, | ||
useClientContext, | ||
useOrganization, | ||
useOrganizationContext, | ||
useOrganizationList, | ||
useOrganizations, | ||
useSessionContext, | ||
useUserContext | ||
}); | ||
/*! ***************************************************************************** | ||
@@ -4,0 +1897,0 @@ Copyright (c) Microsoft Corporation. |
@@ -1,3 +0,215 @@ | ||
"use strict";var S=Object.create;var d=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var y=(e,t)=>{for(var r in t)d(e,r,{get:t[r],enumerable:!0})},m=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of D(t))!I.call(e,n)&&n!==r&&d(e,n,{get:()=>t[n],enumerable:!(i=k(t,n))||i.enumerable});return e},l=(e,t,r)=>(m(e,t,"default"),r&&m(r,t,"default")),_=(e,t,r)=>(r=e!=null?S(P(e)):{},m(t||!e||!e.__esModule?d(r,"default",{value:e,enumerable:!0}):r,e)),L=e=>m(d({},"__esModule",{value:!0}),e);var g={};y(g,{noop:()=>u,render:()=>w,userEvent:()=>h.default});module.exports=L(g);var a={};y(a,{noop:()=>u,render:()=>w,userEvent:()=>h.default});var qe=require("@testing-library/jest-dom/extend-expect"),R=require("@testing-library/react");function f(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)e[i]=r[i]}return e}var A={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function x(e,t){function r(n,s,o){if(!(typeof document>"u")){o=f({},t,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),n=encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var p in o)!o[p]||(c+="; "+p,o[p]!==!0&&(c+="="+o[p].split(";")[0]));return document.cookie=n+"="+e.write(s,n)+c}}function i(n){if(!(typeof document>"u"||arguments.length&&!n)){for(var s=document.cookie?document.cookie.split("; "):[],o={},c=0;c<s.length;c++){var p=s[c].split("="),E=p.slice(1).join("=");try{var b=decodeURIComponent(p[0]);if(o[b]=e.read(E,b),n===b)break}catch{}}return n?o[n]:o}}return Object.create({set:r,get:i,remove:function(n,s){r(n,"",f({},s,{expires:-1}))},withAttributes:function(n){return x(this.converter,f({},this.attributes,n))},withConverter:function(n){return x(f({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var Z=x(A,{path:"/"});var pe=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"});var u=(...e)=>{};function C(e){return e?e.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace(/-|_/,"")):""}function T(e){return e?e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`):""}var v=e=>{let t=r=>{if(!r)return r;if(Array.isArray(r))return r.map(s=>typeof s=="object"||Array.isArray(s)?t(s):s);let i={...r},n=Object.keys(i);for(let s of n){let o=e(s.toString());o!==s&&(i[o]=i[s],delete i[s]),typeof i[o]=="object"&&(i[o]=t(i[o]))}return i};return t},ge=v(T),be=v(C);l(a,require("@testing-library/react"));var h=_(require("@testing-library/user-event")),w=(e,t)=>(0,R.render)(e,t);l(g,a,module.exports);0&&(module.exports={noop,render,userEvent}); | ||
"use strict"; | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
// src/testUtils/index.ts | ||
var testUtils_exports2 = {}; | ||
__export(testUtils_exports2, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => import_user_event.default | ||
}); | ||
module.exports = __toCommonJS(testUtils_exports2); | ||
// src/testUtils/testUtils.ts | ||
var testUtils_exports = {}; | ||
__export(testUtils_exports, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => import_user_event.default | ||
}); | ||
var import_extend_expect = require("@testing-library/jest-dom/extend-expect"); | ||
var import_react = require("@testing-library/react"); | ||
// ../../node_modules/js-cookie/dist/js.cookie.mjs | ||
function assign(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
return target; | ||
} | ||
var defaultConverter = { | ||
read: function(value) { | ||
if (value[0] === '"') { | ||
value = value.slice(1, -1); | ||
} | ||
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); | ||
}, | ||
write: function(value) { | ||
return encodeURIComponent(value).replace( | ||
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, | ||
decodeURIComponent | ||
); | ||
} | ||
}; | ||
function init(converter, defaultAttributes) { | ||
function set(key, value, attributes) { | ||
if (typeof document === "undefined") { | ||
return; | ||
} | ||
attributes = assign({}, defaultAttributes, attributes); | ||
if (typeof attributes.expires === "number") { | ||
attributes.expires = new Date(Date.now() + attributes.expires * 864e5); | ||
} | ||
if (attributes.expires) { | ||
attributes.expires = attributes.expires.toUTCString(); | ||
} | ||
key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); | ||
var stringifiedAttributes = ""; | ||
for (var attributeName in attributes) { | ||
if (!attributes[attributeName]) { | ||
continue; | ||
} | ||
stringifiedAttributes += "; " + attributeName; | ||
if (attributes[attributeName] === true) { | ||
continue; | ||
} | ||
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0]; | ||
} | ||
return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes; | ||
} | ||
function get(key) { | ||
if (typeof document === "undefined" || arguments.length && !key) { | ||
return; | ||
} | ||
var cookies = document.cookie ? document.cookie.split("; ") : []; | ||
var jar = {}; | ||
for (var i = 0; i < cookies.length; i++) { | ||
var parts = cookies[i].split("="); | ||
var value = parts.slice(1).join("="); | ||
try { | ||
var foundKey = decodeURIComponent(parts[0]); | ||
jar[foundKey] = converter.read(value, foundKey); | ||
if (key === foundKey) { | ||
break; | ||
} | ||
} catch (e) { | ||
} | ||
} | ||
return key ? jar[key] : jar; | ||
} | ||
return Object.create( | ||
{ | ||
set, | ||
get, | ||
remove: function(key, attributes) { | ||
set( | ||
key, | ||
"", | ||
assign({}, attributes, { | ||
expires: -1 | ||
}) | ||
); | ||
}, | ||
withAttributes: function(attributes) { | ||
return init(this.converter, assign({}, this.attributes, attributes)); | ||
}, | ||
withConverter: function(converter2) { | ||
return init(assign({}, this.converter, converter2), this.attributes); | ||
} | ||
}, | ||
{ | ||
attributes: { value: Object.freeze(defaultAttributes) }, | ||
converter: { value: Object.freeze(converter) } | ||
} | ||
); | ||
} | ||
var api = init(defaultConverter, { path: "/" }); | ||
// src/utils/mimeTypeExtensions.ts | ||
var MimeTypeToExtensionMap = Object.freeze({ | ||
"image/png": "png", | ||
"image/jpeg": "jpg", | ||
"image/gif": "gif", | ||
"image/webp": "webp", | ||
"image/x-icon": "ico", | ||
"image/vnd.microsoft.icon": "ico" | ||
}); | ||
// src/utils/noop.ts | ||
var noop = (..._args) => { | ||
}; | ||
// src/utils/string.ts | ||
function snakeToCamel(str) { | ||
return str ? str.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, "")) : ""; | ||
} | ||
function camelToSnake(str) { | ||
return str ? str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`) : ""; | ||
} | ||
// src/utils/object.ts | ||
var createDeepObjectTransformer = (transform) => { | ||
const deepTransform = (obj) => { | ||
if (!obj) { | ||
return obj; | ||
} | ||
if (Array.isArray(obj)) { | ||
return obj.map((el) => { | ||
if (typeof el === "object" || Array.isArray(el)) { | ||
return deepTransform(el); | ||
} | ||
return el; | ||
}); | ||
} | ||
const copy = { ...obj }; | ||
const keys = Object.keys(copy); | ||
for (const oldName of keys) { | ||
const newName = transform(oldName.toString()); | ||
if (newName !== oldName) { | ||
copy[newName] = copy[oldName]; | ||
delete copy[oldName]; | ||
} | ||
if (typeof copy[newName] === "object") { | ||
copy[newName] = deepTransform(copy[newName]); | ||
} | ||
} | ||
return copy; | ||
}; | ||
return deepTransform; | ||
}; | ||
var deepCamelToSnake = createDeepObjectTransformer(camelToSnake); | ||
var deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel); | ||
// src/testUtils/testUtils.ts | ||
__reExport(testUtils_exports, require("@testing-library/react")); | ||
var import_user_event = __toESM(require("@testing-library/user-event")); | ||
var customRender = (ui, options) => { | ||
return (0, import_react.render)(ui, options); | ||
}; | ||
// src/testUtils/index.ts | ||
__reExport(testUtils_exports2, testUtils_exports, module.exports); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
noop, | ||
render, | ||
userEvent | ||
}); | ||
/*! js-cookie v3.0.1 | MIT */ | ||
//# sourceMappingURL=index.js.map |
import type { PublishableKey } from '@clerk/types'; | ||
export declare function buildPublishableKey(frontendApi: string): string; | ||
export declare function parsePublishableKey(key: string): PublishableKey | null; | ||
export declare function parsePublishableKey(key: string | undefined): PublishableKey | null; | ||
export declare function isPublishableKey(key: string): boolean; | ||
export declare function isLegacyFrontendApiKey(key: string): boolean; | ||
//# sourceMappingURL=keys.d.ts.map |
export declare function isValidProxyUrl(key: string | undefined): boolean; | ||
export declare function isHttpOrHttps(key: string | undefined): boolean; | ||
export declare function isProxyUrlRelative(key: string): boolean; | ||
export declare function proxyUrlToAbsoluteURL(url: string | undefined): string; | ||
//# sourceMappingURL=proxy.d.ts.map |
{ | ||
"name": "@clerk/shared", | ||
"version": "0.11.4", | ||
"version": "0.11.5-staging.0", | ||
"description": "Internal package utils used by the Clerk SDKs", | ||
@@ -21,3 +21,3 @@ "types": "./dist/types/index.d.ts", | ||
"devDependencies": { | ||
"@clerk/types": "^3.28.1", | ||
"@clerk/types": "^3.28.2-staging.0", | ||
"@testing-library/dom": "8.19.0", | ||
@@ -43,3 +43,3 @@ "@testing-library/jest-dom": "5.16.5", | ||
"license": "ISC", | ||
"gitHead": "1d37795e4b6effa06ec32c09684404a144861bd7", | ||
"gitHead": "909dee61d3e1f32e81e3f19de5d4365830a17b15", | ||
"publishConfig": { | ||
@@ -46,0 +46,0 @@ "access": "public" |
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
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
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 1 instance in 1 package
431982
4360
2