@clerk/chrome-extension
Version:
Clerk SDK for Chrome extensions
4,393 lines • 152 kB
JavaScript
'use strict';
var React8 = require('react');
var index_js = require('use-sync-external-store/shim/index.js');
var reactDom = require('react-dom');
var noRhc = require('@clerk/clerk-js/no-rhc');
var browser = require('webextension-polyfill');
var jsxRuntime = require('react/jsx-runtime');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var React8__default = /*#__PURE__*/_interopDefault(React8);
var browser__default = /*#__PURE__*/_interopDefault(browser);
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// ../shared/dist/chunk-3EORDU4Z.mjs
var DefaultMessages = Object.freeze({
InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`,
InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`,
MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,
MissingSecretKeyErrorMessage: `Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,
MissingClerkProvider: `{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider`
});
function buildErrorThrower({ packageName, customMessages }) {
let pkg = packageName;
const messages = {
...DefaultMessages,
...customMessages
};
function buildMessage(rawMessage, replacements) {
if (!replacements) {
return `${pkg}: ${rawMessage}`;
}
let msg = rawMessage;
const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);
for (const match of matches) {
const replacement = (replacements[match[1]] || "").toString();
msg = msg.replace(`{{${match[1]}}}`, replacement);
}
return `${pkg}: ${msg}`;
}
return {
setPackageName({ packageName: packageName2 }) {
if (typeof packageName2 === "string") {
pkg = packageName2;
}
return this;
},
setMessages({ customMessages: customMessages2 }) {
Object.assign(messages, customMessages2 || {});
return this;
},
throwInvalidPublishableKeyError(params) {
throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params));
},
throwInvalidProxyUrl(params) {
throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params));
},
throwMissingPublishableKeyError() {
throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage));
},
throwMissingSecretKeyError() {
throw new Error(buildMessage(messages.MissingSecretKeyErrorMessage));
},
throwMissingClerkProviderError(params) {
throw new Error(buildMessage(messages.MissingClerkProvider, params));
},
throw(message) {
throw new Error(buildMessage(message));
}
};
}
// ../shared/dist/chunk-7ELT755Q.mjs
var __defProp2 = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export2 = (target, all) => {
for (var name in all)
__defProp2(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)
__defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
// ../shared/dist/chunk-TETGTEI2.mjs
var isomorphicAtob = (data) => {
if (typeof atob !== "undefined" && typeof atob === "function") {
return atob(data);
} else if (typeof global !== "undefined" && global.Buffer) {
return new global.Buffer(data, "base64").toString();
}
return data;
};
// ../shared/dist/chunk-G3VP5PJE.mjs
var PUBLISHABLE_KEY_LIVE_PREFIX = "pk_live_";
var PUBLISHABLE_KEY_TEST_PREFIX = "pk_test_";
function parsePublishableKey(key, options = {}) {
key = key || "";
if (!key || !isPublishableKey(key)) {
if (options.fatal && !key) {
throw new Error(
"Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys"
);
}
if (options.fatal && !isPublishableKey(key)) {
throw new Error("Publishable key not valid.");
}
return null;
}
const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? "production" : "development";
let frontendApi = isomorphicAtob(key.split("_")[2]);
frontendApi = frontendApi.slice(0, -1);
if (options.proxyUrl) {
frontendApi = options.proxyUrl;
} else if (instanceType !== "development" && options.domain) {
frontendApi = `clerk.${options.domain}`;
}
return {
instanceType,
frontendApi
};
}
function isPublishableKey(key = "") {
try {
const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);
const hasValidFrontendApiPostfix = isomorphicAtob(key.split("_")[2] || "").endsWith("$");
return hasValidPrefix && hasValidFrontendApiPostfix;
} catch {
return false;
}
}
// ../../node_modules/.pnpm/swr@2.2.5_react@18.3.1/node_modules/swr/dist/core/index.mjs
var core_exports = {};
__export(core_exports, {
SWRConfig: () => SWRConfig2,
default: () => useSWR,
mutate: () => mutate,
preload: () => preload,
unstable_serialize: () => unstable_serialize,
useSWRConfig: () => useSWRConfig
});
var noop2 = () => {
};
var UNDEFINED = (
/*#__NOINLINE__*/
noop2()
);
var OBJECT = Object;
var isUndefined = (v) => v === UNDEFINED;
var isFunction = (v) => typeof v == "function";
var mergeObjects = (a, b) => ({
...a,
...b
});
var isPromiseLike = (x) => isFunction(x.then);
var table = /* @__PURE__ */ new WeakMap();
var counter = 0;
var stableHash = (arg) => {
const type = typeof arg;
const constructor = arg && arg.constructor;
const isDate = constructor == Date;
let result;
let 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 = "#";
const 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 SWRGlobalState = /* @__PURE__ */ new WeakMap();
var EMPTY_CACHE = {};
var INITIAL_CACHE = {};
var STR_UNDEFINED = "undefined";
var isWindowDefined = typeof window != STR_UNDEFINED;
var isDocumentDefined = typeof document != STR_UNDEFINED;
var hasRequestAnimationFrame = () => isWindowDefined && typeof window["requestAnimationFrame"] != STR_UNDEFINED;
var createCacheHelper = (cache2, key) => {
const state = SWRGlobalState.get(cache2);
return [
// Getter
() => !isUndefined(key) && cache2.get(key) || EMPTY_CACHE,
// Setter
(info) => {
if (!isUndefined(key)) {
const prev = cache2.get(key);
if (!(key in INITIAL_CACHE)) {
INITIAL_CACHE[key] = prev;
}
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);
}
},
// Subscriber
state[6],
// Get server cache snapshot
() => {
if (!isUndefined(key)) {
if (key in INITIAL_CACHE) return INITIAL_CACHE[key];
}
return !isUndefined(key) && cache2.get(key) || EMPTY_CACHE;
}
];
};
var online = true;
var isOnline = () => online;
var [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [
window.addEventListener.bind(window),
window.removeEventListener.bind(window)
] : [
noop2,
noop2
];
var isVisible = () => {
const visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
};
var initFocus = (callback) => {
if (isDocumentDefined) {
document.addEventListener("visibilitychange", callback);
}
onWindowEvent("focus", callback);
return () => {
if (isDocumentDefined) {
document.removeEventListener("visibilitychange", callback);
}
offWindowEvent("focus", callback);
};
};
var initReconnect = (callback) => {
const onOnline = () => {
online = true;
callback();
};
const onOffline = () => {
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return () => {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
};
};
var preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_REACT_LEGACY = !React8__default.default.useId;
var IS_SERVER = !isWindowDefined || "Deno" in window;
var rAF = (f) => hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
var useIsomorphicLayoutEffect = IS_SERVER ? React8.useEffect : React8.useLayoutEffect;
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
var slowConnection = !IS_SERVER && navigatorConnection && ([
"slow-2g",
"2g"
].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var serialize = (key) => {
if (isFunction(key)) {
try {
key = key();
} catch (err) {
key = "";
}
}
const args = key;
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : "";
return [
key,
args
];
};
var __timestamp = 0;
var getTimestamp = () => ++__timestamp;
var FOCUS_EVENT = 0;
var RECONNECT_EVENT = 1;
var MUTATE_EVENT = 2;
var ERROR_REVALIDATE_EVENT = 3;
var events = {
__proto__: null,
ERROR_REVALIDATE_EVENT,
FOCUS_EVENT,
MUTATE_EVENT,
RECONNECT_EVENT
};
async function internalMutate(...args) {
const [cache2, _key, _data, _opts] = args;
const options = mergeObjects({
populateCache: true,
throwOnError: true
}, typeof _opts === "boolean" ? {
revalidate: _opts
} : _opts || {});
let populateCache = options.populateCache;
const rollbackOnErrorOption = options.rollbackOnError;
let optimisticData = options.optimisticData;
const rollbackOnError = (error) => {
return typeof rollbackOnErrorOption === "function" ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;
};
const throwOnError = options.throwOnError;
if (isFunction(_key)) {
const keyFilter = _key;
const matchedKeys = [];
const it = cache2.keys();
for (const key of it) {
if (
// Skip the special useSWRInfinite and useSWRSubscription keys.
!/^\$(inf|sub)\$/.test(key) && keyFilter(cache2.get(key)._k)
) {
matchedKeys.push(key);
}
}
return Promise.all(matchedKeys.map(mutateByKey));
}
return mutateByKey(_key);
async function mutateByKey(_k) {
const [key] = serialize(_k);
if (!key) return;
const [get, set] = createCacheHelper(cache2, key);
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache2);
const startRevalidate = () => {
const revalidators = EVENT_REVALIDATORS[key];
const revalidate = isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false;
if (revalidate) {
delete FETCH[key];
delete PRELOAD[key];
if (revalidators && revalidators[0]) {
return revalidators[0](MUTATE_EVENT).then(() => get().data);
}
}
return get().data;
};
if (args.length < 3) {
return startRevalidate();
}
let data = _data;
let error;
const beforeMutationTs = getTimestamp();
MUTATION[key] = [
beforeMutationTs,
0
];
const hasOptimisticData = !isUndefined(optimisticData);
const state = get();
const displayedData = state.data;
const currentData = state._c;
const committedData = isUndefined(currentData) ? displayedData : currentData;
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;
set({
data: optimisticData,
_c: committedData
});
}
if (isFunction(data)) {
try {
data = data(committedData);
} catch (err) {
error = err;
}
}
if (data && isPromiseLike(data)) {
data = await data.catch((err) => {
error = err;
});
if (beforeMutationTs !== MUTATION[key][0]) {
if (error) throw error;
return data;
} else if (error && hasOptimisticData && rollbackOnError(error)) {
populateCache = true;
set({
data: committedData,
_c: UNDEFINED
});
}
}
if (populateCache) {
if (!error) {
if (isFunction(populateCache)) {
const populateCachedData = populateCache(data, committedData);
set({
data: populateCachedData,
error: UNDEFINED,
_c: UNDEFINED
});
} else {
set({
data,
error: UNDEFINED,
_c: UNDEFINED
});
}
}
}
MUTATION[key][1] = getTimestamp();
Promise.resolve(startRevalidate()).then(() => {
set({
_c: UNDEFINED
});
});
if (error) {
if (throwOnError) throw error;
return;
}
return data;
}
}
var revalidateAllKeys = (revalidators, type) => {
for (const key in revalidators) {
if (revalidators[key][0]) revalidators[key][0](type);
}
};
var initCache = (provider, options) => {
if (!SWRGlobalState.has(provider)) {
const opts = mergeObjects(defaultConfigOptions, options);
const EVENT_REVALIDATORS = {};
const mutate2 = internalMutate.bind(UNDEFINED, provider);
let unmount = noop2;
const subscriptions = {};
const subscribe = (key, callback) => {
const subs = subscriptions[key] || [];
subscriptions[key] = subs;
subs.push(callback);
return () => subs.splice(subs.indexOf(callback), 1);
};
const setter = (key, value, prev) => {
provider.set(key, value);
const subs = subscriptions[key];
if (subs) {
for (const fn of subs) {
fn(value, prev);
}
}
};
const initProvider = () => {
if (!SWRGlobalState.has(provider)) {
SWRGlobalState.set(provider, [
EVENT_REVALIDATORS,
{},
{},
{},
mutate2,
setter,
subscribe
]);
if (!IS_SERVER) {
const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = () => {
releaseFocus && releaseFocus();
releaseReconnect && releaseReconnect();
SWRGlobalState.delete(provider);
};
}
}
};
initProvider();
return [
provider,
mutate2,
initProvider,
unmount
];
}
return [
provider,
SWRGlobalState.get(provider)[4]
];
};
var onErrorRetry = (_, __, config, revalidate, opts) => {
const maxRetryCount = config.errorRetryCount;
const currentRetryCount = opts.retryCount;
const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {
return;
}
setTimeout(revalidate, timeout, opts);
};
var compare = (currentData, newData) => stableHash(currentData) == stableHash(newData);
var [cache, mutate] = initCache(/* @__PURE__ */ new Map());
var defaultConfig = mergeObjects(
{
// events
onLoadingSlow: noop2,
onSuccess: noop2,
onError: noop2,
onErrorRetry,
onDiscarded: noop2,
// switches
revalidateOnFocus: true,
revalidateOnReconnect: true,
revalidateIfStale: true,
shouldRetryOnError: true,
// timeouts
errorRetryInterval: slowConnection ? 1e4 : 5e3,
focusThrottleInterval: 5 * 1e3,
dedupingInterval: 2 * 1e3,
loadingTimeout: slowConnection ? 5e3 : 3e3,
// providers
compare,
isPaused: () => false,
cache,
mutate,
fallback: {}
},
// use web preset by default
preset
);
var mergeConfigs = (a, b) => {
const v = mergeObjects(a, b);
if (b) {
const { use: u1, fallback: f1 } = a;
const { use: u2, fallback: f2 } = b;
if (u1 && u2) {
v.use = u1.concat(u2);
}
if (f1 && f2) {
v.fallback = mergeObjects(f1, f2);
}
}
return v;
};
var SWRConfigContext = React8.createContext({});
var SWRConfig = (props) => {
const { value } = props;
const parentConfig = React8.useContext(SWRConfigContext);
const isFunctionalConfig = isFunction(value);
const config = React8.useMemo(() => isFunctionalConfig ? value(parentConfig) : value, [
isFunctionalConfig,
parentConfig,
value
]);
const extendedConfig = React8.useMemo(() => isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [
isFunctionalConfig,
parentConfig,
config
]);
const provider = config && config.provider;
const cacheContextRef = React8.useRef(UNDEFINED);
if (provider && !cacheContextRef.current) {
cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);
}
const cacheContext = cacheContextRef.current;
if (cacheContext) {
extendedConfig.cache = cacheContext[0];
extendedConfig.mutate = cacheContext[1];
}
useIsomorphicLayoutEffect(() => {
if (cacheContext) {
cacheContext[2] && cacheContext[2]();
return cacheContext[3];
}
}, []);
return React8.createElement(SWRConfigContext.Provider, mergeObjects(props, {
value: extendedConfig
}));
};
var INFINITE_PREFIX = "$inf$";
var enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
var use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
var setupDevTools = () => {
if (enableDevtools) {
window.__SWR_DEVTOOLS_REACT__ = React8__default.default;
}
};
var normalize = (args) => {
return isFunction(args[1]) ? [
args[0],
args[1],
args[2] || {}
] : [
args[0],
null,
(args[1] === null ? args[2] : args[1]) || {}
];
};
var useSWRConfig = () => {
return mergeObjects(defaultConfig, React8.useContext(SWRConfigContext));
};
var preload = (key_, fetcher) => {
const [key, fnArg] = serialize(key_);
const [, , , PRELOAD] = SWRGlobalState.get(cache);
if (PRELOAD[key]) return PRELOAD[key];
const req = fetcher(fnArg);
PRELOAD[key] = req;
return req;
};
var middleware = (useSWRNext) => (key_, fetcher_, config) => {
const fetcher = fetcher_ && ((...args) => {
const [key] = serialize(key_);
const [, , , PRELOAD] = SWRGlobalState.get(cache);
if (key.startsWith(INFINITE_PREFIX)) {
return fetcher_(...args);
}
const req = PRELOAD[key];
if (isUndefined(req)) return fetcher_(...args);
delete PRELOAD[key];
return req;
});
return useSWRNext(key_, fetcher, config);
};
var BUILT_IN_MIDDLEWARE = use.concat(middleware);
var withArgs = (hook) => {
return function useSWRArgs(...args) {
const fallbackConfig = useSWRConfig();
const [key, fn, _config2] = normalize(args);
const config = mergeConfigs(fallbackConfig, _config2);
let next = hook;
const { use: use4 } = config;
const middleware2 = (use4 || []).concat(BUILT_IN_MIDDLEWARE);
for (let i = middleware2.length; i--; ) {
next = middleware2[i](next);
}
return next(key, fn || config.fetcher || null, config);
};
};
var subscribeCallback = (key, callbacks, callback) => {
const keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return () => {
const index = keyedRevalidators.indexOf(callback);
if (index >= 0) {
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
keyedRevalidators.pop();
}
};
};
var withMiddleware = (useSWR3, middleware2) => {
return (...args) => {
const [key, fn, config] = normalize(args);
const uses = (config.use || []).concat(middleware2);
return useSWR3(key, fn, {
...config,
use: uses
});
};
};
setupDevTools();
// ../../node_modules/.pnpm/swr@2.2.5_react@18.3.1/node_modules/swr/dist/core/index.mjs
var unstable_serialize = (key) => serialize(key)[0];
var use2 = React8__default.default.use || ((promise) => {
if (promise.status === "pending") {
throw promise;
} else if (promise.status === "fulfilled") {
return promise.value;
} else if (promise.status === "rejected") {
throw promise.reason;
} else {
promise.status = "pending";
promise.then((v) => {
promise.status = "fulfilled";
promise.value = v;
}, (e) => {
promise.status = "rejected";
promise.reason = e;
});
throw promise;
}
});
var WITH_DEDUPE = {
dedupe: true
};
var useSWRHandler = (_key, fetcher, config) => {
const { cache: cache2, compare: compare2, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config;
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache2);
const [key, fnArg] = serialize(_key);
const initialMountedRef = React8.useRef(false);
const unmountedRef = React8.useRef(false);
const keyRef = React8.useRef(key);
const fetcherRef = React8.useRef(fetcher);
const configRef = React8.useRef(config);
const getConfig = () => configRef.current;
const isActive = () => getConfig().isVisible() && getConfig().isOnline();
const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache2, key);
const stateDependencies = React8.useRef({}).current;
const fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
const isEqual = (prev, current) => {
for (const _ in stateDependencies) {
const t = _;
if (t === "data") {
if (!compare2(prev[t], current[t])) {
if (!isUndefined(prev[t])) {
return false;
}
if (!compare2(returnedData, current[t])) {
return false;
}
}
} else {
if (current[t] !== prev[t]) {
return false;
}
}
}
return true;
};
const getSnapshot = React8.useMemo(() => {
const shouldStartRequest = (() => {
if (!key) return false;
if (!fetcher) return false;
if (!isUndefined(revalidateOnMount)) return revalidateOnMount;
if (getConfig().isPaused()) return false;
if (suspense) return false;
if (!isUndefined(revalidateIfStale)) return revalidateIfStale;
return true;
})();
const getSelectedCache = (state) => {
const snapshot = mergeObjects(state);
delete snapshot._k;
if (!shouldStartRequest) {
return snapshot;
}
return {
isValidating: true,
isLoading: true,
...snapshot
};
};
const cachedData2 = getCache();
const initialData = getInitialCache();
const clientSnapshot = getSelectedCache(cachedData2);
const serverSnapshot = cachedData2 === initialData ? clientSnapshot : getSelectedCache(initialData);
let memorizedSnapshot = clientSnapshot;
return [
() => {
const newSnapshot = getSelectedCache(getCache());
const compareResult = isEqual(newSnapshot, memorizedSnapshot);
if (compareResult) {
memorizedSnapshot.data = newSnapshot.data;
memorizedSnapshot.isLoading = newSnapshot.isLoading;
memorizedSnapshot.isValidating = newSnapshot.isValidating;
memorizedSnapshot.error = newSnapshot.error;
return memorizedSnapshot;
} else {
memorizedSnapshot = newSnapshot;
return newSnapshot;
}
},
() => serverSnapshot
];
}, [
cache2,
key
]);
const cached = index_js.useSyncExternalStore(React8.useCallback(
(callback) => subscribeCache(key, (current, prev) => {
if (!isEqual(prev, current)) callback();
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[
cache2,
key
]
), getSnapshot[0], getSnapshot[1]);
const isInitialMount = !initialMountedRef.current;
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;
const cachedData = cached.data;
const data = isUndefined(cachedData) ? fallback : cachedData;
const error = cached.error;
const laggyDataRef = React8.useRef(data);
const returnedData = keepPreviousData ? isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
const shouldDoInitialRevalidation = (() => {
if (hasRevalidator && !isUndefined(error)) return false;
if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
if (getConfig().isPaused()) return false;
if (suspense) return isUndefined(data) ? false : revalidateIfStale;
return isUndefined(data) || revalidateIfStale;
})();
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
const revalidate = React8.useCallback(
async (revalidateOpts) => {
const currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return false;
}
let newData;
let startAt;
let loading = true;
const opts = revalidateOpts || {};
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
const callbackSafeguard = () => {
if (IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
}
return key === keyRef.current;
};
const finalState = {
isValidating: false,
isLoading: false
};
const finishRequestAndUpdateState = () => {
setCache(finalState);
};
const cleanupState = () => {
const requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
const initialState = {
isValidating: true
};
if (isUndefined(getCache().data)) {
initialState.isLoading = true;
}
try {
if (shouldStartNewRequest) {
setCache(initialState);
if (config.loadingTimeout && isUndefined(getCache().data)) {
setTimeout(() => {
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
FETCH[key] = [
currentFetcher(fnArg),
getTimestamp()
];
}
[newData, startAt] = FETCH[key];
newData = await newData;
if (shouldStartNewRequest) {
setTimeout(cleanupState, config.dedupingInterval);
}
if (!FETCH[key] || FETCH[key][1] !== startAt) {
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
finalState.error = UNDEFINED;
const mutationInfo = MUTATION[key];
if (!isUndefined(mutationInfo) && // case 1
(startAt <= mutationInfo[0] || // case 2
startAt <= mutationInfo[1] || // case 3
mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
const cacheData = getCache().data;
finalState.data = compare2(cacheData, newData) ? cacheData : newData;
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
} catch (err) {
cleanupState();
const currentConfig = getConfig();
const { shouldRetryOnError } = currentConfig;
if (!currentConfig.isPaused()) {
finalState.error = err;
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {
currentConfig.onErrorRetry(err, key, currentConfig, (_opts) => {
const revalidators = EVENT_REVALIDATORS[key];
if (revalidators && revalidators[0]) {
revalidators[0](events.ERROR_REVALIDATE_EVENT, _opts);
}
}, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
}
}
}
}
loading = false;
finishRequestAndUpdateState();
return true;
},
// `setState` is immutable, and `eventsCallback`, `fnArg`, and
// `keyValidating` are depending on `key`, so we can exclude them from
// the deps array.
//
// FIXME:
// `fn` and `config` might be changed during the lifecycle,
// but they might be changed every render like this.
// `useSWR('key', () => fetch('/api/'), { suspense: true })`
// So we omit the values from the deps array
// even though it might cause unexpected behaviors.
// eslint-disable-next-line react-hooks/exhaustive-deps
[
key,
cache2
]
);
const boundMutate = React8.useCallback(
// Use callback to make sure `keyRef.current` returns latest result every time
(...args) => {
return internalMutate(cache2, keyRef.current, ...args);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
useIsomorphicLayoutEffect(() => {
fetcherRef.current = fetcher;
configRef.current = config;
if (!isUndefined(cachedData)) {
laggyDataRef.current = cachedData;
}
});
useIsomorphicLayoutEffect(() => {
if (!key) return;
const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
let nextFocusRevalidatedAt = 0;
const onRevalidate = (type, opts = {}) => {
if (type == events.FOCUS_EVENT) {
const now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
softRevalidate();
}
} else if (type == events.RECONNECT_EVENT) {
if (getConfig().revalidateOnReconnect && isActive()) {
softRevalidate();
}
} else if (type == events.MUTATE_EVENT) {
return revalidate();
} else if (type == events.ERROR_REVALIDATE_EVENT) {
return revalidate(opts);
}
return;
};
const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
unmountedRef.current = false;
keyRef.current = key;
initialMountedRef.current = true;
setCache({
_k: fnArg
});
if (shouldDoInitialRevalidation) {
if (isUndefined(data) || IS_SERVER) {
softRevalidate();
} else {
rAF(softRevalidate);
}
}
return () => {
unmountedRef.current = true;
unsubEvents();
};
}, [
key
]);
useIsomorphicLayoutEffect(() => {
let timer;
function next() {
const interval = isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;
if (interval && timer !== -1) {
timer = setTimeout(execute, interval);
}
}
function execute() {
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {
revalidate(WITH_DEDUPE).then(next);
} else {
next();
}
}
next();
return () => {
if (timer) {
clearTimeout(timer);
timer = -1;
}
};
}, [
refreshInterval,
refreshWhenHidden,
refreshWhenOffline,
key
]);
React8.useDebugValue(returnedData);
if (suspense && isUndefined(data) && key) {
if (!IS_REACT_LEGACY && IS_SERVER) {
throw new Error("Fallback data is required when using suspense in SSR.");
}
fetcherRef.current = fetcher;
configRef.current = config;
unmountedRef.current = false;
const req = PRELOAD[key];
if (!isUndefined(req)) {
const promise = boundMutate(req);
use2(promise);
}
if (isUndefined(error)) {
const promise = revalidate(WITH_DEDUPE);
if (!isUndefined(returnedData)) {
promise.status = "fulfilled";
promise.value = true;
}
use2(promise);
} else {
throw error;
}
}
return {
mutate: boundMutate,
get data() {
stateDependencies.data = true;
return returnedData;
},
get error() {
stateDependencies.error = true;
return error;
},
get isValidating() {
stateDependencies.isValidating = true;
return isValidating;
},
get isLoading() {
stateDependencies.isLoading = true;
return isLoading;
}
};
};
var SWRConfig2 = OBJECT.defineProperty(SWRConfig, "defaultValue", {
value: defaultConfig
});
var useSWR = withArgs(useSWRHandler);
var use3 = React8__default.default.use || ((promise) => {
if (promise.status === "pending") {
throw promise;
} else if (promise.status === "fulfilled") {
return promise.value;
} else if (promise.status === "rejected") {
throw promise.reason;
} else {
promise.status = "pending";
promise.then((v) => {
promise.status = "fulfilled";
promise.value = v;
}, (e) => {
promise.status = "rejected";
promise.reason = e;
});
throw promise;
}
});
var WITH_DEDUPE2 = {
dedupe: true
};
var useSWRHandler2 = (_key, fetcher, config) => {
const { cache: cache2, compare: compare2, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config;
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache2);
const [key, fnArg] = serialize(_key);
const initialMountedRef = React8.useRef(false);
const unmountedRef = React8.useRef(false);
const keyRef = React8.useRef(key);
const fetcherRef = React8.useRef(fetcher);
const configRef = React8.useRef(config);
const getConfig = () => configRef.current;
const isActive = () => getConfig().isVisible() && getConfig().isOnline();
const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache2, key);
const stateDependencies = React8.useRef({}).current;
const fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
const isEqual = (prev, current) => {
for (const _ in stateDependencies) {
const t = _;
if (t === "data") {
if (!compare2(prev[t], current[t])) {
if (!isUndefined(prev[t])) {
return false;
}
if (!compare2(returnedData, current[t])) {
return false;
}
}
} else {
if (current[t] !== prev[t]) {
return false;
}
}
}
return true;
};
const getSnapshot = React8.useMemo(() => {
const shouldStartRequest = (() => {
if (!key) return false;
if (!fetcher) return false;
if (!isUndefined(revalidateOnMount)) return revalidateOnMount;
if (getConfig().isPaused()) return false;
if (suspense) return false;
if (!isUndefined(revalidateIfStale)) return revalidateIfStale;
return true;
})();
const getSelectedCache = (state) => {
const snapshot = mergeObjects(state);
delete snapshot._k;
if (!shouldStartRequest) {
return snapshot;
}
return {
isValidating: true,
isLoading: true,
...snapshot
};
};
const cachedData2 = getCache();
const initialData = getInitialCache();
const clientSnapshot = getSelectedCache(cachedData2);
const serverSnapshot = cachedData2 === initialData ? clientSnapshot : getSelectedCache(initialData);
let memorizedSnapshot = clientSnapshot;
return [
() => {
const newSnapshot = getSelectedCache(getCache());
const compareResult = isEqual(newSnapshot, memorizedSnapshot);
if (compareResult) {
memorizedSnapshot.data = newSnapshot.data;
memorizedSnapshot.isLoading = newSnapshot.isLoading;
memorizedSnapshot.isValidating = newSnapshot.isValidating;
memorizedSnapshot.error = newSnapshot.error;
return memorizedSnapshot;
} else {
memorizedSnapshot = newSnapshot;
return newSnapshot;
}
},
() => serverSnapshot
];
}, [
cache2,
key
]);
const cached = index_js.useSyncExternalStore(React8.useCallback(
(callback) => subscribeCache(key, (current, prev) => {
if (!isEqual(prev, current)) callback();
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[
cache2,
key
]
), getSnapshot[0], getSnapshot[1]);
const isInitialMount = !initialMountedRef.current;
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;
const cachedData = cached.data;
const data = isUndefined(cachedData) ? fallback : cachedData;
const error = cached.error;
const laggyDataRef = React8.useRef(data);
const returnedData = keepPreviousData ? isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
const shouldDoInitialRevalidation = (() => {
if (hasRevalidator && !isUndefined(error)) return false;
if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
if (getConfig().isPaused()) return false;
if (suspense) return isUndefined(data) ? false : revalidateIfStale;
return isUndefined(data) || revalidateIfStale;
})();
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
const revalidate = React8.useCallback(
async (revalidateOpts) => {
const currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return false;
}
let newData;
let startAt;
let loading = true;
const opts = revalidateOpts || {};
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
const callbackSafeguard = () => {
if (IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
}
return key === keyRef.current;
};
const finalState = {
isValidating: false,
isLoading: false
};
const finishRequestAndUpdateState = () => {
setCache(finalState);
};
const cleanupState = () => {
const requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
const initialState = {
isValidating: true
};
if (isUndefined(getCache().data)) {
initialState.isLoading = true;
}
try {
if (shouldStartNewRequest) {
setCache(initialState);
if (config.loadingTimeout && isUndefined(getCache().data)) {
setTimeout(() => {
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
FETCH[key] = [
currentFetcher(fnArg),
getTimestamp()
];
}
[newData, startAt] = FETCH[key];
newData = await newData;
if (shouldStartNewRequest) {
setTimeout(cleanupState, config.dedupingInterval);
}
if (!FETCH[key] || FETCH[key][1] !== startAt) {
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
finalState.error = UNDEFINED;
const mutationInfo = MUTATION[key];
if (!isUndefined(mutationInfo) && // case 1
(startAt <= mutationInfo[0] || // case 2
startAt <= mutationInfo[1] || // case 3
mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
const cacheData = getCache().data;
finalState.data = compare2(cacheData, newData) ? cacheData : newData;
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
} catch (err) {
cleanupState();
const currentConfig = getConfig();
const { shouldRetryOnError } = currentConfig;
if (!currentConfig.isPaused()) {
finalState.error = err;
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {
currentConfig.onErrorRetry(err, key, currentConfig, (_opts) => {
const revalidators = EVENT_REVALIDATORS[key];
if (revalidators && revalidators[0]) {
revalidators[0](events.ERROR_REVALIDATE_EVENT, _opts);
}
}, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
}
}
}
}
loading = false;
finishRequestAndUpdateState();
return true;
},
// `setState` is immutable, and `eventsCallback`, `fnArg`, and
// `keyValidating` are depending on `key`, so we can exclude them from
// the deps array.
//
// FIXME:
// `fn` and `config` might be changed during the lifecycle,
// but they might be changed every render like this.
// `useSWR('key', () => fetch('/api/'), { suspense: true })`
// So we omit the values from the deps array
// even though it might cause unexpected behaviors.
// eslint-disable-next-line react-hooks/exhaustive-deps
[
key,
cache2
]
);
const boundMutate = React8.useCallback(
// Use callback to make sure `keyRef.current` returns latest result every time
(...args) => {
return internalMutate(cache2, keyRef.current, ...args);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
useIsomorphicLayoutEffect(() => {
fetcherRef.current = fetcher;
configRef.current = config;
if (!isUndefined(cachedData)) {
laggyDataRef.current = cachedData;
}
});
useIsomorphicLayoutEffect(() => {
if (!key) return;
const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE2);
let nextFocusRevalidatedAt = 0;
const onRevalidate = (type, opts = {}) => {
if (type == events.FOCUS_EVENT) {
const now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
softRevalidate();
}
} else if (type == events.RECONNECT_EVENT) {
if (getConfig().revalidateOnReconnect && isActive()) {
softRevalidate();
}
} else if (type == events.MUTATE_EVENT) {
return revalidate();
} else if (type == events.ERROR_REVALIDATE_EVENT) {
return revalidate(opts);
}
return;
};
const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
unmountedRef.current = false;
keyRef.current = key;
initialMountedRef.current = true;
setCache({
_k: fnArg
});
if (shouldDoInitialRevalidation) {
if (isUndefined(data) || IS_SERVER) {
softRevalidate();
} else {
rAF(softRevalidate);
}
}
return () => {
unmountedRef.current = true;
unsubEvents();
};
}, [
key
]);
useIsomorphicLayoutEffect(() => {
let timer;
function next() {
const interval = isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;
if (interval && timer !== -1) {
timer = setTimeout(execute, interval);
}
}
function execute() {
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {
revalidate(WITH_DEDUPE2).then(next);
} else {
next();
}
}
next();
return () => {
if (timer) {
clearTimeout(timer);
timer = -1;
}
};
}, [
refreshInterval,
refreshWhenHidden,
refreshWhenOffline,
key
]);
React8.useDebugValue(returnedData);
if (suspense && isUndefined(data) && key) {
if (!IS_REACT_LEGACY && IS_SERVER) {
throw new Error("Fallback data is required when using suspense in SSR.");
}
fetcherRef.current = fetcher;
configRef.current = config;
unmountedRef.current = false;
const req = PRELOAD[key];
if (!isUndefined(req)) {
const promise = boundMutate(req);
use3(promise);
}
if (isUndefined(error)) {
const promise = revalidate(WITH_DEDUPE2);
if (!isUndefined(returnedData)) {
promise.status = "fulfilled";
promise.value = true;
}
use3(promise);
} else {
throw error;
}
}
return {
mutate: boundMutate,
get data() {
stateDependencies.data = true;
return returnedData;
},
get error() {
stateDependencies.error = true;
return error;
},
get isValidating() {
stateDependencies.isValidating = true;
return isValidating;
},
get isLoading() {
stateDependencies.isLoading = true;
return isLoading;
}
};
};
OBJECT.defineProperty(SWRConfig, "defaultValue", {
value: defaultConfig
});
var useSWR2 = withArgs(useSWRHandler2);
var getFirstPageKey = (getKey) => {
return serialize(getKey ? getKey(0, null) : null)[0];
};
var EMPTY_PROMISE = Promise.resolve();
var infinite = (useSWRNext) => (getKey, fn, config) => {
const didMountRef = React8.useRef(false);
const { cache: cache$1, initialSize = 1, revalidateAll = false, persistSize = false, revalidateFirstPage = true, revalidateOnMount = false, parallel = false } = config;
const [, , , PRELOAD] = SWRGlobalState.get(cache);
let infiniteKey;
try {
infiniteKey = getFirstPageKey(getKey);
if (infiniteKey) infiniteKey = INFINITE_PREFIX + infiniteKey;
} catch (err) {
}
const [get, set, subscribeCache] = createCacheHelper(cache$1, infiniteKey);
const getSnapshot = React8.useCallback(() => {
const size = isUndefined(get()._l) ? initialSize : get()._l;
return size;
}, [
cache$1,
infiniteKey,
initialSize
]);
index_js.useSyncExternalStore(React8.useCallback(
(callback) => {
if (infiniteKey) return subscribeCache(infiniteKey, () => {
callback();
});
return () => {
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[
cache$1,
infiniteKey
]
), getSnapshot, getSnapshot);
const resolvePageSize = React8.useCallback(() => {
const cachedPageSize = get()._l;
return isUndefined(cachedPageSize) ? initialSize : cachedPageSize;
}, [
infiniteKey,
initialSize
]);
const lastPageSizeRef = React8.useRef(resolvePageSize());
useIsomorphicLayoutEffect(() => {
if (!didMountRef.current) {
didMountRef.current = true;
return;
}
if (infiniteKey) {
set({
_l: persistSize ? lastPageSizeRef.current : resolvePageSize()
});
}
}, [
infiniteKey,
cache$1
]);
const shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current;
const swr = useSWRNext(infiniteKey, async (key) => {
const forceRevalidateAll = get()._i;
const shouldRevalidatePage = get()._r;
set({
_r: UNDEFINED
});
const data = [];
const pageSize = resolvePageSize();
const [getCache] = createCacheHelper(cache$1, key);
const cacheData = getCache().data;
const revalidators = [];
let previousPageData = null;
for (let i = 0; i < pageSize; ++i) {
const [pageKey, pageArg] = serialize(getKey(i, parallel ? null : previousPageData));
if (!pageKey) {
break;
}
const [getSWRCache, setSWRCache] = createCacheHelper(cache$1, pageKey);
let pageData = getSWRCache().data;
const shouldFetchPage = revalidateAll || forceRevalidateAll || isUndefined(pageData) || revalidateFirstPage && !i && !isUndefined(cacheData) || shouldRevalidateOnMount || cacheData && !isUndefined(cacheData[i]) && !config.compare(cacheData[i], pageData);
if (fn && (typeof shouldRevalidatePage === "function" ? shouldRevalidatePage(pageData, pageArg) : shouldFetchPage)) {
const revalidate = async () => {
const hasPreloadedRequest = pageKey in PRELOAD;
if (!hasPreloadedRequest) {
pageData = await fn(pageArg);
} else {
const req = PRELOAD[pageKey];
delete PRELOAD[pageKey];
pageData = await req;
}
setSWRCache({
data: pageData,
_k: pageArg
});
data[i] = pageData;
};
if (parallel) {
revalidators.push(revalidate);
} else {
await revalidate();
}
} else {
data[i] = pageData;
}
if (!parallel) {
previousPageData = pageData;
}
}
if (parallel) {
await Promise.all(revalidators.map((r) => r()));
}
set({
_i: UNDEFINED
});
return data;
}, config);
const mutate2 = React8.useCallback(
// eslint-disable-next-line func-names
function(data, opts) {
const options = typeof opts === "boolean" ? {
revalidate: opts
} : opts || {};
const shouldRevalidate = options.revalidate !== false;
if (!infiniteKey) return EMPTY_PROMISE;
if (shouldRevalidate) {
if (!isUndefined(data)) {
set({
_i: false,
_r: options.revalidate
});
} else {
set({
_i: true,
_r: options.revalidate
});
}
}
return arguments.length ? swr.mutate(data, {
...options,
revalidate: shouldRevalidate
}) : swr.mutate();
},
// swr.mutate is always the same reference
// eslint-disable-next-line react-hooks/exhaustive-deps
[
infiniteKey,
cache$1
]
);
const setSize = React8.useCallback(
(arg) => {
if (!infiniteKey) return EMPTY_PROMISE;
const [, changeSize] = createCacheHelper(cache$1, infiniteKey);
let size;
if (isFunction(arg)) {
size = arg(resolvePageSize());
} else if (typeof arg == "number") {
size = arg;
}
if (typeof size != "number") return EMPTY_PROMISE;
changeSize({
_l: size
});
lastPageSizeRef.current = size;
const data = [];
const [getInfiniteCache] = createCacheHelper(cache$1, infiniteKey);
let previousPageData = null;
for (let i = 0; i < size; ++i) {
const [pageKey] = serialize(getKey(i, previousPageData));
const [getCache] = createCacheHelper(cache$1, pageKey);
const pageData = pageKey ? getCache().data : UNDEFINED;
if (isUndefined(pageData)) {
return mutate2(getInfiniteCache().data);
}
data.push(pageData);
previousPageData = pageData;
}
return mutate2(data);
},
// exclude getKey from the dependencies, which isn't allowed to change during the lifecycle
// eslint-disable-next-line react-hooks/exhaustive-deps
[
infiniteKey,
cache$1,
mutate2,
resolvePageSize
]
);
return {
size: resolvePageSize(),
setSize,
mutate: mutate2,
get data() {
return swr.data;
},
get error() {
return swr.error;
},
get isValidating() {
return swr.isValidating;
},
get isLoading() {
return swr.isLoading;
}
};
};
var useSWRInfinite = withMiddleware(useSWR2, infinite);
// ../../node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/dist/index.mjs
var has = Object.prototype.hasOwnProperty;
function find(iter, tar, key) {
for (key of iter.keys()) {
if (dequal(key, tar)) return key;
}
}
function dequal(foo, bar) {
var ctor, len, tmp;
if (foo === bar) return true;
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
if (ctor === Date) return foo.getTime() === bar.getTime();
if (ctor === RegExp) return foo.toString() === bar.toString();
if (ctor === Array) {
if ((len = foo.length) === bar.length) {
while (len-- && dequal(foo[len], bar[len])) ;
}
return len === -1;
}
if (ctor === Set) {
if (foo.size !== bar.size) {
return false;
}
for (len of foo) {
tmp = len;
if (tmp && typeof tmp === "object") {
tmp = find(bar, tmp);
if (!tmp) return false;
}
if (!bar.has(tmp)) return false;
}
return true;
}
if (ctor === Map) {
if (foo.size !== bar.size) {
return false;
}
for (len of foo) {
tmp = len[0];
if (tmp && typeof tmp === "object") {
tmp = find(bar, tmp);
if (!tmp) return false;
}
if (!dequal(len[1], bar.get(tmp))) {
return false;
}
}
return true;
}
if (ctor === ArrayBuffer) {
foo = new Uint8Array(foo);
bar = new Uint8Array(bar);
} else if (ctor === DataView) {
if ((len = foo.byteLength) === bar.byteLength) {
while (len-- && foo.getInt8(len) === bar.getInt8(len)) ;
}
return len === -1;
}
if (ArrayBuffer.isView(foo)) {
if ((len = foo.byteLength) === bar.byteLength) {
while (len-- && foo[len] === bar[len]) ;
}
return len === -1;
}
if (!ctor || typeof foo === "object") {
len = 0;
for (ctor in foo) {
if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
}
return Object.keys(bar).length === len;
}
}
return foo !== foo && bar !== bar;
}
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 } = {};
const Ctx = React8__default.default.createContext(void 0);
Ctx.displayName = displayName;
const useCtx = () => {
const ctx = React8__default.default.useContext(Ctx);
assertCtxFn(ctx, `${displayName} not found`);
return ctx.value;
};
const useCtxWithoutGuarantee = () => {
const ctx = React8__default.default.useContext(Ctx);
return ctx ? ctx.value : {};
};
return [Ctx, useCtx, useCtxWithoutGuarantee];
};
var clerk_swr_exports = {};
__export2(clerk_swr_exports, {
useSWR: () => useSWR,
useSWRInfinite: () => useSWRInfinite
});
__reExport(clerk_swr_exports, core_exports);
var [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
var [UserContext, useUserContext] = createContextAndHook("UserContext");
var [ClientContext, useClientContext] = createContextAndHook("ClientContext");
var [SessionContext, useSessionContext] = createContextAndHook(
"SessionContext"
);
React8__default.default.createContext({});
var [OrganizationContextInternal, useOrganizationContext] = createContextAndHook("OrganizationContext");
var OrganizationProvider = ({
children,
organization,
swrConfig
}) => {
return /* @__PURE__ */ React8__default.default.createElement(clerk_swr_exports.SWRConfig, { value: swrConfig }, /* @__PURE__ */ React8__default.default.createElement(
OrganizationContextInternal.Provider,
{
value: {
value: { organization }
}
},
children
));
};
function useAssertWrappedByClerkProvider(displayNameOrFn) {
const ctx = React8__default.default.useContext(ClerkInstanceContext);
if (!ctx) {
if (typeof displayNameOrFn === "function") {
displayNameOrFn();
return;
}
throw new Error(
`${displayNameOrFn} can only be used within the <ClerkProvider /> component.
Possible fixes:
1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.
2. Check for multiple versions of the \`@clerk/shared\` package in your project. Use a tool like \`npm ls @clerk/shared\` to identify multiple versions, and update your dependencies to only rely on one.
Learn more: https://clerk.com/docs/components/clerk-provider`.trim()
);
}
}
typeof window !== "undefined" ? React8__default.default.useLayoutEffect : React8__default.default.useEffect;
var isDeeplyEqual = dequal;
// ../shared/dist/chunk-7HPDNZ3R.mjs
var isDevelopmentEnvironment = () => {
try {
return process.env.NODE_ENV === "development";
} catch {
}
return false;
};
var isTestEnvironment = () => {
try {
return process.env.NODE_ENV === "test";
} catch {
}
return false;
};
var isProductionEnvironment = () => {
try {
return process.env.NODE_ENV === "production";
} catch {
}
return false;
};
// ../shared/dist/chunk-UEY4AZIP.mjs
var displayedWarnings = /* @__PURE__ */ new Set();
var deprecated = (fnName, warning, key) => {
const hideWarning = isTestEnvironment() || isProductionEnvironment();
const messageId = fnName;
if (displayedWarnings.has(messageId) || hideWarning) {
return;
}
displayedWarnings.add(messageId);
console.warn(
`Clerk - DEPRECATION WARNING: "${fnName}" is deprecated and will be removed in the next major release.
${warning}`
);
};
var errorThrower = buildErrorThrower({ packageName: "@clerk/clerk-react" });
function setErrorThrowerOptions(options) {
errorThrower.setMessages(options).setPackageName(options);
}
var [AuthContext, useAuthContext] = createContextAndHook("AuthContext");
var IsomorphicClerkContext = ClerkInstanceContext;
var useIsomorphicClerkContext = useClerkInstanceContext;
var multipleClerkProvidersError = "You've added multiple <ClerkProvider> components in your React component tree. Wrap your components in a single <ClerkProvider>.";
var multipleChildrenInButtonComponent = (name) => `You've passed multiple children components to <${name}/>. You can only pass a single child component or text.`;
var unsupportedNonBrowserDomainOrProxyUrlFunction = "Unsupported usage of isSatellite, domain or proxyUrl. The usage of isSatellite, domain or proxyUrl as function is not supported in non-browser environments.";
var userProfilePageRenderedError = "<UserProfile.Page /> component needs to be a direct child of `<UserProfile />` or `<UserButton />`.";
var userProfileLinkRenderedError = "<UserProfile.Link /> component needs to be a direct child of `<UserProfile />` or `<UserButton />`.";
var organizationProfilePageRenderedError = "<OrganizationProfile.Page /> component needs to be a direct child of `<OrganizationProfile />` or `<OrganizationSwitcher />`.";
var organizationProfileLinkRenderedError = "<OrganizationProfile.Link /> component needs to be a direct child of `<OrganizationProfile />` or `<OrganizationSwitcher />`.";
var customPagesIgnoredComponent = (componentName) => `<${componentName} /> can only accept <${componentName}.Page /> and <${componentName}.Link /> as its children. Any other provided component will be ignored.`;
var customPageWrongProps = (componentName) => `Missing props. <${componentName}.Page /> component requires the following props: url, label, labelIcon, alongside with children to be rendered inside the page.`;
var customLinkWrongProps = (componentName) => `Missing props. <${componentName}.Link /> component requires the following props: url, label and labelIcon.`;
var userButtonIgnoredComponent = `<UserButton /> can only accept <UserButton.UserProfilePage />, <UserButton.UserProfileLink /> and <UserButton.MenuItems /> as its children. Any other provided component will be ignored.`;
var customMenuItemsIgnoredComponent = "<UserButton.MenuItems /> component can only accept <UserButton.Action /> and <UserButton.Link /> as its children. Any other provided component will be ignored.";
var userButtonMenuItemsRenderedError = "<UserButton.MenuItems /> component needs to be a direct child of `<UserButton />`.";
var userButtonMenuActionRenderedError = "<UserButton.Action /> component needs to be a direct child of `<UserButton.MenuItems />`.";
var userButtonMenuLinkRenderedError = "<UserButton.Link /> component needs to be a direct child of `<UserButton.MenuItems />`.";
var userButtonMenuItemLinkWrongProps = "Missing props. <UserButton.Link /> component requires the following props: href, label and labelIcon.";
var userButtonMenuItemsActionWrongsProps = "Missing props. <UserButton.Action /> component requires the following props: label.";
var useAssertWrappedByClerkProvider2 = (source) => {
useAssertWrappedByClerkProvider(() => {
errorThrower.throwMissingClerkProviderError({ source });
});
};
var withClerk = (Component, displayNameOrOptions) => {
const passedDisplayedName = typeof displayNameOrOptions === "string" ? displayNameOrOptions : displayNameOrOptions == null ? void 0 : displayNameOrOptions.component;
const displayName = passedDisplayedName || Component.displayName || Component.name || "Component";
Component.displayName = displayName;
const options = typeof displayNameOrOptions === "string" ? void 0 : displayNameOrOptions;
const HOC = (props) => {
useAssertWrappedByClerkProvider2(displayName || "withClerk");
const clerk2 = useIsomorphicClerkContext();
if (!clerk2.loaded && !(options == null ? void 0 : options.renderWhileLoading)) {
return null;
}
return /* @__PURE__ */ React8__default.default.createElement(
Component,
{
...props,
component: displayName,
clerk: clerk2
}
);
};
HOC.displayName = `withClerk(${displayName})`;
return HOC;
};
withClerk(({ clerk: clerk2, ...props }) => {
const { client, session } = clerk2;
const hasSignedInSessions = client.signedInSessions ? client.signedInSessions.length > 0 : (
// Compat for clerk-js<5.54.0 (which was released with the `signedInSessions` property)
client.activeSessions && client.activeSessions.length > 0
);
React8__default.default.useEffect(() => {
if (session === null && hasSignedInSessions) {
void clerk2.redirectToAfterSignOut();
} else {
void clerk2.redirectToSignIn(props);
}
}, []);
return null;
}, "RedirectToSignIn");
withClerk(({ clerk: clerk2, ...props }) => {
React8__default.default.useEffect(() => {
void clerk2.redirectToSignUp(props);
}, []);
return null;
}, "RedirectToSignUp");
withClerk(({ clerk: clerk2 }) => {
React8__default.default.useEffect(() => {
deprecated("RedirectToUserProfile", "Use the `redirectToUserProfile()` method instead.");
void clerk2.redirectToUserProfile();
}, []);
return null;
}, "RedirectToUserProfile");
withClerk(({ clerk: clerk2 }) => {
React8__default.default.useEffect(() => {
deprecated("RedirectToOrganizationProfile", "Use the `redirectToOrganizationProfile()` method instead.");
void clerk2.redirectToOrganizationProfile();
}, []);
return null;
}, "RedirectToOrganizationProfile");
withClerk(({ clerk: clerk2 }) => {
React8__default.default.useEffect(() => {
deprecated("RedirectToCreateOrganization", "Use the `redirectToCreateOrganization()` method instead.");
void clerk2.redirectToCreateOrganization();
}, []);
return null;
}, "RedirectToCreateOrganization");
withClerk(
({ clerk: clerk2, ...handleRedirectCallbackParams }) => {
React8__default.default.useEffect(() => {
void clerk2.handleRedirectCallback(handleRedirectCallbackParams);
}, []);
return null;
},
"AuthenticateWithRedirectCallback"
);
// ../react/dist/chunk-OANWQR3B.mjs
var __typeError2 = (msg) => {
throw TypeError(msg);
};
var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet2 = (obj, member, value, setter) => (__accessCheck2(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod2 = (obj, member, method) => (__accessCheck2(obj, member, "access private method"), method);
var errorThrower2 = buildErrorThrower({ packageName: "@clerk/shared" });
function setClerkJsLoadingErrorPackageName(packageName) {
errorThrower2.setPackageName({ packageName });
}
// ../shared/dist/chunk-3QKZJFQO.mjs
var logErrorInDevMode = (message) => {
if (isDevelopmentEnvironment()) {
console.error(`Clerk: ${message}`);
}
};
// ../shared/dist/chunk-O32JQBM6.mjs
function handleValueOrFn(value, url, defaultValue) {
if (typeof value === "function") {
return value(url);
}
if (typeof value !== "undefined") {
return value;
}
if (typeof defaultValue !== "undefined") {
return defaultValue;
}
return void 0;
}
// ../shared/dist/chunk-CFXQSUF6.mjs
var without = (obj, ...props) => {
const copy = { ...obj };
for (const prop of props) {
delete copy[prop];
}
return copy;
};
// ../shared/dist/chunk-2GBZREM5.mjs
var deriveState = (clerkLoaded, state, initialState) => {
if (!clerkLoaded && initialState) {
return deriveFromSsrInitialState(initialState);
}
return deriveFromClientSideState(state);
};
var deriveFromSsrInitialState = (initialState) => {
const userId = initialState.userId;
const user = initialState.user;
const sessionId = initialState.sessionId;
const sessionStatus = initialState.sessionStatus;
const session = initialState.session;
const organization = initialState.organization;
const orgId = initialState.orgId;
const orgRole = initialState.orgRole;
const orgPermissions = initialState.orgPermissions;
const orgSlug = initialState.orgSlug;
const actor = initialState.actor;
const factorVerificationAge = initialState.factorVerificationAge;
return {
userId,
user,
sessionId,
session,
sessionStatus,
organization,
orgId,
orgRole,
orgPermissions,
orgSlug,
actor,
factorVerificationAge
};
};
var deriveFromClientSideState = (state) => {
var _a, _b;
const userId = state.user ? state.user.id : state.user;
const user = state.user;
const sessionId = state.session ? state.session.id : state.session;
const session = state.session;
const sessionStatus = (_a = state.session) == null ? void 0 : _a.status;
const factorVerificationAge = state.session ? state.session.factorVerificationAge : null;
const actor = session == null ? void 0 : session.actor;
const organization = state.organization;
const orgId = state.organization ? state.organization.id : state.organization;
const orgSlug = organization == null ? void 0 : organization.slug;
const membership = organization ? (_b = user == null ? void 0 : user.organizationMemberships) == null ? void 0 : _b.find((om) => om.organization.id === orgId) : organization;
const orgPermissions = membership ? membership.permissions : membership;
const orgRole = membership ? membership.role : membership;
return {
userId,
user,
sessionId,
session,
sessionStatus,
organization,
orgId,
orgRole,
orgSlug,
orgPermissions,
actor,
factorVerificationAge
};
};
// ../shared/dist/chunk-JKSAJ6AV.mjs
function inBrowser() {
return typeof window !== "undefined";
}
// ../react/dist/index.mjs
if (typeof window !== "undefined" && !window.global) {
window.global = typeof global === "undefined" ? window : global;
}
var assertSingleChild = (children) => (name) => {
try {
return React8__default.default.Children.only(children);
} catch {
return errorThrower.throw(multipleChildrenInButtonComponent(name));
}
};
var normalizeWithDefaultValue = (children, defaultText) => {
if (!children) {
children = defaultText;
}
if (typeof children === "string") {
children = /* @__PURE__ */ React8__default.default.createElement("button", null, children);
}
return children;
};
var safeExecute = (cb) => (...args) => {
if (cb && typeof cb === "function") {
return cb(...args);
}
};
function isConstructor(f) {
return typeof f === "function";
}
var counts = /* @__PURE__ */ new Map();
function useMaxAllowedInstancesGuard(name, error, maxCount = 1) {
React8__default.default.useEffect(() => {
const count = counts.get(name) || 0;
if (count == maxCount) {
return errorThrower.throw(error);
}
counts.set(name, count + 1);
return () => {
counts.set(name, (counts.get(name) || 1) - 1);
};
}, []);
}
function withMaxAllowedInstancesGuard(WrappedComponent, name, error) {
const displayName = WrappedComponent.displayName || WrappedComponent.name || name || "Component";
const Hoc = (props) => {
useMaxAllowedInstancesGuard(name, error);
return /* @__PURE__ */ React8__default.default.createElement(WrappedComponent, { ...props });
};
Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;
return Hoc;
}
var useCustomElementPortal = (elements) => {
const initialState = Array(elements.length).fill(null);
const [nodes, setNodes] = React8.useState(initialState);
return elements.map((el, index) => ({
id: el.id,
mount: (node) => setNodes((prevState) => prevState.map((n, i) => i === index ? node : n)),
unmount: () => setNodes((prevState) => prevState.map((n, i) => i === index ? null : n)),
portal: () => /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, nodes[index] ? reactDom.createPortal(el.component, nodes[index]) : null)
}));
};
var isThatComponent = (v, component) => {
return !!v && React8__default.default.isValidElement(v) && (v == null ? void 0 : v.type) === component;
};
var useUserProfileCustomPages = (children, options) => {
const reorderItemsLabels = ["account", "security"];
return useCustomPages(
{
children,
reorderItemsLabels,
LinkComponent: UserProfileLink,
PageComponent: UserProfilePage,
MenuItemsComponent: MenuItems,
componentName: "UserProfile"
},
options
);
};
var useOrganizationProfileCustomPages = (children, options) => {
const reorderItemsLabels = ["general", "members"];
return useCustomPages(
{
children,
reorderItemsLabels,
LinkComponent: OrganizationProfileLink,
PageComponent: OrganizationProfilePage,
componentName: "OrganizationProfile"
},
options
);
};
var useSanitizedChildren = (children) => {
const sanitizedChildren = [];
const excludedComponents = [
OrganizationProfileLink,
OrganizationProfilePage,
MenuItems,
UserProfilePage,
UserProfileLink
];
React8__default.default.Children.forEach(children, (child) => {
if (!excludedComponents.some((component) => isThatComponent(child, component))) {
sanitizedChildren.push(child);
}
});
return sanitizedChildren;
};
var useCustomPages = (params, options) => {
const { children, LinkComponent, PageComponent, MenuItemsComponent, reorderItemsLabels, componentName } = params;
const { allowForAnyChildren = false } = options || {};
const validChildren = [];
React8__default.default.Children.forEach(children, (child) => {
if (!isThatComponent(child, PageComponent) && !isThatComponent(child, LinkComponent) && !isThatComponent(child, MenuItemsComponent)) {
if (child && !allowForAnyChildren) {
logErrorInDevMode(customPagesIgnoredComponent(componentName));
}
return;
}
const { props } = child;
const { children: children2, label, url, labelIcon } = props;
if (isThatComponent(child, PageComponent)) {
if (isReorderItem(props, reorderItemsLabels)) {
validChildren.push({ label });
} else if (isCustomPage(props)) {
validChildren.push({ label, labelIcon, children: children2, url });
} else {
logErrorInDevMode(customPageWrongProps(componentName));
return;
}
}
if (isThatComponent(child, LinkComponent)) {
if (isExternalLink(props)) {
validChildren.push({ label, labelIcon, url });
} else {
logErrorInDevMode(customLinkWrongProps(componentName));
return;
}
}
});
const customPageContents = [];
const customPageLabelIcons = [];
const customLinkLabelIcons = [];
validChildren.forEach((cp, index) => {
if (isCustomPage(cp)) {
customPageContents.push({ component: cp.children, id: index });
customPageLabelIcons.push({ component: cp.labelIcon, id: index });
return;
}
if (isExternalLink(cp)) {
customLinkLabelIcons.push({ component: cp.labelIcon, id: index });
}
});
const customPageContentsPortals = useCustomElementPortal(customPageContents);
const customPageLabelIconsPortals = useCustomElementPortal(customPageLabelIcons);
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);
const customPages = [];
const customPagesPortals = [];
validChildren.forEach((cp, index) => {
if (isReorderItem(cp, reorderItemsLabels)) {
customPages.push({ label: cp.label });
return;
}
if (isCustomPage(cp)) {
const {
portal: contentPortal,
mount,
unmount
} = customPageContentsPortals.find((p) => p.id === index);
const {
portal: labelPortal,
mount: mountIcon,
unmount: unmountIcon
} = customPageLabelIconsPortals.find((p) => p.id === index);
customPages.push({ label: cp.label, url: cp.url, mount, unmount, mountIcon, unmountIcon });
customPagesPortals.push(contentPortal);
customPagesPortals.push(labelPortal);
return;
}
if (isExternalLink(cp)) {
const {
portal: labelPortal,
mount: mountIcon,
unmount: unmountIcon
} = customLinkLabelIconsPortals.find((p) => p.id === index);
customPages.push({ label: cp.label, url: cp.url, mountIcon, unmountIcon });
customPagesPortals.push(labelPortal);
return;
}
});
return { customPages, customPagesPortals };
};
var isReorderItem = (childProps, validItems) => {
const { children, label, url, labelIcon } = childProps;
return !children && !url && !labelIcon && validItems.some((v) => v === label);
};
var isCustomPage = (childProps) => {
const { children, label, url, labelIcon } = childProps;
return !!children && !!url && !!labelIcon && !!label;
};
var isExternalLink = (childProps) => {
const { children, label, url, labelIcon } = childProps;
return !children && !!url && !!labelIcon && !!label;
};
var useUserButtonCustomMenuItems = (children) => {
const reorderItemsLabels = ["manageAccount", "signOut"];
return useCustomMenuItems({
children,
reorderItemsLabels,
MenuItemsComponent: MenuItems,
MenuActionComponent: MenuAction,
MenuLinkComponent: MenuLink,
UserProfileLinkComponent: UserProfileLink,
UserProfilePageComponent: UserProfilePage
});
};
var useCustomMenuItems = ({
children,
MenuItemsComponent,
MenuActionComponent,
MenuLinkComponent,
UserProfileLinkComponent,
UserProfilePageComponent,
reorderItemsLabels
}) => {
const validChildren = [];
const customMenuItems = [];
const customMenuItemsPortals = [];
React8__default.default.Children.forEach(children, (child) => {
if (!isThatComponent(child, MenuItemsComponent) && !isThatComponent(child, UserProfileLinkComponent) && !isThatComponent(child, UserProfilePageComponent)) {
if (child) {
logErrorInDevMode(userButtonIgnoredComponent);
}
return;
}
if (isThatComponent(child, UserProfileLinkComponent) || isThatComponent(child, UserProfilePageComponent)) {
return;
}
const { props } = child;
React8__default.default.Children.forEach(props.children, (child2) => {
if (!isThatComponent(child2, MenuActionComponent) && !isThatComponent(child2, MenuLinkComponent)) {
if (child2) {
logErrorInDevMode(customMenuItemsIgnoredComponent);
}
return;
}
const { props: props2 } = child2;
const { label, labelIcon, href, onClick, open } = props2;
if (isThatComponent(child2, MenuActionComponent)) {
if (isReorderItem2(props2, reorderItemsLabels)) {
validChildren.push({ label });
} else if (isCustomMenuItem(props2)) {
const baseItem = {
label,
labelIcon
};
if (onClick !== void 0) {
validChildren.push({
...baseItem,
onClick
});
} else if (open !== void 0) {
validChildren.push({
...baseItem,
open: open.startsWith("/") ? open : `/${open}`
});
} else {
logErrorInDevMode("Custom menu item must have either onClick or open property");
return;
}
} else {
logErrorInDevMode(userButtonMenuItemsActionWrongsProps);
return;
}
}
if (isThatComponent(child2, MenuLinkComponent)) {
if (isExternalLink2(props2)) {
validChildren.push({ label, labelIcon, href });
} else {
logErrorInDevMode(userButtonMenuItemLinkWrongProps);
return;
}
}
});
});
const customMenuItemLabelIcons = [];
const customLinkLabelIcons = [];
validChildren.forEach((mi, index) => {
if (isCustomMenuItem(mi)) {
customMenuItemLabelIcons.push({ component: mi.labelIcon, id: index });
}
if (isExternalLink2(mi)) {
customLinkLabelIcons.push({ component: mi.labelIcon, id: index });
}
});
const customMenuItemLabelIconsPortals = useCustomElementPortal(customMenuItemLabelIcons);
const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);
validChildren.forEach((mi, index) => {
if (isReorderItem2(mi, reorderItemsLabels)) {
customMenuItems.push({
label: mi.label
});
}
if (isCustomMenuItem(mi)) {
const {
portal: iconPortal,
mount: mountIcon,
unmount: unmountIcon
} = customMenuItemLabelIconsPortals.find((p) => p.id === index);
const menuItem = {
label: mi.label,
mountIcon,
unmountIcon
};
if ("onClick" in mi) {
menuItem.onClick = mi.onClick;
} else if ("open" in mi) {
menuItem.open = mi.open;
}
customMenuItems.push(menuItem);
customMenuItemsPortals.push(iconPortal);
}
if (isExternalLink2(mi)) {
const {
portal: iconPortal,
mount: mountIcon,
unmount: unmountIcon
} = customLinkLabelIconsPortals.find((p) => p.id === index);
customMenuItems.push({
label: mi.label,
href: mi.href,
mountIcon,
unmountIcon
});
customMenuItemsPortals.push(iconPortal);
}
});
return { customMenuItems, customMenuItemsPortals };
};
var isReorderItem2 = (childProps, validItems) => {
const { children, label, onClick, labelIcon } = childProps;
return !children && !onClick && !labelIcon && validItems.some((v) => v === label);
};
var isCustomMenuItem = (childProps) => {
const { label, labelIcon, onClick, open } = childProps;
return !!labelIcon && !!label && (typeof onClick === "function" || typeof open === "string");
};
var isExternalLink2 = (childProps) => {
const { label, href, labelIcon } = childProps;
return !!href && !!labelIcon && !!label;
};
function waitForElementChildren(options) {
const { root = document == null ? void 0 : document.body, selector, timeout = 0 } = options;
return new Promise((resolve, reject) => {
if (!root) {
reject(new Error("No root element provided"));
return;
}
let elementToWatch = root;
if (selector) {
elementToWatch = root == null ? void 0 : root.querySelector(selector);
}
const isElementAlreadyPresent = (elementToWatch == null ? void 0 : elementToWatch.childElementCount) && elementToWatch.childElementCount > 0;
if (isElementAlreadyPresent) {
resolve();
return;
}
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
if (!elementToWatch && selector) {
elementToWatch = root == null ? void 0 : root.querySelector(selector);
}
if ((elementToWatch == null ? void 0 : elementToWatch.childElementCount) && elementToWatch.childElementCount > 0) {
observer.disconnect();
resolve();
return;
}
}
}
});
observer.observe(root, { childList: true, subtree: true });
if (timeout > 0) {
setTimeout(() => {
observer.disconnect();
reject(new Error(`Timeout waiting for element children`));
}, timeout);
}
});
}
function useWaitForComponentMount(component) {
const watcherRef = React8.useRef();
const [status, setStatus] = React8.useState("rendering");
React8.useEffect(() => {
if (!component) {
throw new Error("Clerk: no component name provided, unable to detect mount.");
}
if (typeof window !== "undefined" && !watcherRef.current) {
watcherRef.current = waitForElementChildren({ selector: `[data-clerk-component="${component}"]` }).then(() => {
setStatus("rendered");
}).catch(() => {
setStatus("error");
});
}
}, [component]);
return status;
}
var isMountProps = (props) => {
return "mount" in props;
};
var isOpenProps = (props) => {
return "open" in props;
};
var stripMenuItemIconHandlers = (menuItems) => {
return menuItems == null ? void 0 : menuItems.map(({ mountIcon, unmountIcon, ...rest }) => rest);
};
var ClerkHostRenderer = class extends React8__default.default.PureComponent {
constructor() {
super(...arguments);
this.rootRef = React8__default.default.createRef();
}
componentDidUpdate(_prevProps) {
var _a, _b, _c, _d;
if (!isMountProps(_prevProps) || !isMountProps(this.props)) {
return;
}
const prevProps = without(_prevProps.props, "customPages", "customMenuItems", "children");
const newProps = without(this.props.props, "customPages", "customMenuItems", "children");
const customPagesChanged = ((_a = prevProps.customPages) == null ? void 0 : _a.length) !== ((_b = newProps.customPages) == null ? void 0 : _b.length);
const customMenuItemsChanged = ((_c = prevProps.customMenuItems) == null ? void 0 : _c.length) !== ((_d = newProps.customMenuItems) == null ? void 0 : _d.length);
const prevMenuItemsWithoutHandlers = stripMenuItemIconHandlers(_prevProps.props.customMenuItems);
const newMenuItemsWithoutHandlers = stripMenuItemIconHandlers(this.props.props.customMenuItems);
if (!isDeeplyEqual(prevProps, newProps) || !isDeeplyEqual(prevMenuItemsWithoutHandlers, newMenuItemsWithoutHandlers) || customPagesChanged || customMenuItemsChanged) {
if (this.rootRef.current) {
this.props.updateProps({ node: this.rootRef.current, props: this.props.props });
}
}
}
componentDidMount() {
if (this.rootRef.current) {
if (isMountProps(this.props)) {
this.props.mount(this.rootRef.current, this.props.props);
}
if (isOpenProps(this.props)) {
this.props.open(this.props.props);
}
}
}
componentWillUnmount() {
if (this.rootRef.current) {
if (isMountProps(this.props)) {
this.props.unmount(this.rootRef.current);
}
if (isOpenProps(this.props)) {
this.props.close();
}
}
}
render() {
const { hideRootHtmlElement = false } = this.props;
const rootAttributes = {
ref: this.rootRef,
...this.props.rootProps,
...this.props.component && { "data-clerk-component": this.props.component }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, !hideRootHtmlElement && /* @__PURE__ */ React8__default.default.createElement("div", { ...rootAttributes }), this.props.children);
}
};
var CustomPortalsRenderer = (props) => {
var _a, _b;
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, (_a = props == null ? void 0 : props.customPagesPortals) == null ? void 0 : _a.map((portal, index) => React8.createElement(portal, { key: index })), (_b = props == null ? void 0 : props.customMenuItemsPortals) == null ? void 0 : _b.map((portal, index) => React8.createElement(portal, { key: index })));
};
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountSignIn,
unmount: clerk2.unmountSignIn,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "SignIn", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountSignUp,
unmount: clerk2.unmountSignUp,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "SignUp", renderWhileLoading: true }
);
function UserProfilePage({ children }) {
logErrorInDevMode(userProfilePageRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
function UserProfileLink({ children }) {
logErrorInDevMode(userProfileLinkRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
var _UserProfile = withClerk(
({
clerk: clerk2,
component,
fallback,
...props
}) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
const { customPages, customPagesPortals } = useUserProfileCustomPages(props.children);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountUserProfile,
unmount: clerk2.unmountUserProfile,
updateProps: clerk2.__unstable__updateProps,
props: { ...props, customPages },
rootProps: rendererRootProps
},
/* @__PURE__ */ React8__default.default.createElement(CustomPortalsRenderer, { customPagesPortals })
));
},
{ component: "UserProfile", renderWhileLoading: true }
);
Object.assign(_UserProfile, {
Page: UserProfilePage,
Link: UserProfileLink
});
var UserButtonContext = React8.createContext({
mount: () => {
},
unmount: () => {
},
updateProps: () => {
}
});
var _UserButton = withClerk(
({
clerk: clerk2,
component,
fallback,
...props
}) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
const { customPages, customPagesPortals } = useUserProfileCustomPages(props.children, {
allowForAnyChildren: !!props.__experimental_asProvider
});
const userProfileProps = Object.assign(props.userProfileProps || {}, { customPages });
const { customMenuItems, customMenuItemsPortals } = useUserButtonCustomMenuItems(props.children);
const sanitizedChildren = useSanitizedChildren(props.children);
const passableProps = {
mount: clerk2.mountUserButton,
unmount: clerk2.unmountUserButton,
updateProps: clerk2.__unstable__updateProps,
props: { ...props, userProfileProps, customMenuItems }
};
const portalProps = {
customPagesPortals,
customMenuItemsPortals
};
return /* @__PURE__ */ React8__default.default.createElement(UserButtonContext.Provider, { value: passableProps }, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
...passableProps,
hideRootHtmlElement: !!props.__experimental_asProvider,
rootProps: rendererRootProps
},
props.__experimental_asProvider ? sanitizedChildren : null,
/* @__PURE__ */ React8__default.default.createElement(CustomPortalsRenderer, { ...portalProps })
));
},
{ component: "UserButton", renderWhileLoading: true }
);
function MenuItems({ children }) {
logErrorInDevMode(userButtonMenuItemsRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
function MenuAction({ children }) {
logErrorInDevMode(userButtonMenuActionRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
function MenuLink({ children }) {
logErrorInDevMode(userButtonMenuLinkRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
function UserButtonOutlet(outletProps) {
const providerProps = React8.useContext(UserButtonContext);
const portalProps = {
...providerProps,
props: {
...providerProps.props,
...outletProps
}
};
return /* @__PURE__ */ React8__default.default.createElement(ClerkHostRenderer, { ...portalProps });
}
Object.assign(_UserButton, {
UserProfilePage,
UserProfileLink,
MenuItems,
Action: MenuAction,
Link: MenuLink,
__experimental_Outlet: UserButtonOutlet
});
function OrganizationProfilePage({ children }) {
logErrorInDevMode(organizationProfilePageRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
function OrganizationProfileLink({ children }) {
logErrorInDevMode(organizationProfileLinkRenderedError);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, children);
}
var _OrganizationProfile = withClerk(
({
clerk: clerk2,
component,
fallback,
...props
}) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(props.children);
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountOrganizationProfile,
unmount: clerk2.unmountOrganizationProfile,
updateProps: clerk2.__unstable__updateProps,
props: { ...props, customPages },
rootProps: rendererRootProps
},
/* @__PURE__ */ React8__default.default.createElement(CustomPortalsRenderer, { customPagesPortals })
));
},
{ component: "OrganizationProfile", renderWhileLoading: true }
);
Object.assign(_OrganizationProfile, {
Page: OrganizationProfilePage,
Link: OrganizationProfileLink
});
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountCreateOrganization,
unmount: clerk2.unmountCreateOrganization,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "CreateOrganization", renderWhileLoading: true }
);
var OrganizationSwitcherContext = React8.createContext({
mount: () => {
},
unmount: () => {
},
updateProps: () => {
}
});
var _OrganizationSwitcher = withClerk(
({
clerk: clerk2,
component,
fallback,
...props
}) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(props.children, {
allowForAnyChildren: !!props.__experimental_asProvider
});
const organizationProfileProps = Object.assign(props.organizationProfileProps || {}, { customPages });
const sanitizedChildren = useSanitizedChildren(props.children);
const passableProps = {
mount: clerk2.mountOrganizationSwitcher,
unmount: clerk2.unmountOrganizationSwitcher,
updateProps: clerk2.__unstable__updateProps,
props: { ...props, organizationProfileProps },
rootProps: rendererRootProps,
component
};
clerk2.__experimental_prefetchOrganizationSwitcher();
return /* @__PURE__ */ React8__default.default.createElement(OrganizationSwitcherContext.Provider, { value: passableProps }, /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
...passableProps,
hideRootHtmlElement: !!props.__experimental_asProvider
},
props.__experimental_asProvider ? sanitizedChildren : null,
/* @__PURE__ */ React8__default.default.createElement(CustomPortalsRenderer, { customPagesPortals })
)));
},
{ component: "OrganizationSwitcher", renderWhileLoading: true }
);
function OrganizationSwitcherOutlet(outletProps) {
const providerProps = React8.useContext(OrganizationSwitcherContext);
const portalProps = {
...providerProps,
props: {
...providerProps.props,
...outletProps
}
};
return /* @__PURE__ */ React8__default.default.createElement(ClerkHostRenderer, { ...portalProps });
}
Object.assign(_OrganizationSwitcher, {
OrganizationProfilePage,
OrganizationProfileLink,
__experimental_Outlet: OrganizationSwitcherOutlet
});
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountOrganizationList,
unmount: clerk2.unmountOrganizationList,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "OrganizationList", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
open: clerk2.openGoogleOneTap,
close: clerk2.closeGoogleOneTap,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "GoogleOneTap", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, component, fallback, ...props }) => {
const mountingStatus = useWaitForComponentMount(component);
const shouldShowFallback = mountingStatus === "rendering" || !clerk2.loaded;
const rendererRootProps = {
...shouldShowFallback && fallback && { style: { display: "none" } }
};
return /* @__PURE__ */ React8__default.default.createElement(React8__default.default.Fragment, null, shouldShowFallback && fallback, clerk2.loaded && /* @__PURE__ */ React8__default.default.createElement(
ClerkHostRenderer,
{
component,
mount: clerk2.mountWaitlist,
unmount: clerk2.unmountWaitlist,
updateProps: clerk2.__unstable__updateProps,
props,
rootProps: rendererRootProps
}
));
},
{ component: "Waitlist", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, children, ...props }) => {
const {
signUpFallbackRedirectUrl,
forceRedirectUrl,
fallbackRedirectUrl,
signUpForceRedirectUrl,
mode,
initialValues,
withSignUp,
oauthFlow,
...rest
} = props;
children = normalizeWithDefaultValue(children, "Sign in");
const child = assertSingleChild(children)("SignInButton");
const clickHandler = () => {
const opts = {
forceRedirectUrl,
fallbackRedirectUrl,
signUpFallbackRedirectUrl,
signUpForceRedirectUrl,
initialValues,
withSignUp,
oauthFlow
};
if (mode === "modal") {
return clerk2.openSignIn({ ...opts, appearance: props.appearance });
}
return clerk2.redirectToSignIn({
...opts,
signInFallbackRedirectUrl: fallbackRedirectUrl,
signInForceRedirectUrl: forceRedirectUrl
});
};
const wrappedChildClickHandler = async (e) => {
if (child && typeof child === "object" && "props" in child) {
await safeExecute(child.props.onClick)(e);
}
return clickHandler();
};
const childProps = { ...rest, onClick: wrappedChildClickHandler };
return React8__default.default.cloneElement(child, childProps);
},
{ component: "SignInButton", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, children, ...props }) => {
const {
fallbackRedirectUrl,
forceRedirectUrl,
signInFallbackRedirectUrl,
signInForceRedirectUrl,
mode,
unsafeMetadata,
initialValues,
oauthFlow,
...rest
} = props;
children = normalizeWithDefaultValue(children, "Sign up");
const child = assertSingleChild(children)("SignUpButton");
const clickHandler = () => {
const opts = {
fallbackRedirectUrl,
forceRedirectUrl,
signInFallbackRedirectUrl,
signInForceRedirectUrl,
unsafeMetadata,
initialValues,
oauthFlow
};
if (mode === "modal") {
return clerk2.openSignUp({ ...opts, appearance: props.appearance });
}
return clerk2.redirectToSignUp({
...opts,
signUpFallbackRedirectUrl: fallbackRedirectUrl,
signUpForceRedirectUrl: forceRedirectUrl
});
};
const wrappedChildClickHandler = async (e) => {
if (child && typeof child === "object" && "props" in child) {
await safeExecute(child.props.onClick)(e);
}
return clickHandler();
};
const childProps = { ...rest, onClick: wrappedChildClickHandler };
return React8__default.default.cloneElement(child, childProps);
},
{ component: "SignUpButton", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, children, ...props }) => {
const { redirectUrl = "/", signOutOptions, ...rest } = props;
children = normalizeWithDefaultValue(children, "Sign out");
const child = assertSingleChild(children)("SignOutButton");
const clickHandler = () => clerk2.signOut({ redirectUrl, ...signOutOptions });
const wrappedChildClickHandler = async (e) => {
await safeExecute(child.props.onClick)(e);
return clickHandler();
};
const childProps = { ...rest, onClick: wrappedChildClickHandler };
return React8__default.default.cloneElement(child, childProps);
},
{ component: "SignOutButton", renderWhileLoading: true }
);
withClerk(
({ clerk: clerk2, children, ...props }) => {
const { redirectUrl, ...rest } = props;
children = normalizeWithDefaultValue(children, "Sign in with Metamask");
const child = assertSingleChild(children)("SignInWithMetamaskButton");
const clickHandler = async () => {
async function authenticate() {
await clerk2.authenticateWithMetamask({ redirectUrl: redirectUrl || void 0 });
}
void authenticate();
};
const wrappedChildClickHandler = async (e) => {
await safeExecute(child.props.onClick)(e);
return clickHandler();
};
const childProps = { ...rest, onClick: wrappedChildClickHandler };
return React8__default.default.cloneElement(child, childProps);
},
{ component: "SignInWithMetamask", renderWhileLoading: true }
);
if (typeof globalThis.__BUILD_DISABLE_RHC__ === "undefined") {
globalThis.__BUILD_DISABLE_RHC__ = false;
}
var SDK_METADATA = {
name: "@clerk/clerk-react",
version: "5.25.5",
environment: process.env.NODE_ENV
};
var _loaded;
var _domain;
var _proxyUrl;
var _publishableKey;
var _instance;
var _IsomorphicClerk_instances;
var waitForClerkJS_fn;
var _IsomorphicClerk = class _IsomorphicClerk2 {
constructor(options) {
__privateAdd2(this, _IsomorphicClerk_instances);
this.clerkjs = null;
this.preopenOneTap = null;
this.preopenUserVerification = null;
this.preopenSignIn = null;
this.preopenSignUp = null;
this.preopenUserProfile = null;
this.preopenOrganizationProfile = null;
this.preopenCreateOrganization = null;
this.preOpenWaitlist = null;
this.premountSignInNodes = /* @__PURE__ */ new Map();
this.premountSignUpNodes = /* @__PURE__ */ new Map();
this.premountUserProfileNodes = /* @__PURE__ */ new Map();
this.premountUserButtonNodes = /* @__PURE__ */ new Map();
this.premountOrganizationProfileNodes = /* @__PURE__ */ new Map();
this.premountCreateOrganizationNodes = /* @__PURE__ */ new Map();
this.premountOrganizationSwitcherNodes = /* @__PURE__ */ new Map();
this.premountOrganizationListNodes = /* @__PURE__ */ new Map();
this.premountMethodCalls = /* @__PURE__ */ new Map();
this.premountWaitlistNodes = /* @__PURE__ */ new Map();
this.premountPricingTableNodes = /* @__PURE__ */ new Map();
this.premountAddListenerCalls = /* @__PURE__ */ new Map();
this.loadedListeners = [];
__privateAdd2(this, _loaded, false);
__privateAdd2(this, _domain);
__privateAdd2(this, _proxyUrl);
__privateAdd2(this, _publishableKey);
this.buildSignInUrl = (opts) => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildSignInUrl(opts)) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildSignInUrl", callback);
}
};
this.buildSignUpUrl = (opts) => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildSignUpUrl(opts)) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildSignUpUrl", callback);
}
};
this.buildAfterSignInUrl = (...args) => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildAfterSignInUrl(...args)) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildAfterSignInUrl", callback);
}
};
this.buildAfterSignUpUrl = (...args) => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildAfterSignUpUrl(...args)) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildAfterSignUpUrl", callback);
}
};
this.buildAfterSignOutUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildAfterSignOutUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildAfterSignOutUrl", callback);
}
};
this.buildAfterMultiSessionSingleSignOutUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildAfterMultiSessionSingleSignOutUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildAfterMultiSessionSingleSignOutUrl", callback);
}
};
this.buildUserProfileUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildUserProfileUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildUserProfileUrl", callback);
}
};
this.buildCreateOrganizationUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildCreateOrganizationUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildCreateOrganizationUrl", callback);
}
};
this.buildOrganizationProfileUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildOrganizationProfileUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildOrganizationProfileUrl", callback);
}
};
this.buildWaitlistUrl = () => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildWaitlistUrl()) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildWaitlistUrl", callback);
}
};
this.buildUrlWithAuth = (to) => {
const callback = () => {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.buildUrlWithAuth(to)) || "";
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("buildUrlWithAuth", callback);
}
};
this.handleUnauthenticated = async () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.handleUnauthenticated();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
void callback();
} else {
this.premountMethodCalls.set("handleUnauthenticated", callback);
}
};
this.addOnLoaded = (cb) => {
this.loadedListeners.push(cb);
if (this.loaded) {
this.emitLoaded();
}
};
this.emitLoaded = () => {
this.loadedListeners.forEach((cb) => cb());
this.loadedListeners = [];
};
this.hydrateClerkJS = (clerkjs) => {
if (!clerkjs) {
throw new Error("Failed to hydrate latest Clerk JS");
}
this.clerkjs = clerkjs;
this.premountMethodCalls.forEach((cb) => cb());
this.premountAddListenerCalls.forEach((listenerHandlers, listener) => {
listenerHandlers.nativeUnsubscribe = clerkjs.addListener(listener);
});
if (this.preopenSignIn !== null) {
clerkjs.openSignIn(this.preopenSignIn);
}
if (this.preopenSignUp !== null) {
clerkjs.openSignUp(this.preopenSignUp);
}
if (this.preopenUserProfile !== null) {
clerkjs.openUserProfile(this.preopenUserProfile);
}
if (this.preopenUserVerification !== null) {
clerkjs.__internal_openReverification(this.preopenUserVerification);
}
if (this.preopenOneTap !== null) {
clerkjs.openGoogleOneTap(this.preopenOneTap);
}
if (this.preopenOrganizationProfile !== null) {
clerkjs.openOrganizationProfile(this.preopenOrganizationProfile);
}
if (this.preopenCreateOrganization !== null) {
clerkjs.openCreateOrganization(this.preopenCreateOrganization);
}
if (this.preOpenWaitlist !== null) {
clerkjs.openWaitlist(this.preOpenWaitlist);
}
this.premountSignInNodes.forEach((props, node) => {
clerkjs.mountSignIn(node, props);
});
this.premountSignUpNodes.forEach((props, node) => {
clerkjs.mountSignUp(node, props);
});
this.premountUserProfileNodes.forEach((props, node) => {
clerkjs.mountUserProfile(node, props);
});
this.premountUserButtonNodes.forEach((props, node) => {
clerkjs.mountUserButton(node, props);
});
this.premountOrganizationListNodes.forEach((props, node) => {
clerkjs.mountOrganizationList(node, props);
});
this.premountWaitlistNodes.forEach((props, node) => {
clerkjs.mountWaitlist(node, props);
});
this.premountPricingTableNodes.forEach((props, node) => {
clerkjs.__experimental_mountPricingTable(node, props);
});
__privateSet2(this, _loaded, true);
this.emitLoaded();
return this.clerkjs;
};
this.__unstable__updateProps = async (props) => {
const clerkjs = await __privateMethod2(this, _IsomorphicClerk_instances, waitForClerkJS_fn).call(this);
if (clerkjs && "__unstable__updateProps" in clerkjs) {
return clerkjs.__unstable__updateProps(props);
}
};
this.__experimental_nextTask = async (params) => {
if (this.clerkjs) {
return this.clerkjs.__experimental_nextTask(params);
} else {
return Promise.reject();
}
};
this.setActive = (params) => {
if (this.clerkjs) {
return this.clerkjs.setActive(params);
} else {
return Promise.reject();
}
};
this.openSignIn = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openSignIn(props);
} else {
this.preopenSignIn = props;
}
};
this.closeSignIn = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeSignIn();
} else {
this.preopenSignIn = null;
}
};
this.__internal_openReverification = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.__internal_openReverification(props);
} else {
this.preopenUserVerification = props;
}
};
this.__internal_closeReverification = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.__internal_closeReverification();
} else {
this.preopenUserVerification = null;
}
};
this.openGoogleOneTap = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openGoogleOneTap(props);
} else {
this.preopenOneTap = props;
}
};
this.closeGoogleOneTap = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeGoogleOneTap();
} else {
this.preopenOneTap = null;
}
};
this.openUserProfile = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openUserProfile(props);
} else {
this.preopenUserProfile = props;
}
};
this.closeUserProfile = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeUserProfile();
} else {
this.preopenUserProfile = null;
}
};
this.openOrganizationProfile = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openOrganizationProfile(props);
} else {
this.preopenOrganizationProfile = props;
}
};
this.closeOrganizationProfile = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeOrganizationProfile();
} else {
this.preopenOrganizationProfile = null;
}
};
this.openCreateOrganization = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openCreateOrganization(props);
} else {
this.preopenCreateOrganization = props;
}
};
this.closeCreateOrganization = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeCreateOrganization();
} else {
this.preopenCreateOrganization = null;
}
};
this.openWaitlist = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openWaitlist(props);
} else {
this.preOpenWaitlist = props;
}
};
this.closeWaitlist = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeWaitlist();
} else {
this.preOpenWaitlist = null;
}
};
this.openSignUp = (props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.openSignUp(props);
} else {
this.preopenSignUp = props;
}
};
this.closeSignUp = () => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.closeSignUp();
} else {
this.preopenSignUp = null;
}
};
this.mountSignIn = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountSignIn(node, props);
} else {
this.premountSignInNodes.set(node, props);
}
};
this.unmountSignIn = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountSignIn(node);
} else {
this.premountSignInNodes.delete(node);
}
};
this.__experimental_mountPricingTable = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.__experimental_mountPricingTable(node, props);
} else {
this.premountPricingTableNodes.set(node, props);
}
};
this.__experimental_unmountPricingTable = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.__experimental_unmountPricingTable(node);
} else {
this.premountPricingTableNodes.delete(node);
}
};
this.mountSignUp = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountSignUp(node, props);
} else {
this.premountSignUpNodes.set(node, props);
}
};
this.unmountSignUp = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountSignUp(node);
} else {
this.premountSignUpNodes.delete(node);
}
};
this.mountUserProfile = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountUserProfile(node, props);
} else {
this.premountUserProfileNodes.set(node, props);
}
};
this.unmountUserProfile = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountUserProfile(node);
} else {
this.premountUserProfileNodes.delete(node);
}
};
this.mountOrganizationProfile = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountOrganizationProfile(node, props);
} else {
this.premountOrganizationProfileNodes.set(node, props);
}
};
this.unmountOrganizationProfile = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountOrganizationProfile(node);
} else {
this.premountOrganizationProfileNodes.delete(node);
}
};
this.mountCreateOrganization = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountCreateOrganization(node, props);
} else {
this.premountCreateOrganizationNodes.set(node, props);
}
};
this.unmountCreateOrganization = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountCreateOrganization(node);
} else {
this.premountCreateOrganizationNodes.delete(node);
}
};
this.mountOrganizationSwitcher = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountOrganizationSwitcher(node, props);
} else {
this.premountOrganizationSwitcherNodes.set(node, props);
}
};
this.unmountOrganizationSwitcher = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountOrganizationSwitcher(node);
} else {
this.premountOrganizationSwitcherNodes.delete(node);
}
};
this.__experimental_prefetchOrganizationSwitcher = () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.__experimental_prefetchOrganizationSwitcher();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
void callback();
} else {
this.premountMethodCalls.set("__experimental_prefetchOrganizationSwitcher", callback);
}
};
this.mountOrganizationList = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountOrganizationList(node, props);
} else {
this.premountOrganizationListNodes.set(node, props);
}
};
this.unmountOrganizationList = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountOrganizationList(node);
} else {
this.premountOrganizationListNodes.delete(node);
}
};
this.mountUserButton = (node, userButtonProps) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountUserButton(node, userButtonProps);
} else {
this.premountUserButtonNodes.set(node, userButtonProps);
}
};
this.unmountUserButton = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountUserButton(node);
} else {
this.premountUserButtonNodes.delete(node);
}
};
this.mountWaitlist = (node, props) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.mountWaitlist(node, props);
} else {
this.premountWaitlistNodes.set(node, props);
}
};
this.unmountWaitlist = (node) => {
if (this.clerkjs && __privateGet2(this, _loaded)) {
this.clerkjs.unmountWaitlist(node);
} else {
this.premountWaitlistNodes.delete(node);
}
};
this.addListener = (listener) => {
if (this.clerkjs) {
return this.clerkjs.addListener(listener);
} else {
const unsubscribe = () => {
var _a;
const listenerHandlers = this.premountAddListenerCalls.get(listener);
if (listenerHandlers) {
(_a = listenerHandlers.nativeUnsubscribe) == null ? void 0 : _a.call(listenerHandlers);
this.premountAddListenerCalls.delete(listener);
}
};
this.premountAddListenerCalls.set(listener, { unsubscribe, nativeUnsubscribe: void 0 });
return unsubscribe;
}
};
this.navigate = (to) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.navigate(to);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
void callback();
} else {
this.premountMethodCalls.set("navigate", callback);
}
};
this.redirectWithAuth = async (...args) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectWithAuth(...args);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectWithAuth", callback);
return;
}
};
this.redirectToSignIn = async (opts) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToSignIn(opts);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToSignIn", callback);
return;
}
};
this.redirectToSignUp = async (opts) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToSignUp(opts);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToSignUp", callback);
return;
}
};
this.redirectToUserProfile = async () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToUserProfile();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToUserProfile", callback);
return;
}
};
this.redirectToAfterSignUp = () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToAfterSignUp();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToAfterSignUp", callback);
}
};
this.redirectToAfterSignIn = () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToAfterSignIn();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
callback();
} else {
this.premountMethodCalls.set("redirectToAfterSignIn", callback);
}
};
this.redirectToAfterSignOut = () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToAfterSignOut();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
callback();
} else {
this.premountMethodCalls.set("redirectToAfterSignOut", callback);
}
};
this.redirectToOrganizationProfile = async () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToOrganizationProfile();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToOrganizationProfile", callback);
return;
}
};
this.redirectToCreateOrganization = async () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToCreateOrganization();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToCreateOrganization", callback);
return;
}
};
this.redirectToWaitlist = async () => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.redirectToWaitlist();
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("redirectToWaitlist", callback);
return;
}
};
this.handleRedirectCallback = async (params) => {
var _a;
const callback = () => {
var _a2;
return (_a2 = this.clerkjs) == null ? void 0 : _a2.handleRedirectCallback(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
void ((_a = callback()) == null ? void 0 : _a.catch(() => {
}));
} else {
this.premountMethodCalls.set("handleRedirectCallback", callback);
}
};
this.handleGoogleOneTapCallback = async (signInOrUp, params) => {
var _a;
const callback = () => {
var _a2;
return (_a2 = this.clerkjs) == null ? void 0 : _a2.handleGoogleOneTapCallback(signInOrUp, params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
void ((_a = callback()) == null ? void 0 : _a.catch(() => {
}));
} else {
this.premountMethodCalls.set("handleGoogleOneTapCallback", callback);
}
};
this.handleEmailLinkVerification = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.handleEmailLinkVerification(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("handleEmailLinkVerification", callback);
}
};
this.authenticateWithMetamask = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.authenticateWithMetamask(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("authenticateWithMetamask", callback);
}
};
this.authenticateWithCoinbaseWallet = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.authenticateWithCoinbaseWallet(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("authenticateWithCoinbaseWallet", callback);
}
};
this.authenticateWithOKXWallet = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.authenticateWithOKXWallet(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("authenticateWithOKXWallet", callback);
}
};
this.authenticateWithWeb3 = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.authenticateWithWeb3(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("authenticateWithWeb3", callback);
}
};
this.authenticateWithGoogleOneTap = async (params) => {
const clerkjs = await __privateMethod2(this, _IsomorphicClerk_instances, waitForClerkJS_fn).call(this);
return clerkjs.authenticateWithGoogleOneTap(params);
};
this.createOrganization = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.createOrganization(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("createOrganization", callback);
}
};
this.getOrganization = async (organizationId) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.getOrganization(organizationId);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("getOrganization", callback);
}
};
this.joinWaitlist = async (params) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.joinWaitlist(params);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("joinWaitlist", callback);
}
};
this.signOut = async (...args) => {
const callback = () => {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.signOut(...args);
};
if (this.clerkjs && __privateGet2(this, _loaded)) {
return callback();
} else {
this.premountMethodCalls.set("signOut", callback);
}
};
const { Clerk: Clerk2 = null, publishableKey } = options || {};
__privateSet2(this, _publishableKey, publishableKey);
__privateSet2(this, _proxyUrl, options == null ? void 0 : options.proxyUrl);
__privateSet2(this, _domain, options == null ? void 0 : options.domain);
this.options = options;
this.Clerk = Clerk2;
this.mode = inBrowser() ? "browser" : "server";
if (!this.options.sdkMetadata) {
this.options.sdkMetadata = SDK_METADATA;
}
if (__privateGet2(this, _publishableKey)) {
void this.loadClerkJS();
}
}
get publishableKey() {
return __privateGet2(this, _publishableKey);
}
get loaded() {
return __privateGet2(this, _loaded);
}
static getOrCreateInstance(options) {
if (!inBrowser() || !__privateGet2(this, _instance) || options.Clerk && __privateGet2(this, _instance).Clerk !== options.Clerk || // Allow hot swapping PKs on the client
__privateGet2(this, _instance).publishableKey !== options.publishableKey) {
__privateSet2(this, _instance, new _IsomorphicClerk2(options));
}
return __privateGet2(this, _instance);
}
static clearInstance() {
__privateSet2(this, _instance, null);
}
get domain() {
if (typeof window !== "undefined" && window.location) {
return handleValueOrFn(__privateGet2(this, _domain), new URL(window.location.href), "");
}
if (typeof __privateGet2(this, _domain) === "function") {
return errorThrower.throw(unsupportedNonBrowserDomainOrProxyUrlFunction);
}
return __privateGet2(this, _domain) || "";
}
get proxyUrl() {
if (typeof window !== "undefined" && window.location) {
return handleValueOrFn(__privateGet2(this, _proxyUrl), new URL(window.location.href), "");
}
if (typeof __privateGet2(this, _proxyUrl) === "function") {
return errorThrower.throw(unsupportedNonBrowserDomainOrProxyUrlFunction);
}
return __privateGet2(this, _proxyUrl) || "";
}
__internal_getOption(key) {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.__internal_getOption(key);
}
get sdkMetadata() {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.sdkMetadata) || this.options.sdkMetadata || void 0;
}
get instanceType() {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.instanceType;
}
get frontendApi() {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.frontendApi) || "";
}
get isStandardBrowser() {
var _a;
return ((_a = this.clerkjs) == null ? void 0 : _a.isStandardBrowser) || this.options.standardBrowser || false;
}
get isSatellite() {
if (typeof window !== "undefined" && window.location) {
return handleValueOrFn(this.options.isSatellite, new URL(window.location.href), false);
}
if (typeof this.options.isSatellite === "function") {
return errorThrower.throw(unsupportedNonBrowserDomainOrProxyUrlFunction);
}
return false;
}
async loadClerkJS() {
var _a;
if (this.mode !== "browser" || __privateGet2(this, _loaded)) {
return;
}
if (typeof window !== "undefined") {
window.__clerk_publishable_key = __privateGet2(this, _publishableKey);
window.__clerk_proxy_url = this.proxyUrl;
window.__clerk_domain = this.domain;
}
try {
if (this.Clerk) {
let c;
if (isConstructor(this.Clerk)) {
c = new this.Clerk(__privateGet2(this, _publishableKey), {
proxyUrl: this.proxyUrl,
domain: this.domain
});
await c.load(this.options);
} else {
c = this.Clerk;
if (!c.loaded) {
await c.load(this.options);
}
}
global.Clerk = c;
} else if (false) ;
if ((_a = global.Clerk) == null ? void 0 : _a.loaded) {
return this.hydrateClerkJS(global.Clerk);
}
return;
} catch (err) {
const error = err;
if (process.env.NODE_ENV === "production") {
console.error(error.stack || error.message || error);
} else {
throw err;
}
return;
}
}
get version() {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.version;
}
get client() {
if (this.clerkjs) {
return this.clerkjs.client;
} else {
return void 0;
}
}
get session() {
if (this.clerkjs) {
return this.clerkjs.session;
} else {
return void 0;
}
}
get user() {
if (this.clerkjs) {
return this.clerkjs.user;
} else {
return void 0;
}
}
get organization() {
if (this.clerkjs) {
return this.clerkjs.organization;
} else {
return void 0;
}
}
get telemetry() {
if (this.clerkjs) {
return this.clerkjs.telemetry;
} else {
return void 0;
}
}
get __unstable__environment() {
if (this.clerkjs) {
return this.clerkjs.__unstable__environment;
} else {
return void 0;
}
}
get isSignedIn() {
if (this.clerkjs) {
return this.clerkjs.isSignedIn;
} else {
return false;
}
}
get __experimental_commerce() {
var _a;
return (_a = this.clerkjs) == null ? void 0 : _a.__experimental_commerce;
}
__unstable__setEnvironment(...args) {
if (this.clerkjs && "__unstable__setEnvironment" in this.clerkjs) {
this.clerkjs.__unstable__setEnvironment(args);
} else {
return void 0;
}
}
};
_loaded = /* @__PURE__ */ new WeakMap();
_domain = /* @__PURE__ */ new WeakMap();
_proxyUrl = /* @__PURE__ */ new WeakMap();
_publishableKey = /* @__PURE__ */ new WeakMap();
_instance = /* @__PURE__ */ new WeakMap();
_IsomorphicClerk_instances = /* @__PURE__ */ new WeakSet();
waitForClerkJS_fn = function() {
return new Promise((resolve) => {
this.addOnLoaded(() => resolve(this.clerkjs));
});
};
__privateAdd2(_IsomorphicClerk, _instance);
var IsomorphicClerk = _IsomorphicClerk;
function ClerkContextProvider(props) {
const { isomorphicClerkOptions, initialState, children } = props;
const { isomorphicClerk: clerk2, loaded: clerkLoaded } = useLoadedIsomorphicClerk(isomorphicClerkOptions);
const [state, setState] = React8__default.default.useState({
client: clerk2.client,
session: clerk2.session,
user: clerk2.user,
organization: clerk2.organization
});
React8__default.default.useEffect(() => {
return clerk2.addListener((e) => setState({ ...e }));
}, []);
const derivedState = deriveState(clerkLoaded, state, initialState);
const clerkCtx = React8__default.default.useMemo(() => ({ value: clerk2 }), [clerkLoaded]);
const clientCtx = React8__default.default.useMemo(() => ({ value: state.client }), [state.client]);
const {
sessionId,
sessionStatus,
session,
userId,
user,
orgId,
actor,
organization,
orgRole,
orgSlug,
orgPermissions,
factorVerificationAge
} = derivedState;
const authCtx = React8__default.default.useMemo(() => {
const value = {
sessionId,
sessionStatus,
userId,
actor,
orgId,
orgRole,
orgSlug,
orgPermissions,
factorVerificationAge
};
return { value };
}, [sessionId, sessionStatus, userId, actor, orgId, orgRole, orgSlug, factorVerificationAge]);
const sessionCtx = React8__default.default.useMemo(() => ({ value: session }), [sessionId, session]);
const userCtx = React8__default.default.useMemo(() => ({ value: user }), [userId, user]);
const organizationCtx = React8__default.default.useMemo(() => {
const value = {
organization
};
return { value };
}, [orgId, organization]);
return (
// @ts-expect-error value passed is of type IsomorphicClerk where the context expects LoadedClerk
/* @__PURE__ */ React8__default.default.createElement(IsomorphicClerkContext.Provider, { value: clerkCtx }, /* @__PURE__ */ React8__default.default.createElement(ClientContext.Provider, { value: clientCtx }, /* @__PURE__ */ React8__default.default.createElement(SessionContext.Provider, { value: sessionCtx }, /* @__PURE__ */ React8__default.default.createElement(OrganizationProvider, { ...organizationCtx.value }, /* @__PURE__ */ React8__default.default.createElement(AuthContext.Provider, { value: authCtx }, /* @__PURE__ */ React8__default.default.createElement(UserContext.Provider, { value: userCtx }, children))))))
);
}
var useLoadedIsomorphicClerk = (options) => {
const [loaded, setLoaded] = React8__default.default.useState(false);
const isomorphicClerk = React8__default.default.useMemo(() => IsomorphicClerk.getOrCreateInstance(options), []);
React8__default.default.useEffect(() => {
void isomorphicClerk.__unstable__updateProps({ appearance: options.appearance });
}, [options.appearance]);
React8__default.default.useEffect(() => {
void isomorphicClerk.__unstable__updateProps({ options });
}, [options.localization]);
React8__default.default.useEffect(() => {
isomorphicClerk.addOnLoaded(() => setLoaded(true));
}, []);
React8__default.default.useEffect(() => {
return () => {
IsomorphicClerk.clearInstance();
setLoaded(false);
};
}, []);
return { isomorphicClerk, loaded };
};
function ClerkProviderBase(props) {
const { initialState, children, __internal_bypassMissingPublishableKey, ...restIsomorphicClerkOptions } = props;
const { publishableKey = "", Clerk: userInitialisedClerk } = restIsomorphicClerkOptions;
if (!userInitialisedClerk && !__internal_bypassMissingPublishableKey) {
if (!publishableKey) {
errorThrower.throwMissingPublishableKeyError();
} else if (publishableKey && !isPublishableKey(publishableKey)) {
errorThrower.throwInvalidPublishableKeyError({ key: publishableKey });
}
}
return /* @__PURE__ */ React8__default.default.createElement(
ClerkContextProvider,
{
initialState,
isomorphicClerkOptions: restIsomorphicClerkOptions
},
children
);
}
var ClerkProvider = withMaxAllowedInstancesGuard(ClerkProviderBase, "ClerkProvider", multipleClerkProvidersError);
ClerkProvider.displayName = "ClerkProvider";
setErrorThrowerOptions({ packageName: "@clerk/clerk-react" });
setClerkJsLoadingErrorPackageName("@clerk/clerk-react");
// ../shared/dist/chunk-K64INQ4C.mjs
var DEV_BROWSER_JWT_KEY = "__clerk_db_jwt";
// src/types.ts
var SCOPE = {
BACKGROUND: "background"
};
// src/internal/constants.ts
var AUTH_HEADER = {
PRODUCTION: "Authorization",
DEVELOPMENT: "Clerk-Db-Jwt"
};
var CLIENT_JWT_KEY = "__client";
var CLIENT_UAT_KEY = "__clerk_uat";
var DEFAULT_LOCAL_HOST_PERMISSION = "http://localhost";
var STORAGE_KEY_CLIENT_JWT = "__clerk_client_jwt";
// src/internal/utils/errors.ts
var errorLogger = (err) => console.error(err, err.stack);
var errorThrower3 = buildErrorThrower({ packageName: "@clerk/chrome-extension" });
var missingManifestKeyError = (key) => `Missing \`${key}\` entry in manifest.json`;
function assertPublishableKey(publishableKey) {
if (!publishableKey) {
errorThrower3.throwMissingPublishableKeyError();
}
}
function ensureFormattedUrl(url) {
return url.startsWith("http") ? url : `https://${url}`;
}
async function getClientCookie({ url, name }) {
return await browser__default.default.cookies.get({ name, url: ensureFormattedUrl(url) });
}
function createClientCookieListener({ url, name, callback }) {
const domain = new URL(url).hostname;
const cookieDomain = domain.startsWith("www.") ? domain.slice(4) : domain;
const listener = (changeInfo) => {
if (changeInfo.cookie.domain === cookieDomain && changeInfo.cookie.name === name) {
void callback(changeInfo);
}
};
return {
add: () => browser__default.default.cookies.onChanged.addListener(listener),
has: () => browser__default.default.cookies.onChanged.hasListener(listener),
remove: () => browser__default.default.cookies.onChanged.removeListener(listener)
};
}
// src/internal/utils/jwt-handler.ts
function shouldSync(sync, _params) {
return Boolean(sync);
}
function JWTHandler(store, params) {
const { sync, frontendApi, ...cookieParams } = params;
const CACHE_KEY = store.createKey(frontendApi, STORAGE_KEY_CLIENT_JWT, "v2");
const set = async (value) => {
return await store.set(CACHE_KEY, value).catch(errorLogger);
};
const remove = async () => {
return await store.remove(CACHE_KEY).catch(errorLogger);
};
const get = async () => {
if (shouldSync(sync)) {
const syncedJWT = await getClientCookie(cookieParams).catch(errorLogger);
if (syncedJWT) {
await set(syncedJWT.value);
return syncedJWT.value;
}
}
return await store.get(CACHE_KEY);
};
const listener = () => {
if (!shouldSync(sync)) {
return;
}
const { onListenerCallback, ...restCookieParams } = cookieParams;
return createClientCookieListener({
...restCookieParams,
callback: async (changeInfo) => {
const existingJWT = await get();
if (existingJWT === changeInfo.cookie.value) {
const syncedUAT = await getClientCookie({ ...restCookieParams, name: CLIENT_UAT_KEY }).catch(errorLogger);
if (!syncedUAT || (syncedUAT == null ? void 0 : syncedUAT.value) === "0") {
onListenerCallback == null ? void 0 : onListenerCallback();
}
return;
}
await set(changeInfo.cookie.value);
onListenerCallback == null ? void 0 : onListenerCallback();
}
});
};
return { get, listener, set, remove };
}
// src/internal/utils/manifest.ts
function validateRootManifestKey(manifest, key) {
if (!manifest[key]) {
errorThrower3.throw(missingManifestKeyError(key));
}
}
function validateManifestPermission(manifest, key) {
var _a;
if (!((_a = manifest.permissions) == null ? void 0 : _a.includes(key))) {
errorThrower3.throw(missingManifestKeyError(`permissions.${key}`));
}
}
function hasAdditionalFeatures(features) {
return Boolean(features) && Object.keys(features).length > 0;
}
function validateManifest(manifest, features) {
validateRootManifestKey(manifest, "permissions");
validateManifestPermission(manifest, "storage");
if (!hasAdditionalFeatures(features)) {
return;
}
if (features.background) {
validateRootManifestKey(manifest, "background");
}
if (features.sync) {
validateManifestPermission(manifest, "cookies");
validateRootManifestKey(manifest, "host_permissions");
}
}
// src/internal/utils/request-handler.ts
function requestHandler(jwtHandler, { isProd }) {
const handler = async (requestInit) => {
requestInit.credentials = "omit";
const currentJWT = await jwtHandler.get();
if (!currentJWT) {
return;
}
if (isProd) {
prodHandler(requestInit, currentJWT);
} else {
devHandler(requestInit, currentJWT);
}
};
return handler;
}
function devHandler(requestInit, jwt) {
var _a;
(_a = requestInit.url) == null ? void 0 : _a.searchParams.append("__clerk_db_jwt", jwt);
}
function prodHandler(requestInit, jwt) {
var _a;
(_a = requestInit.url) == null ? void 0 : _a.searchParams.append("_is_native", "1");
requestInit.headers.set(AUTH_HEADER.PRODUCTION, `Bearer ${jwt}`);
}
// src/internal/utils/response-handler.ts
function responseHandler(jwtHandler, { isProd }) {
const handler = async (_, response) => {
if (isProd) {
await prodHandler2(response, jwtHandler);
} else {
await devHandler2(response, jwtHandler);
}
};
return handler;
}
async function devHandler2(response, jwtHandler) {
const header = response == null ? void 0 : response.headers.get(AUTH_HEADER.DEVELOPMENT);
if (header) {
await jwtHandler.set(header);
} else {
await jwtHandler.remove();
}
}
async function prodHandler2(response, jwtHandler) {
const header = response == null ? void 0 : response.headers.get(AUTH_HEADER.PRODUCTION);
if (header == null ? void 0 : header.startsWith("Bearer")) {
const jwt = header.split(" ")[1] || void 0;
if (jwt) {
await jwtHandler.set(jwt);
} else {
await jwtHandler.remove();
}
} else if (header) {
await jwtHandler.set(header);
}
}
var createKey = (...keys) => keys.filter(Boolean).join("|");
var createBrowserStorageCache = (opts = {}) => {
const __storageArea = opts.storageArea || "local";
return {
createKey,
get: (key) => browser__default.default.storage[__storageArea].get(key).then((result) => result[key] || void 0),
remove: (key) => browser__default.default.storage[__storageArea].remove(key),
set: (key, value) => browser__default.default.storage[__storageArea].set({ [key]: value })
};
};
var BrowserStorageCache = createBrowserStorageCache();
// src/internal/clerk.ts
var clerk;
noRhc.Clerk.sdkMetadata = {
name: "@clerk/chrome-extension",
version: "2.2.23"
};
async function createClerkClient({
__experimental_syncHostListener = false,
publishableKey,
scope,
storageCache = BrowserStorageCache,
syncHost
}) {
if (scope === SCOPE.BACKGROUND) {
noRhc.Clerk.mountComponentRenderer = void 0;
}
if (clerk && scope !== SCOPE.BACKGROUND) {
return clerk;
}
const sync = Boolean(syncHost);
const key = parsePublishableKey(publishableKey);
assertPublishableKey(key);
const isProd = key.instanceType === "production";
const manifest = browser__default.default.runtime.getManifest();
validateManifest(manifest, {
background: scope === SCOPE.BACKGROUND,
sync
});
const url = syncHost ? syncHost : DEFAULT_LOCAL_HOST_PERMISSION;
clerk = new noRhc.Clerk(publishableKey);
const jwtOptions = {
frontendApi: key.frontendApi,
name: isProd ? CLIENT_JWT_KEY : DEV_BROWSER_JWT_KEY,
url,
sync
};
if (jwtOptions.sync && __experimental_syncHostListener) {
jwtOptions.onListenerCallback = () => {
if (clerk.user) {
clerk.user.reload();
} else {
window.location.reload();
}
};
}
const jwt = JWTHandler(storageCache, jwtOptions);
if (jwtOptions.sync && __experimental_syncHostListener) {
const listener = jwt.listener();
listener == null ? void 0 : listener.add();
}
clerk.__unstable__onAfterResponse(responseHandler(jwt, { isProd }));
clerk.__unstable__onBeforeRequest(requestHandler(jwt, { isProd }));
return clerk;
}
function ClerkProvider2(props) {
const { children, storageCache, syncHost, __experimental_syncHostListener, ...rest } = props;
const { publishableKey = "" } = props;
const [clerkInstance, setClerkInstance] = React8__default.default.useState(null);
React8__default.default.useEffect(() => {
void (async () => {
setClerkInstance(
await createClerkClient({ publishableKey, storageCache, syncHost, __experimental_syncHostListener })
);
})();
}, [publishableKey, storageCache, syncHost, __experimental_syncHostListener]);
if (!clerkInstance) {
return null;
}
return /* @__PURE__ */ jsxRuntime.jsx(
ClerkProvider,
{
...rest,
Clerk: clerkInstance,
standardBrowser: !syncHost,
children
}
);
}
exports.ClerkProvider = ClerkProvider2;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map