// ==UserScript== // @name ChatGPT Exporter // @name:zh-CN ChatGPT Exporter // @name:zh-TW ChatGPT Exporter // @namespace pionxzh // @version 2.29.1 // @author pionxzh // @description Easily export the whole ChatGPT conversation history for further analysis or sharing. // @description:zh-CN 轻松导出 ChatGPT 聊天记录,以便进一步分析或分享。 // @description:zh-TW 輕鬆匯出 ChatGPT 聊天紀錄,以便進一步分析或分享。 // @license MIT // @icon https://chat.openai.com/favicon.ico // @match https://chat.openai.com/ // @match https://chat.openai.com/?model=* // @match https://chat.openai.com/?ce_license_key=* // @match https://chat.openai.com/?license_key=* // @match https://chat.openai.com/?license=* // @match https://chat.openai.com/c/* // @match https://chat.openai.com/g/* // @match https://chat.openai.com/gpts // @match https://chat.openai.com/gpts/* // @match https://chat.openai.com/share/* // @match https://chat.openai.com/share/*/continue // @match https://chatgpt.com/ // @match https://chatgpt.com/?model=* // @match https://chatgpt.com/?ce_license_key=* // @match https://chatgpt.com/?license_key=* // @match https://chatgpt.com/?license=* // @match https://chatgpt.com/c/* // @match https://chatgpt.com/g/* // @match https://chatgpt.com/gpts // @match https://chatgpt.com/gpts/* // @match https://chatgpt.com/share/* // @match https://chatgpt.com/share/*/continue // @match https://new.oaifree.com/ // @match https://new.oaifree.com/?model=* // @match https://new.oaifree.com/?ce_license_key=* // @match https://new.oaifree.com/?license_key=* // @match https://new.oaifree.com/?license=* // @match https://new.oaifree.com/c/* // @match https://new.oaifree.com/g/* // @match https://new.oaifree.com/gpts // @match https://new.oaifree.com/gpts/* // @match https://new.oaifree.com/share/* // @match https://new.oaifree.com/share/*/continue // @match https://gemini.google.com/ // @match https://gemini.google.com/app // @match https://gemini.google.com/app/* // @match https://gemini.google.com/share/* // @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js // @require https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js // @grant GM_deleteValue // @grant GM_getValue // @grant GM_setValue // @grant unsafeWindow // @run-at document-end // ==/UserScript== (function(jszip, html2canvas) { "use strict"; var __create$1 = Object.create; var __defProp$2 = Object.defineProperty; var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor; var __getOwnPropNames$1 = Object.getOwnPropertyNames; var __getProtoOf$1 = Object.getPrototypeOf; var __hasOwnProp$2 = Object.prototype.hasOwnProperty; var __copyProps$1 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$1(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp$2.call(to, key) && key !== except) __defProp$2(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable }); } return to; }; var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$1(__getProtoOf$1(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$2(target, "default", { value: mod, enumerable: true }) : target, mod)); jszip = __toESM$1(jszip); html2canvas = __toESM$1(html2canvas); var s$7 = new Set(); var _css = async (t) => { if (s$7.has(t)) return; s$7.add(t); ((e) => { const o = document.createElement("style"); o.textContent = e; document.head.append(o); setInterval(() => { if (o.isConnected) return; document.head.append(o); }, 300); })(t); }; var __create = Object.create; var __defProp$1 = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res); var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); var __exportAll = (all, no_symbols) => { let target = {}; for (var name in all) __defProp$1(target, name, { get: all[name], enumerable: true }); if (!no_symbols) __defProp$1(target, Symbol.toStringTag, { value: "Module" }); return target; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$1(to, key, { get: ((k) => from[k]).bind(null, 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$1(target, "default", { value: mod, enumerable: true }) : target, mod)); var __toCommonJS = (mod) => __hasOwnProp$1.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp$1({}, "__esModule", { value: true }), mod); function m$3(n, l) { for (var u in l) n[u] = l[u]; return n; } function b$3(n) { n && n.parentNode && n.parentNode.removeChild(n); } function k$2(l, u, t) { var i, r, o, e = {}; for (o in u) "key" == o ? i = u[o] : "ref" == o ? r = u[o] : e[o] = u[o]; if (arguments.length > 2 && (e.children = arguments.length > 3 ? n$3.call(arguments, 2) : t), "function" == typeof l && null != l.defaultProps) for (o in l.defaultProps) void 0 === e[o] && (e[o] = l.defaultProps[o]); return x$2(l, e, i, r, null); } function x$2(n, t, i, r, o) { var e = { type: n, props: t, key: i, ref: r, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: null == o ? ++u$5 : o, __i: -1, __u: 0 }; return null == o && null != l$5.vnode && l$5.vnode(e), e; } function M$2() { return { current: null }; } function S(n) { return n.children; } function C$6(n, l) { this.props = n, this.context = l; } function $$1(n, l) { if (null == l) return n.__ ? $$1(n.__, n.__i + 1) : null; for (var u; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) return u.__e; return "function" == typeof n.type ? $$1(n) : null; } function I$3(n) { if (n.__P && n.__d) { var u = n.__v, t = u.__e, i = [], r = [], o = m$3({}, u); o.__v = u.__v + 1, l$5.vnode && l$5.vnode(o), q$2(n.__P, o, u, n.__n, n.__P.namespaceURI, 32 & u.__u ? [t] : null, i, null == t ? $$1(u) : t, !!(32 & u.__u), r), o.__v = u.__v, o.__.__k[o.__i] = o, D$3(i, o, r), u.__e = u.__ = null, o.__e != t && P$4(o); } } function P$4(n) { if (null != (n = n.__) && null != n.__c) return n.__e = n.__c.base = null, n.__k.some(function(l) { if (null != l && null != l.__e) return n.__e = n.__c.base = l.__e; }), P$4(n); } function A$3(n) { (!n.__d && (n.__d = !0) && i$3.push(n) && !H$3.__r++ || r$4 != l$5.debounceRendering) && ((r$4 = l$5.debounceRendering) || o$7)(H$3); } function H$3() { try { for (var n, l = 1; i$3.length;) i$3.length > l && i$3.sort(e$4), n = i$3.shift(), l = i$3.length, I$3(n); } finally { i$3.length = H$3.__r = 0; } } function L$4(n, l, u, t, i, r, o, e, f, c, a) { var s, h, p, v, y, _, g, m = t && t.__k || w$4, b = l.length; for (f = T$2(u, l, m, f, b), s = 0; s < b; s++) null != (p = u.__k[s]) && (h = -1 != p.__i && m[p.__i] || d$2, p.__i = s, _ = q$2(n, p, h, i, r, o, e, f, c, a), v = p.__e, p.ref && h.ref != p.ref && (h.ref && J$1(h.ref, null, p), a.push(p.ref, p.__c || v, p)), null == y && null != v && (y = v), (g = !!(4 & p.__u)) || h.__k === p.__k ? (f = j$4(p, f, n, g), g && h.__e && (h.__e = null)) : "function" == typeof p.type && void 0 !== _ ? f = _ : v && (f = v.nextSibling), p.__u &= -7); return u.__e = y, f; } function T$2(n, l, u, t, i) { var r, o, e, f, c, a = u.length, s = a, h = 0; for (n.__k = new Array(i), r = 0; r < i; r++) null != (o = l[r]) && "boolean" != typeof o && "function" != typeof o ? ("string" == typeof o || "number" == typeof o || "bigint" == typeof o || o.constructor == String ? o = n.__k[r] = x$2(null, o, null, null, null) : g$3(o) ? o = n.__k[r] = x$2(S, { children: o }, null, null, null) : void 0 === o.constructor && o.__b > 0 ? o = n.__k[r] = x$2(o.type, o.props, o.key, o.ref ? o.ref : null, o.__v) : n.__k[r] = o, f = r + h, o.__ = n, o.__b = n.__b + 1, e = null, -1 != (c = o.__i = O$1(o, u, f, s)) && (s--, (e = u[c]) && (e.__u |= 2)), null == e || null == e.__v ? (-1 == c && (i > a ? h-- : i < a && h++), "function" != typeof o.type && (o.__u |= 4)) : c != f && (c == f - 1 ? h-- : c == f + 1 ? h++ : (c > f ? h-- : h++, o.__u |= 4))) : n.__k[r] = null; if (s) for (r = 0; r < a; r++) null != (e = u[r]) && 0 == (2 & e.__u) && (e.__e == t && (t = $$1(e)), K$2(e, e)); return t; } function j$4(n, l, u, t) { var i, r; if ("function" == typeof n.type) { for (i = n.__k, r = 0; i && r < i.length; r++) i[r] && (i[r].__ = n, l = j$4(i[r], l, u, t)); return l; } n.__e != l && (t && (l && n.type && !l.parentNode && (l = $$1(n)), u.insertBefore(n.__e, l || null)), l = n.__e); do l = l && l.nextSibling; while (null != l && 8 == l.nodeType); return l; } function F$3(n, l) { return l = l || [], null == n || "boolean" == typeof n || (g$3(n) ? n.some(function(n) { F$3(n, l); }) : l.push(n)), l; } function O$1(n, l, u, t) { var i, r, o, e = n.key, f = n.type, c = l[u], a = null != c && 0 == (2 & c.__u); if (null === c && null == e || a && e == c.key && f == c.type) return u; if (t > (a ? 1 : 0)) { for (i = u - 1, r = u + 1; i >= 0 || r < l.length;) if (null != (c = l[o = i >= 0 ? i-- : r++]) && 0 == (2 & c.__u) && e == c.key && f == c.type) return o; } return -1; } function z$2(n, l, u) { "-" == l[0] ? n.setProperty(l, null == u ? "" : u) : n[l] = null == u ? "" : "number" != typeof u || _$2.test(l) ? u : u + "px"; } function N$2(n, l, u, t, i) { var r, o; n: if ("style" == l) if ("string" == typeof u) n.style.cssText = u; else { if ("string" == typeof t && (n.style.cssText = t = ""), t) for (l in t) u && l in u || z$2(n.style, l, ""); if (u) for (l in u) t && u[l] == t[l] || z$2(n.style, l, u[l]); } else if ("o" == l[0] && "n" == l[1]) r = l != (l = l.replace(s$6, "$1")), o = l.toLowerCase(), l = o in n || "onFocusOut" == l || "onFocusIn" == l ? o.slice(2) : l.slice(2), n.l || (n.l = {}), n.l[l + r] = u, u ? t ? u[a$5] = t[a$5] : (u[a$5] = h$2, n.addEventListener(l, r ? v$1 : p$4, r)) : n.removeEventListener(l, r ? v$1 : p$4, r); else { if ("http://www.w3.org/2000/svg" == i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" != l && "height" != l && "href" != l && "list" != l && "form" != l && "tabIndex" != l && "download" != l && "rowSpan" != l && "colSpan" != l && "role" != l && "popover" != l && l in n) try { n[l] = null == u ? "" : u; break n; } catch (n) {} "function" == typeof u || (null == u || !1 === u && "-" != l[4] ? n.removeAttribute(l) : n.setAttribute(l, "popover" == l && 1 == u ? "" : u)); } } function V$3(n) { return function(u) { if (this.l) { var t = this.l[u.type + n]; if (null == u[c$3]) u[c$3] = h$2++; else if (u[c$3] < t[a$5]) return; return t(l$5.event ? l$5.event(u) : u); } }; } function q$2(n, u, t, i, r, o, e, f, c, a) { var s, h, p, v, y, d, _, k, x, M, $, I, P, A, H, T = u.type; if (void 0 !== u.constructor) return null; 128 & t.__u && (c = !!(32 & t.__u), o = [f = u.__e = t.__e]), (s = l$5.__b) && s(u); n: if ("function" == typeof T) try { if (k = u.props, x = T.prototype && T.prototype.render, M = (s = T.contextType) && i[s.__c], $ = s ? M ? M.props.value : s.__ : i, t.__c ? _ = (h = u.__c = t.__c).__ = h.__E : (x ? u.__c = h = new T(k, $) : (u.__c = h = new C$6(k, $), h.constructor = T, h.render = Q$1), M && M.sub(h), h.state || (h.state = {}), h.__n = i, p = h.__d = !0, h.__h = [], h._sb = []), x && null == h.__s && (h.__s = h.state), x && null != T.getDerivedStateFromProps && (h.__s == h.state && (h.__s = m$3({}, h.__s)), m$3(h.__s, T.getDerivedStateFromProps(k, h.__s))), v = h.props, y = h.state, h.__v = u, p) x && null == T.getDerivedStateFromProps && null != h.componentWillMount && h.componentWillMount(), x && null != h.componentDidMount && h.__h.push(h.componentDidMount); else { if (x && null == T.getDerivedStateFromProps && k !== v && null != h.componentWillReceiveProps && h.componentWillReceiveProps(k, $), u.__v == t.__v || !h.__e && null != h.shouldComponentUpdate && !1 === h.shouldComponentUpdate(k, h.__s, $)) { u.__v != t.__v && (h.props = k, h.state = h.__s, h.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.some(function(n) { n && (n.__ = u); }), w$4.push.apply(h.__h, h._sb), h._sb = [], h.__h.length && e.push(h); break n; } null != h.componentWillUpdate && h.componentWillUpdate(k, h.__s, $), x && null != h.componentDidUpdate && h.__h.push(function() { h.componentDidUpdate(v, y, d); }); } if (h.context = $, h.props = k, h.__P = n, h.__e = !1, I = l$5.__r, P = 0, x) h.state = h.__s, h.__d = !1, I && I(u), s = h.render(h.props, h.state, h.context), w$4.push.apply(h.__h, h._sb), h._sb = []; else do h.__d = !1, I && I(u), s = h.render(h.props, h.state, h.context), h.state = h.__s; while (h.__d && ++P < 25); h.state = h.__s, null != h.getChildContext && (i = m$3(m$3({}, i), h.getChildContext())), x && !p && null != h.getSnapshotBeforeUpdate && (d = h.getSnapshotBeforeUpdate(v, y)), A = null != s && s.type === S && null == s.key ? E$5(s.props.children) : s, f = L$4(n, g$3(A) ? A : [A], u, t, i, r, o, e, f, c, a), h.base = u.__e, u.__u &= -161, h.__h.length && e.push(h), _ && (h.__E = h.__ = null); } catch (n) { if (u.__v = null, c || null != o) if (n.then) { for (u.__u |= c ? 160 : 128; f && 8 == f.nodeType && f.nextSibling;) f = f.nextSibling; o[o.indexOf(f)] = null, u.__e = f; } else { for (H = o.length; H--;) b$3(o[H]); B$2(u); } else u.__e = t.__e, u.__k = t.__k, n.then || B$2(u); l$5.__e(n, u, t); } else null == o && u.__v == t.__v ? (u.__k = t.__k, u.__e = t.__e) : f = u.__e = G$2(t.__e, u, t, i, r, o, e, c, a); return (s = l$5.diffed) && s(u), 128 & u.__u ? void 0 : f; } function B$2(n) { n && (n.__c && (n.__c.__e = !0), n.__k && n.__k.some(B$2)); } function D$3(n, u, t) { for (var i = 0; i < t.length; i++) J$1(t[i], t[++i], t[++i]); l$5.__c && l$5.__c(u, n), n.some(function(u) { try { n = u.__h, u.__h = [], n.some(function(n) { n.call(u); }); } catch (n) { l$5.__e(n, u.__v); } }); } function E$5(n) { return "object" != typeof n || null == n || n.__b > 0 ? n : g$3(n) ? n.map(E$5) : void 0 !== n.constructor ? null : m$3({}, n); } function G$2(u, t, i, r, o, e, f, c, a) { var s, h, p, v, y, w, _, m = i.props || d$2, k = t.props, x = t.type; if ("svg" == x ? o = "http://www.w3.org/2000/svg" : "math" == x ? o = "http://www.w3.org/1998/Math/MathML" : o || (o = "http://www.w3.org/1999/xhtml"), null != e) { for (s = 0; s < e.length; s++) if ((y = e[s]) && "setAttribute" in y == !!x && (x ? y.localName == x : 3 == y.nodeType)) { u = y, e[s] = null; break; } } if (null == u) { if (null == x) return document.createTextNode(k); u = document.createElementNS(o, x, k.is && k), c && (l$5.__m && l$5.__m(t, e), c = !1), e = null; } if (null == x) m === k || c && u.data == k || (u.data = k); else { if (e = "textarea" == x && null != k.defaultValue ? null : e && n$3.call(u.childNodes), !c && null != e) for (m = {}, s = 0; s < u.attributes.length; s++) m[(y = u.attributes[s]).name] = y.value; for (s in m) y = m[s], "dangerouslySetInnerHTML" == s ? p = y : "children" == s || s in k || "value" == s && "defaultValue" in k || "checked" == s && "defaultChecked" in k || N$2(u, s, null, y, o); for (s in k) y = k[s], "children" == s ? v = y : "dangerouslySetInnerHTML" == s ? h = y : "value" == s ? w = y : "checked" == s ? _ = y : c && "function" != typeof y || m[s] === y || N$2(u, s, y, m[s], o); if (h) c || p && (h.__html == p.__html || h.__html == u.innerHTML) || (u.innerHTML = h.__html), t.__k = []; else if (p && (u.innerHTML = ""), L$4("template" == t.type ? u.content : u, g$3(v) ? v : [v], t, i, r, "foreignObject" == x ? "http://www.w3.org/1999/xhtml" : o, e, f, e ? e[0] : i.__k && $$1(i, 0), c, a), null != e) for (s = e.length; s--;) b$3(e[s]); c && "textarea" != x || (s = "value", "progress" == x && null == w ? u.removeAttribute("value") : null != w && (w !== u[s] || "progress" == x && !w || "option" == x && w != m[s]) && N$2(u, s, w, m[s], o), s = "checked", null != _ && _ != u[s] && N$2(u, s, _, m[s], o)); } return u; } function J$1(n, u, t) { try { if ("function" == typeof n) { var i = "function" == typeof n.__u; i && n.__u(), i && null == u || (n.__u = n(u)); } else n.current = u; } catch (n) { l$5.__e(n, t); } } function K$2(n, u, t) { var i, r; if (l$5.unmount && l$5.unmount(n), (i = n.ref) && (i.current && i.current != n.__e || J$1(i, null, u)), null != (i = n.__c)) { if (i.componentWillUnmount) try { i.componentWillUnmount(); } catch (n) { l$5.__e(n, u); } i.base = i.__P = null; } if (i = n.__k) for (r = 0; r < i.length; r++) i[r] && K$2(i[r], u, t || "function" != typeof n.type); t || b$3(n.__e), n.__c = n.__ = n.__e = void 0; } function Q$1(n, l, u) { return this.constructor(n, u); } function R$1(u, t, i) { var r, o, e, f; t == document && (t = document.documentElement), l$5.__ && l$5.__(u, t), o = (r = "function" == typeof i) ? null : i && i.__k || t.__k, e = [], f = [], q$2(t, u = (!r && i || t).__k = k$2(S, null, [u]), o || d$2, d$2, t.namespaceURI, !r && i ? [i] : o ? null : t.firstChild ? n$3.call(t.childNodes) : null, e, !r && i ? i : o ? o.__e : t.firstChild, r, f), D$3(e, u, f); } function U$3(n, l) { R$1(n, l, U$3); } function W$1(l, u, t) { var i, r, o, e, f = m$3({}, l.props); for (o in l.type && l.type.defaultProps && (e = l.type.defaultProps), u) "key" == o ? i = u[o] : "ref" == o ? r = u[o] : f[o] = void 0 === u[o] && null != e ? e[o] : u[o]; return arguments.length > 2 && (f.children = arguments.length > 3 ? n$3.call(arguments, 2) : t), x$2(l.type, f, i || l.key, r || l.ref, null); } function X$1(n) { function l(n) { var u, t; return this.getChildContext || (u = new Set(), (t = {})[l.__c] = this, this.getChildContext = function() { return t; }, this.componentWillUnmount = function() { u = null; }, this.shouldComponentUpdate = function(n) { this.props.value != n.value && u.forEach(function(n) { n.__e = !0, A$3(n); }); }, this.sub = function(n) { u.add(n); var l = n.componentWillUnmount; n.componentWillUnmount = function() { u && u.delete(n), l && l.call(n); }; }), n.children; } return l.__c = "__cC" + y$2++, l.__ = n, l.Provider = l.__l = (l.Consumer = function(n, l) { return n.children(l); }).contextType = l, l; } var n$3, l$5, u$5, i$3, r$4, o$7, e$4, f$5, c$3, a$5, s$6, h$2, p$4, v$1, y$2, d$2, w$4, _$2, g$3; var init_preact_module = __esmMin((() => { d$2 = {}, w$4 = [], _$2 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, g$3 = Array.isArray; n$3 = w$4.slice, l$5 = { __e: function(n, l, u, t) { for (var i, r, o; l = l.__;) if ((i = l.__c) && !i.__) try { if ((r = i.constructor) && null != r.getDerivedStateFromError && (i.setState(r.getDerivedStateFromError(n)), o = i.__d), null != i.componentDidCatch && (i.componentDidCatch(n, t || {}), o = i.__d), o) return i.__E = i; } catch (l) { n = l; } throw n; } }, u$5 = 0, C$6.prototype.setState = function(n, l) { var u = null != this.__s && this.__s != this.state ? this.__s : this.__s = m$3({}, this.state); "function" == typeof n && (n = n(m$3({}, u), this.props)), n && m$3(u, n), null != n && this.__v && (l && this._sb.push(l), A$3(this)); }, C$6.prototype.forceUpdate = function(n) { this.__v && (this.__e = !0, n && this.__h.push(n), A$3(this)); }, C$6.prototype.render = S, i$3 = [], o$7 = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, e$4 = function(n, l) { return n.__v.__b - l.__v.__b; }, H$3.__r = 0, f$5 = Math.random().toString(8), c$3 = "__d" + f$5, a$5 = "__a" + f$5, s$6 = /(PointerCapture)$|Capture$/i, h$2 = 0, p$4 = V$3(!1), v$1 = V$3(!0), y$2 = 0; })); var require_sentinel_umd = __commonJSMin(((exports, module) => { (function(root, factory) { if (typeof define === "function" && define.amd) define([], factory); else if (typeof exports === "object") module.exports = factory(); else root.sentinel = factory(); })(exports, function() { var isArray = Array.isArray, selectorToAnimationMap = {}, animationCallbacks = {}, styleEl, styleSheet, cssRules; return { on: function(cssSelectors, callback) { if (!callback) return; if (!styleEl) { var doc = document, head = doc.head; doc.addEventListener("animationstart", function(ev, callbacks, l, i) { callbacks = animationCallbacks[ev.animationName]; if (!callbacks) return; ev.stopImmediatePropagation(); l = callbacks.length; for (i = 0; i < l; i++) callbacks[i](ev.target); }, true); styleEl = doc.getElementById("sentinel-css"); if (!styleEl) { styleEl = doc.createElement("style"); head.insertBefore(styleEl, head.firstChild); } styleSheet = styleEl.sheet; cssRules = styleSheet.cssRules; } (isArray(cssSelectors) ? cssSelectors : [cssSelectors]).map(function(selector, animId, isCustomName) { animId = selectorToAnimationMap[selector]; if (!animId) { isCustomName = selector[0] == "!"; selectorToAnimationMap[selector] = animId = isCustomName ? selector.slice(1) : "sentinel-" + Math.random().toString(16).slice(2); cssRules[styleSheet.insertRule("@keyframes " + animId + "{from{transform:none;}to{transform:none;}}", cssRules.length)]._id = selector; if (!isCustomName) cssRules[styleSheet.insertRule(selector + "{animation-duration:0.0001s;animation-name:" + animId + ";}", cssRules.length)]._id = selector; selectorToAnimationMap[selector] = animId; } (animationCallbacks[animId] = animationCallbacks[animId] || []).push(callback); }); }, off: function(cssSelectors, callback) { (isArray(cssSelectors) ? cssSelectors : [cssSelectors]).map(function(selector, animId, callbackList, i) { if (!(animId = selectorToAnimationMap[selector])) return; callbackList = animationCallbacks[animId]; if (callback) { i = callbackList.length; while (i--) if (callbackList[i] === callback) callbackList.splice(i, 1); } else callbackList = []; if (callbackList.length) return; i = cssRules.length; while (i--) if (cssRules[i]._id == selector) styleSheet.deleteRule(i); delete selectorToAnimationMap[selector]; delete animationCallbacks[animId]; }); }, reset: function() { selectorToAnimationMap = {}; animationCallbacks = {}; if (styleEl) styleEl.parentNode.removeChild(styleEl); styleEl = 0; } }; }); })); init_preact_module(); var import_sentinel_umd = __toESM(require_sentinel_umd(), 1); var _GM_deleteValue = (() => typeof GM_deleteValue != "undefined" ? GM_deleteValue : void 0)(); var _GM_getValue = (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)(); var _GM_setValue = (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)(); var _unsafeWindow = (() => typeof unsafeWindow != "undefined" ? unsafeWindow : void 0)(); var GMStorage = class { static supported = typeof _GM_getValue === "function" && typeof _GM_setValue === "function" && typeof _GM_deleteValue === "function"; static get(key) { const item = _GM_getValue(key, ""); if (item) try { return JSON.parse(item); } catch { return null; } return null; } static set(key, value) { _GM_setValue(key, JSON.stringify(value)); } static delete(key) { _GM_deleteValue(key); } }; var LocalStorage = class { static supported = typeof localStorage === "object"; static get(key) { const item = localStorage.getItem(key); if (item) try { return JSON.parse(item); } catch { return null; } return null; } static set(key, value) { const item = JSON.stringify(value); localStorage.setItem(key, item); } static delete(key) { localStorage.removeItem(key); } }; var MemoryStorage = class { static map = new Map(); static supported = true; static get(key) { const item = this.map.get(key); if (!item) return null; return item; } static set(key, value) { this.map.set(key, value); } static delete(key) { this.map.delete(key); } }; var ScriptStorage = class { static get(key) { if (GMStorage.supported) try { return GMStorage.get(key); } catch {} if (LocalStorage.supported) try { return LocalStorage.get(key); } catch {} return MemoryStorage.get(key); } static set(key, value) { if (GMStorage.supported) try { return GMStorage.set(key, value); } catch {} if (LocalStorage.supported) try { return LocalStorage.set(key, value); } catch {} return MemoryStorage.set(key, value); } static delete(key) { if (GMStorage.supported) try { return GMStorage.delete(key); } catch {} if (LocalStorage.supported) try { return LocalStorage.delete(key); } catch {} return MemoryStorage.delete(key); } }; var EXPORTER_AUTH_API_KEY_DIGEST_STORAGE_KEY = "exporter:auth:api_key_digest"; var EXPORTER_AUTH_API_KEY_ISSUED_AT_STORAGE_KEY = "exporter:auth:api_key_issued_at"; var EXPORTER_AUTH_VERIFIED_DIGEST_SESSION_KEY = "exporter:auth:verified_digest"; var API_KEY_PREFIX = "aice_"; var API_KEY_BYTES = 32; var memoryVerifiedDigest = null; var ExporterAuthError = class extends Error { code; constructor(code, message) { super(message); this.name = "ExporterAuthError"; this.code = code; } }; function isExporterAuthError(error) { return error instanceof ExporterAuthError || typeof error === "object" && error !== null && "name" in error && error.name === "ExporterAuthError"; } async function issueApiKey() { const apiKey = generateApiKey(); const digest = await digestApiKey(apiKey); const issuedAt = new Date().toISOString(); ScriptStorage.set(EXPORTER_AUTH_API_KEY_DIGEST_STORAGE_KEY, digest); ScriptStorage.set(EXPORTER_AUTH_API_KEY_ISSUED_AT_STORAGE_KEY, issuedAt); setVerifiedSessionDigest(digest); return { apiKey, issuedAt }; } async function authorizeApiKey(apiKey) { const configuredDigest = getConfiguredDigest(); if (!configuredDigest) return false; const verified = await digestApiKey(apiKey) === configuredDigest; if (verified) setVerifiedSessionDigest(configuredDigest); return verified; } function revokeApiKey() { ScriptStorage.delete(EXPORTER_AUTH_API_KEY_DIGEST_STORAGE_KEY); ScriptStorage.delete(EXPORTER_AUTH_API_KEY_ISSUED_AT_STORAGE_KEY); clearVerifiedSessionDigest(); } async function getExporterAuthStatus() { const configuredDigest = getConfiguredDigest(); const verifiedDigest = getVerifiedSessionDigest(); return { configured: Boolean(configuredDigest), verified: Boolean(configuredDigest && verifiedDigest === configuredDigest), issuedAt: ScriptStorage.get(EXPORTER_AUTH_API_KEY_ISSUED_AT_STORAGE_KEY), digestStorageKey: EXPORTER_AUTH_API_KEY_DIGEST_STORAGE_KEY, issuedAtStorageKey: EXPORTER_AUTH_API_KEY_ISSUED_AT_STORAGE_KEY, verifiedSessionKey: EXPORTER_AUTH_VERIFIED_DIGEST_SESSION_KEY }; } async function requireExporterApiAuth() { const status = await getExporterAuthStatus(); if (!status.configured) throw new ExporterAuthError("api-key-not-configured", "Exporter API key is required. Open Exporter Settings > API Auth to issue and unlock a key."); if (!status.verified) throw new ExporterAuthError("api-key-not-verified", "Exporter API key is not verified. Open Exporter Settings > API Auth to unlock API access."); } function normalizeApiKey(apiKey) { return apiKey.trim(); } function getConfiguredDigest() { return ScriptStorage.get(EXPORTER_AUTH_API_KEY_DIGEST_STORAGE_KEY); } function generateApiKey() { if (!globalThis.crypto?.getRandomValues) throw new Error("Secure random API is unavailable."); const bytes = new Uint8Array(API_KEY_BYTES); globalThis.crypto.getRandomValues(bytes); return `${API_KEY_PREFIX}${base64UrlEncode(bytes)}`; } async function digestApiKey(apiKey) { if (!globalThis.crypto?.subtle) throw new Error("Web Crypto digest API is unavailable."); const encoded = new TextEncoder().encode(normalizeApiKey(apiKey)); const digest = await globalThis.crypto.subtle.digest("SHA-256", encoded); return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join(""); } function base64UrlEncode(bytes) { const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""); return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function getBrowserSessionStorage() { try { return typeof sessionStorage === "undefined" ? null : sessionStorage; } catch { return null; } } function getVerifiedSessionDigest() { return getBrowserSessionStorage()?.getItem("exporter:auth:verified_digest") ?? memoryVerifiedDigest; } function setVerifiedSessionDigest(digest) { memoryVerifiedDigest = digest; getBrowserSessionStorage()?.setItem(EXPORTER_AUTH_VERIFIED_DIGEST_SESSION_KEY, digest); } function clearVerifiedSessionDigest() { memoryVerifiedDigest = null; getBrowserSessionStorage()?.removeItem(EXPORTER_AUTH_VERIFIED_DIGEST_SESSION_KEY); } var API_MAPPING = { "https://chat.openai.com": "https://chat.openai.com/backend-api", "https://chatgpt.com": "https://chatgpt.com/backend-api", "https://new.oaifree.com": "https://new.oaifree.com/backend-api", "https://gemini.google.com": "https://gemini.google.com" }; var baseUrl = new URL(location.href).origin; var apiUrl = API_MAPPING[baseUrl] ?? baseUrl; var KEY_LANGUAGE = "exporter:language"; var KEY_FILENAME_FORMAT = "exporter:filename_format"; var KEY_TIMESTAMP_ENABLED = "exporter:enable_timestamp"; var KEY_TIMESTAMP_24H = "exporter:timestamp_24h"; var KEY_TIMESTAMP_MARKDOWN = "exporter:timestamp_markdown"; var KEY_TIMESTAMP_HTML = "exporter:timestamp_html"; var KEY_META_ENABLED = "exporter:enable_meta"; var KEY_META_LIST = "exporter:meta_list"; var KEY_EXPORT_ALL_LIMIT = "exporter:export_all_limit"; var KEY_PRO_LICENSE_KEY = "exporter:pro_license_key"; var KEY_OAI_HISTORY_DISABLED = "oai/apps/historyDisabled"; var require_type = __commonJSMin(((exports, module) => { module.exports = TypeError; })); var require___vite_browser_external = __commonJSMin(((exports, module) => { module.exports = {}; })); var require_object_inspect = __commonJSMin(((exports, module) => { var hasMap = typeof Map === "function" && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === "function" && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var weakMapHas = typeof WeakMap === "function" && WeakMap.prototype ? WeakMap.prototype.has : null; var weakSetHas = typeof WeakSet === "function" && WeakSet.prototype ? WeakSet.prototype.has : null; var weakRefDeref = typeof WeakRef === "function" && WeakRef.prototype ? WeakRef.prototype.deref : null; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var functionToString = Function.prototype.toString; var $match = String.prototype.match; var $slice = String.prototype.slice; var $replace = String.prototype.replace; var $toUpperCase = String.prototype.toUpperCase; var $toLowerCase = String.prototype.toLowerCase; var $test = RegExp.prototype.test; var $concat = Array.prototype.concat; var $join = Array.prototype.join; var $arrSlice = Array.prototype.slice; var $floor = Math.floor; var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; var gOPS = Object.getOwnPropertySymbols; var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; var isEnumerable = Object.prototype.propertyIsEnumerable; var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { return O.__proto__; } : null); function addNumericSeparator(num, str) { if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) return str; var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; if (typeof num === "number") { var int = num < 0 ? -$floor(-num) : $floor(num); if (int !== num) { var intStr = String(int); var dec = $slice.call(str, intStr.length + 1); return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); } } return $replace.call(str, sepRegex, "$&_"); } var utilInspect = require___vite_browser_external(); var inspectCustom = utilInspect.custom; var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; var quotes = { __proto__: null, "double": "\"", single: "'" }; var quoteREs = { __proto__: null, "double": /(["\\])/g, single: /(['\\])/g }; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) throw new TypeError("option \"quoteStyle\" must be \"single\" or \"double\""); if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) throw new TypeError("option \"maxStringLength\", if provided, must be a positive integer, Infinity, or `null`"); var customInspect = has(opts, "customInspect") ? opts.customInspect : true; if (typeof customInspect !== "boolean" && customInspect !== "symbol") throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) throw new TypeError("option \"indent\" must be \"\\t\", an integer > 0, or `null`"); if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") throw new TypeError("option \"numericSeparator\", if provided, must be `true` or `false`"); var numericSeparator = opts.numericSeparator; if (typeof obj === "undefined") return "undefined"; if (obj === null) return "null"; if (typeof obj === "boolean") return obj ? "true" : "false"; if (typeof obj === "string") return inspectString(obj, opts); if (typeof obj === "number") { if (obj === 0) return Infinity / obj > 0 ? "0" : "-0"; var str = String(obj); return numericSeparator ? addNumericSeparator(obj, str) : str; } if (typeof obj === "bigint") { var bigIntStr = String(obj) + "n"; return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; } var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; if (typeof depth === "undefined") depth = 0; if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") return isArray(obj) ? "[Array]" : "[Object]"; var indent = getIndent(opts, depth); if (typeof seen === "undefined") seen = []; else if (indexOf(seen, obj) >= 0) return "[Circular]"; function inspect(value, from, noIndent) { if (from) { seen = $arrSlice.call(seen); seen.push(from); } if (noIndent) { var newOpts = { depth: opts.depth }; if (has(opts, "quoteStyle")) newOpts.quoteStyle = opts.quoteStyle; return inspect_(value, newOpts, depth + 1, seen); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === "function" && !isRegExp(obj)) { var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : ""); } if (isSymbol(obj)) { var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = "<" + $toLowerCase.call(String(obj.nodeName)); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) s += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts); s += ">"; if (obj.childNodes && obj.childNodes.length) s += "..."; s += ""; return s; } if (isArray(obj)) { if (obj.length === 0) return "[]"; var xs = arrObjKeys(obj, inspect); if (indent && !singleLineValues(xs)) return "[" + indentedJoin(xs, indent) + "]"; return "[ " + $join.call(xs, ", ") + " ]"; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; if (parts.length === 0) return "[" + String(obj) + "]"; return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; } if (typeof obj === "object" && customInspect) { if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) return utilInspect(obj, { depth: maxDepth - depth }); else if (customInspect !== "symbol" && typeof obj.inspect === "function") return obj.inspect(); } if (isMap(obj)) { var mapParts = []; if (mapForEach) mapForEach.call(obj, function(value, key) { mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); }); return collectionOf("Map", mapSize.call(obj), mapParts, indent); } if (isSet(obj)) { var setParts = []; if (setForEach) setForEach.call(obj, function(value) { setParts.push(inspect(value, obj)); }); return collectionOf("Set", setSize.call(obj), setParts, indent); } if (isWeakMap(obj)) return weakCollectionOf("WeakMap"); if (isWeakSet(obj)) return weakCollectionOf("WeakSet"); if (isWeakRef(obj)) return weakCollectionOf("WeakRef"); if (isNumber(obj)) return markBoxed(inspect(Number(obj))); if (isBigInt(obj)) return markBoxed(inspect(bigIntValueOf.call(obj))); if (isBoolean(obj)) return markBoxed(booleanValueOf.call(obj)); if (isString(obj)) return markBoxed(inspect(String(obj))); if (typeof window !== "undefined" && obj === window) return "{ [object Window] }"; if (typeof globalThis !== "undefined" && obj === globalThis || typeof global !== "undefined" && obj === global) return "{ [object globalThis] }"; if (!isDate(obj) && !isRegExp(obj)) { var ys = arrObjKeys(obj, inspect); var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; var protoTag = obj instanceof Object ? "" : "null prototype"; var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; var tag = (isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "") + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); if (ys.length === 0) return tag + "{}"; if (indent) return tag + "{" + indentedJoin(ys, indent) + "}"; return tag + "{ " + $join.call(ys, ", ") + " }"; } return String(obj); }; function wrapQuotes(s, defaultStyle, opts) { var quoteChar = quotes[opts.quoteStyle || defaultStyle]; return quoteChar + s + quoteChar; } function quote(s) { return $replace.call(String(s), /"/g, """); } function canTrustToString(obj) { return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined")); } function isArray(obj) { return toStr(obj) === "[object Array]" && canTrustToString(obj); } function isDate(obj) { return toStr(obj) === "[object Date]" && canTrustToString(obj); } function isRegExp(obj) { return toStr(obj) === "[object RegExp]" && canTrustToString(obj); } function isError(obj) { return toStr(obj) === "[object Error]" && canTrustToString(obj); } function isString(obj) { return toStr(obj) === "[object String]" && canTrustToString(obj); } function isNumber(obj) { return toStr(obj) === "[object Number]" && canTrustToString(obj); } function isBoolean(obj) { return toStr(obj) === "[object Boolean]" && canTrustToString(obj); } function isSymbol(obj) { if (hasShammedSymbols) return obj && typeof obj === "object" && obj instanceof Symbol; if (typeof obj === "symbol") return true; if (!obj || typeof obj !== "object" || !symToString) return false; try { symToString.call(obj); return true; } catch (e) {} return false; } function isBigInt(obj) { if (!obj || typeof obj !== "object" || !bigIntValueOf) return false; try { bigIntValueOf.call(obj); return true; } catch (e) {} return false; } var hasOwn = Object.prototype.hasOwnProperty || function(key) { return key in this; }; function has(obj, key) { return hasOwn.call(obj, key); } function toStr(obj) { return objectToString.call(obj); } function nameOf(f) { if (f.name) return f.name; var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); if (m) return m[1]; return null; } function indexOf(xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0, l = xs.length; i < l; i++) if (xs[i] === x) return i; return -1; } function isMap(x) { if (!mapSize || !x || typeof x !== "object") return false; try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; } catch (e) {} return false; } function isWeakMap(x) { if (!weakMapHas || !x || typeof x !== "object") return false; try { weakMapHas.call(x, weakMapHas); try { weakSetHas.call(x, weakSetHas); } catch (s) { return true; } return x instanceof WeakMap; } catch (e) {} return false; } function isWeakRef(x) { if (!weakRefDeref || !x || typeof x !== "object") return false; try { weakRefDeref.call(x); return true; } catch (e) {} return false; } function isSet(x) { if (!setSize || !x || typeof x !== "object") return false; try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; } catch (e) {} return false; } function isWeakSet(x) { if (!weakSetHas || !x || typeof x !== "object") return false; try { weakSetHas.call(x, weakSetHas); try { weakMapHas.call(x, weakMapHas); } catch (s) { return true; } return x instanceof WeakSet; } catch (e) {} return false; } function isElement(x) { if (!x || typeof x !== "object") return false; if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) return true; return typeof x.nodeName === "string" && typeof x.getAttribute === "function"; } function inspectString(str, opts) { if (str.length > opts.maxStringLength) { var remaining = str.length - opts.maxStringLength; var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; } var quoteRE = quoteREs[opts.quoteStyle || "single"]; quoteRE.lastIndex = 0; return wrapQuotes($replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte), "single", opts); } function lowbyte(c) { var n = c.charCodeAt(0); var x = { 8: "b", 9: "t", 10: "n", 12: "f", 13: "r" }[n]; if (x) return "\\" + x; return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16)); } function markBoxed(str) { return "Object(" + str + ")"; } function weakCollectionOf(type) { return type + " { ? }"; } function collectionOf(type, size, entries, indent) { var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); return type + " (" + size + ") {" + joinedEntries + "}"; } function singleLineValues(xs) { for (var i = 0; i < xs.length; i++) if (indexOf(xs[i], "\n") >= 0) return false; return true; } function getIndent(opts, depth) { var baseIndent; if (opts.indent === " ") baseIndent = " "; else if (typeof opts.indent === "number" && opts.indent > 0) baseIndent = $join.call(Array(opts.indent + 1), " "); else return null; return { base: baseIndent, prev: $join.call(Array(depth + 1), baseIndent) }; } function indentedJoin(xs, indent) { if (xs.length === 0) return ""; var lineJoiner = "\n" + indent.prev + indent.base; return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; } function arrObjKeys(obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) xs[i] = has(obj, i) ? inspect(obj[i], obj) : ""; } var syms = typeof gOPS === "function" ? gOPS(obj) : []; var symMap; if (hasShammedSymbols) { symMap = {}; for (var k = 0; k < syms.length; k++) symMap["$" + syms[k]] = syms[k]; } for (var key in obj) { if (!has(obj, key)) continue; if (isArr && String(Number(key)) === key && key < obj.length) continue; if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) continue; else if ($test.call(/[^\w$]/, key)) xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); else xs.push(key + ": " + inspect(obj[key], obj)); } if (typeof gOPS === "function") { for (var j = 0; j < syms.length; j++) if (isEnumerable.call(obj, syms[j])) xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj)); } return xs; } })); var require_side_channel_list = __commonJSMin(((exports, module) => { var inspect = require_object_inspect(); var $TypeError = require_type(); var listGetNode = function(list, key, isDelete) { var prev = list; var curr; for (; (curr = prev.next) != null; prev = curr) if (curr.key === key) { prev.next = curr.next; if (!isDelete) { curr.next = list.next; list.next = curr; } return curr; } }; var listGet = function(objects, key) { if (!objects) return; var node = listGetNode(objects, key); return node && node.value; }; var listSet = function(objects, key, value) { var node = listGetNode(objects, key); if (node) node.value = value; else objects.next = { key, next: objects.next, value }; }; var listHas = function(objects, key) { if (!objects) return false; return !!listGetNode(objects, key); }; var listDelete = function(objects, key) { if (objects) return listGetNode(objects, key, true); }; module.exports = function getSideChannelList() { var $o; var channel = { assert: function(key) { if (!channel.has(key)) throw new $TypeError("Side channel does not contain " + inspect(key)); }, "delete": function(key) { var deletedNode = listDelete($o, key); if (deletedNode && $o && !$o.next) $o = void 0; return !!deletedNode; }, get: function(key) { return listGet($o, key); }, has: function(key) { return listHas($o, key); }, set: function(key, value) { if (!$o) $o = { next: void 0 }; listSet($o, key, value); } }; return channel; }; })); var require_es_object_atoms = __commonJSMin(((exports, module) => { module.exports = Object; })); var require_es_errors = __commonJSMin(((exports, module) => { module.exports = Error; })); var require_eval = __commonJSMin(((exports, module) => { module.exports = EvalError; })); var require_range = __commonJSMin(((exports, module) => { module.exports = RangeError; })); var require_ref = __commonJSMin(((exports, module) => { module.exports = ReferenceError; })); var require_syntax = __commonJSMin(((exports, module) => { module.exports = SyntaxError; })); var require_uri = __commonJSMin(((exports, module) => { module.exports = URIError; })); var require_abs = __commonJSMin(((exports, module) => { module.exports = Math.abs; })); var require_floor = __commonJSMin(((exports, module) => { module.exports = Math.floor; })); var require_max = __commonJSMin(((exports, module) => { module.exports = Math.max; })); var require_min = __commonJSMin(((exports, module) => { module.exports = Math.min; })); var require_pow = __commonJSMin(((exports, module) => { module.exports = Math.pow; })); var require_round = __commonJSMin(((exports, module) => { module.exports = Math.round; })); var require_isNaN = __commonJSMin(((exports, module) => { module.exports = Number.isNaN || function isNaN(a) { return a !== a; }; })); var require_sign = __commonJSMin(((exports, module) => { var $isNaN = require_isNaN(); module.exports = function sign(number) { if ($isNaN(number) || number === 0) return number; return number < 0 ? -1 : 1; }; })); var require_gOPD = __commonJSMin(((exports, module) => { module.exports = Object.getOwnPropertyDescriptor; })); var require_gopd = __commonJSMin(((exports, module) => { var $gOPD = require_gOPD(); if ($gOPD) try { $gOPD([], "length"); } catch (e) { $gOPD = null; } module.exports = $gOPD; })); var require_es_define_property = __commonJSMin(((exports, module) => { var $defineProperty = Object.defineProperty || false; if ($defineProperty) try { $defineProperty({}, "a", { value: 1 }); } catch (e) { $defineProperty = false; } module.exports = $defineProperty; })); var require_shams = __commonJSMin(((exports, module) => { module.exports = function hasSymbols() { if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") return false; if (typeof Symbol.iterator === "symbol") return true; var obj = {}; var sym = Symbol("test"); var symObj = Object(sym); if (typeof sym === "string") return false; if (Object.prototype.toString.call(sym) !== "[object Symbol]") return false; if (Object.prototype.toString.call(symObj) !== "[object Symbol]") return false; var symVal = 42; obj[sym] = symVal; for (var _ in obj) return false; if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) return false; if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) return false; var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) return false; if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) return false; if (typeof Object.getOwnPropertyDescriptor === "function") { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) return false; } return true; }; })); var require_has_symbols = __commonJSMin(((exports, module) => { var origSymbol = typeof Symbol !== "undefined" && Symbol; var hasSymbolSham = require_shams(); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== "function") return false; if (typeof Symbol !== "function") return false; if (typeof origSymbol("foo") !== "symbol") return false; if (typeof Symbol("bar") !== "symbol") return false; return hasSymbolSham(); }; })); var require_Reflect_getPrototypeOf = __commonJSMin(((exports, module) => { module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; })); var require_Object_getPrototypeOf = __commonJSMin(((exports, module) => { module.exports = require_es_object_atoms().getPrototypeOf || null; })); var require_implementation = __commonJSMin(((exports, module) => { var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; var toStr = Object.prototype.toString; var max = Math.max; var funcType = "[object Function]"; var concatty = function concatty(a, b) { var arr = []; for (var i = 0; i < a.length; i += 1) arr[i] = a[i]; for (var j = 0; j < b.length; j += 1) arr[j + a.length] = b[j]; return arr; }; var slicy = function slicy(arrLike, offset) { var arr = []; for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) arr[j] = arrLike[i]; return arr; }; var joiny = function(arr, joiner) { var str = ""; for (var i = 0; i < arr.length; i += 1) { str += arr[i]; if (i + 1 < arr.length) str += joiner; } return str; }; module.exports = function bind(that) { var target = this; if (typeof target !== "function" || toStr.apply(target) !== funcType) throw new TypeError(ERROR_MESSAGE + target); var args = slicy(arguments, 1); var bound; var binder = function() { if (this instanceof bound) { var result = target.apply(this, concatty(args, arguments)); if (Object(result) === result) return result; return this; } return target.apply(that, concatty(args, arguments)); }; var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) boundArgs[i] = "$" + i; bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; })); var require_function_bind = __commonJSMin(((exports, module) => { var implementation = require_implementation(); module.exports = Function.prototype.bind || implementation; })); var require_functionCall = __commonJSMin(((exports, module) => { module.exports = Function.prototype.call; })); var require_functionApply = __commonJSMin(((exports, module) => { module.exports = Function.prototype.apply; })); var require_reflectApply = __commonJSMin(((exports, module) => { module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; })); var require_actualApply = __commonJSMin(((exports, module) => { var bind = require_function_bind(); var $apply = require_functionApply(); var $call = require_functionCall(); module.exports = require_reflectApply() || bind.call($call, $apply); })); var require_call_bind_apply_helpers = __commonJSMin(((exports, module) => { var bind = require_function_bind(); var $TypeError = require_type(); var $call = require_functionCall(); var $actualApply = require_actualApply(); module.exports = function callBindBasic(args) { if (args.length < 1 || typeof args[0] !== "function") throw new $TypeError("a function is required"); return $actualApply(bind, $call, args); }; })); var require_get = __commonJSMin(((exports, module) => { var callBind = require_call_bind_apply_helpers(); var gOPD = require_gopd(); var hasProtoAccessor; try { hasProtoAccessor = [].__proto__ === Array.prototype; } catch (e) { if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") throw e; } var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__"); var $Object = Object; var $getPrototypeOf = $Object.getPrototypeOf; module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value) { return $getPrototypeOf(value == null ? value : $Object(value)); } : false; })); var require_get_proto = __commonJSMin(((exports, module) => { var reflectGetProto = require_Reflect_getPrototypeOf(); var originalGetProto = require_Object_getPrototypeOf(); var getDunderProto = require_get(); module.exports = reflectGetProto ? function getProto(O) { return reflectGetProto(O); } : originalGetProto ? function getProto(O) { if (!O || typeof O !== "object" && typeof O !== "function") throw new TypeError("getProto: not an object"); return originalGetProto(O); } : getDunderProto ? function getProto(O) { return getDunderProto(O); } : null; })); var require_hasown = __commonJSMin(((exports, module) => { var call = Function.prototype.call; var $hasOwn = Object.prototype.hasOwnProperty; module.exports = require_function_bind().call(call, $hasOwn); })); var require_get_intrinsic = __commonJSMin(((exports, module) => { var undefined; var $Object = require_es_object_atoms(); var $Error = require_es_errors(); var $EvalError = require_eval(); var $RangeError = require_range(); var $ReferenceError = require_ref(); var $SyntaxError = require_syntax(); var $TypeError = require_type(); var $URIError = require_uri(); var abs = require_abs(); var floor = require_floor(); var max = require_max(); var min = require_min(); var pow = require_pow(); var round = require_round(); var sign = require_sign(); var $Function = Function; var getEvalledConstructor = function(expressionSyntax) { try { return $Function("\"use strict\"; return (" + expressionSyntax + ").constructor;")(); } catch (e) {} }; var $gOPD = require_gopd(); var $defineProperty = require_es_define_property(); var throwTypeError = function() { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? function() { try { arguments.callee; return throwTypeError; } catch (calleeThrows) { try { return $gOPD(arguments, "callee").get; } catch (gOPDthrows) { return throwTypeError; } } }() : throwTypeError; var hasSymbols = require_has_symbols()(); var getProto = require_get_proto(); var $ObjectGPO = require_Object_getPrototypeOf(); var $ReflectGPO = require_Reflect_getPrototypeOf(); var $apply = require_functionApply(); var $call = require_functionCall(); var needsEval = {}; var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined : getProto(Uint8Array); var INTRINSICS = { __proto__: null, "%AggregateError%": typeof AggregateError === "undefined" ? undefined : AggregateError, "%Array%": Array, "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined : ArrayBuffer, "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, "%AsyncFromSyncIteratorPrototype%": undefined, "%AsyncFunction%": needsEval, "%AsyncGenerator%": needsEval, "%AsyncGeneratorFunction%": needsEval, "%AsyncIteratorPrototype%": needsEval, "%Atomics%": typeof Atomics === "undefined" ? undefined : Atomics, "%BigInt%": typeof BigInt === "undefined" ? undefined : BigInt, "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined : BigInt64Array, "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined : BigUint64Array, "%Boolean%": Boolean, "%DataView%": typeof DataView === "undefined" ? undefined : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": $Error, "%eval%": eval, "%EvalError%": $EvalError, "%Float16Array%": typeof Float16Array === "undefined" ? undefined : Float16Array, "%Float32Array%": typeof Float32Array === "undefined" ? undefined : Float32Array, "%Float64Array%": typeof Float64Array === "undefined" ? undefined : Float64Array, "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined : FinalizationRegistry, "%Function%": $Function, "%GeneratorFunction%": needsEval, "%Int8Array%": typeof Int8Array === "undefined" ? undefined : Int8Array, "%Int16Array%": typeof Int16Array === "undefined" ? undefined : Int16Array, "%Int32Array%": typeof Int32Array === "undefined" ? undefined : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, "%JSON%": typeof JSON === "object" ? JSON : undefined, "%Map%": typeof Map === "undefined" ? undefined : Map, "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), "%Math%": Math, "%Number%": Number, "%Object%": $Object, "%Object.getOwnPropertyDescriptor%": $gOPD, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": typeof Promise === "undefined" ? undefined : Promise, "%Proxy%": typeof Proxy === "undefined" ? undefined : Proxy, "%RangeError%": $RangeError, "%ReferenceError%": $ReferenceError, "%Reflect%": typeof Reflect === "undefined" ? undefined : Reflect, "%RegExp%": RegExp, "%Set%": typeof Set === "undefined" ? undefined : Set, "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined, "%Symbol%": hasSymbols ? Symbol : undefined, "%SyntaxError%": $SyntaxError, "%ThrowTypeError%": ThrowTypeError, "%TypedArray%": TypedArray, "%TypeError%": $TypeError, "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined : Uint8Array, "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined : Uint8ClampedArray, "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined : Uint16Array, "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined : Uint32Array, "%URIError%": $URIError, "%WeakMap%": typeof WeakMap === "undefined" ? undefined : WeakMap, "%WeakRef%": typeof WeakRef === "undefined" ? undefined : WeakRef, "%WeakSet%": typeof WeakSet === "undefined" ? undefined : WeakSet, "%Function.prototype.call%": $call, "%Function.prototype.apply%": $apply, "%Object.defineProperty%": $defineProperty, "%Object.getPrototypeOf%": $ObjectGPO, "%Math.abs%": abs, "%Math.floor%": floor, "%Math.max%": max, "%Math.min%": min, "%Math.pow%": pow, "%Math.round%": round, "%Math.sign%": sign, "%Reflect.getPrototypeOf%": $ReflectGPO }; if (getProto) try { null.error; } catch (e) { INTRINSICS["%Error.prototype%"] = getProto(getProto(e)); } var doEval = function doEval(name) { var value; if (name === "%AsyncFunction%") value = getEvalledConstructor("async function () {}"); else if (name === "%GeneratorFunction%") value = getEvalledConstructor("function* () {}"); else if (name === "%AsyncGeneratorFunction%") value = getEvalledConstructor("async function* () {}"); else if (name === "%AsyncGenerator%") { var fn = doEval("%AsyncGeneratorFunction%"); if (fn) value = fn.prototype; } else if (name === "%AsyncIteratorPrototype%") { var gen = doEval("%AsyncGenerator%"); if (gen && getProto) value = getProto(gen.prototype); } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { __proto__: null, "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": [ "Array", "prototype", "entries" ], "%ArrayProto_forEach%": [ "Array", "prototype", "forEach" ], "%ArrayProto_keys%": [ "Array", "prototype", "keys" ], "%ArrayProto_values%": [ "Array", "prototype", "values" ], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": [ "AsyncGeneratorFunction", "prototype", "prototype" ], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": [ "GeneratorFunction", "prototype", "prototype" ], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": [ "Object", "prototype", "toString" ], "%ObjProto_valueOf%": [ "Object", "prototype", "valueOf" ], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": [ "Promise", "prototype", "then" ], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }; var bind = require_function_bind(); var hasOwn = require_hasown(); var $concat = bind.call($call, Array.prototype.concat); var $spliceApply = bind.call($apply, Array.prototype.splice); var $replace = bind.call($call, String.prototype.replace); var $strSlice = bind.call($call, String.prototype.slice); var $exec = bind.call($call, RegExp.prototype.exec); var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === "%" && last !== "%") throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); else if (last === "%" && first !== "%") throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); var result = []; $replace(string, rePropName, function(match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; }); return result; }; var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = "%" + alias[0] + "%"; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) value = doEval(intrinsicName); if (typeof value === "undefined" && !allowMissing) throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); return { alias, name: intrinsicName, value }; } throw new $SyntaxError("intrinsic " + name + " does not exist!"); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== "string" || name.length === 0) throw new $TypeError("intrinsic name must be a non-empty string"); if (arguments.length > 1 && typeof allowMissing !== "boolean") throw new $TypeError("\"allowMissing\" argument must be a boolean"); if ($exec(/^%?[^%]*%?$/, name) === null) throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ((first === "\"" || first === "'" || first === "`" || last === "\"" || last === "'" || last === "`") && first !== last) throw new $SyntaxError("property names with quotes must have matching quotes"); if (part === "constructor" || !isOwn) skipFurtherCaching = true; intrinsicBaseName += "." + part; intrinsicRealName = "%" + intrinsicBaseName + "%"; if (hasOwn(INTRINSICS, intrinsicRealName)) value = INTRINSICS[intrinsicRealName]; else if (value != null) { if (!(part in value)) { if (!allowMissing) throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); return; } if ($gOPD && i + 1 >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; if (isOwn && "get" in desc && !("originalValue" in desc.get)) value = desc.get; else value = value[part]; } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) INTRINSICS[intrinsicRealName] = value; } } return value; }; })); var require_call_bound = __commonJSMin(((exports, module) => { var GetIntrinsic = require_get_intrinsic(); var callBindBasic = require_call_bind_apply_helpers(); var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) return callBindBasic([intrinsic]); return intrinsic; }; })); var require_side_channel_map = __commonJSMin(((exports, module) => { var GetIntrinsic = require_get_intrinsic(); var callBound = require_call_bound(); var inspect = require_object_inspect(); var $TypeError = require_type(); var $Map = GetIntrinsic("%Map%", true); var $mapGet = callBound("Map.prototype.get", true); var $mapSet = callBound("Map.prototype.set", true); var $mapHas = callBound("Map.prototype.has", true); var $mapDelete = callBound("Map.prototype.delete", true); var $mapSize = callBound("Map.prototype.size", true); module.exports = !!$Map && function getSideChannelMap() { var $m; var channel = { assert: function(key) { if (!channel.has(key)) throw new $TypeError("Side channel does not contain " + inspect(key)); }, "delete": function(key) { if ($m) { var result = $mapDelete($m, key); if ($mapSize($m) === 0) $m = void 0; return result; } return false; }, get: function(key) { if ($m) return $mapGet($m, key); }, has: function(key) { if ($m) return $mapHas($m, key); return false; }, set: function(key, value) { if (!$m) $m = new $Map(); $mapSet($m, key, value); } }; return channel; }; })); var require_side_channel_weakmap = __commonJSMin(((exports, module) => { var GetIntrinsic = require_get_intrinsic(); var callBound = require_call_bound(); var inspect = require_object_inspect(); var getSideChannelMap = require_side_channel_map(); var $TypeError = require_type(); var $WeakMap = GetIntrinsic("%WeakMap%", true); var $weakMapGet = callBound("WeakMap.prototype.get", true); var $weakMapSet = callBound("WeakMap.prototype.set", true); var $weakMapHas = callBound("WeakMap.prototype.has", true); var $weakMapDelete = callBound("WeakMap.prototype.delete", true); module.exports = $WeakMap ? function getSideChannelWeakMap() { var $wm; var $m; var channel = { assert: function(key) { if (!channel.has(key)) throw new $TypeError("Side channel does not contain " + inspect(key)); }, "delete": function(key) { if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { if ($wm) return $weakMapDelete($wm, key); } else if (getSideChannelMap) { if ($m) return $m["delete"](key); } return false; }, get: function(key) { if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { if ($wm) return $weakMapGet($wm, key); } return $m && $m.get(key); }, has: function(key) { if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { if ($wm) return $weakMapHas($wm, key); } return !!$m && $m.has(key); }, set: function(key, value) { if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { if (!$wm) $wm = new $WeakMap(); $weakMapSet($wm, key, value); } else if (getSideChannelMap) { if (!$m) $m = getSideChannelMap(); $m.set(key, value); } } }; return channel; } : getSideChannelMap; })); var require_side_channel = __commonJSMin(((exports, module) => { var $TypeError = require_type(); var inspect = require_object_inspect(); var getSideChannelList = require_side_channel_list(); var getSideChannelMap = require_side_channel_map(); var makeChannel = require_side_channel_weakmap() || getSideChannelMap || getSideChannelList; module.exports = function getSideChannel() { var $channelData; var channel = { assert: function(key) { if (!channel.has(key)) throw new $TypeError("Side channel does not contain " + (key && Object(key) === key ? "the given object key" : inspect(key))); }, "delete": function(key) { return !!$channelData && $channelData["delete"](key); }, get: function(key) { return $channelData && $channelData.get(key); }, has: function(key) { return !!$channelData && $channelData.has(key); }, set: function(key, value) { if (!$channelData) $channelData = makeChannel(); $channelData.set(key, value); } }; return channel; }; })); var require_formats = __commonJSMin(((exports, module) => { var replace = String.prototype.replace; var percentTwenties = /%20/g; var Format = { RFC1738: "RFC1738", RFC3986: "RFC3986" }; module.exports = { "default": Format.RFC3986, formatters: { RFC1738: function(value) { return replace.call(value, percentTwenties, "+"); }, RFC3986: function(value) { return String(value); } }, RFC1738: Format.RFC1738, RFC3986: Format.RFC3986 }; })); var require_utils = __commonJSMin(((exports, module) => { var formats = require_formats(); var getSideChannel = require_side_channel(); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var overflowChannel = getSideChannel(); var markOverflow = function markOverflow(obj, maxIndex) { overflowChannel.set(obj, maxIndex); return obj; }; var isOverflow = function isOverflow(obj) { return overflowChannel.has(obj); }; var getMaxIndex = function getMaxIndex(obj) { return overflowChannel.get(obj); }; var setMaxIndex = function setMaxIndex(obj, maxIndex) { overflowChannel.set(obj, maxIndex); }; var hexTable = function() { var array = []; for (var i = 0; i < 256; ++i) array[array.length] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); return array; }(); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) if (typeof obj[j] !== "undefined") compacted[compacted.length] = obj[j]; item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? { __proto__: null } : {}; for (var i = 0; i < source.length; ++i) if (typeof source[i] !== "undefined") obj[i] = source[i]; return obj; }; var merge = function merge(target, source, options) { if (!source) return target; if (typeof source !== "object" && typeof source !== "function") { if (isArray(target)) { var nextIndex = target.length; if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) return markOverflow(arrayToObject(target.concat(source), options), nextIndex); target[nextIndex] = source; } else if (target && typeof target === "object") { if (isOverflow(target)) { var newIndex = getMaxIndex(target) + 1; target[newIndex] = source; setMaxIndex(target, newIndex); } else if (options && options.strictMerge) return [target, source]; else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) target[source] = true; } else return [target, source]; return target; } if (!target || typeof target !== "object") { if (isOverflow(source)) { var sourceKeys = Object.keys(source); var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target }; for (var m = 0; m < sourceKeys.length; m++) { var oldKey = parseInt(sourceKeys[m], 10); result[oldKey + 1] = source[sourceKeys[m]]; } return markOverflow(result, getMaxIndex(source) + 1); } var combined = [target].concat(source); if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) return markOverflow(arrayToObject(combined, options), combined.length - 1); return combined; } var mergeTarget = target; if (isArray(target) && !isArray(source)) mergeTarget = arrayToObject(target, options); if (isArray(target) && isArray(source)) { source.forEach(function(item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === "object" && item && typeof item === "object") target[i] = merge(targetItem, item, options); else target[target.length] = item; } else target[i] = item; }); return target; } return Object.keys(source).reduce(function(acc, key) { var value = source[key]; if (has.call(acc, key)) acc[key] = merge(acc[key], value, options); else acc[key] = value; if (isOverflow(source) && !isOverflow(acc)) markOverflow(acc, getMaxIndex(source)); if (isOverflow(acc)) { var keyNum = parseInt(key, 10); if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) setMaxIndex(acc, keyNum); } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function(acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function(str, defaultDecoder, charset) { var strWithoutPlus = str.replace(/\+/g, " "); if (charset === "iso-8859-1") return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var limit = 1024; module.exports = { arrayToObject, assign, combine: function combine(a, b, arrayLimit, plainObjects) { if (isOverflow(a)) { var newIndex = getMaxIndex(a) + 1; a[newIndex] = b; setMaxIndex(a, newIndex); return a; } var result = [].concat(a, b); if (result.length > arrayLimit) return markOverflow(arrayToObject(result, { plainObjects }), result.length - 1); return result; }, compact: function compact(value) { var queue = [{ obj: { o: value }, prop: "o" }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { queue[queue.length] = { obj, prop: key }; refs[refs.length] = val; } } } compactQueue(queue); return value; }, decode, encode: function encode(str, defaultEncoder, charset, kind, format) { if (str.length === 0) return str; var string = str; if (typeof str === "symbol") string = Symbol.prototype.toString.call(str); else if (typeof str !== "string") string = String(str); if (charset === "iso-8859-1") return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; }); var out = ""; for (var j = 0; j < string.length; j += limit) { var segment = string.length >= limit ? string.slice(j, j + limit) : string; var arr = []; for (var i = 0; i < segment.length; ++i) { var c = segment.charCodeAt(i); if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats.RFC1738 && (c === 40 || c === 41)) { arr[arr.length] = segment.charAt(i); continue; } if (c < 128) { arr[arr.length] = hexTable[c]; continue; } if (c < 2048) { arr[arr.length] = hexTable[192 | c >> 6] + hexTable[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { arr[arr.length] = hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; continue; } i += 1; c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); arr[arr.length] = hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; } out += arr.join(""); } return out; }, isBuffer: function isBuffer(obj) { if (!obj || typeof obj !== "object") return false; return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }, isOverflow, isRegExp: function isRegExp(obj) { return Object.prototype.toString.call(obj) === "[object RegExp]"; }, markOverflow, maybeMap: function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) mapped[mapped.length] = fn(val[i]); return mapped; } return fn(val); }, merge }; })); var require_stringify = __commonJSMin(((exports, module) => { var getSideChannel = require_side_channel(); var utils = require_utils(); var formats = require_formats(); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + "[]"; }, comma: "comma", indices: function indices(prefix, key) { return prefix + "[" + key + "]"; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function(arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats["default"]; var defaults = { addQueryPrefix: false, allowDots: false, allowEmptyArrays: false, arrayFormat: "indices", charset: "utf-8", charsetSentinel: false, commaRoundTrip: false, delimiter: "&", encode: true, encodeDotInKeys: false, encoder: utils.encode, encodeValuesOnly: false, filter: void 0, format: defaultFormat, formatter: formats.formatters[defaultFormat], indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; }; var sentinel = {}; var stringify = function stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { var obj = object; var tmpSc = sideChannel; var step = 0; var findFlag = false; while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { var pos = tmpSc.get(object); step += 1; if (typeof pos !== "undefined") if (pos === step) throw new RangeError("Cyclic object value"); else findFlag = true; if (typeof tmpSc.get(sentinel) === "undefined") step = 0; } if (typeof filter === "function") obj = filter(prefix, obj); else if (obj instanceof Date) obj = serializeDate(obj); else if (generateArrayPrefix === "comma" && isArray(obj)) obj = utils.maybeMap(obj, function(value) { if (value instanceof Date) return serializeDate(value); return value; }); if (obj === null) { if (strictNullHandling) return formatter(encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix); obj = ""; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) return [formatter(encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format)) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))]; return [formatter(prefix) + "=" + formatter(String(obj))]; } var values = []; if (typeof obj === "undefined") return values; var objKeys; if (generateArrayPrefix === "comma" && isArray(obj)) { if (encodeValuesOnly && encoder) obj = utils.maybeMap(obj, function(v) { return v == null ? v : encoder(v); }); objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; } else if (isArray(filter)) objKeys = filter; else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix; if (allowEmptyArrays && isArray(obj) && obj.length === 0) return adjustedPrefix + "[]"; for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key]; if (skipNulls && value === null) continue; var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key); var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]"); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); valueSideChannel.set(sentinel, sideChannel); pushToArray(values, stringify(value, keyPrefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) return defaults; if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function."); var charset = opts.charset || defaults.charset; if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); var format = formats["default"]; if (typeof opts.format !== "undefined") { if (!has.call(formats.formatters, opts.format)) throw new TypeError("Unknown format option provided."); format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === "function" || isArray(opts.filter)) filter = opts.filter; var arrayFormat; if (opts.arrayFormat in arrayPrefixGenerators) arrayFormat = opts.arrayFormat; else if ("indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat"; else arrayFormat = defaults.arrayFormat; if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; return { addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots, allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, arrayFormat, charset, charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, commaRoundTrip: !!opts.commaRoundTrip, delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter, format, formatter, serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === "function" ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function(object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === "function") { filter = options.filter; obj = filter("", obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== "object" || obj === null) return ""; var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; if (!objKeys) objKeys = Object.keys(obj); if (options.sort) objKeys.sort(options.sort); var sideChannel = getSideChannel(); for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (typeof key === "undefined" || key === null) continue; var value = obj[key]; if (options.skipNulls && value === null) continue; pushToArray(keys, stringify(value, key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? "?" : ""; if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B" + options.delimiter; else prefix += "utf8=%E2%9C%93" + options.delimiter; return joined.length > 0 ? prefix + joined : ""; }; })); var require_parse = __commonJSMin(((exports, module) => { var utils = require_utils(); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowEmptyArrays: false, allowPrototypes: false, allowSparse: false, arrayLimit: 20, charset: "utf-8", charsetSentinel: false, comma: false, decodeDotInKeys: false, decoder: utils.decode, delimiter: "&", depth: 5, duplicates: "combine", ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1e3, parseArrays: true, plainObjects: false, strictDepth: false, strictMerge: true, strictNullHandling: false, throwOnLimitExceeded: false }; var interpretNumericEntities = function(str) { return str.replace(/&#(\d+);/g, function($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function(val, options, currentArrayLength) { if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) return val.split(","); if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); return val; }; var isoSentinel = "utf8=%26%2310003%3B"; var charsetSentinel = "utf8=%E2%9C%93"; var parseValues = function parseQueryStringValues(str, options) { var obj = { __proto__: null }; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]"); var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; var parts = cleanStr.split(options.delimiter, options.throwOnLimitExceeded && typeof limit !== "undefined" ? limit + 1 : limit); if (options.throwOnLimitExceeded && typeof limit !== "undefined" && parts.length > limit) throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed."); var skipIndex = -1; var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) if (parts[i].indexOf("utf8=") === 0) { if (parts[i] === charsetSentinel) charset = "utf-8"; else if (parts[i] === isoSentinel) charset = "iso-8859-1"; skipIndex = i; i = parts.length; } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) continue; var part = parts[i]; var bracketEqualsPos = part.indexOf("]="); var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; var key; var val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, "key"); val = options.strictNullHandling ? null : ""; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); if (key !== null) val = utils.maybeMap(parseArrayValue(part.slice(pos + 1), options, isArray(obj[key]) ? obj[key].length : 0), function(encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, "value"); }); } if (val && options.interpretNumericEntities && charset === "iso-8859-1") val = interpretNumericEntities(String(val)); if (part.indexOf("[]=") > -1) val = isArray(val) ? [val] : val; if (options.comma && isArray(val) && val.length > options.arrayLimit) { if (options.throwOnLimitExceeded) throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); val = utils.combine([], val, options.arrayLimit, options.plainObjects); } if (key !== null) { var existing = has.call(obj, key); if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) obj[key] = utils.combine(obj[key], val, options.arrayLimit, options.plainObjects); else if (!existing || options.duplicates === "last") obj[key] = val; } } return obj; }; var parseObject = function(chain, val, options, valuesParsed) { var currentArrayLength = 0; if (chain.length > 0 && chain[chain.length - 1] === "[]") { var parentKey = chain.slice(0, -1).join(""); currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; } var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === "[]" && options.parseArrays) if (utils.isOverflow(leaf)) obj = leaf; else obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils.combine([], leaf, options.arrayLimit, options.plainObjects); else { obj = options.plainObjects ? { __proto__: null } : {}; var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot; var index = parseInt(decodedRoot, 10); var isValidArrayIndex = !isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && options.parseArrays; if (!options.parseArrays && decodedRoot === "") obj = { 0: leaf }; else if (isValidArrayIndex && index < options.arrayLimit) { obj = []; obj[index] = leaf; } else if (isValidArrayIndex && options.throwOnLimitExceeded) throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); else if (isValidArrayIndex) { obj[index] = leaf; utils.markOverflow(obj, index); } else if (decodedRoot !== "__proto__") obj[decodedRoot] = leaf; } leaf = obj; } return leaf; }; var splitKeyIntoSegments = function splitKeyIntoSegments(originalKey, options) { var key = options.allowDots ? originalKey.replace(/\.([^.[]+)/g, "[$1]") : originalKey; if (options.depth <= 0) { if (!options.plainObjects && has.call(Object.prototype, key)) { if (!options.allowPrototypes) return; } return [key]; } var segments = []; var first = key.indexOf("["); var parent = first >= 0 ? key.slice(0, first) : key; if (parent) { if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) return; } segments[segments.length] = parent; } var n = key.length; var open = first; var collected = 0; while (open >= 0 && collected < options.depth) { var level = 1; var i = open + 1; var close = -1; while (i < n && close < 0) { var cu = key.charCodeAt(i); if (cu === 91) level += 1; else if (cu === 93) { level -= 1; if (level === 0) close = i; } i += 1; } if (close < 0) { segments[segments.length] = "[" + key.slice(open) + "]"; return segments; } var seg = key.slice(open, close + 1); var content = seg.slice(1, -1); if (!options.plainObjects && has.call(Object.prototype, content) && !options.allowPrototypes) return; segments[segments.length] = seg; collected += 1; open = key.indexOf("[", close + 1); } if (open >= 0) { if (options.strictDepth === true) throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true"); segments[segments.length] = "[" + key.slice(open) + "]"; } return segments; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) return; var keys = splitKeyIntoSegments(givenKey, options); if (!keys) return; return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) return defaults; if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided"); if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") throw new TypeError("Decoder has to be a function."); if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") throw new TypeError("`throwOnLimitExceeded` option must be a boolean"); var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; var duplicates = typeof opts.duplicates === "undefined" ? defaults.duplicates : opts.duplicates; if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") throw new TypeError("The duplicates option must be either combine, first, or last"); return { allowDots: typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots, allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, charset, charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults.decodeDotInKeys, decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, duplicates, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults.strictDepth, strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults.strictMerge, strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling, throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false }; }; module.exports = function(str, opts) { var options = normalizeParseOptions(opts); if (str === "" || str === null || typeof str === "undefined") return options.plainObjects ? { __proto__: null } : {}; var tempObj = typeof str === "string" ? parseValues(str, options) : str; var obj = options.plainObjects ? { __proto__: null } : {}; var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); obj = utils.merge(obj, newObj, options); } if (options.allowSparse === true) return obj; return utils.compact(obj); }; })); var import_lib = __toESM(__commonJSMin(((exports, module) => { var stringify = require_stringify(); var parse = require_parse(); module.exports = { formats: require_formats(), parse, stringify }; }))(), 1); var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) { for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; function urlcat(baseUrlOrTemplate, pathTemplateOrParams, maybeParams = {}, config = {}) { if (typeof pathTemplateOrParams === "string") return urlcatImpl(pathTemplateOrParams, maybeParams, baseUrlOrTemplate, config); else return urlcatImpl(baseUrlOrTemplate, pathTemplateOrParams, void 0, config); } function joinFullUrl(renderedPath, baseUrl, pathAndQuery) { if (renderedPath.length) return join$1(baseUrl, "/", pathAndQuery); else return join$1(baseUrl, "?", pathAndQuery); } function urlcatImpl(pathTemplate, params, baseUrl, config) { const { renderedPath, remainingParams } = path$1(pathTemplate, params); const pathAndQuery = join$1(renderedPath, "?", query(removeNullOrUndef(remainingParams), config)); return baseUrl ? joinFullUrl(renderedPath, baseUrl, pathAndQuery) : pathAndQuery; } function query(params, config) { var _a, _b; if (Object.keys(params).length < 1) return ""; const qsConfiguration = { format: (_b = (_a = config == null ? void 0 : config.objectFormat) == null ? void 0 : _a.format) != null ? _b : "RFC1738", arrayFormat: config == null ? void 0 : config.arrayFormat }; return import_lib.default.stringify(params, qsConfiguration); } function path$1(template, params) { const remainingParams = __spreadValues({}, params); return { renderedPath: template.replace(/:[_A-Za-z]+[_A-Za-z0-9]*/g, (p) => { const key = p.slice(1); validatePathParam(params, key); delete remainingParams[key]; return encodeURIComponent(params[key]); }), remainingParams }; } function validatePathParam(params, key) { const allowedTypes = [ "boolean", "string", "number" ]; if (!Object.prototype.hasOwnProperty.call(params, key)) throw new Error(`Missing value for path parameter ${key}.`); if (!allowedTypes.includes(typeof params[key])) throw new TypeError(`Path parameter ${key} cannot be of type ${typeof params[key]}. Allowed types are: ${allowedTypes.join(", ")}.`); if (typeof params[key] === "string" && params[key].trim() === "") throw new Error(`Path parameter ${key} cannot be an empty string.`); } function join$1(part1, separator, part2) { const p1 = part1.endsWith(separator) ? part1.slice(0, -separator.length) : part1; const p2 = part2.startsWith(separator) ? part2.slice(separator.length) : part2; return p1 === "" || p2 === "" ? p1 + p2 : p1 + separator + p2; } function removeNullOrUndef(params) { return Object.keys(params).filter((k) => notNullOrUndefined(params[k])).reduce((result, k) => { result[k] = params[k]; return result; }, {}); } function notNullOrUndefined(v) { return v !== void 0 && v !== null; } function getBase64FromImg(el) { const canvas = document.createElement("canvas"); canvas.width = el.naturalWidth; canvas.height = el.naturalHeight; const ctx = canvas.getContext("2d"); if (!ctx) return ""; ctx.drawImage(el, 0, 0); return canvas.toDataURL("image/png"); } async function getBase64FromImageUrl(url) { return getBase64FromImg(await loadImage(url)); } function loadImage(url) { return new Promise((resolve, reject) => { const img = new Image(); img.src = url; img.crossOrigin = "anonymous"; img.onload = () => resolve(img); img.onerror = reject; }); } function blobToDataURL(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onerror = reject; reader.onload = () => resolve(reader.result); reader.readAsDataURL(blob); }); } var LOG_PREFIX = "[chatgpt-exporter]"; var LEVEL_ORDER = { debug: 10, info: 20, warn: 30, error: 40 }; var LEVEL_METHOD = { debug: "debug", info: "info", warn: "warn", error: "error" }; function defaultMinLevel() { try { const env = { "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SSR": false, "VITE_EXPORTER_PUBLIC_JWK": "{\"key_ops\":[\"verify\"],\"ext\":true,\"kty\":\"EC\",\"x\":\"JJ3bVBZP3OEXXQg9ENBUXfB9wtrYh0llWjU4HTNwbvM\",\"y\":\"RwotkzzrDYc06ZrxOyCgkcFXAb_Ip1F06SyGO1N3-II\",\"crv\":\"P-256\"}" }; if (env && env.DEV === false) return "info"; } catch {} return "debug"; } var minLevel = defaultMinLevel(); function shouldLog(level) { return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel]; } function sanitizeContext(context) { if (!context) return void 0; const sanitized = {}; for (const [key, value] of Object.entries(context)) { if (/(token|authorization|api[_-]?key|secret|password)/i.test(key)) { sanitized[key] = "[redacted]"; continue; } if (value instanceof Error) { sanitized[key] = { name: value.name, message: value.message }; continue; } sanitized[key] = value; } return sanitized; } function emit(level, message, context) { if (!shouldLog(level)) return; const tag = `${LOG_PREFIX} ${level.toUpperCase()}`; const sanitized = sanitizeContext(context); const sink = console[LEVEL_METHOD[level]] ?? console.log; if (sanitized && Object.keys(sanitized).length > 0) sink(`${tag} ${message}`, sanitized); else sink(`${tag} ${message}`); } var logger = { debug: (message, context) => emit("debug", message, context), info: (message, context) => emit("info", message, context), warn: (message, context) => emit("warn", message, context), error: (message, context) => emit("error", message, context) }; var generateKey = (args) => JSON.stringify(args); function memorize(fn) { const cache = new Map(); const memorized = (...args) => { const key = generateKey(args); if (cache.has(key)) return cache.get(key); const result = fn(...args); cache.set(key, result); return result; }; return memorized; } var ValidationError = class extends Error { constructor(message) { super(message); this.name = "ValidationError"; } }; function isValidationError(error) { return error instanceof ValidationError || typeof error === "object" && error !== null && "name" in error && error.name === "ValidationError"; } var SHARE_PREFIX = "__share__"; var CHAT_ID_PATTERN = /^[a-z0-9_-]+$/i; function assertValidChatId(chatId, label = "chatId") { if (typeof chatId !== "string") throw new ValidationError(`${label} must be a string, received ${typeof chatId}.`); const trimmed = chatId.trim(); if (trimmed.length === 0) throw new ValidationError(`${label} must not be empty.`); const core = trimmed.startsWith(SHARE_PREFIX) ? trimmed.slice(9) : trimmed; if (core.length === 0 || !CHAT_ID_PATTERN.test(core)) throw new ValidationError(`${label} has an invalid format.`); return trimmed; } function assertValidPagination(offset, limit) { if (!Number.isInteger(offset) || offset < 0) throw new ValidationError(`offset must be a non-negative integer, received ${offset}.`); if (!Number.isInteger(limit) || limit <= 0) throw new ValidationError(`limit must be a positive integer, received ${limit}.`); if (limit > 1e3) throw new ValidationError(`limit must not exceed 1000, received ${limit}.`); } function assertValidRequestUrl(url, label = "request url") { if (typeof url !== "string" || url.trim().length === 0) throw new ValidationError(`${label} is not configured for this site.`); let parsed; try { parsed = new URL(url); } catch { throw new ValidationError(`${label} is not a valid URL.`); } if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ValidationError(`${label} must use http(s), received ${parsed.protocol}.`); return url; } function assertValidHtmlUrl(url, label = "URL") { if (typeof url !== "string" || url.trim().length === 0) throw new ValidationError(`${label} must not be empty.`); const trimmed = url.trim(); if (trimmed.startsWith("data:")) { if (/^data:[a-z]+\/[a-z0-9+.-]+;[a-z0-9]+,/.test(trimmed)) return trimmed; throw new ValidationError(`${label} is not a valid data URI.`); } if (trimmed.startsWith("blob:")) return trimmed; if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) try { new URL(trimmed); return trimmed; } catch { throw new ValidationError(`${label} is not a valid URL.`); } if (trimmed.startsWith("mailto:")) return trimmed; throw new ValidationError(`${label} uses an unsupported protocol.`); } var ApiError = class extends Error { status; statusText; url; method; constructor(message, init) { super(message); this.name = "ApiError"; this.status = init.status; this.statusText = init.statusText; this.url = init.url; this.method = init.method; } }; function redactUrl(url) { try { const parsed = new URL(url); const redactedPath = parsed.pathname.split("/").map((segment) => segment.length >= 8 || /\d/.test(segment) ? "" : segment).join("/"); return `${parsed.origin}${redactedPath}`; } catch { return ""; } } var sessionApi = urlcat(baseUrl, "/api/auth/session"); var conversationApi = (id) => urlcat(apiUrl, "/conversation/:id", { id }); var conversationsApi = (offset, limit) => urlcat(apiUrl, "/conversations", { offset, limit }); var fileDownloadApi = (id) => urlcat(apiUrl, "/files/:id/download", { id }); var projectsApi = () => urlcat(apiUrl, "/gizmos/snorlax/sidebar", { conversations_per_gizmo: 0 }); var projectConversationsApi = (gizmo, offset, limit) => urlcat(apiUrl, "/gizmos/:gizmo/conversations", { gizmo, cursor: offset, limit }); var accountsCheckApi = urlcat(apiUrl, "/accounts/check/v4-2023-04-27"); async function getCurrentChatId() { if (isSharePage()) return `__share__${getChatIdFromUrl()}`; const chatId = getChatIdFromUrl(); if (chatId) return chatId; const conversations = await fetchConversations(); if (conversations && conversations.items.length > 0) return conversations.items[0].id; throw new Error("No chat id found."); } async function fetchImageFromPointer(uri) { const imageDetails = await fetchApi(fileDownloadApi(uri.replace("file-service://", "")), isApiFileDownload); if (imageDetails.status === "error") { logger.error("Failed to fetch image asset", { errorCode: imageDetails.error_code, errorMessage: imageDetails.error_message }); return null; } const image = await fetch(imageDetails.download_url); const blob = await image.blob(); const base64 = await blobToDataURL(blob); const contentType = (image.headers.get("content-type") ?? blob.type) || "application/octet-stream"; return base64.replace(/^data:.*?;/, `data:${contentType};`); } function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function isJsonValue(value) { if (value === null) return true; switch (typeof value) { case "string": case "number": case "boolean": return true; case "object": if (Array.isArray(value)) return value.every(isJsonValue); return isJsonObject(value); default: return false; } } function isJsonObject(value) { return isRecord(value) && Object.values(value).every(isJsonValue); } function isFileServiceImageAssetPointer(part) { return isRecord(part) && part.content_type === "image_asset_pointer" && typeof part.asset_pointer === "string" && part.asset_pointer.startsWith("file-service://"); } function isNonEmptyString(value) { return typeof value === "string" && value.length > 0; } function isStringArray(value) { return Array.isArray(value) && value.every((item) => typeof item === "string"); } function isApiFileDownload(value) { if (!isRecord(value) || typeof value.status !== "string") return false; if (value.status === "success") return typeof value.download_url === "string" && typeof value.file_name === "string" && isJsonObject(value.metadata) && isNonEmptyString(value.creation_time); if (value.status === "error") return typeof value.error_code === "string" && (value.error_message === null || typeof value.error_message === "string"); return false; } function isApiConversationItem(value) { return isRecord(value) && typeof value.id === "string" && typeof value.title === "string" && typeof value.create_time === "number"; } function isApiConversations(value) { return isRecord(value) && typeof value.has_missing_conversations === "boolean" && typeof value.limit === "number" && typeof value.offset === "number" && (value.total === null || typeof value.total === "number") && Array.isArray(value.items) && value.items.every(isApiConversationItem); } function isApiConversation(value) { return isRecord(value) && typeof value.create_time === "number" && typeof value.current_node === "string" && isRecord(value.mapping) && Array.isArray(value.moderation_results) && typeof value.title === "string" && typeof value.is_archived === "boolean" && typeof value.update_time === "number"; } function isApiProjectConversations(value) { return isRecord(value) && Array.isArray(value.items) && (value.cursor === void 0 || value.cursor === null || typeof value.cursor === "number") && value.items.every(isApiConversationItem); } function isApiProjectsResponse(value) { return isRecord(value) && Array.isArray(value.items) && value.items.every(isApiGizmo); } function isApiGizmo(value) { return isRecord(value) && isRecord(value.gizmo) && isRecord(value.gizmo.gizmo) && typeof value.gizmo.gizmo.id === "string" && typeof value.gizmo.gizmo.organization_id === "string" && isRecord(value.gizmo.gizmo.display) && typeof value.gizmo.gizmo.display.name === "string" && typeof value.gizmo.gizmo.display.description === "string"; } function isApiSession(value) { return isRecord(value) && typeof value.accessToken === "string"; } function isApiAccountsCheckAccount(value) { return isRecord(value) && isRecord(value.account) && (value.account.account_id === null || typeof value.account.account_id === "string"); } function isApiAccountsCheck(value) { return isRecord(value) && isRecord(value.accounts) && Object.values(value.accounts).every(isApiAccountsCheckAccount) && isStringArray(value.account_ordering); } function isApiSuccessResponse(value) { return isRecord(value) && typeof value.success === "boolean"; } async function replaceImageAssets(conversation) { const imageAssets = Object.values(conversation.mapping).flatMap((node) => { if (!node.message) return []; if (node.message.content.content_type !== "multimodal_text") return []; return (Array.isArray(node.message.content.parts) ? node.message.content.parts : []).filter(isFileServiceImageAssetPointer); }); const executionOutputs = Object.values(conversation.mapping).flatMap((node) => { if (!node.message) return []; if (node.message.content.content_type !== "execution_output") return []; if (!node.message.metadata?.aggregate_result?.messages) return []; return node.message.metadata.aggregate_result.messages.filter((msg) => msg.message_type === "image"); }); await Promise.all([...imageAssets.map(async (asset) => { try { const newAssetPointer = await fetchImageFromPointer(asset.asset_pointer); if (newAssetPointer) asset.asset_pointer = newAssetPointer; } catch (error) { logger.error("Failed to fetch image asset", { error }); } }), ...executionOutputs.map(async (msg) => { try { const newImageUrl = await fetchImageFromPointer(msg.image_url); if (newImageUrl) msg.image_url = newImageUrl; } catch (error) { logger.error("Failed to fetch image asset", { error }); } })]); } async function fetchConversation(chatId, shouldReplaceAssets) { await requireExporterApiAuth(); const validChatId = assertValidChatId(chatId); if (validChatId.startsWith("__share__")) { const id = validChatId.replace("__share__", ""); const shareConversation = getConversationFromSharePage(); if (!shareConversation) throw new Error("Failed to read shared conversation from the page."); await replaceImageAssets(shareConversation); return { id, ...shareConversation }; } const conversation = await fetchApi(conversationApi(validChatId), isApiConversation); if (shouldReplaceAssets) await replaceImageAssets(conversation); return { id: validChatId, ...conversation }; } async function fetchProjects() { await requireExporterApiAuth(); const { items } = await fetchApi(projectsApi(), isApiProjectsResponse); return items.map((gizmo) => gizmo.gizmo.gizmo); } async function fetchConversations(offset = 0, limit = 20, project = null) { if (project) return fetchProjectConversations(project, offset, limit); assertValidPagination(offset, limit); return fetchApi(conversationsApi(offset, limit), isApiConversations); } async function fetchProjectConversations(project, offset = 0, limit = 20) { assertValidChatId(project, "project"); assertValidPagination(offset, limit); const { items } = await fetchApi(projectConversationsApi(project, offset, limit), isApiProjectConversations); return { has_missing_conversations: false, items, limit, offset, total: null }; } async function fetchAllConversations(project = null, maxConversations = 1e3) { await requireExporterApiAuth(); if (!Number.isInteger(maxConversations) || maxConversations <= 0) throw new Error(`maxConversations must be a positive integer, received ${maxConversations}.`); const conversations = []; const limit = project === null ? 100 : 50; let offset = 0; while (true) try { const result = project === null ? await fetchConversations(offset, limit) : await fetchProjectConversations(project, offset, limit); if (!result.items) { logger.warn("fetchAllConversations received no items", { offset, project }); break; } conversations.push(...result.items); if (result.items.length === 0) break; if (result.total !== null && offset + limit >= result.total) break; if (conversations.length >= maxConversations) break; offset += limit; } catch (error) { logger.error("Error fetching conversations batch", { offset, project, error }); break; } return conversations.slice(0, maxConversations); } async function archiveConversation(chatId) { await requireExporterApiAuth(); const { success } = await fetchApi(conversationApi(assertValidChatId(chatId)), isApiSuccessResponse, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ is_archived: true }) }); return success; } async function deleteConversation(chatId) { await requireExporterApiAuth(); const { success } = await fetchApi(conversationApi(assertValidChatId(chatId)), isApiSuccessResponse, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ is_visible: false }) }); return success; } async function fetchApi(url, validate, options) { await requireExporterApiAuth(); assertValidRequestUrl(url, "backend API url"); const method = options?.method ?? "GET"; const safeUrl = redactUrl(url); const accessToken = await getAccessToken(); const accountId = await getTeamAccountId(); logger.debug("API request", { method, url: safeUrl }); let response; try { response = await fetch(url, { ...options, headers: { "Authorization": `Bearer ${accessToken}`, "X-Authorization": `Bearer ${accessToken}`, ...accountId ? { "Chatgpt-Account-Id": accountId } : {}, ...options?.headers } }); } catch (error) { logger.error("API request failed (network)", { method, url: safeUrl, error }); throw new ApiError("Network request failed.", { status: 0, statusText: "Network Error", url: safeUrl, method }); } if (!response.ok) { logger.error("API request returned an error status", { method, url: safeUrl, status: response.status, statusText: response.statusText }); throw new ApiError(`Request failed with status ${response.status} ${response.statusText}`.trim(), { status: response.status, statusText: response.statusText, url: safeUrl, method }); } try { const payload = await response.json(); if (!validate(payload)) { logger.error("API response had unexpected shape", { method, url: safeUrl }); throw new ApiError("API response had an unexpected shape.", { status: response.status, statusText: response.statusText, url: safeUrl, method }); } return payload; } catch (error) { if (error instanceof ApiError) throw error; logger.error("API response was not valid JSON", { method, url: safeUrl, error }); throw new ApiError("Response was not valid JSON.", { status: response.status, statusText: response.statusText, url: safeUrl, method }); } } async function parseResponsePayload(response, validate, label, method = "GET") { try { const payload = await response.json(); if (!validate(payload)) { logger.error("Response payload failed schema check", { label, status: response.status, statusText: response.statusText, url: redactUrl(response.url) }); throw new ApiError("Response did not match expected schema.", { status: response.status, statusText: response.statusText, url: redactUrl(response.url), method }); } return payload; } catch (error) { if (error instanceof ApiError) throw error; throw new ApiError("Response was not valid JSON.", { status: response.status, statusText: response.statusText, url: redactUrl(response.url), method }); } } async function _fetchSession() { assertValidRequestUrl(sessionApi, "session url"); let response; try { response = await fetch(sessionApi); } catch (error) { logger.error("Session request failed (network)", { error }); throw new ApiError("Network request failed.", { status: 0, statusText: "Network Error", url: redactUrl(sessionApi), method: "GET" }); } if (!response.ok) throw new ApiError(`Session request failed with status ${response.status} ${response.statusText}`.trim(), { status: response.status, statusText: response.statusText, url: redactUrl(sessionApi), method: "GET" }); try { return await parseResponsePayload(response, isApiSession, "session"); } catch (error) { if (error instanceof ApiError) throw error; logger.error("Session response was not valid JSON", { error }); throw new ApiError("Session response was not valid JSON.", { status: response.status, statusText: response.statusText, url: redactUrl(sessionApi), method: "GET" }); } } var fetchSession = memorize(_fetchSession); async function getAccessToken() { const pageAccessToken = getPageAccessToken(); if (pageAccessToken) return pageAccessToken; return (await fetchSession()).accessToken; } async function _fetchAccountsCheck() { assertValidRequestUrl(accountsCheckApi, "accounts check url"); const accessToken = await getAccessToken(); let response; try { response = await fetch(accountsCheckApi, { headers: { "Authorization": `Bearer ${accessToken}`, "X-Authorization": `Bearer ${accessToken}` } }); } catch (error) { logger.error("Accounts check request failed (network)", { error }); throw new ApiError("Network request failed.", { status: 0, statusText: "Network Error", url: redactUrl(accountsCheckApi), method: "GET" }); } if (!response.ok) throw new ApiError(`Accounts check failed with status ${response.status} ${response.statusText}`.trim(), { status: response.status, statusText: response.statusText, url: redactUrl(accountsCheckApi), method: "GET" }); try { return await parseResponsePayload(response, isApiAccountsCheck, "accounts check"); } catch (error) { if (error instanceof ApiError) throw error; logger.error("Accounts check response was not valid JSON", { error }); throw new ApiError("Accounts check response was not valid JSON.", { status: response.status, statusText: response.statusText, url: redactUrl(accountsCheckApi), method: "GET" }); } } var fetchAccountsCheck = memorize(_fetchAccountsCheck); var getCookie = (key) => document.cookie.match(`(^|;)\\s*${key}\\s*=\\s*([^;]+)`)?.pop() || ""; async function getTeamAccountId() { const accountsCheck = await fetchAccountsCheck(); const workspaceId = getCookie("_account"); if (workspaceId) { const account = accountsCheck.accounts[workspaceId]; if (account) return account.account.account_id; } return null; } var ModelMapping = { "text-davinci-002-render-sha": "GPT-3.5", "text-davinci-002-render-paid": "GPT-3.5", "text-davinci-002-browse": "GPT-3.5", "gpt-4": "GPT-4", "gpt-4-browsing": "GPT-4 (Browser)", "gpt-4o": "GPT-4o", "gemini": "Gemini", "text-davinci-002": "GPT-3.5" }; function processConversation(conversation) { const title = conversation.title || "ChatGPT Conversation"; const createTime = conversation.create_time; const updateTime = conversation.update_time; const { model, modelSlug } = extractModel(conversation.mapping); const startNodeId = conversation.current_node || Object.values(conversation.mapping).find((node) => !node.children || node.children.length === 0)?.id; if (!startNodeId) throw new Error("Failed to find start node."); const mergedConversationNodes = mergeContinuationNodes(extractConversationResult(conversation.mapping, startNodeId)); return { id: conversation.id, title, model, modelSlug, createTime, updateTime, conversationNodes: mergedConversationNodes }; } function extractModel(conversationMapping) { let model = ""; const modelSlug = Object.values(conversationMapping).find((node) => node.message?.metadata?.model_slug)?.message?.metadata?.model_slug || ""; if (modelSlug) if (ModelMapping[modelSlug]) model = ModelMapping[modelSlug]; else Object.keys(ModelMapping).forEach((key) => { if (modelSlug.startsWith(key)) model = key; }); return { model, modelSlug }; } function extractConversationResult(conversationMapping, startNodeId) { const result = []; let currentNodeId = startNodeId; while (currentNodeId) { const node = conversationMapping[currentNodeId]; if (!node) break; if (node.parent === void 0) break; if (node.message?.author.role !== "system" && node.message?.content.content_type !== "model_editable_context" && node.message?.content.content_type !== "user_editable_context") result.unshift(node); currentNodeId = node.parent; } return result; } function mergeContinuationNodes(nodes) { const result = []; for (const node of nodes) { const prevNode = result[result.length - 1]; if (prevNode?.message?.author.role === "assistant" && node.message?.author.role === "assistant" && prevNode.message.recipient === "all" && node.message.recipient === "all" && prevNode.message.content.content_type === "text" && node.message.content.content_type === "text") { prevNode.message.content.parts[prevNode.message.content.parts.length - 1] += node.message.content.parts[0]; prevNode.message.content.parts.push(...node.message.content.parts.slice(1)); } else result.push(node); } return result; } var chatgptProvider = { id: "chatgpt", label: "ChatGPT", matchHost: (host) => host.includes("chatgpt.com") || host.includes("chat.openai.com"), getCurrentChatId, fetchConversation, fetchProjects, fetchAllConversations, archiveConversation, deleteConversation, processConversation }; var NOT_IMPLEMENTED = "NotImplemented: claude export needs live session mapping"; var claudeProvider = { id: "claude", label: "Claude", matchHost: (host) => host.includes("claude.ai"), getCurrentChatId() { throw new Error(NOT_IMPLEMENTED); }, fetchConversation(_id, _replaceAssets) { throw new Error(NOT_IMPLEMENTED); }, fetchProjects() { throw new Error(NOT_IMPLEMENTED); }, fetchAllConversations(_project, _max) { throw new Error(NOT_IMPLEMENTED); }, archiveConversation(_id) { throw new Error(NOT_IMPLEMENTED); }, deleteConversation(_id) { throw new Error(NOT_IMPLEMENTED); }, processConversation(_conversation) { throw new Error(NOT_IMPLEMENTED); } }; var GEMINI_CURRENT_CHAT_ID = "gemini-current"; var GEMINI_MODEL_SLUG = "gemini"; var geminiDefaultAvatar = "data:image/svg+xml,%3Csvg%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-width%3D%221.5%22%20viewBox%3D%22-6%20-6%2036%2036%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20style%3D%22color%3A%20white%3B%20background%3A%20%234285f4%3B%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M20%2021v-2a4%204%200%200%200-4-4H8a4%204%200%200%200-4%204v2%22%3E%3C%2Fpath%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%227%22%20r%3D%224%22%3E%3C%2Fcircle%3E%3C%2Fsvg%3E"; var geminiProvider = { id: "gemini", label: "Gemini", features: { bulkExport: false, archive: false, delete: false, projects: false, timestamps: false, png: true }, matchHost: (host) => host.includes("gemini.google.com"), getChatIdFromUrl: getGeminiChatIdFromUrl, getCurrentChatId: async () => getGeminiChatIdFromUrl() ?? GEMINI_CURRENT_CHAT_ID, fetchConversation: async (chatId, _shouldReplaceAssets) => { return getGeminiConversationFromPage(chatId); }, fetchAllConversations: async () => [], fetchProjects: async () => [], archiveConversation: async () => false, deleteConversation: async () => false, processConversation, checkIfConversationStarted: () => extractGeminiTurns(document).length > 0, getUserAvatar: getGeminiUserAvatar, getConversationSource: (id) => { if (id === GEMINI_CURRENT_CHAT_ID) return location.href; return `${location.origin}/app/${id}`; }, getScreenshotTarget: () => { return document.querySelector("main") ?? document.querySelector("chat-window") ?? document.querySelector("infinite-scroller"); }, mountMenu: (getMenuContainer) => { const containerId = "chatgpt-exporter-gemini-menu"; const mount = () => { if (document.getElementById(containerId)) return; const container = getMenuContainer(); container.id = containerId; container.style.position = "fixed"; container.style.left = "16px"; container.style.bottom = "16px"; container.style.zIndex = "2147483647"; container.style.maxWidth = "316px"; document.body.append(container); }; mount(); setInterval(mount, 300); } }; function getGeminiChatIdFromUrl(pathname = location.pathname) { return pathname.match(/^\/app\/([a-z0-9_-]+)/i)?.[1] ?? null; } function getGeminiConversationFromPage(chatId = getGeminiChatIdFromUrl() ?? GEMINI_CURRENT_CHAT_ID) { const now = Date.now() / 1e3; const turns = extractGeminiTurns(document); const createTime = turns.find((turn) => turn.timestamp)?.timestamp ?? now; const updateTime = [...turns].reverse().find((turn) => turn.timestamp)?.timestamp ?? now; const title = getGeminiTitle(turns); const mapping = buildConversationMapping(turns); return { id: chatId, title, create_time: createTime, update_time: updateTime, conversation_id: chatId, current_node: turns.length > 0 ? `gemini-message-${turns.length - 1}` : "gemini-root", mapping, moderation_results: [], is_archived: false }; } function extractGeminiTurns(root) { const nativeTurns = Array.from(root.querySelectorAll("user-query, model-response")); const turnElements = nativeTurns.length > 0 ? nativeTurns : Array.from(root.querySelectorAll([ "[data-message-author-role=\"user\"]", "[data-message-author-role=\"assistant\"]", "[data-testid=\"user-query\"]", "[data-test-id=\"user-query\"]", "[data-testid=\"model-response\"]", "[data-test-id=\"model-response\"]" ].join(","))); const turns = []; turnElements.forEach((element) => { if (turnElements.some((candidate) => candidate !== element && candidate.contains(element))) return; const role = getTurnRole(element); if (!role) return; const text = elementToMarkdown(getTurnContentElement(element, role)).trim(); if (!text) return; turns.push({ role, text, timestamp: getTurnTimestamp(element) }); }); return turns; } function buildConversationMapping(turns) { const mapping = { "gemini-root": { id: "gemini-root", children: turns.length > 0 ? ["gemini-message-0"] : [] } }; turns.forEach((turn, index) => { const id = `gemini-message-${index}`; mapping[id] = { id, parent: index === 0 ? "gemini-root" : `gemini-message-${index - 1}`, children: turns[index + 1] ? [`gemini-message-${index + 1}`] : [], message: createGeminiMessage(id, turn) }; }); return mapping; } function createGeminiMessage(id, turn) { return { id, author: { role: turn.role, name: turn.role === "assistant" ? "Gemini" : void 0, metadata: {} }, content: { content_type: "text", parts: [turn.text] }, create_time: turn.timestamp, update_time: turn.timestamp, metadata: { model_slug: turn.role === "assistant" ? GEMINI_MODEL_SLUG : void 0 }, recipient: "all", status: "finished_successfully", end_turn: true, weight: 1 }; } function getTurnRole(element) { const tagName = element.tagName.toLowerCase(); const explicitRole = element.getAttribute("data-message-author-role")?.toLowerCase(); const testId = [element.getAttribute("data-testid"), element.getAttribute("data-test-id")].filter(Boolean).join(" ").toLowerCase(); if (tagName === "user-query" || explicitRole === "user" || testId.includes("user-query")) return "user"; if (tagName === "model-response" || explicitRole === "assistant" || testId.includes("model-response")) return "assistant"; return null; } function getTurnContentElement(element, role) { return (role === "assistant" ? [ "message-content .markdown", "message-content", "[id^=\"message-content\"] .markdown", "[id^=\"message-content\"]", ".markdown", ".model-response-text", ".response-content" ] : [ ".query-text", ".query-content", ".user-query-text", "[data-testid=\"user-message\"]", "[data-test-id=\"user-message\"]" ]).map((selector) => element.querySelector(selector)).find((candidate) => candidate && getElementText(candidate).trim().length > 0) ?? element; } function getTurnTimestamp(element) { const timeElement = element.querySelector("time[datetime]"); const datetime = timeElement?.dateTime || timeElement?.getAttribute("datetime"); if (!datetime) return void 0; const timestamp = Date.parse(datetime); if (Number.isNaN(timestamp)) return void 0; return timestamp / 1e3; } function getGeminiTitle(turns) { const title = document.title.replace(/\s*[-|]\s*Gemini.*$/i, "").replace(/^Gemini\s*[-|]\s*/i, "").trim(); if (title && title.toLowerCase() !== "gemini") return title; const firstUserTurn = turns.find((turn) => turn.role === "user"); if (firstUserTurn) return normalizeTitle(firstUserTurn.text); return "Gemini Conversation"; } function normalizeTitle(text) { const title = text.replace(/!\[[^\]]*]\([^)]+\)/g, "").replace(/\s+/g, " ").trim(); if (!title) return "Gemini Conversation"; return title.length > 80 ? `${title.slice(0, 77).trim()}...` : title; } async function getGeminiUserAvatar() { try { const avatar = Array.from(document.querySelectorAll([ "button[aria-label*=\"Google Account\"] img", "a[aria-label*=\"Google Account\"] img", "img[alt*=\"profile\" i]", "img[alt*=\"avatar\" i]" ].join(","))).find((img) => img.src && !img.src.startsWith("data:")); if (avatar) return getBase64FromImg(avatar); } catch (error) { logger.warn("Failed to load Gemini avatar from DOM", { error }); } return geminiDefaultAvatar; } function elementToMarkdown(element) { const clone = element.cloneNode(true); clone.querySelectorAll([ "button", "mat-icon", "svg", "[aria-hidden=\"true\"]", "[role=\"toolbar\"]", "[data-test-id*=\"action\"]", "[data-testid*=\"action\"]" ].join(",")).forEach((node) => node.remove()); return normalizeMarkdown(Array.from(clone.childNodes).map((node) => nodeToMarkdown(node)).join("") || getElementText(element)); } function nodeToMarkdown(node, inPre = false) { if (node.nodeType === Node.TEXT_NODE) return node.textContent ?? ""; if (node.nodeType !== Node.ELEMENT_NODE) return ""; const element = node; const tagName = element.tagName.toLowerCase(); const children = () => Array.from(element.childNodes).map((child) => nodeToMarkdown(child, inPre)).join(""); switch (tagName) { case "br": return "\n"; case "p": case "div": case "section": case "article": return block(children()); case "h1": return heading$2(children(), 1); case "h2": return heading$2(children(), 2); case "h3": return heading$2(children(), 3); case "h4": return heading$2(children(), 4); case "h5": return heading$2(children(), 5); case "h6": return heading$2(children(), 6); case "pre": return codeBlock(element); case "code": if (inPre) return element.textContent ?? ""; return inlineCode$2(element.textContent ?? ""); case "strong": case "b": return wrapInline(children(), "**"); case "em": case "i": return wrapInline(children(), "*"); case "a": return linkMarkdown(element, children()); case "img": return imageMarkdown(element); case "blockquote": return block(prefixLines(children(), "> ")); case "ul": return listMarkdown(element, false); case "ol": return listMarkdown(element, true); case "li": return children().trim(); default: return children(); } } function block(value) { const normalized = normalizeMarkdown(value); return normalized ? `\n\n${normalized}\n\n` : ""; } function heading$2(value, level) { const normalized = normalizeMarkdown(value); return normalized ? `\n\n${"#".repeat(level)} ${normalized}\n\n` : ""; } function codeBlock(element) { const code = element.textContent?.replace(/\n+$/, "") ?? ""; const codeElement = element.querySelector("code"); return `\n\n\`\`\`${Array.from(codeElement?.classList ?? []).find((className) => className.startsWith("language-"))?.replace("language-", "") ?? ""}\n${code}\n\`\`\`\n\n`; } function inlineCode$2(value) { if (!value) return ""; const fence = value.includes("`") ? "``" : "`"; return `${fence}${value}${fence}`; } function wrapInline(value, marker) { const normalized = normalizeInline(value); return normalized ? `${marker}${normalized}${marker}` : ""; } function linkMarkdown(element, content) { const text = normalizeInline(content) || normalizeInline(element.textContent ?? ""); const href = element.getAttribute("href"); if (!href || !text || href.startsWith("javascript:")) return text; return `[${text}](${element.href || href})`; } function imageMarkdown(element) { const src = element.getAttribute("src"); if (!src) return ""; return `![${element.getAttribute("alt") ?? "image"}](${element.src || src})`; } function listMarkdown(element, ordered) { const items = Array.from(element.children).filter((child) => child.tagName.toLowerCase() === "li").map((child, index) => { return `${ordered ? `${index + 1}.` : "-"} ${normalizeMarkdown(nodeToMarkdown(child)).replace(/\n/g, "\n ")}`; }).filter((item) => item.trim().length > 2); return items.length > 0 ? `\n\n${items.join("\n")}\n\n` : ""; } function prefixLines(value, prefix) { return normalizeMarkdown(value).split("\n").map((line) => `${prefix}${line}`).join("\n"); } function normalizeMarkdown(value) { return value.replace(/\u00a0/g, " ").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim(); } function normalizeInline(value) { return value.replace(/\s+/g, " ").trim(); } function getElementText(element) { return element.innerText ?? element.textContent ?? ""; } var providers = [ chatgptProvider, claudeProvider, geminiProvider ]; function getActiveProvider(host = location.host) { return providers.find((provider) => provider.matchHost(host)) ?? chatgptProvider; } function getProviderFeature(feature, host = location.host) { return getActiveProvider(host).features?.[feature] ?? true; } function getConversationSource(id, host = location.host) { const provider = getActiveProvider(host); if (provider.getConversationSource) return provider.getConversationSource(id); return `${baseUrl}/c/${id}`; } function getHistoryDisabled() { if (getActiveProvider().id !== "chatgpt") return false; return localStorage.getItem(KEY_OAI_HISTORY_DISABLED) === "\"true\""; } function getPageAccessToken() { return _unsafeWindow?.__remixContext?.state?.loaderData?.root?.clientBootstrap?.session?.accessToken ?? null; } function getUserProfile() { const user = _unsafeWindow?.__NEXT_DATA__?.props?.pageProps?.user ?? _unsafeWindow?.__remixContext?.state?.loaderData?.root?.clientBootstrap?.session?.user; if (!user) throw new Error("No user found."); return user; } function getChatIdFromUrl() { const provider = getActiveProvider(); if (provider.getChatIdFromUrl) return provider.getChatIdFromUrl(); const match = location.pathname.match(/^\/(?:share|c|g\/[a-z0-9-]+\/c)\/([a-z0-9-]+)/i); if (match) return match[1]; return null; } function isSharePage() { if (getActiveProvider().id !== "chatgpt") return false; return location.pathname.startsWith("/share") && !location.pathname.endsWith("/continue"); } function cloneConversation(conversation) { return structuredClone(conversation); } function getConversationFromSharePage() { if (window.__NEXT_DATA__?.props?.pageProps?.serverResponse?.data) return cloneConversation(window.__NEXT_DATA__.props.pageProps.serverResponse.data); if (window.__remixContext?.state?.loaderData?.["routes/share.$shareId.($action)"]?.serverResponse?.data) return cloneConversation(window.__remixContext.state.loaderData["routes/share.$shareId.($action)"].serverResponse.data); return null; } var defaultAvatar = "data:image/svg+xml,%3Csvg%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-width%3D%221.5%22%20viewBox%3D%22-6%20-6%2036%2036%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20style%3D%22color%3A%20white%3B%20background%3A%20%23ab68ff%3B%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M20%2021v-2a4%204%200%200%200-4-4H8a4%204%200%200%200-4%204v2%22%3E%3C%2Fpath%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%227%22%20r%3D%224%22%3E%3C%2Fcircle%3E%3C%2Fsvg%3E"; async function getUserAvatar() { const provider = getActiveProvider(); if (provider.getUserAvatar) return provider.getUserAvatar(); try { const { picture } = getUserProfile(); if (picture) return await getBase64FromImageUrl(picture); } catch (e) { logger.warn("Failed to load user avatar from profile", { error: e }); } try { const avatar = Array.from(document.querySelectorAll("img[alt]:not([aria-hidden])")).find((avatar) => !avatar.src.startsWith("data:")); if (avatar) return getBase64FromImg(avatar); } catch (e) { logger.warn("Failed to load user avatar from DOM", { error: e }); } return defaultAvatar; } function checkIfConversationStarted() { const provider = getActiveProvider(); if (provider.checkIfConversationStarted) return provider.checkIfConversationStarted(); return !!document.querySelector("[data-testid^=\"conversation-turn-\"]"); } function p$3(n, t) { c$2.__h && c$2.__h(r$3, n, o$6 || t), o$6 = 0; var u = r$3.__H || (r$3.__H = { __: [], __h: [] }); return n >= u.__.length && u.__.push({}), u.__[n]; } function d$1(n) { return o$6 = 1, h$1(D$2, n); } function h$1(n, u, i) { var o = p$3(t$4++, 2); if (o.t = n, !o.__c && (o.__ = [i ? i(u) : D$2(void 0, u), function(n) { var t = o.__N ? o.__N[0] : o.__[0], r = o.t(t, n); t !== r && (o.__N = [r, o.__[1]], o.__c.setState({})); }], o.__c = r$3, !r$3.__f)) { var f = function(n, t, r) { if (!o.__c.__H) return !0; var u = o.__c.__H.__.filter(function(n) { return n.__c; }); if (u.every(function(n) { return !n.__N; })) return !c || c.call(this, n, t, r); var i = o.__c.props !== n; return u.some(function(n) { if (n.__N) { var t = n.__[0]; n.__ = n.__N, n.__N = void 0, t !== n.__[0] && (i = !0); } }), c && c.call(this, n, t, r) || i; }; r$3.__f = !0; var c = r$3.shouldComponentUpdate, e = r$3.componentWillUpdate; r$3.componentWillUpdate = function(n, t, r) { if (this.__e) { var u = c; c = void 0, f(n, t, r), c = u; } e && e.call(this, n, t, r); }, r$3.shouldComponentUpdate = f; } return o.__N || o.__; } function y$1(n, u) { var i = p$3(t$4++, 3); !c$2.__s && C$5(i.__H, u) && (i.__ = n, i.u = u, r$3.__H.__h.push(i)); } function _$1(n, u) { var i = p$3(t$4++, 4); !c$2.__s && C$5(i.__H, u) && (i.__ = n, i.u = u, r$3.__h.push(i)); } function A$2(n) { return o$6 = 5, T$1(function() { return { current: n }; }, []); } function F$2(n, t, r) { o$6 = 6, _$1(function() { if ("function" == typeof n) { var r = n(t()); return function() { n(null), r && "function" == typeof r && r(); }; } if (n) return n.current = t(), function() { return n.current = null; }; }, null == r ? r : r.concat(n)); } function T$1(n, r) { var u = p$3(t$4++, 7); return C$5(u.__H, r) && (u.__ = n(), u.__H = r, u.__h = n), u.__; } function q$1(n, t) { return o$6 = 8, T$1(function() { return n; }, t); } function x$1(n) { var u = r$3.context[n.__c], i = p$3(t$4++, 9); return i.c = n, u ? (i.__ ?? (i.__ = !0, u.sub(r$3)), u.props.value) : n.__; } function P$3(n, t) { c$2.useDebugValue && c$2.useDebugValue(t ? t(n) : n); } function b$2(n) { var u = p$3(t$4++, 10), i = d$1(); return u.__ = n, r$3.componentDidCatch || (r$3.componentDidCatch = function(n, t) { u.__ && u.__(n, t), i[1](n); }), [i[0], function() { i[1](void 0); }]; } function g$2() { var n = p$3(t$4++, 11); if (!n.__) { for (var u = r$3.__v; null !== u && !u.__m && null !== u.__;) u = u.__; var i = u.__m || (u.__m = [0, 0]); n.__ = "P" + i[0] + "-" + i[1]++; } return n.__; } function j$3() { for (var n; n = f$4.shift();) { var t = n.__H; if (n.__P && t) try { t.__h.some(z$1), t.__h.some(B$1), t.__h = []; } catch (r) { t.__h = [], c$2.__e(r, n.__v); } } } function w$3(n) { var t, r = function() { clearTimeout(u), k$1 && cancelAnimationFrame(t), setTimeout(n); }, u = setTimeout(r, 35); k$1 && (t = requestAnimationFrame(r)); } function z$1(n) { var t = r$3, u = n.__c; "function" == typeof u && (n.__c = void 0, u()), r$3 = t; } function B$1(n) { var t = r$3; n.__c = n.__(), r$3 = t; } function C$5(n, t) { return !n || n.length !== t.length || t.some(function(t, r) { return t !== n[r]; }); } function D$2(n, t) { return "function" == typeof t ? t(n) : t; } var t$4, r$3, u$4, i$2, o$6, f$4, c$2, e$3, a$4, v, l$4, m$2, s$5, k$1; var init_hooks_module = __esmMin((() => { o$6 = 0, f$4 = [], c$2 = l$5, e$3 = c$2.__b, a$4 = c$2.__r, v = c$2.diffed, l$4 = c$2.__c, m$2 = c$2.unmount, s$5 = c$2.__; c$2.__b = function(n) { r$3 = null, e$3 && e$3(n); }, c$2.__ = function(n, t) { n && t.__k && t.__k.__m && (n.__m = t.__k.__m), s$5 && s$5(n, t); }, c$2.__r = function(n) { a$4 && a$4(n), t$4 = 0; var i = (r$3 = n.__c).__H; i && (u$4 === r$3 ? (i.__h = [], r$3.__h = [], i.__.some(function(n) { n.__N && (n.__ = n.__N), n.u = n.__N = void 0; })) : (i.__h.some(z$1), i.__h.some(B$1), i.__h = [], t$4 = 0)), u$4 = r$3; }, c$2.diffed = function(n) { v && v(n); var t = n.__c; t && t.__H && (t.__H.__h.length && (1 !== f$4.push(t) && i$2 === c$2.requestAnimationFrame || ((i$2 = c$2.requestAnimationFrame) || w$3)(j$3)), t.__H.__.some(function(n) { n.u && (n.__H = n.u), n.u = void 0; })), u$4 = r$3 = null; }, c$2.__c = function(n, t) { t.some(function(n) { try { n.__h.some(z$1), n.__h = n.__h.filter(function(n) { return !n.__ || B$1(n); }); } catch (r) { t.some(function(n) { n.__h && (n.__h = []); }), t = [], c$2.__e(r, n.__v); } }), l$4 && l$4(n, t); }, c$2.unmount = function(n) { m$2 && m$2(n); var t, r = n.__c; r && r.__H && (r.__H.__.some(function(n) { try { z$1(n); } catch (n) { t = n; } }), r.__H = void 0, t && c$2.__e(t, r.__v)); }; k$1 = "function" == typeof requestAnimationFrame; })); var compat_module_exports = __exportAll({ Children: () => L$3, Component: () => C$6, Fragment: () => S, PureComponent: () => M$1, StrictMode: () => S, Suspense: () => P$2, SuspenseList: () => B, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: () => fn, cloneElement: () => mn, createContext: () => X$1, createElement: () => k$2, createFactory: () => sn, createPortal: () => $, createRef: () => M$2, default: () => gn, findDOMNode: () => yn, flushSync: () => bn, forwardRef: () => D$1, hydrate: () => tn, isElement: () => Sn, isFragment: () => vn, isMemo: () => dn, isValidElement: () => hn, lazy: () => z, memo: () => N$1, render: () => nn, startTransition: () => x, unmountComponentAtNode: () => pn, unstable_batchedUpdates: () => _n, useCallback: () => q$1, useContext: () => x$1, useDebugValue: () => P$3, useDeferredValue: () => w$2, useEffect: () => y$1, useErrorBoundary: () => b$2, useId: () => g$2, useImperativeHandle: () => F$2, useInsertionEffect: () => I$2, useLayoutEffect: () => _$1, useMemo: () => T$1, useReducer: () => h$1, useRef: () => A$2, useState: () => d$1, useSyncExternalStore: () => C$4, useTransition: () => k, version: () => an }); function g$1(n, t) { for (var e in t) n[e] = t[e]; return n; } function E$4(n, t) { for (var e in n) if ("__source" !== e && !(e in t)) return !0; for (var r in t) if ("__source" !== r && n[r] !== t[r]) return !0; return !1; } function C$4(n, t) { var e = t(), r = d$1({ t: { __: e, u: t } }), u = r[0].t, o = r[1]; return _$1(function() { u.__ = e, u.u = t, R(u) && o({ t: u }); }, [ n, e, t ]), y$1(function() { return R(u) && o({ t: u }), n(function() { R(u) && o({ t: u }); }); }, [n]), e; } function R(n) { try { return !((t = n.__) === (e = n.u()) && (0 !== t || 1 / t == 1 / e) || t != t && e != e); } catch (n) { return !0; } var t, e; } function x(n) { n(); } function w$2(n) { return n; } function k() { return [!1, x]; } function M$1(n, t) { this.props = n, this.context = t; } function N$1(n, e) { function r(n) { var t = this.props.ref; return t != n.ref && t && ("function" == typeof t ? t(null) : t.current = null), e ? !e(this.props, n) || t != n.ref : E$4(this.props, n); } function u(e) { return this.shouldComponentUpdate = r, k$2(n, e); } return u.displayName = "Memo(" + (n.displayName || n.name) + ")", u.__f = u.prototype.isReactComponent = !0, u.type = n, u; } function D$1(n) { function t(t) { var e = g$1({}, t); return delete e.ref, n(e, t.ref || null); } return t.$$typeof = A$1, t.render = n, t.prototype.isReactComponent = t.__f = !0, t.displayName = "ForwardRef(" + (n.displayName || n.name) + ")", t; } function V$2(n, t, e) { return n && (n.__c && n.__c.__H && (n.__c.__H.__.forEach(function(n) { "function" == typeof n.__c && n.__c(); }), n.__c.__H = null), null != (n = g$1({}, n)).__c && (n.__c.__P === e && (n.__c.__P = t), n.__c.__e = !0, n.__c = null), n.__k = n.__k && n.__k.map(function(n) { return V$2(n, t, e); })), n; } function W(n, t, e) { return n && e && (n.__v = null, n.__k = n.__k && n.__k.map(function(n) { return W(n, t, e); }), n.__c && n.__c.__P === t && (n.__e && e.appendChild(n.__e), n.__c.__e = !0, n.__c.__P = e)), n; } function P$2() { this.__u = 0, this.o = null, this.__b = null; } function j$2(n) { var t = n.__ && n.__.__c; return t && t.__a && t.__a(n); } function z(n) { var e, r, u, o = null; function i(i) { if (e || (e = n()).then(function(n) { n && (o = n.default || n), u = !0; }, function(n) { r = n, u = !0; }), r) throw r; if (!u) throw e; return o ? k$2(o, i) : null; } return i.displayName = "Lazy", i.__f = !0, i; } function B() { this.i = null, this.l = null; } function Z$1(n) { return this.getChildContext = function() { return n.context; }, n.children; } function Y$1(n) { var e = this, r = n.h; if (e.componentWillUnmount = function() { R$1(null, e.v), e.v = null, e.h = null; }, e.h && e.h !== r && e.componentWillUnmount(), !e.v) { for (var u = e.__v; null !== u && !u.__m && null !== u.__;) u = u.__; e.h = r, e.v = { nodeType: 1, parentNode: r, childNodes: [], __k: { __m: u.__m }, contains: function() { return !0; }, namespaceURI: r.namespaceURI, insertBefore: function(n, t) { this.childNodes.push(n), e.h.insertBefore(n, t); }, removeChild: function(n) { this.childNodes.splice(this.childNodes.indexOf(n) >>> 1, 1), e.h.removeChild(n); } }; } R$1(k$2(Z$1, { context: e.context }, n.__v), e.v); } function $(n, e) { var r = k$2(Y$1, { __v: n, h: e }); return r.containerInfo = e, r; } function nn(n, t, e) { return t.__k ?? (t.textContent = ""), R$1(n, t), "function" == typeof e && e(), n ? n.__c : null; } function tn(n, t, e) { return U$3(n, t), "function" == typeof e && e(), n ? n.__c : null; } function sn(n) { return k$2.bind(null, n); } function hn(n) { return !!n && n.$$typeof === q; } function vn(n) { return hn(n) && n.type === S; } function dn(n) { return !!n && "string" == typeof n.displayName && 0 == n.displayName.indexOf("Memo("); } function mn(n) { return hn(n) ? W$1.apply(null, arguments) : n; } function pn(n) { return !!n.__k && (R$1(null, n), !0); } function yn(n) { return n && (n.base || 1 === n.nodeType && n) || null; } var I$2, T, A$1, F$1, L$3, O, U$2, H$2, q, G$1, J, K$1, Q, X, en, rn, un, on, ln, cn, fn, an, _n, bn, Sn, gn; var init_compat_module = __esmMin((() => { init_preact_module(); init_hooks_module(); init_hooks_module(); I$2 = _$1; (M$1.prototype = new C$6()).isPureReactComponent = !0, M$1.prototype.shouldComponentUpdate = function(n, t) { return E$4(this.props, n) || E$4(this.state, t); }; T = l$5.__b; l$5.__b = function(n) { n.type && n.type.__f && n.ref && (n.props.ref = n.ref, n.ref = null), T && T(n); }; A$1 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.forward_ref") || 3911; F$1 = function(n, t) { return null == n ? null : F$3(F$3(n).map(t)); }, L$3 = { map: F$1, forEach: F$1, count: function(n) { return n ? F$3(n).length : 0; }, only: function(n) { var t = F$3(n); if (1 !== t.length) throw "Children.only"; return t[0]; }, toArray: F$3 }, O = l$5.__e; l$5.__e = function(n, t, e, r) { if (n.then) { for (var u, o = t; o = o.__;) if ((u = o.__c) && u.__c) return t.__e ?? (t.__e = e.__e, t.__k = e.__k), u.__c(n, t); } O(n, t, e, r); }; U$2 = l$5.unmount; l$5.unmount = function(n) { var t = n.__c; t && (t.__z = !0), t && t.__R && t.__R(), t && 32 & n.__u && (n.type = null), U$2 && U$2(n); }, (P$2.prototype = new C$6()).__c = function(n, t) { var e = t.__c, r = this; r.o ??= [], r.o.push(e); var u = j$2(r.__v), o = !1, i = function() { o || r.__z || (o = !0, e.__R = null, u ? u(c) : c()); }; e.__R = i; var l = e.__P; e.__P = null; var c = function() { if (!--r.__u) { if (r.state.__a) { var n = r.state.__a; r.__v.__k[0] = W(n, n.__c.__P, n.__c.__O); } var t; for (r.setState({ __a: r.__b = null }); t = r.o.pop();) t.__P = l, t.forceUpdate(); } }; r.__u++ || 32 & t.__u || r.setState({ __a: r.__b = r.__v.__k[0] }), n.then(i, i); }, P$2.prototype.componentWillUnmount = function() { this.o = []; }, P$2.prototype.render = function(n, e) { if (this.__b) { if (this.__v.__k) { var r = document.createElement("div"), o = this.__v.__k[0].__c; this.__v.__k[0] = V$2(this.__b, r, o.__O = o.__P); } this.__b = null; } var i = e.__a && k$2(S, null, n.fallback); return i && (i.__u &= -33), [k$2(S, null, e.__a ? null : n.children), i]; }; H$2 = function(n, t, e) { if (++e[1] === e[0] && n.l.delete(t), n.props.revealOrder && ("t" !== n.props.revealOrder[0] || !n.l.size)) for (e = n.i; e;) { for (; e.length > 3;) e.pop()(); if (e[1] < e[0]) break; n.i = e = e[2]; } }; (B.prototype = new C$6()).__a = function(n) { var t = this, e = j$2(t.__v), r = t.l.get(n); return r[0]++, function(u) { var o = function() { t.props.revealOrder ? (r.push(u), H$2(t, n, r)) : u(); }; e ? e(o) : o(); }; }, B.prototype.render = function(n) { this.i = null, this.l = new Map(); var t = F$3(n.children); n.revealOrder && "b" === n.revealOrder[0] && t.reverse(); for (var e = t.length; e--;) this.l.set(t[e], this.i = [ 1, 0, this.i ]); return n.children; }, B.prototype.componentDidUpdate = B.prototype.componentDidMount = function() { var n = this; this.l.forEach(function(t, e) { H$2(n, e, t); }); }; q = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, G$1 = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, J = /^on(Ani|Tra|Tou|BeforeInp|Compo)/, K$1 = /[A-Z0-9]/g, Q = "undefined" != typeof document, X = function(n) { return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/ : /fil|che|ra/).test(n); }; C$6.prototype.isReactComponent = !0, [ "componentWillMount", "componentWillReceiveProps", "componentWillUpdate" ].forEach(function(t) { Object.defineProperty(C$6.prototype, t, { configurable: !0, get: function() { return this["UNSAFE_" + t]; }, set: function(n) { Object.defineProperty(this, t, { configurable: !0, writable: !0, value: n }); } }); }); en = l$5.event; l$5.event = function(n) { return en && (n = en(n)), n.persist = function() {}, n.isPropagationStopped = function() { return this.cancelBubble; }, n.isDefaultPrevented = function() { return this.defaultPrevented; }, n.nativeEvent = n; }; un = { configurable: !0, get: function() { return this.class; } }, on = l$5.vnode; l$5.vnode = function(n) { "string" == typeof n.type && function(n) { var t = n.props, e = n.type, u = {}, o = -1 == e.indexOf("-"); for (var i in t) { var l = t[i]; if (!("value" === i && "defaultValue" in t && null == l || Q && "children" === i && "noscript" === e || "class" === i || "className" === i)) { var c = i.toLowerCase(); "defaultValue" === i && "value" in t && null == t.value ? i = "value" : "download" === i && !0 === l ? l = "" : "translate" === c && "no" === l ? l = !1 : "o" === c[0] && "n" === c[1] ? "ondoubleclick" === c ? i = "ondblclick" : "onchange" !== c || "input" !== e && "textarea" !== e || X(t.type) ? "onfocus" === c ? i = "onfocusin" : "onblur" === c ? i = "onfocusout" : J.test(i) && (i = c) : c = i = "oninput" : o && G$1.test(i) ? i = i.replace(K$1, "-$&").toLowerCase() : null === l && (l = void 0), "oninput" === c && u[i = c] && (i = "oninputCapture"), u[i] = l; } } "select" == e && (u.multiple && Array.isArray(u.value) && (u.value = F$3(t.children).forEach(function(n) { n.props.selected = -1 != u.value.indexOf(n.props.value); })), null != u.defaultValue && (u.value = F$3(t.children).forEach(function(n) { n.props.selected = u.multiple ? -1 != u.defaultValue.indexOf(n.props.value) : u.defaultValue == n.props.value; }))), t.class && !t.className ? (u.class = t.class, Object.defineProperty(u, "className", un)) : t.className && (u.class = u.className = t.className), n.props = u; }(n), n.$$typeof = q, on && on(n); }; ln = l$5.__r; l$5.__r = function(n) { ln && ln(n), rn = n.__c; }; cn = l$5.diffed; l$5.diffed = function(n) { cn && cn(n); var t = n.props, e = n.__e; null != e && "textarea" === n.type && "value" in t && t.value !== e.value && (e.value = null == t.value ? "" : t.value), rn = null; }; fn = { ReactCurrentDispatcher: { current: { readContext: function(n) { return rn.__n[n.__c].props.value; }, useCallback: q$1, useContext: x$1, useDebugValue: P$3, useDeferredValue: w$2, useEffect: y$1, useId: g$2, useImperativeHandle: F$2, useInsertionEffect: I$2, useLayoutEffect: _$1, useMemo: T$1, useReducer: h$1, useRef: A$2, useState: d$1, useSyncExternalStore: C$4, useTransition: k } } }, an = "18.3.1"; _n = function(n, t) { return n(t); }, bn = function(n, t) { var r = l$5.debounceRendering; l$5.debounceRendering = function(n) { return n(); }; var u = n(t); return l$5.debounceRendering = r, u; }, Sn = hn, gn = { useState: d$1, useId: g$2, useReducer: h$1, useEffect: y$1, useLayoutEffect: _$1, useInsertionEffect: I$2, useTransition: k, useDeferredValue: w$2, useSyncExternalStore: C$4, startTransition: x, useRef: A$2, useImperativeHandle: F$2, useMemo: T$1, useCallback: q$1, useContext: x$1, useDebugValue: P$3, version: "18.3.1", Children: L$3, render: nn, hydrate: tn, unmountComponentAtNode: pn, createPortal: $, createElement: k$2, createContext: X$1, createFactory: sn, cloneElement: mn, createRef: M$2, Fragment: S, isValidElement: hn, isElement: Sn, isFragment: vn, isMemo: dn, findDOMNode: yn, Component: C$6, PureComponent: M$1, memo: N$1, forwardRef: D$1, flushSync: bn, unstable_batchedUpdates: _n, StrictMode: S, Suspense: P$2, SuspenseList: B, lazy: z, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: fn }; })); init_compat_module(); typeof window !== "undefined" && window.document && window.document.createElement; function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) { return function handleEvent(event) { originalEventHandler?.(event); if (checkForDefaultPrevented === false || !event.defaultPrevented) return ourEventHandler?.(event); }; } function setRef$1(ref, value) { if (typeof ref === "function") return ref(value); else if (ref !== null && ref !== void 0) ref.current = value; } function composeRefs(...refs) { return (node) => { let hasCleanup = false; const cleanups = refs.map((ref) => { const cleanup = setRef$1(ref, node); if (!hasCleanup && typeof cleanup == "function") hasCleanup = true; return cleanup; }); if (hasCleanup) return () => { for (let i = 0; i < cleanups.length; i++) { const cleanup = cleanups[i]; if (typeof cleanup == "function") cleanup(); else setRef$1(refs[i], null); } }; }; } function useComposedRefs(...refs) { return q$1(composeRefs(...refs), refs); } init_preact_module(); var f$3 = 0; Array.isArray; function u$3(e, t, n, o, i, u) { t || (t = {}); var a, c, p = t; if ("ref" in p) for (c in p = {}, t) "ref" == c ? a = t[c] : p[c] = t[c]; var l = { type: e, props: p, key: n, ref: a, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --f$3, __i: -1, __u: 0, __source: i, __self: u }; if ("function" == typeof e && (a = e.defaultProps)) for (c in a) void 0 === p[c] && (p[c] = a[c]); return l$5.vnode && l$5.vnode(l), l; } init_compat_module(); function createContextScope(scopeName, createContextScopeDeps = []) { let defaultContexts = []; function createContext3(rootComponentName, defaultContext) { const BaseContext = X$1(defaultContext); BaseContext.displayName = rootComponentName + "Context"; const index = defaultContexts.length; defaultContexts = [...defaultContexts, defaultContext]; const Provider = (props) => { const { scope, children, ...context } = props; const Context = scope?.[scopeName]?.[index] || BaseContext; const value = T$1(() => context, Object.values(context)); return u$3(Context.Provider, { value, children }); }; Provider.displayName = rootComponentName + "Provider"; function useContext2(consumerName, scope) { const context = x$1(scope?.[scopeName]?.[index] || BaseContext); if (context) return context; if (defaultContext !== void 0) return defaultContext; throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); } return [Provider, useContext2]; } const createScope = () => { const scopeContexts = defaultContexts.map((defaultContext) => { return X$1(defaultContext); }); return function useScope(scope) { const contexts = scope?.[scopeName] || scopeContexts; return T$1(() => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }), [scope, contexts]); }; }; createScope.scopeName = scopeName; return [createContext3, composeContextScopes(createScope, ...createContextScopeDeps)]; } function composeContextScopes(...scopes) { const baseScope = scopes[0]; if (scopes.length === 1) return baseScope; const createScope = () => { const scopeHooks = scopes.map((createScope2) => ({ useScope: createScope2(), scopeName: createScope2.scopeName })); return function useComposedScopes(overrideScopes) { const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => { const currentScope = useScope(overrideScopes)[`__scope${scopeName}`]; return { ...nextScopes2, ...currentScope }; }, {}); return T$1(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]); }; }; createScope.scopeName = baseScope.scopeName; return createScope; } init_compat_module(); var useLayoutEffect2 = globalThis?.document ? _$1 : () => {}; init_compat_module(); var useReactId = compat_module_exports[" useId ".trim().toString()] || (() => void 0); var count$1 = 0; function useId(deterministicId) { const [id, setId] = d$1(useReactId()); useLayoutEffect2(() => { if (!deterministicId) setId((reactId) => reactId ?? String(count$1++)); }, [deterministicId]); return deterministicId || (id ? `radix-${id}` : ""); } init_compat_module(); var useInsertionEffect = compat_module_exports[" useInsertionEffect ".trim().toString()] || useLayoutEffect2; function useControllableState({ prop, defaultProp, onChange = () => {}, caller }) { const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({ defaultProp, onChange }); const isControlled = prop !== void 0; const value = isControlled ? prop : uncontrolledProp; { const isControlledRef = A$2(prop !== void 0); y$1(() => { const wasControlled = isControlledRef.current; if (wasControlled !== isControlled) console.warn(`${caller} is changing from ${wasControlled ? "controlled" : "uncontrolled"} to ${isControlled ? "controlled" : "uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`); isControlledRef.current = isControlled; }, [isControlled, caller]); } return [value, q$1((nextValue) => { if (isControlled) { const value2 = isFunction(nextValue) ? nextValue(prop) : nextValue; if (value2 !== prop) onChangeRef.current?.(value2); } else setUncontrolledProp(nextValue); }, [ isControlled, prop, setUncontrolledProp, onChangeRef ])]; } function useUncontrolledState({ defaultProp, onChange }) { const [value, setValue] = d$1(defaultProp); const prevValueRef = A$2(value); const onChangeRef = A$2(onChange); useInsertionEffect(() => { onChangeRef.current = onChange; }, [onChange]); y$1(() => { if (prevValueRef.current !== value) { onChangeRef.current?.(value); prevValueRef.current = value; } }, [value, prevValueRef]); return [ value, setValue, onChangeRef ]; } function isFunction(value) { return typeof value === "function"; } init_compat_module(); function createSlot(ownerName) { const Slot2 = D$1((props, forwardedRef) => { let { children, ...slotProps } = props; let slottableElement = null; let hasSlottable = false; const newChildren = []; if (isLazyComponent(children) && typeof use$1 === "function") children = use$1(children._payload); L$3.forEach(children, (maybeSlottable) => { if (isSlottable(maybeSlottable)) { hasSlottable = true; const slottable = maybeSlottable; let child = "child" in slottable.props ? slottable.props.child : slottable.props.children; if (isLazyComponent(child) && typeof use$1 === "function") child = use$1(child._payload); slottableElement = getSlottableElementFromSlottable(slottable, child); newChildren.push(slottableElement?.props?.children); } else newChildren.push(maybeSlottable); }); if (slottableElement) slottableElement = mn(slottableElement, void 0, newChildren); else if (!hasSlottable && L$3.count(children) === 1 && hn(children)) slottableElement = children; const slottableElementRef = slottableElement ? getElementRef$1(slottableElement) : void 0; const composedRef = useComposedRefs(forwardedRef, slottableElementRef); if (!slottableElement) { if (children || children === 0) throw new Error(hasSlottable ? createSlottableError(ownerName) : createSlotError(ownerName)); return children; } const mergedProps = mergeProps(slotProps, slottableElement.props ?? {}); if (slottableElement.type !== S) mergedProps.ref = forwardedRef ? composedRef : slottableElementRef; return mn(slottableElement, mergedProps); }); Slot2.displayName = `${ownerName}.Slot`; return Slot2; } var SLOTTABLE_IDENTIFIER = Symbol.for("radix.slottable"); var getSlottableElementFromSlottable = (slottable, child) => { if ("child" in slottable.props) { const child2 = slottable.props.child; if (!hn(child2)) return null; return mn(child2, void 0, slottable.props.children(child2.props.children)); } return hn(child) ? child : null; }; function mergeProps(slotProps, childProps) { const overrideProps = { ...childProps }; for (const propName in childProps) { const slotPropValue = slotProps[propName]; const childPropValue = childProps[propName]; if (/^on[A-Z]/.test(propName)) { if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => { const result = childPropValue(...args); slotPropValue(...args); return result; }; else if (slotPropValue) overrideProps[propName] = slotPropValue; } else if (propName === "style") overrideProps[propName] = { ...slotPropValue, ...childPropValue }; else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" "); } return { ...slotProps, ...overrideProps }; } function getElementRef$1(element) { let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get; let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) return element.ref; getter = Object.getOwnPropertyDescriptor(element, "ref")?.get; mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) return element.props.ref; return element.props.ref || element.ref; } function isSlottable(child) { return hn(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER; } var REACT_LAZY_TYPE = Symbol.for("react.lazy"); function isLazyComponent(element) { return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE && "_payload" in element && isPromiseLike(element._payload); } function isPromiseLike(value) { return typeof value === "object" && value !== null && "then" in value; } var createSlotError = (ownerName) => { return `${ownerName} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`; }; var createSlottableError = (ownerName) => { return `${ownerName} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`; }; var use$1 = compat_module_exports[" use ".trim().toString()]; init_compat_module(); var Primitive = [ "a", "button", "div", "form", "h2", "h3", "img", "input", "label", "li", "nav", "ol", "p", "select", "span", "svg", "ul" ].reduce((primitive, node) => { const Slot = createSlot(`Primitive.${node}`); const Node = D$1((props, forwardedRef) => { const { asChild, ...primitiveProps } = props; const Comp = asChild ? Slot : node; if (typeof window !== "undefined") window[Symbol.for("radix-ui")] = true; return u$3(Comp, { ...primitiveProps, ref: forwardedRef }); }); Node.displayName = `Primitive.${node}`; return { ...primitive, [node]: Node }; }, {}); function dispatchDiscreteCustomEvent(target, event) { if (target) bn(() => target.dispatchEvent(event)); } init_compat_module(); function useCallbackRef$1(callback) { const callbackRef = A$2(callback); y$1(() => { callbackRef.current = callback; }); return T$1(() => ((...args) => callbackRef.current?.(...args)), []); } init_compat_module(); function useEscapeKeydown(onEscapeKeyDownProp, ownerDocument = globalThis?.document) { const onEscapeKeyDown = useCallbackRef$1(onEscapeKeyDownProp); y$1(() => { const handleKeyDown = (event) => { if (event.key === "Escape") onEscapeKeyDown(event); }; ownerDocument.addEventListener("keydown", handleKeyDown, { capture: true }); return () => ownerDocument.removeEventListener("keydown", handleKeyDown, { capture: true }); }, [onEscapeKeyDown, ownerDocument]); } init_compat_module(); var DISMISSABLE_LAYER_NAME = "DismissableLayer"; var CONTEXT_UPDATE = "dismissableLayer.update"; var POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside"; var FOCUS_OUTSIDE = "dismissableLayer.focusOutside"; var originalBodyPointerEvents; var DismissableLayerContext = X$1({ layers: new Set(), layersWithOutsidePointerEventsDisabled: new Set(), branches: new Set(), dismissableSurfaces: new Set() }); var DismissableLayer = D$1((props, forwardedRef) => { const { disableOutsidePointerEvents = false, deferPointerDownOutside = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props; const context = x$1(DismissableLayerContext); const [node, setNode] = d$1(null); const ownerDocument = node?.ownerDocument ?? globalThis?.document; const [, force] = d$1({}); const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2)); const layers = Array.from(context.layers); const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); const index = node ? layers.indexOf(node) : -1; const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex; const isDeferredPointerDownOutsideRef = A$2(false); const pointerDownOutside = usePointerDownOutside((event) => { const target = event.target; if (!(target instanceof Node)) return; const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target)); if (!isPointerEventsEnabled || isPointerDownOnBranch) return; onPointerDownOutside?.(event); onInteractOutside?.(event); if (!event.defaultPrevented) onDismiss?.(); }, { ownerDocument, deferPointerDownOutside, isDeferredPointerDownOutsideRef, dismissableSurfaces: context.dismissableSurfaces }); const focusOutside = useFocusOutside((event) => { if (deferPointerDownOutside && isDeferredPointerDownOutsideRef.current) return; const target = event.target; if ([...context.branches].some((branch) => branch.contains(target))) return; onFocusOutside?.(event); onInteractOutside?.(event); if (!event.defaultPrevented) onDismiss?.(); }, ownerDocument); useEscapeKeydown((event) => { if (!(index === context.layers.size - 1)) return; onEscapeKeyDown?.(event); if (!event.defaultPrevented && onDismiss) { event.preventDefault(); onDismiss(); } }, ownerDocument); y$1(() => { if (!node) return; if (disableOutsidePointerEvents) { if (context.layersWithOutsidePointerEventsDisabled.size === 0) { originalBodyPointerEvents = ownerDocument.body.style.pointerEvents; ownerDocument.body.style.pointerEvents = "none"; } context.layersWithOutsidePointerEventsDisabled.add(node); } context.layers.add(node); dispatchUpdate(); return () => { if (disableOutsidePointerEvents) { context.layersWithOutsidePointerEventsDisabled.delete(node); if (context.layersWithOutsidePointerEventsDisabled.size === 0) ownerDocument.body.style.pointerEvents = originalBodyPointerEvents; } }; }, [ node, ownerDocument, disableOutsidePointerEvents, context ]); y$1(() => { return () => { if (!node) return; context.layers.delete(node); context.layersWithOutsidePointerEventsDisabled.delete(node); dispatchUpdate(); }; }, [node, context]); y$1(() => { const handleUpdate = () => force({}); document.addEventListener(CONTEXT_UPDATE, handleUpdate); return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate); }, []); return u$3(Primitive.div, { ...layerProps, ref: composedRefs, style: { pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0, ...props.style }, onFocusCapture: composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture), onBlurCapture: composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture), onPointerDownCapture: composeEventHandlers(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture) }); }); DismissableLayer.displayName = DISMISSABLE_LAYER_NAME; var BRANCH_NAME = "DismissableLayerBranch"; var DismissableLayerBranch = D$1((props, forwardedRef) => { const context = x$1(DismissableLayerContext); const ref = A$2(null); const composedRefs = useComposedRefs(forwardedRef, ref); y$1(() => { const node = ref.current; if (node) { context.branches.add(node); return () => { context.branches.delete(node); }; } }, [context.branches]); return u$3(Primitive.div, { ...props, ref: composedRefs }); }); DismissableLayerBranch.displayName = BRANCH_NAME; function useDismissableLayerSurface() { const context = x$1(DismissableLayerContext); const [node, setNode] = d$1(null); y$1(() => { if (!node) return; context.dismissableSurfaces.add(node); return () => { context.dismissableSurfaces.delete(node); }; }, [node, context.dismissableSurfaces]); return setNode; } function usePointerDownOutside(onPointerDownOutside, args) { const { ownerDocument = globalThis?.document, deferPointerDownOutside = false, isDeferredPointerDownOutsideRef, dismissableSurfaces } = args; const handlePointerDownOutside = useCallbackRef$1(onPointerDownOutside); const isPointerInsideReactTreeRef = A$2(false); const isPointerDownOutsideRef = A$2(false); const interceptedOutsideInteractionEventsRef = A$2(new Map()); const handleClickRef = A$2(() => {}); y$1(() => { function resetOutsideInteraction() { isPointerDownOutsideRef.current = false; isDeferredPointerDownOutsideRef.current = false; interceptedOutsideInteractionEventsRef.current.clear(); } function isOutsideInteractionIntercepted() { return Array.from(interceptedOutsideInteractionEventsRef.current.values()).some(Boolean); } function handleInteractionCapture(event) { if (!isPointerDownOutsideRef.current) return; const target = event.target; if (!(target instanceof Node && [...dismissableSurfaces].some((surface) => surface.contains(target)))) interceptedOutsideInteractionEventsRef.current.set(event.type, true); if (event.type === "click") window.setTimeout(() => { if (isPointerDownOutsideRef.current) handleClickRef.current(); }, 0); } function handleInteractionBubble(event) { if (isPointerDownOutsideRef.current) interceptedOutsideInteractionEventsRef.current.set(event.type, false); } const handlePointerDown = (event) => { if (event.target && !isPointerInsideReactTreeRef.current) { let handleAndDispatchPointerDownOutsideEvent2 = function() { ownerDocument.removeEventListener("click", handleClickRef.current); const wasOutsideInteractionIntercepted = isOutsideInteractionIntercepted(); resetOutsideInteraction(); if (!wasOutsideInteractionIntercepted) handleAndDispatchCustomEvent(POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { discrete: true }); }; const eventDetail = { originalEvent: event }; isPointerDownOutsideRef.current = true; isDeferredPointerDownOutsideRef.current = deferPointerDownOutside && event.button === 0; interceptedOutsideInteractionEventsRef.current.clear(); if (!deferPointerDownOutside || event.button !== 0) handleAndDispatchPointerDownOutsideEvent2(); else { ownerDocument.removeEventListener("click", handleClickRef.current); handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2; ownerDocument.addEventListener("click", handleClickRef.current, { once: true }); } } else { ownerDocument.removeEventListener("click", handleClickRef.current); resetOutsideInteraction(); } isPointerInsideReactTreeRef.current = false; }; const outsideInteractionEvents = [ "pointerup", "mousedown", "mouseup", "touchstart", "touchend", "click" ]; for (const eventName of outsideInteractionEvents) { ownerDocument.addEventListener(eventName, handleInteractionCapture, true); ownerDocument.addEventListener(eventName, handleInteractionBubble); } const timerId = window.setTimeout(() => { ownerDocument.addEventListener("pointerdown", handlePointerDown); }, 0); return () => { window.clearTimeout(timerId); ownerDocument.removeEventListener("pointerdown", handlePointerDown); ownerDocument.removeEventListener("click", handleClickRef.current); for (const eventName of outsideInteractionEvents) { ownerDocument.removeEventListener(eventName, handleInteractionCapture, true); ownerDocument.removeEventListener(eventName, handleInteractionBubble); } }; }, [ ownerDocument, handlePointerDownOutside, deferPointerDownOutside, isDeferredPointerDownOutsideRef, dismissableSurfaces ]); return { onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true }; } function useFocusOutside(onFocusOutside, ownerDocument = globalThis?.document) { const handleFocusOutside = useCallbackRef$1(onFocusOutside); const isFocusInsideReactTreeRef = A$2(false); y$1(() => { const handleFocus = (event) => { if (event.target && !isFocusInsideReactTreeRef.current) handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, { originalEvent: event }, { discrete: false }); }; ownerDocument.addEventListener("focusin", handleFocus); return () => ownerDocument.removeEventListener("focusin", handleFocus); }, [ownerDocument, handleFocusOutside]); return { onFocusCapture: () => isFocusInsideReactTreeRef.current = true, onBlurCapture: () => isFocusInsideReactTreeRef.current = false }; } function dispatchUpdate() { const event = new CustomEvent(CONTEXT_UPDATE); document.dispatchEvent(event); } function handleAndDispatchCustomEvent(name, handler, detail, { discrete }) { const target = detail.originalEvent.target; const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail }); if (handler) target.addEventListener(name, handler, { once: true }); if (discrete) dispatchDiscreteCustomEvent(target, event); else target.dispatchEvent(event); } init_compat_module(); var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount"; var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount"; var EVENT_OPTIONS = { bubbles: false, cancelable: true }; var FOCUS_SCOPE_NAME = "FocusScope"; var FocusScope = D$1((props, forwardedRef) => { const { loop = false, trapped = false, onMountAutoFocus: onMountAutoFocusProp, onUnmountAutoFocus: onUnmountAutoFocusProp, ...scopeProps } = props; const [container, setContainer] = d$1(null); const onMountAutoFocus = useCallbackRef$1(onMountAutoFocusProp); const onUnmountAutoFocus = useCallbackRef$1(onUnmountAutoFocusProp); const lastFocusedElementRef = A$2(null); const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node)); const focusScope = A$2({ paused: false, pause() { this.paused = true; }, resume() { this.paused = false; } }).current; y$1(() => { if (trapped) { let handleFocusIn2 = function(event) { if (focusScope.paused || !container) return; const target = event.target; if (container.contains(target)) lastFocusedElementRef.current = target; else focus(lastFocusedElementRef.current, { select: true }); }, handleFocusOut2 = function(event) { if (focusScope.paused || !container) return; const relatedTarget = event.relatedTarget; if (relatedTarget === null) return; if (!container.contains(relatedTarget)) focus(lastFocusedElementRef.current, { select: true }); }, handleMutations2 = function(mutations) { if (document.activeElement !== document.body) return; for (const mutation of mutations) if (mutation.removedNodes.length > 0) focus(container); }; document.addEventListener("focusin", handleFocusIn2); document.addEventListener("focusout", handleFocusOut2); const mutationObserver = new MutationObserver(handleMutations2); if (container) mutationObserver.observe(container, { childList: true, subtree: true }); return () => { document.removeEventListener("focusin", handleFocusIn2); document.removeEventListener("focusout", handleFocusOut2); mutationObserver.disconnect(); }; } }, [ trapped, container, focusScope.paused ]); y$1(() => { if (container) { focusScopesStack.add(focusScope); const previouslyFocusedElement = document.activeElement; if (!container.contains(previouslyFocusedElement)) { const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus); container.dispatchEvent(mountEvent); if (!mountEvent.defaultPrevented) { focusFirst(removeLinks(getTabbableCandidates(container)), { select: true }); if (document.activeElement === previouslyFocusedElement) focus(container); } } return () => { container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus); setTimeout(() => { const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); container.dispatchEvent(unmountEvent); if (!unmountEvent.defaultPrevented) focus(previouslyFocusedElement ?? document.body, { select: true }); container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); focusScopesStack.remove(focusScope); }, 0); }; } }, [ container, onMountAutoFocus, onUnmountAutoFocus, focusScope ]); const handleKeyDown = q$1((event) => { if (!loop && !trapped) return; if (focusScope.paused) return; const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey; const focusedElement = document.activeElement; if (isTabKey && focusedElement) { const container2 = event.currentTarget; const [first, last] = getTabbableEdges(container2); if (!(first && last)) { if (focusedElement === container2) event.preventDefault(); } else if (!event.shiftKey && focusedElement === last) { event.preventDefault(); if (loop) focus(first, { select: true }); } else if (event.shiftKey && focusedElement === first) { event.preventDefault(); if (loop) focus(last, { select: true }); } } }, [ loop, trapped, focusScope.paused ]); return u$3(Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown }); }); FocusScope.displayName = FOCUS_SCOPE_NAME; function focusFirst(candidates, { select = false } = {}) { const previouslyFocusedElement = document.activeElement; for (const candidate of candidates) { focus(candidate, { select }); if (document.activeElement !== previouslyFocusedElement) return; } } function getTabbableEdges(container) { const candidates = getTabbableCandidates(container); return [findVisible(candidates, container), findVisible(candidates.reverse(), container)]; } function getTabbableCandidates(container) { const nodes = []; const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { acceptNode: (node) => { const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden"; if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP; return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } }); while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } function findVisible(elements, container) { for (const element of elements) if (!isHidden(element, { upTo: container })) return element; } function isHidden(node, { upTo }) { if (getComputedStyle(node).visibility === "hidden") return true; while (node) { if (upTo !== void 0 && node === upTo) return false; if (getComputedStyle(node).display === "none") return true; node = node.parentElement; } return false; } function isSelectableInput(element) { return element instanceof HTMLInputElement && "select" in element; } function focus(element, { select = false } = {}) { if (element && element.focus) { const previouslyFocusedElement = document.activeElement; element.focus({ preventScroll: true }); if (element !== previouslyFocusedElement && isSelectableInput(element) && select) element.select(); } } var focusScopesStack = createFocusScopesStack(); function createFocusScopesStack() { let stack = []; return { add(focusScope) { const activeFocusScope = stack[0]; if (focusScope !== activeFocusScope) activeFocusScope?.pause(); stack = arrayRemove(stack, focusScope); stack.unshift(focusScope); }, remove(focusScope) { stack = arrayRemove(stack, focusScope); stack[0]?.resume(); } }; } function arrayRemove(array, item) { const updatedArray = [...array]; const index = updatedArray.indexOf(item); if (index !== -1) updatedArray.splice(index, 1); return updatedArray; } function removeLinks(items) { return items.filter((item) => item.tagName !== "A"); } init_compat_module(); var PORTAL_NAME$2 = "Portal"; var Portal$1 = D$1((props, forwardedRef) => { const { container: containerProp, ...portalProps } = props; const [mounted, setMounted] = d$1(false); useLayoutEffect2(() => setMounted(true), []); const container = containerProp || mounted && globalThis?.document?.body; return container ? $(u$3(Primitive.div, { ...portalProps, ref: forwardedRef }), container) : null; }); Portal$1.displayName = PORTAL_NAME$2; init_compat_module(); function useStateMachine(initialState, machine) { return h$1((state, event) => { return machine[state][event] ?? state; }, initialState); } var Presence = (props) => { const { present, children } = props; const presence = usePresence(present); const child = typeof children === "function" ? children({ present: presence.isPresent }) : L$3.only(children); const ref = useStableComposedRefs(presence.ref, getElementRef(child)); return typeof children === "function" || presence.isPresent ? mn(child, { ref }) : null; }; Presence.displayName = "Presence"; function usePresence(present) { const [node, setNode] = d$1(); const stylesRef = A$2(null); const prevPresentRef = A$2(present); const prevAnimationNameRef = A$2("none"); const [state, send] = useStateMachine(present ? "mounted" : "unmounted", { mounted: { UNMOUNT: "unmounted", ANIMATION_OUT: "unmountSuspended" }, unmountSuspended: { MOUNT: "mounted", ANIMATION_END: "unmounted" }, unmounted: { MOUNT: "mounted" } }); y$1(() => { const currentAnimationName = getAnimationName(stylesRef.current); prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none"; }, [state]); useLayoutEffect2(() => { const styles = stylesRef.current; const wasPresent = prevPresentRef.current; if (wasPresent !== present) { const prevAnimationName = prevAnimationNameRef.current; const currentAnimationName = getAnimationName(styles); if (present) send("MOUNT"); else if (currentAnimationName === "none" || styles?.display === "none") send("UNMOUNT"); else if (wasPresent && prevAnimationName !== currentAnimationName) send("ANIMATION_OUT"); else send("UNMOUNT"); prevPresentRef.current = present; } }, [present, send]); useLayoutEffect2(() => { if (node) { let timeoutId; const ownerWindow = node.ownerDocument.defaultView ?? window; const handleAnimationEnd = (event) => { const isCurrentAnimation = getAnimationName(stylesRef.current).includes(CSS.escape(event.animationName)); if (event.target === node && isCurrentAnimation) { send("ANIMATION_END"); if (!prevPresentRef.current) { const currentFillMode = node.style.animationFillMode; node.style.animationFillMode = "forwards"; timeoutId = ownerWindow.setTimeout(() => { if (node.style.animationFillMode === "forwards") node.style.animationFillMode = currentFillMode; }); } } }; const handleAnimationStart = (event) => { if (event.target === node) prevAnimationNameRef.current = getAnimationName(stylesRef.current); }; node.addEventListener("animationstart", handleAnimationStart); node.addEventListener("animationcancel", handleAnimationEnd); node.addEventListener("animationend", handleAnimationEnd); return () => { ownerWindow.clearTimeout(timeoutId); node.removeEventListener("animationstart", handleAnimationStart); node.removeEventListener("animationcancel", handleAnimationEnd); node.removeEventListener("animationend", handleAnimationEnd); }; } else send("ANIMATION_END"); }, [node, send]); return { isPresent: ["mounted", "unmountSuspended"].includes(state), ref: q$1((node2) => { stylesRef.current = node2 ? getComputedStyle(node2) : null; setNode(node2); }, []) }; } function setRef(ref, value) { if (typeof ref === "function") return ref(value); else if (ref !== null && ref !== void 0) ref.current = value; } function useStableComposedRefs(...refs) { const refsRef = A$2(refs); refsRef.current = refs; return q$1((node) => { const currentRefs = refsRef.current; let hasCleanup = false; const cleanups = currentRefs.map((ref) => { const cleanup = setRef(ref, node); if (!hasCleanup && typeof cleanup === "function") hasCleanup = true; return cleanup; }); if (hasCleanup) return () => { for (let i = 0; i < cleanups.length; i++) { const cleanup = cleanups[i]; if (typeof cleanup === "function") cleanup(); else setRef(currentRefs[i], null); } }; }, []); } function getAnimationName(styles) { return styles?.animationName || "none"; } function getElementRef(element) { let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get; let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) return element.ref; getter = Object.getOwnPropertyDescriptor(element, "ref")?.get; mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) return element.props.ref; return element.props.ref || element.ref; } init_compat_module(); var count = 0; var guards = null; function useFocusGuards() { y$1(() => { if (!guards) guards = { start: createFocusGuard(), end: createFocusGuard() }; const { start, end } = guards; if (document.body.firstElementChild !== start) document.body.insertAdjacentElement("afterbegin", start); if (document.body.lastElementChild !== end) document.body.insertAdjacentElement("beforeend", end); count++; return () => { if (count === 1) { guards?.start.remove(); guards?.end.remove(); guards = null; } count = Math.max(0, count - 1); }; }, []); } function createFocusGuard() { const element = document.createElement("span"); element.setAttribute("data-radix-focus-guard", ""); element.tabIndex = 0; element.style.outline = "none"; element.style.opacity = "0"; element.style.position = "fixed"; element.style.pointerEvents = "none"; return element; } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) { for (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } var zeroRightClassName = "right-scroll-bar-position"; var fullWidthClassName = "width-before-scroll-bar"; var noScrollbarsClassName = "with-scroll-bars-hidden"; var removedBarSizeVariable = "--removed-body-scroll-bar-size"; function assignRef(ref, value) { if (typeof ref === "function") ref(value); else if (ref) ref.current = value; return ref; } init_compat_module(); function useCallbackRef(initialValue, callback) { var ref = d$1(function() { return { value: initialValue, callback, facade: { get current() { return ref.value; }, set current(value) { var last = ref.value; if (last !== value) { ref.value = value; ref.callback(value, last); } } } }; })[0]; ref.callback = callback; return ref.facade; } init_compat_module(); var useIsomorphicLayoutEffect = typeof window !== "undefined" ? _$1 : y$1; var currentValues = new WeakMap(); function useMergeRefs(refs, defaultValue) { var callbackRef = useCallbackRef(defaultValue || null, function(newValue) { return refs.forEach(function(ref) { return assignRef(ref, newValue); }); }); useIsomorphicLayoutEffect(function() { var oldValue = currentValues.get(callbackRef); if (oldValue) { var prevRefs_1 = new Set(oldValue); var nextRefs_1 = new Set(refs); var current_1 = callbackRef.current; prevRefs_1.forEach(function(ref) { if (!nextRefs_1.has(ref)) assignRef(ref, null); }); nextRefs_1.forEach(function(ref) { if (!prevRefs_1.has(ref)) assignRef(ref, current_1); }); } currentValues.set(callbackRef, refs); }, [refs]); return callbackRef; } function ItoI(a) { return a; } function innerCreateMedium(defaults, middleware) { if (middleware === void 0) middleware = ItoI; var buffer = []; var assigned = false; return { read: function() { if (assigned) throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`."); if (buffer.length) return buffer[buffer.length - 1]; return defaults; }, useMedium: function(data) { var item = middleware(data, assigned); buffer.push(item); return function() { buffer = buffer.filter(function(x) { return x !== item; }); }; }, assignSyncMedium: function(cb) { assigned = true; while (buffer.length) { var cbs = buffer; buffer = []; cbs.forEach(cb); } buffer = { push: function(x) { return cb(x); }, filter: function() { return buffer; } }; }, assignMedium: function(cb) { assigned = true; var pendingQueue = []; if (buffer.length) { var cbs = buffer; buffer = []; cbs.forEach(cb); pendingQueue = buffer; } var executeQueue = function() { var cbs = pendingQueue; pendingQueue = []; cbs.forEach(cb); }; var cycle = function() { return Promise.resolve().then(executeQueue); }; cycle(); buffer = { push: function(x) { pendingQueue.push(x); cycle(); }, filter: function(filter) { pendingQueue = pendingQueue.filter(filter); return buffer; } }; } }; } function createSidecarMedium(options) { if (options === void 0) options = {}; var medium = innerCreateMedium(null); medium.options = __assign({ async: true, ssr: false }, options); return medium; } init_compat_module(); var SideCar = function(_a) { var sideCar = _a.sideCar, rest = __rest(_a, ["sideCar"]); if (!sideCar) throw new Error("Sidecar: please provide `sideCar` property to import the right car"); var Target = sideCar.read(); if (!Target) throw new Error("Sidecar medium not found"); return k$2(Target, __assign({}, rest)); }; SideCar.isSideCarExport = true; function exportSidecar(medium, exported) { medium.useMedium(exported); return SideCar; } var effectCar = createSidecarMedium(); init_compat_module(); var nothing = function() {}; var RemoveScroll = D$1(function(props, parentRef) { var ref = A$2(null); var _a = d$1({ onScrollCapture: nothing, onWheelCapture: nothing, onTouchMoveCapture: nothing }), callbacks = _a[0], setCallbacks = _a[1]; var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noRelative = props.noRelative, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest(props, [ "forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noRelative", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode" ]); var SideCar = sideCar; var containerRef = useMergeRefs([ref, parentRef]); var containerProps = __assign(__assign({}, rest), callbacks); return k$2(S, null, enabled && k$2(SideCar, { sideCar: effectCar, removeScrollBar, shards, noRelative, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode }), forwardProps ? mn(L$3.only(children), __assign(__assign({}, containerProps), { ref: containerRef })) : k$2(Container, __assign({}, containerProps, { className, ref: containerRef }), children)); }); RemoveScroll.defaultProps = { enabled: true, removeScrollBar: true, inert: false }; RemoveScroll.classNames = { fullWidth: fullWidthClassName, zeroRight: zeroRightClassName }; var currentNonce; var getNonce = function() { if (currentNonce) return currentNonce; if (typeof __webpack_nonce__ !== "undefined") return __webpack_nonce__; }; function makeStyleTag() { if (!document) return null; var tag = document.createElement("style"); tag.type = "text/css"; var nonce = getNonce(); if (nonce) tag.setAttribute("nonce", nonce); return tag; } function injectStyles(tag, css) { if (tag.styleSheet) tag.styleSheet.cssText = css; else tag.appendChild(document.createTextNode(css)); } function insertStyleTag(tag) { (document.head || document.getElementsByTagName("head")[0]).appendChild(tag); } var stylesheetSingleton = function() { var counter = 0; var stylesheet = null; return { add: function(style) { if (counter == 0) { if (stylesheet = makeStyleTag()) { injectStyles(stylesheet, style); insertStyleTag(stylesheet); } } counter++; }, remove: function() { counter--; if (!counter && stylesheet) { stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); stylesheet = null; } } }; }; init_compat_module(); var styleHookSingleton = function() { var sheet = stylesheetSingleton(); return function(styles, isDynamic) { y$1(function() { sheet.add(styles); return function() { sheet.remove(); }; }, [styles && isDynamic]); }; }; var styleSingleton = function() { var useStyle = styleHookSingleton(); var Sheet = function(_a) { var styles = _a.styles, dynamic = _a.dynamic; useStyle(styles, dynamic); return null; }; return Sheet; }; var zeroGap = { left: 0, top: 0, right: 0, gap: 0 }; var parse$1 = function(x) { return parseInt(x || "", 10) || 0; }; var getOffset = function(gapMode) { var cs = window.getComputedStyle(document.body); var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"]; var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"]; var right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"]; return [ parse$1(left), parse$1(top), parse$1(right) ]; }; var getGapWidth = function(gapMode) { if (gapMode === void 0) gapMode = "margin"; if (typeof window === "undefined") return zeroGap; var offsets = getOffset(gapMode); var documentWidth = document.documentElement.clientWidth; var windowWidth = window.innerWidth; return { left: offsets[0], top: offsets[1], right: offsets[2], gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) }; }; init_compat_module(); var Style = styleSingleton(); var lockAttribute = "data-scroll-locked"; var getStyles = function(_a, allowRelative, gapMode, important) { var left = _a.left, top = _a.top, right = _a.right, gap = _a.gap; if (gapMode === void 0) gapMode = "margin"; return "\n .".concat(noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body[").concat(lockAttribute, "] {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([ allowRelative && "position: relative ".concat(important, ";"), gapMode === "margin" && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";") ].filter(Boolean).join(""), "\n }\n \n .").concat(zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body[").concat(lockAttribute, "] {\n ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); }; var getCurrentUseCounter = function() { var counter = parseInt(document.body.getAttribute("data-scroll-locked") || "0", 10); return isFinite(counter) ? counter : 0; }; var useLockAttribute = function() { y$1(function() { document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString()); return function() { var newCounter = getCurrentUseCounter() - 1; if (newCounter <= 0) document.body.removeAttribute(lockAttribute); else document.body.setAttribute(lockAttribute, newCounter.toString()); }; }, []); }; var RemoveScrollBar = function(_a) { var noRelative = _a.noRelative, noImportant = _a.noImportant, _b = _a.gapMode, gapMode = _b === void 0 ? "margin" : _b; useLockAttribute(); return k$2(Style, { styles: getStyles(T$1(function() { return getGapWidth(gapMode); }, [gapMode]), !noRelative, gapMode, !noImportant ? "!important" : "") }); }; var passiveSupported = false; if (typeof window !== "undefined") try { var options = Object.defineProperty({}, "passive", { get: function() { passiveSupported = true; return true; } }); window.addEventListener("test", options, options); window.removeEventListener("test", options, options); } catch (err) { passiveSupported = false; } var nonPassive = passiveSupported ? { passive: false } : false; var alwaysContainsScroll = function(node) { return node.tagName === "TEXTAREA"; }; var elementCanBeScrolled = function(node, overflow) { if (!(node instanceof Element)) return false; var styles = window.getComputedStyle(node); return styles[overflow] !== "hidden" && !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === "visible"); }; var elementCouldBeVScrolled = function(node) { return elementCanBeScrolled(node, "overflowY"); }; var elementCouldBeHScrolled = function(node) { return elementCanBeScrolled(node, "overflowX"); }; var locationCouldBeScrolled = function(axis, node) { var ownerDocument = node.ownerDocument; var current = node; do { if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) current = current.host; if (elementCouldBeScrolled(axis, current)) { var _a = getScrollVariables(axis, current); if (_a[1] > _a[2]) return true; } current = current.parentNode; } while (current && current !== ownerDocument.body); return false; }; var getVScrollVariables = function(_a) { return [ _a.scrollTop, _a.scrollHeight, _a.clientHeight ]; }; var getHScrollVariables = function(_a) { return [ _a.scrollLeft, _a.scrollWidth, _a.clientWidth ]; }; var elementCouldBeScrolled = function(axis, node) { return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); }; var getScrollVariables = function(axis, node) { return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node); }; var getDirectionFactor = function(axis, direction) { return axis === "h" && direction === "rtl" ? -1 : 1; }; var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) { var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); var delta = directionFactor * sourceDelta; var target = event.target; var targetInLock = endTarget.contains(target); var shouldCancelScroll = false; var isDeltaPositive = delta > 0; var availableScroll = 0; var availableScrollTop = 0; do { if (!target) break; var _a = getScrollVariables(axis, target), position = _a[0]; var elementScroll = _a[1] - _a[2] - directionFactor * position; if (position || elementScroll) { if (elementCouldBeScrolled(axis, target)) { availableScroll += elementScroll; availableScrollTop += position; } } var parent_1 = target.parentNode; target = parent_1 && parent_1.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? parent_1.host : parent_1; } while (!targetInLock && target !== document.body || targetInLock && (endTarget.contains(target) || endTarget === target)); if (isDeltaPositive && (noOverscroll && Math.abs(availableScroll) < 1 || !noOverscroll && delta > availableScroll)) shouldCancelScroll = true; else if (!isDeltaPositive && (noOverscroll && Math.abs(availableScrollTop) < 1 || !noOverscroll && -delta > availableScrollTop)) shouldCancelScroll = true; return shouldCancelScroll; }; init_compat_module(); var getTouchXY = function(event) { return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; }; var getDeltaXY = function(event) { return [event.deltaX, event.deltaY]; }; var extractRef = function(ref) { return ref && "current" in ref ? ref.current : ref; }; var deltaCompare = function(x, y) { return x[0] === y[0] && x[1] === y[1]; }; var generateStyle = function(id) { return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); }; var idCounter = 0; var lockStack = []; function RemoveScrollSideCar(props) { var shouldPreventQueue = A$2([]); var touchStartRef = A$2([0, 0]); var activeAxis = A$2(); var id = d$1(idCounter++)[0]; var Style = d$1(styleSingleton)[0]; var lastProps = A$2(props); y$1(function() { lastProps.current = props; }, [props]); y$1(function() { if (props.inert) { document.body.classList.add("block-interactivity-".concat(id)); var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); allow_1.forEach(function(el) { return el.classList.add("allow-interactivity-".concat(id)); }); return function() { document.body.classList.remove("block-interactivity-".concat(id)); allow_1.forEach(function(el) { return el.classList.remove("allow-interactivity-".concat(id)); }); }; } }, [ props.inert, props.lockRef.current, props.shards ]); var shouldCancelEvent = q$1(function(event, parent) { if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) return !lastProps.current.allowPinchZoom; var touch = getTouchXY(event); var touchStart = touchStartRef.current; var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0]; var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1]; var currentAxis; var target = event.target; var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v"; if ("touches" in event && moveDirection === "h" && target.type === "range") return false; var selection = window.getSelection(); var anchorNode = selection && selection.anchorNode; if (anchorNode ? anchorNode === target || anchorNode.contains(target) : false) return false; var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); if (!canBeScrolledInMainDirection) return true; if (canBeScrolledInMainDirection) currentAxis = moveDirection; else { currentAxis = moveDirection === "v" ? "h" : "v"; canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); } if (!canBeScrolledInMainDirection) return false; if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) activeAxis.current = currentAxis; if (!currentAxis) return true; var cancelingAxis = activeAxis.current || currentAxis; return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true); }, []); var shouldPrevent = q$1(function(_event) { var event = _event; if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) return; var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event); var sourceEvent = shouldPreventQueue.current.filter(function(e) { return e.name === event.type && (e.target === event.target || event.target === e.shadowParent) && deltaCompare(e.delta, delta); })[0]; if (sourceEvent && sourceEvent.should) { if (event.cancelable) event.preventDefault(); return; } if (!sourceEvent) { var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) { return node.contains(event.target); }); if (shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation) { if (event.cancelable) event.preventDefault(); } } }, []); var shouldCancel = q$1(function(name, delta, target, should) { var event = { name, delta, target, should, shadowParent: getOutermostShadowParent(target) }; shouldPreventQueue.current.push(event); setTimeout(function() { shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e) { return e !== event; }); }, 1); }, []); var scrollTouchStart = q$1(function(event) { touchStartRef.current = getTouchXY(event); activeAxis.current = void 0; }, []); var scrollWheel = q$1(function(event) { shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); }, []); var scrollTouchMove = q$1(function(event) { shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); }, []); y$1(function() { lockStack.push(Style); props.setCallbacks({ onScrollCapture: scrollWheel, onWheelCapture: scrollWheel, onTouchMoveCapture: scrollTouchMove }); document.addEventListener("wheel", shouldPrevent, nonPassive); document.addEventListener("touchmove", shouldPrevent, nonPassive); document.addEventListener("touchstart", scrollTouchStart, nonPassive); return function() { lockStack = lockStack.filter(function(inst) { return inst !== Style; }); document.removeEventListener("wheel", shouldPrevent, nonPassive); document.removeEventListener("touchmove", shouldPrevent, nonPassive); document.removeEventListener("touchstart", scrollTouchStart, nonPassive); }; }, []); var removeScrollBar = props.removeScrollBar, inert = props.inert; return k$2(S, null, inert ? k$2(Style, { styles: generateStyle(id) }) : null, removeScrollBar ? k$2(RemoveScrollBar, { noRelative: props.noRelative, gapMode: props.gapMode }) : null); } function getOutermostShadowParent(node) { var shadowParent = null; while (node !== null) { if (node instanceof ShadowRoot) { shadowParent = node.host; node = node.host; } node = node.parentNode; } return shadowParent; } var sidecar_default = exportSidecar(effectCar, RemoveScrollSideCar); init_compat_module(); var ReactRemoveScroll = D$1(function(props, ref) { return k$2(RemoveScroll, __assign({}, props, { ref, sideCar: sidecar_default })); }); ReactRemoveScroll.classNames = RemoveScroll.classNames; var getDefaultParent = function(originalTarget) { if (typeof document === "undefined") return null; return (Array.isArray(originalTarget) ? originalTarget[0] : originalTarget).ownerDocument.body; }; var counterMap = new WeakMap(); var uncontrolledNodes = new WeakMap(); var markerMap = {}; var lockCount = 0; var unwrapHost = function(node) { return node && (node.host || unwrapHost(node.parentNode)); }; var correctTargets = function(parent, targets) { return targets.map(function(target) { if (parent.contains(target)) return target; var correctedTarget = unwrapHost(target); if (correctedTarget && parent.contains(correctedTarget)) return correctedTarget; console.error("aria-hidden", target, "in not contained inside", parent, ". Doing nothing"); return null; }).filter(function(x) { return Boolean(x); }); }; var applyAttributeToOthers = function(originalTarget, parentNode, markerName, controlAttribute) { var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]); if (!markerMap[markerName]) markerMap[markerName] = new WeakMap(); var markerCounter = markerMap[markerName]; var hiddenNodes = []; var elementsToKeep = new Set(); var elementsToStop = new Set(targets); var keep = function(el) { if (!el || elementsToKeep.has(el)) return; elementsToKeep.add(el); keep(el.parentNode); }; targets.forEach(keep); var deep = function(parent) { if (!parent || elementsToStop.has(parent)) return; Array.prototype.forEach.call(parent.children, function(node) { if (elementsToKeep.has(node)) deep(node); else try { var attr = node.getAttribute(controlAttribute); var alreadyHidden = attr !== null && attr !== "false"; var counterValue = (counterMap.get(node) || 0) + 1; var markerValue = (markerCounter.get(node) || 0) + 1; counterMap.set(node, counterValue); markerCounter.set(node, markerValue); hiddenNodes.push(node); if (counterValue === 1 && alreadyHidden) uncontrolledNodes.set(node, true); if (markerValue === 1) node.setAttribute(markerName, "true"); if (!alreadyHidden) node.setAttribute(controlAttribute, "true"); } catch (e) { console.error("aria-hidden: cannot operate on ", node, e); } }); }; deep(parentNode); elementsToKeep.clear(); lockCount++; return function() { hiddenNodes.forEach(function(node) { var counterValue = counterMap.get(node) - 1; var markerValue = markerCounter.get(node) - 1; counterMap.set(node, counterValue); markerCounter.set(node, markerValue); if (!counterValue) { if (!uncontrolledNodes.has(node)) node.removeAttribute(controlAttribute); uncontrolledNodes.delete(node); } if (!markerValue) node.removeAttribute(markerName); }); lockCount--; if (!lockCount) { counterMap = new WeakMap(); counterMap = new WeakMap(); uncontrolledNodes = new WeakMap(); markerMap = {}; } }; }; var hideOthers = function(originalTarget, parentNode, markerName) { if (markerName === void 0) markerName = "data-aria-hidden"; var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]); var activeParentNode = parentNode || getDefaultParent(originalTarget); if (!activeParentNode) return function() { return null; }; targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll("[aria-live], script"))); return applyAttributeToOthers(targets, activeParentNode, markerName, "aria-hidden"); }; init_compat_module(); var DIALOG_NAME = "Dialog"; var [createDialogContext, createDialogScope] = createContextScope(DIALOG_NAME); var [DialogProvider, useDialogContext] = createDialogContext(DIALOG_NAME); var Dialog = (props) => { const { __scopeDialog, children, open: openProp, defaultOpen, onOpenChange, modal = true } = props; const triggerRef = A$2(null); const contentRef = A$2(null); const [open, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen ?? false, onChange: onOpenChange, caller: DIALOG_NAME }); return u$3(DialogProvider, { scope: __scopeDialog, triggerRef, contentRef, contentId: useId(), titleId: useId(), descriptionId: useId(), open, onOpenChange: setOpen, onOpenToggle: q$1(() => setOpen((prevOpen) => !prevOpen), [setOpen]), modal, children }); }; Dialog.displayName = DIALOG_NAME; var TRIGGER_NAME$1 = "DialogTrigger"; var DialogTrigger = D$1((props, forwardedRef) => { const { __scopeDialog, ...triggerProps } = props; const context = useDialogContext(TRIGGER_NAME$1, __scopeDialog); const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef); return u$3(Primitive.button, { type: "button", "aria-haspopup": "dialog", "aria-expanded": context.open, "aria-controls": context.open ? context.contentId : void 0, "data-state": getState(context.open), ...triggerProps, ref: composedTriggerRef, onClick: composeEventHandlers(props.onClick, context.onOpenToggle) }); }); DialogTrigger.displayName = TRIGGER_NAME$1; var PORTAL_NAME$1 = "DialogPortal"; var [PortalProvider$1, usePortalContext$1] = createDialogContext(PORTAL_NAME$1, { forceMount: void 0 }); var DialogPortal = (props) => { const { __scopeDialog, forceMount, children, container } = props; const context = useDialogContext(PORTAL_NAME$1, __scopeDialog); return u$3(PortalProvider$1, { scope: __scopeDialog, forceMount, children: L$3.map(children, (child) => u$3(Presence, { present: forceMount || context.open, children: u$3(Portal$1, { asChild: true, container, children: child }) })) }); }; DialogPortal.displayName = PORTAL_NAME$1; var OVERLAY_NAME = "DialogOverlay"; var DialogOverlay = D$1((props, forwardedRef) => { const portalContext = usePortalContext$1(OVERLAY_NAME, props.__scopeDialog); const { forceMount = portalContext.forceMount, ...overlayProps } = props; const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog); return context.modal ? u$3(Presence, { present: forceMount || context.open, children: u$3(DialogOverlayImpl, { ...overlayProps, ref: forwardedRef }) }) : null; }); DialogOverlay.displayName = OVERLAY_NAME; var Slot = createSlot("DialogOverlay.RemoveScroll"); var DialogOverlayImpl = D$1((props, forwardedRef) => { const { __scopeDialog, ...overlayProps } = props; const context = useDialogContext(OVERLAY_NAME, __scopeDialog); const composedRefs = useComposedRefs(forwardedRef, useDismissableLayerSurface()); return u$3(ReactRemoveScroll, { as: Slot, allowPinchZoom: true, shards: [context.contentRef], children: u$3(Primitive.div, { "data-state": getState(context.open), ...overlayProps, ref: composedRefs, style: { pointerEvents: "auto", ...overlayProps.style } }) }); }); var CONTENT_NAME$2 = "DialogContent"; var DialogContent$1 = D$1((props, forwardedRef) => { const portalContext = usePortalContext$1(CONTENT_NAME$2, props.__scopeDialog); const { forceMount = portalContext.forceMount, ...contentProps } = props; const context = useDialogContext(CONTENT_NAME$2, props.__scopeDialog); return u$3(Presence, { present: forceMount || context.open, children: context.modal ? u$3(DialogContentModal, { ...contentProps, ref: forwardedRef }) : u$3(DialogContentNonModal, { ...contentProps, ref: forwardedRef }) }); }); DialogContent$1.displayName = CONTENT_NAME$2; var DialogContentModal = D$1((props, forwardedRef) => { const context = useDialogContext(CONTENT_NAME$2, props.__scopeDialog); const contentRef = A$2(null); const composedRefs = useComposedRefs(forwardedRef, context.contentRef, contentRef); y$1(() => { const content = contentRef.current; if (content) return hideOthers(content); }, []); return u$3(DialogContentImpl, { ...props, ref: composedRefs, trapFocus: context.open, disableOutsidePointerEvents: context.open, onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => { event.preventDefault(); context.triggerRef.current?.focus(); }), onPointerDownOutside: composeEventHandlers(props.onPointerDownOutside, (event) => { const originalEvent = event.detail.originalEvent; const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; if (originalEvent.button === 2 || ctrlLeftClick) event.preventDefault(); }), onFocusOutside: composeEventHandlers(props.onFocusOutside, (event) => event.preventDefault()) }); }); var DialogContentNonModal = D$1((props, forwardedRef) => { const context = useDialogContext(CONTENT_NAME$2, props.__scopeDialog); const hasInteractedOutsideRef = A$2(false); const hasPointerDownOutsideRef = A$2(false); return u$3(DialogContentImpl, { ...props, ref: forwardedRef, trapFocus: false, disableOutsidePointerEvents: false, onCloseAutoFocus: (event) => { props.onCloseAutoFocus?.(event); if (!event.defaultPrevented) { if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus(); event.preventDefault(); } hasInteractedOutsideRef.current = false; hasPointerDownOutsideRef.current = false; }, onInteractOutside: (event) => { props.onInteractOutside?.(event); if (!event.defaultPrevented) { hasInteractedOutsideRef.current = true; if (event.detail.originalEvent.type === "pointerdown") hasPointerDownOutsideRef.current = true; } const target = event.target; if (context.triggerRef.current?.contains(target)) event.preventDefault(); if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) event.preventDefault(); } }); }); var DialogContentImpl = D$1((props, forwardedRef) => { const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props; const context = useDialogContext(CONTENT_NAME$2, __scopeDialog); useFocusGuards(); return u$3(S, { children: u$3(FocusScope, { asChild: true, loop: true, trapped: trapFocus, onMountAutoFocus: onOpenAutoFocus, onUnmountAutoFocus: onCloseAutoFocus, children: u$3(DismissableLayer, { role: "dialog", id: context.contentId, "aria-describedby": context.descriptionId, "aria-labelledby": context.titleId, "data-state": getState(context.open), ...contentProps, ref: forwardedRef, deferPointerDownOutside: true, onDismiss: () => context.onOpenChange(false) }) }) }); }); var TITLE_NAME = "DialogTitle"; var DialogTitle = D$1((props, forwardedRef) => { const { __scopeDialog, ...titleProps } = props; const context = useDialogContext(TITLE_NAME, __scopeDialog); return u$3(Primitive.h2, { id: context.titleId, ...titleProps, ref: forwardedRef }); }); DialogTitle.displayName = TITLE_NAME; var DESCRIPTION_NAME = "DialogDescription"; var DialogDescription = D$1((props, forwardedRef) => { const { __scopeDialog, ...descriptionProps } = props; const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog); return u$3(Primitive.p, { id: context.descriptionId, ...descriptionProps, ref: forwardedRef }); }); DialogDescription.displayName = DESCRIPTION_NAME; var CLOSE_NAME = "DialogClose"; var DialogClose = D$1((props, forwardedRef) => { const { __scopeDialog, ...closeProps } = props; const context = useDialogContext(CLOSE_NAME, __scopeDialog); return u$3(Primitive.button, { type: "button", ...closeProps, ref: forwardedRef, onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false)) }); }); DialogClose.displayName = CLOSE_NAME; function getState(open) { return open ? "open" : "closed"; } var sides = [ "top", "right", "bottom", "left" ]; var min = Math.min; var max = Math.max; var round = Math.round; var floor = Math.floor; var createCoords = (v) => ({ x: v, y: v }); var oppositeSideMap = { left: "right", right: "left", bottom: "top", top: "bottom" }; function clamp(start, value, end) { return max(start, min(value, end)); } function evaluate(value, param) { return typeof value === "function" ? value(param) : value; } function getSide(placement) { return placement.split("-")[0]; } function getAlignment(placement) { return placement.split("-")[1]; } function getOppositeAxis(axis) { return axis === "x" ? "y" : "x"; } function getAxisLength(axis) { return axis === "y" ? "height" : "width"; } function getSideAxis(placement) { const firstChar = placement[0]; return firstChar === "t" || firstChar === "b" ? "y" : "x"; } function getAlignmentAxis(placement) { return getOppositeAxis(getSideAxis(placement)); } function getAlignmentSides(placement, rects, rtl) { if (rtl === void 0) rtl = false; const alignment = getAlignment(placement); const alignmentAxis = getAlignmentAxis(placement); const length = getAxisLength(alignmentAxis); let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top"; if (rects.reference[length] > rects.floating[length]) mainAlignmentSide = getOppositePlacement(mainAlignmentSide); return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; } function getExpandedPlacements(placement) { const oppositePlacement = getOppositePlacement(placement); return [ getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement) ]; } function getOppositeAlignmentPlacement(placement) { return placement.includes("start") ? placement.replace("start", "end") : placement.replace("end", "start"); } var lrPlacement = ["left", "right"]; var rlPlacement = ["right", "left"]; var tbPlacement = ["top", "bottom"]; var btPlacement = ["bottom", "top"]; function getSideList(side, isStart, rtl) { switch (side) { case "top": case "bottom": if (rtl) return isStart ? rlPlacement : lrPlacement; return isStart ? lrPlacement : rlPlacement; case "left": case "right": return isStart ? tbPlacement : btPlacement; default: return []; } } function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { const alignment = getAlignment(placement); let list = getSideList(getSide(placement), direction === "start", rtl); if (alignment) { list = list.map((side) => side + "-" + alignment); if (flipAlignment) list = list.concat(list.map(getOppositeAlignmentPlacement)); } return list; } function getOppositePlacement(placement) { const side = getSide(placement); return oppositeSideMap[side] + placement.slice(side.length); } function expandPaddingObject(padding) { return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; } function getPaddingObject(padding) { return typeof padding !== "number" ? expandPaddingObject(padding) : { top: padding, right: padding, bottom: padding, left: padding }; } function rectToClientRect(rect) { const { x, y, width, height } = rect; return { width, height, top: y, left: x, right: x + width, bottom: y + height, x, y }; } function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === "y"; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case "top": coords = { x: commonX, y: reference.y - floating.height }; break; case "bottom": coords = { x: commonX, y: reference.y + reference.height }; break; case "right": coords = { x: reference.x + reference.width, y: commonY }; break; case "left": coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case "start": coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case "end": coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) options = {}; const { x, y, platform, rects, elements, strategy } = state; const { boundary = "clippingAncestors", rootBoundary = "viewport", elementContext = "floating", altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const element = elements[altBoundary ? elementContext === "floating" ? "reference" : "floating" : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating)), boundary, rootBoundary, strategy })); const rect = elementContext === "floating" ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = await (platform.isElement == null ? void 0 : platform.isElement(offsetParent)) ? await (platform.getScale == null ? void 0 : platform.getScale(offsetParent)) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } var MAX_RESET_COUNT = 50; var computePosition$1 = async (reference, floating, config) => { const { placement = "bottom", strategy = "absolute", middleware = [], platform } = config; const platformWithDetectOverflow = platform.detectOverflow ? platform : { ...platform, detectOverflow }; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let resetCount = 0; const middlewareData = {}; for (let i = 0; i < middleware.length; i++) { const currentMiddleware = middleware[i]; if (!currentMiddleware) continue; const { name, fn } = currentMiddleware; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform: platformWithDetectOverflow, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData[name] = { ...middlewareData[name], ...data }; if (reset && resetCount < MAX_RESET_COUNT) { resetCount++; if (typeof reset === "object") { if (reset.placement) statefulPlacement = reset.placement; if (reset.rects) rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; ({x, y} = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; var arrow$3 = (options) => ({ name: "arrow", options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) return {}; const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === "y"; const minProp = isYAxis ? "top" : "left"; const maxProp = isYAxis ? "bottom" : "right"; const clientProp = isYAxis ? "clientHeight" : "clientWidth"; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; if (!clientSize || !await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent))) clientSize = elements.floating[clientProp] || rects.floating[length]; const centerToReference = endDiff / 2 - startDiff / 2; const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...shouldAddOffset && { alignmentOffset } }, reset: shouldAddOffset }; } }); var flip$2 = function(options) { if (options === void 0) options = {}; return { name: "flip", options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = "bestFit", fallbackAxisSideDirection = "none", flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) return {}; const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none"; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await platform.detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) overflows.push(overflow[side]); if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; if (!overflows.every((side) => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { if (!(checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false) || overflowsData.every((d) => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; if (!resetPlacement) switch (fallbackStrategy) { case "bestFit": { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter((d) => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || currentSideAxis === "y"; } return true; }).map((d) => [d.placement, d.overflows.filter((overflow) => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) resetPlacement = placement; break; } case "initialPlacement": resetPlacement = initialPlacement; break; } if (placement !== resetPlacement) return { reset: { placement: resetPlacement } }; } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some((side) => overflow[side] >= 0); } var hide$2 = function(options) { if (options === void 0) options = {}; return { name: "hide", options, async fn(state) { const { rects, platform } = state; const { strategy = "referenceHidden", ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case "referenceHidden": { const offsets = getSideOffsets(await platform.detectOverflow(state, { ...detectOverflowOptions, elementContext: "reference" }), rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case "escaped": { const offsets = getSideOffsets(await platform.detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }), rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: return {}; } } }; }; var originSides = new Set(["left", "top"]); async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === "y"; const mainAxisMulti = originSides.has(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === "number" ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === "number") crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis; return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } var offset$2 = function(options) { if (options === void 0) options = 0; return { name: "offset", options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) return {}; return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; var shift$2 = function(options) { if (options === void 0) options = {}; return { name: "shift", options, async fn(state) { const { x, y, placement, platform } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: (_ref) => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await platform.detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === "y" ? "top" : "left"; const maxSide = mainAxis === "y" ? "bottom" : "right"; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === "y" ? "top" : "left"; const maxSide = crossAxis === "y" ? "bottom" : "right"; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; var limitShift$2 = function(options) { if (options === void 0) options = {}; return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset, state); const computedOffset = typeof rawOffset === "number" ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === "y" ? "height" : "width"; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) mainAxisCoord = limitMin; else if (mainAxisCoord > limitMax) mainAxisCoord = limitMax; } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === "y" ? "width" : "height"; const isOriginSide = originSides.has(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) crossAxisCoord = limitMin; else if (crossAxisCoord > limitMax) crossAxisCoord = limitMax; } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; var size$2 = function(options) { if (options === void 0) options = {}; return { name: "size", options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await platform.detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === "y"; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === "top" || side === "bottom") { heightSide = side; widthSide = alignment === (await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right"; } else { widthSide = side; heightSide = alignment === "end" ? "top" : "bottom"; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) availableWidth = maximumClippingWidth; if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) availableHeight = maximumClippingHeight; if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); else availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) return { reset: { rects: true } }; return {}; } }; }; function hasWindow() { return typeof window !== "undefined"; } function getNodeName(node) { if (isNode(node)) return (node.nodeName || "").toLowerCase(); return "#document"; } function getWindow(node) { var _node$ownerDocument; return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; } function getDocumentElement(node) { var _ref; return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement; } function isNode(value) { if (!hasWindow()) return false; return value instanceof Node || value instanceof getWindow(value).Node; } function isElement(value) { if (!hasWindow()) return false; return value instanceof Element || value instanceof getWindow(value).Element; } function isHTMLElement(value) { if (!hasWindow()) return false; return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement; } function isShadowRoot(value) { if (!hasWindow() || typeof ShadowRoot === "undefined") return false; return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot; } function isOverflowElement(element) { const { overflow, overflowX, overflowY, display } = getComputedStyle$1(element); return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== "inline" && display !== "contents"; } function isTableElement(element) { return /^(table|td|th)$/.test(getNodeName(element)); } function isTopLayer(element) { try { if (element.matches(":popover-open")) return true; } catch (_e) {} try { return element.matches(":modal"); } catch (_e) { return false; } } var willChangeRe = /transform|translate|scale|rotate|perspective|filter/; var containRe = /paint|layout|strict|content/; var isNotNone = (value) => !!value && value !== "none"; var isWebKitValue; function isContainingBlock(elementOrCss) { const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss; return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || "") || containRe.test(css.contain || ""); } function getContainingBlock(element) { let currentNode = getParentNode(element); while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { if (isContainingBlock(currentNode)) return currentNode; else if (isTopLayer(currentNode)) return null; currentNode = getParentNode(currentNode); } return null; } function isWebKit() { if (isWebKitValue == null) isWebKitValue = typeof CSS !== "undefined" && CSS.supports && CSS.supports("-webkit-backdrop-filter", "none"); return isWebKitValue; } function isLastTraversableNode(node) { return /^(html|body|#document)$/.test(getNodeName(node)); } function getComputedStyle$1(element) { return getWindow(element).getComputedStyle(element); } function getNodeScroll(element) { if (isElement(element)) return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; return { scrollLeft: element.scrollX, scrollTop: element.scrollY }; } function getParentNode(node) { if (getNodeName(node) === "html") return node; const result = node.assignedSlot || node.parentNode || isShadowRoot(node) && node.host || getDocumentElement(node); return isShadowRoot(result) ? result.host : result; } function getNearestOverflowAncestor(node) { const parentNode = getParentNode(node); if (isLastTraversableNode(parentNode)) return node.ownerDocument ? node.ownerDocument.body : node.body; if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) return parentNode; return getNearestOverflowAncestor(parentNode); } function getOverflowAncestors(node, list, traverseIframes) { var _node$ownerDocument2; if (list === void 0) list = []; if (traverseIframes === void 0) traverseIframes = true; const scrollableAncestor = getNearestOverflowAncestor(node); const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body); const win = getWindow(scrollableAncestor); if (isBody) { const frameElement = getFrameElement(win); return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []); } else return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes)); } function getFrameElement(win) { return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null; } function getCssDimensions(element) { const css = getComputedStyle$1(element); let width = parseFloat(css.width) || 0; let height = parseFloat(css.height) || 0; const hasOffset = isHTMLElement(element); const offsetWidth = hasOffset ? element.offsetWidth : width; const offsetHeight = hasOffset ? element.offsetHeight : height; const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; if (shouldFallback) { width = offsetWidth; height = offsetHeight; } return { width, height, $: shouldFallback }; } function unwrapElement(element) { return !isElement(element) ? element.contextElement : element; } function getScale(element) { const domElement = unwrapElement(element); if (!isHTMLElement(domElement)) return createCoords(1); const rect = domElement.getBoundingClientRect(); const { width, height, $ } = getCssDimensions(domElement); let x = ($ ? round(rect.width) : rect.width) / width; let y = ($ ? round(rect.height) : rect.height) / height; if (!x || !Number.isFinite(x)) x = 1; if (!y || !Number.isFinite(y)) y = 1; return { x, y }; } var noOffsets = createCoords(0); function getVisualOffsets(element) { const win = getWindow(element); if (!isWebKit() || !win.visualViewport) return noOffsets; return { x: win.visualViewport.offsetLeft, y: win.visualViewport.offsetTop }; } function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { if (isFixed === void 0) isFixed = false; if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) return false; return isFixed; } function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { if (includeScale === void 0) includeScale = false; if (isFixedStrategy === void 0) isFixedStrategy = false; const clientRect = element.getBoundingClientRect(); const domElement = unwrapElement(element); let scale = createCoords(1); if (includeScale) if (offsetParent) { if (isElement(offsetParent)) scale = getScale(offsetParent); } else scale = getScale(element); const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0); let x = (clientRect.left + visualOffsets.x) / scale.x; let y = (clientRect.top + visualOffsets.y) / scale.y; let width = clientRect.width / scale.x; let height = clientRect.height / scale.y; if (domElement) { const win = getWindow(domElement); const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; let currentWin = win; let currentIFrame = getFrameElement(currentWin); while (currentIFrame && offsetParent && offsetWin !== currentWin) { const iframeScale = getScale(currentIFrame); const iframeRect = currentIFrame.getBoundingClientRect(); const css = getComputedStyle$1(currentIFrame); const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; x *= iframeScale.x; y *= iframeScale.y; width *= iframeScale.x; height *= iframeScale.y; x += left; y += top; currentWin = getWindow(currentIFrame); currentIFrame = getFrameElement(currentWin); } } return rectToClientRect({ width, height, x, y }); } function getWindowScrollBarX(element, rect) { const leftScroll = getNodeScroll(element).scrollLeft; if (!rect) return getBoundingClientRect(getDocumentElement(element)).left + leftScroll; return rect.left + leftScroll; } function getHTMLOffset(documentElement, scroll) { const htmlRect = documentElement.getBoundingClientRect(); return { x: htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect), y: htmlRect.top + scroll.scrollTop }; } function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { let { elements, rect, offsetParent, strategy } = _ref; const isFixed = strategy === "fixed"; const documentElement = getDocumentElement(offsetParent); const topLayer = elements ? isTopLayer(elements.floating) : false; if (offsetParent === documentElement || topLayer && isFixed) return rect; let scroll = { scrollLeft: 0, scrollTop: 0 }; let scale = createCoords(1); const offsets = createCoords(0); const isOffsetParentAnElement = isHTMLElement(offsetParent); if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) scroll = getNodeScroll(offsetParent); if (isOffsetParentAnElement) { const offsetRect = getBoundingClientRect(offsetParent); scale = getScale(offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } } const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); return { width: rect.width * scale.x, height: rect.height * scale.y, x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x, y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y }; } function getClientRects(element) { return Array.from(element.getClientRects()); } function getDocumentRect(element) { const html = getDocumentElement(element); const scroll = getNodeScroll(element); const body = element.ownerDocument.body; const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); let x = -scroll.scrollLeft + getWindowScrollBarX(element); const y = -scroll.scrollTop; if (getComputedStyle$1(body).direction === "rtl") x += max(html.clientWidth, body.clientWidth) - width; return { width, height, x, y }; } var SCROLLBAR_MAX = 25; function getViewportRect(element, strategy) { const win = getWindow(element); const html = getDocumentElement(element); const visualViewport = win.visualViewport; let width = html.clientWidth; let height = html.clientHeight; let x = 0; let y = 0; if (visualViewport) { width = visualViewport.width; height = visualViewport.height; const visualViewportBased = isWebKit(); if (!visualViewportBased || visualViewportBased && strategy === "fixed") { x = visualViewport.offsetLeft; y = visualViewport.offsetTop; } } const windowScrollbarX = getWindowScrollBarX(html); if (windowScrollbarX <= 0) { const doc = html.ownerDocument; const body = doc.body; const bodyStyles = getComputedStyle(body); const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0; const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline); if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) width -= clippingStableScrollbarWidth; } else if (windowScrollbarX <= SCROLLBAR_MAX) width += windowScrollbarX; return { width, height, x, y }; } function getInnerBoundingClientRect(element, strategy) { const clientRect = getBoundingClientRect(element, true, strategy === "fixed"); const top = clientRect.top + element.clientTop; const left = clientRect.left + element.clientLeft; const scale = isHTMLElement(element) ? getScale(element) : createCoords(1); return { width: element.clientWidth * scale.x, height: element.clientHeight * scale.y, x: left * scale.x, y: top * scale.y }; } function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { let rect; if (clippingAncestor === "viewport") rect = getViewportRect(element, strategy); else if (clippingAncestor === "document") rect = getDocumentRect(getDocumentElement(element)); else if (isElement(clippingAncestor)) rect = getInnerBoundingClientRect(clippingAncestor, strategy); else { const visualOffsets = getVisualOffsets(element); rect = { x: clippingAncestor.x - visualOffsets.x, y: clippingAncestor.y - visualOffsets.y, width: clippingAncestor.width, height: clippingAncestor.height }; } return rectToClientRect(rect); } function hasFixedPositionAncestor(element, stopNode) { const parentNode = getParentNode(element); if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) return false; return getComputedStyle$1(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode); } function getClippingElementAncestors(element, cache) { const cachedResult = cache.get(element); if (cachedResult) return cachedResult; let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body"); let currentContainingBlockComputedStyle = null; const elementIsFixed = getComputedStyle$1(element).position === "fixed"; let currentNode = elementIsFixed ? getParentNode(element) : element; while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { const computedStyle = getComputedStyle$1(currentNode); const currentNodeIsContaining = isContainingBlock(currentNode); if (!currentNodeIsContaining && computedStyle.position === "fixed") currentContainingBlockComputedStyle = null; if (elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === "absolute" || currentContainingBlockComputedStyle.position === "fixed") || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode)) result = result.filter((ancestor) => ancestor !== currentNode); else currentContainingBlockComputedStyle = computedStyle; currentNode = getParentNode(currentNode); } cache.set(element, result); return result; } function getClippingRect(_ref) { let { element, boundary, rootBoundary, strategy } = _ref; const clippingAncestors = [...boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary), rootBoundary]; const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy); let top = firstRect.top; let right = firstRect.right; let bottom = firstRect.bottom; let left = firstRect.left; for (let i = 1; i < clippingAncestors.length; i++) { const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i], strategy); top = max(rect.top, top); right = min(rect.right, right); bottom = min(rect.bottom, bottom); left = max(rect.left, left); } return { width: right - left, height: bottom - top, x: left, y: top }; } function getDimensions(element) { const { width, height } = getCssDimensions(element); return { width, height }; } function getRectRelativeToOffsetParent(element, offsetParent, strategy) { const isOffsetParentAnElement = isHTMLElement(offsetParent); const documentElement = getDocumentElement(offsetParent); const isFixed = strategy === "fixed"; const rect = getBoundingClientRect(element, true, isFixed, offsetParent); let scroll = { scrollLeft: 0, scrollTop: 0 }; const offsets = createCoords(0); function setLeftRTLScrollbarOffset() { offsets.x = getWindowScrollBarX(documentElement); } if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) scroll = getNodeScroll(offsetParent); if (isOffsetParentAnElement) { const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } else if (documentElement) setLeftRTLScrollbarOffset(); } if (isFixed && !isOffsetParentAnElement && documentElement) setLeftRTLScrollbarOffset(); const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); return { x: rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x, y: rect.top + scroll.scrollTop - offsets.y - htmlOffset.y, width: rect.width, height: rect.height }; } function isStaticPositioned(element) { return getComputedStyle$1(element).position === "static"; } function getTrueOffsetParent(element, polyfill) { if (!isHTMLElement(element) || getComputedStyle$1(element).position === "fixed") return null; if (polyfill) return polyfill(element); let rawOffsetParent = element.offsetParent; if (getDocumentElement(element) === rawOffsetParent) rawOffsetParent = rawOffsetParent.ownerDocument.body; return rawOffsetParent; } function getOffsetParent(element, polyfill) { const win = getWindow(element); if (isTopLayer(element)) return win; if (!isHTMLElement(element)) { let svgOffsetParent = getParentNode(element); while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) { if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) return svgOffsetParent; svgOffsetParent = getParentNode(svgOffsetParent); } return win; } let offsetParent = getTrueOffsetParent(element, polyfill); while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) offsetParent = getTrueOffsetParent(offsetParent, polyfill); if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) return win; return offsetParent || getContainingBlock(element) || win; } var getElementRects = async function(data) { const getOffsetParentFn = this.getOffsetParent || getOffsetParent; const getDimensionsFn = this.getDimensions; const floatingDimensions = await getDimensionsFn(data.floating); return { reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy), floating: { x: 0, y: 0, width: floatingDimensions.width, height: floatingDimensions.height } }; }; function isRTL(element) { return getComputedStyle$1(element).direction === "rtl"; } var platform = { convertOffsetParentRelativeRectToViewportRelativeRect, getDocumentElement, getClippingRect, getOffsetParent, getElementRects, getClientRects, getDimensions, getScale, isElement, isRTL }; function rectsAreEqual(a, b) { return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; } function observeMove(element, onMove) { let io = null; let timeoutId; const root = getDocumentElement(element); function cleanup() { var _io; clearTimeout(timeoutId); (_io = io) == null || _io.disconnect(); io = null; } function refresh(skip, threshold) { if (skip === void 0) skip = false; if (threshold === void 0) threshold = 1; cleanup(); const elementRectForRootMargin = element.getBoundingClientRect(); const { left, top, width, height } = elementRectForRootMargin; if (!skip) onMove(); if (!width || !height) return; const insetTop = floor(top); const insetRight = floor(root.clientWidth - (left + width)); const insetBottom = floor(root.clientHeight - (top + height)); const insetLeft = floor(left); const options = { rootMargin: -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px", threshold: max(0, min(1, threshold)) || 1 }; let isFirstUpdate = true; function handleObserve(entries) { const ratio = entries[0].intersectionRatio; if (ratio !== threshold) { if (!isFirstUpdate) return refresh(); if (!ratio) timeoutId = setTimeout(() => { refresh(false, 1e-7); }, 1e3); else refresh(false, ratio); } if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) refresh(); isFirstUpdate = false; } try { io = new IntersectionObserver(handleObserve, { ...options, root: root.ownerDocument }); } catch (_e) { io = new IntersectionObserver(handleObserve, options); } io.observe(element); } refresh(true); return cleanup; } function autoUpdate(reference, floating, update, options) { if (options === void 0) options = {}; const { ancestorScroll = true, ancestorResize = true, elementResize = typeof ResizeObserver === "function", layoutShift = typeof IntersectionObserver === "function", animationFrame = false } = options; const referenceEl = unwrapElement(reference); const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...floating ? getOverflowAncestors(floating) : []] : []; ancestors.forEach((ancestor) => { ancestorScroll && ancestor.addEventListener("scroll", update, { passive: true }); ancestorResize && ancestor.addEventListener("resize", update); }); const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null; let reobserveFrame = -1; let resizeObserver = null; if (elementResize) { resizeObserver = new ResizeObserver((_ref) => { let [firstEntry] = _ref; if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) { resizeObserver.unobserve(floating); cancelAnimationFrame(reobserveFrame); reobserveFrame = requestAnimationFrame(() => { var _resizeObserver; (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating); }); } update(); }); if (referenceEl && !animationFrame) resizeObserver.observe(referenceEl); if (floating) resizeObserver.observe(floating); } let frameId; let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null; if (animationFrame) frameLoop(); function frameLoop() { const nextRefRect = getBoundingClientRect(reference); if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) update(); prevRefRect = nextRefRect; frameId = requestAnimationFrame(frameLoop); } update(); return () => { var _resizeObserver2; ancestors.forEach((ancestor) => { ancestorScroll && ancestor.removeEventListener("scroll", update); ancestorResize && ancestor.removeEventListener("resize", update); }); cleanupIo?.(); (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect(); resizeObserver = null; if (animationFrame) cancelAnimationFrame(frameId); }; } var offset$1 = offset$2; var shift$1 = shift$2; var flip$1 = flip$2; var size$1 = size$2; var hide$1 = hide$2; var arrow$2 = arrow$3; var limitShift$1 = limitShift$2; var computePosition = (reference, floating, options) => { const cache = new Map(); const mergedOptions = { platform, ...options }; const platformWithCache = { ...mergedOptions.platform, _c: cache }; return computePosition$1(reference, floating, { ...mergedOptions, platform: platformWithCache }); }; init_compat_module(); var index$1 = typeof document !== "undefined" ? _$1 : function noop() {}; function deepEqual(a, b) { if (a === b) return true; if (typeof a !== typeof b) return false; if (typeof a === "function" && a.toString() === b.toString()) return true; let length; let i; let keys; if (a && b && typeof a === "object") { if (Array.isArray(a)) { length = a.length; if (length !== b.length) return false; for (i = length; i-- !== 0;) if (!deepEqual(a[i], b[i])) return false; return true; } keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!{}.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { const key = keys[i]; if (key === "_owner" && a.$$typeof) continue; if (!deepEqual(a[key], b[key])) return false; } return true; } return a !== a && b !== b; } function getDPR(element) { if (typeof window === "undefined") return 1; return (element.ownerDocument.defaultView || window).devicePixelRatio || 1; } function roundByDPR(element, value) { const dpr = getDPR(element); return Math.round(value * dpr) / dpr; } function useLatestRef(value) { const ref = A$2(value); index$1(() => { ref.current = value; }); return ref; } function useFloating(options) { if (options === void 0) options = {}; const { placement = "bottom", strategy = "absolute", middleware = [], platform, elements: { reference: externalReference, floating: externalFloating } = {}, transform = true, whileElementsMounted, open } = options; const [data, setData] = d$1({ x: 0, y: 0, strategy, placement, middlewareData: {}, isPositioned: false }); const [latestMiddleware, setLatestMiddleware] = d$1(middleware); if (!deepEqual(latestMiddleware, middleware)) setLatestMiddleware(middleware); const [_reference, _setReference] = d$1(null); const [_floating, _setFloating] = d$1(null); const setReference = q$1((node) => { if (node !== referenceRef.current) { referenceRef.current = node; _setReference(node); } }, []); const setFloating = q$1((node) => { if (node !== floatingRef.current) { floatingRef.current = node; _setFloating(node); } }, []); const referenceEl = externalReference || _reference; const floatingEl = externalFloating || _floating; const referenceRef = A$2(null); const floatingRef = A$2(null); const dataRef = A$2(data); const hasWhileElementsMounted = whileElementsMounted != null; const whileElementsMountedRef = useLatestRef(whileElementsMounted); const platformRef = useLatestRef(platform); const openRef = useLatestRef(open); const update = q$1(() => { if (!referenceRef.current || !floatingRef.current) return; const config = { placement, strategy, middleware: latestMiddleware }; if (platformRef.current) config.platform = platformRef.current; computePosition(referenceRef.current, floatingRef.current, config).then((data) => { const fullData = { ...data, isPositioned: openRef.current !== false }; if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { dataRef.current = fullData; bn(() => { setData(fullData); }); } }); }, [ latestMiddleware, placement, strategy, platformRef, openRef ]); index$1(() => { if (open === false && dataRef.current.isPositioned) { dataRef.current.isPositioned = false; setData((data) => ({ ...data, isPositioned: false })); } }, [open]); const isMountedRef = A$2(false); index$1(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; }; }, []); index$1(() => { if (referenceEl) referenceRef.current = referenceEl; if (floatingEl) floatingRef.current = floatingEl; if (referenceEl && floatingEl) { if (whileElementsMountedRef.current) return whileElementsMountedRef.current(referenceEl, floatingEl, update); update(); } }, [ referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted ]); const refs = T$1(() => ({ reference: referenceRef, floating: floatingRef, setReference, setFloating }), [setReference, setFloating]); const elements = T$1(() => ({ reference: referenceEl, floating: floatingEl }), [referenceEl, floatingEl]); const floatingStyles = T$1(() => { const initialStyles = { position: strategy, left: 0, top: 0 }; if (!elements.floating) return initialStyles; const x = roundByDPR(elements.floating, data.x); const y = roundByDPR(elements.floating, data.y); if (transform) return { ...initialStyles, transform: "translate(" + x + "px, " + y + "px)", ...getDPR(elements.floating) >= 1.5 && { willChange: "transform" } }; return { position: strategy, left: x, top: y }; }, [ strategy, transform, elements.floating, data.x, data.y ]); return T$1(() => ({ ...data, update, refs, elements, floatingStyles }), [ data, update, refs, elements, floatingStyles ]); } var arrow$1 = (options) => { function isRef(value) { return {}.hasOwnProperty.call(value, "current"); } return { name: "arrow", options, fn(state) { const { element, padding } = typeof options === "function" ? options(state) : options; if (element && isRef(element)) { if (element.current != null) return arrow$2({ element: element.current, padding }).fn(state); return {}; } if (element) return arrow$2({ element, padding }).fn(state); return {}; } }; }; var offset = (options, deps) => { const result = offset$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; var shift = (options, deps) => { const result = shift$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; var limitShift = (options, deps) => { return { fn: limitShift$1(options).fn, options: [options, deps] }; }; var flip = (options, deps) => { const result = flip$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; var size = (options, deps) => { const result = size$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; var hide = (options, deps) => { const result = hide$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; var arrow = (options, deps) => { const result = arrow$1(options); return { name: result.name, fn: result.fn, options: [options, deps] }; }; init_compat_module(); var NAME = "Arrow"; var Arrow$1 = D$1((props, forwardedRef) => { const { children, width = 10, height = 5, ...arrowProps } = props; return u$3(Primitive.svg, { ...arrowProps, ref: forwardedRef, width, height, viewBox: "0 0 30 10", preserveAspectRatio: "none", children: props.asChild ? children : u$3("polygon", { points: "0,0 30,0 15,10" }) }); }); Arrow$1.displayName = NAME; var Root = Arrow$1; init_compat_module(); function useSize(element) { const [size, setSize] = d$1(void 0); useLayoutEffect2(() => { if (element) { setSize({ width: element.offsetWidth, height: element.offsetHeight }); const resizeObserver = new ResizeObserver((entries) => { if (!Array.isArray(entries)) return; if (!entries.length) return; const entry = entries[0]; let width; let height; if ("borderBoxSize" in entry) { const borderSizeEntry = entry["borderBoxSize"]; const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry; width = borderSize["inlineSize"]; height = borderSize["blockSize"]; } else { width = element.offsetWidth; height = element.offsetHeight; } setSize({ width, height }); }); resizeObserver.observe(element, { box: "border-box" }); return () => resizeObserver.unobserve(element); } else setSize(void 0); }, [element]); return size; } init_compat_module(); var POPPER_NAME = "Popper"; var [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME); var [PopperProvider, usePopperContext] = createPopperContext(POPPER_NAME); var Popper = (props) => { const { __scopePopper, children } = props; const [anchor, setAnchor] = d$1(null); const [placementState, setPlacementState] = d$1(void 0); return u$3(PopperProvider, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, placementState, setPlacementState, children }); }; Popper.displayName = POPPER_NAME; var ANCHOR_NAME = "PopperAnchor"; var PopperAnchor = D$1((props, forwardedRef) => { const { __scopePopper, virtualRef, ...anchorProps } = props; const context = usePopperContext(ANCHOR_NAME, __scopePopper); const ref = A$2(null); const onAnchorChange = context.onAnchorChange; const composedRefs = useComposedRefs(forwardedRef, q$1((node) => { ref.current = node; if (node) onAnchorChange(node); }, [onAnchorChange])); const anchorRef = A$2(null); y$1(() => { if (!virtualRef) return; const previousAnchor = anchorRef.current; anchorRef.current = virtualRef.current; if (previousAnchor !== anchorRef.current) onAnchorChange(anchorRef.current); }); const sideAndAlign = context.placementState && getSideAndAlignFromPlacement(context.placementState); const placedSide = sideAndAlign?.[0]; const placedAlign = sideAndAlign?.[1]; return virtualRef ? null : u$3(Primitive.div, { "data-radix-popper-side": placedSide, "data-radix-popper-align": placedAlign, ...anchorProps, ref: composedRefs }); }); PopperAnchor.displayName = ANCHOR_NAME; var CONTENT_NAME$1 = "PopperContent"; var [PopperContentProvider, useContentContext] = createPopperContext(CONTENT_NAME$1); var PopperContent = D$1((props, forwardedRef) => { const { __scopePopper, side = "bottom", sideOffset = 0, align = "center", alignOffset = 0, arrowPadding = 0, avoidCollisions = true, collisionBoundary = [], collisionPadding: collisionPaddingProp = 0, sticky = "partial", hideWhenDetached = false, updatePositionStrategy = "optimized", onPlaced, ...contentProps } = props; const context = usePopperContext(CONTENT_NAME$1, __scopePopper); const [content, setContent] = d$1(null); const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node)); const [arrow$4, setArrow] = d$1(null); const arrowSize = useSize(arrow$4); const arrowWidth = arrowSize?.width ?? 0; const arrowHeight = arrowSize?.height ?? 0; const desiredPlacement = side + (align !== "center" ? "-" + align : ""); const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp }; const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary]; const hasExplicitBoundaries = boundary.length > 0; const detectOverflowOptions = { padding: collisionPadding, boundary: boundary.filter(isNotNull), altBoundary: hasExplicitBoundaries }; const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({ strategy: "fixed", placement: desiredPlacement, whileElementsMounted: (...args) => { return autoUpdate(...args, { animationFrame: updatePositionStrategy === "always" }); }, elements: { reference: context.anchor }, middleware: [ offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }), avoidCollisions && shift({ mainAxis: true, crossAxis: false, limiter: sticky === "partial" ? limitShift() : void 0, ...detectOverflowOptions }), avoidCollisions && flip({ ...detectOverflowOptions }), size({ ...detectOverflowOptions, apply: ({ elements, rects, availableWidth, availableHeight }) => { const { width: anchorWidth, height: anchorHeight } = rects.reference; const contentStyle = elements.floating.style; contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`); contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`); contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`); contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`); } }), arrow$4 && arrow({ element: arrow$4, padding: arrowPadding }), transformOrigin({ arrowWidth, arrowHeight }), hideWhenDetached && hide({ strategy: "referenceHidden", ...detectOverflowOptions, boundary: hasExplicitBoundaries ? detectOverflowOptions.boundary : void 0 }) ] }); const setPlacementState = context.setPlacementState; useLayoutEffect2(() => { setPlacementState(placement); return () => { setPlacementState(void 0); }; }, [placement, setPlacementState]); const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement); const handlePlaced = useCallbackRef$1(onPlaced); useLayoutEffect2(() => { if (isPositioned) handlePlaced?.(); }, [isPositioned, handlePlaced]); const arrowX = middlewareData.arrow?.x; const arrowY = middlewareData.arrow?.y; const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0; const [contentZIndex, setContentZIndex] = d$1(); useLayoutEffect2(() => { if (content) setContentZIndex(window.getComputedStyle(content).zIndex); }, [content]); return u$3("div", { ref: refs.setFloating, "data-radix-popper-content-wrapper": "", style: { ...floatingStyles, transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)", minWidth: "max-content", zIndex: contentZIndex, "--radix-popper-transform-origin": [middlewareData.transformOrigin?.x, middlewareData.transformOrigin?.y].join(" "), ...middlewareData.hide?.referenceHidden && { visibility: "hidden", pointerEvents: "none" } }, dir: props.dir, children: u$3(PopperContentProvider, { scope: __scopePopper, placedSide, placedAlign, onArrowChange: setArrow, arrowX, arrowY, shouldHideArrow: cannotCenterArrow, children: u$3(Primitive.div, { "data-side": placedSide, "data-align": placedAlign, ...contentProps, ref: composedRefs, style: { ...contentProps.style, animation: !isPositioned ? "none" : void 0 } }) }) }); }); PopperContent.displayName = CONTENT_NAME$1; var ARROW_NAME$1 = "PopperArrow"; var OPPOSITE_SIDE = { top: "bottom", right: "left", bottom: "top", left: "right" }; var PopperArrow = D$1(function PopperArrow2(props, forwardedRef) { const { __scopePopper, ...arrowProps } = props; const contentContext = useContentContext(ARROW_NAME$1, __scopePopper); const baseSide = OPPOSITE_SIDE[contentContext.placedSide]; return u$3("span", { ref: contentContext.onArrowChange, style: { position: "absolute", left: contentContext.arrowX, top: contentContext.arrowY, [baseSide]: 0, transformOrigin: { top: "", right: "0 0", bottom: "center 0", left: "100% 0" }[contentContext.placedSide], transform: { top: "translateY(100%)", right: "translateY(50%) rotate(90deg) translateX(-50%)", bottom: `rotate(180deg)`, left: "translateY(50%) rotate(-90deg) translateX(50%)" }[contentContext.placedSide], visibility: contentContext.shouldHideArrow ? "hidden" : void 0 }, children: u$3(Root, { ...arrowProps, ref: forwardedRef, style: { ...arrowProps.style, display: "block" } }) }); }); PopperArrow.displayName = ARROW_NAME$1; function isNotNull(value) { return value !== null; } var transformOrigin = (options) => ({ name: "transformOrigin", options, fn(data) { const { placement, rects, middlewareData } = data; const isArrowHidden = middlewareData.arrow?.centerOffset !== 0; const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement); const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign]; const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2; const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2; let x = ""; let y = ""; if (placedSide === "bottom") { x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; y = `${-arrowHeight}px`; } else if (placedSide === "top") { x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; y = `${rects.floating.height + arrowHeight}px`; } else if (placedSide === "right") { x = `${-arrowHeight}px`; y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; } else if (placedSide === "left") { x = `${rects.floating.width + arrowHeight}px`; y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; } return { data: { x, y } }; } }); function getSideAndAlignFromPlacement(placement) { const [side, align = "center"] = placement.split("-"); return [side, align]; } var Root2$1 = Popper; var Anchor = PopperAnchor; var Content = PopperContent; var Arrow = PopperArrow; init_compat_module(); var originalBodyUserSelect; var HOVERCARD_NAME = "HoverCard"; var [createHoverCardContext, createHoverCardScope] = createContextScope(HOVERCARD_NAME, [createPopperScope]); var usePopperScope = createPopperScope(); var [HoverCardProvider, useHoverCardContext] = createHoverCardContext(HOVERCARD_NAME); var HoverCard = (props) => { const { __scopeHoverCard, children, open: openProp, defaultOpen, onOpenChange, openDelay = 700, closeDelay = 300 } = props; const popperScope = usePopperScope(__scopeHoverCard); const openTimerRef = A$2(0); const closeTimerRef = A$2(0); const hasSelectionRef = A$2(false); const isPointerDownOnContentRef = A$2(false); const [open, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen ?? false, onChange: onOpenChange, caller: HOVERCARD_NAME }); const handleOpen = q$1(() => { clearTimeout(closeTimerRef.current); openTimerRef.current = window.setTimeout(() => setOpen(true), openDelay); }, [openDelay, setOpen]); const handleClose = q$1(() => { clearTimeout(openTimerRef.current); if (!hasSelectionRef.current && !isPointerDownOnContentRef.current) closeTimerRef.current = window.setTimeout(() => setOpen(false), closeDelay); }, [closeDelay, setOpen]); const handleDismiss = q$1(() => setOpen(false), [setOpen]); y$1(() => { return () => { clearTimeout(openTimerRef.current); clearTimeout(closeTimerRef.current); }; }, []); return u$3(HoverCardProvider, { scope: __scopeHoverCard, open, onOpenChange: setOpen, onOpen: handleOpen, onClose: handleClose, onDismiss: handleDismiss, hasSelectionRef, isPointerDownOnContentRef, children: u$3(Root2$1, { ...popperScope, children }) }); }; HoverCard.displayName = HOVERCARD_NAME; var TRIGGER_NAME = "HoverCardTrigger"; var HoverCardTrigger = D$1((props, forwardedRef) => { const { __scopeHoverCard, ...triggerProps } = props; const context = useHoverCardContext(TRIGGER_NAME, __scopeHoverCard); return u$3(Anchor, { asChild: true, ...usePopperScope(__scopeHoverCard), children: u$3(Primitive.a, { "data-state": context.open ? "open" : "closed", ...triggerProps, ref: forwardedRef, onPointerEnter: composeEventHandlers(props.onPointerEnter, excludeTouch(context.onOpen)), onPointerLeave: composeEventHandlers(props.onPointerLeave, excludeTouch(context.onClose)), onFocus: composeEventHandlers(props.onFocus, context.onOpen), onBlur: composeEventHandlers(props.onBlur, context.onClose), onTouchStart: composeEventHandlers(props.onTouchStart, (event) => event.preventDefault()) }) }); }); HoverCardTrigger.displayName = TRIGGER_NAME; var PORTAL_NAME = "HoverCardPortal"; var [PortalProvider, usePortalContext] = createHoverCardContext(PORTAL_NAME, { forceMount: void 0 }); var HoverCardPortal = (props) => { const { __scopeHoverCard, forceMount, children, container } = props; const context = useHoverCardContext(PORTAL_NAME, __scopeHoverCard); return u$3(PortalProvider, { scope: __scopeHoverCard, forceMount, children: u$3(Presence, { present: forceMount || context.open, children: u$3(Portal$1, { asChild: true, container, children }) }) }); }; HoverCardPortal.displayName = PORTAL_NAME; var CONTENT_NAME = "HoverCardContent"; var HoverCardContent = D$1((props, forwardedRef) => { const portalContext = usePortalContext(CONTENT_NAME, props.__scopeHoverCard); const { forceMount = portalContext.forceMount, ...contentProps } = props; const context = useHoverCardContext(CONTENT_NAME, props.__scopeHoverCard); return u$3(Presence, { present: forceMount || context.open, children: u$3(HoverCardContentImpl, { "data-state": context.open ? "open" : "closed", ...contentProps, onPointerEnter: composeEventHandlers(props.onPointerEnter, excludeTouch(context.onOpen)), onPointerLeave: composeEventHandlers(props.onPointerLeave, excludeTouch(context.onClose)), ref: forwardedRef }) }); }); HoverCardContent.displayName = CONTENT_NAME; var HoverCardContentImpl = D$1((props, forwardedRef) => { const { __scopeHoverCard, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, ...contentProps } = props; const context = useHoverCardContext(CONTENT_NAME, __scopeHoverCard); const popperScope = usePopperScope(__scopeHoverCard); const ref = A$2(null); const composedRefs = useComposedRefs(forwardedRef, ref); const [containSelection, setContainSelection] = d$1(false); y$1(() => { if (containSelection) { const body = document.body; originalBodyUserSelect = body.style.userSelect || body.style.webkitUserSelect; body.style.userSelect = "none"; body.style.webkitUserSelect = "none"; return () => { body.style.userSelect = originalBodyUserSelect; body.style.webkitUserSelect = originalBodyUserSelect; }; } }, [containSelection]); y$1(() => { if (ref.current) { const handlePointerUp = () => { setContainSelection(false); context.isPointerDownOnContentRef.current = false; setTimeout(() => { if (document.getSelection()?.toString() !== "") context.hasSelectionRef.current = true; }); }; document.addEventListener("pointerup", handlePointerUp); return () => { document.removeEventListener("pointerup", handlePointerUp); context.hasSelectionRef.current = false; context.isPointerDownOnContentRef.current = false; }; } }, [context.isPointerDownOnContentRef, context.hasSelectionRef]); y$1(() => { if (ref.current) getTabbableNodes(ref.current).forEach((tabbable) => tabbable.setAttribute("tabindex", "-1")); }); return u$3(DismissableLayer, { asChild: true, disableOutsidePointerEvents: false, onInteractOutside, onEscapeKeyDown, onPointerDownOutside, onFocusOutside: composeEventHandlers(onFocusOutside, (event) => { event.preventDefault(); }), onDismiss: context.onDismiss, children: u$3(Content, { ...popperScope, ...contentProps, onPointerDown: composeEventHandlers(contentProps.onPointerDown, (event) => { if (event.currentTarget.contains(event.target)) setContainSelection(true); context.hasSelectionRef.current = false; context.isPointerDownOnContentRef.current = true; }), ref: composedRefs, style: { ...contentProps.style, userSelect: containSelection ? "text" : void 0, WebkitUserSelect: containSelection ? "text" : void 0, "--radix-hover-card-content-transform-origin": "var(--radix-popper-transform-origin)", "--radix-hover-card-content-available-width": "var(--radix-popper-available-width)", "--radix-hover-card-content-available-height": "var(--radix-popper-available-height)", "--radix-hover-card-trigger-width": "var(--radix-popper-anchor-width)", "--radix-hover-card-trigger-height": "var(--radix-popper-anchor-height)" } }) }); }); var ARROW_NAME = "HoverCardArrow"; var HoverCardArrow = D$1((props, forwardedRef) => { const { __scopeHoverCard, ...arrowProps } = props; return u$3(Arrow, { ...usePopperScope(__scopeHoverCard), ...arrowProps, ref: forwardedRef }); }); HoverCardArrow.displayName = ARROW_NAME; function excludeTouch(eventHandler) { return (event) => event.pointerType === "touch" ? void 0 : eventHandler(); } function getTabbableNodes(container) { const nodes = []; const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { acceptNode: (node) => { return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } }); while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } var Root2 = HoverCard; var Trigger = HoverCardTrigger; var Portal = HoverCardPortal; var Content2 = HoverCardContent; var Arrow2 = HoverCardArrow; var isString$1 = (obj) => typeof obj === "string"; var defer = () => { let res; let rej; const promise = new Promise((resolve, reject) => { res = resolve; rej = reject; }); promise.resolve = res; promise.reject = rej; return promise; }; var makeString = (object) => { if (object == null) return ""; return String(object); }; var copy = (a, s, t) => { a.forEach((m) => { if (s[m]) t[m] = s[m]; }); }; var lastOfPathSeparatorRegExp = /###/g; var cleanKey = (key) => key && key.includes("###") ? key.replace(lastOfPathSeparatorRegExp, ".") : key; var canNotTraverseDeeper = (object) => !object || isString$1(object); var getLastOfPath = (object, path, Empty) => { const stack = !isString$1(path) ? path : path.split("."); let stackIndex = 0; while (stackIndex < stack.length - 1) { if (canNotTraverseDeeper(object)) return {}; const key = cleanKey(stack[stackIndex]); if (!object[key] && Empty) object[key] = new Empty(); if (Object.prototype.hasOwnProperty.call(object, key)) object = object[key]; else object = {}; ++stackIndex; } if (canNotTraverseDeeper(object)) return {}; return { obj: object, k: cleanKey(stack[stackIndex]) }; }; var setPath = (object, path, newValue) => { const { obj, k } = getLastOfPath(object, path, Object); if (obj !== void 0 || path.length === 1) { obj[k] = newValue; return; } let e = path[path.length - 1]; let p = path.slice(0, path.length - 1); let last = getLastOfPath(object, p, Object); while (last.obj === void 0 && p.length) { e = `${p[p.length - 1]}.${e}`; p = p.slice(0, p.length - 1); last = getLastOfPath(object, p, Object); if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") last.obj = void 0; } last.obj[`${last.k}.${e}`] = newValue; }; var pushPath = (object, path, newValue, concat) => { const { obj, k } = getLastOfPath(object, path, Object); obj[k] = obj[k] || []; obj[k].push(newValue); }; var getPath = (object, path) => { const { obj, k } = getLastOfPath(object, path); if (!obj) return void 0; if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0; return obj[k]; }; var getPathWithDefaults = (data, defaultData, key) => { const value = getPath(data, key); if (value !== void 0) return value; return getPath(defaultData, key); }; var deepExtend = (target, source, overwrite) => { for (const prop in source) if (prop !== "__proto__" && prop !== "constructor") if (prop in target) if (isString$1(target[prop]) || target[prop] instanceof String || isString$1(source[prop]) || source[prop] instanceof String) { if (overwrite) target[prop] = source[prop]; } else deepExtend(target[prop], source[prop], overwrite); else target[prop] = source[prop]; return target; }; var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); var _entityMap = { "&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/" }; var escape$2 = (data) => { if (isString$1(data)) return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]); return data; }; var RegExpCache = class { constructor(capacity) { this.capacity = capacity; this.regExpMap = new Map(); this.regExpQueue = []; } getRegExp(pattern) { const regExpFromCache = this.regExpMap.get(pattern); if (regExpFromCache !== void 0) return regExpFromCache; const regExpNew = new RegExp(pattern); if (this.regExpQueue.length === this.capacity) this.regExpMap.delete(this.regExpQueue.shift()); this.regExpMap.set(pattern, regExpNew); this.regExpQueue.push(pattern); return regExpNew; } }; var chars = [ " ", ",", "?", "!", ";" ]; var looksLikeObjectPathRegExpCache = new RegExpCache(20); var looksLikeObjectPath = (key, nsSeparator, keySeparator) => { nsSeparator = nsSeparator || ""; keySeparator = keySeparator || ""; const possibleChars = chars.filter((c) => !nsSeparator.includes(c) && !keySeparator.includes(c)); if (possibleChars.length === 0) return true; const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`); let matched = !r.test(key); if (!matched) { const ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) matched = true; } return matched; }; var deepFind = (obj, path, keySeparator = ".") => { if (!obj) return void 0; if (obj[path]) { if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0; return obj[path]; } const tokens = path.split(keySeparator); let current = obj; for (let i = 0; i < tokens.length;) { if (!current || typeof current !== "object") return; let next; let nextPath = ""; for (let j = i; j < tokens.length; ++j) { if (j !== i) nextPath += keySeparator; nextPath += tokens[j]; next = current[nextPath]; if (next !== void 0) { if ([ "string", "number", "boolean" ].includes(typeof next) && j < tokens.length - 1) continue; i += j - i + 1; break; } } current = next; } return current; }; var getCleanedCode = (code) => code?.replace(/_/g, "-"); var consoleLogger = { type: "logger", log(args) { this.output("log", args); }, warn(args) { this.output("warn", args); }, error(args) { this.output("error", args); }, output(type, args) { console?.[type]?.apply?.(console, args); } }; var baseLogger = new class Logger { constructor(concreteLogger, options = {}) { this.init(concreteLogger, options); } init(concreteLogger, options = {}) { this.prefix = options.prefix || "i18next:"; this.logger = concreteLogger || consoleLogger; this.options = options; this.debug = options.debug; } log(...args) { return this.forward(args, "log", "", true); } warn(...args) { return this.forward(args, "warn", "", true); } error(...args) { return this.forward(args, "error", ""); } deprecate(...args) { return this.forward(args, "warn", "WARNING DEPRECATED: ", true); } forward(args, lvl, prefix, debugOnly) { if (debugOnly && !this.debug) return null; args = args.map((a) => isString$1(a) ? a.replace(/[\r\n\x00-\x1F\x7F]/g, " ") : a); if (isString$1(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`; return this.logger[lvl](args); } create(moduleName) { return new Logger(this.logger, { prefix: `${this.prefix}:${moduleName}:`, ...this.options }); } clone(options) { options = options || this.options; options.prefix = options.prefix || this.prefix; return new Logger(this.logger, options); } }(); var EventEmitter = class { constructor() { this.observers = {}; } on(events, listener) { events.split(" ").forEach((event) => { if (!this.observers[event]) this.observers[event] = new Map(); const numListeners = this.observers[event].get(listener) || 0; this.observers[event].set(listener, numListeners + 1); }); return this; } off(event, listener) { if (!this.observers[event]) return; if (!listener) { delete this.observers[event]; return; } this.observers[event].delete(listener); } once(event, listener) { const wrapper = (...args) => { listener(...args); this.off(event, wrapper); }; this.on(event, wrapper); return this; } emit(event, ...args) { if (this.observers[event]) Array.from(this.observers[event].entries()).forEach(([observer, numTimesAdded]) => { for (let i = 0; i < numTimesAdded; i++) observer(...args); }); if (this.observers["*"]) Array.from(this.observers["*"].entries()).forEach(([observer, numTimesAdded]) => { for (let i = 0; i < numTimesAdded; i++) observer(event, ...args); }); } }; var ResourceStore = class extends EventEmitter { constructor(data, options = { ns: ["translation"], defaultNS: "translation" }) { super(); this.data = data || {}; this.options = options; if (this.options.keySeparator === void 0) this.options.keySeparator = "."; if (this.options.ignoreJSONStructure === void 0) this.options.ignoreJSONStructure = true; } addNamespaces(ns) { if (!this.options.ns.includes(ns)) this.options.ns.push(ns); } removeNamespaces(ns) { const index = this.options.ns.indexOf(ns); if (index > -1) this.options.ns.splice(index, 1); } getResource(lng, ns, key, options = {}) { const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; let path; if (lng.includes(".")) path = lng.split("."); else { path = [lng, ns]; if (key) if (Array.isArray(key)) path.push(...key); else if (isString$1(key) && keySeparator) path.push(...key.split(keySeparator)); else path.push(key); } const result = getPath(this.data, path); if (!result && !ns && !key && lng.includes(".")) { lng = path[0]; ns = path[1]; key = path.slice(2).join("."); } if (result || !ignoreJSONStructure || !isString$1(key)) return result; return deepFind(this.data?.[lng]?.[ns], key, keySeparator); } addResource(lng, ns, key, value, options = { silent: false }) { const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; let path = [lng, ns]; if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.includes(".")) { path = lng.split("."); value = ns; ns = path[1]; } this.addNamespaces(ns); setPath(this.data, path, value); if (!options.silent) this.emit("added", lng, ns, key, value); } addResources(lng, ns, resources, options = { silent: false }) { for (const m in resources) if (isString$1(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], { silent: true }); if (!options.silent) this.emit("added", lng, ns, resources); } addResourceBundle(lng, ns, resources, deep, overwrite, options = { silent: false, skipCopy: false }) { let path = [lng, ns]; if (lng.includes(".")) { path = lng.split("."); deep = resources; resources = ns; ns = path[1]; } this.addNamespaces(ns); let pack = getPath(this.data, path) || {}; if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources)); if (deep) deepExtend(pack, resources, overwrite); else pack = { ...pack, ...resources }; setPath(this.data, path, pack); if (!options.silent) this.emit("added", lng, ns, resources); } removeResourceBundle(lng, ns) { if (this.hasResourceBundle(lng, ns)) delete this.data[lng][ns]; this.removeNamespaces(ns); this.emit("removed", lng, ns); } hasResourceBundle(lng, ns) { return this.getResource(lng, ns) !== void 0; } getResourceBundle(lng, ns) { if (!ns) ns = this.options.defaultNS; return this.getResource(lng, ns); } getDataByLanguage(lng) { return this.data[lng]; } hasLanguageSomeTranslations(lng) { const data = this.getDataByLanguage(lng); return !!(data && Object.keys(data) || []).find((v) => data[v] && Object.keys(data[v]).length > 0); } toJSON() { return this.data; } }; var postProcessor = { processors: {}, addPostProcessor(module) { this.processors[module.name] = module; }, handle(processors, value, key, options, translator) { processors.forEach((processor) => { value = this.processors[processor]?.process(value, key, options, translator) ?? value; }); return value; } }; var PATH_KEY = Symbol("i18next/PATH_KEY"); function createProxy() { const state = []; const handler = Object.create(null); let proxy; handler.get = (target, key) => { proxy?.revoke?.(); if (key === PATH_KEY) return state; state.push(key); proxy = Proxy.revocable(target, handler); return proxy.proxy; }; return Proxy.revocable(Object.create(null), handler).proxy; } function keysFromSelector(selector, opts) { const { [PATH_KEY]: path } = selector(createProxy()); const keySeparator = opts?.keySeparator ?? "."; const nsSeparator = opts?.nsSeparator ?? ":"; const strict = opts?.enableSelector === "strict"; if (path.length > 1 && nsSeparator) { const ns = opts?.ns; const nsList = strict ? Array.isArray(ns) ? ns : ns ? [ns] : null : Array.isArray(ns) ? ns : null; if (nsList) { if ((strict ? nsList : nsList.length > 1 ? nsList.slice(1) : []).includes(path[0])) return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`; } } return path.join(keySeparator); } var shouldHandleAsObject = (res) => !isString$1(res) && typeof res !== "boolean" && typeof res !== "number"; var Translator = class Translator extends EventEmitter { constructor(services, options = {}) { super(); copy([ "resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils" ], services, this); this.options = options; if (this.options.keySeparator === void 0) this.options.keySeparator = "."; this.logger = baseLogger.create("translator"); this.checkedLoadedFor = {}; } changeLanguage(lng) { if (lng) this.language = lng; } exists(key, o = { interpolation: {} }) { const opt = { ...o }; if (key == null) return false; const resolved = this.resolve(key, opt); if (resolved?.res === void 0) return false; const isObject = shouldHandleAsObject(resolved.res); if (opt.returnObjects === false && isObject) return false; return true; } extractFromKey(key, opt) { let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; if (nsSeparator === void 0) nsSeparator = ":"; const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; let namespaces = opt.ns || this.options.defaultNS || []; const wouldCheckForNsInKey = nsSeparator && key.includes(nsSeparator); const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); if (wouldCheckForNsInKey && !seemsNaturalLanguage) { const m = key.match(this.interpolator.nestingRegexp); if (m && m.length > 0) return { key, namespaces: isString$1(namespaces) ? [namespaces] : namespaces }; const parts = key.split(nsSeparator); if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.includes(parts[0])) namespaces = parts.shift(); key = parts.join(keySeparator); } return { key, namespaces: isString$1(namespaces) ? [namespaces] : namespaces }; } translate(keys, o, lastKey) { let opt = typeof o === "object" ? { ...o } : o; if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) opt = this.options.overloadTranslationOptionHandler(arguments); if (typeof opt === "object") opt = { ...opt }; if (!opt) opt = {}; if (keys == null) return ""; if (typeof keys === "function") keys = keysFromSelector(keys, { ...this.options, ...opt }); if (!Array.isArray(keys)) keys = [String(keys)]; keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, { ...this.options, ...opt }) : String(k)); const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails; const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; const { key, namespaces } = this.extractFromKey(keys[keys.length - 1], opt); const namespace = namespaces[namespaces.length - 1]; let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; if (nsSeparator === void 0) nsSeparator = ":"; const lng = opt.lng || this.language; const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; if (lng?.toLowerCase() === "cimode") { if (appendNamespaceToCIMode) { if (returnDetails) return { res: `${namespace}${nsSeparator}${key}`, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace, usedParams: this.getUsedParamsDetails(opt) }; return `${namespace}${nsSeparator}${key}`; } if (returnDetails) return { res: key, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace, usedParams: this.getUsedParamsDetails(opt) }; return key; } const resolved = this.resolve(keys, opt); let res = resolved?.res; const resUsedKey = resolved?.usedKey || key; const resExactUsedKey = resolved?.exactUsedKey || key; const noObject = [ "[object Number]", "[object Function]", "[object RegExp]" ]; const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays; const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; const needsPluralHandling = opt.count !== void 0 && !isString$1(opt.count); const hasDefaultValue = Translator.hasDefaultValue(opt); const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : ""; const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { ordinal: false }) : ""; const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue; let resForObjHndl = res; if (handleAsObjectInI18nFormat && !res && hasDefaultValue) resForObjHndl = defaultValue; const handleAsObject = shouldHandleAsObject(resForObjHndl); const resType = Object.prototype.toString.apply(resForObjHndl); if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && !noObject.includes(resType) && !(isString$1(joinArrays) && Array.isArray(resForObjHndl))) { if (!opt.returnObjects && !this.options.returnObjects) { if (!this.options.returnedObjectHandler) this.logger.warn("accessing an object - but returnObjects options is not enabled!"); const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, { ...opt, ns: namespaces }) : `key '${key} (${this.language})' returned an object instead of string.`; if (returnDetails) { resolved.res = r; resolved.usedParams = this.getUsedParamsDetails(opt); return resolved; } return r; } if (keySeparator) { const resTypeIsArray = Array.isArray(resForObjHndl); const copy = resTypeIsArray ? [] : {}; const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; for (const m in resForObjHndl) if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) { const deepKey = `${newKeyToUse}${keySeparator}${m}`; if (hasDefaultValue && !res) copy[m] = this.translate(deepKey, { ...opt, defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0, joinArrays: false, ns: namespaces }); else copy[m] = this.translate(deepKey, { ...opt, joinArrays: false, ns: namespaces }); if (copy[m] === deepKey) copy[m] = resForObjHndl[m]; } res = copy; } } else if (handleAsObjectInI18nFormat && isString$1(joinArrays) && Array.isArray(res)) { res = res.join(joinArrays); if (res) res = this.extendTranslation(res, keys, opt, lastKey); } else { let usedDefault = false; let usedKey = false; if (!this.isValidLookup(res) && hasDefaultValue) { usedDefault = true; res = defaultValue; } if (!this.isValidLookup(res)) { usedKey = true; res = key; } const resForMissing = (opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey) && usedKey ? void 0 : res; const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; if (usedKey || usedDefault || updateMissing) { this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, needsPluralHandling && !updateMissing ? `${key}${this.pluralResolver.getSuffix(lng, opt.count, opt)}` : key, updateMissing ? defaultValue : res); if (keySeparator) { const fk = this.resolve(key, { ...opt, keySeparator: false }); if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format."); } let lngs = []; const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language); if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) for (let i = 0; i < fallbackLngs.length; i++) lngs.push(fallbackLngs[i]); else if (this.options.saveMissingTo === "all") lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language); else lngs.push(opt.lng || this.language); const send = (l, k, specificDefaultValue) => { const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; if (this.options.missingKeyHandler) this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt); else if (this.backendConnector?.saveMissing) this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt); this.emit("missingKey", l, namespace, k, res); }; if (this.options.saveMissing) if (this.options.saveMissingPlurals && needsPluralHandling) lngs.forEach((language) => { const suffixes = this.pluralResolver.getSuffixes(language, opt); if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && !suffixes.includes(`${this.options.pluralSeparator}zero`)) suffixes.push(`${this.options.pluralSeparator}zero`); suffixes.forEach((suffix) => { send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue); }); }); else send(lngs, key, defaultValue); } res = this.extendTranslation(res, keys, opt, resolved, lastKey); if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}${nsSeparator}${key}`; if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt); } if (returnDetails) { resolved.res = res; resolved.usedParams = this.getUsedParamsDetails(opt); return resolved; } return res; } extendTranslation(res, key, opt, resolved, lastKey) { if (this.i18nFormat?.parse) res = this.i18nFormat.parse(res, { ...this.options.interpolation.defaultVariables, ...opt }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved }); else if (!opt.skipInterpolation) { if (opt.interpolation) this.interpolator.init({ ...opt, interpolation: { ...this.options.interpolation, ...opt.interpolation } }); const skipOnVariables = isString$1(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); let nestBef; if (skipOnVariables) { const nb = res.match(this.interpolator.nestingRegexp); nestBef = nb && nb.length; } let data = opt.replace && !isString$1(opt.replace) ? opt.replace : opt; if (this.options.interpolation.defaultVariables) data = { ...this.options.interpolation.defaultVariables, ...data }; res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt); if (skipOnVariables) { const na = res.match(this.interpolator.nestingRegexp); const nestAft = na && na.length; if (nestBef < nestAft) opt.nest = false; } if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng; if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => { if (lastKey?.[0] === args[0] && !opt.context) { this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`); return null; } return this.translate(...args, key); }, opt); if (opt.interpolation) this.interpolator.reset(); } const postProcess = opt.postProcess || this.options.postProcess; const postProcessorNames = isString$1(postProcess) ? [postProcess] : postProcess; if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? { i18nResolved: { ...resolved, usedParams: this.getUsedParamsDetails(opt) }, ...opt } : opt, this); return res; } resolve(keys, opt = {}) { let found; let usedKey; let exactUsedKey; let usedLng; let usedNS; if (isString$1(keys)) keys = [keys]; if (Array.isArray(keys)) keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, { ...this.options, ...opt }) : k); keys.forEach((k) => { if (this.isValidLookup(found)) return; const extracted = this.extractFromKey(k, opt); const key = extracted.key; usedKey = key; let namespaces = extracted.namespaces; if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS); const needsPluralHandling = opt.count !== void 0 && !isString$1(opt.count); const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; const needsContextHandling = opt.context !== void 0 && (isString$1(opt.context) || typeof opt.context === "number") && opt.context !== ""; const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng); namespaces.forEach((ns) => { if (this.isValidLookup(found)) return; usedNS = ns; if (!this.checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) { this.checkedLoadedFor[`${codes[0]}-${ns}`] = true; this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); } codes.forEach((code) => { if (this.isValidLookup(found)) return; usedLng = code; const finalKeys = [key]; if (this.i18nFormat?.addLookupKeys) this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt); else { let pluralSuffix; if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt); const zeroSuffix = `${this.options.pluralSeparator}zero`; const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`; if (needsPluralHandling) { if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); finalKeys.push(key + pluralSuffix); if (needsZeroSuffixLookup) finalKeys.push(key + zeroSuffix); } if (needsContextHandling) { const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`; finalKeys.push(contextKey); if (needsPluralHandling) { if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); finalKeys.push(contextKey + pluralSuffix); if (needsZeroSuffixLookup) finalKeys.push(contextKey + zeroSuffix); } } } let possibleKey; while (possibleKey = finalKeys.pop()) if (!this.isValidLookup(found)) { exactUsedKey = possibleKey; found = this.getResource(code, ns, possibleKey, opt); } }); }); }); return { res: found, usedKey, exactUsedKey, usedLng, usedNS }; } isValidLookup(res) { return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ""); } getResource(code, ns, key, options = {}) { if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options); return this.resourceStore.getResource(code, ns, key, options); } getUsedParamsDetails(options = {}) { const optionsKeys = [ "defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation" ]; const useOptionsReplaceForData = options.replace && !isString$1(options.replace); let data = useOptionsReplaceForData ? options.replace : options; if (useOptionsReplaceForData && typeof options.count !== "undefined") data.count = options.count; if (this.options.interpolation.defaultVariables) data = { ...this.options.interpolation.defaultVariables, ...data }; if (!useOptionsReplaceForData) { data = { ...data }; for (const key of optionsKeys) delete data[key]; } return data; } static hasDefaultValue(options) { const prefix = "defaultValue"; for (const option in options) if (Object.prototype.hasOwnProperty.call(options, option) && option.startsWith(prefix) && void 0 !== options[option]) return true; return false; } }; var LanguageUtil = class { constructor(options) { this.options = options; this.supportedLngs = this.options.supportedLngs || false; this.logger = baseLogger.create("languageUtils"); } getScriptPartFromCode(code) { code = getCleanedCode(code); if (!code || !code.includes("-")) return null; const p = code.split("-"); if (p.length === 2) return null; p.pop(); if (p[p.length - 1].toLowerCase() === "x") return null; return this.formatLanguageCode(p.join("-")); } getLanguagePartFromCode(code) { code = getCleanedCode(code); if (!code || !code.includes("-")) return code; const p = code.split("-"); return this.formatLanguageCode(p[0]); } formatLanguageCode(code) { if (isString$1(code) && code.includes("-")) { let formattedCode; try { formattedCode = Intl.getCanonicalLocales(code)[0]; } catch (e) {} if (formattedCode && this.options.lowerCaseLng) formattedCode = formattedCode.toLowerCase(); if (formattedCode) return formattedCode; if (this.options.lowerCaseLng) return code.toLowerCase(); return code; } return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; } isSupportedCode(code) { if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) code = this.getLanguagePartFromCode(code); return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.includes(code); } getBestMatchFromCodes(codes) { if (!codes) return null; let found; codes.forEach((code) => { if (found) return; const cleanedLng = this.formatLanguageCode(code); if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng; }); if (!found && this.options.supportedLngs) codes.forEach((code) => { if (found) return; const lngScOnly = this.getScriptPartFromCode(code); if (this.isSupportedCode(lngScOnly)) return found = lngScOnly; const lngOnly = this.getLanguagePartFromCode(code); if (this.isSupportedCode(lngOnly)) return found = lngOnly; found = this.options.supportedLngs.find((supportedLng) => { if (supportedLng === lngOnly) return true; if (!supportedLng.includes("-") && !lngOnly.includes("-")) return false; if (supportedLng.includes("-") && !lngOnly.includes("-") && supportedLng.slice(0, supportedLng.indexOf("-")) === lngOnly) return true; if (supportedLng.startsWith(lngOnly) && lngOnly.length > 1) return true; return false; }); }); if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0]; return found; } getFallbackCodes(fallbacks, code) { if (!fallbacks) return []; if (typeof fallbacks === "function") fallbacks = fallbacks(code); if (isString$1(fallbacks)) fallbacks = [fallbacks]; if (Array.isArray(fallbacks)) return fallbacks; if (!code) return fallbacks.default || []; let found = fallbacks[code]; if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; if (!found) found = fallbacks[this.formatLanguageCode(code)]; if (!found) found = fallbacks[this.getLanguagePartFromCode(code)]; if (!found) found = fallbacks.default; return found || []; } toResolveHierarchy(code, fallbackCode) { const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code); const codes = []; const addCode = (c) => { if (!c) return; if (this.isSupportedCode(c)) codes.push(c); else this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`); }; if (isString$1(code) && (code.includes("-") || code.includes("_"))) { if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code)); if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code)); if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code)); } else if (isString$1(code)) addCode(this.formatLanguageCode(code)); fallbackCodes.forEach((fc) => { if (!codes.includes(fc)) addCode(this.formatLanguageCode(fc)); }); return codes; } }; var suffixesOrder = { zero: 0, one: 1, two: 2, few: 3, many: 4, other: 5 }; var dummyRule = { select: (count) => count === 1 ? "one" : "other", resolvedOptions: () => ({ pluralCategories: ["one", "other"] }) }; var PluralResolver = class { constructor(languageUtils, options = {}) { this.languageUtils = languageUtils; this.options = options; this.logger = baseLogger.create("pluralResolver"); this.pluralRulesCache = {}; } clearCache() { this.pluralRulesCache = {}; } getRule(code, options = {}) { const cleanedCode = getCleanedCode(code === "dev" ? "en" : code); const type = options.ordinal ? "ordinal" : "cardinal"; const cacheKey = JSON.stringify({ cleanedCode, type }); if (cacheKey in this.pluralRulesCache) return this.pluralRulesCache[cacheKey]; let rule; try { rule = new Intl.PluralRules(cleanedCode, { type }); } catch (err) { if (typeof Intl === "undefined") { this.logger.error("No Intl support, please use an Intl polyfill!"); return dummyRule; } if (!code.match(/-|_/)) return dummyRule; const lngPart = this.languageUtils.getLanguagePartFromCode(code); rule = this.getRule(lngPart, options); } this.pluralRulesCache[cacheKey] = rule; return rule; } needsPlural(code, options = {}) { let rule = this.getRule(code, options); if (!rule) rule = this.getRule("dev", options); return rule?.resolvedOptions().pluralCategories.length > 1; } getPluralFormsOfKey(code, key, options = {}) { return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`); } getSuffixes(code, options = {}) { let rule = this.getRule(code, options); if (!rule) rule = this.getRule("dev", options); if (!rule) return []; return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`); } getSuffix(code, count, options = {}) { const rule = this.getRule(code, options); if (rule) return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`; this.logger.warn(`no plural rule found for: ${code}`); return this.getSuffix("dev", count, options); } }; var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => { let path = getPathWithDefaults(data, defaultData, key); if (!path && ignoreJSONStructure && isString$1(key)) { path = deepFind(data, key, keySeparator); if (path === void 0) path = deepFind(defaultData, key, keySeparator); } return path; }; var regexSafe = (val) => val.replace(/\$/g, "$$$$"); var Interpolator = class { constructor(options = {}) { this.logger = baseLogger.create("interpolator"); this.options = options; this.format = options?.interpolation?.format || ((value) => value); this.init(options); } init(options = {}) { if (!options.interpolation) options.interpolation = { escapeValue: true }; const { escape: escape$1, escapeValue, useRawValueToEscape, prefix, prefixEscaped, suffix, suffixEscaped, formatSeparator, unescapeSuffix, unescapePrefix, nestingPrefix, nestingPrefixEscaped, nestingSuffix, nestingSuffixEscaped, nestingOptionsSeparator, maxReplaces, alwaysFormat } = options.interpolation; this.escape = escape$1 !== void 0 ? escape$1 : escape$2; this.escapeValue = escapeValue !== void 0 ? escapeValue : true; this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false; this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{"; this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}"; this.formatSeparator = formatSeparator || ","; this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix ? regexEscape(unescapePrefix) : "-"; this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix ? regexEscape(unescapeSuffix) : ""; this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t("); this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")"); this.nestingOptionsSeparator = nestingOptionsSeparator || ","; this.maxReplaces = maxReplaces || 1e3; this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false; this.resetRegExp(); } reset() { if (this.options) this.init(this.options); } resetRegExp() { const getOrResetRegExp = (existingRegExp, pattern) => { if (existingRegExp?.source === pattern) { existingRegExp.lastIndex = 0; return existingRegExp; } return new RegExp(pattern, "g"); }; this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`); this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`); this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`); } interpolate(str, data, lng, options) { let match; let value; let replaces; const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; const handleFormat = (key) => { if (!key.includes(this.formatSeparator)) { const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure); return this.alwaysFormat ? this.format(path, void 0, lng, { ...options, ...data, interpolationkey: key }) : path; } const p = key.split(this.formatSeparator); const k = p.shift().trim(); const f = p.join(this.formatSeparator).trim(); return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, { ...options, ...data, interpolationkey: k }); }; this.resetRegExp(); if (!this.escapeValue && typeof str === "string" && /\$t\([^)]*\{[^}]*\{\{/.test(str)) this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true."); const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler; const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; [{ regex: this.regexpUnescape, safeValue: (val) => regexSafe(val) }, { regex: this.regexp, safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val) }].forEach((todo) => { replaces = 0; while (match = todo.regex.exec(str)) { const matchedVar = match[1].trim(); value = handleFormat(matchedVar); if (value === void 0) if (typeof missingInterpolationHandler === "function") { const temp = missingInterpolationHandler(str, match, options); value = isString$1(temp) ? temp : ""; } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) value = ""; else if (skipOnVariables) { value = match[0]; continue; } else { this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`); value = ""; } else if (!isString$1(value) && !this.useRawValueToEscape) value = makeString(value); const safeValue = todo.safeValue(value); str = str.replace(match[0], safeValue); if (skipOnVariables) { todo.regex.lastIndex += value.length; todo.regex.lastIndex -= match[0].length; } else todo.regex.lastIndex = 0; replaces++; if (replaces >= this.maxReplaces) break; } }); return str; } nest(str, fc, options = {}) { let match; let value; let clonedOptions; const handleHasOptions = (key, inheritedOptions) => { const sep = this.nestingOptionsSeparator; if (!key.includes(sep)) return key; const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`)); let optionsString = `{${c[1]}`; key = c[0]; optionsString = this.interpolate(optionsString, clonedOptions); const matchedSingleQuotes = optionsString.match(/'/g); const matchedDoubleQuotes = optionsString.match(/"/g); if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) optionsString = optionsString.replace(/'/g, "\""); try { clonedOptions = JSON.parse(optionsString); if (inheritedOptions) clonedOptions = { ...inheritedOptions, ...clonedOptions }; } catch (e) { this.logger.warn(`failed parsing options string in nesting for key ${key}`, e); return `${key}${sep}${optionsString}`; } if (clonedOptions.defaultValue && clonedOptions.defaultValue.includes(this.prefix)) delete clonedOptions.defaultValue; return key; }; while (match = this.nestingRegexp.exec(str)) { let formatters = []; clonedOptions = { ...options }; clonedOptions = clonedOptions.replace && !isString$1(clonedOptions.replace) ? clonedOptions.replace : clonedOptions; clonedOptions.applyPostProcessor = false; delete clonedOptions.defaultValue; const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator); if (keyEndIndex !== -1) { formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean); match[1] = match[1].slice(0, keyEndIndex); } value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); if (value && match[0] === str && !isString$1(value)) return value; if (!isString$1(value)) value = makeString(value); if (!value) { this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`); value = ""; } if (formatters.length) value = formatters.reduce((v, f) => this.format(v, f, options.lng, { ...options, interpolationkey: match[1].trim() }), value.trim()); str = str.replace(match[0], value); this.regexp.lastIndex = 0; } return str; } }; var parseFormatStr = (formatStr) => { let formatName = formatStr.toLowerCase().trim(); const formatOptions = {}; if (formatStr.includes("(")) { const p = formatStr.split("("); formatName = p[0].toLowerCase().trim(); const optStr = p[1].slice(0, -1); if (formatName === "currency" && !optStr.includes(":")) { if (!formatOptions.currency) formatOptions.currency = optStr.trim(); } else if (formatName === "relativetime" && !optStr.includes(":")) { if (!formatOptions.range) formatOptions.range = optStr.trim(); } else optStr.split(";").forEach((opt) => { if (opt) { const [key, ...rest] = opt.split(":"); const val = rest.join(":").trim().replace(/^'+|'+$/g, ""); const trimmedKey = key.trim(); if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val; if (val === "false") formatOptions[trimmedKey] = false; if (val === "true") formatOptions[trimmedKey] = true; if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10); } }); } return { formatName, formatOptions }; }; var createCachedFormatter = (fn) => { const cache = {}; return (v, l, o) => { let optForCache = o; if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) optForCache = { ...optForCache, [o.interpolationkey]: void 0 }; const key = l + JSON.stringify(optForCache); let frm = cache[key]; if (!frm) { frm = fn(getCleanedCode(l), o); cache[key] = frm; } return frm(v); }; }; var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v); var Formatter = class { constructor(options = {}) { this.logger = baseLogger.create("formatter"); this.options = options; this.init(options); } init(services, options = { interpolation: {} }) { this.formatSeparator = options.interpolation.formatSeparator || ","; const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter; this.formats = { number: cf((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt }); return (val) => formatter.format(val); }), currency: cf((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt, style: "currency" }); return (val) => formatter.format(val); }), datetime: cf((lng, opt) => { const formatter = new Intl.DateTimeFormat(lng, { ...opt }); return (val) => formatter.format(val); }), relativetime: cf((lng, opt) => { const formatter = new Intl.RelativeTimeFormat(lng, { ...opt }); return (val) => formatter.format(val, opt.range || "day"); }), list: cf((lng, opt) => { const formatter = new Intl.ListFormat(lng, { ...opt }); return (val) => formatter.format(val); }) }; } add(name, fc) { this.formats[name.toLowerCase().trim()] = fc; } addCached(name, fc) { this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); } format(value, format, lng, options = {}) { if (!format) return value; if (value == null) return value; const formats = format.split(this.formatSeparator); if (formats.length > 1 && formats[0].indexOf("(") > 1 && !formats[0].includes(")") && formats.find((f) => f.includes(")"))) { const lastIndex = formats.findIndex((f) => f.includes(")")); formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator); } return formats.reduce((mem, f) => { const { formatName, formatOptions } = parseFormatStr(f); if (this.formats[formatName]) { let formatted = mem; try { const valOptions = options?.formatParams?.[options.interpolationkey] || {}; const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; formatted = this.formats[formatName](mem, l, { ...formatOptions, ...options, ...valOptions }); } catch (error) { this.logger.warn(error); } return formatted; } else this.logger.warn(`there was no format function for ${formatName}`); return mem; }, value); } }; var removePending = (q, name) => { if (q.pending[name] !== void 0) { delete q.pending[name]; q.pendingCount--; } }; var Connector = class extends EventEmitter { constructor(backend, store, services, options = {}) { super(); this.backend = backend; this.store = store; this.services = services; this.languageUtils = services.languageUtils; this.options = options; this.logger = baseLogger.create("backendConnector"); this.waitingReads = []; this.maxParallelReads = options.maxParallelReads || 10; this.readingCalls = 0; this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; this.state = {}; this.queue = []; this.backend?.init?.(services, options.backend, options); } queueLoad(languages, namespaces, options, callback) { const toLoad = {}; const pending = {}; const toLoadLanguages = {}; const toLoadNamespaces = {}; languages.forEach((lng) => { let hasAllNamespaces = true; namespaces.forEach((ns) => { const name = `${lng}|${ns}`; if (!options.reload && this.store.hasResourceBundle(lng, ns)) this.state[name] = 2; else if (this.state[name] < 0); else if (this.state[name] === 1) { if (pending[name] === void 0) pending[name] = true; } else { this.state[name] = 1; hasAllNamespaces = false; if (pending[name] === void 0) pending[name] = true; if (toLoad[name] === void 0) toLoad[name] = true; if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true; } }); if (!hasAllNamespaces) toLoadLanguages[lng] = true; }); if (Object.keys(toLoad).length || Object.keys(pending).length) this.queue.push({ pending, pendingCount: Object.keys(pending).length, loaded: {}, errors: [], callback }); return { toLoad: Object.keys(toLoad), pending: Object.keys(pending), toLoadLanguages: Object.keys(toLoadLanguages), toLoadNamespaces: Object.keys(toLoadNamespaces) }; } loaded(name, err, data) { const s = name.split("|"); const lng = s[0]; const ns = s[1]; if (err) this.emit("failedLoading", lng, ns, err); if (!err && data) this.store.addResourceBundle(lng, ns, data, void 0, void 0, { skipCopy: true }); this.state[name] = err ? -1 : 2; if (err && data) this.state[name] = 0; const loaded = {}; this.queue.forEach((q) => { pushPath(q.loaded, [lng], ns); removePending(q, name); if (err) q.errors.push(err); if (q.pendingCount === 0 && !q.done) { Object.keys(q.loaded).forEach((l) => { if (!loaded[l]) loaded[l] = {}; const loadedKeys = q.loaded[l]; if (loadedKeys.length) loadedKeys.forEach((n) => { if (loaded[l][n] === void 0) loaded[l][n] = true; }); }); q.done = true; if (q.errors.length) q.callback(q.errors); else q.callback(); } }); this.emit("loaded", loaded); this.queue = this.queue.filter((q) => !q.done); } read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) { if (!lng.length) return callback(null, {}); if (this.readingCalls >= this.maxParallelReads) { this.waitingReads.push({ lng, ns, fcName, tried, wait, callback }); return; } this.readingCalls++; const resolver = (err, data) => { this.readingCalls--; if (this.waitingReads.length > 0) { const next = this.waitingReads.shift(); this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); } if (err && data && tried < this.maxRetries) { setTimeout(() => { this.read(lng, ns, fcName, tried + 1, wait * 2, callback); }, wait); return; } callback(err, data); }; const fc = this.backend[fcName].bind(this.backend); if (fc.length === 2) { try { const r = fc(lng, ns); if (r && typeof r.then === "function") r.then((data) => resolver(null, data)).catch(resolver); else resolver(null, r); } catch (err) { resolver(err); } return; } return fc(lng, ns, resolver); } prepareLoading(languages, namespaces, options = {}, callback) { if (!this.backend) { this.logger.warn("No backend was added via i18next.use. Will not load resources."); return callback && callback(); } if (isString$1(languages)) languages = this.languageUtils.toResolveHierarchy(languages); if (isString$1(namespaces)) namespaces = [namespaces]; const toLoad = this.queueLoad(languages, namespaces, options, callback); if (!toLoad.toLoad.length) { if (!toLoad.pending.length) callback(); return null; } toLoad.toLoad.forEach((name) => { this.loadOne(name); }); } load(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, {}, callback); } reload(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, { reload: true }, callback); } loadOne(name, prefix = "") { const s = name.split("|"); const lng = s[0]; const ns = s[1]; this.read(lng, ns, "read", void 0, void 0, (err, data) => { if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err); if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data); this.loaded(name, err, data); }); } saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) { if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) { this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); return; } if (key === void 0 || key === null || key === "") return; if (this.backend?.create) { const opts = { ...options, isUpdate }; const fc = this.backend.create.bind(this.backend); if (fc.length < 6) try { let r; if (fc.length === 5) r = fc(languages, namespace, key, fallbackValue, opts); else r = fc(languages, namespace, key, fallbackValue); if (r && typeof r.then === "function") r.then((data) => clb(null, data)).catch(clb); else clb(null, r); } catch (err) { clb(err); } else fc(languages, namespace, key, fallbackValue, clb, opts); } if (!languages || !languages[0]) return; this.store.addResource(languages[0], namespace, key, fallbackValue); } }; var get = () => ({ debug: false, initAsync: true, ns: ["translation"], defaultNS: ["translation"], fallbackLng: ["dev"], fallbackNS: false, supportedLngs: false, nonExplicitSupportedLngs: false, load: "all", preload: false, keySeparator: ".", nsSeparator: ":", pluralSeparator: "_", contextSeparator: "_", enableSelector: false, partialBundledLanguages: false, saveMissing: false, updateMissing: false, saveMissingTo: "fallback", saveMissingPlurals: true, missingKeyHandler: false, missingInterpolationHandler: false, postProcess: false, postProcessPassResolved: false, returnNull: false, returnEmptyString: true, returnObjects: false, joinArrays: false, returnedObjectHandler: false, parseMissingKeyHandler: false, appendNamespaceToMissingKey: false, appendNamespaceToCIMode: false, overloadTranslationOptionHandler: (args) => { let ret = {}; if (typeof args[1] === "object") ret = args[1]; if (isString$1(args[1])) ret.defaultValue = args[1]; if (isString$1(args[2])) ret.tDescription = args[2]; if (typeof args[2] === "object" || typeof args[3] === "object") { const options = args[3] || args[2]; Object.keys(options).forEach((key) => { ret[key] = options[key]; }); } return ret; }, interpolation: { escapeValue: true, prefix: "{{", suffix: "}}", formatSeparator: ",", unescapePrefix: "-", nestingPrefix: "$t(", nestingSuffix: ")", nestingOptionsSeparator: ",", maxReplaces: 1e3, skipOnVariables: true }, cacheInBuiltFormats: true }); var transformOptions = (options) => { if (isString$1(options.ns)) options.ns = [options.ns]; if (isString$1(options.fallbackLng)) options.fallbackLng = [options.fallbackLng]; if (isString$1(options.fallbackNS)) options.fallbackNS = [options.fallbackNS]; if (options.supportedLngs && !options.supportedLngs.includes("cimode")) options.supportedLngs = options.supportedLngs.concat(["cimode"]); return options; }; var noop$1 = () => {}; var bindMemberFunctions = (inst) => { Object.getOwnPropertyNames(Object.getPrototypeOf(inst)).forEach((mem) => { if (typeof inst[mem] === "function") inst[mem] = inst[mem].bind(inst); }); }; var instance = class I18n extends EventEmitter { constructor(options = {}, callback) { super(); this.options = transformOptions(options); this.services = {}; this.logger = baseLogger; this.modules = { external: [] }; bindMemberFunctions(this); if (callback && !this.isInitialized && !options.isClone) { if (!this.options.initAsync) { this.init(options, callback); return this; } setTimeout(() => { this.init(options, callback); }, 0); } } init(options = {}, callback) { this.isInitializing = true; if (typeof options === "function") { callback = options; options = {}; } if (options.defaultNS == null && options.ns) { if (isString$1(options.ns)) options.defaultNS = options.ns; else if (!options.ns.includes("translation")) options.defaultNS = options.ns[0]; } const defOpts = get(); this.options = { ...defOpts, ...this.options, ...transformOptions(options) }; this.options.interpolation = { ...defOpts.interpolation, ...this.options.interpolation }; if (options.keySeparator !== void 0) this.options.userDefinedKeySeparator = options.keySeparator; if (options.nsSeparator !== void 0) this.options.userDefinedNsSeparator = options.nsSeparator; if (typeof this.options.overloadTranslationOptionHandler !== "function") this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler; const createClassOnDemand = (ClassOrObject) => { if (!ClassOrObject) return null; if (typeof ClassOrObject === "function") return new ClassOrObject(); return ClassOrObject; }; if (!this.options.isClone) { if (this.modules.logger) baseLogger.init(createClassOnDemand(this.modules.logger), this.options); else baseLogger.init(null, this.options); let formatter; if (this.modules.formatter) formatter = this.modules.formatter; else formatter = Formatter; const lu = new LanguageUtil(this.options); this.store = new ResourceStore(this.options.resources, this.options); const s = this.services; s.logger = baseLogger; s.resourceStore = this.store; s.languageUtils = lu; s.pluralResolver = new PluralResolver(lu, { prepend: this.options.pluralSeparator }); if (formatter) { s.formatter = createClassOnDemand(formatter); if (s.formatter.init) s.formatter.init(s, this.options); this.options.interpolation.format = s.formatter.format.bind(s.formatter); } s.interpolator = new Interpolator(this.options); s.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) }; s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); s.backendConnector.on("*", (event, ...args) => { this.emit(event, ...args); }); if (this.modules.languageDetector) { s.languageDetector = createClassOnDemand(this.modules.languageDetector); if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options); } if (this.modules.i18nFormat) { s.i18nFormat = createClassOnDemand(this.modules.i18nFormat); if (s.i18nFormat.init) s.i18nFormat.init(this); } this.translator = new Translator(this.services, this.options); this.translator.on("*", (event, ...args) => { this.emit(event, ...args); }); this.modules.external.forEach((m) => { if (m.init) m.init(this); }); } this.format = this.options.interpolation.format; if (!callback) callback = noop$1; if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0]; } if (!this.services.languageDetector && !this.options.lng) this.logger.warn("init: no languageDetector is used and no lng is defined"); [ "getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage" ].forEach((fcName) => { this[fcName] = (...args) => this.store[fcName](...args); }); [ "addResource", "addResources", "addResourceBundle", "removeResourceBundle" ].forEach((fcName) => { this[fcName] = (...args) => { this.store[fcName](...args); return this; }; }); const deferred = defer(); const load = () => { const finish = (err, t) => { this.isInitializing = false; if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!"); this.isInitialized = true; if (!this.options.isClone) this.logger.log("initialized", this.options); this.emit("initialized", this.options); deferred.resolve(t); callback(err, t); }; if ((this.languages || this.isLanguageChangingTo) && !this.isInitialized) return finish(null, this.t.bind(this)); this.changeLanguage(this.options.lng, finish); }; if (this.options.resources || !this.options.initAsync) load(); else setTimeout(load, 0); return deferred; } loadResources(language, callback = noop$1) { let usedCallback = callback; const usedLng = isString$1(language) ? language : this.language; if (typeof language === "function") usedCallback = language; if (!this.options.resources || this.options.partialBundledLanguages) { if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); const toLoad = []; const append = (lng) => { if (!lng) return; if (lng === "cimode") return; this.services.languageUtils.toResolveHierarchy(lng).forEach((l) => { if (l === "cimode") return; if (!toLoad.includes(l)) toLoad.push(l); }); }; if (!usedLng) this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((l) => append(l)); else append(usedLng); this.options.preload?.forEach?.((l) => append(l)); this.services.backendConnector.load(toLoad, this.options.ns, (e) => { if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language); usedCallback(e); }); } else usedCallback(null); } reloadResources(lngs, ns, callback) { const deferred = defer(); if (typeof lngs === "function") { callback = lngs; lngs = void 0; } if (typeof ns === "function") { callback = ns; ns = void 0; } if (!lngs) lngs = this.languages; if (!ns) ns = this.options.ns; if (!callback) callback = noop$1; this.services.backendConnector.reload(lngs, ns, (err) => { deferred.resolve(); callback(err); }); return deferred; } use(module) { if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()"); if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()"); if (module.type === "backend") this.modules.backend = module; if (module.type === "logger" || module.log && module.warn && module.error) this.modules.logger = module; if (module.type === "languageDetector") this.modules.languageDetector = module; if (module.type === "i18nFormat") this.modules.i18nFormat = module; if (module.type === "postProcessor") postProcessor.addPostProcessor(module); if (module.type === "formatter") this.modules.formatter = module; if (module.type === "3rdParty") this.modules.external.push(module); return this; } setResolvedLanguage(l) { if (!l || !this.languages) return; if (["cimode", "dev"].includes(l)) return; for (let li = 0; li < this.languages.length; li++) { const lngInLngs = this.languages[li]; if (["cimode", "dev"].includes(lngInLngs)) continue; if (this.store.hasLanguageSomeTranslations(lngInLngs)) { this.resolvedLanguage = lngInLngs; break; } } if (!this.resolvedLanguage && !this.languages.includes(l) && this.store.hasLanguageSomeTranslations(l)) { this.resolvedLanguage = l; this.languages.unshift(l); } } changeLanguage(lng, callback) { this.isLanguageChangingTo = lng; const deferred = defer(); this.emit("languageChanging", lng); const setLngProps = (l) => { this.language = l; this.languages = this.services.languageUtils.toResolveHierarchy(l); this.resolvedLanguage = void 0; this.setResolvedLanguage(l); }; const done = (err, l) => { if (l) { if (this.isLanguageChangingTo === lng) { setLngProps(l); this.translator.changeLanguage(l); this.isLanguageChangingTo = void 0; this.emit("languageChanged", l); this.logger.log("languageChanged", l); } } else this.isLanguageChangingTo = void 0; deferred.resolve((...args) => this.t(...args)); if (callback) callback(err, (...args) => this.t(...args)); }; const setLng = (lngs) => { if (!lng && !lngs && this.services.languageDetector) lngs = []; const fl = isString$1(lngs) ? lngs : lngs && lngs[0]; const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString$1(lngs) ? [lngs] : lngs); if (l) { if (!this.language) setLngProps(l); if (!this.translator.language) this.translator.changeLanguage(l); this.services.languageDetector?.cacheUserLanguage?.(l); } this.loadResources(l, (err) => { done(err, l); }); }; if (!lng && this.services.languageDetector && !this.services.languageDetector.async) setLng(this.services.languageDetector.detect()); else if (!lng && this.services.languageDetector && this.services.languageDetector.async) if (this.services.languageDetector.detect.length === 0) this.services.languageDetector.detect().then(setLng); else this.services.languageDetector.detect(setLng); else setLng(lng); return deferred; } getFixedT(lng, ns, keyPrefix, fixedOpts) { const scopeNs = fixedOpts?.scopeNs; const fixedT = (key, opts, ...rest) => { let o; if (typeof opts !== "object") o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest)); else o = { ...opts }; o.lng = o.lng || fixedT.lng; o.lngs = o.lngs || fixedT.lngs; const explicitCallNs = o.ns !== void 0 && o.ns !== null; o.ns = o.ns || fixedT.ns; if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix; const selectorOpts = { ...this.options, ...o }; if (Array.isArray(scopeNs) && !explicitCallNs) selectorOpts.ns = scopeNs; if (typeof o.keyPrefix === "function") o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts); const keySeparator = this.options.keySeparator || "."; let resultKey; if (o.keyPrefix && Array.isArray(key)) resultKey = key.map((k) => { if (typeof k === "function") k = keysFromSelector(k, selectorOpts); return `${o.keyPrefix}${keySeparator}${k}`; }); else { if (typeof key === "function") key = keysFromSelector(key, selectorOpts); resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key; } return this.t(resultKey, o); }; if (isString$1(lng)) fixedT.lng = lng; else fixedT.lngs = lng; fixedT.ns = ns; fixedT.keyPrefix = keyPrefix; return fixedT; } t(...args) { return this.translator?.translate(...args); } exists(...args) { return this.translator?.exists(...args); } setDefaultNamespace(ns) { this.options.defaultNS = ns; } hasLoadedNamespace(ns, options = {}) { if (!this.isInitialized) { this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages); return false; } if (!this.languages || !this.languages.length) { this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages); return false; } const lng = options.lng || this.resolvedLanguage || this.languages[0]; const fallbackLng = this.options ? this.options.fallbackLng : false; const lastLng = this.languages[this.languages.length - 1]; if (lng.toLowerCase() === "cimode") return true; const loadNotPending = (l, n) => { const loadState = this.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 0 || loadState === 2; }; if (options.precheck) { const preResult = options.precheck(this, loadNotPending); if (preResult !== void 0) return preResult; } if (this.hasResourceBundle(lng, ns)) return true; if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true; if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; return false; } loadNamespaces(ns, callback) { const deferred = defer(); if (!this.options.ns) { if (callback) callback(); return Promise.resolve(); } if (isString$1(ns)) ns = [ns]; ns.forEach((n) => { if (!this.options.ns.includes(n)) this.options.ns.push(n); }); this.loadResources((err) => { deferred.resolve(); if (callback) callback(err); }); return deferred; } loadLanguages(lngs, callback) { const deferred = defer(); if (isString$1(lngs)) lngs = [lngs]; const preloaded = this.options.preload || []; const newLngs = lngs.filter((lng) => !preloaded.includes(lng) && this.services.languageUtils.isSupportedCode(lng)); if (!newLngs.length) { if (callback) callback(); return Promise.resolve(); } this.options.preload = preloaded.concat(newLngs); this.loadResources((err) => { deferred.resolve(); if (callback) callback(err); }); return deferred; } dir(lng) { if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language); if (!lng) return "rtl"; try { const l = new Intl.Locale(lng); if (l && l.getTextInfo) { const ti = l.getTextInfo(); if (ti && ti.direction) return ti.direction; } } catch (e) {} const rtlLngs = [ "ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb" ]; const languageUtils = this.services?.languageUtils || new LanguageUtil(get()); if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr"; return rtlLngs.includes(languageUtils.getLanguagePartFromCode(lng)) || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr"; } static createInstance(options = {}, callback) { const instance = new I18n(options, callback); instance.createInstance = I18n.createInstance; return instance; } cloneInstance(options = {}, callback = noop$1) { const forkResourceStore = options.forkResourceStore; if (forkResourceStore) delete options.forkResourceStore; const mergedOptions = { ...this.options, ...options, isClone: true }; const clone = new I18n(mergedOptions); if (options.debug !== void 0 || options.prefix !== void 0) clone.logger = clone.logger.clone(options); [ "store", "services", "language" ].forEach((m) => { clone[m] = this[m]; }); clone.services = { ...this.services }; clone.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; if (forkResourceStore) { clone.store = new ResourceStore(Object.keys(this.store.data).reduce((prev, l) => { prev[l] = { ...this.store.data[l] }; prev[l] = Object.keys(prev[l]).reduce((acc, n) => { acc[n] = { ...prev[l][n] }; return acc; }, prev[l]); return prev; }, {}), mergedOptions); clone.services.resourceStore = clone.store; } if (options.interpolation) { const mergedInterpolation = { ...get().interpolation, ...this.options.interpolation, ...options.interpolation }; const mergedForInterpolator = { ...mergedOptions, interpolation: mergedInterpolation }; clone.services.interpolator = new Interpolator(mergedForInterpolator); } clone.translator = new Translator(clone.services, mergedOptions); clone.translator.on("*", (event, ...args) => { clone.emit(event, ...args); }); clone.init(mergedOptions, callback); clone.translator.options = mergedOptions; clone.translator.backendConnector.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; return clone; } toJSON() { return { options: this.options, store: this.store, language: this.language, languages: this.languages, resolvedLanguage: this.resolvedLanguage }; } }.createInstance(); instance.createInstance; instance.dir; instance.init; instance.loadResources; instance.reloadResources; instance.use; instance.changeLanguage; instance.getFixedT; instance.t; instance.exists; instance.setDefaultNamespace; instance.hasLoadedNamespace; instance.loadNamespaces; instance.loadLanguages; var warn = (i18n, code, msg, rest) => { const args = [msg, { code, ...rest || {} }]; if (i18n?.services?.logger?.forward) return i18n.services.logger.forward(args, "warn", "react-i18next::", true); if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`; if (i18n?.services?.logger?.warn) i18n.services.logger.warn(...args); else if (console?.warn) console.warn(...args); }; var alreadyWarned = {}; var warnOnce = (i18n, code, msg, rest) => { if (isString(msg) && alreadyWarned[msg]) return; if (isString(msg)) alreadyWarned[msg] = new Date(); warn(i18n, code, msg, rest); }; var loadedClb = (i18n, cb) => () => { if (i18n.isInitialized) cb(); else { const initialized = () => { setTimeout(() => { i18n.off("initialized", initialized); }, 0); cb(); }; i18n.on("initialized", initialized); } }; var loadNamespaces = (i18n, ns, cb) => { i18n.loadNamespaces(ns, loadedClb(i18n, cb)); }; var loadLanguages = (i18n, lng, ns, cb) => { if (isString(ns)) ns = [ns]; if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb); ns.forEach((n) => { if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n); }); i18n.loadLanguages(lng, loadedClb(i18n, cb)); }; var hasLoadedNamespace = (ns, i18n, options = {}) => { if (!i18n.languages || !i18n.languages.length) { warnOnce(i18n, "NO_LANGUAGES", "i18n.languages were undefined or empty", { languages: i18n.languages }); return true; } return i18n.hasLoadedNamespace(ns, { lng: options.lng, precheck: (i18nInstance, loadNotPending) => { if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false; } }); }; var isString = (obj) => typeof obj === "string"; var isObject = (obj) => typeof obj === "object" && obj !== null; var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g; var htmlEntities = { "&": "&", "&": "&", "<": "<", "<": "<", ">": ">", ">": ">", "'": "'", "'": "'", """: "\"", """: "\"", " ": " ", " ": " ", "©": "©", "©": "©", "®": "®", "®": "®", "…": "…", "…": "…", "/": "/", "/": "/" }; var unescapeHtmlEntity = (m) => htmlEntities[m]; var unescape$1 = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity); var defaultOptions = { bindI18n: "languageChanged", bindI18nStore: "", transEmptyNodeValue: "", transSupportBasicHtmlNodes: true, transWrapTextNodes: "", transKeepBasicHtmlNodesFor: [ "br", "strong", "i", "p" ], useSuspense: true, unescape: unescape$1, transDefaultProps: void 0 }; var setDefaults = (options = {}) => { defaultOptions = { ...defaultOptions, ...options }; }; var getDefaults = () => defaultOptions; var i18nInstance; var setI18n = (instance) => { i18nInstance = instance; }; var getI18n = () => i18nInstance; var initReactI18next = { type: "3rdParty", init(instance) { setDefaults(instance.options.react); setI18n(instance); } }; init_compat_module(); var I18nContext = X$1(); var ReportNamespaces = class { constructor() { this.usedNamespaces = {}; } addUsedNamespaces(namespaces) { namespaces.forEach((ns) => { if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; }); } getUsedNamespaces() { return Object.keys(this.usedNamespaces); } }; var require_use_sync_external_store_shim_production = __commonJSMin(((exports) => { var React = (init_compat_module(), __toCommonJS(compat_module_exports)); function is(x, y) { return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; } var objectIs = "function" === typeof Object.is ? Object.is : is, useState = React.useState, useEffect = React.useEffect, useLayoutEffect = React.useLayoutEffect, useDebugValue = React.useDebugValue; function useSyncExternalStore$2(subscribe, getSnapshot) { var value = getSnapshot(), _useState = useState({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1]; useLayoutEffect(function() { inst.value = value; inst.getSnapshot = getSnapshot; checkIfSnapshotChanged(inst) && forceUpdate({ inst }); }, [ subscribe, value, getSnapshot ]); useEffect(function() { checkIfSnapshotChanged(inst) && forceUpdate({ inst }); return subscribe(function() { checkIfSnapshotChanged(inst) && forceUpdate({ inst }); }); }, [subscribe]); useDebugValue(value); return value; } function checkIfSnapshotChanged(inst) { var latestGetSnapshot = inst.getSnapshot; inst = inst.value; try { var nextValue = latestGetSnapshot(); return !objectIs(inst, nextValue); } catch (error) { return !0; } } function useSyncExternalStore$1(subscribe, getSnapshot) { return getSnapshot(); } var shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; exports.useSyncExternalStore = void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim; })); var require_shim = __commonJSMin(((exports, module) => { module.exports = require_use_sync_external_store_shim_production(); })); init_compat_module(); var import_shim = require_shim(); var notReadyT = (k, optsOrDefaultValue) => { if (isString(optsOrDefaultValue)) return optsOrDefaultValue; if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue; if (typeof k === "function") return ""; if (Array.isArray(k)) { const last = k[k.length - 1]; return typeof last === "function" ? "" : last; } return k; }; var notReadySnapshot = { t: notReadyT, ready: false }; var dummySubscribe = () => () => {}; var useTranslation = (ns, props = {}) => { const { i18n: i18nFromProps } = props; const { i18n: i18nFromContext, defaultNS: defaultNSFromContext } = x$1(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces(); if (!i18n) warnOnce(i18n, "NO_I18NEXT_INSTANCE", "useTranslation: You will need to pass in an i18next instance by using initReactI18next"); const i18nOptions = T$1(() => ({ ...getDefaults(), ...i18n?.options?.react, ...props }), [i18n, props]); const { useSuspense, keyPrefix } = i18nOptions; const nsOrContext = ns || defaultNSFromContext || i18n?.options?.defaultNS; const unstableNamespaces = isString(nsOrContext) ? [nsOrContext] : nsOrContext || ["translation"]; const namespaces = T$1(() => unstableNamespaces, unstableNamespaces); i18n?.reportNamespaces?.addUsedNamespaces?.(namespaces); const revisionRef = A$2(0); const subscribe = q$1((callback) => { if (!i18n) return dummySubscribe; const { bindI18n, bindI18nStore } = i18nOptions; const wrappedCallback = () => { revisionRef.current += 1; callback(); }; if (bindI18n) i18n.on(bindI18n, wrappedCallback); if (bindI18nStore) i18n.store.on(bindI18nStore, wrappedCallback); return () => { if (bindI18n) bindI18n.split(" ").forEach((e) => i18n.off(e, wrappedCallback)); if (bindI18nStore) bindI18nStore.split(" ").forEach((e) => i18n.store.off(e, wrappedCallback)); }; }, [i18n, i18nOptions]); const snapshotRef = A$2(); const getSnapshot = q$1(() => { if (!i18n) return notReadySnapshot; const calculatedReady = !!(i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every((n) => hasLoadedNamespace(n, i18n, i18nOptions)); const currentLng = props.lng || i18n.language; const currentRevision = revisionRef.current; const lastSnapshot = snapshotRef.current; if (lastSnapshot && lastSnapshot.ready === calculatedReady && lastSnapshot.lng === currentLng && lastSnapshot.keyPrefix === keyPrefix && lastSnapshot.revision === currentRevision) return lastSnapshot; const newSnapshot = { t: i18n.getFixedT(currentLng, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix, { scopeNs: namespaces }), ready: calculatedReady, lng: currentLng, keyPrefix, revision: currentRevision }; snapshotRef.current = newSnapshot; return newSnapshot; }, [ i18n, namespaces, keyPrefix, i18nOptions, props.lng ]); const [loadCount, setLoadCount] = d$1(0); const { t, ready } = (0, import_shim.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot); y$1(() => { if (i18n && !ready && !useSuspense) { const onLoaded = () => setLoadCount((c) => c + 1); if (props.lng) loadLanguages(i18n, props.lng, namespaces, onLoaded); else loadNamespaces(i18n, namespaces, onLoaded); } }, [ i18n, props.lng, namespaces, ready, useSuspense, loadCount ]); const finalI18n = i18n || {}; const wrapperRef = A$2(null); const wrapperLangRef = A$2(); const createI18nWrapper = (original) => { const descriptors = Object.getOwnPropertyDescriptors(original); if (descriptors.__original) delete descriptors.__original; const wrapper = Object.create(Object.getPrototypeOf(original), descriptors); if (!Object.prototype.hasOwnProperty.call(wrapper, "__original")) try { Object.defineProperty(wrapper, "__original", { value: original, writable: false, enumerable: false, configurable: false }); } catch (_) {} return wrapper; }; const ret = T$1(() => { const original = finalI18n; const lang = original?.language; let i18nWrapper = original; if (original) if (wrapperRef.current && wrapperRef.current.__original === original) if (wrapperLangRef.current !== lang) { i18nWrapper = createI18nWrapper(original); wrapperRef.current = i18nWrapper; wrapperLangRef.current = lang; } else i18nWrapper = wrapperRef.current; else { i18nWrapper = createI18nWrapper(original); wrapperRef.current = i18nWrapper; wrapperLangRef.current = lang; } const effectiveT = !ready && !useSuspense ? (...args) => { warnOnce(i18n, "USE_T_BEFORE_READY", "useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."); return t(...args); } : t; const arr = [ effectiveT, i18nWrapper, ready ]; arr.t = effectiveT; arr.i18n = i18nWrapper; arr.ready = ready; return arr; }, [ t, finalI18n, ready, finalI18n.resolvedLanguage, finalI18n.language, finalI18n.languages ]); if (i18n && useSuspense && !ready) throw new Promise((resolve) => { const onLoaded = () => resolve(); if (props.lng) loadLanguages(i18n, props.lng, namespaces, onLoaded); else loadNamespaces(i18n, namespaces, onLoaded); }); return ret; }; var en_default = { title: "ChatGPT Exporter", ExportHelper: "Export", Setting: "Setting", Language: "Language", "Copy Text": "Copy Text", "Copied!": "Copied!", Screenshot: "Screenshot", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Archive", Save: "Save", Delete: "Delete", "Select All": "Select All", Export: "Export", Error: "Error", Loading: "Loading", Preview: "Preview", "File Name": "File Name", "Export All": "Export All", "Exporter Settings": "Exporter Settings", "Export Dialog Title": "Export Conversations", "Invalid File Format": "Invalid File Format", "Export from official export file": "Export from official export file", "Export from API": "Export from API", "Available variables": "Available variables", "Conversation Timestamp": "Conversation Timestamp", "Conversation Timestamp Description": "Will show on the page.", "Enable on HTML": "Enable on HTML files", "Enable on Markdown": "Enable on Markdown files", "Use 24-hour format": "Use 24-hour format (eg. 23:59)", "Export Format": "Export Format", "Export Metadata": "Export Metadata", "Export Metadata Description": "Add metadata to exported Markdown and HTML files.", "OpenAI Official Format": "OpenAI Official Format", "Conversation Archive Alert": "Are you sure you want to archive all selected conversations?", "Conversation Archived Message": "All selected conversations have been archived. Please refresh the page to see the changes.", "Conversation Delete Alert": "Are you sure you want to delete all selected conversations?", "Conversation Deleted Message": "All selected conversations have been deleted. Please refresh the page to see the changes.", "Please start a conversation first": "Please start a conversation first.", "Select Project": "Select Project", "(no project)": "(no project)", "Export All Limit": "Export All Limit", "Export All Limit Description": "Set the maximum number of conversations to load in the 'Export All' dialog.", "Pro License": "Pro License", "License Key Placeholder": "License key", "Pro License Active": "Pro features are enabled.", "Pro License Required Description": "Enter a Pro license key to enable bulk and multi-provider export.", "Pro License Required Message": "A Pro license key is required for bulk and multi-provider export.", "License Verifying": "Verifying license…", "License Invalid": "Invalid or inactive license. Free tier features only.", "Buy Pro": "Buy Pro", "Checkout Not Configured": "Checkout is not configured.", "API Auth": "API Auth", "API Key Placeholder": "API key", "Issue API Key": "Issue API key", Unlock: "Unlock", Revoke: "Revoke", Issued: "Issued", "New API Key": "New API key", "API Auth Unlocked": "Unlocked", "API Auth Locked": "Locked", "API Auth Not Issued": "Not issued", "API Key Issued": "API key issued.", "API Key Verified": "API key verified.", "Invalid API Key": "Invalid API key.", "API Key Revoked": "API key revoked." }; var es_default = { title: "ChatGPT Exporter", ExportHelper: "Exportar", Setting: "Ajustes", Language: "Idioma", "Copy Text": "Copiar Texto", "Copied!": "¡Copiado!", Screenshot: "Captura De Pantalla", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Archivo", Save: "Guardar", Delete: "Borrar", "Select All": "Seleccionar Todos", Export: "Exportar", Error: "Error", Loading: "Cargando", Preview: "Previsualizar", "File Name": "Nombre del Archivo", "Export All": "Exportar Todos", "Exporter Settings": "Ajustes De Exportación", "Export Dialog Title": "Exportar Conversaciones", "Invalid File Format": "Formato de archivo inválido", "Export from official export file": "Exportar desde archivo de exportación oficial", "Export from API": "Exportar desde API", "Available variables": "Variables Disponibles", "Conversation Timestamp": "Marca de Tiempo", "Conversation Timestamp Description": "Aparecerá en la página.", "Enable on HTML": "Habilitar en archivos HTML", "Enable on Markdown": "Habilitar en archivos Markdown", "Use 24-hour format": "Usar formato de 24 horas (ej. 23:59)", "Export Format": "Formato de Exportación", "Export Metadata": "Exportar Metadatos", "Export Metadata Description": "Añadir Metadatos a los archivos Markdown y HTML exportados.", "OpenAI Official Format": "Formato Oficial de OpenAI", "Conversation Archive Alert": "¿Estás seguro que quieres archivar todas las conversaciones seleccionadas?", "Conversation Archived Message": "Todos las conversaciones seleccionadas se han archivado. Por favor refresca la página para ver los cambios.", "Conversation Delete Alert": "¿Estás seguro que quieres borrar todas las conversaciones seleccionadas?", "Conversation Deleted Message": "Todos las conversaciones seleccionadas se han borrado. Por favor refresca la página para ver los cambios.", "Please start a conversation first": "Por favor empieza una conversación antes.", "Select Project": "Seleccionar proyecto", "(no project)": "(sin proyecto)", "Export All Limit": "Límite de Exportar Todos", "Export All Limit Description": "Establece el número máximo de conversaciones a cargar en el diálogo 'Exportar Todos'." }; var fr_default = { title: "Exportateur ChatGPT", ExportHelper: "Exporter", Setting: "Paramètre", Language: "Langue", "Copy Text": "Copier le texte", "Copied!": "Copié !", Screenshot: "Capture d'écran", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Archiver", Save: "Enregistrer", Delete: "Supprimer", "Select All": "Tout sélectionner", Export: "Exporter", Error: "Erreur", Loading: "Chargement", Preview: "Aperçu", "File Name": "Nom du fichier", "Export All": "Tout exporter", "Exporter Settings": "Paramètres de l'exportateur", "Export Dialog Title": "Exporter les conversations", "Invalid File Format": "Format de fichier invalide", "Export from official export file": "Exporter depuis un fichier officiel", "Export from API": "Exporter depuis l'API", "Available variables": "Variables disponibles", "Conversation Timestamp": "Horodatage de la conversation", "Conversation Timestamp Description": "S'affichera sur la page.", "Enable on HTML": "Activer sur les fichiers HTML", "Enable on Markdown": "Activer sur les fichiers Markdown", "Use 24-hour format": "Utiliser le format 24 heures (ex. 23:59)", "Export Format": "Format d'exportation", "Export Metadata": "Exporter les métadonnées", "Export Metadata Description": "Ajouter des métadonnées aux fichiers Markdown et HTML exportés.", "OpenAI Official Format": "Format officiel OpenAI", "Conversation Archive Alert": "Êtes-vous sûr de vouloir archiver toutes les conversations sélectionnées ?", "Conversation Archived Message": "Toutes les conversations sélectionnées ont été archivées. Veuillez actualiser la page pour voir les changements.", "Conversation Delete Alert": "Êtes-vous sûr de vouloir supprimer toutes les conversations sélectionnées ?", "Conversation Deleted Message": "Toutes les conversations sélectionnées ont été supprimées. Veuillez actualiser la page pour voir les changements.", "Please start a conversation first": "Veuillez commencer une conversation d'abord.", "Select Project": "Sélectionner un projet", "(no project)": "(aucun projet)", "Export All Limit": "Limite d'Exportation Multiple", "Export All Limit Description": "Définit le nombre maximal de conversations à charger dans la boîte de dialogue 'Tout exporter'." }; var id_default = { title: "ChatGPT Exporter", ExportHelper: "Ekspor", Setting: "Pengaturan", Language: "Bahasa", "Copy Text": "Salin Teks", "Copied!": "Disalin!", Screenshot: "Tangkapan Layar", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Arsip", Save: "Simpan", Delete: "Hapus", "Select All": "Pilih Semua", Export: "Ekspor", Error: "Kesalahan", Loading: "Memuat", Preview: "Pratinjau", "File Name": "Nama File", "Export All": "Ekspor Semua", "Exporter Settings": "Pengaturan Pengekspor", "Export Dialog Title": "Ekspor Percakapan", "Invalid File Format": "Format File Tidak Valid", "Export from official export file": "Ekspor dari file ekspor resmi", "Export from API": "Ekspor dari API", "Available variables": "Variabel yang Tersedia", "Conversation Timestamp": "Timestamp Percakapan", "Conversation Timestamp Description": "Akan ditampilkan pada halaman.", "Enable on HTML": "Aktifkan pada file HTML", "Enable on Markdown": "Aktifkan pada file Markdown", "Use 24-hour format": "Gunakan format 24 jam (contohnya: 23:59)", "Export Format": "Format Ekspor", "Export Metadata": "Ekspor Metada", "Export Metadata Description": "Tambahkan metadata ke file Markdown dan HTML yang diekspor.", "OpenAI Official Format": "Format Resmi OpenAI", "Conversation Archive Alert": "Apakah Anda yakin ingin mengarsipkan semua percakapan yang dipilih?", "Conversation Archived Message": "Semua percakapan yang dipilih telah diarsipkan. Harap segarkan halaman untuk melihat perubahan.", "Conversation Delete Alert": "Apakah Anda yakin ingin menghapus semua percakapan yang dipilih?", "Conversation Deleted Message": "Semua percakapan yang dipilih telah dihapus. Harap segarkan halaman untuk melihat perubahan.", "Please start a conversation first": "Harap mulai percakapan terlebih dahulu.", "Select Project": "Pilih Proyek", "(no project)": "(tidak ada proyek)", "Export All Limit": "Batas Ekspor Semua", "Export All Limit Description": "Atur jumlah maksimum percakapan yang akan dimuat dalam dialog 'Ekspor Semua'." }; var jp_default = { title: "ChatGPTエクスポーター", ExportHelper: "エクスポート", Setting: "設定", Language: "言語", "Copy Text": "テキストをコピー", "Copied!": "コピーしました!", Screenshot: "スクリーンショット", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "アーカイブ", Save: "保存", Delete: "削除", "Select All": "すべて選択", Export: "エクスポート", Error: "エラー", Loading: "読み込み中", Preview: "プレビュー", "File Name": "ファイル名", "Export All": "すべてエクスポート", "Exporter Settings": "エクスポーター設定", "Export Dialog Title": "会話をエクスポート", "Invalid File Format": "無効なファイル形式", "Export from official export file": "公式エクスポートファイルからエクスポートする", "Export from API": "APIからエクスポートする", "Available variables": "使用可能な変数", "Conversation Timestamp": "会話のタイムスタンプ", "Conversation Timestamp Description": "ページに表示されます。", "Enable on HTML": "HTML ファイルで有効にする", "Enable on Markdown": "Markdown ファイルで有効にする", "Use 24-hour format": "24時間形式を使用する (例: 23:59)", "Export Format": "エクスポートフォーマット", "Export Metadata": "メタデータをエクスポート", "Export Metadata Description": "エクスポートされたMarkdownおよびHTMLファイルにメタデータを追加します。", "OpenAI Official Format": "OpenAI公式フォーマット", "Conversation Archive Alert": "選択したすべての会話をアーカイブしてもよろしいですか?", "Conversation Archived Message": "選択したすべての会話がアーカイブされました。変更を表示するには、ページを更新してください。", "Conversation Delete Alert": "選択したすべての会話を削除してもよろしいですか?", "Conversation Deleted Message": "選択したすべての会話が削除されました。変更を表示するには、ページを更新してください。", "Please start a conversation first": "まず会話を開始してください。", "Select Project": "プロジェクトを選択", "(no project)": "(プロジェクトなし)", "Export All Limit": "すべてエクスポートの上限", "Export All Limit Description": "「すべてエクスポート」ダイアログで読み込む会話の最大数を設定します。" }; var ru_default = { title: "ChatGPT Exporter", ExportHelper: "Export", Setting: "Параметры", Language: "Язык", "Copy Text": "Копировать текст", "Copied!": "Скопировано!", Screenshot: "Скриншот", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Архивировать", Save: "Сохранить", Delete: "Удалить", "Select All": "Выбрать все", Export: "Экспорт", Error: "Ошибка", Loading: "Загрузка", Preview: "Предпросмотр", "File Name": "Имя файла", "Export All": "Экспортировать все", "Exporter Settings": "Параметры экспорта", "Export Dialog Title": "Экспортировать беседы", "Invalid File Format": "Неверный формат файла", "Export from official export file": "Экспорт из официального файла", "Export from API": "Экспорт из API", "Available variables": "Доступные переменные", "Conversation Timestamp": "Временная метка разговора", "Conversation Timestamp Description": "Будет отображаться на странице.", "Enable on HTML": "Включить для HTML-файлов", "Enable on Markdown": "Включить для файлов Markdown", "Use 24-hour format": "Использовать 24-часовой формат (например, 23:59)", "Export Format": "Формат экспорта", "Export Metadata": "Экспорт метаданных", "Export Metadata Description": "Добавляйте метаданные в экспортированные файлы Markdown и HTML.", "OpenAI Official Format": "Официальный формат OpenAI", "Conversation Archive Alert": "Вы уверены, что хотите архивировать все выбранные разговоры?", "Conversation Archived Message": "Все выбранные разговоры были заархивированы. Пожалуйста, обновите страницу, чтобы увидеть изменения.", "Conversation Delete Alert": "Вы уверены, что хотите удалить все выбранные разговоры?", "Conversation Deleted Message": "Все выбранные разговоры были удалены. Пожалуйста, обновите страницу, чтобы увидеть изменения.", "Please start a conversation first": "Пожалуйста, начните разговор первым.", "Select Project": "Выберите проект", "(no project)": "(нет проекта)", "Export All Limit": "Лимит экспорта всех", "Export All Limit Description": "Установите максимальное количество бесед для загрузки в диалоге 'Экспортировать все'." }; var tr_default = { title: "ChatGPT Exporter", ExportHelper: "Dışa Aktar", Setting: "Ayarlar", Language: "Dil", "Copy Text": "Metni Kopyala", "Copied!": "Kopyalandı!", Screenshot: "Ekran Alıntısı", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "Arşiv", Save: "Kaydet", Delete: "Sil", "Select All": "Tümünü Seç", Export: "Dışa Aktar", Error: "Hata", Loading: "Yükleniyor", Preview: "Önizleme", "File Name": "Dosya Adı", "Export All": "Tümünü Dışa Aktar", "Exporter Settings": "Dışa Aktarma Ayarları", "Export Dialog Title": "Konuşmaları Dışa Aktar", "Invalid File Format": "Dosya Biçimi Geçersiz", "Export from official export file": "Resmi dışa aktarma dosyasından dışa aktar", "Export from API": "API'den dışa aktar", "Available variables": "Kullanılabilir değişkenler", "Conversation Timestamp": "Konuşma zaman bilgisi", "Conversation Timestamp Description": "Sayfada gösterilir.", "Enable on HTML": "HTML dosyalarında etkinleştir", "Enable on Markdown": "Markdown dosyalarında etkinleştir", "Use 24-hour format": "24 saat biçimini kullan (örn. 23:59)", "Export Format": "Dışa Aktarma Formatı", "Export Metadata": "Üst veriyi dışa aktar", "Export Metadata Description": "Dışa aktarılan Markdown ve HTML dosyalarına üst veri ekle", "OpenAI Official Format": "OpenAI Resmi Format", "Conversation Archive Alert": "Seçilen tüm konuşmaları arşivlemek istediğinizden emin misiniz?", "Conversation Archived Message": "Seçilen tüm konuşmalar arşivlendi. Değişiklikleri görmek için sayfayı yenileyin.", "Conversation Delete Alert": "Seçilen tüm konuşmaları silmek istediğinizden emin misiniz?", "Conversation Deleted Message": "Seçilen tüm konuşmalar silindi. Değişiklikleri görmek için sayfayı yenileyin.", "Please start a conversation first": "Lütfen önce bir konuşma başlatın.", "Select Project": "Proje Seç", "(no project)": "(proje yok)", "Export All Limit": "Tümünü Dışa Aktarma Limiti", "Export All Limit Description": "'Tümünü Dışa Aktar' iletişim kutusunda yüklenecek maksimum konuşma sayısını ayarlayın." }; var zh_Hans_default = { title: "ChatGPT Exporter", ExportHelper: "导出助手", Setting: "设置", Language: "语言", "Copy Text": "复制文字", "Copied!": "已复制!", Screenshot: "截屏", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "归档", Save: "保存", Delete: "删除", "Select All": "全选", Export: "导出", Error: "错误", Loading: "加载中", Preview: "预览", "File Name": "文件名", "Export All": "批量导出", "Exporter Settings": "导出设置", "Export Dialog Title": "导出对话", "Invalid File Format": "无效的文件格式", "Export from official export file": "从官方导出文件导出", "Export from API": "从 API 导出", "Available variables": "可用变量", "Conversation Timestamp": "对话时间戳", "Conversation Timestamp Description": "会显示在页面上。", "Enable on HTML": "在 HTML 文件上启用", "Enable on Markdown": "在 Markdown 文件上启用", "Use 24-hour format": "使用24小时制 (例如 23:59)", "Export Format": "导出格式", "Export Metadata": "导出元数据", "Export Metadata Description": "会添加至 Markdown 以及 HTML 导出。", "OpenAI Official Format": "OpenAI 官方格式", "Conversation Archive Alert": "确定要归档所有选取的对话?", "Conversation Archived Message": "所有所选的对话已归档。请刷新页面。", "Conversation Delete Alert": "确定要删除所有选取的对话?", "Conversation Deleted Message": "所有所选的对话已删除。请刷新页面。", "Please start a conversation first": "请先开始对话。", "Select Project": "选择项目", "(no project)": "(无项目)", "Export All Limit": "批量导出上限", "Export All Limit Description": "设置“批量导出”对话框中加载的最大对话数量。" }; var zh_Hant_default = { title: "ChatGPT Exporter", ExportHelper: "Export", Setting: "設定", Language: "語言", "Copy Text": "複製文字", "Copied!": "已複製!", Screenshot: "截圖", Markdown: "Markdown", HTML: "HTML", JSON: "JSON", Archive: "封存", Save: "保存", Delete: "刪除", "Select All": "全選", Export: "匯出", Error: "錯誤", Loading: "載入中", Preview: "預覽", "File Name": "檔案名稱", "Export All": "批量匯出", "Exporter Settings": "設定", "Export Dialog Title": "匯出對話", "Invalid File Format": "無效的檔案格式", "Export from official export file": "從官方匯出檔案匯出", "Export from API": "從 API 匯出", "Available variables": "可用變數", "Conversation Timestamp": "對話時間戳", "Conversation Timestamp Description": "會顯示在頁面上。", "Enable on HTML": "在 HTML 檔案上啟用", "Enable on Markdown": "在 Markdown 檔案上啟用", "Use 24-hour format": "使用24小時制 (例如 23:59)", "Export Format": "匯出格式", "Export Metadata": "匯出元資料", "Export Metadata Description": "會添加至 Markdown 以及 HTML 匯出。", "OpenAI Official Format": "OpenAI 官方格式", "Conversation Archive Alert": "確定要封存所有選取的對話?", "Conversation Archived Message": "所有選取的對話已封存。請重新整理頁面。", "Conversation Delete Alert": "確定要刪除所有選取的對話?", "Conversation Deleted Message": "所有選取的對話已刪除。請重新整理頁面。", "Please start a conversation first": "請先開始對話。", "Select Project": "選擇專案", "(no project)": "(無專案)", "Export All Limit": "批量匯出上限", "Export All Limit Description": "設定「批量匯出」對話方塊中載入的最大對話數量。" }; var EN_US = { name: "English", code: "en-US", resource: en_default }; var ES = { name: "Español", code: "es", resource: es_default }; var FR = { name: "Français", code: "fr", resource: fr_default }; var ID_ID = { name: "Indonesia", code: "id-ID", resource: id_default }; var JA_JP = { name: "日本語", code: "ja-JP", resource: jp_default }; var RU = { name: "Русский", code: "ru", resource: ru_default }; var TR_TR = { name: "Türkçe", code: "tr-TR", resource: tr_default }; var ZH_Hans = { name: "简体中文", code: "zh-Hans", resource: zh_Hans_default }; var ZH_Hant = { name: "繁體中文", code: "zh-Hant", resource: zh_Hant_default }; var LOCALES = [ EN_US, ES, FR, ID_ID, JA_JP, RU, TR_TR, ZH_Hans, ZH_Hant ]; var LanguageMapping = { "en": EN_US.code, "en-US": EN_US.code, "es": ES.code, "es-ES": ES.code, "es-AR": ES.code, "es-CL": ES.code, "es-CO": ES.code, "es-MX": ES.code, "es-US": ES.code, "fr": FR.code, "fr-FR": FR.code, "id": ID_ID.code, "id-ID": ID_ID.code, "ja": JA_JP.code, "ja-JP": JA_JP.code, "ru": RU.code, "ru-RU": RU.code, "tr": TR_TR.code, "tr-TR": TR_TR.code, "zh": ZH_Hans.code, "zh-CN": ZH_Hans.code, "zh-MO": ZH_Hans.code, "zh-SG": ZH_Hans.code, "zh-Hans": ZH_Hans.code, "zh-HK": ZH_Hant.code, "zh-TW": ZH_Hant.code, "zh-Hant": ZH_Hant.code }; var resources = LOCALES.reduce((acc, cur) => { acc[cur.code] = { translation: cur.resource }; return acc; }, {}); function standardizeLanguage(language) { if (!language) return null; if (language in LanguageMapping) return LanguageMapping[language]; const shortLang = language.split("-")[0]; if (shortLang in LanguageMapping) return LanguageMapping[shortLang]; return null; } function getNavigatorLanguage() { const { language, languages } = navigator; if (language) return language; if (languages && languages.length) return languages[0]; return null; } function getOaiLanguage() { return (window?.localStorage?.getItem("oai/apps/locale"))?.replace(/^"(.*)"$/, "$1") ?? null; } function getDefaultLanguage() { const storedLanguage = ScriptStorage.get(KEY_LANGUAGE); const oaiLanguage = getOaiLanguage(); const browserLanguage = getNavigatorLanguage(); return standardizeLanguage(storedLanguage) ?? standardizeLanguage(oaiLanguage) ?? standardizeLanguage(browserLanguage) ?? EN_US.code; } instance.use(initReactI18next).init({ fallbackLng: EN_US.code, lng: getDefaultLanguage(), debug: false, resources, interpolation: { escapeValue: false } }); instance.on("languageChanged", (lng) => { ScriptStorage.set(KEY_LANGUAGE, lng); }); var i18n_default = instance; var template_default = "\n\n\n \n \n \n {{title}}\n \n