Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@clerk/shared

Package Overview
Dependencies
Maintainers
9
Versions
1753
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@clerk/shared - npm Package Compare versions

Comparing version 0.9.2 to 0.9.3-staging.1

dist/esm/chunk-S6EBXHRO.js

1098

dist/esm/index.js

@@ -1,2 +0,1098 @@

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 fr,J as lr,K as cr,L as dr,M as vr,N as gr,O as mr,P as hr,c as St,d as Pt,e as At,f as kt,g as Ut,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-CX34SAMA.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}})",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 pr({packageName:e,customMessages:i}){let t=e,n={...tt,...i};function a(r,o){if(!o)return`${t}: ${r}`;let f=r,d=r.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);for(let s of d){let l=(o[s[1]]||"").toString();f=f.replace(`{{${s[1]}}}`,l)}return`${t}: ${f}`}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))},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[xr,G]=H("ClerkInstanceContext"),[Er,Ie]=H("UserContext"),[wr,Lr]=H("ClientContext"),[Mr,Se]=H("SessionContext"),[Tr,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 f(l){try{s(n.next(l))}catch(v){o(v)}}function d(l){try{s(n.throw(l))}catch(v){o(v)}}function s(l){l.done?r(l.value):a(l.value).then(f,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:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function f(s){return function(l){return d([s,l])}}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(l){s=[6,l],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},k=function(e){return typeof e=="function"},S=function(e,i){return Q.assign({},e,i)},Ce="undefined",ye=function(){return typeof window!=Ce},ut=function(){return typeof document!=Ce},ft=function(){return ye()&&typeof window.requestAnimationFrame!=Ce},ie=new WeakMap,lt=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=++lt+"~",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=ye(),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=!ye()||"Deno"in window,Ot=function(e){return ft()?window.requestAnimationFrame(e):setTimeout(e,1)},X=ae?nt:it,ve=typeof navigator<"u"&&navigator.connection,Ae=!ae&&ve&&(["slow-2g","2g"].includes(ve.effectiveType)||ve.saveData),Ne=function(e){if(k(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 f=_.get(e),d=f[0],s=f[1],l=f[3],v=d[i],c=s[i];if(o&&c)for(var y=0;y<c.length;++y)c[y](t,n,a);return r&&(delete l[i],v&&v[0])?v[0](He).then(function(){return e.get(i)}):e.get(i)},zt=0,Oe=function(){return++zt},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,f,d,s,l,v,c,y,N,O,g,u,q,U,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||{},f=b(o.populateCache)?!0:o.populateCache,d=o.revalidate!==!1,s=o.rollbackOnError!==!1,l=o.optimisticData,v=Ne(n),c=v[0],y=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],U=!b(l),T=t.get(c),U&&(E=k(l)?l(T):l,t.set(c,E),ee(t,c,E)),k(g))try{g=g(t.get(c))}catch(V){u=V}return g&&k(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&&U&&s&&(f=!0,g=T,t.set(c,T));P.label=2;case 2:return f&&(u||(k(f)&&(g=f(g,T)),t.set(c,g)),t.set(y,S(t.get(y),{error:u}))),O[c][1]=Oe(),[4,ee(t,c,g,u,h,d,!!f)];case 3:if(D=P.sent(),u)throw u;return[2,f?D:g]}})})},ke=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,ke.bind(h,n,Ke))),f=t.initReconnect(setTimeout.bind(h,ke.bind(h,n,$e)));r=function(){o&&o(),f&&f(),_.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,f=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!b(r)&&o>r||setTimeout(n,f,a)},je=qe(new Map),Je=je[0],yt=je[1],Ye=S({onLoadingSlow:M,onSuccess:M,onError:M,onErrorRetry:Ct,onDiscarded:M,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Ae?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Ae?5e3:3e3,compare:function(e,i){return te(e)==te(i)},isPaused:function(){return!1},cache:Je,mutate:yt,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},ze=at({}),Rt=function(e){var i=e.value,t=Be(De(ze),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(ze.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 f=!1,d=n.current;for(var s in o){var l=s;d[l]!==o[l]&&(d[l]=o[l],a.current[l]&&(f=!0))}f&&!i.current&&t({})},[]);return X(function(){n.current=e}),[n,a.current,r]},Et=function(e){return k(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},wt=function(){return S(Ye,De(ze))},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],f=r[1],d=r[2],s=Be(a,d),l=e,v=s.use;if(v)for(var c=v.length;c-- >0;)l=v[c](l);return l(o,f||s.fetcher,s)}},Ue=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,f=t.revalidateOnMount,d=t.refreshInterval,s=t.refreshWhenHidden,l=t.refreshWhenOffline,v=_.get(n),c=v[0],y=v[1],N=v[2],O=v[3],g=Ne(e),u=g[0],q=g[1],U=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(U,S(n.get(U),R))},Ee=n.get(u),Qe=b(r)?t.fallback[u]:r,I=b(Ee)?Qe:Ee,we=n.get(U)||{},j=we.error,Le=!T.current,Me=function(){return Le&&!b(f)?f: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],fe=ue[1],ne=ue[2],F=me(function(R){return Fe(void 0,void 0,void 0,function(){var z,C,x,J,Y,w,p,A,L,le,B,$,ce;return We(this,function(Z){switch(Z.label){case 0:if(z=P.current,!u||!z||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},A=function(){var Te=O[u];Te&&Te[1]===x&&delete O[u]},L={isValidating:!1},le=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]=[z.apply(void 0,q),Oe()]),ce=O[u],C=ce[0],x=ce[1],[4,C];case 2:return C=Z.sent(),w&&setTimeout(A,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)?(le(),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(),A(),m().isPaused()||(re({error:$}),L.error=$,w&&p()&&(m().onError($,u,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||k(t.shouldRetryOnError)&&t.shouldRetryOnError($))&&oe()&&m().onErrorRetry($,u,t,F,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return J=!1,le(),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,z=F.bind(h,ge),C=function(p,A,L){ne(S({error:A,isValidating:L},a(K.current.data,p)?h:{data:p}))},x=0,J=function(p){if(p==Ke){var A=Date.now();m().revalidateOnFocus&&A>x&&oe()&&(x=A+m().focusThrottleInterval,z())}else if(p==$e)m().revalidateOnReconnect&&oe()&&z();else if(p==He)return F()},Y=Ue(u,y,C),w=Ue(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?z():Ot(z)),function(){E.current=!0,Y(),w()}}},[u,F]),X(function(){var R;function z(){var x=k(d)?d(I):d;x&&R!==-1&&(R=setTimeout(C,x))}function C(){!K.current.error&&(s||m().isVisible())&&(l||m().isOnline())?F(ge).then(z):z()}return z(),function(){R&&(clearTimeout(R),R=-1)}},[d,s,l,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 fe.data=!0,I},get error(){return fe.error=!0,j},get isValidating(){return fe.isValidating=!0,se}}},Pr=Q.defineProperty(Rt,"default",{value:Ye});var xe=Lt(Mt);var Dr=e=>{let{invitationList:i,membershipList:t}=e||{},{organization:n,lastOrganizationMember:a,lastOrganizationInvitation:r}=Pe(),o=Se(),f=G(),d=f.loaded&&o&&n,s=f.loaded?()=>f.organization?.getPendingInvitations(i):()=>[],l=f.loaded?()=>f.organization?.getMemberships(t):()=>[],{data:v,isValidating:c,mutate:y}=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,l);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}:!f.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(),y()}}};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 Wr=()=>{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 Kr=()=>{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{xr as ClerkInstanceContext,wr as ClientContext,nr as LocalStorageBroadcastChannel,Tr as OrganizationContext,vr as Poller,Mr as SessionContext,Er as UserContext,Yt as addYears,rt as assertContextExists,pr as buildErrorThrower,Qt as buildPublishableKey,fr as camelToSnake,Kt as colorToSameTypeString,H as createContextAndHook,Ht as createCookieHandler,dr as createWorkerTimers,Gt as dateTo12HourTime,lr as deepCamelToSnake,cr as deepSnakeToCamel,qt as differenceInCalendarDays,ir as extension,Jt as formatRelative,Wt as hasAlpha,$t as hexStringToRgbaColor,Pt as inBrowser,gr as inClientSide,Vt as isHSLColor,or as isIPV4Address,tr as isLegacyFrontendApiKey,er as isPublishableKey,Dt as isRGBColor,rr as isRetinaDisplay,Ft as isTransparent,At as isValidHexString,Ut as isValidHslaString,kt as isValidRgbaString,Zt as isomorphicAtob,ar as noop,jt as normalizeDate,Xt as parsePublishableKey,mr as parseSearchParams,Bt as readJSONFile,hr as runWithExponentialBackOff,ur as snakeToCamel,_t as stringToHslaColor,Nt as stringToSameTypeColor,sr as titleize,St as toSentence,G as useClerkInstanceContext,Lr as useClientContext,Dr as useOrganization,Pe as useOrganizationContext,Wr as useOrganizationList,Kr as useOrganizations,Se as useSessionContext,Ie as useUserContext};
import {
LocalStorageBroadcastChannel,
Poller,
addYears,
buildPublishableKey,
camelToSnake,
colorToSameTypeString,
createCookieHandler,
createWorkerTimers,
dateTo12HourTime,
deepCamelToSnake,
deepSnakeToCamel,
differenceInCalendarDays,
extension,
formatRelative,
hasAlpha,
hexStringToRgbaColor,
inBrowser,
inClientSide,
isHSLColor,
isIPV4Address,
isLegacyFrontendApiKey,
isPublishableKey,
isRGBColor,
isRetinaDisplay,
isTransparent,
isValidHexString,
isValidHslaString,
isValidRgbaString,
isomorphicAtob,
noop,
normalizeDate,
parsePublishableKey,
parseSearchParams,
readJSONFile,
runWithExponentialBackOff,
snakeToCamel,
stringToHslaColor,
stringToSameTypeColor,
titleize,
toSentence
} from "./chunk-S6EBXHRO.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}})`,
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));
},
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 ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.getPendingInvitations(invitationListParams);
};
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.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 == null ? void 0 : resource.id, resource == null ? void 0 : 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,
createWorkerTimers,
dateTo12HourTime,
deepCamelToSnake,
deepSnakeToCamel,
differenceInCalendarDays,
extension,
formatRelative,
hasAlpha,
hexStringToRgbaColor,
inBrowser,
inClientSide,
isHSLColor,
isIPV4Address,
isLegacyFrontendApiKey,
isPublishableKey,
isRGBColor,
isRetinaDisplay,
isTransparent,
isValidHexString,
isValidHslaString,
isValidRgbaString,
isomorphicAtob,
noop,
normalizeDate,
parsePublishableKey,
parseSearchParams,
readJSONFile,
runWithExponentialBackOff,
snakeToCamel,
stringToHslaColor,
stringToSameTypeColor,
titleize,
toSentence,
useClerkInstanceContext,
useClientContext,
useOrganization,
useOrganizationContext,
useOrganizationList,
useOrganizations,
useSessionContext,
useUserContext
};
/*! *****************************************************************************

@@ -3,0 +1099,0 @@ Copyright (c) Microsoft Corporation.

@@ -1,2 +0,38 @@

import{E as t,a as m,b as e}from"../chunk-CX34SAMA.js";var o={};m(o,{noop:()=>t,render:()=>n,userEvent:()=>p});var r={};m(r,{noop:()=>t,render:()=>n,userEvent:()=>p});import"@testing-library/jest-dom/extend-expect";import{render as a}from"@testing-library/react";e(r,u);import*as u from"@testing-library/react";import{default as p}from"@testing-library/user-event";var n=(f,s)=>a(f,s);e(o,r);export{t as noop,n as render,p as userEvent};
import {
__export,
__reExport,
noop
} from "../chunk-S6EBXHRO.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

@@ -1,3 +0,1807 @@

"use strict";var zt=Object.create;var ae=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var Mt=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty;var Pt=(e,r)=>{for(var t in r)ae(e,t,{get:r[t],enumerable:!0})},qe=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Lt(r))!Dt.call(e,a)&&a!==t&&ae(e,a,{get:()=>r[a],enumerable:!(n=kt(r,a))||n.enumerable});return e};var At=(e,r,t)=>(t=e!=null?zt(Mt(e)):{},qe(r||!e||!e.__esModule?ae(t,"default",{value:e,enumerable:!0}):t,e)),_t=e=>qe(ae({},"__esModule",{value:!0}),e);var un={};Pt(un,{ClerkInstanceContext:()=>Ft,ClientContext:()=>$t,LocalStorageBroadcastChannel:()=>$e,OrganizationContext:()=>Kt,Poller:()=>en,SessionContext:()=>Nt,UserContext:()=>Vt,addYears:()=>Wr,assertContextExists:()=>Ze,buildErrorThrower:()=>Ut,buildPublishableKey:()=>Vr,camelToSnake:()=>Ke,colorToSameTypeString:()=>vt,createContextAndHook:()=>$,createCookieHandler:()=>Pr,createWorkerTimers:()=>ve,dateTo12HourTime:()=>Ar,deepCamelToSnake:()=>Jr,deepSnakeToCamel:()=>qr,differenceInCalendarDays:()=>xt,extension:()=>Gr,formatRelative:()=>_r,hasAlpha:()=>Or,hexStringToRgbaColor:()=>ht,inBrowser:()=>br,inClientSide:()=>tn,isHSLColor:()=>Ue,isIPV4Address:()=>Xr,isLegacyFrontendApiKey:()=>Hr,isPublishableKey:()=>Rt,isRGBColor:()=>We,isRetinaDisplay:()=>Nr,isTransparent:()=>de,isValidHexString:()=>re,isValidHslaString:()=>ce,isValidRgbaString:()=>le,isomorphicAtob:()=>ge,noop:()=>He,normalizeDate:()=>me,parsePublishableKey:()=>$r,parseSearchParams:()=>rn,readJSONFile:()=>Ur,runWithExponentialBackOff:()=>sn,snakeToCamel:()=>Ne,stringToHslaColor:()=>Sr,stringToSameTypeColor:()=>Ir,titleize:()=>Yr,toSentence:()=>hr,useClerkInstanceContext:()=>H,useClientContext:()=>Ht,useOrganization:()=>fr,useOrganizationContext:()=>we,useOrganizationList:()=>mr,useOrganizations:()=>vr,useSessionContext:()=>Oe,useUserContext:()=>Re});module.exports=_t(un);var Wt=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}})",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 Ut({packageName:e,customMessages:r}){let t=e,n={...Wt,...r};function a(i,o){if(!o)return`${t}: ${i}`;let u=i,f=i.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);for(let s of f){let c=(o[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(a(n.InvalidPublishableKeyErrorMessage,i))},throwInvalidFrontendApiError(i){throw new Error(a(n.InvalidFrontendApiErrorMessage,i))},throwMissingPublishableKeyError(){throw new Error(a(n.MissingPublishableKeyErrorMessage))}}}var oe=At(require("react"));function Ze(e,r){if(!e)throw typeof r=="string"?new Error(r):new Error(`${r.displayName} not found`)}var $=(e,r)=>{let{assertCtxFn:t=Ze}=r||{},n=oe.default.createContext(void 0);return n.displayName=e,[n,()=>{let o=oe.default.useContext(n);return t(o,`${e} not found`),o.value},()=>{let o=oe.default.useContext(n);return o?o.value:{}}]};var[Ft,H]=$("ClerkInstanceContext"),[Vt,Re]=$("UserContext"),[$t,Ht]=$("ClientContext"),[Nt,Oe]=$("SessionContext"),[Kt,we]=$("OrganizationContext");var p=require("react");function rt(e,r,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(c){try{s(n.next(c))}catch(m){o(m)}}function f(c){try{s(n.throw(c))}catch(m){o(m)}}function s(c){c.done?i(c.value):a(c.value).then(u,f)}s((n=n.apply(e,r||[])).next())})}function nt(e,r){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,a,i,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;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,a&&(i=s[0]&2?a.return:s[0]?a.throw||((i=a.return)&&i.call(a),0):a.next)&&!(i=i.call(a,s[1])).done)return i;switch(a=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++,a=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],a=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var k=function(){},b=k(),Z=Object,y=function(e){return e===b},_=function(e){return typeof e=="function"},D=function(e,r){return Z.assign({},e,r)},De="undefined",Pe=function(){return typeof window!=De},Bt=function(){return typeof document!=De},Gt=function(){return Pe()&&typeof window.requestAnimationFrame!=De},se=new WeakMap,jt=0,te=function(e){var r=typeof e,t=e&&e.constructor,n=t==Date,a,i;if(Z(e)===e&&!n&&t!=RegExp){if(a=se.get(e),a)return a;if(a=++jt+"~",se.set(e,a),t==Array){for(a="@",i=0;i<e.length;i++)a+=te(e[i])+",";se.set(e,a)}if(t==Z){a="#";for(var o=Z.keys(e).sort();!y(i=o.pop());)y(e[i])||(a+=i+":"+te(e[i])+",");se.set(e,a)}}else a=n?e.toJSON():r=="symbol"?e.toString():r=="string"?JSON.stringify(e):""+e;return a},Ie=!0,Xt=function(){return Ie},it=Pe(),Ae=Bt(),ze=it&&window.addEventListener?window.addEventListener.bind(window):k,Yt=Ae?document.addEventListener.bind(document):k,ke=it&&window.removeEventListener?window.removeEventListener.bind(window):k,Jt=Ae?document.removeEventListener.bind(document):k,qt=function(){var e=Ae&&document.visibilityState;return y(e)||e!=="hidden"},Zt=function(e){return Yt("visibilitychange",e),ze("focus",e),function(){Jt("visibilitychange",e),ke("focus",e)}},Qt=function(e){var r=function(){Ie=!0,e()},t=function(){Ie=!1};return ze("online",r),ze("offline",t),function(){ke("online",r),ke("offline",t)}},er={isOnline:Xt,isVisible:qt},tr={initFocus:Zt,initReconnect:Qt},ue=!Pe()||"Deno"in window,rr=function(e){return Gt()?window.requestAnimationFrame(e):setTimeout(e,1)},Q=ue?p.useEffect:p.useLayoutEffect,Ee=typeof navigator<"u"&&navigator.connection,Qe=!ue&&Ee&&(["slow-2g","2g"].includes(Ee.effectiveType)||Ee.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)?te(e):"";var t=e?"$swr$"+e:"";return[e,r,t]},N=new WeakMap,ot=0,st=1,ut=2,ee=function(e,r,t,n,a,i,o){o===void 0&&(o=!0);var u=N.get(e),f=u[0],s=u[1],c=u[3],m=f[r],l=s[r];if(o&&l)for(var v=0;v<l.length;++v)l[v](t,n,a);return i&&(delete c[r],m&&m[0])?m[0](ut).then(function(){return e.get(r)}):e.get(r)},nr=0,Le=function(){return++nr},lt=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return rt(void 0,void 0,void 0,function(){var t,n,a,i,o,u,f,s,c,m,l,v,x,T,g,d,G,W,L,S,U;return nt(this,function(P){switch(P.label){case 0:if(t=e[0],n=e[1],a=e[2],i=e[3],o=typeof i=="boolean"?{revalidate:i}:i||{},u=y(o.populateCache)?!0:o.populateCache,f=o.revalidate!==!1,s=o.rollbackOnError!==!1,c=o.optimisticData,m=at(n),l=m[0],v=m[2],!l)return[2];if(x=N.get(t),T=x[2],e.length<3)return[2,ee(t,l,t.get(l),b,b,f,!0)];if(g=a,G=Le(),T[l]=[G,0],W=!y(c),L=t.get(l),W&&(S=_(c)?c(L):c,t.set(l,S),ee(t,l,S)),_(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=P.sent(),G!==T[l][0]){if(d)throw d;return[2,g]}else d&&W&&s&&(u=!0,g=L,t.set(l,L));P.label=2;case 2:return u&&(d||(_(u)&&(g=u(g,L)),t.set(l,g)),t.set(v,D(t.get(v),{error:d}))),T[l][1]=Le(),[4,ee(t,l,g,d,b,f,!!u)];case 3:if(U=P.sent(),d)throw d;return[2,u?U:g]}})})},et=function(e,r){for(var t in e)e[t][0]&&e[t][0](r)},ct=function(e,r){if(!N.has(e)){var t=D(tr,r),n={},a=lt.bind(b,e),i=k;if(N.set(e,[n,{},{},{},a]),!ue){var o=t.initFocus(setTimeout.bind(b,et.bind(b,n,ot))),u=t.initReconnect(setTimeout.bind(b,et.bind(b,n,st)));i=function(){o&&o(),u&&u(),N.delete(e)}}return[e,a,i]}return[e,N.get(e)[4]]},ir=function(e,r,t,n,a){var i=t.errorRetryCount,o=a.retryCount,u=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!y(i)&&o>i||setTimeout(n,u,a)},dt=ct(new Map),ft=dt[0],ar=dt[1],pt=D({onLoadingSlow:k,onSuccess:k,onError:k,onErrorRetry:ir,onDiscarded:k,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Qe?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Qe?5e3:3e3,compare:function(e,r){return te(e)==te(r)},isPaused:function(){return!1},cache:ft,mutate:ar,fallback:{}},er),mt=function(e,r){var t=D(e,r);if(r){var n=e.use,a=e.fallback,i=r.use,o=r.fallback;n&&i&&(t.use=n.concat(i)),a&&o&&(t.fallback=D(a,o))}return t},Me=(0,p.createContext)({}),or=function(e){var r=e.value,t=mt((0,p.useContext)(Me),r),n=r&&r.provider,a=(0,p.useState)(function(){return n?ct(n(t.cache||ft),r):b})[0];return a&&(t.cache=a[0],t.mutate=a[1]),Q(function(){return a?a[2]:b},[]),(0,p.createElement)(Me.Provider,D(e,{value:t}))},sr=function(e,r){var t=(0,p.useState)({})[1],n=(0,p.useRef)(e),a=(0,p.useRef)({data:!1,error:!1,isValidating:!1}),i=(0,p.useCallback)(function(o){var u=!1,f=n.current;for(var s in o){var c=s;f[c]!==o[c]&&(f[c]=o[c],a.current[c]&&(u=!0))}u&&!r.current&&t({})},[]);return Q(function(){n.current=e}),[n,a.current,i]},ur=function(e){return _(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},lr=function(){return D(pt,(0,p.useContext)(Me))},cr=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var a=lr(),i=ur(t),o=i[0],u=i[1],f=i[2],s=mt(a,f),c=e,m=s.use;if(m)for(var l=m.length;l-- >0;)c=m[l](c);return c(o,u||s.fetcher,s)}},tt=function(e,r,t){var n=r[e]||(r[e]=[]);return n.push(t),function(){var a=n.indexOf(t);a>=0&&(n[a]=n[n.length-1],n.pop())}},Se={dedupe:!0},dr=function(e,r,t){var n=t.cache,a=t.compare,i=t.fallbackData,o=t.suspense,u=t.revalidateOnMount,f=t.refreshInterval,s=t.refreshWhenHidden,c=t.refreshWhenOffline,m=N.get(n),l=m[0],v=m[1],x=m[2],T=m[3],g=at(e),d=g[0],G=g[1],W=g[2],L=(0,p.useRef)(!1),S=(0,p.useRef)(!1),U=(0,p.useRef)(d),P=(0,p.useRef)(r),F=(0,p.useRef)(t),h=function(){return F.current},he=function(){return h().isVisible()&&h().isOnline()},ne=function(w){return n.set(W,D(n.get(W),w))},Ge=n.get(d),Et=y(i)?t.fallback[d]:i,M=y(Ge)?Et:Ge,je=n.get(W)||{},j=je.error,Xe=!L.current,Ye=function(){return Xe&&!y(u)?u:h().isPaused()?!1:o?y(M)?!1:t.revalidateIfStale:y(M)||t.revalidateIfStale},St=function(){return!d||!r?!1:je.isValidating?!0:Xe&&Ye()},be=St(),Ce=sr({data:M,error:j,isValidating:be},S),K=Ce[0],ye=Ce[1],ie=Ce[2],V=(0,p.useCallback)(function(w){return rt(void 0,void 0,void 0,function(){var R,O,E,X,Y,I,C,A,z,xe,J,B,Te;return nt(this,function(q){switch(q.label){case 0:if(R=P.current,!d||!R||S.current||h().isPaused())return[2,!1];X=!0,Y=w||{},I=!T[d]||!Y.dedupe,C=function(){return!S.current&&d===U.current&&L.current},A=function(){var Je=T[d];Je&&Je[1]===E&&delete T[d]},z={isValidating:!1},xe=function(){ne({isValidating:!1}),C()&&ie(z)},ne({isValidating:!0}),ie({isValidating:!0}),q.label=1;case 1:return q.trys.push([1,3,,4]),I&&(ee(n,d,K.current.data,K.current.error,!0),t.loadingTimeout&&!n.get(d)&&setTimeout(function(){X&&C()&&h().onLoadingSlow(d,t)},t.loadingTimeout),T[d]=[R.apply(void 0,G),Le()]),Te=T[d],O=Te[0],E=Te[1],[4,O];case 2:return O=q.sent(),I&&setTimeout(A,t.dedupingInterval),!T[d]||T[d][1]!==E?(I&&C()&&h().onDiscarded(d),[2,!1]):(ne({error:b}),z.error=b,J=x[d],!y(J)&&(E<=J[0]||E<=J[1]||J[1]===0)?(xe(),I&&C()&&h().onDiscarded(d),[2,!1]):(a(K.current.data,O)?z.data=K.current.data:z.data=O,a(n.get(d),O)||n.set(d,O),I&&C()&&h().onSuccess(O,d,t),[3,4]));case 3:return B=q.sent(),A(),h().isPaused()||(ne({error:B}),z.error=B,I&&C()&&(h().onError(B,d,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||_(t.shouldRetryOnError)&&t.shouldRetryOnError(B))&&he()&&h().onErrorRetry(B,d,t,V,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return X=!1,xe(),C()&&I&&ee(n,d,z.data,z.error,!1),[2,!0]}})})},[d]),It=(0,p.useCallback)(lt.bind(b,n,function(){return U.current}),[]);if(Q(function(){P.current=r,F.current=t}),Q(function(){if(!!d){var w=d!==U.current,R=V.bind(b,Se),O=function(C,A,z){ie(D({error:A,isValidating:z},a(K.current.data,C)?b:{data:C}))},E=0,X=function(C){if(C==ot){var A=Date.now();h().revalidateOnFocus&&A>E&&he()&&(E=A+h().focusThrottleInterval,R())}else if(C==st)h().revalidateOnReconnect&&he()&&R();else if(C==ut)return V()},Y=tt(d,v,O),I=tt(d,l,X);return S.current=!1,U.current=d,L.current=!0,w&&ie({data:M,error:j,isValidating:be}),Ye()&&(y(M)||ue?R():rr(R)),function(){S.current=!0,Y(),I()}}},[d,V]),Q(function(){var w;function R(){var E=_(f)?f(M):f;E&&w!==-1&&(w=setTimeout(O,E))}function O(){!K.current.error&&(s||h().isVisible())&&(c||h().isOnline())?V(Se).then(R):R()}return R(),function(){w&&(clearTimeout(w),w=-1)}},[f,s,c,V]),(0,p.useDebugValue)(M),o&&y(M)&&d)throw P.current=r,F.current=t,S.current=!1,y(j)?V(Se):j;return{mutate:It,get data(){return ye.data=!0,M},get error(){return ye.error=!0,j},get isValidating(){return ye.isValidating=!0,be}}},vn=Z.defineProperty(or,"default",{value:pt});var _e=cr(dr);var fr=e=>{let{invitationList:r,membershipList:t}=e||{},{organization:n,lastOrganizationMember:a,lastOrganizationInvitation:i}=we(),o=Oe(),u=H(),f=u.loaded&&o&&n,s=u.loaded?()=>u.organization?.getPendingInvitations(r):()=>[],c=u.loaded?()=>u.organization?.getMemberships(t):()=>[],{data:m,isValidating:l,mutate:v}=_e(f&&r?gt("invites",n,i,r):null,s),{data:x,isValidating:T,mutate:g}=_e(f&&t?gt("memberships",n,a,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:x,membership:pr(o.user.organizationMemberships,n.id),invitationList:m,unstable__mutate:()=>{g(),v()}}};function pr(e,r){return e.find(t=>t.organization.id===r)}function gt(e,r,t,n){return[e,r.id,t?.id,t?.updatedAt,n.offset,n.limit].filter(Boolean).join("-")}var mr=()=>{let e=H(),r=Re();return!e.loaded||!r?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:gr(r.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function gr(e){return e.map(r=>({membership:r,organization:r.organization}))}var vr=()=>{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 hr=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 br(){return typeof window<"u"}var Cr=/^#?([A-F0-9]{6}|[A-F0-9]{3})$/i,yr=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i,xr=/^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i,Tr=/^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i,Rr=/^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i,re=e=>!!e.match(Cr),le=e=>!!(e.match(yr)||e.match(xr)),ce=e=>!!e.match(Tr)||!!e.match(Rr),We=e=>typeof e!="string"&&"r"in e,Ue=e=>typeof e!="string"&&"h"in e,de=e=>e==="transparent",Or=e=>typeof e!="string"&&e.a!=null&&e.a<1;var wr=/[hsla()]/g,Er=/[rgba()]/g,Sr=e=>e==="transparent"?{h:0,s:0,l:0,a:0}:re(e)?Lr(e):ce(e)?yt(e):le(e)?bt(e):null,Ir=e=>(e=e.trim(),re(e)?e.startsWith("#")?e:`#${e}`:le(e)?Ct(e):ce(e)?yt(e):de(e)?e:""),vt=e=>typeof e=="string"&&(re(e)||de(e))?e:We(e)?zr(e):Ue(e)?kr(e):"",ht=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}},zr=e=>{let{a:r,b:t,g:n,r:a}=e;return e.a===0?"transparent":e.a!=null?`rgba(${a},${n},${t},${r})`:`rgb(${a},${n},${t})`},kr=e=>{let{h:r,s:t,l:n,a}=e,i=Math.round(t*100),o=Math.round(n*100);return e.a===0?"transparent":e.a!=null?`hsla(${r},${i}%,${o}%,${a})`:`hsl(${r},${i}%,${o}%)`},Lr=e=>{let r=vt(ht(e));return bt(r)},bt=e=>{let r=Ct(e),t=r.r/255,n=r.g/255,a=r.b/255,i=Math.max(t,n,a),o=Math.min(t,n,a),u,f,s=(i+o)/2;if(i==o)u=f=0;else{let l=i-o;switch(f=s>=.5?l/(2-(i+o)):l/(i+o),i){case t:u=(n-a)/l*60;break;case n:u=((a-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},Ct=e=>{let[r,t,n,a]=e.replace(Er,"").split(",").map(i=>Number.parseFloat(i));return{r,g:t,b:n,a}},yt=e=>{let[r,t,n,a]=e.replace(wr,"").split(",").map(i=>Number.parseFloat(i));return{h:r,s:t/100,l:n/100,a}};function fe(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 Mr={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 Fe(e,r){function t(a,i,o){if(!(typeof document>"u")){o=fe({},r,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),a=encodeURIComponent(a).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in o)!o[f]||(u+="; "+f,o[f]!==!0&&(u+="="+o[f].split(";")[0]));return document.cookie=a+"="+e.write(i,a)+u}}function n(a){if(!(typeof document>"u"||arguments.length&&!a)){for(var i=document.cookie?document.cookie.split("; "):[],o={},u=0;u<i.length;u++){var f=i[u].split("="),s=f.slice(1).join("=");try{var c=decodeURIComponent(f[0]);if(o[c]=e.read(s,c),a===c)break}catch{}}return a?o[a]:o}}return Object.create({set:t,get:n,remove:function(a,i){t(a,"",fe({},i,{expires:-1}))},withAttributes:function(a){return Fe(this.converter,fe({},this.attributes,a))},withConverter:function(a){return Fe(fe({},this.converter,a),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}var Dr=Fe(Mr,{path:"/"}),pe=Dr;function Pr(e){return{get(){return pe.get(e)},set(r,t={}){return pe.set(e,r,t)},remove(r){pe.remove(e,r)}}}function Ar(e){return e?e.toLocaleString("en-US",{hour:"2-digit",minute:"numeric",hour12:!0}):""}function xt(e,r,{absolute:t=!0}={}){if(!e||!r)return 0;let n=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),a=Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()),i=Math.floor((a-n)/864e5);return t?Math.abs(i):i}function me(e){try{return new Date(e||new Date)}catch{return new Date}}function _r(e){let{date:r,relativeTo:t}=e;if(!r||!t)return null;let n=me(r),a=me(t),i=xt(a,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 Wr(e,r){let t=me(e);return t.setFullYear(t.getFullYear()+r),t}function Ur(e){return new Promise((r,t)=>{let n=new FileReader;n.addEventListener("load",function(){let a=JSON.parse(n.result);r(a)}),n.addEventListener("error",t),n.readAsText(e)})}var ge=e=>typeof atob<"u"&&typeof atob=="function"?atob(e):typeof Buffer<"u"?new Buffer(e,"base64").toString():e;var Ve="pk_live_",Tt="pk_test_",Fr=/^(([a-z]+)-){2}([0-9]{1,2})\.clerk\.accounts([a-z.]*)(dev|com)$/i;function Vr(e){return`${Fr.test(e)?Tt:Ve}${btoa(`${e}$`)}`}function $r(e){if(e=e||"",!Rt(e))return null;let r=e.startsWith(Ve)?"production":"development",t=ge(e.split("_")[2]);return t.endsWith("$")?(t=t.slice(0,-1),{instanceType:r,frontendApi:t}):null}function Rt(e){e=e||"";let r=e.startsWith(Ve)||e.startsWith(Tt),t=ge(e.split("_")[2]||"").endsWith("$");return r&&t}function Hr(e){return e=e||"",e.startsWith("clerk.")}function Nr(){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 Kr="__lsbc__",$e=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||""),a=new MessageEvent(this.prefixEventName("message"),{data:n});this.eventTarget.dispatchEvent(a)}catch{}};window.addEventListener("storage",r)};this.channelKey=Kr+r,this.setupLocalStorageListener()}prefixEventName(r){return this.channelKey+r}};var Br=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"}),Gr=e=>Br[e];var He=(...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 Xr(e){return jr.test(e||"")}function Yr(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 Ot=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},a=Object.keys(n);for(let i of a){let o=e(i.toString());o!==i&&(n[o]=n[i],delete n[i]),typeof n[o]=="object"&&(n[o]=r(n[o]))}return n};return r},Jr=Ot(Ke),qr=Ot(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 wt=(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}},Qr=()=>{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:He}},ve=()=>{let e=0,r=()=>e++,t=new Map,n=(l,v)=>l?.postMessage(v),a=l=>{t.get(l.data.id)?.()},i=wt(Be,{name:"clerk-timers"});if(i?.addEventListener("message",a),!i)return Qr();let o=()=>{i||(i=wt(Be,{name:"clerk-timers"}),i?.addEventListener("message",a))};return{setTimeout:(l,v)=>{o();let x=r();return t.set(x,l),n(i,{type:"setTimeout",id:x,ms:v}),x},setInterval:(l,v)=>{o();let x=r();return t.set(x,l),n(i,{type:"setInterval",id:x,ms:v}),x},clearTimeout:l=>{o(),t.delete(l),n(i,{type:"clearTimeout",id:l})},clearInterval:l=>{o(),t.delete(l),n(i,{type:"clearInterval",id:l})},cleanup:()=>{i&&(i.terminate(),i=null,t.clear())}}};function en({delayInMs:e}={delayInMs:1e3}){let r=ve(),t,n=!1,a=()=>{t&&(r.clearTimeout(t),r.cleanup()),n=!0},i=async o=>{n=!1,await o(a),!n&&(t=r.setTimeout(()=>{i(o)},e))};return{run:i,stop:a}}var tn=()=>typeof window<"u";function rn(e=""){return e.startsWith("?")&&(e=e.slice(1)),new URLSearchParams(e)}var nn={maxRetries:10,firstDelay:125,timeMultiple:2,shouldRetry:()=>!0},an=async e=>new Promise(r=>setTimeout(r,e)),on=e=>{let r=0,t=()=>{let n=e.firstDelay,a=e.timeMultiple;return n*Math.pow(a,r)};return async()=>{await an(t()),r++}},sn=async(e,r={})=>{let t=0,{maxRetries:n,shouldRetry:a,firstDelay:i,timeMultiple:o}={...nn,...r},u=()=>t===n,f=on({firstDelay:i,timeMultiple:o});for(;!u();)try{return await e()}catch(s){if(t++,!a(s,t)||u())throw s;await f()}throw new Error("Something went wrong")};0&&(module.exports={ClerkInstanceContext,ClientContext,LocalStorageBroadcastChannel,OrganizationContext,Poller,SessionContext,UserContext,addYears,assertContextExists,buildErrorThrower,buildPublishableKey,camelToSnake,colorToSameTypeString,createContextAndHook,createCookieHandler,createWorkerTimers,dateTo12HourTime,deepCamelToSnake,deepSnakeToCamel,differenceInCalendarDays,extension,formatRelative,hasAlpha,hexStringToRgbaColor,inBrowser,inClientSide,isHSLColor,isIPV4Address,isLegacyFrontendApiKey,isPublishableKey,isRGBColor,isRetinaDisplay,isTransparent,isValidHexString,isValidHslaString,isValidRgbaString,isomorphicAtob,noop,normalizeDate,parsePublishableKey,parseSearchParams,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,
createWorkerTimers: () => createWorkerTimers,
dateTo12HourTime: () => dateTo12HourTime,
deepCamelToSnake: () => deepCamelToSnake,
deepSnakeToCamel: () => deepSnakeToCamel,
differenceInCalendarDays: () => differenceInCalendarDays,
extension: () => extension,
formatRelative: () => formatRelative,
hasAlpha: () => hasAlpha,
hexStringToRgbaColor: () => hexStringToRgbaColor,
inBrowser: () => inBrowser,
inClientSide: () => inClientSide,
isHSLColor: () => isHSLColor,
isIPV4Address: () => isIPV4Address,
isLegacyFrontendApiKey: () => isLegacyFrontendApiKey,
isPublishableKey: () => isPublishableKey,
isRGBColor: () => isRGBColor,
isRetinaDisplay: () => isRetinaDisplay,
isTransparent: () => isTransparent,
isValidHexString: () => isValidHexString,
isValidHslaString: () => isValidHslaString,
isValidRgbaString: () => isValidRgbaString,
isomorphicAtob: () => isomorphicAtob,
noop: () => noop2,
normalizeDate: () => normalizeDate,
parsePublishableKey: () => parsePublishableKey,
parseSearchParams: () => parseSearchParams,
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}})`,
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));
},
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 ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.getPendingInvitations(invitationListParams);
};
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.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 == null ? void 0 : resource.id, resource == null ? void 0 : 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";
}
// 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 == null ? void 0 : w.postMessage(p);
const handleMessage = (e) => {
var _a2;
(_a2 = callbacks.get(e.data.id)) == null ? void 0 : _a2();
};
let worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" });
worker == null ? void 0 : worker.addEventListener("message", handleMessage);
if (!worker) {
return fallbackTimers();
}
const init2 = () => {
if (!worker) {
worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" });
worker == null ? void 0 : 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/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");
};
// 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,
createWorkerTimers,
dateTo12HourTime,
deepCamelToSnake,
deepSnakeToCamel,
differenceInCalendarDays,
extension,
formatRelative,
hasAlpha,
hexStringToRgbaColor,
inBrowser,
inClientSide,
isHSLColor,
isIPV4Address,
isLegacyFrontendApiKey,
isPublishableKey,
isRGBColor,
isRetinaDisplay,
isTransparent,
isValidHexString,
isValidHslaString,
isValidRgbaString,
isomorphicAtob,
noop,
normalizeDate,
parsePublishableKey,
parseSearchParams,
readJSONFile,
runWithExponentialBackOff,
snakeToCamel,
stringToHslaColor,
stringToSameTypeColor,
titleize,
toSentence,
useClerkInstanceContext,
useClientContext,
useOrganization,
useOrganizationContext,
useOrganizationList,
useOrganizations,
useSessionContext,
useUserContext
});
/*! *****************************************************************************

@@ -4,0 +1808,0 @@ Copyright (c) Microsoft Corporation.

@@ -1,3 +0,215 @@

"use strict";var D=Object.create;var m=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var r in t)m(e,r,{get:t[r],enumerable:!0})},u=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of k(t))!P.call(e,n)&&n!==r&&m(e,n,{get:()=>t[n],enumerable:!(s=w(t,n))||s.enumerable});return e},l=(e,t,r)=>(u(e,t,"default"),r&&u(r,t,"default")),_=(e,t,r)=>(r=e!=null?D(I(e)):{},u(t||!e||!e.__esModule?m(r,"default",{value:e,enumerable:!0}):r,e)),L=e=>u(m({},"__esModule",{value:!0}),e);var g={};C(g,{noop:()=>d,render:()=>S,userEvent:()=>b.default});module.exports=L(g);var a={};C(a,{noop:()=>d,render:()=>S,userEvent:()=>b.default});var Ye=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 s in r)e[s]=r[s]}return e}var M={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,i,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(i,n)+c}}function s(n){if(!(typeof document>"u"||arguments.length&&!n)){for(var i=document.cookie?document.cookie.split("; "):[],o={},c=0;c<i.length;c++){var p=i[c].split("="),E=p.slice(1).join("=");try{var h=decodeURIComponent(p[0]);if(o[h]=e.read(E,h),n===h)break}catch{}}return n?o[n]:o}}return Object.create({set:r,get:s,remove:function(n,i){r(n,"",f({},i,{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(M,{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 d=(...e)=>{};function y(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(i=>typeof i=="object"||Array.isArray(i)?t(i):i);let s={...r},n=Object.keys(s);for(let i of n){let o=e(i.toString());o!==i&&(s[o]=s[i],delete s[i]),typeof s[o]=="object"&&(s[o]=t(s[o]))}return s};return t},ge=v(T),he=v(y);l(a,require("@testing-library/react"));var b=_(require("@testing-library/user-event")),S=(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

6

package.json
{
"name": "@clerk/shared",
"version": "0.9.2",
"version": "0.9.3-staging.1",
"description": "Internal package utils used by the Clerk SDKs",

@@ -21,3 +21,3 @@ "types": "./dist/types/index.d.ts",

"devDependencies": {
"@clerk/types": "^3.24.1",
"@clerk/types": "^3.24.2-staging.0",
"@testing-library/dom": "^8.19.0",

@@ -41,3 +41,3 @@ "@testing-library/jest-dom": "^5.16.5",

"license": "ISC",
"gitHead": "67f4db21c10cf0c6527ee5c02d3aca90b4ccee70",
"gitHead": "ba69052c93676a2de21d0edfeaa8c2b5ebfaeb18",
"publishConfig": {

@@ -44,0 +44,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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc