Socket
Socket
Sign inDemoInstall

@clerk/shared

Package Overview
Dependencies
Maintainers
9
Versions
1549
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@clerk/shared - npm Package Compare versions

Comparing version 0.5.2-staging.0 to 0.5.2-staging.1

dist/chunk-YIFOKRC3.mjs

1573

dist/index.js

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

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
ClerkInstanceContext: () => ClerkInstanceContext,
ClientContext: () => ClientContext,
LocalStorageBroadcastChannel: () => LocalStorageBroadcastChannel,
OrganizationContext: () => OrganizationContext,
Poller: () => Poller,
SessionContext: () => SessionContext,
UserContext: () => UserContext,
addYears: () => addYears,
assertContextExists: () => assertContextExists,
camelToSnake: () => camelToSnake,
colorToSameTypeString: () => colorToSameTypeString,
createContextAndHook: () => createContextAndHook,
createCookieHandler: () => createCookieHandler,
dateTo12HourTime: () => dateTo12HourTime,
deepCamelToSnake: () => deepCamelToSnake,
deepSnakeToCamel: () => deepSnakeToCamel,
differenceInCalendarDays: () => differenceInCalendarDays,
extension: () => extension,
formatRelative: () => formatRelative,
hasAlpha: () => hasAlpha,
hexStringToRgbaColor: () => hexStringToRgbaColor,
inBrowser: () => inBrowser,
inClientSide: () => inClientSide,
isHSLColor: () => isHSLColor,
isIPV4Address: () => isIPV4Address,
isRGBColor: () => isRGBColor,
isRetinaDisplay: () => isRetinaDisplay,
isTransparent: () => isTransparent,
isValidHexString: () => isValidHexString,
isValidHslaString: () => isValidHslaString,
isValidRgbaString: () => isValidRgbaString,
noop: () => noop,
parseSearchParams: () => parseSearchParams,
readJSONFile: () => readJSONFile,
snakeToCamel: () => snakeToCamel,
stringToHslaColor: () => stringToHslaColor,
stringToSameTypeColor: () => stringToSameTypeColor,
titleize: () => titleize,
toSentence: () => toSentence,
useClerkInstanceContext: () => useClerkInstanceContext,
useClientContext: () => useClientContext,
useOrganization: () => useOrganization,
useOrganizationContext: () => useOrganizationContext,
useOrganizationList: () => useOrganizationList,
useOrganizations: () => useOrganizations,
useSessionContext: () => useSessionContext,
useUserContext: () => useUserContext
});
module.exports = __toCommonJS(src_exports);
// src/utils/array.ts
var toSentence = (items) => {
if (items.length == 0) {
return "";
}
if (items.length == 1) {
return items[0];
}
let sentence = items.slice(0, -1).join(", ");
sentence += `, or ${items.slice(-1)}`;
return sentence;
};
// src/utils/browser.ts
function inBrowser() {
return typeof window !== "undefined";
}
// src/utils/color/predicates.ts
var IS_HEX_COLOR_REGEX = /^#?([A-F0-9]{6}|[A-F0-9]{3})$/i;
var IS_RGB_COLOR_REGEX = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i;
var IS_RGBA_COLOR_REGEX = /^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i;
var IS_HSL_COLOR_REGEX = /^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i;
var IS_HSLA_COLOR_REGEX = /^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i;
var isValidHexString = (s) => {
return !!s.match(IS_HEX_COLOR_REGEX);
};
var isValidRgbaString = (s) => {
return !!(s.match(IS_RGB_COLOR_REGEX) || s.match(IS_RGBA_COLOR_REGEX));
};
var isValidHslaString = (s) => {
return !!s.match(IS_HSL_COLOR_REGEX) || !!s.match(IS_HSLA_COLOR_REGEX);
};
var isRGBColor = (c) => {
return typeof c !== "string" && "r" in c;
};
var isHSLColor = (c) => {
return typeof c !== "string" && "h" in c;
};
var isTransparent = (c) => {
return c === "transparent";
};
var hasAlpha = (color) => {
return typeof color !== "string" && color.a != void 0 && color.a < 1;
};
// src/utils/color/cssColorUtils.ts
var CLEAN_HSLA_REGEX = /[hsla()]/g;
var CLEAN_RGBA_REGEX = /[rgba()]/g;
var stringToHslaColor = (value) => {
if (value === "transparent") {
return { h: 0, s: 0, l: 0, a: 0 };
}
if (isValidHexString(value)) {
return hexStringToHslaColor(value);
}
if (isValidHslaString(value)) {
return parseHslaString(value);
}
if (isValidRgbaString(value)) {
return rgbaStringToHslaColor(value);
}
return null;
};
var stringToSameTypeColor = (value) => {
value = value.trim();
if (isValidHexString(value)) {
return value.startsWith("#") ? value : `#${value}`;
}
if (isValidRgbaString(value)) {
return parseRgbaString(value);
}
if (isValidHslaString(value)) {
return parseHslaString(value);
}
if (isTransparent(value)) {
return value;
}
return "";
};
var colorToSameTypeString = (color) => {
if (typeof color === "string" && (isValidHexString(color) || isTransparent(color))) {
return color;
}
if (isRGBColor(color)) {
return rgbaColorToRgbaString(color);
}
if (isHSLColor(color)) {
return hslaColorToHslaString(color);
}
return "";
};
var hexStringToRgbaColor = (hex) => {
hex = hex.replace("#", "");
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return { r, g, b };
};
var rgbaColorToRgbaString = (color) => {
const { a, b, g, r } = color;
return color.a === 0 ? "transparent" : color.a != void 0 ? `rgba(${r},${g},${b},${a})` : `rgb(${r},${g},${b})`;
};
var hslaColorToHslaString = (color) => {
const { h, s, l, a } = color;
const sPerc = Math.round(s * 100);
const lPerc = Math.round(l * 100);
return color.a === 0 ? "transparent" : color.a != void 0 ? `hsla(${h},${sPerc}%,${lPerc}%,${a})` : `hsl(${h},${sPerc}%,${lPerc}%)`;
};
var hexStringToHslaColor = (hex) => {
const rgbaString = colorToSameTypeString(hexStringToRgbaColor(hex));
return rgbaStringToHslaColor(rgbaString);
};
var rgbaStringToHslaColor = (rgba) => {
const rgbaColor = parseRgbaString(rgba);
const r = rgbaColor.r / 255;
const g = rgbaColor.g / 255;
const b = rgbaColor.b / 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s;
const l = (max + min) / 2;
if (max == min) {
h = s = 0;
} else {
const d = max - min;
s = l >= 0.5 ? d / (2 - (max + min)) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d * 60;
break;
case g:
h = ((b - r) / d + 2) * 60;
break;
default:
h = ((r - g) / d + 4) * 60;
break;
}
}
const res = { h: Math.round(h), s, l };
const a = rgbaColor.a;
if (a != void 0) {
res.a = a;
}
return res;
};
var parseRgbaString = (str) => {
const [r, g, b, a] = str.replace(CLEAN_RGBA_REGEX, "").split(",").map((c) => Number.parseFloat(c));
return { r, g, b, a };
};
var parseHslaString = (str) => {
const [h, s, l, a] = str.replace(CLEAN_HSLA_REGEX, "").split(",").map((c) => Number.parseFloat(c));
return { h, s: s / 100, l: l / 100, a };
};
// ../../node_modules/js-cookie/dist/js.cookie.mjs
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
target[key] = source[key];
}
}
return target;
}
var defaultConverter = {
read: function(value) {
if (value[0] === '"') {
value = value.slice(1, -1);
}
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
},
write: function(value) {
return encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
decodeURIComponent
);
}
};
function init(converter, defaultAttributes) {
function set(key, value, attributes) {
if (typeof document === "undefined") {
return;
}
attributes = assign({}, defaultAttributes, attributes);
if (typeof attributes.expires === "number") {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString();
}
key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var stringifiedAttributes = "";
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += "; " + attributeName;
if (attributes[attributeName] === true) {
continue;
}
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
}
return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes;
}
function get(key) {
if (typeof document === "undefined" || arguments.length && !key) {
return;
}
var cookies = document.cookie ? document.cookie.split("; ") : [];
var jar = {};
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split("=");
var value = parts.slice(1).join("=");
try {
var foundKey = decodeURIComponent(parts[0]);
jar[foundKey] = converter.read(value, foundKey);
if (key === foundKey) {
break;
}
} catch (e) {
}
}
return key ? jar[key] : jar;
}
return Object.create(
{
set,
get,
remove: function(key, attributes) {
set(
key,
"",
assign({}, attributes, {
expires: -1
})
);
},
withAttributes: function(attributes) {
return init(this.converter, assign({}, this.attributes, attributes));
},
withConverter: function(converter2) {
return init(assign({}, this.converter, converter2), this.attributes);
}
},
{
attributes: { value: Object.freeze(defaultAttributes) },
converter: { value: Object.freeze(converter) }
}
);
}
var api = init(defaultConverter, { path: "/" });
var js_cookie_default = api;
// src/utils/cookies.ts
function createCookieHandler(cookieName) {
return {
get() {
return js_cookie_default.get(cookieName);
},
set(newValue, options = {}) {
return js_cookie_default.set(cookieName, newValue, options);
},
remove(locationAttributes) {
js_cookie_default.remove(cookieName, locationAttributes);
}
};
}
// src/utils/date.ts
var MILLISECONDS_IN_DAY = 864e5;
var DAYS_EN = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function dateTo12HourTime(date) {
if (!date) {
return "";
}
return date.toLocaleString("en-US", {
hour: "2-digit",
minute: "numeric",
hour12: true
});
}
function differenceInCalendarDays(a, b, { absolute = true } = {}) {
if (!a || !b) {
return 0;
}
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
const diff = Math.floor((utcB - utcA) / MILLISECONDS_IN_DAY);
return absolute ? Math.abs(diff) : diff;
}
function normalizeDate(d) {
try {
return new Date(d || new Date());
} catch (e) {
return new Date();
}
}
function formatRelative(date, relativeTo) {
if (!date || !relativeTo) {
return "";
}
const a = normalizeDate(date);
const b = normalizeDate(relativeTo);
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false });
const time12Hour = dateTo12HourTime(a);
const dayName = DAYS_EN[a.getDay()];
if (differenceInDays < -6) {
return a.toLocaleDateString();
}
if (differenceInDays < -1) {
return `last ${dayName} at ${time12Hour}`;
}
if (differenceInDays === -1) {
return `yesterday at ${time12Hour}`;
}
if (differenceInDays === 0) {
return `today at ${time12Hour}`;
}
if (differenceInDays === 1) {
return `tomorrow at ${time12Hour}`;
}
if (differenceInDays < 7) {
return `${dayName} at ${time12Hour}`;
}
return a.toLocaleDateString();
}
function addYears(initialDate, yearsToAdd) {
const date = normalizeDate(initialDate);
date.setFullYear(date.getFullYear() + yearsToAdd);
return date;
}
// src/utils/file.ts
function readJSONFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", function() {
const result = JSON.parse(reader.result);
resolve(result);
});
reader.addEventListener("error", reject);
reader.readAsText(file);
});
}
// src/utils/isRetinaDisplay.ts
function isRetinaDisplay() {
if (!window.matchMedia) {
return false;
}
const mq = window.matchMedia(
"only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)"
);
return mq && mq.matches || window.devicePixelRatio > 1;
}
// src/utils/localStorageBroadcastChannel.ts
var KEY_PREFIX = "__lsbc__";
var LocalStorageBroadcastChannel = class {
constructor(name) {
this.eventTarget = window;
this.postMessage = (data) => {
try {
localStorage.setItem(this.channelKey, JSON.stringify(data));
localStorage.removeItem(this.channelKey);
} catch (e) {
}
};
this.addEventListener = (eventName, listener) => {
this.eventTarget.addEventListener(this.prefixEventName(eventName), (e) => {
listener(e);
});
};
this.setupLocalStorageListener = () => {
const notifyListeners = (e) => {
if (e.key !== this.channelKey || !e.newValue) {
return;
}
try {
const data = JSON.parse(e.newValue || "");
const event = new MessageEvent(this.prefixEventName("message"), {
data
});
this.eventTarget.dispatchEvent(event);
} catch (e2) {
}
};
window.addEventListener("storage", notifyListeners);
};
this.channelKey = KEY_PREFIX + name;
this.setupLocalStorageListener();
}
prefixEventName(eventName) {
return this.channelKey + eventName;
}
};
// src/utils/mimeTypeExtensions.ts
var MimeTypeToExtensionMap = Object.freeze({
"image/png": "png",
"image/jpeg": "jpg",
"image/gif": "gif",
"image/webp": "webp",
"image/x-icon": "ico",
"image/vnd.microsoft.icon": "ico"
});
var extension = (mimeType) => {
return MimeTypeToExtensionMap[mimeType];
};
// src/utils/noop.ts
var noop = (..._args) => {
};
// src/utils/string.ts
var IP_V4_ADDRESS_REGEX = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
function isIPV4Address(str) {
return IP_V4_ADDRESS_REGEX.test(str || "");
}
function titleize(str) {
const s = str || "";
return s.charAt(0).toUpperCase() + s.slice(1);
}
function snakeToCamel(str) {
return str.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, ""));
}
function camelToSnake(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
// src/utils/object.ts
var createDeepObjectTransformer = (transform) => {
const deepTransform = (obj) => {
if (!obj) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((el) => {
if (typeof el === "object" || Array.isArray(el)) {
return deepTransform(el);
}
return el;
});
}
const copy = { ...obj };
const keys = Object.keys(copy);
for (const oldName of keys) {
const newName = transform(oldName.toString());
if (newName !== oldName) {
copy[newName] = copy[oldName];
delete copy[oldName];
}
if (typeof copy[newName] === "object") {
copy[newName] = deepTransform(copy[newName]);
}
}
return copy;
};
return deepTransform;
};
var deepCamelToSnake = createDeepObjectTransformer(camelToSnake);
var deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel);
// src/utils/poller.ts
function Poller({ delayInMs } = { delayInMs: 1e3 }) {
let timerId;
let stopped = false;
const stop = () => {
clearTimeout(timerId);
stopped = true;
};
const run = async (cb) => {
stopped = false;
await cb(stop);
if (stopped) {
return;
}
timerId = setTimeout(() => run(cb), delayInMs);
};
return { run, stop };
}
// src/utils/ssr.ts
var inClientSide = () => {
return typeof window !== "undefined";
};
// src/utils/url.ts
function parseSearchParams(queryString = "") {
if (queryString.startsWith("?")) {
queryString = queryString.slice(1);
}
return new URLSearchParams(queryString);
}
// src/hooks/createContextAndHook.ts
var import_react = __toESM(require("react"));
function assertContextExists(contextVal, msgOrCtx) {
if (!contextVal) {
throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`);
}
}
var createContextAndHook = (displayName, options) => {
const { assertCtxFn = assertContextExists } = options || {};
const Ctx = import_react.default.createContext(void 0);
Ctx.displayName = displayName;
const useCtx = () => {
const ctx = import_react.default.useContext(Ctx);
assertCtxFn(ctx, `${displayName} not found`);
return ctx.value;
};
const useCtxWithoutGuarantee = () => {
const ctx = import_react.default.useContext(Ctx);
return ctx ? ctx.value : {};
};
return [Ctx, useCtx, useCtxWithoutGuarantee];
};
// src/hooks/contexts.tsx
var [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
var [UserContext, useUserContext] = createContextAndHook("UserContext");
var [ClientContext, useClientContext] = createContextAndHook("ClientContext");
var [SessionContext, useSessionContext] = createContextAndHook(
"SessionContext"
);
var [OrganizationContext, useOrganizationContext] = createContextAndHook("OrganizationContext");
// ../../node_modules/swr/dist/index.mjs
var import_react2 = require("react");
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1)
throw t[1];
return t[1];
}, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var noop2 = function() {
};
var UNDEFINED = noop2();
var OBJECT = Object;
var isUndefined = function(v) {
return v === UNDEFINED;
};
var isFunction = function(v) {
return typeof v == "function";
};
var mergeObjects = function(a, b) {
return OBJECT.assign({}, a, b);
};
var STR_UNDEFINED = "undefined";
var hasWindow = function() {
return typeof window != STR_UNDEFINED;
};
var hasDocument = function() {
return typeof document != STR_UNDEFINED;
};
var hasRequestAnimationFrame = function() {
return hasWindow() && typeof window["requestAnimationFrame"] != STR_UNDEFINED;
};
var table = /* @__PURE__ */ new WeakMap();
var counter = 0;
var stableHash = function(arg) {
var type = typeof arg;
var constructor = arg && arg.constructor;
var isDate = constructor == Date;
var result;
var index;
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {
result = table.get(arg);
if (result)
return result;
result = ++counter + "~";
table.set(arg, result);
if (constructor == Array) {
result = "@";
for (index = 0; index < arg.length; index++) {
result += stableHash(arg[index]) + ",";
}
table.set(arg, result);
}
if (constructor == OBJECT) {
result = "#";
var keys = OBJECT.keys(arg).sort();
while (!isUndefined(index = keys.pop())) {
if (!isUndefined(arg[index])) {
result += index + ":" + stableHash(arg[index]) + ",";
}
}
table.set(arg, result);
}
} else {
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
}
return result;
};
var online = true;
var isOnline = function() {
return online;
};
var hasWin = hasWindow();
var hasDoc = hasDocument();
var onWindowEvent = hasWin && window.addEventListener ? window.addEventListener.bind(window) : noop2;
var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop2;
var offWindowEvent = hasWin && window.removeEventListener ? window.removeEventListener.bind(window) : noop2;
var offDocumentEvent = hasDoc ? document.removeEventListener.bind(document) : noop2;
var isVisible = function() {
var visibilityState = hasDoc && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
};
var initFocus = function(callback) {
onDocumentEvent("visibilitychange", callback);
onWindowEvent("focus", callback);
return function() {
offDocumentEvent("visibilitychange", callback);
offWindowEvent("focus", callback);
};
};
var initReconnect = function(callback) {
var onOnline = function() {
online = true;
callback();
};
var onOffline = function() {
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return function() {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
};
};
var preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_SERVER = !hasWindow() || "Deno" in window;
var rAF = function(f) {
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
};
var useIsomorphicLayoutEffect = IS_SERVER ? import_react2.useEffect : import_react2.useLayoutEffect;
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var serialize = function(key) {
if (isFunction(key)) {
try {
key = key();
} catch (err) {
key = "";
}
}
var args = [].concat(key);
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : "";
var infoKey = key ? "$swr$" + key : "";
return [key, args, infoKey];
};
var SWRGlobalState = /* @__PURE__ */ new WeakMap();
var FOCUS_EVENT = 0;
var RECONNECT_EVENT = 1;
var MUTATE_EVENT = 2;
var broadcastState = function(cache2, key, data, error, isValidating, revalidate, broadcast) {
if (broadcast === void 0) {
broadcast = true;
}
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], FETCH = _a2[3];
var revalidators = EVENT_REVALIDATORS[key];
var updaters = STATE_UPDATERS[key];
if (broadcast && updaters) {
for (var i = 0; i < updaters.length; ++i) {
updaters[i](data, error, isValidating);
}
}
if (revalidate) {
delete FETCH[key];
if (revalidators && revalidators[0]) {
return revalidators[0](MUTATE_EVENT).then(function() {
return cache2.get(key);
});
}
}
return cache2.get(key);
};
var __timestamp = 0;
var getTimestamp = function() {
return ++__timestamp;
};
var internalMutate = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(void 0, void 0, void 0, function() {
var cache2, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, customOptimisticData, _a2, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasCustomOptimisticData, rollbackData, optimisticData, res;
return __generator(this, function(_c) {
switch (_c.label) {
case 0:
cache2 = args[0], _key = args[1], _data = args[2], _opts = args[3];
options = typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {};
populateCache = isUndefined(options.populateCache) ? true : options.populateCache;
revalidate = options.revalidate !== false;
rollbackOnError = options.rollbackOnError !== false;
customOptimisticData = options.optimisticData;
_a2 = serialize(_key), key = _a2[0], keyInfo = _a2[2];
if (!key)
return [2];
_b = SWRGlobalState.get(cache2), MUTATION = _b[2];
if (args.length < 3) {
return [2, broadcastState(cache2, key, cache2.get(key), UNDEFINED, UNDEFINED, revalidate, true)];
}
data = _data;
beforeMutationTs = getTimestamp();
MUTATION[key] = [beforeMutationTs, 0];
hasCustomOptimisticData = !isUndefined(customOptimisticData);
rollbackData = cache2.get(key);
if (hasCustomOptimisticData) {
optimisticData = isFunction(customOptimisticData) ? customOptimisticData(rollbackData) : customOptimisticData;
cache2.set(key, optimisticData);
broadcastState(cache2, key, optimisticData);
}
if (isFunction(data)) {
try {
data = data(cache2.get(key));
} catch (err) {
error = err;
}
}
if (!(data && isFunction(data.then)))
return [3, 2];
return [
4,
data.catch(function(err) {
error = err;
})
];
case 1:
data = _c.sent();
if (beforeMutationTs !== MUTATION[key][0]) {
if (error)
throw error;
return [2, data];
} else if (error && hasCustomOptimisticData && rollbackOnError) {
populateCache = true;
data = rollbackData;
cache2.set(key, rollbackData);
}
_c.label = 2;
case 2:
if (populateCache) {
if (!error) {
if (isFunction(populateCache)) {
data = populateCache(data, rollbackData);
}
cache2.set(key, data);
}
cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), { error }));
}
MUTATION[key][1] = getTimestamp();
return [
4,
broadcastState(cache2, key, data, error, UNDEFINED, revalidate, !!populateCache)
];
case 3:
res = _c.sent();
if (error)
throw error;
return [2, populateCache ? res : data];
}
});
});
};
var revalidateAllKeys = function(revalidators, type) {
for (var key in revalidators) {
if (revalidators[key][0])
revalidators[key][0](type);
}
};
var initCache = function(provider, options) {
if (!SWRGlobalState.has(provider)) {
var opts = mergeObjects(defaultConfigOptions, options);
var EVENT_REVALIDATORS = {};
var mutate2 = internalMutate.bind(UNDEFINED, provider);
var unmount = noop2;
SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate2]);
if (!IS_SERVER) {
var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = function() {
releaseFocus_1 && releaseFocus_1();
releaseReconnect_1 && releaseReconnect_1();
SWRGlobalState.delete(provider);
};
}
return [provider, mutate2, unmount];
}
return [provider, SWRGlobalState.get(provider)[4]];
};
var onErrorRetry = function(_, __, config, revalidate, opts) {
var maxRetryCount = config.errorRetryCount;
var currentRetryCount = opts.retryCount;
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {
return;
}
setTimeout(revalidate, timeout, opts);
};
var _a = initCache(/* @__PURE__ */ new Map());
var cache = _a[0];
var mutate = _a[1];
var defaultConfig = mergeObjects(
{
onLoadingSlow: noop2,
onSuccess: noop2,
onError: noop2,
onErrorRetry,
onDiscarded: noop2,
revalidateOnFocus: true,
revalidateOnReconnect: true,
revalidateIfStale: true,
shouldRetryOnError: true,
errorRetryInterval: slowConnection ? 1e4 : 5e3,
focusThrottleInterval: 5 * 1e3,
dedupingInterval: 2 * 1e3,
loadingTimeout: slowConnection ? 5e3 : 3e3,
compare: function(currentData, newData) {
return stableHash(currentData) == stableHash(newData);
},
isPaused: function() {
return false;
},
cache,
mutate,
fallback: {}
},
preset
);
var mergeConfigs = function(a, b) {
var v = mergeObjects(a, b);
if (b) {
var u1 = a.use, f1 = a.fallback;
var u2 = b.use, f2 = b.fallback;
if (u1 && u2) {
v.use = u1.concat(u2);
}
if (f1 && f2) {
v.fallback = mergeObjects(f1, f2);
}
}
return v;
};
var SWRConfigContext = (0, import_react2.createContext)({});
var SWRConfig$1 = function(props) {
var value = props.value;
var extendedConfig = mergeConfigs((0, import_react2.useContext)(SWRConfigContext), value);
var provider = value && value.provider;
var cacheContext = (0, import_react2.useState)(function() {
return provider ? initCache(provider(extendedConfig.cache || cache), value) : UNDEFINED;
})[0];
if (cacheContext) {
extendedConfig.cache = cacheContext[0];
extendedConfig.mutate = cacheContext[1];
}
useIsomorphicLayoutEffect(function() {
return cacheContext ? cacheContext[2] : UNDEFINED;
}, []);
return (0, import_react2.createElement)(SWRConfigContext.Provider, mergeObjects(props, {
value: extendedConfig
}));
};
var useStateWithDeps = function(state, unmountedRef) {
var rerender = (0, import_react2.useState)({})[1];
var stateRef = (0, import_react2.useRef)(state);
var stateDependenciesRef = (0, import_react2.useRef)({
data: false,
error: false,
isValidating: false
});
var setState = (0, import_react2.useCallback)(
function(payload) {
var shouldRerender = false;
var currentState = stateRef.current;
for (var _ in payload) {
var k = _;
if (currentState[k] !== payload[k]) {
currentState[k] = payload[k];
if (stateDependenciesRef.current[k]) {
shouldRerender = true;
}
}
}
if (shouldRerender && !unmountedRef.current) {
rerender({});
}
},
[]
);
useIsomorphicLayoutEffect(function() {
stateRef.current = state;
});
return [stateRef, stateDependenciesRef.current, setState];
};
var normalize = function(args) {
return isFunction(args[1]) ? [args[0], args[1], args[2] || {}] : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}];
};
var useSWRConfig = function() {
return mergeObjects(defaultConfig, (0, import_react2.useContext)(SWRConfigContext));
};
var withArgs = function(hook) {
return function useSWRArgs() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var fallbackConfig = useSWRConfig();
var _a2 = normalize(args), key = _a2[0], fn = _a2[1], _config = _a2[2];
var config = mergeConfigs(fallbackConfig, _config);
var next = hook;
var use = config.use;
if (use) {
for (var i = use.length; i-- > 0; ) {
next = use[i](next);
}
}
return next(key, fn || config.fetcher, config);
};
};
var subscribeCallback = function(key, callbacks, callback) {
var keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return function() {
var index = keyedRevalidators.indexOf(callback);
if (index >= 0) {
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
keyedRevalidators.pop();
}
};
};
var WITH_DEDUPE = { dedupe: true };
var useSWRHandler = function(_key, fetcher, config) {
var cache2 = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline;
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], MUTATION = _a2[2], FETCH = _a2[3];
var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2];
var initialMountedRef = (0, import_react2.useRef)(false);
var unmountedRef = (0, import_react2.useRef)(false);
var keyRef = (0, import_react2.useRef)(key);
var fetcherRef = (0, import_react2.useRef)(fetcher);
var configRef = (0, import_react2.useRef)(config);
var getConfig = function() {
return configRef.current;
};
var isActive = function() {
return getConfig().isVisible() && getConfig().isOnline();
};
var patchFetchInfo = function(info2) {
return cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), info2));
};
var cached = cache2.get(key);
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
var data = isUndefined(cached) ? fallback : cached;
var info = cache2.get(keyInfo) || {};
var error = info.error;
var isInitialMount = !initialMountedRef.current;
var shouldRevalidate = function() {
if (isInitialMount && !isUndefined(revalidateOnMount))
return revalidateOnMount;
if (getConfig().isPaused())
return false;
if (suspense)
return isUndefined(data) ? false : config.revalidateIfStale;
return isUndefined(data) || config.revalidateIfStale;
};
var resolveValidating = function() {
if (!key || !fetcher)
return false;
if (info.isValidating)
return true;
return isInitialMount && shouldRevalidate();
};
var isValidating = resolveValidating();
var _c = useStateWithDeps({
data,
error,
isValidating
}, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2];
var revalidate = (0, import_react2.useCallback)(
function(revalidateOpts) {
return __awaiter(void 0, void 0, void 0, function() {
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1;
var _a3;
return __generator(this, function(_b2) {
switch (_b2.label) {
case 0:
currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return [2, false];
}
loading = true;
opts = revalidateOpts || {};
shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
isCurrentKeyMounted = function() {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
};
cleanupState = function() {
var requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
newState = { isValidating: false };
finishRequestAndUpdateState = function() {
patchFetchInfo({ isValidating: false });
if (isCurrentKeyMounted()) {
setState(newState);
}
};
patchFetchInfo({
isValidating: true
});
setState({ isValidating: true });
_b2.label = 1;
case 1:
_b2.trys.push([1, 3, , 4]);
if (shouldStartNewRequest) {
broadcastState(cache2, key, stateRef.current.data, stateRef.current.error, true);
if (config.loadingTimeout && !cache2.get(key)) {
setTimeout(function() {
if (loading && isCurrentKeyMounted()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()];
}
_a3 = FETCH[key], newData = _a3[0], startAt = _a3[1];
return [4, newData];
case 2:
newData = _b2.sent();
if (shouldStartNewRequest) {
setTimeout(cleanupState, config.dedupingInterval);
}
if (!FETCH[key] || FETCH[key][1] !== startAt) {
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onDiscarded(key);
}
}
return [2, false];
}
patchFetchInfo({
error: UNDEFINED
});
newState.error = UNDEFINED;
mutationInfo = MUTATION[key];
if (!isUndefined(mutationInfo) && (startAt <= mutationInfo[0] || startAt <= mutationInfo[1] || mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onDiscarded(key);
}
}
return [2, false];
}
if (!compare(stateRef.current.data, newData)) {
newState.data = newData;
} else {
newState.data = stateRef.current.data;
}
if (!compare(cache2.get(key), newData)) {
cache2.set(key, newData);
}
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onSuccess(newData, key, config);
}
}
return [3, 4];
case 3:
err_1 = _b2.sent();
cleanupState();
if (!getConfig().isPaused()) {
patchFetchInfo({ error: err_1 });
newState.error = err_1;
if (shouldStartNewRequest && isCurrentKeyMounted()) {
getConfig().onError(err_1, key, config);
if (typeof config.shouldRetryOnError === "boolean" && config.shouldRetryOnError || isFunction(config.shouldRetryOnError) && config.shouldRetryOnError(err_1)) {
if (isActive()) {
getConfig().onErrorRetry(err_1, key, config, revalidate, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
}
}
}
return [3, 4];
case 4:
loading = false;
finishRequestAndUpdateState();
if (isCurrentKeyMounted() && shouldStartNewRequest) {
broadcastState(cache2, key, newState.data, newState.error, false);
}
return [2, true];
}
});
});
},
[key]
);
var boundMutate = (0, import_react2.useCallback)(
internalMutate.bind(UNDEFINED, cache2, function() {
return keyRef.current;
}),
[]
);
useIsomorphicLayoutEffect(function() {
fetcherRef.current = fetcher;
configRef.current = config;
});
useIsomorphicLayoutEffect(function() {
if (!key)
return;
var keyChanged = key !== keyRef.current;
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
var onStateUpdate = function(updatedData, updatedError, updatedIsValidating) {
setState(mergeObjects(
{
error: updatedError,
isValidating: updatedIsValidating
},
compare(stateRef.current.data, updatedData) ? UNDEFINED : {
data: updatedData
}
));
};
var nextFocusRevalidatedAt = 0;
var onRevalidate = function(type) {
if (type == FOCUS_EVENT) {
var now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
softRevalidate();
}
} else if (type == RECONNECT_EVENT) {
if (getConfig().revalidateOnReconnect && isActive()) {
softRevalidate();
}
} else if (type == MUTATE_EVENT) {
return revalidate();
}
return;
};
var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate);
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
unmountedRef.current = false;
keyRef.current = key;
initialMountedRef.current = true;
if (keyChanged) {
setState({
data,
error,
isValidating
});
}
if (shouldRevalidate()) {
if (isUndefined(data) || IS_SERVER) {
softRevalidate();
} else {
rAF(softRevalidate);
}
}
return function() {
unmountedRef.current = true;
unsubUpdate();
unsubEvents();
};
}, [key, revalidate]);
useIsomorphicLayoutEffect(function() {
var timer;
function next() {
var interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval;
if (interval && timer !== -1) {
timer = setTimeout(execute, interval);
}
}
function execute() {
if (!stateRef.current.error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {
revalidate(WITH_DEDUPE).then(next);
} else {
next();
}
}
next();
return function() {
if (timer) {
clearTimeout(timer);
timer = -1;
}
};
}, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]);
(0, import_react2.useDebugValue)(data);
if (suspense && isUndefined(data) && key) {
fetcherRef.current = fetcher;
configRef.current = config;
unmountedRef.current = false;
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error;
}
return {
mutate: boundMutate,
get data() {
stateDependencies.data = true;
return data;
},
get error() {
stateDependencies.error = true;
return error;
},
get isValidating() {
stateDependencies.isValidating = true;
return isValidating;
}
};
};
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "default", {
value: defaultConfig
});
var useSWR = withArgs(useSWRHandler);
// src/hooks/useOrganization.tsx
var useOrganization = (params) => {
const { invitationList: invitationListParams, membershipList: membershipListParams } = params || {};
const { organization, lastOrganizationMember, lastOrganizationInvitation } = useOrganizationContext();
const session = useSessionContext();
const clerk = useClerkInstanceContext();
const shouldFetch = clerk.loaded && session && organization;
const pendingInvitations = !clerk.loaded ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.getPendingInvitations(invitationListParams);
};
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => {
var _a2;
return (_a2 = clerk.organization) == null ? void 0 : _a2.getMemberships(membershipListParams);
};
const {
data: invitationList,
isValidating: isInvitationsLoading,
mutate: mutateInvitationList
} = useSWR(
shouldFetch && invitationListParams ? cacheKey("invites", organization, lastOrganizationInvitation, invitationListParams) : null,
pendingInvitations
);
const {
data: membershipList,
isValidating: isMembershipsLoading,
mutate: mutateMembershipList
} = useSWR(
shouldFetch && membershipListParams ? cacheKey("memberships", organization, lastOrganizationMember, membershipListParams) : null,
currentOrganizationMemberships
);
if (organization === void 0) {
return {
isLoaded: false,
organization: void 0,
invitationList: void 0,
membershipList: void 0,
membership: void 0
};
}
if (organization === null) {
return {
isLoaded: true,
organization: null,
invitationList: null,
membershipList: null,
membership: null
};
}
if (!clerk.loaded && organization) {
return {
isLoaded: true,
organization,
invitationList: void 0,
membershipList: void 0,
membership: void 0
};
}
return {
isLoaded: !isMembershipsLoading && !isInvitationsLoading,
organization,
membershipList,
membership: getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id),
invitationList,
unstable__mutate: () => {
void mutateMembershipList();
void mutateInvitationList();
}
};
};
function getCurrentOrganizationMembership(organizationMemberships, activeOrganizationId) {
return organizationMemberships.find(
(organizationMembership) => organizationMembership.organization.id === activeOrganizationId
);
}
function cacheKey(type, organization, resource, pagination) {
return [type, organization.id, resource == null ? void 0 : resource.id, resource == null ? void 0 : resource.updatedAt, pagination.offset, pagination.limit].filter(Boolean).join("-");
}
// src/hooks/useOrganizationList.tsx
var useOrganizationList = () => {
const clerk = useClerkInstanceContext();
const user = useUserContext();
if (!clerk.loaded || !user) {
return { isLoaded: false, organizationList: void 0, createOrganization: void 0, setActive: void 0 };
}
return {
isLoaded: true,
organizationList: createOrganizationList(user.organizationMemberships),
setActive: clerk.setActive,
createOrganization: clerk.createOrganization
};
};
function createOrganizationList(organizationMemberships) {
return organizationMemberships.map((organizationMembership) => ({
membership: organizationMembership,
organization: organizationMembership.organization
}));
}
// src/hooks/useOrganizations.tsx
var useOrganizations = () => {
const clerk = useClerkInstanceContext();
if (!clerk.loaded) {
return {
isLoaded: false,
createOrganization: void 0,
getOrganizationMemberships: void 0,
getOrganization: void 0
};
}
return {
isLoaded: true,
createOrganization: clerk.createOrganization,
getOrganizationMemberships: clerk.getOrganizationMemberships,
getOrganization: clerk.getOrganization
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ClerkInstanceContext,
ClientContext,
LocalStorageBroadcastChannel,
OrganizationContext,
Poller,
SessionContext,
UserContext,
addYears,
assertContextExists,
camelToSnake,
colorToSameTypeString,
createContextAndHook,
createCookieHandler,
dateTo12HourTime,
deepCamelToSnake,
deepSnakeToCamel,
differenceInCalendarDays,
extension,
formatRelative,
hasAlpha,
hexStringToRgbaColor,
inBrowser,
inClientSide,
isHSLColor,
isIPV4Address,
isRGBColor,
isRetinaDisplay,
isTransparent,
isValidHexString,
isValidHslaString,
isValidRgbaString,
noop,
parseSearchParams,
readJSONFile,
snakeToCamel,
stringToHslaColor,
stringToSameTypeColor,
titleize,
toSentence,
useClerkInstanceContext,
useClientContext,
useOrganization,
useOrganizationContext,
useOrganizationList,
useOrganizations,
useSessionContext,
useUserContext
});
"use strict";var Rt=Object.create;var ae=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var Lt=(e,n)=>{for(var t in n)ae(e,t,{get:n[t],enumerable:!0})},Be=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of St(n))!Et.call(e,i)&&i!==t&&ae(e,i,{get:()=>n[i],enumerable:!(r=yt(n,i))||r.enumerable});return e};var wt=(e,n,t)=>(t=e!=null?Rt(zt(e)):{},Be(n||!e||!e.__esModule?ae(t,"default",{value:e,enumerable:!0}):t,e)),Tt=e=>Be(ae({},"__esModule",{value:!0}),e);var Gn={};Lt(Gn,{ClerkInstanceContext:()=>dn,ClientContext:()=>gn,LocalStorageBroadcastChannel:()=>Se,OrganizationContext:()=>hn,Poller:()=>cn,SessionContext:()=>vn,UserContext:()=>pn,addYears:()=>Jt,assertContextExists:()=>tt,camelToSnake:()=>Ee,colorToSameTypeString:()=>Xe,createContextAndHook:()=>H,createCookieHandler:()=>Xt,dateTo12HourTime:()=>Ze,deepCamelToSnake:()=>sn,deepSnakeToCamel:()=>un,differenceInCalendarDays:()=>Qe,extension:()=>tn,formatRelative:()=>Yt,hasAlpha:()=>Vt,hexStringToRgbaColor:()=>Ke,inBrowser:()=>Dt,inClientSide:()=>ln,isHSLColor:()=>Oe,isIPV4Address:()=>an,isRGBColor:()=>be,isRetinaDisplay:()=>Zt,isTransparent:()=>ue,isValidHexString:()=>Z,isValidHslaString:()=>se,isValidRgbaString:()=>oe,noop:()=>nn,parseSearchParams:()=>fn,readJSONFile:()=>qt,snakeToCamel:()=>ze,stringToHslaColor:()=>Ht,stringToSameTypeColor:()=>$t,titleize:()=>on,toSentence:()=>It,useClerkInstanceContext:()=>$,useClientContext:()=>mn,useOrganization:()=>kn,useOrganizationContext:()=>Te,useOrganizationList:()=>$n,useOrganizations:()=>Wn,useSessionContext:()=>we,useUserContext:()=>Le});module.exports=Tt(Gn);var It=e=>{if(e.length==0)return"";if(e.length==1)return e[0];let n=e.slice(0,-1).join(", ");return n+=`, or ${e.slice(-1)}`,n};function Dt(){return typeof window<"u"}var Mt=/^#?([A-F0-9]{6}|[A-F0-9]{3})$/i,At=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i,Pt=/^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i,_t=/^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i,Ut=/^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i,Z=e=>!!e.match(Mt),oe=e=>!!(e.match(At)||e.match(Pt)),se=e=>!!e.match(_t)||!!e.match(Ut),be=e=>typeof e!="string"&&"r"in e,Oe=e=>typeof e!="string"&&"h"in e,ue=e=>e==="transparent",Vt=e=>typeof e!="string"&&e.a!=null&&e.a<1;var Ft=/[hsla()]/g,kt=/[rgba()]/g,Ht=e=>e==="transparent"?{h:0,s:0,l:0,a:0}:Z(e)?Gt(e):se(e)?qe(e):oe(e)?Ye(e):null,$t=e=>(e=e.trim(),Z(e)?e.startsWith("#")?e:`#${e}`:oe(e)?Je(e):se(e)?qe(e):ue(e)?e:""),Xe=e=>typeof e=="string"&&(Z(e)||ue(e))?e:be(e)?Nt(e):Oe(e)?Wt(e):"",Ke=e=>{e=e.replace("#","");let n=parseInt(e.substring(0,2),16),t=parseInt(e.substring(2,4),16),r=parseInt(e.substring(4,6),16);return{r:n,g:t,b:r}},Nt=e=>{let{a:n,b:t,g:r,r:i}=e;return e.a===0?"transparent":e.a!=null?`rgba(${i},${r},${t},${n})`:`rgb(${i},${r},${t})`},Wt=e=>{let{h:n,s:t,l:r,a:i}=e,a=Math.round(t*100),o=Math.round(r*100);return e.a===0?"transparent":e.a!=null?`hsla(${n},${a}%,${o}%,${i})`:`hsl(${n},${a}%,${o}%)`},Gt=e=>{let n=Xe(Ke(e));return Ye(n)},Ye=e=>{let n=Je(e),t=n.r/255,r=n.g/255,i=n.b/255,a=Math.max(t,r,i),o=Math.min(t,r,i),u,f,s=(a+o)/2;if(a==o)u=f=0;else{let d=a-o;switch(f=s>=.5?d/(2-(a+o)):d/(a+o),a){case t:u=(r-i)/d*60;break;case r:u=((i-t)/d+2)*60;break;default:u=((t-r)/d+4)*60;break}}let l={h:Math.round(u),s:f,l:s},g=n.a;return g!=null&&(l.a=g),l},Je=e=>{let[n,t,r,i]=e.replace(kt,"").split(",").map(a=>Number.parseFloat(a));return{r:n,g:t,b:r,a:i}},qe=e=>{let[n,t,r,i]=e.replace(Ft,"").split(",").map(a=>Number.parseFloat(a));return{h:n,s:t/100,l:r/100,a:i}};function ce(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)e[r]=t[r]}return e}var jt={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Re(e,n){function t(i,a,o){if(!(typeof document>"u")){o=ce({},n,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in o)!o[f]||(u+="; "+f,o[f]!==!0&&(u+="="+o[f].split(";")[0]));return document.cookie=i+"="+e.write(a,i)+u}}function r(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var a=document.cookie?document.cookie.split("; "):[],o={},u=0;u<a.length;u++){var f=a[u].split("="),s=f.slice(1).join("=");try{var l=decodeURIComponent(f[0]);if(o[l]=e.read(s,l),i===l)break}catch{}}return i?o[i]:o}}return Object.create({set:t,get:r,remove:function(i,a){t(i,"",ce({},a,{expires:-1}))},withAttributes:function(i){return Re(this.converter,ce({},this.attributes,i))},withConverter:function(i){return Re(ce({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(e)}})}var Bt=Re(jt,{path:"/"}),le=Bt;function Xt(e){return{get(){return le.get(e)},set(n,t={}){return le.set(e,n,t)},remove(n){le.remove(e,n)}}}var Kt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Ze(e){return e?e.toLocaleString("en-US",{hour:"2-digit",minute:"numeric",hour12:!0}):""}function Qe(e,n,{absolute:t=!0}={}){if(!e||!n)return 0;let r=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),i=Date.UTC(n.getFullYear(),n.getMonth(),n.getDate()),a=Math.floor((i-r)/864e5);return t?Math.abs(a):a}function ye(e){try{return new Date(e||new Date)}catch{return new Date}}function Yt(e,n){if(!e||!n)return"";let t=ye(e),r=ye(n),i=Qe(r,t,{absolute:!1}),a=Ze(t),o=Kt[t.getDay()];return i<-6?t.toLocaleDateString():i<-1?`last ${o} at ${a}`:i===-1?`yesterday at ${a}`:i===0?`today at ${a}`:i===1?`tomorrow at ${a}`:i<7?`${o} at ${a}`:t.toLocaleDateString()}function Jt(e,n){let t=ye(e);return t.setFullYear(t.getFullYear()+n),t}function qt(e){return new Promise((n,t)=>{let r=new FileReader;r.addEventListener("load",function(){let i=JSON.parse(r.result);n(i)}),r.addEventListener("error",t),r.readAsText(e)})}function Zt(){if(!window.matchMedia)return!1;let e=window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");return e&&e.matches||window.devicePixelRatio>1}var Qt="__lsbc__",Se=class{constructor(n){this.eventTarget=window;this.postMessage=n=>{try{localStorage.setItem(this.channelKey,JSON.stringify(n)),localStorage.removeItem(this.channelKey)}catch{}};this.addEventListener=(n,t)=>{this.eventTarget.addEventListener(this.prefixEventName(n),r=>{t(r)})};this.setupLocalStorageListener=()=>{let n=t=>{if(!(t.key!==this.channelKey||!t.newValue))try{let r=JSON.parse(t.newValue||""),i=new MessageEvent(this.prefixEventName("message"),{data:r});this.eventTarget.dispatchEvent(i)}catch{}};window.addEventListener("storage",n)};this.channelKey=Qt+n,this.setupLocalStorageListener()}prefixEventName(n){return this.channelKey+n}};var en=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"}),tn=e=>en[e];var nn=(...e)=>{};var rn=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;function an(e){return rn.test(e||"")}function on(e){let n=e||"";return n.charAt(0).toUpperCase()+n.slice(1)}function ze(e){return e.replace(/([-_][a-z])/g,n=>n.toUpperCase().replace(/-|_/,""))}function Ee(e){return e.replace(/[A-Z]/g,n=>`_${n.toLowerCase()}`)}var et=e=>{let n=t=>{if(!t)return t;if(Array.isArray(t))return t.map(a=>typeof a=="object"||Array.isArray(a)?n(a):a);let r={...t},i=Object.keys(r);for(let a of i){let o=e(a.toString());o!==a&&(r[o]=r[a],delete r[a]),typeof r[o]=="object"&&(r[o]=n(r[o]))}return r};return n},sn=et(Ee),un=et(ze);function cn({delayInMs:e}={delayInMs:1e3}){let n,t=!1,r=()=>{clearTimeout(n),t=!0},i=async a=>{t=!1,await a(r),!t&&(n=setTimeout(()=>i(a),e))};return{run:i,stop:r}}var ln=()=>typeof window<"u";function fn(e=""){return e.startsWith("?")&&(e=e.slice(1)),new URLSearchParams(e)}var fe=wt(require("react"));function tt(e,n){if(!e)throw typeof n=="string"?new Error(n):new Error(`${n.displayName} not found`)}var H=(e,n)=>{let{assertCtxFn:t=tt}=n||{},r=fe.default.createContext(void 0);return r.displayName=e,[r,()=>{let o=fe.default.useContext(r);return t(o,`${e} not found`),o.value},()=>{let o=fe.default.useContext(r);return o?o.value:{}}]};var[dn,$]=H("ClerkInstanceContext"),[pn,Le]=H("UserContext"),[gn,mn]=H("ClientContext"),[vn,we]=H("SessionContext"),[hn,Te]=H("OrganizationContext");var p=require("react");function at(e,n,t,r){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function u(l){try{s(r.next(l))}catch(g){o(g)}}function f(l){try{s(r.throw(l))}catch(g){o(g)}}function s(l){l.done?a(l.value):i(l.value).then(u,f)}s((r=r.apply(e,n||[])).next())})}function ot(e,n){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(s){return function(l){return f([s,l])}}function f(s){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,i=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){t.label=s[1];break}if(s[0]===6&&t.label<a[1]){t.label=a[1],a=s;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(s);break}a[2]&&t.ops.pop(),t.trys.pop();continue}s=n.call(e,t)}catch(l){s=[6,l],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var T=function(){},h=T(),Q=Object,x=function(e){return e===h},_=function(e){return typeof e=="function"},M=function(e,n){return Q.assign({},e,n)},Ve="undefined",Fe=function(){return typeof window!=Ve},Cn=function(){return typeof document!=Ve},xn=function(){return Fe()&&typeof window.requestAnimationFrame!=Ve},de=new WeakMap,bn=0,ne=function(e){var n=typeof e,t=e&&e.constructor,r=t==Date,i,a;if(Q(e)===e&&!r&&t!=RegExp){if(i=de.get(e),i)return i;if(i=++bn+"~",de.set(e,i),t==Array){for(i="@",a=0;a<e.length;a++)i+=ne(e[a])+",";de.set(e,i)}if(t==Q){i="#";for(var o=Q.keys(e).sort();!x(a=o.pop());)x(e[a])||(i+=a+":"+ne(e[a])+",");de.set(e,i)}}else i=r?e.toJSON():n=="symbol"?e.toString():n=="string"?JSON.stringify(e):""+e;return i},Me=!0,On=function(){return Me},st=Fe(),ke=Cn(),Ae=st&&window.addEventListener?window.addEventListener.bind(window):T,Rn=ke?document.addEventListener.bind(document):T,Pe=st&&window.removeEventListener?window.removeEventListener.bind(window):T,yn=ke?document.removeEventListener.bind(document):T,Sn=function(){var e=ke&&document.visibilityState;return x(e)||e!=="hidden"},zn=function(e){return Rn("visibilitychange",e),Ae("focus",e),function(){yn("visibilitychange",e),Pe("focus",e)}},En=function(e){var n=function(){Me=!0,e()},t=function(){Me=!1};return Ae("online",n),Ae("offline",t),function(){Pe("online",n),Pe("offline",t)}},Ln={isOnline:On,isVisible:Sn},wn={initFocus:zn,initReconnect:En},pe=!Fe()||"Deno"in window,Tn=function(e){return xn()?window.requestAnimationFrame(e):setTimeout(e,1)},ee=pe?p.useEffect:p.useLayoutEffect,Ie=typeof navigator<"u"&&navigator.connection,nt=!pe&&Ie&&(["slow-2g","2g"].includes(Ie.effectiveType)||Ie.saveData),ut=function(e){if(_(e))try{e=e()}catch{e=""}var n=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?ne(e):"";var t=e?"$swr$"+e:"";return[e,n,t]},N=new WeakMap,ct=0,lt=1,ft=2,te=function(e,n,t,r,i,a,o){o===void 0&&(o=!0);var u=N.get(e),f=u[0],s=u[1],l=u[3],g=f[n],d=s[n];if(o&&d)for(var y=0;y<d.length;++y)d[y](t,r,i);return a&&(delete l[n],g&&g[0])?g[0](ft).then(function(){return e.get(n)}):e.get(n)},In=0,_e=function(){return++In},dt=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return at(void 0,void 0,void 0,function(){var t,r,i,a,o,u,f,s,l,g,d,y,W,b,m,c,B,U,I,E,V;return ot(this,function(A){switch(A.label){case 0:if(t=e[0],r=e[1],i=e[2],a=e[3],o=typeof a=="boolean"?{revalidate:a}:a||{},u=x(o.populateCache)?!0:o.populateCache,f=o.revalidate!==!1,s=o.rollbackOnError!==!1,l=o.optimisticData,g=ut(r),d=g[0],y=g[2],!d)return[2];if(W=N.get(t),b=W[2],e.length<3)return[2,te(t,d,t.get(d),h,h,f,!0)];if(m=i,B=_e(),b[d]=[B,0],U=!x(l),I=t.get(d),U&&(E=_(l)?l(I):l,t.set(d,E),te(t,d,E)),_(m))try{m=m(t.get(d))}catch(F){c=F}return m&&_(m.then)?[4,m.catch(function(F){c=F})]:[3,2];case 1:if(m=A.sent(),B!==b[d][0]){if(c)throw c;return[2,m]}else c&&U&&s&&(u=!0,m=I,t.set(d,I));A.label=2;case 2:return u&&(c||(_(u)&&(m=u(m,I)),t.set(d,m)),t.set(y,M(t.get(y),{error:c}))),b[d][1]=_e(),[4,te(t,d,m,c,h,f,!!u)];case 3:if(V=A.sent(),c)throw c;return[2,u?V:m]}})})},rt=function(e,n){for(var t in e)e[t][0]&&e[t][0](n)},pt=function(e,n){if(!N.has(e)){var t=M(wn,n),r={},i=dt.bind(h,e),a=T;if(N.set(e,[r,{},{},{},i]),!pe){var o=t.initFocus(setTimeout.bind(h,rt.bind(h,r,ct))),u=t.initReconnect(setTimeout.bind(h,rt.bind(h,r,lt)));a=function(){o&&o(),u&&u(),N.delete(e)}}return[e,i,a]}return[e,N.get(e)[4]]},Dn=function(e,n,t,r,i){var a=t.errorRetryCount,o=i.retryCount,u=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!x(a)&&o>a||setTimeout(r,u,i)},gt=pt(new Map),mt=gt[0],Mn=gt[1],vt=M({onLoadingSlow:T,onSuccess:T,onError:T,onErrorRetry:Dn,onDiscarded:T,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:nt?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:nt?5e3:3e3,compare:function(e,n){return ne(e)==ne(n)},isPaused:function(){return!1},cache:mt,mutate:Mn,fallback:{}},Ln),ht=function(e,n){var t=M(e,n);if(n){var r=e.use,i=e.fallback,a=n.use,o=n.fallback;r&&a&&(t.use=r.concat(a)),i&&o&&(t.fallback=M(i,o))}return t},Ue=(0,p.createContext)({}),An=function(e){var n=e.value,t=ht((0,p.useContext)(Ue),n),r=n&&n.provider,i=(0,p.useState)(function(){return r?pt(r(t.cache||mt),n):h})[0];return i&&(t.cache=i[0],t.mutate=i[1]),ee(function(){return i?i[2]:h},[]),(0,p.createElement)(Ue.Provider,M(e,{value:t}))},Pn=function(e,n){var t=(0,p.useState)({})[1],r=(0,p.useRef)(e),i=(0,p.useRef)({data:!1,error:!1,isValidating:!1}),a=(0,p.useCallback)(function(o){var u=!1,f=r.current;for(var s in o){var l=s;f[l]!==o[l]&&(f[l]=o[l],i.current[l]&&(u=!0))}u&&!n.current&&t({})},[]);return ee(function(){r.current=e}),[r,i.current,a]},_n=function(e){return _(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},Un=function(){return M(vt,(0,p.useContext)(Ue))},Vn=function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=Un(),a=_n(t),o=a[0],u=a[1],f=a[2],s=ht(i,f),l=e,g=s.use;if(g)for(var d=g.length;d-- >0;)l=g[d](l);return l(o,u||s.fetcher,s)}},it=function(e,n,t){var r=n[e]||(n[e]=[]);return r.push(t),function(){var i=r.indexOf(t);i>=0&&(r[i]=r[r.length-1],r.pop())}},De={dedupe:!0},Fn=function(e,n,t){var r=t.cache,i=t.compare,a=t.fallbackData,o=t.suspense,u=t.revalidateOnMount,f=t.refreshInterval,s=t.refreshWhenHidden,l=t.refreshWhenOffline,g=N.get(r),d=g[0],y=g[1],W=g[2],b=g[3],m=ut(e),c=m[0],B=m[1],U=m[2],I=(0,p.useRef)(!1),E=(0,p.useRef)(!1),V=(0,p.useRef)(c),A=(0,p.useRef)(n),F=(0,p.useRef)(t),v=function(){return F.current},ge=function(){return v().isVisible()&&v().isOnline()},re=function(S){return r.set(U,M(r.get(U),S))},$e=r.get(c),xt=x(a)?t.fallback[c]:a,D=x($e)?xt:$e,Ne=r.get(U)||{},X=Ne.error,We=!I.current,Ge=function(){return We&&!x(u)?u:v().isPaused()?!1:o?x(D)?!1:t.revalidateIfStale:x(D)||t.revalidateIfStale},bt=function(){return!c||!n?!1:Ne.isValidating?!0:We&&Ge()},me=bt(),ve=Pn({data:D,error:X,isValidating:me},E),G=ve[0],he=ve[1],ie=ve[2],k=(0,p.useCallback)(function(S){return at(void 0,void 0,void 0,function(){var O,R,z,K,Y,L,C,P,w,Ce,J,j,xe;return ot(this,function(q){switch(q.label){case 0:if(O=A.current,!c||!O||E.current||v().isPaused())return[2,!1];K=!0,Y=S||{},L=!b[c]||!Y.dedupe,C=function(){return!E.current&&c===V.current&&I.current},P=function(){var je=b[c];je&&je[1]===z&&delete b[c]},w={isValidating:!1},Ce=function(){re({isValidating:!1}),C()&&ie(w)},re({isValidating:!0}),ie({isValidating:!0}),q.label=1;case 1:return q.trys.push([1,3,,4]),L&&(te(r,c,G.current.data,G.current.error,!0),t.loadingTimeout&&!r.get(c)&&setTimeout(function(){K&&C()&&v().onLoadingSlow(c,t)},t.loadingTimeout),b[c]=[O.apply(void 0,B),_e()]),xe=b[c],R=xe[0],z=xe[1],[4,R];case 2:return R=q.sent(),L&&setTimeout(P,t.dedupingInterval),!b[c]||b[c][1]!==z?(L&&C()&&v().onDiscarded(c),[2,!1]):(re({error:h}),w.error=h,J=W[c],!x(J)&&(z<=J[0]||z<=J[1]||J[1]===0)?(Ce(),L&&C()&&v().onDiscarded(c),[2,!1]):(i(G.current.data,R)?w.data=G.current.data:w.data=R,i(r.get(c),R)||r.set(c,R),L&&C()&&v().onSuccess(R,c,t),[3,4]));case 3:return j=q.sent(),P(),v().isPaused()||(re({error:j}),w.error=j,L&&C()&&(v().onError(j,c,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||_(t.shouldRetryOnError)&&t.shouldRetryOnError(j))&&ge()&&v().onErrorRetry(j,c,t,k,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return K=!1,Ce(),C()&&L&&te(r,c,w.data,w.error,!1),[2,!0]}})})},[c]),Ot=(0,p.useCallback)(dt.bind(h,r,function(){return V.current}),[]);if(ee(function(){A.current=n,F.current=t}),ee(function(){if(!!c){var S=c!==V.current,O=k.bind(h,De),R=function(C,P,w){ie(M({error:P,isValidating:w},i(G.current.data,C)?h:{data:C}))},z=0,K=function(C){if(C==ct){var P=Date.now();v().revalidateOnFocus&&P>z&&ge()&&(z=P+v().focusThrottleInterval,O())}else if(C==lt)v().revalidateOnReconnect&&ge()&&O();else if(C==ft)return k()},Y=it(c,y,R),L=it(c,d,K);return E.current=!1,V.current=c,I.current=!0,S&&ie({data:D,error:X,isValidating:me}),Ge()&&(x(D)||pe?O():Tn(O)),function(){E.current=!0,Y(),L()}}},[c,k]),ee(function(){var S;function O(){var z=_(f)?f(D):f;z&&S!==-1&&(S=setTimeout(R,z))}function R(){!G.current.error&&(s||v().isVisible())&&(l||v().isOnline())?k(De).then(O):O()}return O(),function(){S&&(clearTimeout(S),S=-1)}},[f,s,l,k]),(0,p.useDebugValue)(D),o&&x(D)&&c)throw A.current=n,F.current=t,E.current=!1,x(X)?k(De):X;return{mutate:Ot,get data(){return he.data=!0,D},get error(){return he.error=!0,X},get isValidating(){return he.isValidating=!0,me}}},_r=Q.defineProperty(An,"default",{value:vt});var He=Vn(Fn);var kn=e=>{let{invitationList:n,membershipList:t}=e||{},{organization:r,lastOrganizationMember:i,lastOrganizationInvitation:a}=Te(),o=we(),u=$(),f=u.loaded&&o&&r,s=u.loaded?()=>{var c;return(c=u.organization)==null?void 0:c.getPendingInvitations(n)}:()=>[],l=u.loaded?()=>{var c;return(c=u.organization)==null?void 0:c.getMemberships(t)}:()=>[],{data:g,isValidating:d,mutate:y}=He(f&&n?Ct("invites",r,a,n):null,s),{data:W,isValidating:b,mutate:m}=He(f&&t?Ct("memberships",r,i,t):null,l);return r===void 0?{isLoaded:!1,organization:void 0,invitationList:void 0,membershipList:void 0,membership:void 0}:r===null?{isLoaded:!0,organization:null,invitationList:null,membershipList:null,membership:null}:!u.loaded&&r?{isLoaded:!0,organization:r,invitationList:void 0,membershipList:void 0,membership:void 0}:{isLoaded:!b&&!d,organization:r,membershipList:W,membership:Hn(o.user.organizationMemberships,r.id),invitationList:g,unstable__mutate:()=>{m(),y()}}};function Hn(e,n){return e.find(t=>t.organization.id===n)}function Ct(e,n,t,r){return[e,n.id,t==null?void 0:t.id,t==null?void 0:t.updatedAt,r.offset,r.limit].filter(Boolean).join("-")}var $n=()=>{let e=$(),n=Le();return!e.loaded||!n?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:Nn(n.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function Nn(e){return e.map(n=>({membership:n,organization:n.organization}))}var Wn=()=>{let e=$();return e.loaded?{isLoaded:!0,createOrganization:e.createOrganization,getOrganizationMemberships:e.getOrganizationMemberships,getOrganization:e.getOrganization}:{isLoaded:!1,createOrganization:void 0,getOrganizationMemberships:void 0,getOrganization:void 0}};0&&(module.exports={ClerkInstanceContext,ClientContext,LocalStorageBroadcastChannel,OrganizationContext,Poller,SessionContext,UserContext,addYears,assertContextExists,camelToSnake,colorToSameTypeString,createContextAndHook,createCookieHandler,dateTo12HourTime,deepCamelToSnake,deepSnakeToCamel,differenceInCalendarDays,extension,formatRelative,hasAlpha,hexStringToRgbaColor,inBrowser,inClientSide,isHSLColor,isIPV4Address,isRGBColor,isRetinaDisplay,isTransparent,isValidHexString,isValidHslaString,isValidRgbaString,noop,parseSearchParams,readJSONFile,snakeToCamel,stringToHslaColor,stringToSameTypeColor,titleize,toSentence,useClerkInstanceContext,useClientContext,useOrganization,useOrganizationContext,useOrganizationList,useOrganizations,useSessionContext,useUserContext});
/*! *****************************************************************************

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

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

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/testUtils/index.ts
var testUtils_exports2 = {};
__export(testUtils_exports2, {
noop: () => noop,
render: () => customRender,
userEvent: () => import_user_event.default
});
module.exports = __toCommonJS(testUtils_exports2);
// src/testUtils/testUtils.ts
var testUtils_exports = {};
__export(testUtils_exports, {
noop: () => noop,
render: () => customRender,
userEvent: () => import_user_event.default
});
var import_extend_expect = require("@testing-library/jest-dom/extend-expect");
var import_react = require("@testing-library/react");
// ../../node_modules/js-cookie/dist/js.cookie.mjs
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
target[key] = source[key];
}
}
return target;
}
var defaultConverter = {
read: function(value) {
if (value[0] === '"') {
value = value.slice(1, -1);
}
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
},
write: function(value) {
return encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
decodeURIComponent
);
}
};
function init(converter, defaultAttributes) {
function set(key, value, attributes) {
if (typeof document === "undefined") {
return;
}
attributes = assign({}, defaultAttributes, attributes);
if (typeof attributes.expires === "number") {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString();
}
key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var stringifiedAttributes = "";
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += "; " + attributeName;
if (attributes[attributeName] === true) {
continue;
}
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
}
return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes;
}
function get(key) {
if (typeof document === "undefined" || arguments.length && !key) {
return;
}
var cookies = document.cookie ? document.cookie.split("; ") : [];
var jar = {};
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split("=");
var value = parts.slice(1).join("=");
try {
var foundKey = decodeURIComponent(parts[0]);
jar[foundKey] = converter.read(value, foundKey);
if (key === foundKey) {
break;
}
} catch (e) {
}
}
return key ? jar[key] : jar;
}
return Object.create(
{
set,
get,
remove: function(key, attributes) {
set(
key,
"",
assign({}, attributes, {
expires: -1
})
);
},
withAttributes: function(attributes) {
return init(this.converter, assign({}, this.attributes, attributes));
},
withConverter: function(converter2) {
return init(assign({}, this.converter, converter2), this.attributes);
}
},
{
attributes: { value: Object.freeze(defaultAttributes) },
converter: { value: Object.freeze(converter) }
}
);
}
var api = init(defaultConverter, { path: "/" });
// src/utils/mimeTypeExtensions.ts
var MimeTypeToExtensionMap = Object.freeze({
"image/png": "png",
"image/jpeg": "jpg",
"image/gif": "gif",
"image/webp": "webp",
"image/x-icon": "ico",
"image/vnd.microsoft.icon": "ico"
});
// src/utils/noop.ts
var noop = (..._args) => {
};
// src/utils/string.ts
function snakeToCamel(str) {
return str.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, ""));
}
function camelToSnake(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
// src/utils/object.ts
var createDeepObjectTransformer = (transform) => {
const deepTransform = (obj) => {
if (!obj) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((el) => {
if (typeof el === "object" || Array.isArray(el)) {
return deepTransform(el);
}
return el;
});
}
const copy = { ...obj };
const keys = Object.keys(copy);
for (const oldName of keys) {
const newName = transform(oldName.toString());
if (newName !== oldName) {
copy[newName] = copy[oldName];
delete copy[oldName];
}
if (typeof copy[newName] === "object") {
copy[newName] = deepTransform(copy[newName]);
}
}
return copy;
};
return deepTransform;
};
var deepCamelToSnake = createDeepObjectTransformer(camelToSnake);
var deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel);
// src/testUtils/testUtils.ts
__reExport(testUtils_exports, require("@testing-library/react"));
var import_user_event = __toESM(require("@testing-library/user-event"));
var customRender = (ui, options) => {
return (0, import_react.render)(ui, options);
};
// src/testUtils/index.ts
__reExport(testUtils_exports2, testUtils_exports, module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
noop,
render,
userEvent
});
"use strict";var v=Object.create;var d=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var y=(e,r)=>{for(var t in r)d(e,t,{get:r[t],enumerable:!0})},u=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of D(r))!I.call(e,n)&&n!==t&&d(e,n,{get:()=>r[n],enumerable:!(s=_(r,n))||s.enumerable});return e},c=(e,r,t)=>(u(e,r,"default"),t&&u(t,r,"default")),$=(e,r,t)=>(t=e!=null?v(L(e)):{},u(r||!e||!e.__esModule?d(t,"default",{value:e,enumerable:!0}):t,e)),A=e=>u(d({},"__esModule",{value:!0}),e);var g={};y(g,{noop:()=>C,render:()=>T,userEvent:()=>h.default});module.exports=A(g);var a={};y(a,{noop:()=>C,render:()=>T,userEvent:()=>h.default});var He=require("@testing-library/jest-dom/extend-expect"),E=require("@testing-library/react");function f(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var s in t)e[s]=t[s]}return e}var H={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function x(e,r){function t(n,i,o){if(!(typeof document>"u")){o=f({},r,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),n=encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var p="";for(var l in o)!o[l]||(p+="; "+l,o[l]!==!0&&(p+="="+o[l].split(";")[0]));return document.cookie=n+"="+e.write(i,n)+p}}function s(n){if(!(typeof document>"u"||arguments.length&&!n)){for(var i=document.cookie?document.cookie.split("; "):[],o={},p=0;p<i.length;p++){var l=i[p].split("="),w=l.slice(1).join("=");try{var m=decodeURIComponent(l[0]);if(o[m]=e.read(w,m),n===m)break}catch{}}return n?o[n]:o}}return Object.create({set:t,get:s,remove:function(n,i){t(n,"",f({},i,{expires:-1}))},withAttributes:function(n){return x(this.converter,f({},this.attributes,n))},withConverter:function(n){return x(f({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}var W=x(H,{path:"/"});var se=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"});var C=(...e)=>{};function S(e){return e.replace(/([-_][a-z])/g,r=>r.toUpperCase().replace(/-|_/,""))}function b(e){return e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`)}var R=e=>{let r=t=>{if(!t)return t;if(Array.isArray(t))return t.map(i=>typeof i=="object"||Array.isArray(i)?r(i):i);let s={...t},n=Object.keys(s);for(let i of n){let o=e(i.toString());o!==i&&(s[o]=s[i],delete s[i]),typeof s[o]=="object"&&(s[o]=r(s[o]))}return s};return r},le=R(b),ue=R(S);c(a,require("@testing-library/react"));var h=$(require("@testing-library/user-event")),T=(e,r)=>(0,E.render)(e,r);c(g,a,module.exports);0&&(module.exports={noop,render,userEvent});
/*! js-cookie v3.0.1 | MIT */
//# sourceMappingURL=index.js.map
{
"name": "@clerk/shared",
"version": "0.5.2-staging.0",
"version": "0.5.2-staging.1",
"description": "Internal package utils used by the Clerk SDKs",

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

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

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

"license": "ISC",
"gitHead": "b5040820b07a726b372422363c11653b679f0dd4",
"gitHead": "e428cd983008ccce9e41c63e5680fb2bd217b25d",
"publishConfig": {

@@ -44,0 +44,0 @@ "access": "public"

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc