Socket
Socket
Sign inDemoInstall

@clerk/shared

Package Overview
Dependencies
Maintainers
9
Versions
1549
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.5.0 to 0.5.1-staging.0

dist/chunk-HRYCZLZ4.mjs

1573

dist/index.js

@@ -1,2 +0,1573 @@

"use strict";var Rt=Object.create;var ae=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var Lt=(e,n)=>{for(var t in n)ae(e,t,{get:n[t],enumerable:!0})},Be=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of St(n))!Et.call(e,i)&&i!==t&&ae(e,i,{get:()=>n[i],enumerable:!(r=yt(n,i))||r.enumerable});return e};var wt=(e,n,t)=>(t=e!=null?Rt(zt(e)):{},Be(n||!e||!e.__esModule?ae(t,"default",{value:e,enumerable:!0}):t,e)),Tt=e=>Be(ae({},"__esModule",{value:!0}),e);var Gn={};Lt(Gn,{ClerkInstanceContext:()=>dn,ClientContext:()=>gn,LocalStorageBroadcastChannel:()=>Se,OrganizationContext:()=>hn,Poller:()=>cn,SessionContext:()=>vn,UserContext:()=>pn,addYears:()=>Jt,assertContextExists:()=>tt,camelToSnake:()=>Ee,colorToSameTypeString:()=>Xe,createContextAndHook:()=>H,createCookieHandler:()=>Xt,dateTo12HourTime:()=>Ze,deepCamelToSnake:()=>sn,deepSnakeToCamel:()=>un,differenceInCalendarDays:()=>Qe,extension:()=>tn,formatRelative:()=>Yt,hasAlpha:()=>Vt,hexStringToRgbaColor:()=>Ke,inBrowser:()=>Dt,inClientSide:()=>ln,isHSLColor:()=>Oe,isIPV4Address:()=>an,isRGBColor:()=>be,isRetinaDisplay:()=>Zt,isTransparent:()=>ue,isValidHexString:()=>Z,isValidHslaString:()=>se,isValidRgbaString:()=>oe,noop:()=>nn,parseSearchParams:()=>fn,readJSONFile:()=>qt,snakeToCamel:()=>ze,stringToHslaColor:()=>Ht,stringToSameTypeColor:()=>$t,titleize:()=>on,toSentence:()=>It,useClerkInstanceContext:()=>$,useClientContext:()=>mn,useOrganization:()=>kn,useOrganizationContext:()=>Te,useOrganizationList:()=>$n,useOrganizations:()=>Wn,useSessionContext:()=>we,useUserContext:()=>Le});module.exports=Tt(Gn);var It=e=>{if(e.length==0)return"";if(e.length==1)return e[0];let n=e.slice(0,-1).join(", ");return n+=`, or ${e.slice(-1)}`,n};function Dt(){return typeof window<"u"}var Mt=/^#?([A-F0-9]{6}|[A-F0-9]{3})$/i,At=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i,Pt=/^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i,_t=/^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i,Ut=/^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i,Z=e=>!!e.match(Mt),oe=e=>!!(e.match(At)||e.match(Pt)),se=e=>!!e.match(_t)||!!e.match(Ut),be=e=>typeof e!="string"&&"r"in e,Oe=e=>typeof e!="string"&&"h"in e,ue=e=>e==="transparent",Vt=e=>typeof e!="string"&&e.a!=null&&e.a<1;var Ft=/[hsla()]/g,kt=/[rgba()]/g,Ht=e=>e==="transparent"?{h:0,s:0,l:0,a:0}:Z(e)?Gt(e):se(e)?qe(e):oe(e)?Ye(e):null,$t=e=>(e=e.trim(),Z(e)?e.startsWith("#")?e:`#${e}`:oe(e)?Je(e):se(e)?qe(e):ue(e)?e:""),Xe=e=>typeof e=="string"&&(Z(e)||ue(e))?e:be(e)?Nt(e):Oe(e)?Wt(e):"",Ke=e=>{e=e.replace("#","");let n=parseInt(e.substring(0,2),16),t=parseInt(e.substring(2,4),16),r=parseInt(e.substring(4,6),16);return{r:n,g:t,b:r}},Nt=e=>{let{a:n,b:t,g:r,r:i}=e;return e.a===0?"transparent":e.a!=null?`rgba(${i},${r},${t},${n})`:`rgb(${i},${r},${t})`},Wt=e=>{let{h:n,s:t,l:r,a:i}=e,a=Math.round(t*100),o=Math.round(r*100);return e.a===0?"transparent":e.a!=null?`hsla(${n},${a}%,${o}%,${i})`:`hsl(${n},${a}%,${o}%)`},Gt=e=>{let n=Xe(Ke(e));return Ye(n)},Ye=e=>{let n=Je(e),t=n.r/255,r=n.g/255,i=n.b/255,a=Math.max(t,r,i),o=Math.min(t,r,i),u,f,s=(a+o)/2;if(a==o)u=f=0;else{let d=a-o;switch(f=s>=.5?d/(2-(a+o)):d/(a+o),a){case t:u=(r-i)/d*60;break;case r:u=((i-t)/d+2)*60;break;default:u=((t-r)/d+4)*60;break}}let l={h:Math.round(u),s:f,l:s},g=n.a;return g!=null&&(l.a=g),l},Je=e=>{let[n,t,r,i]=e.replace(kt,"").split(",").map(a=>Number.parseFloat(a));return{r:n,g:t,b:r,a:i}},qe=e=>{let[n,t,r,i]=e.replace(Ft,"").split(",").map(a=>Number.parseFloat(a));return{h:n,s:t/100,l:r/100,a:i}};function ce(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)e[r]=t[r]}return e}var jt={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 Re(e,n){function t(i,a,o){if(!(typeof document>"u")){o=ce({},n,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).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=i+"="+e.write(a,i)+u}}function r(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var a=document.cookie?document.cookie.split("; "):[],o={},u=0;u<a.length;u++){var f=a[u].split("="),s=f.slice(1).join("=");try{var l=decodeURIComponent(f[0]);if(o[l]=e.read(s,l),i===l)break}catch{}}return i?o[i]:o}}return Object.create({set:t,get:r,remove:function(i,a){t(i,"",ce({},a,{expires:-1}))},withAttributes:function(i){return Re(this.converter,ce({},this.attributes,i))},withConverter:function(i){return Re(ce({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(e)}})}var Bt=Re(jt,{path:"/"}),le=Bt;function Xt(e){return{get(){return le.get(e)},set(n,t={}){return le.set(e,n,t)},remove(n){le.remove(e,n)}}}var Kt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Ze(e){return e?e.toLocaleString("en-US",{hour:"2-digit",minute:"numeric",hour12:!0}):""}function Qe(e,n,{absolute:t=!0}={}){if(!e||!n)return 0;let r=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),i=Date.UTC(n.getFullYear(),n.getMonth(),n.getDate()),a=Math.floor((i-r)/864e5);return t?Math.abs(a):a}function ye(e){try{return new Date(e||new Date)}catch{return new Date}}function Yt(e,n){if(!e||!n)return"";let t=ye(e),r=ye(n),i=Qe(r,t,{absolute:!1}),a=Ze(t),o=Kt[t.getDay()];return i<-6?t.toLocaleDateString():i<-1?`last ${o} at ${a}`:i===-1?`yesterday at ${a}`:i===0?`today at ${a}`:i===1?`tomorrow at ${a}`:i<7?`${o} at ${a}`:t.toLocaleDateString()}function Jt(e,n){let t=ye(e);return t.setFullYear(t.getFullYear()+n),t}function qt(e){return new Promise((n,t)=>{let r=new FileReader;r.addEventListener("load",function(){let i=JSON.parse(r.result);n(i)}),r.addEventListener("error",t),r.readAsText(e)})}function Zt(){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 Qt="__lsbc__",Se=class{constructor(n){this.eventTarget=window;this.postMessage=n=>{try{localStorage.setItem(this.channelKey,JSON.stringify(n)),localStorage.removeItem(this.channelKey)}catch{}};this.addEventListener=(n,t)=>{this.eventTarget.addEventListener(this.prefixEventName(n),r=>{t(r)})};this.setupLocalStorageListener=()=>{let n=t=>{if(!(t.key!==this.channelKey||!t.newValue))try{let r=JSON.parse(t.newValue||""),i=new MessageEvent(this.prefixEventName("message"),{data:r});this.eventTarget.dispatchEvent(i)}catch{}};window.addEventListener("storage",n)};this.channelKey=Qt+n,this.setupLocalStorageListener()}prefixEventName(n){return this.channelKey+n}};var en=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"}),tn=e=>en[e];var nn=(...e)=>{};var rn=/^(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 an(e){return rn.test(e||"")}function on(e){let n=e||"";return n.charAt(0).toUpperCase()+n.slice(1)}function ze(e){return e.replace(/([-_][a-z])/g,n=>n.toUpperCase().replace(/-|_/,""))}function Ee(e){return e.replace(/[A-Z]/g,n=>`_${n.toLowerCase()}`)}var et=e=>{let n=t=>{if(!t)return t;if(Array.isArray(t))return t.map(a=>typeof a=="object"||Array.isArray(a)?n(a):a);let r={...t},i=Object.keys(r);for(let a of i){let o=e(a.toString());o!==a&&(r[o]=r[a],delete r[a]),typeof r[o]=="object"&&(r[o]=n(r[o]))}return r};return n},sn=et(Ee),un=et(ze);function cn({delayInMs:e}={delayInMs:1e3}){let n,t=!1,r=()=>{clearTimeout(n),t=!0},i=async a=>{t=!1,await a(r),!t&&(n=setTimeout(()=>i(a),e))};return{run:i,stop:r}}var ln=()=>typeof window<"u";function fn(e=""){return e.startsWith("?")&&(e=e.slice(1)),new URLSearchParams(e)}var fe=wt(require("react"));function tt(e,n){if(!e)throw typeof n=="string"?new Error(n):new Error(`${n.displayName} not found`)}var H=(e,n)=>{let{assertCtxFn:t=tt}=n||{},r=fe.default.createContext(void 0);return r.displayName=e,[r,()=>{let o=fe.default.useContext(r);return t(o,`${e} not found`),o.value},()=>{let o=fe.default.useContext(r);return o?o.value:{}}]};var[dn,$]=H("ClerkInstanceContext"),[pn,Le]=H("UserContext"),[gn,mn]=H("ClientContext"),[vn,we]=H("SessionContext"),[hn,Te]=H("OrganizationContext");var p=require("react");function at(e,n,t,r){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function u(l){try{s(r.next(l))}catch(g){o(g)}}function f(l){try{s(r.throw(l))}catch(g){o(g)}}function s(l){l.done?a(l.value):i(l.value).then(u,f)}s((r=r.apply(e,n||[])).next())})}function ot(e,n){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,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(l){return f([s,l])}}function f(s){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,i=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){t.label=s[1];break}if(s[0]===6&&t.label<a[1]){t.label=a[1],a=s;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(s);break}a[2]&&t.ops.pop(),t.trys.pop();continue}s=n.call(e,t)}catch(l){s=[6,l],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var T=function(){},h=T(),Q=Object,x=function(e){return e===h},_=function(e){return typeof e=="function"},M=function(e,n){return Q.assign({},e,n)},Ve="undefined",Fe=function(){return typeof window!=Ve},Cn=function(){return typeof document!=Ve},xn=function(){return Fe()&&typeof window.requestAnimationFrame!=Ve},de=new WeakMap,bn=0,ne=function(e){var n=typeof e,t=e&&e.constructor,r=t==Date,i,a;if(Q(e)===e&&!r&&t!=RegExp){if(i=de.get(e),i)return i;if(i=++bn+"~",de.set(e,i),t==Array){for(i="@",a=0;a<e.length;a++)i+=ne(e[a])+",";de.set(e,i)}if(t==Q){i="#";for(var o=Q.keys(e).sort();!x(a=o.pop());)x(e[a])||(i+=a+":"+ne(e[a])+",");de.set(e,i)}}else i=r?e.toJSON():n=="symbol"?e.toString():n=="string"?JSON.stringify(e):""+e;return i},Me=!0,On=function(){return Me},st=Fe(),ke=Cn(),Ae=st&&window.addEventListener?window.addEventListener.bind(window):T,Rn=ke?document.addEventListener.bind(document):T,Pe=st&&window.removeEventListener?window.removeEventListener.bind(window):T,yn=ke?document.removeEventListener.bind(document):T,Sn=function(){var e=ke&&document.visibilityState;return x(e)||e!=="hidden"},zn=function(e){return Rn("visibilitychange",e),Ae("focus",e),function(){yn("visibilitychange",e),Pe("focus",e)}},En=function(e){var n=function(){Me=!0,e()},t=function(){Me=!1};return Ae("online",n),Ae("offline",t),function(){Pe("online",n),Pe("offline",t)}},Ln={isOnline:On,isVisible:Sn},wn={initFocus:zn,initReconnect:En},pe=!Fe()||"Deno"in window,Tn=function(e){return xn()?window.requestAnimationFrame(e):setTimeout(e,1)},ee=pe?p.useEffect:p.useLayoutEffect,Ie=typeof navigator<"u"&&navigator.connection,nt=!pe&&Ie&&(["slow-2g","2g"].includes(Ie.effectiveType)||Ie.saveData),ut=function(e){if(_(e))try{e=e()}catch{e=""}var n=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?ne(e):"";var t=e?"$swr$"+e:"";return[e,n,t]},N=new WeakMap,ct=0,lt=1,ft=2,te=function(e,n,t,r,i,a,o){o===void 0&&(o=!0);var u=N.get(e),f=u[0],s=u[1],l=u[3],g=f[n],d=s[n];if(o&&d)for(var y=0;y<d.length;++y)d[y](t,r,i);return a&&(delete l[n],g&&g[0])?g[0](ft).then(function(){return e.get(n)}):e.get(n)},In=0,_e=function(){return++In},dt=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return at(void 0,void 0,void 0,function(){var t,r,i,a,o,u,f,s,l,g,d,y,W,b,m,c,B,U,I,E,V;return ot(this,function(A){switch(A.label){case 0:if(t=e[0],r=e[1],i=e[2],a=e[3],o=typeof a=="boolean"?{revalidate:a}:a||{},u=x(o.populateCache)?!0:o.populateCache,f=o.revalidate!==!1,s=o.rollbackOnError!==!1,l=o.optimisticData,g=ut(r),d=g[0],y=g[2],!d)return[2];if(W=N.get(t),b=W[2],e.length<3)return[2,te(t,d,t.get(d),h,h,f,!0)];if(m=i,B=_e(),b[d]=[B,0],U=!x(l),I=t.get(d),U&&(E=_(l)?l(I):l,t.set(d,E),te(t,d,E)),_(m))try{m=m(t.get(d))}catch(F){c=F}return m&&_(m.then)?[4,m.catch(function(F){c=F})]:[3,2];case 1:if(m=A.sent(),B!==b[d][0]){if(c)throw c;return[2,m]}else c&&U&&s&&(u=!0,m=I,t.set(d,I));A.label=2;case 2:return u&&(c||(_(u)&&(m=u(m,I)),t.set(d,m)),t.set(y,M(t.get(y),{error:c}))),b[d][1]=_e(),[4,te(t,d,m,c,h,f,!!u)];case 3:if(V=A.sent(),c)throw c;return[2,u?V:m]}})})},rt=function(e,n){for(var t in e)e[t][0]&&e[t][0](n)},pt=function(e,n){if(!N.has(e)){var t=M(wn,n),r={},i=dt.bind(h,e),a=T;if(N.set(e,[r,{},{},{},i]),!pe){var o=t.initFocus(setTimeout.bind(h,rt.bind(h,r,ct))),u=t.initReconnect(setTimeout.bind(h,rt.bind(h,r,lt)));a=function(){o&&o(),u&&u(),N.delete(e)}}return[e,i,a]}return[e,N.get(e)[4]]},Dn=function(e,n,t,r,i){var a=t.errorRetryCount,o=i.retryCount,u=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!x(a)&&o>a||setTimeout(r,u,i)},gt=pt(new Map),mt=gt[0],Mn=gt[1],vt=M({onLoadingSlow:T,onSuccess:T,onError:T,onErrorRetry:Dn,onDiscarded:T,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:nt?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:nt?5e3:3e3,compare:function(e,n){return ne(e)==ne(n)},isPaused:function(){return!1},cache:mt,mutate:Mn,fallback:{}},Ln),ht=function(e,n){var t=M(e,n);if(n){var r=e.use,i=e.fallback,a=n.use,o=n.fallback;r&&a&&(t.use=r.concat(a)),i&&o&&(t.fallback=M(i,o))}return t},Ue=(0,p.createContext)({}),An=function(e){var n=e.value,t=ht((0,p.useContext)(Ue),n),r=n&&n.provider,i=(0,p.useState)(function(){return r?pt(r(t.cache||mt),n):h})[0];return i&&(t.cache=i[0],t.mutate=i[1]),ee(function(){return i?i[2]:h},[]),(0,p.createElement)(Ue.Provider,M(e,{value:t}))},Pn=function(e,n){var t=(0,p.useState)({})[1],r=(0,p.useRef)(e),i=(0,p.useRef)({data:!1,error:!1,isValidating:!1}),a=(0,p.useCallback)(function(o){var u=!1,f=r.current;for(var s in o){var l=s;f[l]!==o[l]&&(f[l]=o[l],i.current[l]&&(u=!0))}u&&!n.current&&t({})},[]);return ee(function(){r.current=e}),[r,i.current,a]},_n=function(e){return _(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},Un=function(){return M(vt,(0,p.useContext)(Ue))},Vn=function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=Un(),a=_n(t),o=a[0],u=a[1],f=a[2],s=ht(i,f),l=e,g=s.use;if(g)for(var d=g.length;d-- >0;)l=g[d](l);return l(o,u||s.fetcher,s)}},it=function(e,n,t){var r=n[e]||(n[e]=[]);return r.push(t),function(){var i=r.indexOf(t);i>=0&&(r[i]=r[r.length-1],r.pop())}},De={dedupe:!0},Fn=function(e,n,t){var r=t.cache,i=t.compare,a=t.fallbackData,o=t.suspense,u=t.revalidateOnMount,f=t.refreshInterval,s=t.refreshWhenHidden,l=t.refreshWhenOffline,g=N.get(r),d=g[0],y=g[1],W=g[2],b=g[3],m=ut(e),c=m[0],B=m[1],U=m[2],I=(0,p.useRef)(!1),E=(0,p.useRef)(!1),V=(0,p.useRef)(c),A=(0,p.useRef)(n),F=(0,p.useRef)(t),v=function(){return F.current},ge=function(){return v().isVisible()&&v().isOnline()},re=function(S){return r.set(U,M(r.get(U),S))},$e=r.get(c),xt=x(a)?t.fallback[c]:a,D=x($e)?xt:$e,Ne=r.get(U)||{},X=Ne.error,We=!I.current,Ge=function(){return We&&!x(u)?u:v().isPaused()?!1:o?x(D)?!1:t.revalidateIfStale:x(D)||t.revalidateIfStale},bt=function(){return!c||!n?!1:Ne.isValidating?!0:We&&Ge()},me=bt(),ve=Pn({data:D,error:X,isValidating:me},E),G=ve[0],he=ve[1],ie=ve[2],k=(0,p.useCallback)(function(S){return at(void 0,void 0,void 0,function(){var O,R,z,K,Y,L,C,P,w,Ce,J,j,xe;return ot(this,function(q){switch(q.label){case 0:if(O=A.current,!c||!O||E.current||v().isPaused())return[2,!1];K=!0,Y=S||{},L=!b[c]||!Y.dedupe,C=function(){return!E.current&&c===V.current&&I.current},P=function(){var je=b[c];je&&je[1]===z&&delete b[c]},w={isValidating:!1},Ce=function(){re({isValidating:!1}),C()&&ie(w)},re({isValidating:!0}),ie({isValidating:!0}),q.label=1;case 1:return q.trys.push([1,3,,4]),L&&(te(r,c,G.current.data,G.current.error,!0),t.loadingTimeout&&!r.get(c)&&setTimeout(function(){K&&C()&&v().onLoadingSlow(c,t)},t.loadingTimeout),b[c]=[O.apply(void 0,B),_e()]),xe=b[c],R=xe[0],z=xe[1],[4,R];case 2:return R=q.sent(),L&&setTimeout(P,t.dedupingInterval),!b[c]||b[c][1]!==z?(L&&C()&&v().onDiscarded(c),[2,!1]):(re({error:h}),w.error=h,J=W[c],!x(J)&&(z<=J[0]||z<=J[1]||J[1]===0)?(Ce(),L&&C()&&v().onDiscarded(c),[2,!1]):(i(G.current.data,R)?w.data=G.current.data:w.data=R,i(r.get(c),R)||r.set(c,R),L&&C()&&v().onSuccess(R,c,t),[3,4]));case 3:return j=q.sent(),P(),v().isPaused()||(re({error:j}),w.error=j,L&&C()&&(v().onError(j,c,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||_(t.shouldRetryOnError)&&t.shouldRetryOnError(j))&&ge()&&v().onErrorRetry(j,c,t,k,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return K=!1,Ce(),C()&&L&&te(r,c,w.data,w.error,!1),[2,!0]}})})},[c]),Ot=(0,p.useCallback)(dt.bind(h,r,function(){return V.current}),[]);if(ee(function(){A.current=n,F.current=t}),ee(function(){if(!!c){var S=c!==V.current,O=k.bind(h,De),R=function(C,P,w){ie(M({error:P,isValidating:w},i(G.current.data,C)?h:{data:C}))},z=0,K=function(C){if(C==ct){var P=Date.now();v().revalidateOnFocus&&P>z&&ge()&&(z=P+v().focusThrottleInterval,O())}else if(C==lt)v().revalidateOnReconnect&&ge()&&O();else if(C==ft)return k()},Y=it(c,y,R),L=it(c,d,K);return E.current=!1,V.current=c,I.current=!0,S&&ie({data:D,error:X,isValidating:me}),Ge()&&(x(D)||pe?O():Tn(O)),function(){E.current=!0,Y(),L()}}},[c,k]),ee(function(){var S;function O(){var z=_(f)?f(D):f;z&&S!==-1&&(S=setTimeout(R,z))}function R(){!G.current.error&&(s||v().isVisible())&&(l||v().isOnline())?k(De).then(O):O()}return O(),function(){S&&(clearTimeout(S),S=-1)}},[f,s,l,k]),(0,p.useDebugValue)(D),o&&x(D)&&c)throw A.current=n,F.current=t,E.current=!1,x(X)?k(De):X;return{mutate:Ot,get data(){return he.data=!0,D},get error(){return he.error=!0,X},get isValidating(){return he.isValidating=!0,me}}},_r=Q.defineProperty(An,"default",{value:vt});var He=Vn(Fn);var kn=e=>{let{invitationList:n,membershipList:t}=e||{},{organization:r,lastOrganizationMember:i,lastOrganizationInvitation:a}=Te(),o=we(),u=$(),f=u.loaded&&o&&r,s=u.loaded?()=>{var c;return(c=u.organization)==null?void 0:c.getPendingInvitations(n)}:()=>[],l=u.loaded?()=>{var c;return(c=u.organization)==null?void 0:c.getMemberships(t)}:()=>[],{data:g,isValidating:d,mutate:y}=He(f&&n?Ct("invites",r,a,n):null,s),{data:W,isValidating:b,mutate:m}=He(f&&t?Ct("memberships",r,i,t):null,l);return r===void 0?{isLoaded:!1,organization:void 0,invitationList:void 0,membershipList:void 0,membership:void 0}:r===null?{isLoaded:!0,organization:null,invitationList:null,membershipList:null,membership:null}:!u.loaded&&r?{isLoaded:!0,organization:r,invitationList:void 0,membershipList:void 0,membership:void 0}:{isLoaded:!b&&!d,organization:r,membershipList:W,membership:Hn(o.user.organizationMemberships,r.id),invitationList:g,unstable__mutate:()=>{m(),y()}}};function Hn(e,n){return e.find(t=>t.organization.id===n)}function Ct(e,n,t,r){return[e,n.id,t==null?void 0:t.id,t==null?void 0:t.updatedAt,r.offset,r.limit].filter(Boolean).join("-")}var $n=()=>{let e=$(),n=Le();return!e.loaded||!n?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:Nn(n.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function Nn(e){return e.map(n=>({membership:n,organization:n.organization}))}var Wn=()=>{let e=$();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}};0&&(module.exports={ClerkInstanceContext,ClientContext,LocalStorageBroadcastChannel,OrganizationContext,Poller,SessionContext,UserContext,addYears,assertContextExists,camelToSnake,colorToSameTypeString,createContextAndHook,createCookieHandler,dateTo12HourTime,deepCamelToSnake,deepSnakeToCamel,differenceInCalendarDays,extension,formatRelative,hasAlpha,hexStringToRgbaColor,inBrowser,inClientSide,isHSLColor,isIPV4Address,isRGBColor,isRetinaDisplay,isTransparent,isValidHexString,isValidHslaString,isValidRgbaString,noop,parseSearchParams,readJSONFile,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,
camelToSnake: () => camelToSnake,
colorToSameTypeString: () => colorToSameTypeString,
createContextAndHook: () => createContextAndHook,
createCookieHandler: () => createCookieHandler,
dateTo12HourTime: () => dateTo12HourTime,
deepCamelToSnake: () => deepCamelToSnake,
deepSnakeToCamel: () => deepSnakeToCamel,
differenceInCalendarDays: () => differenceInCalendarDays,
extension: () => extension,
formatRelative: () => formatRelative,
hasAlpha: () => hasAlpha,
hexStringToRgbaColor: () => hexStringToRgbaColor,
inBrowser: () => inBrowser,
inClientSide: () => inClientSide,
isHSLColor: () => isHSLColor,
isIPV4Address: () => isIPV4Address,
isRGBColor: () => isRGBColor,
isRetinaDisplay: () => isRetinaDisplay,
isTransparent: () => isTransparent,
isValidHexString: () => isValidHexString,
isValidHslaString: () => isValidHslaString,
isValidRgbaString: () => isValidRgbaString,
noop: () => noop,
parseSearchParams: () => parseSearchParams,
readJSONFile: () => readJSONFile,
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/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;
var DAYS_EN = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
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(date, relativeTo) {
if (!date || !relativeTo) {
return "";
}
const a = normalizeDate(date);
const b = normalizeDate(relativeTo);
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false });
const time12Hour = dateTo12HourTime(a);
const dayName = DAYS_EN[a.getDay()];
if (differenceInDays < -6) {
return a.toLocaleDateString();
}
if (differenceInDays < -1) {
return `last ${dayName} at ${time12Hour}`;
}
if (differenceInDays === -1) {
return `yesterday at ${time12Hour}`;
}
if (differenceInDays === 0) {
return `today at ${time12Hour}`;
}
if (differenceInDays === 1) {
return `tomorrow at ${time12Hour}`;
}
if (differenceInDays < 7) {
return `${dayName} at ${time12Hour}`;
}
return a.toLocaleDateString();
}
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/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 noop = (..._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.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, ""));
}
function camelToSnake(str) {
return 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/poller.ts
function Poller({ delayInMs } = { delayInMs: 1e3 }) {
let timerId;
let stopped = false;
const stop = () => {
clearTimeout(timerId);
stopped = true;
};
const run = async (cb) => {
stopped = false;
await cb(stop);
if (stopped) {
return;
}
timerId = setTimeout(() => 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/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 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 ? 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 = 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 = (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
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ClerkInstanceContext,
ClientContext,
LocalStorageBroadcastChannel,
OrganizationContext,
Poller,
SessionContext,
UserContext,
addYears,
assertContextExists,
camelToSnake,
colorToSameTypeString,
createContextAndHook,
createCookieHandler,
dateTo12HourTime,
deepCamelToSnake,
deepSnakeToCamel,
differenceInCalendarDays,
extension,
formatRelative,
hasAlpha,
hexStringToRgbaColor,
inBrowser,
inClientSide,
isHSLColor,
isIPV4Address,
isRGBColor,
isRetinaDisplay,
isTransparent,
isValidHexString,
isValidHslaString,
isValidRgbaString,
noop,
parseSearchParams,
readJSONFile,
snakeToCamel,
stringToHslaColor,
stringToSameTypeColor,
titleize,
toSentence,
useClerkInstanceContext,
useClientContext,
useOrganization,
useOrganizationContext,
useOrganizationList,
useOrganizations,
useSessionContext,
useUserContext
});
/*! *****************************************************************************

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

@@ -1,3 +0,873 @@

"use strict";var z=Object.create;var S=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty;var q=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),$=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},b=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of K(e))!Q.call(o,i)&&i!==t&&S(o,i,{get:()=>e[i],enumerable:!(r=J(e,i))||r.enumerable});return o},f=(o,e,t)=>(b(o,e,"default"),t&&b(t,e,"default")),M=(o,e,t)=>(t=o!=null?z(Z(o)):{},b(e||!o||!o.__esModule?S(t,"default",{value:o,enumerable:!0}):t,o)),ee=o=>b(S({},"__esModule",{value:!0}),o);var U=q(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.spyOn=m.mocked=m.fn=m.ModuleMocker=void 0;function C(o,e,t){return e in o?Object.defineProperty(o,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[e]=t,o}var P="mockConstructor",N=/[\s!-\/:-@\[-`{-~]/,ne=new RegExp(N.source,"g"),re=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]);function oe(o,e){let t;switch(e){case 1:t=function(r){return o.apply(this,arguments)};break;case 2:t=function(r,i){return o.apply(this,arguments)};break;case 3:t=function(r,i,c){return o.apply(this,arguments)};break;case 4:t=function(r,i,c,s){return o.apply(this,arguments)};break;case 5:t=function(r,i,c,s,n){return o.apply(this,arguments)};break;case 6:t=function(r,i,c,s,n,a){return o.apply(this,arguments)};break;case 7:t=function(r,i,c,s,n,a,l){return o.apply(this,arguments)};break;case 8:t=function(r,i,c,s,n,a,l,p){return o.apply(this,arguments)};break;case 9:t=function(r,i,c,s,n,a,l,p,g){return o.apply(this,arguments)};break;default:t=function(){return o.apply(this,arguments)};break}return t}function D(o){return Object.prototype.toString.apply(o).slice(8,-1)}function ie(o){let e=D(o);return e==="Function"||e==="AsyncFunction"||e==="GeneratorFunction"?"function":Array.isArray(o)?"array":e==="Object"?"object":e==="Number"||e==="String"||e==="Boolean"||e==="Symbol"?"constant":e==="Map"||e==="WeakMap"||e==="Set"?"collection":e==="RegExp"?"regexp":o===void 0?"undefined":o===null?"null":null}function se(o,e){if(e==="arguments"||e==="caller"||e==="callee"||e==="name"||e==="length"){let t=D(o);return t==="Function"||t==="AsyncFunction"||t==="GeneratorFunction"}return e==="source"||e==="global"||e==="ignoreCase"||e==="multiline"?D(o)==="RegExp":!1}var O=class{constructor(e){C(this,"_environmentGlobal",void 0),C(this,"_mockState",void 0),C(this,"_mockConfigRegistry",void 0),C(this,"_spyState",void 0),C(this,"_invocationCallCounter",void 0),this._environmentGlobal=e,this._mockState=new WeakMap,this._mockConfigRegistry=new WeakMap,this._spyState=new Set,this._invocationCallCounter=1}_getSlots(e){if(!e)return[];let t=new Set,r=this._environmentGlobal.Object.prototype,i=this._environmentGlobal.Function.prototype,c=this._environmentGlobal.RegExp.prototype,s=Object.prototype,n=Function.prototype,a=RegExp.prototype;for(;e!=null&&e!==r&&e!==i&&e!==c&&e!==s&&e!==n&&e!==a;){let l=Object.getOwnPropertyNames(e);for(let p=0;p<l.length;p++){let g=l[p];if(!se(e,g)){let h=Object.getOwnPropertyDescriptor(e,g);(h!==void 0&&!h.get||e.__esModule)&&t.add(g)}}e=Object.getPrototypeOf(e)}return Array.from(t)}_ensureMockConfig(e){let t=this._mockConfigRegistry.get(e);return t||(t=this._defaultMockConfig(),this._mockConfigRegistry.set(e,t)),t}_ensureMockState(e){let t=this._mockState.get(e);return t||(t=this._defaultMockState(),this._mockState.set(e,t)),t}_defaultMockConfig(){return{mockImpl:void 0,mockName:"jest.fn()",specificMockImpls:[],specificReturnValues:[]}}_defaultMockState(){return{calls:[],instances:[],invocationCallOrder:[],results:[]}}_makeComponent(e,t){if(e.type==="object")return new this._environmentGlobal.Object;if(e.type==="array")return new this._environmentGlobal.Array;if(e.type==="regexp")return new this._environmentGlobal.RegExp("");if(e.type==="constant"||e.type==="collection"||e.type==="null"||e.type==="undefined")return e.value;if(e.type==="function"){let r=e.members&&e.members.prototype&&e.members.prototype.members||{},i=this._getSlots(r),c=this,s=oe(function(...a){let l=c._ensureMockState(n),p=c._ensureMockConfig(n);l.instances.push(this),l.calls.push(a);let g={type:"incomplete",value:void 0};l.results.push(g),l.invocationCallOrder.push(c._invocationCallCounter++);let h,F,E=!1;try{h=(()=>{if(this instanceof n){i.forEach(k=>{if(r[k].type==="function"){let Y=this[k];this[k]=c.generateFromMetadata(r[k]),this[k]._protoImpl=Y}});let L=p.specificMockImpls.length?p.specificMockImpls.shift():p.mockImpl;return L&&L.apply(this,arguments)}let d=p.specificMockImpls.shift();if(d===void 0&&(d=p.mockImpl),d)return d.apply(this,arguments);if(n._protoImpl)return n._protoImpl.apply(this,arguments)})()}catch(d){throw F=d,E=!0,d}finally{g.type=E?"throw":"return",g.value=E?F:h}return h},e.length||0),n=this._createMockFunction(e,s);return n._isMockFunction=!0,n.getMockImplementation=()=>this._ensureMockConfig(n).mockImpl,typeof t=="function"&&this._spyState.add(t),this._mockState.set(n,this._defaultMockState()),this._mockConfigRegistry.set(n,this._defaultMockConfig()),Object.defineProperty(n,"mock",{configurable:!1,enumerable:!0,get:()=>this._ensureMockState(n),set:a=>this._mockState.set(n,a)}),n.mockClear=()=>(this._mockState.delete(n),n),n.mockReset=()=>(n.mockClear(),this._mockConfigRegistry.delete(n),n),n.mockRestore=()=>(n.mockReset(),t?t():void 0),n.mockReturnValueOnce=a=>n.mockImplementationOnce(()=>a),n.mockResolvedValueOnce=a=>n.mockImplementationOnce(()=>Promise.resolve(a)),n.mockRejectedValueOnce=a=>n.mockImplementationOnce(()=>Promise.reject(a)),n.mockReturnValue=a=>n.mockImplementation(()=>a),n.mockResolvedValue=a=>n.mockImplementation(()=>Promise.resolve(a)),n.mockRejectedValue=a=>n.mockImplementation(()=>Promise.reject(a)),n.mockImplementationOnce=a=>(this._ensureMockConfig(n).specificMockImpls.push(a),n),n.mockImplementation=a=>{let l=this._ensureMockConfig(n);return l.mockImpl=a,n},n.mockReturnThis=()=>n.mockImplementation(function(){return this}),n.mockName=a=>{if(a){let l=this._ensureMockConfig(n);l.mockName=a}return n},n.getMockName=()=>this._ensureMockConfig(n).mockName||"jest.fn()",e.mockImpl&&n.mockImplementation(e.mockImpl),n}else{let r=e.type||"undefined type";throw new Error("Unrecognized type "+r)}}_createMockFunction(e,t){let r=e.name;if(!r)return t;let i="bound ",c="";if(r&&r.startsWith(i))do r=r.substring(i.length),c=".bind(null)";while(r&&r.startsWith(i));if(r===P)return t;(re.has(r)||/^\d/.test(r))&&(r="$"+r),N.test(r)&&(r=r.replace(ne,"$"));let s="return function "+r+"() {return "+P+".apply(this,arguments);}"+c;return new this._environmentGlobal.Function(P,s)(t)}_generateMock(e,t,r){let i=this._makeComponent(e);return e.refID!=null&&(r[e.refID]=i),this._getSlots(e.members).forEach(c=>{let s=e.members&&e.members[c]||{};s.ref!=null?t.push(function(n){return()=>i[c]=r[n]}(s.ref)):i[c]=this._generateMock(s,t,r)}),e.type!=="undefined"&&e.type!=="null"&&i.prototype&&typeof i.prototype=="object"&&(i.prototype.constructor=i),i}generateFromMetadata(e){let t=[],r={},i=this._generateMock(e,t,r);return t.forEach(c=>c()),i}getMetadata(e,t){let r=t||new Map,i=r.get(e);if(i!=null)return{ref:i};let c=ie(e);if(!c)return null;let s={type:c};if(c==="constant"||c==="collection"||c==="undefined"||c==="null")return s.value=e,s;c==="function"&&(s.name=e.name,e._isMockFunction===!0&&(s.mockImpl=e.getMockImplementation())),s.refID=r.size,r.set(e,s.refID);let n=null;return c!=="array"&&this._getSlots(e).forEach(a=>{if(c==="function"&&e._isMockFunction===!0&&a.match(/^mock/))return;let l=this.getMetadata(e[a],r);l&&(n||(n={}),n[a]=l)}),n&&(s.members=n),s}isMockFunction(e){return!!e&&e._isMockFunction===!0}fn(e){let t=e?e.length:0,r=this._makeComponent({length:t,type:"function"});return e&&r.mockImplementation(e),r}spyOn(e,t,r){if(r)return this._spyOnProperty(e,t,r);if(typeof e!="object"&&typeof e!="function")throw new Error("Cannot spyOn on a primitive value; "+this._typeOf(e)+" given");let i=e[t];if(!this.isMockFunction(i)){if(typeof i!="function")throw new Error("Cannot spy the "+t+" property because it is not a function; "+this._typeOf(i)+" given instead");let c=Object.prototype.hasOwnProperty.call(e,t),s=Object.getOwnPropertyDescriptor(e,t),n=Object.getPrototypeOf(e);for(;!s&&n!==null;)s=Object.getOwnPropertyDescriptor(n,t),n=Object.getPrototypeOf(n);let a;if(s&&s.get){let l=s.get;a=this._makeComponent({type:"function"},()=>{s.get=l,Object.defineProperty(e,t,s)}),s.get=()=>a,Object.defineProperty(e,t,s)}else a=this._makeComponent({type:"function"},()=>{c?e[t]=i:delete e[t]}),e[t]=a;a.mockImplementation(function(){return i.apply(this,arguments)})}return e[t]}_spyOnProperty(e,t,r="get"){if(typeof e!="object"&&typeof e!="function")throw new Error("Cannot spyOn on a primitive value; "+this._typeOf(e)+" given");if(!e)throw new Error("spyOn could not find an object to spy upon for "+t);if(!t)throw new Error("No property name supplied");let i=Object.getOwnPropertyDescriptor(e,t),c=Object.getPrototypeOf(e);for(;!i&&c!==null;)i=Object.getOwnPropertyDescriptor(c,t),c=Object.getPrototypeOf(c);if(!i)throw new Error(t+" property does not exist");if(!i.configurable)throw new Error(t+" is not declared configurable");if(!i[r])throw new Error("Property "+t+" does not have access type "+r);let s=i[r];if(!this.isMockFunction(s)){if(typeof s!="function")throw new Error("Cannot spy the "+t+" property because it is not a function; "+this._typeOf(s)+" given instead");i[r]=this._makeComponent({type:"function"},()=>{i[r]=s,Object.defineProperty(e,t,i)}),i[r].mockImplementation(function(){return s.apply(this,arguments)})}return Object.defineProperty(e,t,i),i[r]}clearAllMocks(){this._mockState=new WeakMap}resetAllMocks(){this._mockConfigRegistry=new WeakMap,this._mockState=new WeakMap}restoreAllMocks(){this._spyState.forEach(e=>e()),this._spyState=new Set}_typeOf(e){return e==null?""+e:typeof e}mocked(e,t=!1){return e}};m.ModuleMocker=O;var y=new O(global),ce=y.fn.bind(y);m.fn=ce;var ae=y.spyOn.bind(y);m.spyOn=ae;var le=y.mocked.bind(y);m.mocked=le});var R={};$(R,{actHook:()=>_.act,mocked:()=>A.mocked,noop:()=>I,render:()=>j,renderHook:()=>_.renderHook,renderJSON:()=>B,renderJSONAfterFirstAct:()=>X,userEvent:()=>T.default});module.exports=ee(R);var u={};$(u,{actHook:()=>_.act,mocked:()=>A.mocked,noop:()=>I,render:()=>j,renderHook:()=>_.renderHook,renderJSON:()=>B,renderJSONAfterFirstAct:()=>X,userEvent:()=>T.default});var lt=require("@testing-library/jest-dom/extend-expect"),W=require("@testing-library/react"),x=M(require("react-test-renderer"));function w(o){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)o[r]=t[r]}return o}var te={read:function(o){return o[0]==='"'&&(o=o.slice(1,-1)),o.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(o){return encodeURIComponent(o).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function v(o,e){function t(i,c,s){if(!(typeof document>"u")){s=w({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var a in s)!s[a]||(n+="; "+a,s[a]!==!0&&(n+="="+s[a].split(";")[0]));return document.cookie=i+"="+o.write(c,i)+n}}function r(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var c=document.cookie?document.cookie.split("; "):[],s={},n=0;n<c.length;n++){var a=c[n].split("="),l=a.slice(1).join("=");try{var p=decodeURIComponent(a[0]);if(s[p]=o.read(l,p),i===p)break}catch{}}return i?s[i]:s}}return Object.create({set:t,get:r,remove:function(i,c){t(i,"",w({},c,{expires:-1}))},withAttributes:function(i){return v(this.converter,w({},this.attributes,i))},withConverter:function(i){return v(w({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(o)}})}var xe=v(te,{path:"/"});var Ae=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"});var I=(...o)=>{};function H(o){return o.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,""))}function G(o){return o.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}var V=o=>{let e=t=>{if(!t)return t;if(Array.isArray(t))return t.map(c=>typeof c=="object"||Array.isArray(c)?e(c):c);let r={...t},i=Object.keys(r);for(let c of i){let s=o(c.toString());s!==c&&(r[s]=r[c],delete r[c]),typeof r[s]=="object"&&(r[s]=e(r[s]))}return r};return e},Ge=V(G),Ve=V(H);f(u,require("@testing-library/react"));var _=require("@testing-library/react-hooks"),T=M(require("@testing-library/user-event")),A=M(U()),j=(o,e)=>(0,W.render)(o,e),B=o=>x.default.create(o).toJSON(),X=o=>{let e;return x.default.act(()=>{e=x.default.create(o)}),e.toJSON()};f(R,u,module.exports);0&&(module.exports={actHook,mocked,noop,render,renderHook,renderJSON,renderJSONAfterFirstAct,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 __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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);
// ../../node_modules/jest-mock/build/index.js
var require_build = __commonJS({
"../../node_modules/jest-mock/build/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.spyOn = exports.mocked = exports.fn = exports.ModuleMocker = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var MOCK_CONSTRUCTOR_NAME = "mockConstructor";
var FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/;
var FUNCTION_NAME_RESERVED_REPLACE = new RegExp(
FUNCTION_NAME_RESERVED_PATTERN.source,
"g"
);
var RESERVED_KEYWORDS = /* @__PURE__ */ new Set([
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield"
]);
function matchArity(fn2, length) {
let mockConstructor;
switch (length) {
case 1:
mockConstructor = function(_a) {
return fn2.apply(this, arguments);
};
break;
case 2:
mockConstructor = function(_a, _b) {
return fn2.apply(this, arguments);
};
break;
case 3:
mockConstructor = function(_a, _b, _c) {
return fn2.apply(this, arguments);
};
break;
case 4:
mockConstructor = function(_a, _b, _c, _d) {
return fn2.apply(this, arguments);
};
break;
case 5:
mockConstructor = function(_a, _b, _c, _d, _e) {
return fn2.apply(this, arguments);
};
break;
case 6:
mockConstructor = function(_a, _b, _c, _d, _e, _f) {
return fn2.apply(this, arguments);
};
break;
case 7:
mockConstructor = function(_a, _b, _c, _d, _e, _f, _g) {
return fn2.apply(this, arguments);
};
break;
case 8:
mockConstructor = function(_a, _b, _c, _d, _e, _f, _g, _h) {
return fn2.apply(this, arguments);
};
break;
case 9:
mockConstructor = function(_a, _b, _c, _d, _e, _f, _g, _h, _i) {
return fn2.apply(this, arguments);
};
break;
default:
mockConstructor = function() {
return fn2.apply(this, arguments);
};
break;
}
return mockConstructor;
}
function getObjectType(value) {
return Object.prototype.toString.apply(value).slice(8, -1);
}
function getType(ref) {
const typeName = getObjectType(ref);
if (typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction") {
return "function";
} else if (Array.isArray(ref)) {
return "array";
} else if (typeName === "Object") {
return "object";
} else if (typeName === "Number" || typeName === "String" || typeName === "Boolean" || typeName === "Symbol") {
return "constant";
} else if (typeName === "Map" || typeName === "WeakMap" || typeName === "Set") {
return "collection";
} else if (typeName === "RegExp") {
return "regexp";
} else if (ref === void 0) {
return "undefined";
} else if (ref === null) {
return "null";
} else {
return null;
}
}
function isReadonlyProp(object, prop) {
if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
const typeName = getObjectType(object);
return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction";
}
if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
return getObjectType(object) === "RegExp";
}
return false;
}
var ModuleMocker = class {
constructor(global2) {
_defineProperty(this, "_environmentGlobal", void 0);
_defineProperty(this, "_mockState", void 0);
_defineProperty(this, "_mockConfigRegistry", void 0);
_defineProperty(this, "_spyState", void 0);
_defineProperty(this, "_invocationCallCounter", void 0);
this._environmentGlobal = global2;
this._mockState = /* @__PURE__ */ new WeakMap();
this._mockConfigRegistry = /* @__PURE__ */ new WeakMap();
this._spyState = /* @__PURE__ */ new Set();
this._invocationCallCounter = 1;
}
_getSlots(object) {
if (!object) {
return [];
}
const slots = /* @__PURE__ */ new Set();
const EnvObjectProto = this._environmentGlobal.Object.prototype;
const EnvFunctionProto = this._environmentGlobal.Function.prototype;
const EnvRegExpProto = this._environmentGlobal.RegExp.prototype;
const ObjectProto = Object.prototype;
const FunctionProto = Function.prototype;
const RegExpProto = RegExp.prototype;
while (object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto) {
const ownNames = Object.getOwnPropertyNames(object);
for (let i = 0; i < ownNames.length; i++) {
const prop = ownNames[i];
if (!isReadonlyProp(object, prop)) {
const propDesc = Object.getOwnPropertyDescriptor(object, prop);
if (propDesc !== void 0 && !propDesc.get || object.__esModule) {
slots.add(prop);
}
}
}
object = Object.getPrototypeOf(object);
}
return Array.from(slots);
}
_ensureMockConfig(f) {
let config = this._mockConfigRegistry.get(f);
if (!config) {
config = this._defaultMockConfig();
this._mockConfigRegistry.set(f, config);
}
return config;
}
_ensureMockState(f) {
let state = this._mockState.get(f);
if (!state) {
state = this._defaultMockState();
this._mockState.set(f, state);
}
return state;
}
_defaultMockConfig() {
return {
mockImpl: void 0,
mockName: "jest.fn()",
specificMockImpls: [],
specificReturnValues: []
};
}
_defaultMockState() {
return {
calls: [],
instances: [],
invocationCallOrder: [],
results: []
};
}
_makeComponent(metadata, restore) {
if (metadata.type === "object") {
return new this._environmentGlobal.Object();
} else if (metadata.type === "array") {
return new this._environmentGlobal.Array();
} else if (metadata.type === "regexp") {
return new this._environmentGlobal.RegExp("");
} else if (metadata.type === "constant" || metadata.type === "collection" || metadata.type === "null" || metadata.type === "undefined") {
return metadata.value;
} else if (metadata.type === "function") {
const prototype = metadata.members && metadata.members.prototype && metadata.members.prototype.members || {};
const prototypeSlots = this._getSlots(prototype);
const mocker = this;
const mockConstructor = matchArity(function(...args) {
const mockState = mocker._ensureMockState(f);
const mockConfig = mocker._ensureMockConfig(f);
mockState.instances.push(this);
mockState.calls.push(args);
const mockResult = {
type: "incomplete",
value: void 0
};
mockState.results.push(mockResult);
mockState.invocationCallOrder.push(mocker._invocationCallCounter++);
let finalReturnValue;
let thrownError;
let callDidThrowError = false;
try {
finalReturnValue = (() => {
if (this instanceof f) {
prototypeSlots.forEach((slot) => {
if (prototype[slot].type === "function") {
const protoImpl = this[slot];
this[slot] = mocker.generateFromMetadata(prototype[slot]);
this[slot]._protoImpl = protoImpl;
}
});
const mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl;
return mockImpl && mockImpl.apply(this, arguments);
}
let specificMockImpl = mockConfig.specificMockImpls.shift();
if (specificMockImpl === void 0) {
specificMockImpl = mockConfig.mockImpl;
}
if (specificMockImpl) {
return specificMockImpl.apply(this, arguments);
}
if (f._protoImpl) {
return f._protoImpl.apply(this, arguments);
}
return void 0;
})();
} catch (error) {
thrownError = error;
callDidThrowError = true;
throw error;
} finally {
mockResult.type = callDidThrowError ? "throw" : "return";
mockResult.value = callDidThrowError ? thrownError : finalReturnValue;
}
return finalReturnValue;
}, metadata.length || 0);
const f = this._createMockFunction(metadata, mockConstructor);
f._isMockFunction = true;
f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl;
if (typeof restore === "function") {
this._spyState.add(restore);
}
this._mockState.set(f, this._defaultMockState());
this._mockConfigRegistry.set(f, this._defaultMockConfig());
Object.defineProperty(f, "mock", {
configurable: false,
enumerable: true,
get: () => this._ensureMockState(f),
set: (val) => this._mockState.set(f, val)
});
f.mockClear = () => {
this._mockState.delete(f);
return f;
};
f.mockReset = () => {
f.mockClear();
this._mockConfigRegistry.delete(f);
return f;
};
f.mockRestore = () => {
f.mockReset();
return restore ? restore() : void 0;
};
f.mockReturnValueOnce = (value) => f.mockImplementationOnce(() => value);
f.mockResolvedValueOnce = (value) => f.mockImplementationOnce(() => Promise.resolve(value));
f.mockRejectedValueOnce = (value) => f.mockImplementationOnce(() => Promise.reject(value));
f.mockReturnValue = (value) => f.mockImplementation(() => value);
f.mockResolvedValue = (value) => f.mockImplementation(() => Promise.resolve(value));
f.mockRejectedValue = (value) => f.mockImplementation(() => Promise.reject(value));
f.mockImplementationOnce = (fn2) => {
const mockConfig = this._ensureMockConfig(f);
mockConfig.specificMockImpls.push(fn2);
return f;
};
f.mockImplementation = (fn2) => {
const mockConfig = this._ensureMockConfig(f);
mockConfig.mockImpl = fn2;
return f;
};
f.mockReturnThis = () => f.mockImplementation(function() {
return this;
});
f.mockName = (name) => {
if (name) {
const mockConfig = this._ensureMockConfig(f);
mockConfig.mockName = name;
}
return f;
};
f.getMockName = () => {
const mockConfig = this._ensureMockConfig(f);
return mockConfig.mockName || "jest.fn()";
};
if (metadata.mockImpl) {
f.mockImplementation(metadata.mockImpl);
}
return f;
} else {
const unknownType = metadata.type || "undefined type";
throw new Error("Unrecognized type " + unknownType);
}
}
_createMockFunction(metadata, mockConstructor) {
let name = metadata.name;
if (!name) {
return mockConstructor;
}
const boundFunctionPrefix = "bound ";
let bindCall = "";
if (name && name.startsWith(boundFunctionPrefix)) {
do {
name = name.substring(boundFunctionPrefix.length);
bindCall = ".bind(null)";
} while (name && name.startsWith(boundFunctionPrefix));
}
if (name === MOCK_CONSTRUCTOR_NAME) {
return mockConstructor;
}
if (RESERVED_KEYWORDS.has(name) || /^\d/.test(name)) {
name = "$" + name;
}
if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) {
name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, "$");
}
const body = "return function " + name + "() {return " + MOCK_CONSTRUCTOR_NAME + ".apply(this,arguments);}" + bindCall;
const createConstructor = new this._environmentGlobal.Function(
MOCK_CONSTRUCTOR_NAME,
body
);
return createConstructor(mockConstructor);
}
_generateMock(metadata, callbacks, refs) {
const mock = this._makeComponent(metadata);
if (metadata.refID != null) {
refs[metadata.refID] = mock;
}
this._getSlots(metadata.members).forEach((slot) => {
const slotMetadata = metadata.members && metadata.members[slot] || {};
if (slotMetadata.ref != null) {
callbacks.push(
function(ref) {
return () => mock[slot] = refs[ref];
}(slotMetadata.ref)
);
} else {
mock[slot] = this._generateMock(slotMetadata, callbacks, refs);
}
});
if (metadata.type !== "undefined" && metadata.type !== "null" && mock.prototype && typeof mock.prototype === "object") {
mock.prototype.constructor = mock;
}
return mock;
}
generateFromMetadata(_metadata) {
const callbacks = [];
const refs = {};
const mock = this._generateMock(_metadata, callbacks, refs);
callbacks.forEach((setter) => setter());
return mock;
}
getMetadata(component, _refs) {
const refs = _refs || /* @__PURE__ */ new Map();
const ref = refs.get(component);
if (ref != null) {
return {
ref
};
}
const type = getType(component);
if (!type) {
return null;
}
const metadata = {
type
};
if (type === "constant" || type === "collection" || type === "undefined" || type === "null") {
metadata.value = component;
return metadata;
} else if (type === "function") {
metadata.name = component.name;
if (component._isMockFunction === true) {
metadata.mockImpl = component.getMockImplementation();
}
}
metadata.refID = refs.size;
refs.set(component, metadata.refID);
let members = null;
if (type !== "array") {
this._getSlots(component).forEach((slot) => {
if (type === "function" && component._isMockFunction === true && slot.match(/^mock/)) {
return;
}
const slotMetadata = this.getMetadata(component[slot], refs);
if (slotMetadata) {
if (!members) {
members = {};
}
members[slot] = slotMetadata;
}
});
}
if (members) {
metadata.members = members;
}
return metadata;
}
isMockFunction(fn2) {
return !!fn2 && fn2._isMockFunction === true;
}
fn(implementation) {
const length = implementation ? implementation.length : 0;
const fn2 = this._makeComponent({
length,
type: "function"
});
if (implementation) {
fn2.mockImplementation(implementation);
}
return fn2;
}
spyOn(object, methodName, accessType) {
if (accessType) {
return this._spyOnProperty(object, methodName, accessType);
}
if (typeof object !== "object" && typeof object !== "function") {
throw new Error(
"Cannot spyOn on a primitive value; " + this._typeOf(object) + " given"
);
}
const original = object[methodName];
if (!this.isMockFunction(original)) {
if (typeof original !== "function") {
throw new Error(
"Cannot spy the " + methodName + " property because it is not a function; " + this._typeOf(original) + " given instead"
);
}
const isMethodOwner = Object.prototype.hasOwnProperty.call(
object,
methodName
);
let descriptor = Object.getOwnPropertyDescriptor(object, methodName);
let proto = Object.getPrototypeOf(object);
while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
proto = Object.getPrototypeOf(proto);
}
let mock;
if (descriptor && descriptor.get) {
const originalGet = descriptor.get;
mock = this._makeComponent(
{
type: "function"
},
() => {
descriptor.get = originalGet;
Object.defineProperty(object, methodName, descriptor);
}
);
descriptor.get = () => mock;
Object.defineProperty(object, methodName, descriptor);
} else {
mock = this._makeComponent(
{
type: "function"
},
() => {
if (isMethodOwner) {
object[methodName] = original;
} else {
delete object[methodName];
}
}
);
object[methodName] = mock;
}
mock.mockImplementation(function() {
return original.apply(this, arguments);
});
}
return object[methodName];
}
_spyOnProperty(obj, propertyName, accessType = "get") {
if (typeof obj !== "object" && typeof obj !== "function") {
throw new Error(
"Cannot spyOn on a primitive value; " + this._typeOf(obj) + " given"
);
}
if (!obj) {
throw new Error(
"spyOn could not find an object to spy upon for " + propertyName
);
}
if (!propertyName) {
throw new Error("No property name supplied");
}
let descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
let proto = Object.getPrototypeOf(obj);
while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, propertyName);
proto = Object.getPrototypeOf(proto);
}
if (!descriptor) {
throw new Error(propertyName + " property does not exist");
}
if (!descriptor.configurable) {
throw new Error(propertyName + " is not declared configurable");
}
if (!descriptor[accessType]) {
throw new Error(
"Property " + propertyName + " does not have access type " + accessType
);
}
const original = descriptor[accessType];
if (!this.isMockFunction(original)) {
if (typeof original !== "function") {
throw new Error(
"Cannot spy the " + propertyName + " property because it is not a function; " + this._typeOf(original) + " given instead"
);
}
descriptor[accessType] = this._makeComponent(
{
type: "function"
},
() => {
descriptor[accessType] = original;
Object.defineProperty(obj, propertyName, descriptor);
}
);
descriptor[accessType].mockImplementation(function() {
return original.apply(this, arguments);
});
}
Object.defineProperty(obj, propertyName, descriptor);
return descriptor[accessType];
}
clearAllMocks() {
this._mockState = /* @__PURE__ */ new WeakMap();
}
resetAllMocks() {
this._mockConfigRegistry = /* @__PURE__ */ new WeakMap();
this._mockState = /* @__PURE__ */ new WeakMap();
}
restoreAllMocks() {
this._spyState.forEach((restore) => restore());
this._spyState = /* @__PURE__ */ new Set();
}
_typeOf(value) {
return value == null ? "" + value : typeof value;
}
mocked(item, _deep = false) {
return item;
}
};
exports.ModuleMocker = ModuleMocker;
var JestMock = new ModuleMocker(global);
var fn = JestMock.fn.bind(JestMock);
exports.fn = fn;
var spyOn = JestMock.spyOn.bind(JestMock);
exports.spyOn = spyOn;
var mocked2 = JestMock.mocked.bind(JestMock);
exports.mocked = mocked2;
}
});
// src/testUtils/index.ts
var testUtils_exports2 = {};
__export(testUtils_exports2, {
actHook: () => import_react_hooks.act,
mocked: () => import_jest_mock.mocked,
noop: () => noop,
render: () => customRender,
renderHook: () => import_react_hooks.renderHook,
renderJSON: () => renderJSON,
renderJSONAfterFirstAct: () => renderJSONAfterFirstAct,
userEvent: () => import_user_event.default
});
module.exports = __toCommonJS(testUtils_exports2);
// src/testUtils/testUtils.ts
var testUtils_exports = {};
__export(testUtils_exports, {
actHook: () => import_react_hooks.act,
mocked: () => import_jest_mock.mocked,
noop: () => noop,
render: () => customRender,
renderHook: () => import_react_hooks.renderHook,
renderJSON: () => renderJSON,
renderJSONAfterFirstAct: () => renderJSONAfterFirstAct,
userEvent: () => import_user_event.default
});
var import_extend_expect = require("@testing-library/jest-dom/extend-expect");
var import_react = require("@testing-library/react");
var import_react_test_renderer = __toESM(require("react-test-renderer"));
// ../../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.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, ""));
}
function camelToSnake(str) {
return 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_react_hooks = require("@testing-library/react-hooks");
var import_user_event = __toESM(require("@testing-library/user-event"));
var import_jest_mock = __toESM(require_build());
var customRender = (ui, options) => {
return (0, import_react.render)(ui, options);
};
var renderJSON = (c) => import_react_test_renderer.default.create(c).toJSON();
var renderJSONAfterFirstAct = (c) => {
let root;
import_react_test_renderer.default.act(() => {
root = import_react_test_renderer.default.create(c);
});
return root.toJSON();
};
// src/testUtils/index.ts
__reExport(testUtils_exports2, testUtils_exports, module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
actHook,
mocked,
noop,
render,
renderHook,
renderJSON,
renderJSONAfterFirstAct,
userEvent
});
/*! js-cookie v3.0.1 | MIT */
//# sourceMappingURL=index.js.map

6

package.json
{
"name": "@clerk/shared",
"version": "0.5.0",
"version": "0.5.1-staging.0",
"description": "Internal package utils used by the Clerk SDKs",

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

"devDependencies": {
"@clerk/types": "^3.15.0",
"@clerk/types": "^3.15.1-staging.0",
"@types/js-cookie": "^3.0.2",

@@ -41,3 +41,3 @@ "js-cookie": "^3.0.1",

"license": "ISC",
"gitHead": "c93fd33ad514a4c33109ee19cc644eba96c7bb11",
"gitHead": "8eb84ca6d3bcd7dacb9976f7df1a3034b419090a",
"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

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