// ==UserScript== // @name uBlacklist // @version 8.12.0 // @description Blocks sites you specify from appearing in Google search results // @namespace ublacklist // @author Converter Script // @match https://www.google.com/search?* // @match https://www.google.ad/search?* // @match https://www.google.ae/search?* // @match https://www.google.com.af/search?* // @match https://www.google.com.ag/search?* // @match https://www.google.com.ai/search?* // @match https://www.google.al/search?* // @match https://www.google.am/search?* // @match https://www.google.co.ao/search?* // @match https://www.google.com.ar/search?* // @match https://www.google.as/search?* // @match https://www.google.at/search?* // @match https://www.google.com.au/search?* // @match https://www.google.az/search?* // @match https://www.google.ba/search?* // @match https://www.google.com.bd/search?* // @match https://www.google.be/search?* // @match https://www.google.bf/search?* // @match https://www.google.bg/search?* // @match https://www.google.com.bh/search?* // @match https://www.google.bi/search?* // @match https://www.google.bj/search?* // @match https://www.google.com.bn/search?* // @match https://www.google.com.bo/search?* // @match https://www.google.com.br/search?* // @match https://www.google.bs/search?* // @match https://www.google.bt/search?* // @match https://www.google.co.bw/search?* // @match https://www.google.by/search?* // @match https://www.google.com.bz/search?* // @match https://www.google.ca/search?* // @match https://www.google.cd/search?* // @match https://www.google.cf/search?* // @match https://www.google.cg/search?* // @match https://www.google.ch/search?* // @match https://www.google.ci/search?* // @match https://www.google.co.ck/search?* // @match https://www.google.cl/search?* // @match https://www.google.cm/search?* // @match https://www.google.cn/search?* // @match https://www.google.com.co/search?* // @match https://www.google.co.cr/search?* // @match https://www.google.com.cu/search?* // @match https://www.google.cv/search?* // @match https://www.google.com.cy/search?* // @match https://www.google.cz/search?* // @match https://www.google.de/search?* // @match https://www.google.dj/search?* // @match https://www.google.dk/search?* // @match https://www.google.dm/search?* // @match https://www.google.com.do/search?* // @match https://www.google.dz/search?* // @match https://www.google.com.ec/search?* // @match https://www.google.ee/search?* // @match https://www.google.com.eg/search?* // @match https://www.google.es/search?* // @match https://www.google.com.et/search?* // @match https://www.google.fi/search?* // @match https://www.google.com.fj/search?* // @match https://www.google.fm/search?* // @match https://www.google.fr/search?* // @match https://www.google.ga/search?* // @match https://www.google.ge/search?* // @match https://www.google.gg/search?* // @match https://www.google.com.gh/search?* // @match https://www.google.com.gi/search?* // @match https://www.google.gl/search?* // @match https://www.google.gm/search?* // @match https://www.google.gp/search?* // @match https://www.google.gr/search?* // @match https://www.google.com.gt/search?* // @match https://www.google.gy/search?* // @match https://www.google.com.hk/search?* // @match https://www.google.hn/search?* // @match https://www.google.hr/search?* // @match https://www.google.ht/search?* // @match https://www.google.hu/search?* // @match https://www.google.co.id/search?* // @match https://www.google.ie/search?* // @match https://www.google.co.il/search?* // @match https://www.google.im/search?* // @match https://www.google.co.in/search?* // @match https://www.google.iq/search?* // @match https://www.google.is/search?* // @match https://www.google.it/search?* // @match https://www.google.je/search?* // @match https://www.google.com.jm/search?* // @match https://www.google.jo/search?* // @match https://www.google.co.jp/search?* // @match https://www.google.co.ke/search?* // @match https://www.google.com.kh/search?* // @match https://www.google.ki/search?* // @match https://www.google.kg/search?* // @match https://www.google.co.kr/search?* // @match https://www.google.com.kw/search?* // @match https://www.google.kz/search?* // @match https://www.google.la/search?* // @match https://www.google.com.lb/search?* // @match https://www.google.li/search?* // @match https://www.google.lk/search?* // @match https://www.google.co.ls/search?* // @match https://www.google.lt/search?* // @match https://www.google.lu/search?* // @match https://www.google.lv/search?* // @match https://www.google.com.ly/search?* // @match https://www.google.co.ma/search?* // @match https://www.google.md/search?* // @match https://www.google.me/search?* // @match https://www.google.mg/search?* // @match https://www.google.mk/search?* // @match https://www.google.ml/search?* // @match https://www.google.com.mm/search?* // @match https://www.google.mn/search?* // @match https://www.google.ms/search?* // @match https://www.google.com.mt/search?* // @match https://www.google.mu/search?* // @match https://www.google.mv/search?* // @match https://www.google.mw/search?* // @match https://www.google.com.mx/search?* // @match https://www.google.com.my/search?* // @match https://www.google.co.mz/search?* // @match https://www.google.com.na/search?* // @match https://www.google.com.nf/search?* // @match https://www.google.com.ng/search?* // @match https://www.google.com.ni/search?* // @match https://www.google.ne/search?* // @match https://www.google.nl/search?* // @match https://www.google.no/search?* // @match https://www.google.com.np/search?* // @match https://www.google.nr/search?* // @match https://www.google.nu/search?* // @match https://www.google.co.nz/search?* // @match https://www.google.com.om/search?* // @match https://www.google.com.pa/search?* // @match https://www.google.com.pe/search?* // @match https://www.google.com.pg/search?* // @match https://www.google.com.ph/search?* // @match https://www.google.com.pk/search?* // @match https://www.google.pl/search?* // @match https://www.google.pn/search?* // @match https://www.google.com.pr/search?* // @match https://www.google.ps/search?* // @match https://www.google.pt/search?* // @match https://www.google.com.py/search?* // @match https://www.google.com.qa/search?* // @match https://www.google.ro/search?* // @match https://www.google.ru/search?* // @match https://www.google.rw/search?* // @match https://www.google.com.sa/search?* // @match https://www.google.com.sb/search?* // @match https://www.google.sc/search?* // @match https://www.google.se/search?* // @match https://www.google.com.sg/search?* // @match https://www.google.sh/search?* // @match https://www.google.si/search?* // @match https://www.google.sk/search?* // @match https://www.google.com.sl/search?* // @match https://www.google.sn/search?* // @match https://www.google.so/search?* // @match https://www.google.sm/search?* // @match https://www.google.sr/search?* // @match https://www.google.st/search?* // @match https://www.google.com.sv/search?* // @match https://www.google.td/search?* // @match https://www.google.tg/search?* // @match https://www.google.co.th/search?* // @match https://www.google.com.tj/search?* // @match https://www.google.tk/search?* // @match https://www.google.tl/search?* // @match https://www.google.tm/search?* // @match https://www.google.tn/search?* // @match https://www.google.to/search?* // @match https://www.google.com.tr/search?* // @match https://www.google.tt/search?* // @match https://www.google.com.tw/search?* // @match https://www.google.co.tz/search?* // @match https://www.google.com.ua/search?* // @match https://www.google.co.ug/search?* // @match https://www.google.co.uk/search?* // @match https://www.google.com.uy/search?* // @match https://www.google.co.uz/search?* // @match https://www.google.com.vc/search?* // @match https://www.google.co.ve/search?* // @match https://www.google.vg/search?* // @match https://www.google.co.vi/search?* // @match https://www.google.com.vn/search?* // @match https://www.google.vu/search?* // @match https://www.google.ws/search?* // @match https://www.google.rs/search?* // @match https://www.google.co.za/search?* // @match https://www.google.co.zm/search?* // @match https://www.google.co.zw/search?* // @match https://www.google.cat/search?* // @grant GM_setValue // @grant GM_getValue // @grant GM_listValues // @grant GM_deleteValue // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @grant GM_openInTab // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAFGElEQVRoQ9VaXShtWRz/LR6vKHHLy8xpJOqWFCci3ZqEBx4IRY3JV8LMxMxEwkwzSDQzdO9F8tXcKQrxwAMyU5PICSV1i2Ry50UNKcY8sqb/bu/TPtv+WvvsM9NZb2fttf7r9/uv/9da6zC40DjnHwB4CcAL4AUAD4DnAJ7J4v8B8BeACwDvAOwD+J0x9mewyzOnAjjncQCqAVQAyHQoxwdgAcBbxti1ExnCBGRtfw3gMwDC8w1AcgBvAPwguitCADjnPQC+0wO+ubmJ7e1tHB0d4ezsDJeXl7i/v5fwRkVFISEhAUlJSUhLS0Nubi7y8/P1uBCRbxljvXZ3wxYBznk6gFGtqezu7mJ2dhYLCwu4u7uzu6Y0Ljo6GhUVFaipqUF2drZ2LplWC2Ps0EqoJQHO+ScAflZrnYAPDAxgbW3NSr6t70VFRejs7NQSod34lDH2i5kQUwKc8y8B/KgW0NbWhpGREVvARAe1trZieHhYO+0rxthPRrIMCWjBHx8fo7a2FoeHlrsqijtgfHp6OmZmZpCamqruNyShS0A2m7eKBHLQ8vJyYTt3yoT8Y3FxUevo1Xrm9ISA7LCUaKRvBL6wsBCck0mat5KSEuTl5YG0mJiYiNjYWGnCzc0Nzs/Ppd3b2trCysqKlSgwxrC+vq4mQQC8WsfWI7CnRBsyGwp5ZhGGtNXe3o7GxkbExVFus27X19eYmJjA0NCQpWwKzSpz8jHGstQrBBCQ4/z3yoCMjAxTmyefGBwctA1cS42IeL1eXFxQhaHfaDcPDg7UH79R5wk/ATnDkiSpzyrajI6Oorm52VrdJiPIr5aWlixlaKITmZJHydhqAq8AfE7SKM7n5OQYCp6bm0NlZaXlwmYD7IJXZOzs7KjzxGvG2Bf0TSIgF2ZULUq/i4uLDZPUf6l5tQIo2a2uripdtAvPqQBUCPgTlpn2yeanp6dDqnmPx2PoE5pdkHKDQsAfeRoaGjA1NfUEJEUbCoV2I40eSyuzKSsrw/j4uBSC9SJffX09JicnFdFSRGKy875XemNiYnQn9/X1oaury7H27YCn5EWtv78f3d3dukq8vb1V939IBKhYk7IuJa2CggJdkFdXV461LwKeFqfwGh8fr4tjY2NDndyqiYA/+vT09IA0rW2UYZeXlx1pXxS8skhpaaluxqad6e31HxdeE4FfAXxsFn2cRh6n4AnL2NgYWlpanihNE41+IwLnAD6ikSkpKTg9PX0yaW9vD5mZYsfeYMATAJ/Ph6ysgKpBwpWcnIyTkxMF4x9E4G869VGPkQOL2n+w4M38gKKhypHvicCjksAiIyPx+Eg/A9vDwwMiIiJs+YAb4GkhwkF4tI1wEB65cVcJuAVelIArJuQmeFETCtqJ3QYv6sRBhdFQgBcNo44TWajAEwGRROaolAgleNFSgm6WhYq5UIIn7QsVczSBc267nG5qajI9BlJJrFSVthKHZhBpX6iclgnYOtCYHTZITrDgSUZdXZ10saXXzA40dB9i60hppFU3wBsVcLSm6ZFS3gXbh3otCTfAz8/Po6qqytDqTA/1MgFyZtvXKspKboA30zytY+taRSZBDxi2L7bIJ/b39x2f1MhhOzo6DG2eMNm+2PKXd6qIFHZXi/Iu0GtM+F7uyiT82Zl+h9X1usqUAl5nwuqBw4gE9Vtd+jrJvsocV5+YVCTC95FPRSJ8n1nVJhG2D90aEpSxw/OvBhoi4flnD70o83/+3eZfGPyIZF68J1kAAAAASUVORK5CYII= // @run-at document-start // ==/UserScript== console.log("Script start:",performance.now());const e=!0,t=e=>e,o="passthrough";let s,c={createHTML:t,createScript:t,createScriptURL:t},i=!1;const r=()=>{try{void 0!==window.isSecureContext&&window.isSecureContext&&window.trustedTypes&&window.trustedTypes.createPolicy&&(i=!0,trustedTypes.defaultPolicy?(l("TT Default Policy exists"),c=window.trustedTypes.createPolicy("default",c),s=trustedTypes.defaultPolicy,l(`Created custom passthrough policy, in case the default policy is too restrictive: Use Policy '${o}' in var 'TTP':`,c)):s=c=window.trustedTypes.createPolicy("default",c),l("Trusted-Type Policies: TTP:",c,"TTP_default:",s))}catch(e){l(e)}},l=(...e)=>{console.log(...e)};r(); (function() { // #region Logging const SCRIPT_NAME = "uBlacklist"; const _log = (...args) => {}; const _warn = (...args) => console.warn(`[${typeof SCRIPT_NAME === 'string' ? SCRIPT_NAME : '[USERSCRIPT_CONVERTED]'}]`, ...args); const _error = (...args) => { let e = args[0]; console.error(`[${typeof SCRIPT_NAME === 'string' ? SCRIPT_NAME : '[USERSCRIPT_CONVERTED]'}]`, ...args); } // #endregion // #region Unified Polyfill // #region Messaging implementation function createEventBus( scopeId, type = "page", // "page" or "iframe" { allowedOrigin = "*", children = [], parentWindow = null } = {} ) { if (!scopeId) throw new Error("createEventBus requires a scopeId"); const handlers = {}; function handleIncoming(ev) { if (allowedOrigin !== "*" && ev.origin !== allowedOrigin) return; const msg = ev.data; if (!msg || msg.__eventBus !== true || msg.scopeId !== scopeId) return; const { event, payload } = msg; // PAGE: if it's an INIT from an iframe, adopt it if (type === "page" && event === "__INIT__") { const win = ev.source; if (win && !children.includes(win)) { children.push(win); } return; } (handlers[event] || []).forEach((fn) => fn(payload, { origin: ev.origin, source: ev.source }) ); } window.addEventListener("message", handleIncoming); function emitTo(win, event, payload) { const envelope = { __eventBus: true, scopeId, event, payload, }; win.postMessage(envelope, allowedOrigin); } // IFRAME: announce to page on startup if (type === "iframe") { setTimeout(() => { const pw = parentWindow || window.parent; if (pw && pw.postMessage) { emitTo(pw, "__INIT__", null); } }, 0); } return { on(event, fn) { handlers[event] = handlers[event] || []; handlers[event].push(fn); }, off(event, fn) { if (!handlers[event]) return; handlers[event] = handlers[event].filter((h) => h !== fn); }, /** * Emits an event. * @param {string} event - The event name. * @param {any} payload - The event payload. * @param {object} [options] - Emission options. * @param {Window} [options.to] - A specific window to target. If provided, message is ONLY sent to the target. */ emit(event, payload, { to } = {}) { // If a specific target window is provided, send only to it and DO NOT dispatch locally. // This prevents a port from receiving its own messages. if (to) { if (to && typeof to.postMessage === "function") { emitTo(to, event, payload); } return; // Exit after targeted send. } // For broadcast messages (no 'to' target), dispatch locally first. (handlers[event] || []).forEach((fn) => fn(payload, { origin: location.origin, source: window }) ); // Then propagate the broadcast to other windows. if (type === "page") { children.forEach((win) => emitTo(win, event, payload)); } else { const pw = parentWindow || window.parent; if (pw && pw.postMessage) { emitTo(pw, event, payload); } } }, }; } function createRuntime(type = "background", bus) { let nextId = 1; const pending = {}; const msgListeners = []; let nextPortId = 1; const ports = {}; const onConnectListeners = []; function parseArgs(args) { let target, message, options, callback; const arr = [...args]; if (arr.length === 0) { throw new Error("sendMessage requires at least one argument"); } if (arr.length === 1) { return { message: arr[0] }; } // last object could be options if ( arr.length && typeof arr[arr.length - 1] === "object" && !Array.isArray(arr[arr.length - 1]) ) { options = arr.pop(); } // last function is callback if (arr.length && typeof arr[arr.length - 1] === "function") { callback = arr.pop(); } if ( arr.length === 2 && (typeof arr[0] === "string" || typeof arr[0] === "number") ) { [target, message] = arr; } else { [message] = arr; } return { target, message, options, callback }; } if (type === "background") { bus.on("__REQUEST__", ({ id, message }, { source }) => { let responded = false, isAsync = false; function sendResponse(resp) { if (responded) return; responded = true; // Target the response directly back to the window that sent the request. bus.emit("__RESPONSE__", { id, response: resp }, { to: source }); } const results = msgListeners .map((fn) => { try { // msg, sender, sendResponse const ret = fn(message, { id, tab: { id: source } }, sendResponse); if (ret === true || (ret && typeof ret.then === "function")) { isAsync = true; return ret; } return ret; } catch (e) { _error(e); } }) .filter((r) => r !== undefined); const promises = results.filter((r) => r && typeof r.then === "function"); if (!isAsync && promises.length === 0) { const out = results.length === 1 ? results[0] : results; sendResponse(out); } else if (promises.length) { Promise.all(promises).then((vals) => { if (!responded) { const out = vals.length === 1 ? vals[0] : vals; sendResponse(out); } }); } }); } if (type !== "background") { bus.on("__RESPONSE__", ({ id, response }) => { const entry = pending[id]; if (!entry) return; entry.resolve(response); if (entry.callback) entry.callback(response); delete pending[id]; }); } function sendMessage(...args) { // Background should be able to send message to itself // if (type === "background") { // throw new Error("Background cannot sendMessage to itself"); // } const { target, message, callback } = parseArgs(args); const id = nextId++; const promise = new Promise((resolve) => { pending[id] = { resolve, callback }; bus.emit("__REQUEST__", { id, message }); }); return promise; } bus.on("__PORT_CONNECT__", ({ portId, name }, { source }) => { if (type !== "background") return; const backgroundPort = makePort("background", portId, name, source); ports[portId] = backgroundPort; onConnectListeners.forEach((fn) => fn(backgroundPort)); // send back a CONNECT_ACK so the client can // start listening on its end: bus.emit("__PORT_CONNECT_ACK__", { portId, name }, { to: source }); }); // Clients handle the ACK and finalize their Port object by learning the remote window. bus.on("__PORT_CONNECT_ACK__", ({ portId, name }, { source }) => { if (type === "background") return; // ignore const p = ports[portId]; if (!p) return; // Call the port's internal finalize method to complete the handshake if (p._finalize) { p._finalize(source); } }); // Any port message travels via "__PORT_MESSAGE__" bus.on("__PORT_MESSAGE__", (envelope, { source }) => { const { portId } = envelope; const p = ports[portId]; if (!p) return; p._receive(envelope, source); }); // Any port disconnect: bus.on("__PORT_DISCONNECT__", ({ portId }) => { const p = ports[portId]; if (!p) return; p._disconnect(); delete ports[portId]; }); // Refactored makePort to correctly manage internal state and the connection handshake. function makePort(side, portId, name, remoteWindow) { let onMessageHandlers = []; let onDisconnectHandlers = []; let buffer = []; // Unique instance ID for this port instance const instanceId = Math.random().toString(36).slice(2) + Date.now(); // These state variables are part of the closure and are updated by _finalize let _ready = side === "background"; function _drainBuffer() { buffer.forEach((m) => _post(m)); buffer = []; } function _post(msg) { // Always use the 'to' parameter for port messages, making them directional. // Include senderInstanceId bus.emit( "__PORT_MESSAGE__", { portId, msg, senderInstanceId: instanceId }, { to: remoteWindow } ); } function postMessage(msg) { if (!_ready) { buffer.push(msg); } else { _post(msg); } } function _receive(envelope, source) { // envelope: { msg, senderInstanceId } if (envelope.senderInstanceId === instanceId) return; // Don't dispatch to self onMessageHandlers.forEach((fn) => fn(envelope.msg, { id: portId, tab: { id: source } }) ); } function disconnect() { // Also use the 'to' parameter for disconnect messages bus.emit("__PORT_DISCONNECT__", { portId }, { to: remoteWindow }); _disconnect(); delete ports[portId]; } function _disconnect() { onDisconnectHandlers.forEach((fn) => fn()); onMessageHandlers = []; onDisconnectHandlers = []; } // This function is called on the client port when the ACK is received from background. // It updates the port's state, completing the connection. function _finalize(win) { remoteWindow = win; // <-- This is the crucial part: learn the destination _ready = true; _drainBuffer(); } return { name, sender: { id: portId, }, onMessage: { addListener(fn) { onMessageHandlers.push(fn); }, removeListener(fn) { onMessageHandlers = onMessageHandlers.filter((x) => x !== fn); }, }, onDisconnect: { addListener(fn) { onDisconnectHandlers.push(fn); }, removeListener(fn) { onDisconnectHandlers = onDisconnectHandlers.filter((x) => x !== fn); }, }, postMessage, disconnect, // Internal methods used by the runtime _receive, _disconnect, _finalize, // Expose the finalizer for the ACK handler }; } function connect(connectInfo = {}) { if (type === "background") { throw new Error("Background must use onConnect, not connect()"); } const name = connectInfo.name || ""; const portId = nextPortId++; // create the client side port // remoteWindow is initially null; it will be set by _finalize upon ACK. const clientPort = makePort("client", portId, name, null); ports[portId] = clientPort; // fire the connect event across the bus bus.emit("__PORT_CONNECT__", { portId, name }); return clientPort; } function onConnect(fn) { if (type !== "background") { throw new Error("connect event only fires in background"); } onConnectListeners.push(fn); } return { // rpc: sendMessage, onMessage: { addListener(fn) { msgListeners.push(fn); }, removeListener(fn) { const i = msgListeners.indexOf(fn); if (i >= 0) msgListeners.splice(i, 1); }, }, // port API: connect, onConnect: { addListener(fn) { onConnect(fn); }, removeListener(fn) { const i = onConnectListeners.indexOf(fn); if (i >= 0) onConnectListeners.splice(i, 1); }, }, }; } // #region Abstraction layer Handle postmesage for (function () { const pendingRequests = new Map(); // requestId -> { resolve, reject, timeout } let nextRequestId = 1; window.addEventListener("message", async (event) => { const { type, requestId, method, args } = event.data; if (type === "abstraction-request") { try { let result; switch (method) { case "_storageSet": result = await _storageSet(args[0]); break; case "_storageGet": result = await _storageGet(args[0]); break; case "_storageRemove": result = await _storageRemove(args[0]); break; case "_storageClear": result = await _storageClear(); break; case "_cookieList": result = await _cookieList(args[0]); break; case "_cookieSet": result = await _cookieSet(args[0]); break; case "_cookieDelete": result = await _cookieDelete(args[0]); break; case "_fetch": result = await _fetch(args[0], args[1]); break; case "_registerMenuCommand": result = _registerMenuCommand(args[0], args[1]); break; case "_openTab": result = _openTab(args[0], args[1]); break; case "_initStorage": result = await _initStorage(); break; default: throw new Error(`Unknown abstraction method: ${method}`); } event.source.postMessage({ type: "abstraction-response", requestId, success: true, result, }); } catch (error) { event.source.postMessage({ type: "abstraction-response", requestId, success: false, error: { message: error.message, stack: error.stack, }, }); } } }); _log("[PostMessage Handler] Abstraction layer message handler initialized"); })(); // #endregion // #region Abstraction Layer Userscript Target async function _storageSet(items) { try { for (const key in items) { if (items.hasOwnProperty(key)) { await GM_setValue(key, items[key]); } } return Promise.resolve(); } catch (e) { _error("GM_setValue error:", e); return Promise.reject(e); } } async function _storageGet(keys) { if (!keys) { keys = null; } if ( Array.isArray(keys) && (keys.length === 0 || [null, undefined].includes(keys[0])) ) { keys = null; } try { const results = {}; let keyList = []; let defaults = {}; let requestedKeys = []; if (keys === null) { keyList = await GM_listValues(); requestedKeys = [...keyList]; } else if (typeof keys === "string") { keyList = [keys]; requestedKeys = [keys]; } else if (Array.isArray(keys)) { keyList = keys; requestedKeys = [...keys]; } else if (typeof keys === "object" && keys !== null) { keyList = Object.keys(keys); requestedKeys = [...keyList]; defaults = keys; } else { _error("_storageGet error: Invalid keys format", keys); return Promise.reject(new Error("Invalid keys format for get")); } for (const key of keyList) { const defaultValue = defaults.hasOwnProperty(key) ? defaults[key] : undefined; const storedValue = await GM_getValue(key, defaultValue); results[key] = storedValue; } const finalResult = {}; for (const key of requestedKeys) { if (results.hasOwnProperty(key)) { finalResult[key] = results[key]; } else if (defaults.hasOwnProperty(key)) { finalResult[key] = defaults[key]; } } return Promise.resolve(finalResult); } catch (e) { _error("GM_getValue/GM_listValues error:", e); return Promise.reject(e); } } async function _storageRemove(keysToRemove) { try { let keyList = []; if (typeof keysToRemove === "string") { keyList = [keysToRemove]; } else if (Array.isArray(keysToRemove)) { keyList = keysToRemove; } else { _error("_storageRemove error: Invalid keys format", keysToRemove); return Promise.reject(new Error("Invalid keys format for remove")); } for (const key of keyList) { await GM_deleteValue(key); } return Promise.resolve(); } catch (e) { _error("GM_deleteValue error:", e); return Promise.reject(e); } } async function _storageClear() { try { const keys = await GM_listValues(); await Promise.all(keys.map((key) => GM_deleteValue(key))); return Promise.resolve(); } catch (e) { _error("GM_listValues/GM_deleteValue error during clear:", e); return Promise.reject(e); } } async function _cookieList(details) { return new Promise((resolve, reject) => { if (typeof GM_cookie === "undefined" || !GM_cookie.list) { return reject(new Error("GM_cookie.list is not available.")); } GM_cookie.list(details, (cookies, error) => { if (error) { return reject(new Error(error)); } resolve(cookies); }); }); } async function _cookieSet(details) { return new Promise((resolve, reject) => { if (typeof GM_cookie === "undefined" || !GM_cookie.set) { return reject(new Error("GM_cookie.set is not available.")); } GM_cookie.set(details, (error) => { if (error) { return reject(new Error(error)); } resolve(); }); }); } async function _cookieDelete(details) { return new Promise((resolve, reject) => { if (typeof GM_cookie === "undefined" || !GM_cookie.delete) { return reject(new Error("GM_cookie.delete is not available.")); } GM_cookie.delete(details, (error) => { if (error) { return reject(new Error(error)); } resolve(); }); }); } async function _fetch(url, options = {}) { return new Promise((resolve, reject) => { try { GM_xmlhttpRequest({ method: options.method || "GET", url: url, headers: options.headers || {}, data: options.body, responseType: options.responseType, timeout: options.timeout || 0, binary: options.responseType === "blob" || options.responseType === "arraybuffer", onload: function (response) { const responseHeaders = {}; if (response.responseHeaders) { response.responseHeaders .trim() .split("\\r\\n") .forEach((header) => { const parts = header.match(/^([^:]+):\s*(.*)$/); if (parts && parts.length === 3) { responseHeaders[parts[1].toLowerCase()] = parts[2]; } }); } const mockResponse = { ok: response.status >= 200 && response.status < 300, status: response.status, statusText: response.statusText || (response.status >= 200 && response.status < 300 ? "OK" : ""), url: response.finalUrl || url, headers: new Headers(responseHeaders), text: () => Promise.resolve(response.responseText), json: () => { try { return Promise.resolve(JSON.parse(response.responseText)); } catch (e) { return Promise.reject(new SyntaxError("Could not parse JSON")); } }, blob: () => { if (response.response instanceof Blob) { return Promise.resolve(response.response); } return Promise.reject( new Error("Requires responseType:'blob' in GM_xmlhttpRequest") ); }, arrayBuffer: () => { if (response.response instanceof ArrayBuffer) { return Promise.resolve(response.response); } return Promise.reject( new Error( "Requires responseType:'arraybuffer' in GM_xmlhttpRequest" ) ); }, clone: function () { const cloned = { ...this }; cloned.text = () => Promise.resolve(response.responseText); cloned.json = () => this.json(); cloned.blob = () => this.blob(); cloned.arrayBuffer = () => this.arrayBuffer(); return cloned; }, }; if (mockResponse.ok) { resolve(mockResponse); } else { const error = new Error(`HTTP error! status: ${response.status}`); error.response = mockResponse; reject(error); } }, onerror: function (response) { reject( new Error( `GM_xmlhttpRequest network error: ${ response.statusText || "Unknown Error" }` ) ); }, onabort: function () { reject(new Error("GM_xmlhttpRequest aborted")); }, ontimeout: function () { reject(new Error("GM_xmlhttpRequest timed out")); }, }); } catch (e) { _error("_fetch (GM_xmlhttpRequest) error:", e); reject(e); } }); } function _registerMenuCommand(name, func) { if (typeof GM_registerMenuCommand === "function") { try { GM_registerMenuCommand(name, func); } catch (e) { _error("GM_registerMenuCommand failed:", e); } } else { _warn("GM_registerMenuCommand not available."); } } function _openTab(url, active) { if (typeof GM_openInTab === "function") { try { GM_openInTab(url, { loadInBackground: !active }); } catch (e) { _error("GM_openInTab failed:", e); } } else { _warn("GM_openInTab not available, using window.open as fallback."); try { window.open(url); } catch (e) { _error("window.open fallback failed:", e); } } } async function _initStorage() { return Promise.resolve(); } const EXTENSION_ASSETS_MAP = { "pages/options.html": "\n\n \n \n \n \n Options\n \n \n
\n \n \n\n", "pages/popup.html": "\n\n \n \n \n \n \n \n
\n \n \n\n", "pages/serpinfo/options.html": "\n\n \n \n \n \n SERPINFO Options\n \n \n
\n \n \n\n" }; // #endregion // #endregion // #region Polyfill Implementation function buildPolyfill({ isBackground = false, isOtherPage = false } = {}) { // Generate a unique context ID for this polyfill instance const contextType = isBackground ? "background" : isOtherPage ? "options" : "content"; const contextId = `${contextType}_${Math.random() .toString(36) .substring(2, 15)}`; const IS_IFRAME = "false" === "true"; const BUS = (function () { if (globalThis.__BUS) { return globalThis.__BUS; } globalThis.__BUS = createEventBus( "ublacklist", IS_IFRAME ? "iframe" : "page", ); return globalThis.__BUS; })(); const RUNTIME = createRuntime(isBackground ? "background" : "tab", BUS); const createNoopListeners = () => ({ addListener: (callback) => { _log("addListener", callback); }, removeListener: (callback) => { _log("removeListener", callback); }, }); // TODO: Stub const storageChangeListeners = new Set(); function broadcastStorageChange(changes, areaName) { storageChangeListeners.forEach((listener) => { listener(changes, areaName); }); } let REQ_PERMS = []; // #region Chrome polyfill let chrome = { extension: { isAllowedIncognitoAccess: () => Promise.resolve(true), sendMessage: (...args) => _messagingHandler.sendMessage(...args), }, permissions: { // TODO: Remove origin permission means exclude from origin in startup (when checking for content scripts) request: (permissions, callback) => { _log("permissions.request", permissions, callback); if (Array.isArray(permissions)) { REQ_PERMS = [...REQ_PERMS, ...permissions]; } if (typeof callback === "function") { callback(permissions); } return Promise.resolve(permissions); }, contains: (permissions, callback) => { if (typeof callback === "function") { callback(true); } return Promise.resolve(true); }, getAll: () => { return Promise.resolve({ permissions: EXTENSION_PERMISSIONS, origins: ORIGIN_PERMISSIONS, }); }, onAdded: createNoopListeners(), onRemoved: createNoopListeners(), }, i18n: { getUILanguage: () => { return USED_LOCALE || "en"; }, getMessage: (key, substitutions = []) => { if (typeof substitutions === "string") { substitutions = [substitutions]; } if (typeof LOCALE_KEYS !== "undefined" && LOCALE_KEYS[key]) { return LOCALE_KEYS[key].message?.replace( /\$(\d+)/g, (match, p1) => substitutions[p1 - 1] || match, ); } return key; }, }, alarms: { onAlarm: createNoopListeners(), create: () => { _log("alarms.create", arguments); }, get: () => { _log("alarms.get", arguments); }, }, runtime: { ...RUNTIME, onInstalled: createNoopListeners(), onStartup: createNoopListeners(), // TODO: Postmessage to parent to open options page or call openOptionsPage openOptionsPage: () => { // const url = chrome.runtime.getURL(OPTIONS_PAGE_PATH); // console.log("openOptionsPage", _openTab, url, EXTENSION_ASSETS_MAP); // _openTab(url); if (typeof openOptionsPage === "function") { openOptionsPage(); } else if (window.parent) { window.parent.postMessage({ type: "openOptionsPage" }, "*"); } else { _warn("openOptionsPage not available."); } }, getManifest: () => { // The manifest object will be injected into the scope where buildPolyfill is called if (typeof INJECTED_MANIFEST !== "undefined") { return JSON.parse(JSON.stringify(INJECTED_MANIFEST)); // Return deep copy } _warn("INJECTED_MANIFEST not found for chrome.runtime.getManifest"); return { name: "Unknown", version: "0.0", manifest_version: 2 }; }, getURL: (path) => { if (!path) return ""; if (path.startsWith("/")) { path = path.substring(1); } if (typeof _createAssetUrl === "function") { return _createAssetUrl(path); } _warn( `chrome.runtime.getURL fallback for '${path}'. Assets may not be available.`, ); // Attempt a relative path resolution (highly context-dependent and likely wrong) try { if (window.location.protocol.startsWith("http")) { return new URL(path, window.location.href).toString(); } } catch (e) { /* ignore error, fallback */ } return path; }, id: "polyfilled-extension-" + Math.random().toString(36).substring(2, 15), lastError: null, setUninstallURL: () => {}, setUpdateURL: () => {}, getPlatformInfo: async () => { const platform = { os: "unknown", arch: "unknown", nacl_arch: "unknown", }; if (typeof navigator !== "undefined") { const userAgent = navigator.userAgent.toLowerCase(); if (userAgent.includes("mac")) platform.os = "mac"; else if (userAgent.includes("win")) platform.os = "win"; else if (userAgent.includes("linux")) platform.os = "linux"; else if (userAgent.includes("android")) platform.os = "android"; else if (userAgent.includes("ios")) platform.os = "ios"; if (userAgent.includes("x86_64") || userAgent.includes("amd64")) { platform.arch = "x86-64"; } else if (userAgent.includes("i386") || userAgent.includes("i686")) { platform.arch = "x86-32"; } else if (userAgent.includes("arm")) { platform.arch = "arm"; } } return platform; }, getBrowserInfo: async () => { const info = { name: "unknown", version: "unknown", buildID: "unknown", }; if (typeof navigator !== "undefined") { const userAgent = navigator.userAgent; if (userAgent.includes("Chrome")) { info.name = "Chrome"; const match = userAgent.match(/Chrome\/([0-9.]+)/); if (match) info.version = match[1]; } else if (userAgent.includes("Firefox")) { info.name = "Firefox"; const match = userAgent.match(/Firefox\/([0-9.]+)/); if (match) info.version = match[1]; } else if (userAgent.includes("Safari")) { info.name = "Safari"; const match = userAgent.match(/Version\/([0-9.]+)/); if (match) info.version = match[1]; } } return info; }, }, storage: { local: { get: function (keys, callback) { if (typeof _storageGet !== "function") throw new Error("_storageGet not defined"); const promise = _storageGet(keys); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.get callback:", e); } }) .catch((error) => { _error("Storage.get error:", error); callback({}); }); return; } return promise; }, set: function (items, callback) { if (typeof _storageSet !== "function") throw new Error("_storageSet not defined"); const promise = _storageSet(items).then((result) => { broadcastStorageChange(items, "local"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.set callback:", e); } }) .catch((error) => { _error("Storage.set error:", error); callback(); }); return; } return promise; }, remove: function (keys, callback) { if (typeof _storageRemove !== "function") throw new Error("_storageRemove not defined"); const promise = _storageRemove(keys).then((result) => { const changes = {}; const keyList = Array.isArray(keys) ? keys : [keys]; keyList.forEach((key) => { changes[key] = { oldValue: undefined, newValue: undefined }; }); broadcastStorageChange(changes, "local"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.remove callback:", e); } }) .catch((error) => { _error("Storage.remove error:", error); callback(); }); return; } return promise; }, clear: function (callback) { if (typeof _storageClear !== "function") throw new Error("_storageClear not defined"); const promise = _storageClear().then((result) => { broadcastStorageChange({}, "local"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.clear callback:", e); } }) .catch((error) => { _error("Storage.clear error:", error); callback(); }); return; } return promise; }, onChanged: { addListener: (callback) => { storageChangeListeners.add(callback); }, removeListener: (callback) => { storageChangeListeners.delete(callback); }, }, }, sync: { get: function (keys, callback) { _warn("chrome.storage.sync polyfill maps to local"); return chrome.storage.local.get(keys, callback); }, set: function (items, callback) { _warn("chrome.storage.sync polyfill maps to local"); const promise = chrome.storage.local.set(items).then((result) => { broadcastStorageChange(items, "sync"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.sync.set callback:", e); } }) .catch((error) => { _error("Storage.sync.set error:", error); callback(); }); return; } return promise; }, remove: function (keys, callback) { _warn("chrome.storage.sync polyfill maps to local"); const promise = chrome.storage.local.remove(keys).then((result) => { const changes = {}; const keyList = Array.isArray(keys) ? keys : [keys]; keyList.forEach((key) => { changes[key] = { oldValue: undefined, newValue: undefined }; }); broadcastStorageChange(changes, "sync"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.sync.remove callback:", e); } }) .catch((error) => { _error("Storage.sync.remove error:", error); callback(); }); return; } return promise; }, clear: function (callback) { _warn("chrome.storage.sync polyfill maps to local"); const promise = chrome.storage.local.clear().then((result) => { broadcastStorageChange({}, "sync"); return result; }); if (typeof callback === "function") { promise .then((result) => { try { callback(result); } catch (e) { _error("Error in storage.sync.clear callback:", e); } }) .catch((error) => { _error("Storage.sync.clear error:", error); callback(); }); return; } return promise; }, onChanged: { addListener: (callback) => { storageChangeListeners.add(callback); }, removeListener: (callback) => { storageChangeListeners.delete(callback); }, }, }, onChanged: { addListener: (callback) => { storageChangeListeners.add(callback); }, removeListener: (callback) => { storageChangeListeners.delete(callback); }, }, managed: { get: function (keys, callback) { _warn("chrome.storage.managed polyfill is read-only empty."); const promise = Promise.resolve({}); if (typeof callback === "function") { promise.then((result) => { try { callback(result); } catch (e) { _error("Error in storage.managed.get callback:", e); } }); return; } return promise; }, }, }, cookies: (function () { const cookieChangeListeners = new Set(); function broadcastCookieChange(changeInfo) { cookieChangeListeners.forEach((listener) => { try { listener(changeInfo); } catch (e) { _error("Error in cookies.onChanged listener:", e); } }); } function handlePromiseCallback(promise, callback) { if (typeof callback === "function") { promise .then((result) => callback(result)) .catch((error) => { // chrome.runtime.lastError = { message: error.message }; // TODO: Implement lastError _error(error); callback(); // Call with undefined on error }); return; } return promise; } return { get: function (details, callback) { if (typeof _cookieList !== "function") { return handlePromiseCallback( Promise.reject(new Error("_cookieList not defined")), callback, ); } const promise = _cookieList({ url: details.url, name: details.name, storeId: details.storeId, partitionKey: details.partitionKey, }).then((cookies) => { if (!cookies || cookies.length === 0) { return null; } // Sort by path length (longest first), then creation time (earliest first, if available) cookies.sort((a, b) => { const pathLenDiff = (b.path || "").length - (a.path || "").length; if (pathLenDiff !== 0) return pathLenDiff; return (a.creationTime || 0) - (b.creationTime || 0); }); return cookies[0]; }); return handlePromiseCallback(promise, callback); }, getAll: function (details, callback) { if (typeof _cookieList !== "function") { return handlePromiseCallback( Promise.reject(new Error("_cookieList not defined")), callback, ); } if (details.partitionKey) { _warn( "cookies.getAll: partitionKey is not fully supported in this environment.", ); } const promise = _cookieList(details); return handlePromiseCallback(promise, callback); }, set: function (details, callback) { const promise = (async () => { if ( typeof _cookieSet !== "function" || typeof _cookieList !== "function" ) { throw new Error("_cookieSet or _cookieList not defined"); } if (details.partitionKey) { _warn( "cookies.set: partitionKey is not fully supported in this environment.", ); } const getDetails = { url: details.url, name: details.name, storeId: details.storeId, }; const oldCookies = await _cookieList(getDetails); const oldCookie = oldCookies && oldCookies[0]; if (oldCookie) { broadcastCookieChange({ cause: "overwrite", cookie: oldCookie, removed: true, }); } await _cookieSet(details); const newCookies = await _cookieList(getDetails); const newCookie = newCookies && newCookies[0]; if (newCookie) { broadcastCookieChange({ cause: "explicit", cookie: newCookie, removed: false, }); } return newCookie || null; })(); return handlePromiseCallback(promise, callback); }, remove: function (details, callback) { const promise = (async () => { if ( typeof _cookieDelete !== "function" || typeof _cookieList !== "function" ) { throw new Error("_cookieDelete or _cookieList not defined"); } const oldCookies = await _cookieList(details); const oldCookie = oldCookies && oldCookies[0]; if (!oldCookie) return null; // Nothing to remove await _cookieDelete(details); broadcastCookieChange({ cause: "explicit", cookie: oldCookie, removed: true, }); return { url: details.url, name: details.name, storeId: details.storeId || "0", partitionKey: details.partitionKey, }; })(); return handlePromiseCallback(promise, callback); }, getAllCookieStores: function (callback) { const promise = Promise.resolve([ { id: "0", tabIds: [1] }, // Mock store for the current context ]); return handlePromiseCallback(promise, callback); }, getPartitionKey: function (details, callback) { _warn( "chrome.cookies.getPartitionKey is not supported in this environment.", ); const promise = Promise.resolve({ partitionKey: {} }); // Return empty partition key return handlePromiseCallback(promise, callback); }, onChanged: { addListener: (callback) => { if (typeof callback === "function") { cookieChangeListeners.add(callback); } }, removeListener: (callback) => { cookieChangeListeners.delete(callback); }, }, }; })(), tabs: { query: async (queryInfo) => { _warn("chrome.tabs.query polyfill only returns current tab info."); const dummyId = Math.floor(Math.random() * 1000) + 1; return [ { id: dummyId, url: CURRENT_LOCATION, active: true, windowId: 1, status: "complete", }, ]; }, create: async ({ url, active = true }) => { _log(`[Polyfill tabs.create] URL: ${url}`); if (typeof _openTab !== "function") throw new Error("_openTab not defined"); _openTab(url, active); const dummyId = Math.floor(Math.random() * 1000) + 1001; return Promise.resolve({ id: dummyId, url: url, active, windowId: 1, }); }, sendMessage: async (tabId, message) => { _warn( `chrome.tabs.sendMessage polyfill (to tab ${tabId}) redirects to runtime.sendMessage (current context).`, ); return chrome.runtime.sendMessage(message); }, onActivated: createNoopListeners(), onUpdated: createNoopListeners(), onRemoved: createNoopListeners(), onReplaced: createNoopListeners(), onCreated: createNoopListeners(), onMoved: createNoopListeners(), onDetached: createNoopListeners(), onAttached: createNoopListeners(), }, windows: { onFocusChanged: createNoopListeners(), onCreated: createNoopListeners(), onRemoved: createNoopListeners(), onFocused: createNoopListeners(), onFocus: createNoopListeners(), onBlur: createNoopListeners(), onFocused: createNoopListeners(), }, notifications: { create: async (notificationId, options) => { try { let id = notificationId; let notificationOptions = options; if (typeof notificationId === "object" && notificationId !== null) { notificationOptions = notificationId; id = "notification_" + Math.random().toString(36).substring(2, 15); } else if (typeof notificationId === "string" && options) { id = notificationId; notificationOptions = options; } else { throw new Error("Invalid parameters for notifications.create"); } if (!notificationOptions || typeof notificationOptions !== "object") { throw new Error("Notification options must be an object"); } const { title, message, iconUrl, type = "basic", } = notificationOptions; if (!title || !message) { throw new Error("Notification must have title and message"); } if ("Notification" in window) { if (Notification.permission === "granted") { const notification = new Notification(title, { body: message, icon: iconUrl, tag: id, }); _log(`[Notifications] Created notification: ${id}`); return id; } else if (Notification.permission === "default") { const permission = await Notification.requestPermission(); if (permission === "granted") { const notification = new Notification(title, { body: message, icon: iconUrl, tag: id, }); _log( `[Notifications] Created notification after permission: ${id}`, ); return id; } else { _warn("[Notifications] Permission denied for notifications"); return id; } } else { _warn("[Notifications] Notifications are blocked"); return id; } } else { _warn( "[Notifications] Native notifications not supported, using console fallback", ); _log(`[Notification] ${title}: ${message}`); return id; } } catch (error) { _error("[Notifications] Error creating notification:", error.message); throw error; } }, clear: async (notificationId) => { _log(`[Notifications] Clear notification: ${notificationId}`); // For native notifications, there's no direct way to clear by ID // This is a limitation of the Web Notifications API return true; }, getAll: async () => { _warn("[Notifications] getAll not fully supported in polyfill"); return {}; }, getPermissionLevel: async () => { if ("Notification" in window) { const permission = Notification.permission; return { level: permission === "granted" ? "granted" : "denied" }; } return { level: "denied" }; }, }, contextMenus: { create: (createProperties, callback) => { try { if (!createProperties || typeof createProperties !== "object") { throw new Error("Context menu create properties must be an object"); } const { id, title, contexts = ["page"], onclick } = createProperties; const menuId = id || `menu_${Math.random().toString(36).substring(2, 15)}`; if (!title || typeof title !== "string") { throw new Error("Context menu must have a title"); } // Store menu items for potential use if (!window._polyfillContextMenus) { window._polyfillContextMenus = new Map(); } window._polyfillContextMenus.set(menuId, { id: menuId, title, contexts, onclick, enabled: createProperties.enabled !== false, }); _log( `[ContextMenus] Created context menu item: ${title} (${menuId})`, ); // Try to register a menu command as fallback if (typeof _registerMenuCommand === "function") { try { _registerMenuCommand( title, onclick || (() => { _log(`Context menu clicked: ${title}`); }), ); } catch (e) { _warn( "[ContextMenus] Failed to register as menu command:", e.message, ); } } if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } return menuId; } catch (error) { _error("[ContextMenus] Error creating context menu:", error.message); if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } throw error; } }, update: (id, updateProperties, callback) => { try { if ( !window._polyfillContextMenus || !window._polyfillContextMenus.has(id) ) { throw new Error(`Context menu item not found: ${id}`); } const menuItem = window._polyfillContextMenus.get(id); Object.assign(menuItem, updateProperties); _log(`[ContextMenus] Updated context menu item: ${id}`); if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } catch (error) { _error("[ContextMenus] Error updating context menu:", error.message); if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } }, remove: (menuItemId, callback) => { try { if ( window._polyfillContextMenus && window._polyfillContextMenus.has(menuItemId) ) { window._polyfillContextMenus.delete(menuItemId); _log(`[ContextMenus] Removed context menu item: ${menuItemId}`); } else { _warn( `[ContextMenus] Context menu item not found for removal: ${menuItemId}`, ); } if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } catch (error) { _error("[ContextMenus] Error removing context menu:", error.message); if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } }, removeAll: (callback) => { try { if (window._polyfillContextMenus) { const count = window._polyfillContextMenus.size; window._polyfillContextMenus.clear(); _log(`[ContextMenus] Removed all ${count} context menu items`); } if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } catch (error) { _error( "[ContextMenus] Error removing all context menus:", error.message, ); if (callback && typeof callback === "function") { setTimeout(() => callback(), 0); } } }, onClicked: { addListener: (callback) => { if (!window._polyfillContextMenuListeners) { window._polyfillContextMenuListeners = new Set(); } window._polyfillContextMenuListeners.add(callback); _log("[ContextMenus] Added click listener"); }, removeListener: (callback) => { if (window._polyfillContextMenuListeners) { window._polyfillContextMenuListeners.delete(callback); _log("[ContextMenus] Removed click listener"); } }, }, }, }; const tc = (fn) => { try { fn(); } catch (e) {} }; const loggingProxyHandler = (_key) => ({ get(target, key, receiver) { tc(() => _log(`[${contextType}] [CHROME - ${_key}] Getting ${key}`)); return Reflect.get(target, key, receiver); }, set(target, key, value, receiver) { tc(() => _log(`[${contextType}] [CHROME - ${_key}] Setting ${key} to ${value}`), ); return Reflect.set(target, key, value, receiver); }, has(target, key) { tc(() => _log(`[${contextType}] [CHROME - ${_key}] Checking if ${key} exists`), ); return Reflect.has(target, key); }, }); chrome = Object.fromEntries( Object.entries(chrome).map(([key, value]) => [ key, new Proxy(value, loggingProxyHandler(key)), ]), ); // Alias browser to chrome for common Firefox pattern const browser = new Proxy(chrome, loggingProxyHandler); const oldGlobalThis = globalThis; const oldWindow = window; const oldSelf = self; const oldGlobal = globalThis; const __globalsStorage = {}; const TO_MODIFY = [oldGlobalThis, oldWindow, oldSelf, oldGlobal]; const set = (k, v) => { __globalsStorage[k] = v; TO_MODIFY.forEach((target) => { target[k] = v; }); }; const proxyHandler = { get(target, key, receiver) { const fns = [ () => __globalsStorage[key], () => Reflect.get(target, key, target), () => target[key], ]; const out = fns .map((f) => { try { let out = f(); return out; } catch (e) { return undefined; } }) .find((f) => f !== undefined); if (typeof out === "function") { return out.bind(target); } return out; }, set(target, key, value, receiver) { try { tc(() => _log(`[${contextType}] Setting ${key} to ${value}`)); set(key, value); return Reflect.set(target, key, value, receiver); } catch (e) { _error("Error setting", key, value, e); try { target[key] = value; return true; } catch (e) { _error("Error setting", key, value, e); } return false; } }, has(target, key) { try { return key in __globalsStorage || key in target; } catch (e) { _error("Error has", key, e); try { return key in __globalsStorage || key in target; } catch (e) { _error("Error has", key, e); } return false; } }, getOwnPropertyDescriptor(target, key) { try { if (key in __globalsStorage) { return { configurable: true, enumerable: true, writable: true, value: __globalsStorage[key], }; } // fall back to the real globalThis const desc = Reflect.getOwnPropertyDescriptor(target, key); // ensure it's configurable so the with‑scope binding logic can override it if (desc && !desc.configurable) { desc.configurable = true; } return desc; } catch (e) { _error("Error getOwnPropertyDescriptor", key, e); return { configurable: true, enumerable: true, writable: true, value: undefined, }; } }, defineProperty(target, key, descriptor) { try { // Normalize descriptor to avoid mixed accessor & data attributes const hasAccessor = "get" in descriptor || "set" in descriptor; if (hasAccessor) { // Build a clean descriptor without value/writable when accessors present const normalized = { configurable: "configurable" in descriptor ? descriptor.configurable : true, enumerable: "enumerable" in descriptor ? descriptor.enumerable : false, }; if ("get" in descriptor) normalized.get = descriptor.get; if ("set" in descriptor) normalized.set = descriptor.set; // Store accessor references for inspection but avoid breaking invariants set(key, { get: descriptor.get, set: descriptor.set, }); return Reflect.defineProperty(target, key, normalized); } // Data descriptor path set(key, descriptor.value); return Reflect.defineProperty(target, key, descriptor); } catch (e) { _error("Error defineProperty", key, descriptor, e); return false; } }, }; // Create proxies once proxyHandler is defined const proxyWindow = new Proxy(oldWindow, proxyHandler); const proxyGlobalThis = new Proxy(oldGlobalThis, proxyHandler); const proxyGlobal = new Proxy(oldGlobal, proxyHandler); const proxySelf = new Proxy(oldSelf, proxyHandler); // Seed storage with core globals so lookups succeed inside `with` blocks Object.assign(__globalsStorage, { chrome, browser, window: proxyWindow, globalThis: proxyGlobalThis, global: proxyGlobal, self: proxySelf, document: oldWindow.document, }); const __globals = { chrome, browser, window: proxyWindow, globalThis: proxyGlobalThis, global: proxyGlobal, self: proxySelf, __globals: __globalsStorage, }; __globals.contextId = contextId; __globals.contextType = contextType; __globals.module = undefined; __globals.amd = undefined; __globals.define = undefined; __globals.importScripts = (...args) => { _log("importScripts", args); }; return __globals; } if (typeof window !== 'undefined') { window.buildPolyfill = buildPolyfill; } // #endregion // #endregion // #endregion // #region Background Script Environment const START_BACKGROUND_SCRIPT = (function(){ const backgroundPolyfill = buildPolyfill({ isBackground: true }); const scriptName = "uBlacklist"; const debug = "[uBlacklist]"; _log(debug + ' Executing background scripts...'); function executeBackgroundScripts(){ with(backgroundPolyfill){ // BG: scripts/background.js (() => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name51 in all) __defProp(target, name51, { get: all[name51], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // node_modules/.pnpm/dayjs@1.11.13/node_modules/dayjs/dayjs.min.js var require_dayjs_min = __commonJS({ "node_modules/.pnpm/dayjs@1.11.13/node_modules/dayjs/dayjs.min.js"(exports, module) { !function(t2, e) { "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : (t2 = "undefined" != typeof globalThis ? globalThis : t2 || self).dayjs = e(); }(exports, function() { "use strict"; var t2 = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t3) { var e2 = ["th", "st", "nd", "rd"], n2 = t3 % 100; return "[" + t3 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]"; } }, m = function(t3, e2, n2) { var r2 = String(t3); return !r2 || r2.length >= e2 ? t3 : "" + Array(e2 + 1 - r2.length).join(n2) + t3; }, v = { s: m, z: function(t3) { var e2 = -t3.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60; return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0"); }, m: function t3(e2, n2) { if (e2.date() < n2.date()) return -t3(n2, e2); var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c); return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0); }, a: function(t3) { return t3 < 0 ? Math.ceil(t3) || 0 : Math.floor(t3); }, p: function(t3) { return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t3] || String(t3 || "").toLowerCase().replace(/s$/, ""); }, u: function(t3) { return void 0 === t3; } }, g = "en", D = {}; D[g] = M; var p = "$isDayjsObject", S = function(t3) { return t3 instanceof _ || !(!t3 || !t3[p]); }, w = function t3(e2, n2, r2) { var i2; if (!e2) return g; if ("string" == typeof e2) { var s2 = e2.toLowerCase(); D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2); var u2 = e2.split("-"); if (!i2 && u2.length > 1) return t3(u2[0]); } else { var a2 = e2.name; D[a2] = e2, i2 = a2; } return !r2 && i2 && (g = i2), i2 || !r2 && g; }, O = function(t3, e2) { if (S(t3)) return t3.clone(); var n2 = "object" == typeof e2 ? e2 : {}; return n2.date = t3, n2.args = arguments, new _(n2); }, b = v; b.l = w, b.i = S, b.w = function(t3, e2) { return O(t3, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset }); }; var _ = function() { function M2(t3) { this.$L = w(t3.locale, null, true), this.parse(t3), this.$x = this.$x || t3.x || {}, this[p] = true; } var m2 = M2.prototype; return m2.parse = function(t3) { this.$d = function(t4) { var e2 = t4.date, n2 = t4.utc; if (null === e2) return /* @__PURE__ */ new Date(NaN); if (b.u(e2)) return /* @__PURE__ */ new Date(); if (e2 instanceof Date) return new Date(e2); if ("string" == typeof e2 && !/Z$/i.test(e2)) { var r2 = e2.match($); if (r2) { var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3); return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2); } } return new Date(e2); }(t3), this.init(); }, m2.init = function() { var t3 = this.$d; this.$y = t3.getFullYear(), this.$M = t3.getMonth(), this.$D = t3.getDate(), this.$W = t3.getDay(), this.$H = t3.getHours(), this.$m = t3.getMinutes(), this.$s = t3.getSeconds(), this.$ms = t3.getMilliseconds(); }, m2.$utils = function() { return b; }, m2.isValid = function() { return !(this.$d.toString() === l); }, m2.isSame = function(t3, e2) { var n2 = O(t3); return this.startOf(e2) <= n2 && n2 <= this.endOf(e2); }, m2.isAfter = function(t3, e2) { return O(t3) < this.startOf(e2); }, m2.isBefore = function(t3, e2) { return this.endOf(e2) < O(t3); }, m2.$g = function(t3, e2, n2) { return b.u(t3) ? this[e2] : this.set(n2, t3); }, m2.unix = function() { return Math.floor(this.valueOf() / 1e3); }, m2.valueOf = function() { return this.$d.getTime(); }, m2.startOf = function(t3, e2) { var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t3), l2 = function(t4, e3) { var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t4) : new Date(n2.$y, e3, t4), n2); return r2 ? i2 : i2.endOf(a); }, $2 = function(t4, e3) { return b.w(n2.toDate()[t4].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2); }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : ""); switch (f2) { case h: return r2 ? l2(1, 0) : l2(31, 11); case c: return r2 ? l2(1, M3) : l2(0, M3 + 1); case o: var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2; return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3); case a: case d: return $2(v2 + "Hours", 0); case u: return $2(v2 + "Minutes", 1); case s: return $2(v2 + "Seconds", 2); case i: return $2(v2 + "Milliseconds", 3); default: return this.clone(); } }, m2.endOf = function(t3) { return this.startOf(t3, false); }, m2.$set = function(t3, e2) { var n2, o2 = b.p(t3), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2; if (o2 === c || o2 === h) { var y2 = this.clone().set(d, 1); y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d; } else l2 && this.$d[l2]($2); return this.init(), this; }, m2.set = function(t3, e2) { return this.clone().$set(t3, e2); }, m2.get = function(t3) { return this[b.p(t3)](); }, m2.add = function(r2, f2) { var d2, l2 = this; r2 = Number(r2); var $2 = b.p(f2), y2 = function(t3) { var e2 = O(l2); return b.w(e2.date(e2.date() + Math.round(t3 * r2)), l2); }; if ($2 === c) return this.set(c, this.$M + r2); if ($2 === h) return this.set(h, this.$y + r2); if ($2 === a) return y2(1); if ($2 === o) return y2(7); var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t2, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3; return b.w(m3, this); }, m2.subtract = function(t3, e2) { return this.add(-1 * t3, e2); }, m2.format = function(t3) { var e2 = this, n2 = this.$locale(); if (!this.isValid()) return n2.invalidDate || l; var r2 = t3 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t4, n3, i3, s3) { return t4 && (t4[n3] || t4(e2, r2)) || i3[n3].slice(0, s3); }, d2 = function(t4) { return b.s(s2 % 12 || 12, t4, "0"); }, $2 = f2 || function(t4, e3, n3) { var r3 = t4 < 12 ? "AM" : "PM"; return n3 ? r3.toLowerCase() : r3; }; return r2.replace(y, function(t4, r3) { return r3 || function(t5) { switch (t5) { case "YY": return String(e2.$y).slice(-2); case "YYYY": return b.s(e2.$y, 4, "0"); case "M": return a2 + 1; case "MM": return b.s(a2 + 1, 2, "0"); case "MMM": return h2(n2.monthsShort, a2, c2, 3); case "MMMM": return h2(c2, a2); case "D": return e2.$D; case "DD": return b.s(e2.$D, 2, "0"); case "d": return String(e2.$W); case "dd": return h2(n2.weekdaysMin, e2.$W, o2, 2); case "ddd": return h2(n2.weekdaysShort, e2.$W, o2, 3); case "dddd": return o2[e2.$W]; case "H": return String(s2); case "HH": return b.s(s2, 2, "0"); case "h": return d2(1); case "hh": return d2(2); case "a": return $2(s2, u2, true); case "A": return $2(s2, u2, false); case "m": return String(u2); case "mm": return b.s(u2, 2, "0"); case "s": return String(e2.$s); case "ss": return b.s(e2.$s, 2, "0"); case "SSS": return b.s(e2.$ms, 3, "0"); case "Z": return i2; } return null; }(t4) || i2.replace(":", ""); }); }, m2.utcOffset = function() { return 15 * -Math.round(this.$d.getTimezoneOffset() / 15); }, m2.diff = function(r2, d2, l2) { var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() { return b.m(y2, m3); }; switch (M3) { case h: $2 = D2() / 12; break; case c: $2 = D2(); break; case f: $2 = D2() / 3; break; case o: $2 = (g2 - v2) / 6048e5; break; case a: $2 = (g2 - v2) / 864e5; break; case u: $2 = g2 / n; break; case s: $2 = g2 / e; break; case i: $2 = g2 / t2; break; default: $2 = g2; } return l2 ? $2 : b.a($2); }, m2.daysInMonth = function() { return this.endOf(c).$D; }, m2.$locale = function() { return D[this.$L]; }, m2.locale = function(t3, e2) { if (!t3) return this.$L; var n2 = this.clone(), r2 = w(t3, e2, true); return r2 && (n2.$L = r2), n2; }, m2.clone = function() { return b.w(this.$d, this); }, m2.toDate = function() { return new Date(this.valueOf()); }, m2.toJSON = function() { return this.isValid() ? this.toISOString() : null; }, m2.toISOString = function() { return this.$d.toISOString(); }, m2.toString = function() { return this.$d.toUTCString(); }, M2; }(), k = _.prototype; return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t3) { k[t3[1]] = function(e2) { return this.$g(e2, t3[0], t3[1]); }; }), O.extend = function(t3, e2) { return t3.$i || (t3(e2, _, O), t3.$i = true), O; }, O.locale = w, O.isDayjs = S, O.unix = function(t3) { return O(1e3 * t3); }, O.en = D[g], O.Ls = D, O.p = {}, O; }); } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/base64.js var require_base64 = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/base64.js"(exports) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); exports.encode = function(number3) { if (0 <= number3 && number3 < intToCharMap.length) { return intToCharMap[number3]; } throw new TypeError("Must be between 0 and 63: " + number3); }; exports.decode = function(charCode) { var bigA = 65; var bigZ = 90; var littleA = 97; var littleZ = 122; var zero2 = 48; var nine = 57; var plus = 43; var slash = 47; var littleOffset = 26; var numberOffset = 52; if (bigA <= charCode && charCode <= bigZ) { return charCode - bigA; } if (littleA <= charCode && charCode <= littleZ) { return charCode - littleA + littleOffset; } if (zero2 <= charCode && charCode <= nine) { return charCode - zero2 + numberOffset; } if (charCode == plus) { return 62; } if (charCode == slash) { return 63; } return -1; }; } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/base64-vlq.js"(exports) { var base64 = require_base64(); var VLQ_BASE_SHIFT = 5; var VLQ_BASE = 1 << VLQ_BASE_SHIFT; var VLQ_BASE_MASK = VLQ_BASE - 1; var VLQ_CONTINUATION_BIT = VLQ_BASE; function toVLQSigned(aValue) { return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift2 = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift2); shift2 += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/util.js var require_util = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/util.js"(exports) { function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ""; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ":"; } url += "//"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@"; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; var MAX_CACHED_INPUTS = 32; function lruMemoize(f) { var cache = []; return function(input) { for (var i = 0; i < cache.length; i++) { if (cache[i].input === input) { var temp = cache[0]; cache[0] = cache[i]; cache[i] = temp; return cache[0].result; } } var result = f(input); cache.unshift({ input, result }); if (cache.length > MAX_CACHED_INPUTS) { cache.pop(); } return result; }; } var normalize = lruMemoize(function normalize2(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = []; var start = 0; var i = 0; while (true) { start = i; i = path.indexOf("/", start); if (i === -1) { parts.push(path.slice(start)); break; } else { parts.push(path.slice(start, i)); while (i < path.length && path[i] === "/") { i++; } } } for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === ".") { parts.splice(i, 1); } else if (part === "..") { up++; } else if (up > 0) { if (part === "") { parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join("/"); if (path === "") { path = isAbsolute ? "/" : "."; } if (url) { url.path = path; return urlGenerate(url); } return path; }); exports.normalize = normalize; function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || "/"; } if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function(aPath) { return aPath.charAt(0) === "/" || urlRegexp.test(aPath); }; function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ""); var level = 0; while (aPath.indexOf(aRoot + "/") !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = function() { var obj = /* @__PURE__ */ Object.create(null); return !("__proto__" in obj); }(); function identity(s) { return s; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length2 = s.length; if (length2 < 9) { return false; } if (s.charCodeAt(length2 - 1) !== 95 || s.charCodeAt(length2 - 2) !== 95 || s.charCodeAt(length2 - 3) !== 111 || s.charCodeAt(length2 - 4) !== 116 || s.charCodeAt(length2 - 5) !== 111 || s.charCodeAt(length2 - 6) !== 114 || s.charCodeAt(length2 - 7) !== 112 || s.charCodeAt(length2 - 8) !== 95 || s.charCodeAt(length2 - 9) !== 95) { return false; } for (var i = length2 - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36) { return false; } } return true; } function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; } if (aStr2 === null) { return -1; } if (aStr1 > aStr2) { return 1; } return -1; } function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; function parseSourceMapInput(str2) { return JSON.parse(str2.replace(/^\)]}'[^\n]*\n/, "")); } exports.parseSourceMapInput = parseSourceMapInput; function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ""; if (sourceRoot) { if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { sourceRoot += "/"; } sourceURL = sourceRoot + sourceURL; } if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { var index = parsed.path.lastIndexOf("/"); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/array-set.js var require_array_set = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/array-set.js"(exports) { var util2 = require_util(); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; function ArraySet() { this._array = []; this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); } ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set2 = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set2.add(aArray[i], aAllowDuplicates); } return set2; }; ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util2.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util2.toSetString(aStr); return has.call(this._set, sStr); } }; ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util2.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error("No element indexed by " + aIdx); }; ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/mapping-list.js"(exports) { var util2 = require_util(); function generatedPositionAfter(mappingA, mappingB) { var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } function MappingList() { this._array = []; this._sorted = true; this._last = { generatedLine: -1, generatedColumn: 0 }; } MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util2.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; } }); // node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/source-map-generator.js var require_source_map_generator = __commonJS({ "node_modules/.pnpm/source-map-js@1.2.1/node_modules/source-map-js/lib/source-map-generator.js"(exports) { var base64VLQ = require_base64_vlq(); var util2 = require_util(); var ArraySet = require_array_set().ArraySet; var MappingList = require_mapping_list().MappingList; function SourceMapGenerator2(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util2.getArg(aArgs, "file", null); this._sourceRoot = util2.getArg(aArgs, "sourceRoot", null); this._skipValidation = util2.getArg(aArgs, "skipValidation", false); this._ignoreInvalidMapping = util2.getArg(aArgs, "ignoreInvalidMapping", false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator2.prototype._version = 3; SourceMapGenerator2.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator2(Object.assign(generatorOps || {}, { file: aSourceMapConsumer.file, sourceRoot })); aSourceMapConsumer.eachMapping(function(mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util2.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function(sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util2.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content2 = aSourceMapConsumer.sourceContentFor(sourceFile); if (content2 != null) { generator.setSourceContent(sourceFile, content2); } }); return generator; }; SourceMapGenerator2.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util2.getArg(aArgs, "generated"); var original = util2.getArg(aArgs, "original", null); var source = util2.getArg(aArgs, "source", null); var name51 = util2.getArg(aArgs, "name", null); if (!this._skipValidation) { if (this._validateMapping(generated, original, source, name51) === false) { return; } } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name51 != null) { name51 = String(name51); if (!this._names.has(name51)) { this._names.add(name51); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source, name: name51 }); }; SourceMapGenerator2.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util2.relative(this._sourceRoot, source); } if (aSourceContent != null) { if (!this._sourcesContents) { this._sourcesContents = /* @__PURE__ */ Object.create(null); } this._sourcesContents[util2.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { delete this._sourcesContents[util2.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; SourceMapGenerator2.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.` ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; if (sourceRoot != null) { sourceFile = util2.relative(sourceRoot, sourceFile); } var newSources = new ArraySet(); var newNames = new ArraySet(); this._mappings.unsortedForEach(function(mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util2.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util2.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name51 = mapping.name; if (name51 != null && !newNames.has(name51)) { newNames.add(name51); } }, this); this._sources = newSources; this._names = newNames; aSourceMapConsumer.sources.forEach(function(sourceFile2) { var content2 = aSourceMapConsumer.sourceContentFor(sourceFile2); if (content2 != null) { if (aSourceMapPath != null) { sourceFile2 = util2.join(aSourceMapPath, sourceFile2); } if (sourceRoot != null) { sourceFile2 = util2.relative(sourceRoot, sourceFile2); } this.setSourceContent(sourceFile2, content2); } }, this); }; SourceMapGenerator2.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { var message = "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."; if (this._ignoreInvalidMapping) { if (typeof console !== "undefined" && console.warn) { console.warn(message); } return false; } else { throw new Error(message); } } if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { return; } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { return; } else { var message = "Invalid mapping: " + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName }); if (this._ignoreInvalidMapping) { if (typeof console !== "undefined" && console.warn) { console.warn(message); } return false; } else { throw new Error(message); } } }; SourceMapGenerator2.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ""; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ";"; previousGeneratedLine++; } } else { if (i > 0) { if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ","; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator2.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function(source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util2.relative(aSourceRoot, source); } var key = util2.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; SourceMapGenerator2.prototype.toJSON = function SourceMapGenerator_toJSON() { var map2 = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map2.file = this._file; } if (this._sourceRoot != null) { map2.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot); } return map2; }; SourceMapGenerator2.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator2; } }); // node_modules/.pnpm/dayjs@1.11.13/node_modules/dayjs/plugin/utc.js var require_utc = __commonJS({ "node_modules/.pnpm/dayjs@1.11.13/node_modules/dayjs/plugin/utc.js"(exports, module) { !function(t2, i) { "object" == typeof exports && "undefined" != typeof module ? module.exports = i() : "function" == typeof define && define.amd ? define(i) : (t2 = "undefined" != typeof globalThis ? globalThis : t2 || self).dayjs_plugin_utc = i(); }(exports, function() { "use strict"; var t2 = "minute", i = /[+-]\d\d(?::?\d\d)?/g, e = /([+-]|\d\d)/g; return function(s, f, n) { var u = f.prototype; n.utc = function(t3) { var i2 = { date: t3, utc: true, args: arguments }; return new f(i2); }, u.utc = function(i2) { var e2 = n(this.toDate(), { locale: this.$L, utc: true }); return i2 ? e2.add(this.utcOffset(), t2) : e2; }, u.local = function() { return n(this.toDate(), { locale: this.$L, utc: false }); }; var o = u.parse; u.parse = function(t3) { t3.utc && (this.$u = true), this.$utils().u(t3.$offset) || (this.$offset = t3.$offset), o.call(this, t3); }; var r = u.init; u.init = function() { if (this.$u) { var t3 = this.$d; this.$y = t3.getUTCFullYear(), this.$M = t3.getUTCMonth(), this.$D = t3.getUTCDate(), this.$W = t3.getUTCDay(), this.$H = t3.getUTCHours(), this.$m = t3.getUTCMinutes(), this.$s = t3.getUTCSeconds(), this.$ms = t3.getUTCMilliseconds(); } else r.call(this); }; var a = u.utcOffset; u.utcOffset = function(s2, f2) { var n2 = this.$utils().u; if (n2(s2)) return this.$u ? 0 : n2(this.$offset) ? a.call(this) : this.$offset; if ("string" == typeof s2 && (s2 = function(t3) { void 0 === t3 && (t3 = ""); var s3 = t3.match(i); if (!s3) return null; var f3 = ("" + s3[0]).match(e) || ["-", 0, 0], n3 = f3[0], u3 = 60 * +f3[1] + +f3[2]; return 0 === u3 ? 0 : "+" === n3 ? u3 : -u3; }(s2), null === s2)) return this; var u2 = Math.abs(s2) <= 16 ? 60 * s2 : s2, o2 = this; if (f2) return o2.$offset = u2, o2.$u = 0 === s2, o2; if (0 !== s2) { var r2 = this.$u ? this.toDate().getTimezoneOffset() : -1 * this.utcOffset(); (o2 = this.local().add(u2 + r2, t2)).$offset = u2, o2.$x.$localOffset = r2; } else o2 = this.utc(); return o2; }; var h = u.format; u.format = function(t3) { var i2 = t3 || (this.$u ? "YYYY-MM-DDTHH:mm:ss[Z]" : ""); return h.call(this, i2); }, u.valueOf = function() { var t3 = this.$utils().u(this.$offset) ? 0 : this.$offset + (this.$x.$localOffset || this.$d.getTimezoneOffset()); return this.$d.valueOf() - 6e4 * t3; }, u.isUTC = function() { return !!this.$u; }, u.toISOString = function() { return this.toDate().toISOString(); }, u.toString = function() { return this.toDate().toUTCString(); }; var l = u.toDate; u.toDate = function(t3) { return "s" === t3 && this.$offset ? n(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate() : l.call(this); }; var c = u.diff; u.diff = function(t3, i2, e2) { if (t3 && this.$u === t3.$u) return c.call(this, t3, i2, e2); var s2 = this.local(), f2 = n(t3).local(); return c.call(s2, f2, i2, e2); }; }; }); } }); // src/scripts/background.ts var import_dayjs9 = __toESM(require_dayjs_min(), 1); // src/scripts/background/backup-restore.ts var import_dayjs7 = __toESM(require_dayjs_min(), 1); // src/common/search-engines.ts var SEARCH_ENGINES = { google: { contentScripts: [ { matches: [ "https://www.google.com/search?*", "https://www.google.ad/search?*", "https://www.google.ae/search?*", "https://www.google.com.af/search?*", "https://www.google.com.ag/search?*", "https://www.google.com.ai/search?*", "https://www.google.al/search?*", "https://www.google.am/search?*", "https://www.google.co.ao/search?*", "https://www.google.com.ar/search?*", "https://www.google.as/search?*", "https://www.google.at/search?*", "https://www.google.com.au/search?*", "https://www.google.az/search?*", "https://www.google.ba/search?*", "https://www.google.com.bd/search?*", "https://www.google.be/search?*", "https://www.google.bf/search?*", "https://www.google.bg/search?*", "https://www.google.com.bh/search?*", "https://www.google.bi/search?*", "https://www.google.bj/search?*", "https://www.google.com.bn/search?*", "https://www.google.com.bo/search?*", "https://www.google.com.br/search?*", "https://www.google.bs/search?*", "https://www.google.bt/search?*", "https://www.google.co.bw/search?*", "https://www.google.by/search?*", "https://www.google.com.bz/search?*", "https://www.google.ca/search?*", "https://www.google.cd/search?*", "https://www.google.cf/search?*", "https://www.google.cg/search?*", "https://www.google.ch/search?*", "https://www.google.ci/search?*", "https://www.google.co.ck/search?*", "https://www.google.cl/search?*", "https://www.google.cm/search?*", "https://www.google.cn/search?*", "https://www.google.com.co/search?*", "https://www.google.co.cr/search?*", "https://www.google.com.cu/search?*", "https://www.google.cv/search?*", "https://www.google.com.cy/search?*", "https://www.google.cz/search?*", "https://www.google.de/search?*", "https://www.google.dj/search?*", "https://www.google.dk/search?*", "https://www.google.dm/search?*", "https://www.google.com.do/search?*", "https://www.google.dz/search?*", "https://www.google.com.ec/search?*", "https://www.google.ee/search?*", "https://www.google.com.eg/search?*", "https://www.google.es/search?*", "https://www.google.com.et/search?*", "https://www.google.fi/search?*", "https://www.google.com.fj/search?*", "https://www.google.fm/search?*", "https://www.google.fr/search?*", "https://www.google.ga/search?*", "https://www.google.ge/search?*", "https://www.google.gg/search?*", "https://www.google.com.gh/search?*", "https://www.google.com.gi/search?*", "https://www.google.gl/search?*", "https://www.google.gm/search?*", "https://www.google.gp/search?*", "https://www.google.gr/search?*", "https://www.google.com.gt/search?*", "https://www.google.gy/search?*", "https://www.google.com.hk/search?*", "https://www.google.hn/search?*", "https://www.google.hr/search?*", "https://www.google.ht/search?*", "https://www.google.hu/search?*", "https://www.google.co.id/search?*", "https://www.google.ie/search?*", "https://www.google.co.il/search?*", "https://www.google.im/search?*", "https://www.google.co.in/search?*", "https://www.google.iq/search?*", "https://www.google.is/search?*", "https://www.google.it/search?*", "https://www.google.je/search?*", "https://www.google.com.jm/search?*", "https://www.google.jo/search?*", "https://www.google.co.jp/search?*", "https://www.google.co.ke/search?*", "https://www.google.com.kh/search?*", "https://www.google.ki/search?*", "https://www.google.kg/search?*", "https://www.google.co.kr/search?*", "https://www.google.com.kw/search?*", "https://www.google.kz/search?*", "https://www.google.la/search?*", "https://www.google.com.lb/search?*", "https://www.google.li/search?*", "https://www.google.lk/search?*", "https://www.google.co.ls/search?*", "https://www.google.lt/search?*", "https://www.google.lu/search?*", "https://www.google.lv/search?*", "https://www.google.com.ly/search?*", "https://www.google.co.ma/search?*", "https://www.google.md/search?*", "https://www.google.me/search?*", "https://www.google.mg/search?*", "https://www.google.mk/search?*", "https://www.google.ml/search?*", "https://www.google.com.mm/search?*", "https://www.google.mn/search?*", "https://www.google.ms/search?*", "https://www.google.com.mt/search?*", "https://www.google.mu/search?*", "https://www.google.mv/search?*", "https://www.google.mw/search?*", "https://www.google.com.mx/search?*", "https://www.google.com.my/search?*", "https://www.google.co.mz/search?*", "https://www.google.com.na/search?*", "https://www.google.com.nf/search?*", "https://www.google.com.ng/search?*", "https://www.google.com.ni/search?*", "https://www.google.ne/search?*", "https://www.google.nl/search?*", "https://www.google.no/search?*", "https://www.google.com.np/search?*", "https://www.google.nr/search?*", "https://www.google.nu/search?*", "https://www.google.co.nz/search?*", "https://www.google.com.om/search?*", "https://www.google.com.pa/search?*", "https://www.google.com.pe/search?*", "https://www.google.com.pg/search?*", "https://www.google.com.ph/search?*", "https://www.google.com.pk/search?*", "https://www.google.pl/search?*", "https://www.google.pn/search?*", "https://www.google.com.pr/search?*", "https://www.google.ps/search?*", "https://www.google.pt/search?*", "https://www.google.com.py/search?*", "https://www.google.com.qa/search?*", "https://www.google.ro/search?*", "https://www.google.ru/search?*", "https://www.google.rw/search?*", "https://www.google.com.sa/search?*", "https://www.google.com.sb/search?*", "https://www.google.sc/search?*", "https://www.google.se/search?*", "https://www.google.com.sg/search?*", "https://www.google.sh/search?*", "https://www.google.si/search?*", "https://www.google.sk/search?*", "https://www.google.com.sl/search?*", "https://www.google.sn/search?*", "https://www.google.so/search?*", "https://www.google.sm/search?*", "https://www.google.sr/search?*", "https://www.google.st/search?*", "https://www.google.com.sv/search?*", "https://www.google.td/search?*", "https://www.google.tg/search?*", "https://www.google.co.th/search?*", "https://www.google.com.tj/search?*", "https://www.google.tk/search?*", "https://www.google.tl/search?*", "https://www.google.tm/search?*", "https://www.google.tn/search?*", "https://www.google.to/search?*", "https://www.google.com.tr/search?*", "https://www.google.tt/search?*", "https://www.google.com.tw/search?*", "https://www.google.co.tz/search?*", "https://www.google.com.ua/search?*", "https://www.google.co.ug/search?*", "https://www.google.co.uk/search?*", "https://www.google.com.uy/search?*", "https://www.google.co.uz/search?*", "https://www.google.com.vc/search?*", "https://www.google.co.ve/search?*", "https://www.google.vg/search?*", "https://www.google.co.vi/search?*", "https://www.google.com.vn/search?*", "https://www.google.vu/search?*", "https://www.google.ws/search?*", "https://www.google.rs/search?*", "https://www.google.co.za/search?*", "https://www.google.co.zm/search?*", "https://www.google.co.zw/search?*", "https://www.google.cat/search?*" ], runAt: "document_start" } ], messageNames: { name: "searchEngines_googleName" } }, bing: { contentScripts: [ { matches: [ "https://www.bing.com/search?*", "https://www.bing.com/images/search?*", "https://www.bing.com/videos/search?*", "https://www.bing.com/news/search?*", "https://cn.bing.com/search?*", "https://cn.bing.com/images/search?*", "https://cn.bing.com/videos/search?*", "https://cn.bing.com/news/search?*", "https://www2.bing.com/search?*", "https://www2.bing.com/images/search?*", "https://www2.bing.com/videos/search?*", "https://www2.bing.com/news/search?*", "https://www4.bing.com/search?*", "https://www4.bing.com/images/search?*", "https://www4.bing.com/videos/search?*", "https://www4.bing.com/news/search?*" ], runAt: "document_start" } ], messageNames: { name: "searchEngines_bingName" } }, brave: { contentScripts: [ { matches: [ "https://search.brave.com/search?*", "https://search.brave.com/images?*", "https://search.brave.com/news?*", "https://search.brave.com/videos?*", "https://search.brave.com/goggles?*", "*://search.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/search?*", "*://search.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/images?*", "*://search.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/news?*", "*://search.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/videos?*", "*://search.brave4u7jddbv7cyviptqjc7jusxh72uik7zt6adtckl5f4nwy2v72qd.onion/goggles?*" ], runAt: "document_idle" } ], messageNames: { name: "searchEngines_braveName" } }, duckduckgo: { contentScripts: [ { matches: [ "*://duckduckgo.com/", "*://duckduckgo.com/?*", ...true ? [ "*://html.duckduckgo.com/html/", "*://html.duckduckgo.com/html/?*", "*://lite.duckduckgo.com/lite/", "*://lite.duckduckgo.com/lite/?*" ] : [], "*://safe.duckduckgo.com/", "*://safe.duckduckgo.com/?*", "*://start.duckduckgo.com/", "*://start.duckduckgo.com/?*", "*://duckduckgogg42xjoc72x3sjasowoarfbgcmvfimaftt6twagswzczad.onion/", "*://duckduckgogg42xjoc72x3sjasowoarfbgcmvfimaftt6twagswzczad.onion/?*" ], runAt: "document_start" } ], messageNames: { name: "searchEngines_duckduckgoName" } }, ecosia: { contentScripts: [ { matches: ["https://www.ecosia.org/search?*"], runAt: "document_idle" } ], messageNames: { name: "searchEngines_ecosiaName" } }, kagi: { contentScripts: [ { matches: [ "https://kagi.com/search?*", "https://kagi.com/images?*", "https://kagi.com/videos?*", "https://kagi.com/news?*", "https://kagi.com/podcasts?*" ], runAt: "document_idle" } ], messageNames: { name: "searchEngines_kagiName" } }, qwant: { contentScripts: [ { matches: ["https://www.qwant.com/?*"], // https://github.com/iorate/ublacklist/pull/179 runAt: "document_idle" }, { matches: ["https://lite.qwant.com/?*"], runAt: "document_start" } ], messageNames: { name: "searchEngines_qwantName", description: "searchEngines_qwantDescription" } }, searx: { contentScripts: [ { matches: [ "*://searx.be/search*", "*://searx.fmac.xyz/search*", "*://search.unlocked.link/search*", "*://search.ononoki.org/search*", "*://northboot.xyz/search*", "*://searx.tiekoetter.com/search*", "*://searx.work/search*", "*://paulgo.io/search*", "*://search.rhscz.eu/search*", "*://search.rabbit-company.com/search*", "*://priv.au/search*", "*://search.sapti.me/search*", "*://searxng.nicfab.eu/searxng/search*", "*://search.smnz.de/search*", "*://notsearch.uk/search*", "*://search.bus-hit.me/search*", "*://xo.wtf/search*", "*://searx.mha.fi/search*", "*://searx.prvcy.eu/search*", "*://search.chemicals-in-the-water.eu/search*", "*://searx.baczek.me/search*", "*://search.rowie.at/search*", "*://searx.ericaftereric.top/search*", "*://sh0.it/search*", "*://s.frlt.one/search*", "*://search.gcomm.ch/searx/search*", "*://ooglester.com/search*", "*://searx.priv.pw/search*", "*://swag.pw/search*", "*://search.projectsegfau.lt/search*", "*://searx.xyz/search*", "*://opnxng.com/search*", "*://s.zhaocloud.net/search*", "*://searx.catfluori.de/search*", "*://searx.cthd.icu/search*", "*://intelwinds.com/search*", "*://search.drivet.xyz/search*", "*://spot.murena.io/search*", "*://search.leptons.xyz/searxng/search*", "*://searx.si/search*", "*://baresearch.org/search*", "*://searx.oakleycord.dev/search*", "*://search.zzls.xyz/search*", "*://searx.sev.monster/search*", "*://gsch.eu/search*", "*://search.us.projectsegfau.lt/search*", "*://searx.rasp.fr/search*", "*://s.trung.fun/searxng/search*", "*://searxng.bandarawela.net/search*", "*://searx.chocoflan.net/searx/search*", "*://search.cronobox.one/search*", "*://search.charleseroop.com/search*", "*://sx.fukt.lol/search*", "*://searx.juancord.xyz/searxng/search*", "*://searx.delicta.pp.ua/search*", "*://searx.esmailelbob.xyz/search*", "*://search.privacyguides.net/search*", "*://searxng.fingerbib.xyz/searxng/search*", "*://search.affusio.com/search*", "*://search.suenram.us/searxng/search*", "*://searxng.au/search*", "*://search.disroot.org/search*", "*://searx.fi/search*", "*://searx.netzspielplatz.de/search*", "*://search.mpx.wtf/search*", "*://jackgoss.xyz/search*", "*://etsi.me/search*", "*://search.uspersec.com/search*", "*://search.kiwitalk.de/search*", "*://search.0relay.com/search*", "*://srx.cosmohub.io/search*", "*://privatus.live/search*", "*://search.kvj.ovh/search*", "*://searx.becomesovran.com/search*", "*://searx.gnous.eu/search*", "*://searx.orion-hub.fr/search*", "*://searx.slipfox.xyz/searx/search*", "*://privatesearch.dev/search*", "*://searx.ru/search*", "*://searx.mastodontech.de/search*", "*://searx.dresden.network/search*", "*://searx.stuehieyr.com/search*", "*://searx.webheberg.info/search*", "*://searx.win/search*", "*://searx.gnu.style/search*", "*://searx.roflcopter.fr/search*", "*://sx.catgirl.cloud/search*", "*://suche.tromdienste.de/search*", "*://search.trom.tf/search*", "*://searx.mxchange.org/search*", "*://searx.tyil.nl/search*", "*://searx.divided-by-zero.eu/search*", "*://searx.nakhan.net/search*", "*://searx.nixnet.services/search*", "*://searx.zapashcanon.fr/search*", "*://darmarit.org/searx/search*", "*://jsearch.pw/searx/search*", "*://gruble.de/search*", "*://search.inetol.net/search*", "*://search.demoniac.ch/search*", "*://search.lvkaszus.pl/search*", "*://searxng.diadz.de/search*", "*://searx.namejeff.xyz/search*", "*://searx.dofpot.nl/search*", "*://search.modalogi.com/search*", "*://searxng.xcxc.eu/search*", "*://searx.tuxcloud.net/search*", "*://search.whateveritworks.org/search*", "*://copp.gg/search*", "*://sarch.im-in.space/search*", "*://searxng.se/search*", "*://search.laksith.dev/search*", "*://searx.ox2.fr/search*", "*://search.0xgingi.com/search*", "*://search.dojoro.de/search*", "*://jabber-germany.de/searx/search*", "*://myprivatesrx.us/search*", "*://search.bowlman.org/search*", "*://search.fascinated.cc/search*", "*://stalk.antelope.day/search*", "*://searxng.no-logs.com/search*", "*://searx.kutay.dev/search*", "*://searx.daetalytica.io/search*", "*://searx.bissisoft.com/search*", "*://search.neet.works/search*", "*://offtheradar.info/search*", "*://search.shinglea.dev/search*", "*://search.listi.me/search*", "*://search.serginho.dev/search*", "*://searx.netzspielplatz.de/search*", "*://searx.thefloatinglab.world/search*", "*://search.whatever.social/searxng/search*", "*://freesearch.club/search*", "*://northboot.xyz/search*", "*://nyc1.sx.ggtyler.dev/search*", "*://priv.au/search*", "*://s.mble.dk/search*", "*://s.trung.fun/search*", "*://search.broker/search*", "*://search.datura.network/search*", "*://search.demoniak.ch/search*", "*://search.gcomm.ch/search*", "*://search.hbubli.cc/search*", "*://search.im-in.space/search*", "*://search.in.projectsegfau.lt/search*", "*://search.inetol.net/search*", "*://search.leptons.xyz/search*", "*://search.mdosch.de/search*", "*://search.nadeko.net/search*", "*://search.ononoki.org/search*", "*://search.privacyredirect.com/search*", "*://search.projectsegfau.lt/search*", "*://search.wush.cc/search*", "*://search.iswsh.com/search*", "*://search.starless.one/search*", "*://search.upinmars.com/search*", "*://searx.aleteoryx.me/search*", "*://searx.ankha.ac/search*", "*://searx.ari.lt/search*", "*://searx.cthd.icu/search*", "*://searx.ee/search*", "*://searx.headpat.exchange/search*", "*://searx.juancord.xyz/search*", "*://searx.lunar.icu/search*", "*://searx.nobulart.com/search*", "*://searx.perennialte.ch/search*", "*://searx.rhscz.eu/search*", "*://searx.techsaviours.org/search*", "*://searx.zhenyapav.com/search*", "*://searxng.brihx.fr/search*", "*://searxng.ca/search*", "*://searxng.ch/search*", "*://searxng.site/search*", "*://sex.finaltek.net/search*", "*://sx.thatxtreme.dev/search*", "*://twinkpad.pl/search*", "*://www.gruble.de/search*", "*://www.jabber-germany.de/searx/search*", "*://searx.juancord.xyz/searxng/search*", "*://searx.oloke.xyz/search*" ], runAt: "document_start" } ], messageNames: { name: "searchEngines_searxName" } }, startpage: { contentScripts: [ { matches: [ "https://*.startpage.com/do/*", "https://*.startpage.com/rvd/*", "https://*.startpage.com/sp/*", "*://startpagel6srwcjlue4zgq3zevrujfaow726kjytqbbjyrswwmjzcqd.onion/do/*", "*://startpagel6srwcjlue4zgq3zevrujfaow726kjytqbbjyrswwmjzcqd.onion/rvd/*", "*://startpagel6srwcjlue4zgq3zevrujfaow726kjytqbbjyrswwmjzcqd.onion/sp/*" ], runAt: "document_idle" } ], messageNames: { name: "searchEngines_startpageName" } }, yahooJapan: { contentScripts: [ { matches: ["https://search.yahoo.co.jp/search?*"], runAt: "document_idle" } ], messageNames: { name: "searchEngines_yahooJapanName" } }, yandex: { contentScripts: [ { matches: [ // Web "https://ya.ru/search*", "https://yandex.com/search*", "https://yandex.ru/search*", "https://yandex.ua/search*", "https://yandex.by/search*", "https://yandex.kz/search*", "https://yandex.uz/search*", "https://yandex.com.tr/search*", "https://yandex.fr/search*", "https://yandex.az/search*", "https://yandex.com.ge/search*", "https://yandex.com.am/search*", "https://yandex.co.il/search*", "https://yandex.lv/search*", "https://yandex.lt/search*", "https://yandex.ee/search*", "https://yandex.md/search*", "https://yandex.tm/search*", "https://yandex.tj/search*" ], runAt: "document_idle" } ], messageNames: { name: "searchEngines_yandexName" } } }; // src/scripts/browser.ts var browser = true ? globalThis.chrome : globalThis.browser; // src/scripts/messages.ts function postMessage(type2, ...args) { void (async () => { try { await browser.runtime.sendMessage({ type: type2, args }); } catch (e) { if (e instanceof Error && e.message === "Could not establish connection. Receiving end does not exist.") { return; } console.error(e); } })(); } function invokeListener(listener, args, sendResponse) { const value = listener(...args); if (value instanceof Promise) { void value.then((value2) => sendResponse(toResponse(value2))); return true; } sendResponse(toResponse(value)); } function addMessageListeners(listeners) { const listener = (message, _sender, sendResponse) => { const { type: type2, args } = message; if (listeners[type2]) { return invokeListener( listeners[type2], args, sendResponse ); } }; browser.runtime.onMessage.addListener(listener); return () => { browser.runtime.onMessage.removeListener(listener); }; } function addMessageFromTabListeners(listeners) { const listener = (message, sender, sendResponse) => { const { type: type2, args } = message; if (listeners[type2]) { const tabId = sender.tab?.id; if (tabId == null) { return; } return invokeListener( listeners[type2], [tabId, ...args], sendResponse ); } }; browser.runtime.onMessage.addListener(listener); return () => { browser.runtime.onMessage.removeListener(listener); }; } function toResponse(value) { return value !== void 0 ? { value } : {}; } // node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/index.mjs var util; (function(util2) { util2.assertEqual = (val) => val; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t2 = typeof data; switch (t2) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json2 = JSON.stringify(obj, null, 2); return json2.replace(/"([^"]+)":/g, "$1:"); }; var ZodError = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; var errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; var overrideErrorMap = errorMap; function setErrorMap(map2) { overrideErrorMap = map2; } function getErrorMap() { return overrideErrorMap; } var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; var EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === errorMap ? void 0 : errorMap // then global default map ].filter((x) => !!x) }); ctx.common.issues.push(issue); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs2) { const syncPairs = []; for (const pair2 of pairs2) { const key = await pair2.key; const value = await pair2.value; syncPairs.push({ key, value }); } return _ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs2) { const finalObject = {}; for (const pair2 of pairs2) { const { key, value } = pair2; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair2.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); var _ZodEnum_cache; var _ZodNativeEnum_cache; var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { var _a2, _b; const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: (_a2 = message !== null && message !== void 0 ? message : required_error) !== null && _a2 !== void 0 ? _a2 : ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a2; const ctx = { common: { issues: [], async: (_a2 = params === null || params === void 0 ? void 0 : params.async) !== null && _a2 !== void 0 ? _a2 : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { var _a2, _b; const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err) { if ((_b = (_a2 = err === null || err === void 0 ? void 0 : err.message) === null || _a2 === void 0 ? void 0 : _a2.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; var dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; if (args.precision) { regex = `${regex}\\.\\d{${args.precision}}`; } else if (args.precision == null) { regex = `${regex}(\\.\\d+)?`; } return regex; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt, alg) { if (!jwtRegex.test(jwt)) return false; try { const [header] = jwt.split("."); const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; if (!decoded.typ || !decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch (_a2) { return false; } } function isValidCidr(ip, version) { if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString = class _ZodString extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a2) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message }); status.dirty(); } } else if (check.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check.message }); status.dirty(); } } else if (check.kind === "time") { const regex = timeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check.message }); status.dirty(); } } else if (check.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "jwt") { if (!isValidJWT(input.data, check.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cidr") { if (!isValidCidr(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message) }); } _addCheck(check) { return new _ZodString({ ...this._def, checks: [...this._def.checks, check] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { var _a2, _b; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a2 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a2 !== void 0 ? _a2 : false, local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options }); } return this._addCheck({ kind: "time", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString.create = (params) => { var _a2; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a2 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a2 !== void 0 ? _a2 : false, ...processCreateParams(params) }); }; function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / Math.pow(10, decCount); } var ZodNumber = class _ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new _ZodNumber({ ...this._def, checks: [...this._def.checks, check] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodBigInt = class _ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { try { input.data = BigInt(input.data); } catch (_a2) { return this._getInvalidInput(input); } } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt.create = (params) => { var _a2; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a2 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a2 !== void 0 ? _a2 : false, ...processCreateParams(params) }); }; var ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodDate = class _ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date" }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date" }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check) { return new _ZodDate({ ...this._def, checks: [...this._def.checks, check] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class _ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema2, params) => { return new ZodArray({ type: schema2, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema2) { if (schema2 instanceof ZodObject) { const newShape = {}; for (const key in schema2.shape) { const fieldSchema = schema2.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema2._def, shape: () => newShape }); } else if (schema2 instanceof ZodArray) { return new ZodArray({ ...schema2._def, type: deepPartialify(schema2.element) }); } else if (schema2 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodTuple) { return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); } else { return schema2; } } var ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); return this._cached = { shape, keys }; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs2 = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs2.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair2 of pairs2) { const key = await pair2.key; const value = await pair2.value; syncPairs.push({ key, value, alwaysSet: pair2.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { var _a2, _b, _c, _d; const defaultError = (_c = (_b = (_a2 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a2, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema2) { return this.augment({ [key]: schema2 }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new _ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types3, params) => { return new ZodUnion({ options: types3, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type2) => { if (type2 instanceof ZodLazy) { return getDiscriminator(type2.schema); } else if (type2 instanceof ZodEffects) { return getDiscriminator(type2.innerType()); } else if (type2 instanceof ZodLiteral) { return [type2.value]; } else if (type2 instanceof ZodEnum) { return type2.options; } else if (type2 instanceof ZodNativeEnum) { return util.objectValues(type2.enum); } else if (type2 instanceof ZodDefault) { return getDiscriminator(type2._def.innerType); } else if (type2 instanceof ZodUndefined) { return [void 0]; } else if (type2 instanceof ZodNull) { return [null]; } else if (type2 instanceof ZodOptional) { return [void 0, ...getDiscriminator(type2.unwrap())]; } else if (type2 instanceof ZodNullable) { return [null, ...getDiscriminator(type2.unwrap())]; } else if (type2 instanceof ZodBranded) { return getDiscriminator(type2.unwrap()); } else if (type2 instanceof ZodReadonly) { return getDiscriminator(type2.unwrap()); } else if (type2 instanceof ZodCatch) { return getDiscriminator(type2._def.innerType); } else { return []; } }; var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type2 of options) { const discriminatorValues = getDiscriminator(type2.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type2); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } var ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple = class _ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema2 = this._def.items[itemIndex] || this._def.rest; if (!schema2) return null; return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class _ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs2 = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs2.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs2); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs2 = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair2 of pairs2) { const key = await pair2.key; const value = await pair2.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair2 of pairs2) { const key = pair2.key; const value = pair2.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet = class _ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class _ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error } }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { const error = new ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new _ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new _ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class _ZodEnum extends ZodType { constructor() { super(...arguments); _ZodEnum_cache.set(this, void 0); } _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); } if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; _ZodEnum_cache = /* @__PURE__ */ new WeakMap(); ZodEnum.create = createZodEnum; var ZodNativeEnum = class extends ZodType { constructor() { super(...arguments); _ZodNativeEnum_cache.set(this, void 0); } _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); } if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; _ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap(); ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise.create = (schema2, params) => { return new ZodPromise({ type: schema2, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base3 = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base3)) return base3; const result = effect.transform(base3.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base3) => { if (!isValid(base3)) return base3; return Promise.resolve(effect.transform(base3.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema2, effect, params) => { return new ZodEffects({ schema: schema2, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema2, params) => { return new ZodEffects({ schema: schema2, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type2, params) => { return new ZodOptional({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type2, params) => { return new ZodNullable({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault.create = (type2, params) => { return new ZodDefault({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type2, params) => { return new ZodCatch({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = Symbol("zod_brand"); var ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class _ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a, b) { return new _ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; var ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } }; ZodReadonly.create = (type2, params) => { return new ZodReadonly({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; function cleanParams(params, data) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const p2 = typeof p === "string" ? { message: p } : p; return p2; } function custom(check, _params = {}, fatal) { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a2, _b; const r = check(data); if (r instanceof Promise) { return r.then((r2) => { var _a3, _b2; if (!r2) { const params = cleanParams(_params, data); const _fatal = (_b2 = (_a3 = params.fatal) !== null && _a3 !== void 0 ? _a3 : fatal) !== null && _b2 !== void 0 ? _b2 : true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } }); } if (!r) { const params = cleanParams(_params, data); const _fatal = (_b = (_a2 = params.fatal) !== null && _a2 !== void 0 ? _a2 : fatal) !== null && _b !== void 0 ? _b : true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } return; }); return ZodAny.create(); } var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; var ostring = () => stringType().optional(); var onumber = () => numberType().optional(); var oboolean = () => booleanType().optional(); var coerce = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; var NEVER = INVALID; var z = /* @__PURE__ */ Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap, getErrorMap, makeIssue, EMPTY_PATH, addIssueToContext, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, get util() { return util; }, get objectUtil() { return objectUtil; }, ZodParsedType, getParsedType, ZodType, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodTransformer: ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, Schema: ZodType, ZodSchema: ZodType, late, get ZodFirstPartyTypeKind() { return ZodFirstPartyTypeKind; }, coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, "enum": enumType, "function": functionType, "instanceof": instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, "null": nullType, nullable: nullableType, number: numberType, object: objectType, oboolean, onumber, optional: optionalType, ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, "undefined": undefinedType, union: unionType, unknown: unknownType, "void": voidType, NEVER, ZodIssueCode, quotelessJson, ZodError }); // src/common/match-pattern.ts function parseMatchPattern(pattern) { const execResult = matchPatternRegExp.exec(pattern); if (!execResult) { return null; } const groups = execResult.groups; return groups.allURLs != null ? { allURLs: true } : { allURLs: false, scheme: groups.scheme.toLowerCase(), host: groups.host.toLowerCase(), path: groups.path }; } var matchPatternRegExp = (() => { const allURLs = String.raw`(?)`; const scheme = String.raw`(?\*|[A-Za-z][0-9A-Za-z+.-]*)`; const label = String.raw`(?:[0-9A-Za-z](?:[0-9A-Za-z-]*[0-9A-Za-z])?)`; const host = String.raw`(?(?:\*|${label})(?:\.${label})*)`; const path = String.raw`(?/(?:\*|[0-9A-Za-z._~:/?[\]@!$&'()+,;=-]|%[0-9A-Fa-f]{2})*)`; return new RegExp(String.raw`^(?:${allURLs}|${scheme}://${host}${path})$`); })(); var MatchPatternMap = class _MatchPatternMap { static supportedSchemes = ["http", "https"]; allURLs; hostMap; constructor(json2) { if (json2) { this.allURLs = json2[0]; this.hostMap = json2[1]; } else { this.allURLs = []; this.hostMap = [[], []]; } } toJSON() { return [this.allURLs, this.hostMap]; } get(url) { const { protocol, hostname: host, pathname, search } = new URL(url); const scheme = protocol.slice(0, -1); const path = `${pathname}${search}`; if (!_MatchPatternMap.supportedSchemes.includes(scheme)) { return []; } const values = [...this.allURLs]; let node = this.hostMap; for (const label of host.split(".").reverse()) { collectBucket(node[1], scheme, path, values); if (!node[2]?.[label]) { return values; } node = node[2][label]; } collectBucket(node[1], scheme, path, values); collectBucket(node[0], scheme, path, values); return values; } set(pattern, value) { const parseResult = parseMatchPattern(pattern); if (!parseResult) { throw new Error(`Invalid match pattern: ${pattern}`); } if (parseResult.allURLs) { this.allURLs.push(value); return; } const { scheme, host, path } = parseResult; if (scheme !== "*" && !_MatchPatternMap.supportedSchemes.includes(scheme)) { throw new Error(`Unsupported scheme: ${scheme}`); } const labels = host.split(".").reverse(); const anySubdomain = labels[labels.length - 1] === "*"; if (anySubdomain) { labels.pop(); } let node = this.hostMap; for (const label of labels) { node[2] ||= {}; node = node[2][label] ||= [[], []]; } node[anySubdomain ? 1 : 0].push( path === "/*" ? scheme === "*" ? [value] : [value, scheme] : [value, scheme, path] ); } }; function collectBucket(bucket, scheme, path, values) { for (const [value, schemePattern = "*", pathPattern = "/*"] of bucket) { if (testScheme(schemePattern, scheme) && testPath(pathPattern, path)) { values.push(value); } } } function testScheme(schemePattern, scheme) { return schemePattern === "*" ? scheme === "http" || scheme === "https" : scheme === schemePattern; } function testPath(pathPattern, path) { if (pathPattern === "/*") { return true; } const [first, ...rest] = pathPattern.split("*"); if (rest.length === 0) { return path === first; } if (!path.startsWith(first)) { return false; } let pos = first.length; for (const part of rest.slice(0, -1)) { const partPos = path.indexOf(part, pos); if (partPos === -1) { return false; } pos = partPos + part.length; } return path.slice(pos).endsWith(rest[rest.length - 1]); } // builtin/serpinfo/bing.yml var bing_default = `name: Bing homepage: https://github.com/ublacklist/builtin#readme lastModified: 2025-04-29T09:49:28Z pages: - name: Web (desktop) matches: - https://www.bing.com/search?* userAgent: desktop results: - root: .b_algo url: - or - - - regexExclude - "^https:\\\\/\\\\/www\\\\.bing\\\\.com/ck/" - [property, "href", "h2 > a"] - [domainToURL, ".b_attribution"] props: title: h2 commonProps: $site: bing $category: web - name: Web (mobile) matches: - https://www.bing.com/search?* userAgent: mobile results: - root: .b_algo url: .b_algoheader > a props: title: h2 commonProps: $site: bing $category: web - name: Images (desktop) matches: - https://www.bing.com/images/search?* userAgent: desktop results: - root: [upward, 1, ".iuscp"] url: - regexSubstitute - '"purl":"([^"]+)' - "\\\\1" - [attribute, "m", ".iusc"] props: title: [attribute, "title", "li > a"] button: [inset, { top: "4px", right: "36px" }, ".iuscp"] commonProps: $site: bing $category: images - name: Images (mobile) matches: - https://www.bing.com/images/search?* userAgent: mobile results: - root: [upward, 1, ".iuscp"] url: - regexSubstitute - '"purl":"([^"]+)' - "\\\\1" - [attribute, "m", ".iusc"] props: title: [attribute, "title", "li > a"] commonProps: $site: bing $category: images - name: Videos (desktop) matches: - https://www.bing.com/videos/search?* userAgent: desktop results: - root: [upward, 1, ".mc_vtvc"] url: [attribute, "ourl", ".mc_vtvc_con_rc"] props: title: [attribute, "title", ".mc_vtvc_title"] button: [inset, { top: "4px", right: "36px" }, ".mc_vtvc"] commonProps: $site: bing $category: videos - name: Videos (mobile) matches: - https://www.bing.com/videos/search?* userAgent: mobile results: - root: [upward, 1, ".mc_vtvc"] url: [attribute, "ourl", ".mc_vtvc_con_rc"] props: title: [attribute, "title", ".mc_vtvc_title"] commonProps: $site: bing $category: videos - name: News (desktop) matches: - https://www.bing.com/news/search?* userAgent: desktop results: - root: .news-card url: .title props: title: .title commonProps: $site: bing $category: news - name: News (mobile) matches: - https://www.bing.com/news/search?* userAgent: mobile results: - root: .newscard url: .title props: title: .title commonProps: $site: bing $category: news `; // builtin/serpinfo/brave.yml var brave_default = 'name: Brave\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-04-29T09:49:28Z\n\npages:\n - name: Web\n matches:\n - https://search.brave.com/search?*\n results:\n - root: .snippet[data-type="web"]\n url: a\n props:\n title: .title\n commonProps:\n $site: brave\n $category: web\n delay: 100\n\n - name: Images\n matches:\n - https://search.brave.com/images?*\n results:\n - root: .image-wrapper\n url: [domainToURL, ".img-source"]\n props:\n title: .img-title\n commonProps:\n $site: brave\n $category: images\n delay: 100\n\n - name: News\n matches:\n - https://search.brave.com/news?*\n results:\n - root: .snippet[data-type="news"]\n url: a\n props:\n title: .snippet-title\n commonProps:\n $site: brave\n $category: news\n delay: 100\n\n - name: Videos\n matches:\n - https://search.brave.com/videos?*\n results:\n - root: .snippet[data-type="videos"]\n url: a\n props:\n title: .snippet-title\n commonProps:\n $site: brave\n $category: videos\n delay: 100\n'; // builtin/serpinfo/duckduckgo.yml var duckduckgo_default = `name: DuckDuckGo homepage: https://github.com/ublacklist/builtin#readme lastModified: 2025-04-29T09:49:28Z pages: - name: Default matches: - https://duckduckgo.com/ - https://duckduckgo.com/?* - https://safe.duckduckgo.com/ - https://safe.duckduckgo.com/?* - https://start.duckduckgo.com/ - https://start.duckduckgo.com/?* delay: true commonProps: $site: duckduckgo results: - name: Web (desktop) root: - upward - 1 - ':root:not(.is-mobile) [data-testid="web-vertical"] li > article' url: h2 > a props: title: h2 $category: [const, "web"] button: [inset, { top: "5.4px", right: "36px" }, "article"] - name: Web (mobile) root: - upward - 1 - ':root.is-mobile [data-testid="web-vertical"] li > article' url: h2 > a props: title: h2 $category: [const, "web"] button: [inset, { top: "10px", right: "36px" }, "article"] - name: Images root: [upward, 1, '[data-testid="zci-images"] li > figure'] url: figcaption > a props: title: figcaption > a > p $category: [const, "images"] - name: Videos root: [upward, 2, '[data-testid="zci-videos"] li > a > article'] url: a props: title: h2 $category: [const, "videos"] - name: News root: [upward, 1, '[data-testid="news-vertical"] li > article'] url: article > a props: title: h2 $category: [const, "news"] `; // builtin/serpinfo/ecosia.yml var ecosia_default = 'name: Ecosia\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-04-29T09:49:28Z\n\npages:\n - name: Web\n matches:\n - https://www.ecosia.org/search?*\n results:\n - root: .result\n url: a.result__link\n props:\n title: h2\n button: [inset, { top: "4px", right: "20px" }]\n commonProps:\n $site: ecosia\n $category: web\n delay: true\n\n - name: Images\n matches:\n - https://www.ecosia.org/images?*\n results:\n - root: .image-result\n url: a.image-result__details-link\n props:\n title: h2\n preserveSpace: true\n commonProps:\n $site: ecosia\n $category: images\n delay: true\n\n - name: News\n matches:\n - https://www.ecosia.org/news?*\n results:\n - root: .result\n url: a.result__link\n props:\n title: h2\n commonProps:\n $site: ecosia\n $category: news\n delay: true\n\n - name: Videos\n matches:\n - https://www.ecosia.org/videos?*\n results:\n - root: .result\n url: a.result__link\n props:\n title: h2\n commonProps:\n $site: ecosia\n $category: videos\n delay: true\n'; // builtin/serpinfo/google.yml var google_default = `name: Google homepage: https://github.com/ublacklist/builtin#readme lastModified: 2025-05-02T04:08:02Z pages: - name: Web (desktop) matches: &matches - https://www.google.com/search?* - https://www.google.ad/search?* - https://www.google.ae/search?* - https://www.google.com.af/search?* - https://www.google.com.ag/search?* - https://www.google.al/search?* - https://www.google.am/search?* - https://www.google.co.ao/search?* - https://www.google.com.ar/search?* - https://www.google.as/search?* - https://www.google.at/search?* - https://www.google.com.au/search?* - https://www.google.az/search?* - https://www.google.ba/search?* - https://www.google.com.bd/search?* - https://www.google.be/search?* - https://www.google.bf/search?* - https://www.google.bg/search?* - https://www.google.com.bh/search?* - https://www.google.bi/search?* - https://www.google.bj/search?* - https://www.google.com.bn/search?* - https://www.google.com.bo/search?* - https://www.google.com.br/search?* - https://www.google.bs/search?* - https://www.google.bt/search?* - https://www.google.co.bw/search?* - https://www.google.by/search?* - https://www.google.com.bz/search?* - https://www.google.ca/search?* - https://www.google.cd/search?* - https://www.google.cf/search?* - https://www.google.cg/search?* - https://www.google.ch/search?* - https://www.google.ci/search?* - https://www.google.co.ck/search?* - https://www.google.cl/search?* - https://www.google.cm/search?* - https://www.google.cn/search?* - https://www.google.com.co/search?* - https://www.google.co.cr/search?* - https://www.google.com.cu/search?* - https://www.google.cv/search?* - https://www.google.com.cy/search?* - https://www.google.cz/search?* - https://www.google.de/search?* - https://www.google.dj/search?* - https://www.google.dk/search?* - https://www.google.dm/search?* - https://www.google.com.do/search?* - https://www.google.dz/search?* - https://www.google.com.ec/search?* - https://www.google.ee/search?* - https://www.google.com.eg/search?* - https://www.google.es/search?* - https://www.google.com.et/search?* - https://www.google.fi/search?* - https://www.google.com.fj/search?* - https://www.google.fm/search?* - https://www.google.fr/search?* - https://www.google.ga/search?* - https://www.google.ge/search?* - https://www.google.gg/search?* - https://www.google.com.gh/search?* - https://www.google.com.gi/search?* - https://www.google.gl/search?* - https://www.google.gm/search?* - https://www.google.gr/search?* - https://www.google.com.gt/search?* - https://www.google.gy/search?* - https://www.google.com.hk/search?* - https://www.google.hn/search?* - https://www.google.hr/search?* - https://www.google.ht/search?* - https://www.google.hu/search?* - https://www.google.co.id/search?* - https://www.google.ie/search?* - https://www.google.co.il/search?* - https://www.google.im/search?* - https://www.google.co.in/search?* - https://www.google.iq/search?* - https://www.google.is/search?* - https://www.google.it/search?* - https://www.google.je/search?* - https://www.google.com.jm/search?* - https://www.google.jo/search?* - https://www.google.co.jp/search?* - https://www.google.co.ke/search?* - https://www.google.com.kh/search?* - https://www.google.ki/search?* - https://www.google.kg/search?* - https://www.google.co.kr/search?* - https://www.google.com.kw/search?* - https://www.google.kz/search?* - https://www.google.la/search?* - https://www.google.com.lb/search?* - https://www.google.li/search?* - https://www.google.lk/search?* - https://www.google.co.ls/search?* - https://www.google.lt/search?* - https://www.google.lu/search?* - https://www.google.lv/search?* - https://www.google.com.ly/search?* - https://www.google.co.ma/search?* - https://www.google.md/search?* - https://www.google.me/search?* - https://www.google.mg/search?* - https://www.google.mk/search?* - https://www.google.ml/search?* - https://www.google.com.mm/search?* - https://www.google.mn/search?* - https://www.google.com.mt/search?* - https://www.google.mu/search?* - https://www.google.mv/search?* - https://www.google.mw/search?* - https://www.google.com.mx/search?* - https://www.google.com.my/search?* - https://www.google.co.mz/search?* - https://www.google.com.na/search?* - https://www.google.com.ng/search?* - https://www.google.com.ni/search?* - https://www.google.ne/search?* - https://www.google.nl/search?* - https://www.google.no/search?* - https://www.google.com.np/search?* - https://www.google.nr/search?* - https://www.google.nu/search?* - https://www.google.co.nz/search?* - https://www.google.com.om/search?* - https://www.google.com.pa/search?* - https://www.google.com.pe/search?* - https://www.google.com.pg/search?* - https://www.google.com.ph/search?* - https://www.google.com.pk/search?* - https://www.google.pl/search?* - https://www.google.pn/search?* - https://www.google.com.pr/search?* - https://www.google.ps/search?* - https://www.google.pt/search?* - https://www.google.com.py/search?* - https://www.google.com.qa/search?* - https://www.google.ro/search?* - https://www.google.ru/search?* - https://www.google.rw/search?* - https://www.google.com.sa/search?* - https://www.google.com.sb/search?* - https://www.google.sc/search?* - https://www.google.se/search?* - https://www.google.com.sg/search?* - https://www.google.sh/search?* - https://www.google.si/search?* - https://www.google.sk/search?* - https://www.google.com.sl/search?* - https://www.google.sn/search?* - https://www.google.so/search?* - https://www.google.sm/search?* - https://www.google.sr/search?* - https://www.google.st/search?* - https://www.google.com.sv/search?* - https://www.google.td/search?* - https://www.google.tg/search?* - https://www.google.co.th/search?* - https://www.google.com.tj/search?* - https://www.google.tl/search?* - https://www.google.tm/search?* - https://www.google.tn/search?* - https://www.google.to/search?* - https://www.google.com.tr/search?* - https://www.google.tt/search?* - https://www.google.com.tw/search?* - https://www.google.co.tz/search?* - https://www.google.com.ua/search?* - https://www.google.co.ug/search?* - https://www.google.co.uk/search?* - https://www.google.com.uy/search?* - https://www.google.co.uz/search?* - https://www.google.com.vc/search?* - https://www.google.co.ve/search?* - https://www.google.co.vi/search?* - https://www.google.com.vn/search?* - https://www.google.vu/search?* - https://www.google.ws/search?* - https://www.google.rs/search?* - https://www.google.co.za/search?* - https://www.google.co.zm/search?* - https://www.google.co.zw/search?* - https://www.google.cat/search?* excludeRegex: "[?&](udm=(?!14(&|$))|tbm=)" userAgent: desktop results: - name: Default root: .vt6azd:not(.g-blk) url: :is(.yuRUbf, .xe8e1b) a props: title: h3 - name: Images root: .vCUuC url: a props: title: .Yt787 - name: Videos root: .sHEJob url: a[href^="http"] props: title: .OSrXXb commonProps: $site: google $category: web - name: Images (desktop) matches: *matches includeRegex: "[?&]udm=2(&|$)" userAgent: desktop results: - root: .ivg-i url: .EZAeBe props: title: .OSrXXb commonProps: $site: google $category: images - name: Videos (desktop) matches: *matches includeRegex: "[?&]udm=7(&|$)" userAgent: desktop results: - root: .vt6azd url: .xe8e1b a props: title: h3 commonProps: $site: google $category: videos - name: News (desktop) matches: *matches includeRegex: "[?&]tbm=nws(&|$)" userAgent: desktop results: - root: .SoaBEf url: .WlydOe props: title: '[role="heading"][aria-level="3"]' commonProps: $site: google $category: news - name: Web (mobile) matches: *matches excludeRegex: "[?&](udm=(?!14(&|$))|tbm=)" userAgent: mobile results: - name: Default root: .vt6azd url: a[role="presentation"] props: title: '[role="heading"][aria-level="3"]' button: [inset, { top: "16px", right: "32px" }] - name: Images root: .DyfMyc url: a props: title: .Yt787 preserveSpace: true - name: Videos root: .sHEJob url: a[href^="http"] props: title: .OSrXXb commonProps: $site: google $category: web - name: Images (mobile) matches: *matches includeRegex: "[?&]udm=2(&|$)" userAgent: mobile results: - root: [upward, 1, ".ivg-i"] url: a props: title: .Q6A6Dc commonProps: $site: google $category: images - name: Videos (mobile) matches: *matches includeRegex: "[?&]udm=7(&|$)" userAgent: mobile results: - root: .Ww4FFb url: a[href^="http"] props: title: .J4ORzd commonProps: $site: google $category: videos - name: News (mobile) matches: *matches includeRegex: "[?&]tbm=nws(&|$)" userAgent: mobile results: - root: .Ww4FFb url: .WlydOe props: title: '[role="heading"][aria-level="3"]' commonProps: $site: google $category: news `; // builtin/serpinfo/searxng.yml var searxng_default = 'name: SearXNG\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-05-02T04:08:02Z\n\npages:\n - name: All\n includeRegex: "/search(\\\\?|$)"\n results:\n - root: .category-general\n url: a\n props:\n title: h3\n $category: [const, "web"]\n - root: .category-images\n url: .result-url > a\n props:\n title: .title\n $category: [const, "images"]\n - root: .category-videos\n url: a\n props:\n title: h3\n $category: [const, "videos"]\n - root: .category-news\n url: a\n props:\n title: h3\n $cateogry: [const, "news"]\n commonProps:\n $site: searx # backwards compatibility\n matches:\n # https://github.com/searxng/searx-instances/blob/54135f280e613540604e11ed577c09d31ff71b20/searxinstances/instances.yml\n - https://baresearch.org/*\n - https://copp.gg/*\n - https://darmarit.org/searx/*\n - https://etsi.me/*\n - https://fairsuch.net/*\n - https://kantan.cat/*\n - https://metacat.online/*\n - https://nogoo.me/*\n - https://northboot.xyz/*\n - https://nyc1.sx.ggtyler.dev/*\n - https://ooglester.com/*\n - https://opnxng.com/*\n - https://paulgo.io/*\n - https://priv.au/*\n - https://s.datuan.dev/*\n - https://s.mble.dk/*\n - https://search.080609.xyz/*\n - https://search.canine.tools/*\n - https://search.catboy.house/*\n - https://search.citw.lgbt/*\n - https://search.cloakpanda.com/*\n - https://search.einfachzocken.eu/*\n - https://search.fredix.xyz/*\n - https://search.gcomm.ch/*\n - https://search.hbubli.cc/*\n - https://search.im-in.space/*\n - https://search.indst.eu/*\n - https://search.inetol.net/*\n - https://search.ipv6s.net/*\n - https://search.leptons.xyz/*\n - https://search.librenode.com/*\n - https://search.mdosch.de/*\n - https://search.mrblake.cc/*\n - https://search.nerdvpn.de/*\n - https://search.nordh.tech/*\n - https://search.ohaa.xyz/*\n - https://search.ononoki.org/*\n - https://search.privacyredirect.com/*\n - https://search.projectsegfau.lt/*\n - https://search.rhscz.eu/*\n - https://search.rowie.at/*\n - https://search.sapti.me/*\n - https://search.url4irl.com/*\n - https://searx.ankha.ac/*\n - https://searx.be/*\n - https://searx.dresden.network/*\n - https://searx.foobar.vip/*\n - https://searx.foss.family/*\n - https://searx.juancord.xyz/*\n - https://searx.lunar.icu/*\n - https://searx.mbuf.net/*\n - https://searx.mxchange.org/*\n - https://searx.namejeff.xyz/*\n - https://searx.oakleycord.dev/*\n - https://searx.oloke.xyz/*\n - https://searx.ox2.fr/*\n - https://searx.party/*\n - https://searx.perennialte.ch/*\n - https://searx.rhscz.eu/*\n - https://searx.ro/*\n - https://searx.sev.monster/*\n - https://searx.thefloatinglab.world/*\n - https://searx.tiekoetter.com/*\n - https://searx.tuxcloud.net/*\n - https://searx.zhenyapav.com/*\n - https://searxng.biz/*\n - https://searxng.brihx.fr/*\n - https://searxng.deliberate.world/*\n - https://searxng.f24o.zip/*\n - https://searxng.hweeren.com/*\n - https://searxng.shreven.org/*\n - https://searxng.site/*\n - https://searxng.website/*\n - https://searxng.world/*\n - https://seek.fyi/*\n - https://suche.dasnetzundich.de/*\n - https://sx.catgirl.cloud/*\n - https://www.gruble.de/*\n'; // builtin/serpinfo/startpage.yml var startpage_default = 'name: Startpage\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-04-29T09:49:28Z\n\npages:\n - name: Default\n matches:\n - https://*.startpage.com/do/*\n - https://*.startpage.com/rvd/*\n - https://*.startpage.com/sp/*\n results:\n - root: .w-gl > .result\n url: .result-link\n props:\n title: h2\n $category: [const, "web"]\n - root: .image-container\n url: [domainToURL, ".image-quick-details > span"]\n props:\n title: .image-quick-details > div\n $category: [const, "images"]\n - root: .article\n url: a\n props:\n title: h3\n $category: [const, "news"]\n - root: .vo-bg > .result\n url: a\n props:\n title: h3\n $category: [const, "videos"]\n commonProps:\n $site: startpage\n'; // builtin/serpinfo/yahoo-japan.yml var yahoo_japan_default = 'name: Yahoo! JAPAN\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-04-29T09:49:28Z\n\npages:\n - name: Web\n matches:\n - https://search.yahoo.co.jp/search?*\n results:\n - root: [upward, 1, ".sw-Card.Algo"]\n url: a\n props:\n title: h3\n commonProps:\n $site: yahooJapan\n $category: web\n delay: true\n\n - name: Images (desktop)\n matches:\n - https://search.yahoo.co.jp/image/search?*\n userAgent: desktop\n results:\n - root: .sw-Thumbnail\n url: .sw-Thumbnail__details\n props:\n title: .sw-Thumbnail__title\n button: [inset, { top: 0, right: 0, zIndex: 4 }]\n preserveSpace: true\n commonsProps:\n $site: yahooJapan\n $category: images\n delay: true\n\n - name: Images (mobile)\n matches:\n - https://search.yahoo.co.jp/image/search?*\n userAgent: mobile\n results:\n - root: .sw-ThumbnailGrid__columnItem\n url:\n - regexSubstitute\n - "targurl:([^;]+)"\n - "https://\\\\1"\n - [attribute, "data-cl-params", ".sw-ThumbnailGrid__details"]\n props:\n title: .sw-ThumbnailGrid__title\n commonsProps:\n $site: yahooJapan\n $category: images\n delay: true\n\n - name: Videos (desktop)\n matches:\n - https://search.yahoo.co.jp/video/search?*\n userAgent: desktop\n results:\n - root: .sw-CardBase\n url: a\n props:\n title: h3\n commonProps:\n $site: yahooJapan\n $category: videos\n delay: true\n\n - name: Videos (mobile)\n matches:\n - https://search.yahoo.co.jp/video/search?*\n userAgent: mobile\n results:\n - root: .sw-EmbedListItem\n url:\n - regexSubstitute\n - "targurl:([^;]+)"\n - "https://\\\\1"\n - [attribute, "data-cl-params", ".sw-EmbedListItem__wrapper"]\n props:\n title: h2\n - root: .sw-ListItem\n url: .sw-ListItem__wrapper\n props:\n title: h2\n commonProps:\n $site: yahooJapan\n $category: videos\n delay: true\n'; // builtin/serpinfo/yandex.yml var yandex_default = 'name: Yandex\nhomepage: https://github.com/ublacklist/builtin#readme\nlastModified: 2025-05-02T04:08:02Z\n\npages:\n - name: Web (desktop)\n matches: &matches\n - https://yandex.com/*\n - https://yandex.com.am/*\n - https://yandex.az/*\n - https://yandex.by/*\n - https://yandex.ee/*\n - https://yandex.eu/*\n - https://yandex.com.ge/*\n - https://yandex.co.il/*\n - https://yandex.kz/*\n - https://yandex.lt/*\n - https://yandex.lv/*\n - https://yandex.md/*\n - https://yandex.ru/*\n - https://yandex.tj/*\n - https://yandex.tm/*\n - https://yandex.com.tr/*\n - https://yandex.uz/*\n - https://ya.ru/*\n includeRegex: "^https://[^/]+/search/?\\\\?"\n results:\n - root: .serp-item\n url: a\n props:\n title: h2\n button: [inset, { top: "4px", right: "24px", zIndex: 10 }]\n commonProps:\n $site: yandex\n $category: web\n\n - name: Web (mobile)\n matches: *matches\n includeRegex: "^https://[^/]+/search/touch/?\\\\?"\n results:\n - root: .serp-item\n url: a\n props:\n title: h2\n button: [inset, { top: "8px", right: "24px" }]\n commonProps:\n $site: yandex\n $category: web\n\n - name: Videos (desktop)\n matches: *matches\n includeRegex: "^https://[^/]+/video/search/?\\\\?"\n results:\n - root: .SearchBlock\n url: .VideoHostExtended-Host\n props:\n title: .VideoSnippet-Title\n button: [inset, { top: "3px", right: "24px" }]\n commonProps:\n $site: yandex\n $category: videos\n\n - name: Videos (mobile)\n matches: *matches\n includeRegex: "^https://[^/]+/video/touch/search/?\\\\?"\n results:\n - root: .SearchBlock\n url: .VideoHostExtended-Host\n props:\n title: .VideoSnippet-Title\n commonProps:\n $site: yandex\n $category: videos\n'; // src/scripts/serpinfo/builtins.ts function getURL(filename) { return `https://raw.githubusercontent.com/ublacklist/builtin/refs/heads/dist/serpinfo/${filename}`; } var GOOGLE_SERPINFO_URL = getURL("google.yml"); var BUILTINS = [ { url: GOOGLE_SERPINFO_URL, content: google_default }, { url: getURL("bing.yml"), content: bing_default }, { url: getURL("brave.yml"), content: brave_default }, { url: getURL("duckduckgo.yml"), content: duckduckgo_default }, { url: getURL("ecosia.yml"), content: ecosia_default }, { url: getURL("searxng.yml"), content: searxng_default }, { url: getURL("startpage.yml"), content: startpage_default }, { url: getURL("yahoo-japan.yml"), content: yahoo_japan_default }, { url: getURL("yandex.yml"), content: yandex_default } ]; // node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs function isNothing(subject) { return typeof subject === "undefined" || subject === null; } function isObject(subject) { return typeof subject === "object" && subject !== null; } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [sequence]; } function extend(target, source) { var index, length2, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length2 = sourceKeys.length; index < length2; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string2, count) { var result = "", cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string2; } return result; } function isNegativeZero(number3) { return number3 === 0 && Number.NEGATIVE_INFINITY === 1 / number3; } var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; function formatError(exception2, compact) { var where = "", message = exception2.reason || "(unknown reason)"; if (!exception2.mark) return message; if (exception2.mark.name) { where += 'in "' + exception2.mark.name + '" '; } where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; if (!compact && exception2.mark.snippet) { where += "\n\n" + exception2.mark.snippet; } return message + " " + where; } function YAMLException$1(reason, mark) { Error.call(this); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError(this, false); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack || ""; } } YAMLException$1.prototype = Object.create(Error.prototype); YAMLException$1.prototype.constructor = YAMLException$1; YAMLException$1.prototype.toString = function toString(compact) { return this.name + ": " + formatError(this, compact); }; var exception = YAMLException$1; function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ""; var tail = ""; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = " ... "; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = " ..."; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string2, max) { return common.repeat(" ", max - string2.length) + string2; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== "number") options.indent = 1; if (typeof options.linesBefore !== "number") options.linesBefore = 3; if (typeof options.linesAfter !== "number") options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [0]; var lineEnds = []; var match; var foundLineNo = -1; while (match = re.exec(mark.buffer)) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = "", i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; } return result.replace(/\n$/, ""); } var snippet = makeSnippet; var TYPE_CONSTRUCTOR_OPTIONS = [ "kind", "multi", "resolve", "construct", "instanceOf", "predicate", "represent", "representName", "defaultStyle", "styleAliases" ]; var YAML_NODE_KINDS = [ "scalar", "sequence", "mapping" ]; function compileStyleAliases(map2) { var result = {}; if (map2 !== null) { Object.keys(map2).forEach(function(style) { map2[style].forEach(function(alias) { result[String(alias)] = style; }); }); } return result; } function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function(name51) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name51) === -1) { throw new exception('Unknown option "' + name51 + '" is met in definition of "' + tag + '" YAML type.'); } }); this.options = options; this.tag = tag; this.kind = options["kind"] || null; this.resolve = options["resolve"] || function() { return true; }; this.construct = options["construct"] || function(data) { return data; }; this.instanceOf = options["instanceOf"] || null; this.predicate = options["predicate"] || null; this.represent = options["represent"] || null; this.representName = options["representName"] || null; this.defaultStyle = options["defaultStyle"] || null; this.multi = options["multi"] || false; this.styleAliases = compileStyleAliases(options["styleAliases"] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } var type = Type$1; function compileList(schema2, name51) { var result = []; schema2[name51].forEach(function(currentType) { var newIndex = result.length; result.forEach(function(previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap() { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length2; function collectType(type2) { if (type2.multi) { result.multi[type2.kind].push(type2); result.multi["fallback"].push(type2); } else { result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; } } for (index = 0, length2 = arguments.length; index < length2; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema$1(definition) { return this.extend(definition); } Schema$1.prototype.extend = function extend2(definition) { var implicit = []; var explicit = []; if (definition instanceof type) { explicit.push(definition); } else if (Array.isArray(definition)) { explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); } implicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } if (type$1.loadKind && type$1.loadKind !== "scalar") { throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); } if (type$1.multi) { throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); } }); explicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } }); var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, "implicit"); result.compiledExplicit = compileList(result, "explicit"); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; var schema = Schema$1; var str = new type("tag:yaml.org,2002:str", { kind: "scalar", construct: function(data) { return data !== null ? data : ""; } }); var seq = new type("tag:yaml.org,2002:seq", { kind: "sequence", construct: function(data) { return data !== null ? data : []; } }); var map = new type("tag:yaml.org,2002:map", { kind: "mapping", construct: function(data) { return data !== null ? data : {}; } }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL"); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } var _null = new type("tag:yaml.org,2002:null", { kind: "scalar", resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function() { return "~"; }, lowercase: function() { return "null"; }, uppercase: function() { return "NULL"; }, camelcase: function() { return "Null"; }, empty: function() { return ""; } }, defaultStyle: "lowercase" }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE"); } function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } function isBoolean(object) { return Object.prototype.toString.call(object) === "[object Boolean]"; } var bool = new type("tag:yaml.org,2002:bool", { kind: "scalar", resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function(object) { return object ? "true" : "false"; }, uppercase: function(object) { return object ? "TRUE" : "FALSE"; }, camelcase: function(object) { return object ? "True" : "False"; } }, defaultStyle: "lowercase" }); function isHexCode(c) { return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102; } function isOctCode(c) { return 48 <= c && c <= 55; } function isDecCode(c) { return 48 <= c && c <= 57; } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; if (ch === "-" || ch === "+") { ch = data[++index]; } if (ch === "0") { if (index + 1 === max) return true; ch = data[++index]; if (ch === "b") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (ch !== "0" && ch !== "1") return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "x") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "o") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } } if (ch === "_") return false; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } if (!hasDigits || ch === "_") return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf("_") !== -1) { value = value.replace(/_/g, ""); } ch = value[0]; if (ch === "-" || ch === "+") { if (ch === "-") sign = -1; value = value.slice(1); ch = value[0]; } if (value === "0") return 0; if (ch === "0") { if (value[1] === "b") return sign * parseInt(value.slice(2), 2); if (value[1] === "x") return sign * parseInt(value.slice(2), 16); if (value[1] === "o") return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object)); } var int = new type("tag:yaml.org,2002:int", { kind: "scalar", resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function(obj) { return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); }, octal: function(obj) { return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); }, decimal: function(obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function(obj) { return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: "decimal", styleAliases: { binary: [2, "bin"], octal: [8, "oct"], decimal: [10, "dec"], hexadecimal: [16, "hex"] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$" ); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === "_") { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, "").toLowerCase(); sign = value[0] === "-" ? -1 : 1; if ("+-".indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === ".inf") { return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === ".nan") { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case "lowercase": return ".nan"; case "uppercase": return ".NAN"; case "camelcase": return ".NaN"; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case "lowercase": return ".inf"; case "uppercase": return ".INF"; case "camelcase": return ".Inf"; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case "lowercase": return "-.inf"; case "uppercase": return "-.INF"; case "camelcase": return "-.Inf"; } } else if (common.isNegativeZero(object)) { return "-0.0"; } res = object.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } function isFloat(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); } var float = new type("tag:yaml.org,2002:float", { kind: "scalar", resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: "lowercase" }); var json = failsafe.extend({ implicit: [ _null, bool, int, float ] }); var core = json; var YAML_DATE_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" ); var YAML_TIMESTAMP_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$" ); function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error("Date resolve error"); year = +match[1]; month = +match[2] - 1; day = +match[3]; if (!match[4]) { return new Date(Date.UTC(year, month, day)); } hour = +match[4]; minute = +match[5]; second = +match[6]; if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { fraction += "0"; } fraction = +fraction; } if (match[9]) { tz_hour = +match[10]; tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 6e4; if (match[9] === "-") delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object) { return object.toISOString(); } var timestamp = new type("tag:yaml.org,2002:timestamp", { kind: "scalar", resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === "<<" || data === null; } var merge = new type("tag:yaml.org,2002:merge", { kind: "scalar", resolve: resolveYamlMerge }); var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; function resolveYamlBinary(data) { if (data === null) return false; var code2, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { code2 = map2.indexOf(data.charAt(idx)); if (code2 > 64) continue; if (code2 < 0) return false; bitlen += 6; } return bitlen % 8 === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = []; for (idx = 0; idx < max; idx++) { if (idx % 4 === 0 && idx) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } bits = bits << 6 | map2.indexOf(input.charAt(idx)); } tailbits = max % 4 * 6; if (tailbits === 0) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } else if (tailbits === 18) { result.push(bits >> 10 & 255); result.push(bits >> 2 & 255); } else if (tailbits === 12) { result.push(bits >> 4 & 255); } return new Uint8Array(result); } function representYamlBinary(object) { var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } bits = (bits << 8) + object[idx]; } tail = max % 3; if (tail === 0) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } else if (tail === 2) { result += map2[bits >> 10 & 63]; result += map2[bits >> 4 & 63]; result += map2[bits << 2 & 63]; result += map2[64]; } else if (tail === 1) { result += map2[bits >> 2 & 63]; result += map2[bits << 4 & 63]; result += map2[64]; result += map2[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } var binary = new type("tag:yaml.org,2002:binary", { kind: "scalar", resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length2, pair2, pairKey, pairHasKey, object = data; for (index = 0, length2 = object.length; index < length2; index += 1) { pair2 = object[index]; pairHasKey = false; if (_toString$2.call(pair2) !== "[object Object]") return false; for (pairKey in pair2) { if (_hasOwnProperty$3.call(pair2, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } var omap = new type("tag:yaml.org,2002:omap", { kind: "sequence", resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length2, pair2, keys, result, object = data; result = new Array(object.length); for (index = 0, length2 = object.length; index < length2; index += 1) { pair2 = object[index]; if (_toString$1.call(pair2) !== "[object Object]") return false; keys = Object.keys(pair2); if (keys.length !== 1) return false; result[index] = [keys[0], pair2[keys[0]]]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length2, pair2, keys, result, object = data; result = new Array(object.length); for (index = 0, length2 = object.length; index < length2; index += 1) { pair2 = object[index]; keys = Object.keys(pair2); result[index] = [keys[0], pair2[keys[0]]]; } return result; } var pairs = new type("tag:yaml.org,2002:pairs", { kind: "sequence", resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } var set = new type("tag:yaml.org,2002:set", { kind: "mapping", resolve: resolveYamlSet, construct: constructYamlSet }); var _default = core.extend({ implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return c === 10 || c === 13; } function is_WHITE_SPACE(c) { return c === 9 || c === 32; } function is_WS_OR_EOL(c) { return c === 9 || c === 32 || c === 10 || c === 13; } function is_FLOW_INDICATOR(c) { return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; } function fromHexCode(c) { var lc; if (48 <= c && c <= 57) { return c - 48; } lc = c | 32; if (97 <= lc && lc <= 102) { return lc - 97 + 10; } return -1; } function escapedHexLen(c) { if (c === 120) { return 2; } if (c === 117) { return 4; } if (c === 85) { return 8; } return 0; } function fromDecimalCode(c) { if (48 <= c && c <= 57) { return c - 48; } return -1; } function simpleEscapeSequence(c) { return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : ""; } function charFromCodepoint(c) { if (c <= 65535) { return String.fromCharCode(c); } return String.fromCharCode( (c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320 ); } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } var i; function State$1(input, options) { this.input = input; this.filename = options["filename"] || null; this.schema = options["schema"] || _default; this.onWarning = options["onWarning"] || null; this.legacy = options["legacy"] || false; this.json = options["json"] || false; this.listener = options["listener"] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.firstTabInLine = -1; this.documents = []; } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = snippet(mark); return new exception(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name51, args) { var match, major, minor; if (state.version !== null) { throwError(state, "duplication of %YAML directive"); } if (args.length !== 1) { throwError(state, "YAML directive accepts exactly one argument"); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, "ill-formed argument of the YAML directive"); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, "unacceptable YAML version of the document"); } state.version = args[0]; state.checkLineBreaks = minor < 2; if (minor !== 1 && minor !== 2) { throwWarning(state, "unsupported YAML version of the document"); } }, TAG: function handleTagDirective(state, name51, args) { var handle, prefix; if (args.length !== 2) { throwError(state, "TAG directive accepts exactly two arguments"); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); } if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, "tag prefix is malformed: " + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 9 || 32 <= _character && _character <= 1114111)) { throwError(state, "expected valid JSON character"); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, "the stream contains non-printable characters"); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, "cannot merge mappings; the provided source object is unacceptable"); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, "nested arrays are not supported inside keys"); } if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") { keyNode[index] = "[object Object]"; } } } if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") { keyNode = "[object Object]"; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === "tag:yaml.org,2002:merge") { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, "duplicated mapping key"); } if (keyNode === "__proto__") { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 10) { state.position++; } else if (ch === 13) { state.position++; if (state.input.charCodeAt(state.position) === 10) { state.position++; } } else { throwError(state, "a line break is expected"); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 9 && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 10 && ch !== 13 && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, "deficient indentation"); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += " "; } else if (count > 1) { state.result += common.repeat("\n", count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) { return false; } if (ch === 63 || ch === 45) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = "scalar"; state.result = ""; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 58) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 35) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 39) { return false; } state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 39) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 39) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, "unexpected end of the document within a single quoted scalar"); } else { state.position++; captureEnd = state.position; } } throwError(state, "unexpected end of the stream within a single quoted scalar"); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 34) { return false; } state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 34) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 92) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, "expected hexadecimal character"); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, "unknown escape sequence"); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, "unexpected end of the document within a double quoted scalar"); } else { state.position++; captureEnd = state.position; } } throwError(state, "unexpected end of the stream within a double quoted scalar"); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 91) { terminator = 93; isMapping = false; _result = []; } else if (ch === 123) { terminator = 125; isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? "mapping" : "sequence"; state.result = _result; return true; } else if (!readNext) { throwError(state, "missed comma between flow collection entries"); } else if (ch === 44) { throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 63) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 58) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 44) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, "unexpected end of the stream within a flow collection"); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 124) { folding = false; } else if (ch === 62) { folding = true; } else { return false; } state.kind = "scalar"; state.result = ""; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 43 || ch === 45) { if (CHOMPING_CLIP === chomping) { chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, "repeat of a chomping mode identifier"); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, "repeat of an indentation width identifier"); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && ch !== 0); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } if (state.lineIndent < textIndent) { if (chomping === CHOMPING_KEEP) { state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { state.result += "\n"; } } break; } if (folding) { if (is_WHITE_SPACE(ch)) { atMoreIndented = true; state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat("\n", emptyLines + 1); } else if (emptyLines === 0) { if (didReadContent) { state.result += " "; } } else { state.result += common.repeat("\n", emptyLines); } } else { state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && ch !== 0) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } if (ch !== 45) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { throwError(state, "bad indentation of a sequence entry"); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "sequence"; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } following = state.input.charCodeAt(state.position + 1); _line = state.line; if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) { if (ch === 63) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { atExplicitKey = false; allowCompact = true; } else { throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); } state.position += 1; ch = following; } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 58) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, "can not read an implicit mapping pair; a colon is missed"); } else { state.tag = _tag; state.anchor = _anchor; return true; } } else if (detected) { throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); } else { state.tag = _tag; state.anchor = _anchor; return true; } } if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { throwError(state, "bad indentation of a mapping entry"); } else if (state.lineIndent < nodeIndent) { break; } } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "mapping"; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 33) return false; if (state.tag !== null) { throwError(state, "duplication of a tag property"); } ch = state.input.charCodeAt(++state.position); if (ch === 60) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 33) { isNamed = true; tagHandle = "!!"; ch = state.input.charCodeAt(++state.position); } else { tagHandle = "!"; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 62); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, "unexpected end of the stream within a verbatim tag"); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 33) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, "named tag handle cannot contain such characters"); } isNamed = true; _position = state.position + 1; } else { throwError(state, "tag suffix cannot contain exclamation marks"); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, "tag suffix cannot contain flow indicator characters"); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, "tag name cannot contain such characters: " + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, "tag name is malformed: " + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === "!") { state.tag = "!" + tagName; } else if (tagHandle === "!!") { state.tag = "tag:yaml.org,2002:" + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 38) return false; if (state.anchor !== null) { throwError(state, "duplication of an anchor property"); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, "name of an anchor node must contain at least one character"); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 42) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, "name of an alias node must contain at least one character"); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent; if (state.listener !== null) { state.listener("open", state); } state.tag = null; state.anchor = null; state.kind = null; state.result = null; allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, "alias node should not have any properties"); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = "?"; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === "?") { if (state.result !== null && state.kind !== "scalar") { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type2 = state.implicitTypes[typeIndex]; if (type2.resolve(state.result)) { state.result = type2.construct(state.result); state.tag = type2.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== "!") { if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) { type2 = state.typeMap[state.kind || "fallback"][state.tag]; } else { type2 = null; typeList = state.typeMap.multi[state.kind || "fallback"]; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type2 = typeList[typeIndex]; break; } } } if (!type2) { throwError(state, "unknown tag !<" + state.tag + ">"); } if (state.result !== null && type2.kind !== state.kind) { throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"'); } if (!type2.resolve(state.result, state.tag)) { throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); } else { state.result = type2.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener("close", state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = /* @__PURE__ */ Object.create(null); state.anchorMap = /* @__PURE__ */ Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 37) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, "directive name must not be less than one character in length"); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, "directives end mark is expected"); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, "non-ASCII line breaks are interpreted as content"); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 46) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < state.length - 1) { throwError(state, "end of the stream or a document separator is expected"); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) { input += "\n"; } if (input.charCodeAt(0) === 65279) { input = input.slice(1); } } var state = new State$1(input, options); var nullpos = input.indexOf("\0"); if (nullpos !== -1) { state.position = nullpos; throwError(state, "null byte is not allowed in input"); } state.input += "\0"; while (state.input.charCodeAt(state.position) === 32) { state.lineIndent += 1; state.position += 1; } while (state.position < state.length - 1) { readDocument(state); } return state.documents; } function loadAll$1(input, iterator, options) { if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== "function") { return documents; } for (var index = 0, length2 = documents.length; index < length2; index += 1) { iterator(documents[index]); } } function load$1(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { return void 0; } else if (documents.length === 1) { return documents[0]; } throw new exception("expected a single document in the stream, but found more"); } var loadAll_1 = loadAll$1; var load_1 = load$1; var loader = { loadAll: loadAll_1, load: load_1 }; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 65279; var CHAR_TAB = 9; var CHAR_LINE_FEED = 10; var CHAR_CARRIAGE_RETURN = 13; var CHAR_SPACE = 32; var CHAR_EXCLAMATION = 33; var CHAR_DOUBLE_QUOTE = 34; var CHAR_SHARP = 35; var CHAR_PERCENT = 37; var CHAR_AMPERSAND = 38; var CHAR_SINGLE_QUOTE = 39; var CHAR_ASTERISK = 42; var CHAR_COMMA = 44; var CHAR_MINUS = 45; var CHAR_COLON = 58; var CHAR_EQUALS = 61; var CHAR_GREATER_THAN = 62; var CHAR_QUESTION = 63; var CHAR_COMMERCIAL_AT = 64; var CHAR_LEFT_SQUARE_BRACKET = 91; var CHAR_RIGHT_SQUARE_BRACKET = 93; var CHAR_GRAVE_ACCENT = 96; var CHAR_LEFT_CURLY_BRACKET = 123; var CHAR_VERTICAL_LINE = 124; var CHAR_RIGHT_CURLY_BRACKET = 125; var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0] = "\\0"; ESCAPE_SEQUENCES[7] = "\\a"; ESCAPE_SEQUENCES[8] = "\\b"; ESCAPE_SEQUENCES[9] = "\\t"; ESCAPE_SEQUENCES[10] = "\\n"; ESCAPE_SEQUENCES[11] = "\\v"; ESCAPE_SEQUENCES[12] = "\\f"; ESCAPE_SEQUENCES[13] = "\\r"; ESCAPE_SEQUENCES[27] = "\\e"; ESCAPE_SEQUENCES[34] = '\\"'; ESCAPE_SEQUENCES[92] = "\\\\"; ESCAPE_SEQUENCES[133] = "\\N"; ESCAPE_SEQUENCES[160] = "\\_"; ESCAPE_SEQUENCES[8232] = "\\L"; ESCAPE_SEQUENCES[8233] = "\\P"; var DEPRECATED_BOOLEANS_SYNTAX = [ "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", "n", "N", "no", "No", "NO", "off", "Off", "OFF" ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema2, map2) { var result, keys, index, length2, tag, style, type2; if (map2 === null) return {}; result = {}; keys = Object.keys(map2); for (index = 0, length2 = keys.length; index < length2; index += 1) { tag = keys[index]; style = String(map2[tag]); if (tag.slice(0, 2) === "!!") { tag = "tag:yaml.org,2002:" + tag.slice(2); } type2 = schema2.compiledTypeMap["fallback"][tag]; if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) { style = type2.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string2, handle, length2; string2 = character.toString(16).toUpperCase(); if (character <= 255) { handle = "x"; length2 = 2; } else if (character <= 65535) { handle = "u"; length2 = 4; } else if (character <= 4294967295) { handle = "U"; length2 = 8; } else { throw new exception("code point within a string may not be greater than 0xFFFFFFFF"); } return "\\" + handle + common.repeat("0", length2 - string2.length) + string2; } var QUOTING_TYPE_SINGLE = 1; var QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options["schema"] || _default; this.indent = Math.max(1, options["indent"] || 2); this.noArrayIndent = options["noArrayIndent"] || false; this.skipInvalid = options["skipInvalid"] || false; this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; this.styleMap = compileStyleMap(this.schema, options["styles"] || null); this.sortKeys = options["sortKeys"] || false; this.lineWidth = options["lineWidth"] || 80; this.noRefs = options["noRefs"] || false; this.noCompatMode = options["noCompatMode"] || false; this.condenseFlow = options["condenseFlow"] || false; this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options["forceQuotes"] || false; this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ""; this.duplicates = []; this.usedDuplicates = null; } function indentString(string2, spaces) { var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length2 = string2.length; while (position < length2) { next = string2.indexOf("\n", position); if (next === -1) { line = string2.slice(position); position = length2; } else { line = string2.slice(position, next + 1); position = next + 1; } if (line.length && line !== "\n") result += ind; result += line; } return result; } function generateNextLine(state, level) { return "\n" + common.repeat(" ", state.indent * level); } function testImplicitResolving(state, str2) { var index, length2, type2; for (index = 0, length2 = state.implicitTypes.length; index < length2; index += 1) { type2 = state.implicitTypes[index]; if (type2.resolve(str2)) { return true; } } return false; } function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } function isPrintable(c) { return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111; } function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } function isPlainSafe(c, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return ( // ns-plain-safe (inblock ? ( // c = flow-in cIsNsCharOrWhitespace ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar ); } function isPlainSafeFirst(c) { return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } function isPlainSafeLast(c) { return !isWhitespace(c) && c !== CHAR_COLON; } function codePointAt(string2, pos) { var first = string2.charCodeAt(pos), second; if (first >= 55296 && first <= 56319 && pos + 1 < string2.length) { second = string2.charCodeAt(pos + 1); if (second >= 56320 && second <= 57343) { return (first - 55296) * 1024 + second - 56320 + 65536; } } return first; } function needIndentIndicator(string2) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string2); } var STYLE_PLAIN = 1; var STYLE_SINGLE = 2; var STYLE_LITERAL = 3; var STYLE_FOLDED = 4; var STYLE_DOUBLE = 5; function chooseScalarStyle(string2, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; var plain = isPlainSafeFirst(codePointAt(string2, 0)) && isPlainSafeLast(codePointAt(string2, string2.length - 1)); if (singleLineOnly || forceQuotes) { for (i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string2, i); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { for (i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string2, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. i - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " "; previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " "); } if (!hasLineBreak && !hasFoldableLine) { if (plain && !forceQuotes && !testAmbiguousType(string2)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } if (indentPerLevel > 9 && needIndentIndicator(string2)) { return STYLE_DOUBLE; } if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } function writeScalar(state, string2, level, iskey, inblock) { state.dump = function() { if (string2.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string2) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string2)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string2 + '"' : "'" + string2 + "'"; } } var indent = state.indent * Math.max(1, level); var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; function testAmbiguity(string3) { return testImplicitResolving(state, string3); } switch (chooseScalarStyle( string2, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock )) { case STYLE_PLAIN: return string2; case STYLE_SINGLE: return "'" + string2.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return "|" + blockHeader(string2, state.indent) + dropEndingNewline(indentString(string2, indent)); case STYLE_FOLDED: return ">" + blockHeader(string2, state.indent) + dropEndingNewline(indentString(foldString(string2, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string2) + '"'; default: throw new exception("impossible error: invalid scalar style"); } }(); } function blockHeader(string2, indentPerLevel) { var indentIndicator = needIndentIndicator(string2) ? String(indentPerLevel) : ""; var clip2 = string2[string2.length - 1] === "\n"; var keep = clip2 && (string2[string2.length - 2] === "\n" || string2 === "\n"); var chomp = keep ? "+" : clip2 ? "" : "-"; return indentIndicator + chomp + "\n"; } function dropEndingNewline(string2) { return string2[string2.length - 1] === "\n" ? string2.slice(0, -1) : string2; } function foldString(string2, width) { var lineRe = /(\n+)([^\n]*)/g; var result = function() { var nextLF = string2.indexOf("\n"); nextLF = nextLF !== -1 ? nextLF : string2.length; lineRe.lastIndex = nextLF; return foldLine(string2.slice(0, nextLF), width); }(); var prevMoreIndented = string2[0] === "\n" || string2[0] === " "; var moreIndented; var match; while (match = lineRe.exec(string2)) { var prefix = match[1], line = match[2]; moreIndented = line[0] === " "; result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } function foldLine(line, width) { if (line === "" || line[0] === " ") return line; var breakRe = / [^ ]/g; var match; var start = 0, end, curr = 0, next = 0; var result = ""; while (match = breakRe.exec(line)) { next = match.index; if (next - start > width) { end = curr > start ? curr : next; result += "\n" + line.slice(start, end); start = end + 1; } curr = next; } result += "\n"; if (line.length - start > width && curr > start) { result += line.slice(start, curr) + "\n" + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); } function escapeString(string2) { var result = ""; var char = 0; var escapeSeq; for (var i = 0; i < string2.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string2, i); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string2[i]; if (char >= 65536) result += string2[i + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = "", _tag = state.tag, index, length2, value; for (index = 0, length2 = object.length; index < length2; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); _result += state.dump; } } state.tag = _tag; state.dump = "[" + _result + "]"; } function writeBlockSequence(state, level, object, compact) { var _result = "", _tag = state.tag, index, length2, value; for (index = 0, length2 = object.length; index < length2; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { if (!compact || _result !== "") { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += "-"; } else { _result += "- "; } _result += state.dump; } } state.tag = _tag; state.dump = _result || "[]"; } function writeFlowMapping(state, level, object) { var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length2, objectKey, objectValue, pairBuffer; for (index = 0, length2 = objectKeyList.length; index < length2; index += 1) { pairBuffer = ""; if (_result !== "") pairBuffer += ", "; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; } if (state.dump.length > 1024) pairBuffer += "? "; pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " "); if (!writeNode(state, level, objectValue, false, false)) { continue; } pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = "{" + _result + "}"; } function writeBlockMapping(state, level, object, compact) { var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length2, objectKey, objectValue, explicitPair, pairBuffer; if (state.sortKeys === true) { objectKeyList.sort(); } else if (typeof state.sortKeys === "function") { objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { throw new exception("sortKeys must be a boolean or a function"); } for (index = 0, length2 = objectKeyList.length; index < length2; index += 1) { pairBuffer = ""; if (!compact || _result !== "") { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; } explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += "?"; } else { pairBuffer += "? "; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ":"; } else { pairBuffer += ": "; } pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = _result || "{}"; } function detectType(state, object, explicit) { var _result, typeList, index, length2, type2, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length2 = typeList.length; index < length2; index += 1) { type2 = typeList[index]; if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) { if (explicit) { if (type2.multi && type2.representName) { state.tag = type2.representName(object); } else { state.tag = type2.tag; } } else { state.tag = "?"; } if (type2.represent) { style = state.styleMap[type2.tag] || type2.defaultStyle; if (_toString.call(type2.represent) === "[object Function]") { _result = type2.represent(object, style); } else if (_hasOwnProperty.call(type2.represent, style)) { _result = type2.represent[style](object, style); } else { throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type2 = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = state.flowLevel < 0 || state.flowLevel > level; } var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = "*ref_" + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type2 === "[object Object]") { if (block && Object.keys(state.dump).length !== 0) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = "&ref_" + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = "&ref_" + duplicateIndex + " " + state.dump; } } } else if (type2 === "[object Array]") { if (block && state.dump.length !== 0) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = "&ref_" + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = "&ref_" + duplicateIndex + " " + state.dump; } } } else if (type2 === "[object String]") { if (state.tag !== "?") { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type2 === "[object Undefined]") { return false; } else { if (state.skipInvalid) return false; throw new exception("unacceptable kind of an object to dump " + type2); } if (state.tag !== null && state.tag !== "?") { tagStr = encodeURI( state.tag[0] === "!" ? state.tag.slice(1) : state.tag ).replace(/!/g, "%21"); if (state.tag[0] === "!") { tagStr = "!" + tagStr; } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") { tagStr = "!!" + tagStr.slice(18); } else { tagStr = "!<" + tagStr + ">"; } state.dump = tagStr + " " + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length2; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length2 = duplicatesIndexes.length; index < length2; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length2); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length2; if (object !== null && typeof object === "object") { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length2 = object.length; index < length2; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length2 = objectKeyList.length; index < length2; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump$1(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ "": value }, "", value); } if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; return ""; } var dump_1 = dump$1; var dumper = { dump: dump_1 }; function renamed(from, to) { return function() { throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default."); }; } var Type = type; var Schema = schema; var FAILSAFE_SCHEMA = failsafe; var JSON_SCHEMA = json; var CORE_SCHEMA = core; var DEFAULT_SCHEMA = _default; var load = loader.load; var loadAll = loader.loadAll; var dump = dumper.dump; var YAMLException = exception; var types = { binary, float, map, null: _null, pairs, set, timestamp, bool, int, merge, omap, seq, str }; var safeLoad = renamed("safeLoad", "load"); var safeLoadAll = renamed("safeLoadAll", "loadAll"); var safeDump = renamed("safeDump", "dump"); var jsYaml = { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump }; var js_yaml_default = jsYaml; // node_modules/.pnpm/zod-validation-error@3.4.0_zod@3.24.2/node_modules/zod-validation-error/dist/index.mjs function isZodErrorLike(err) { return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues); } var ValidationError = class extends Error { name; details; constructor(message, options) { super(message, options); this.name = "ZodValidationError"; this.details = getIssuesFromErrorOptions(options); } toString() { return this.message; } }; function getIssuesFromErrorOptions(options) { if (options) { const cause = options.cause; if (isZodErrorLike(cause)) { return cause.issues; } } return []; } function isNonEmptyArray(value) { return value.length !== 0; } var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u; function joinPath(path) { if (path.length === 1) { return path[0].toString(); } return path.reduce((acc, item) => { if (typeof item === "number") { return acc + "[" + item.toString() + "]"; } if (item.includes('"')) { return acc + '["' + escapeQuotes(item) + '"]'; } if (!identifierRegex.test(item)) { return acc + '["' + item + '"]'; } const separator = acc.length === 0 ? "" : "."; return acc + separator + item; }, ""); } function escapeQuotes(str2) { return str2.replace(/"/g, '\\"'); } var ISSUE_SEPARATOR = "; "; var MAX_ISSUES_IN_MESSAGE = 99; var PREFIX = "Validation error"; var PREFIX_SEPARATOR = ": "; var UNION_SEPARATOR = ", or "; function createMessageBuilder(props = {}) { const { issueSeparator = ISSUE_SEPARATOR, unionSeparator = UNION_SEPARATOR, prefixSeparator = PREFIX_SEPARATOR, prefix = PREFIX, includePath = true, maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE } = props; return (issues) => { const message = issues.slice(0, maxIssuesInMessage).map( (issue) => getMessageFromZodIssue({ issue, issueSeparator, unionSeparator, includePath }) ).join(issueSeparator); return prefixMessage(message, prefix, prefixSeparator); }; } function getMessageFromZodIssue(props) { const { issue, issueSeparator, unionSeparator, includePath } = props; if (issue.code === ZodIssueCode.invalid_union) { return issue.unionErrors.reduce((acc, zodError) => { const newIssues = zodError.issues.map( (issue2) => getMessageFromZodIssue({ issue: issue2, issueSeparator, unionSeparator, includePath }) ).join(issueSeparator); if (!acc.includes(newIssues)) { acc.push(newIssues); } return acc; }, []).join(unionSeparator); } if (issue.code === ZodIssueCode.invalid_arguments) { return [ issue.message, ...issue.argumentsError.issues.map( (issue2) => getMessageFromZodIssue({ issue: issue2, issueSeparator, unionSeparator, includePath }) ) ].join(issueSeparator); } if (issue.code === ZodIssueCode.invalid_return_type) { return [ issue.message, ...issue.returnTypeError.issues.map( (issue2) => getMessageFromZodIssue({ issue: issue2, issueSeparator, unionSeparator, includePath }) ) ].join(issueSeparator); } if (includePath && isNonEmptyArray(issue.path)) { if (issue.path.length === 1) { const identifier = issue.path[0]; if (typeof identifier === "number") { return `${issue.message} at index ${identifier}`; } } return `${issue.message} at "${joinPath(issue.path)}"`; } return issue.message; } function prefixMessage(message, prefix, prefixSeparator) { if (prefix !== null) { if (message.length > 0) { return [prefix, message].join(prefixSeparator); } return prefix; } if (message.length > 0) { return message; } return PREFIX; } function fromZodError(zodError, options = {}) { if (!isZodErrorLike(zodError)) { throw new TypeError( `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?` ); } return fromZodErrorWithoutRuntimeCheck(zodError, options); } function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) { const zodIssues = zodError.errors; let message; if (isNonEmptyArray(zodIssues)) { const messageBuilder = createMessageBuilderFromOptions2(options); message = messageBuilder(zodIssues); } else { message = zodError.message; } return new ValidationError(message, { cause: zodError }); } function createMessageBuilderFromOptions2(options) { if ("messageBuilder" in options) { return options.messageBuilder; } return createMessageBuilder(options); } var toValidationError = (options = {}) => (err) => { if (isZodErrorLike(err)) { return fromZodErrorWithoutRuntimeCheck(err, options); } if (err instanceof Error) { return new ValidationError(err.message, { cause: err }); } return new ValidationError("Unknown error"); }; function fromError(err, options = {}) { return toValidationError(options)(err); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/types.js var EOF = 0; var Ident = 1; var Function2 = 2; var AtKeyword = 3; var Hash = 4; var String2 = 5; var BadString = 6; var Url = 7; var BadUrl = 8; var Delim = 9; var Number2 = 10; var Percentage = 11; var Dimension = 12; var WhiteSpace = 13; var CDO = 14; var CDC = 15; var Colon = 16; var Semicolon = 17; var Comma = 18; var LeftSquareBracket = 19; var RightSquareBracket = 20; var LeftParenthesis = 21; var RightParenthesis = 22; var LeftCurlyBracket = 23; var RightCurlyBracket = 24; var Comment = 25; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/char-code-definitions.js var EOF2 = 0; function isDigit(code2) { return code2 >= 48 && code2 <= 57; } function isHexDigit(code2) { return isDigit(code2) || // 0 .. 9 code2 >= 65 && code2 <= 70 || // A .. F code2 >= 97 && code2 <= 102; } function isUppercaseLetter(code2) { return code2 >= 65 && code2 <= 90; } function isLowercaseLetter(code2) { return code2 >= 97 && code2 <= 122; } function isLetter(code2) { return isUppercaseLetter(code2) || isLowercaseLetter(code2); } function isNonAscii(code2) { return code2 >= 128; } function isNameStart(code2) { return isLetter(code2) || isNonAscii(code2) || code2 === 95; } function isName(code2) { return isNameStart(code2) || isDigit(code2) || code2 === 45; } function isNonPrintable(code2) { return code2 >= 0 && code2 <= 8 || code2 === 11 || code2 >= 14 && code2 <= 31 || code2 === 127; } function isNewline(code2) { return code2 === 10 || code2 === 13 || code2 === 12; } function isWhiteSpace(code2) { return isNewline(code2) || code2 === 32 || code2 === 9; } function isValidEscape(first, second) { if (first !== 92) { return false; } if (isNewline(second) || second === EOF2) { return false; } return true; } function isIdentifierStart(first, second, third) { if (first === 45) { return isNameStart(second) || second === 45 || isValidEscape(second, third); } if (isNameStart(first)) { return true; } if (first === 92) { return isValidEscape(first, second); } return false; } function isNumberStart(first, second, third) { if (first === 43 || first === 45) { if (isDigit(second)) { return 2; } return second === 46 && isDigit(third) ? 3 : 0; } if (first === 46) { return isDigit(second) ? 2 : 0; } if (isDigit(first)) { return 1; } return 0; } function isBOM(code2) { if (code2 === 65279) { return 1; } if (code2 === 65534) { return 1; } return 0; } var CATEGORY = new Array(128); var EofCategory = 128; var WhiteSpaceCategory = 130; var DigitCategory = 131; var NameStartCategory = 132; var NonPrintableCategory = 133; for (let i = 0; i < CATEGORY.length; i++) { CATEGORY[i] = isWhiteSpace(i) && WhiteSpaceCategory || isDigit(i) && DigitCategory || isNameStart(i) && NameStartCategory || isNonPrintable(i) && NonPrintableCategory || i || EofCategory; } function charCodeCategory(code2) { return code2 < 128 ? CATEGORY[code2] : NameStartCategory; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/utils.js function getCharCode(source, offset) { return offset < source.length ? source.charCodeAt(offset) : 0; } function getNewlineLength(source, offset, code2) { if (code2 === 13 && getCharCode(source, offset + 1) === 10) { return 2; } return 1; } function cmpChar(testStr, offset, referenceCode) { let code2 = testStr.charCodeAt(offset); if (isUppercaseLetter(code2)) { code2 = code2 | 32; } return code2 === referenceCode; } function cmpStr(testStr, start, end, referenceStr) { if (end - start !== referenceStr.length) { return false; } if (start < 0 || end > testStr.length) { return false; } for (let i = start; i < end; i++) { const referenceCode = referenceStr.charCodeAt(i - start); let testCode = testStr.charCodeAt(i); if (isUppercaseLetter(testCode)) { testCode = testCode | 32; } if (testCode !== referenceCode) { return false; } } return true; } function findWhiteSpaceStart(source, offset) { for (; offset >= 0; offset--) { if (!isWhiteSpace(source.charCodeAt(offset))) { break; } } return offset + 1; } function findWhiteSpaceEnd(source, offset) { for (; offset < source.length; offset++) { if (!isWhiteSpace(source.charCodeAt(offset))) { break; } } return offset; } function findDecimalNumberEnd(source, offset) { for (; offset < source.length; offset++) { if (!isDigit(source.charCodeAt(offset))) { break; } } return offset; } function consumeEscaped(source, offset) { offset += 2; if (isHexDigit(getCharCode(source, offset - 1))) { for (const maxOffset2 = Math.min(source.length, offset + 5); offset < maxOffset2; offset++) { if (!isHexDigit(getCharCode(source, offset))) { break; } } const code2 = getCharCode(source, offset); if (isWhiteSpace(code2)) { offset += getNewlineLength(source, offset, code2); } } return offset; } function consumeName(source, offset) { for (; offset < source.length; offset++) { const code2 = source.charCodeAt(offset); if (isName(code2)) { continue; } if (isValidEscape(code2, getCharCode(source, offset + 1))) { offset = consumeEscaped(source, offset) - 1; continue; } break; } return offset; } function consumeNumber(source, offset) { let code2 = source.charCodeAt(offset); if (code2 === 43 || code2 === 45) { code2 = source.charCodeAt(offset += 1); } if (isDigit(code2)) { offset = findDecimalNumberEnd(source, offset + 1); code2 = source.charCodeAt(offset); } if (code2 === 46 && isDigit(source.charCodeAt(offset + 1))) { offset += 2; offset = findDecimalNumberEnd(source, offset); } if (cmpChar( source, offset, 101 /* e */ )) { let sign = 0; code2 = source.charCodeAt(offset + 1); if (code2 === 45 || code2 === 43) { sign = 1; code2 = source.charCodeAt(offset + 2); } if (isDigit(code2)) { offset = findDecimalNumberEnd(source, offset + 1 + sign + 1); } } return offset; } function consumeBadUrlRemnants(source, offset) { for (; offset < source.length; offset++) { const code2 = source.charCodeAt(offset); if (code2 === 41) { offset++; break; } if (isValidEscape(code2, getCharCode(source, offset + 1))) { offset = consumeEscaped(source, offset); } } return offset; } function decodeEscaped(escaped) { if (escaped.length === 1 && !isHexDigit(escaped.charCodeAt(0))) { return escaped[0]; } let code2 = parseInt(escaped, 16); if (code2 === 0 || // If this number is zero, code2 >= 55296 && code2 <= 57343 || // or is for a surrogate, code2 > 1114111) { code2 = 65533; } return String.fromCodePoint(code2); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/names.js var names_default = [ "EOF-token", "ident-token", "function-token", "at-keyword-token", "hash-token", "string-token", "bad-string-token", "url-token", "bad-url-token", "delim-token", "number-token", "percentage-token", "dimension-token", "whitespace-token", "CDO-token", "CDC-token", "colon-token", "semicolon-token", "comma-token", "[-token", "]-token", "(-token", ")-token", "{-token", "}-token", "comment-token" ]; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/adopt-buffer.js var MIN_SIZE = 16 * 1024; function adoptBuffer(buffer = null, size) { if (buffer === null || buffer.length < size) { return new Uint32Array(Math.max(size + 1024, MIN_SIZE)); } return buffer; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/OffsetToLocation.js var N = 10; var F = 12; var R = 13; function computeLinesAndColumns(host) { const source = host.source; const sourceLength = source.length; const startOffset = source.length > 0 ? isBOM(source.charCodeAt(0)) : 0; const lines = adoptBuffer(host.lines, sourceLength); const columns = adoptBuffer(host.columns, sourceLength); let line = host.startLine; let column = host.startColumn; for (let i = startOffset; i < sourceLength; i++) { const code2 = source.charCodeAt(i); lines[i] = line; columns[i] = column++; if (code2 === N || code2 === R || code2 === F) { if (code2 === R && i + 1 < sourceLength && source.charCodeAt(i + 1) === N) { i++; lines[i] = line; columns[i] = column; } line++; column = 1; } } lines[sourceLength] = line; columns[sourceLength] = column; host.lines = lines; host.columns = columns; host.computed = true; } var OffsetToLocation = class { constructor(source, startOffset, startLine, startColumn) { this.setSource(source, startOffset, startLine, startColumn); this.lines = null; this.columns = null; } setSource(source = "", startOffset = 0, startLine = 1, startColumn = 1) { this.source = source; this.startOffset = startOffset; this.startLine = startLine; this.startColumn = startColumn; this.computed = false; } getLocation(offset, filename) { if (!this.computed) { computeLinesAndColumns(this); } return { source: filename, offset: this.startOffset + offset, line: this.lines[offset], column: this.columns[offset] }; } getLocationRange(start, end, filename) { if (!this.computed) { computeLinesAndColumns(this); } return { source: filename, start: { offset: this.startOffset + start, line: this.lines[start], column: this.columns[start] }, end: { offset: this.startOffset + end, line: this.lines[end], column: this.columns[end] } }; } }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/TokenStream.js var OFFSET_MASK = 16777215; var TYPE_SHIFT = 24; var balancePair = new Uint8Array(32); balancePair[Function2] = RightParenthesis; balancePair[LeftParenthesis] = RightParenthesis; balancePair[LeftSquareBracket] = RightSquareBracket; balancePair[LeftCurlyBracket] = RightCurlyBracket; function isBlockOpenerToken(tokenType2) { return balancePair[tokenType2] !== 0; } var TokenStream = class { constructor(source, tokenize3) { this.setSource(source, tokenize3); } reset() { this.eof = false; this.tokenIndex = -1; this.tokenType = 0; this.tokenStart = this.firstCharOffset; this.tokenEnd = this.firstCharOffset; } setSource(source = "", tokenize3 = () => { }) { source = String(source || ""); const sourceLength = source.length; const offsetAndType = adoptBuffer(this.offsetAndType, source.length + 1); const balance = adoptBuffer(this.balance, source.length + 1); let tokenCount = 0; let firstCharOffset = -1; let balanceCloseType = 0; let balanceStart = source.length; this.offsetAndType = null; this.balance = null; balance.fill(0); tokenize3(source, (type2, start, end) => { const index = tokenCount++; offsetAndType[index] = type2 << TYPE_SHIFT | end; if (firstCharOffset === -1) { firstCharOffset = start; } balance[index] = balanceStart; if (type2 === balanceCloseType) { const prevBalanceStart = balance[balanceStart]; balance[balanceStart] = index; balanceStart = prevBalanceStart; balanceCloseType = balancePair[offsetAndType[prevBalanceStart] >> TYPE_SHIFT]; } else if (isBlockOpenerToken(type2)) { balanceStart = index; balanceCloseType = balancePair[type2]; } }); offsetAndType[tokenCount] = EOF << TYPE_SHIFT | sourceLength; balance[tokenCount] = tokenCount; for (let i = 0; i < tokenCount; i++) { const balanceStart2 = balance[i]; if (balanceStart2 <= i) { const balanceEnd = balance[balanceStart2]; if (balanceEnd !== i) { balance[i] = balanceEnd; } } else if (balanceStart2 > tokenCount) { balance[i] = tokenCount; } } this.source = source; this.firstCharOffset = firstCharOffset === -1 ? 0 : firstCharOffset; this.tokenCount = tokenCount; this.offsetAndType = offsetAndType; this.balance = balance; this.reset(); this.next(); } lookupType(offset) { offset += this.tokenIndex; if (offset < this.tokenCount) { return this.offsetAndType[offset] >> TYPE_SHIFT; } return EOF; } lookupTypeNonSC(idx) { for (let offset = this.tokenIndex; offset < this.tokenCount; offset++) { const tokenType2 = this.offsetAndType[offset] >> TYPE_SHIFT; if (tokenType2 !== WhiteSpace && tokenType2 !== Comment) { if (idx-- === 0) { return tokenType2; } } } return EOF; } lookupOffset(offset) { offset += this.tokenIndex; if (offset < this.tokenCount) { return this.offsetAndType[offset - 1] & OFFSET_MASK; } return this.source.length; } lookupOffsetNonSC(idx) { for (let offset = this.tokenIndex; offset < this.tokenCount; offset++) { const tokenType2 = this.offsetAndType[offset] >> TYPE_SHIFT; if (tokenType2 !== WhiteSpace && tokenType2 !== Comment) { if (idx-- === 0) { return offset - this.tokenIndex; } } } return EOF; } lookupValue(offset, referenceStr) { offset += this.tokenIndex; if (offset < this.tokenCount) { return cmpStr( this.source, this.offsetAndType[offset - 1] & OFFSET_MASK, this.offsetAndType[offset] & OFFSET_MASK, referenceStr ); } return false; } getTokenStart(tokenIndex) { if (tokenIndex === this.tokenIndex) { return this.tokenStart; } if (tokenIndex > 0) { return tokenIndex < this.tokenCount ? this.offsetAndType[tokenIndex - 1] & OFFSET_MASK : this.offsetAndType[this.tokenCount] & OFFSET_MASK; } return this.firstCharOffset; } substrToCursor(start) { return this.source.substring(start, this.tokenStart); } isBalanceEdge(pos) { return this.balance[this.tokenIndex] < pos; } isDelim(code2, offset) { if (offset) { return this.lookupType(offset) === Delim && this.source.charCodeAt(this.lookupOffset(offset)) === code2; } return this.tokenType === Delim && this.source.charCodeAt(this.tokenStart) === code2; } skip(tokenCount) { let next = this.tokenIndex + tokenCount; if (next < this.tokenCount) { this.tokenIndex = next; this.tokenStart = this.offsetAndType[next - 1] & OFFSET_MASK; next = this.offsetAndType[next]; this.tokenType = next >> TYPE_SHIFT; this.tokenEnd = next & OFFSET_MASK; } else { this.tokenIndex = this.tokenCount; this.next(); } } next() { let next = this.tokenIndex + 1; if (next < this.tokenCount) { this.tokenIndex = next; this.tokenStart = this.tokenEnd; next = this.offsetAndType[next]; this.tokenType = next >> TYPE_SHIFT; this.tokenEnd = next & OFFSET_MASK; } else { this.eof = true; this.tokenIndex = this.tokenCount; this.tokenType = EOF; this.tokenStart = this.tokenEnd = this.source.length; } } skipSC() { while (this.tokenType === WhiteSpace || this.tokenType === Comment) { this.next(); } } skipUntilBalanced(startToken, stopConsume) { let cursor = startToken; let balanceEnd = 0; let offset = 0; loop: for (; cursor < this.tokenCount; cursor++) { balanceEnd = this.balance[cursor]; if (balanceEnd < startToken) { break loop; } offset = cursor > 0 ? this.offsetAndType[cursor - 1] & OFFSET_MASK : this.firstCharOffset; switch (stopConsume(this.source.charCodeAt(offset))) { case 1: break loop; case 2: cursor++; break loop; default: if (isBlockOpenerToken(this.offsetAndType[cursor] >> TYPE_SHIFT)) { cursor = balanceEnd; } } } this.skip(cursor - this.tokenIndex); } forEachToken(fn) { for (let i = 0, offset = this.firstCharOffset; i < this.tokenCount; i++) { const start = offset; const item = this.offsetAndType[i]; const end = item & OFFSET_MASK; const type2 = item >> TYPE_SHIFT; offset = end; fn(type2, start, end, i); } } dump() { const tokens = new Array(this.tokenCount); this.forEachToken((type2, start, end, index) => { tokens[index] = { idx: index, type: names_default[type2], chunk: this.source.substring(start, end), balance: this.balance[index] }; }); return tokens; } }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/tokenizer/index.js function tokenize(source, onToken) { function getCharCode2(offset2) { return offset2 < sourceLength ? source.charCodeAt(offset2) : 0; } function consumeNumericToken() { offset = consumeNumber(source, offset); if (isIdentifierStart(getCharCode2(offset), getCharCode2(offset + 1), getCharCode2(offset + 2))) { type2 = Dimension; offset = consumeName(source, offset); return; } if (getCharCode2(offset) === 37) { type2 = Percentage; offset++; return; } type2 = Number2; } function consumeIdentLikeToken() { const nameStartOffset = offset; offset = consumeName(source, offset); if (cmpStr(source, nameStartOffset, offset, "url") && getCharCode2(offset) === 40) { offset = findWhiteSpaceEnd(source, offset + 1); if (getCharCode2(offset) === 34 || getCharCode2(offset) === 39) { type2 = Function2; offset = nameStartOffset + 4; return; } consumeUrlToken(); return; } if (getCharCode2(offset) === 40) { type2 = Function2; offset++; return; } type2 = Ident; } function consumeStringToken(endingCodePoint) { if (!endingCodePoint) { endingCodePoint = getCharCode2(offset++); } type2 = String2; for (; offset < source.length; offset++) { const code2 = source.charCodeAt(offset); switch (charCodeCategory(code2)) { // ending code point case endingCodePoint: offset++; return; // EOF // case EofCategory: // This is a parse error. Return the . // return; // newline case WhiteSpaceCategory: if (isNewline(code2)) { offset += getNewlineLength(source, offset, code2); type2 = BadString; return; } break; // U+005C REVERSE SOLIDUS (\) case 92: if (offset === source.length - 1) { break; } const nextCode = getCharCode2(offset + 1); if (isNewline(nextCode)) { offset += getNewlineLength(source, offset + 1, nextCode); } else if (isValidEscape(code2, nextCode)) { offset = consumeEscaped(source, offset) - 1; } break; } } } function consumeUrlToken() { type2 = Url; offset = findWhiteSpaceEnd(source, offset); for (; offset < source.length; offset++) { const code2 = source.charCodeAt(offset); switch (charCodeCategory(code2)) { // U+0029 RIGHT PARENTHESIS ()) case 41: offset++; return; // EOF // case EofCategory: // This is a parse error. Return the . // return; // whitespace case WhiteSpaceCategory: offset = findWhiteSpaceEnd(source, offset); if (getCharCode2(offset) === 41 || offset >= source.length) { if (offset < source.length) { offset++; } return; } offset = consumeBadUrlRemnants(source, offset); type2 = BadUrl; return; // U+0022 QUOTATION MARK (") // U+0027 APOSTROPHE (') // U+0028 LEFT PARENTHESIS (() // non-printable code point case 34: case 39: case 40: case NonPrintableCategory: offset = consumeBadUrlRemnants(source, offset); type2 = BadUrl; return; // U+005C REVERSE SOLIDUS (\) case 92: if (isValidEscape(code2, getCharCode2(offset + 1))) { offset = consumeEscaped(source, offset) - 1; break; } offset = consumeBadUrlRemnants(source, offset); type2 = BadUrl; return; } } } source = String(source || ""); const sourceLength = source.length; let start = isBOM(getCharCode2(0)); let offset = start; let type2; while (offset < sourceLength) { const code2 = source.charCodeAt(offset); switch (charCodeCategory(code2)) { // whitespace case WhiteSpaceCategory: type2 = WhiteSpace; offset = findWhiteSpaceEnd(source, offset + 1); break; // U+0022 QUOTATION MARK (") case 34: consumeStringToken(); break; // U+0023 NUMBER SIGN (#) case 35: if (isName(getCharCode2(offset + 1)) || isValidEscape(getCharCode2(offset + 1), getCharCode2(offset + 2))) { type2 = Hash; offset = consumeName(source, offset + 1); } else { type2 = Delim; offset++; } break; // U+0027 APOSTROPHE (') case 39: consumeStringToken(); break; // U+0028 LEFT PARENTHESIS (() case 40: type2 = LeftParenthesis; offset++; break; // U+0029 RIGHT PARENTHESIS ()) case 41: type2 = RightParenthesis; offset++; break; // U+002B PLUS SIGN (+) case 43: if (isNumberStart(code2, getCharCode2(offset + 1), getCharCode2(offset + 2))) { consumeNumericToken(); } else { type2 = Delim; offset++; } break; // U+002C COMMA (,) case 44: type2 = Comma; offset++; break; // U+002D HYPHEN-MINUS (-) case 45: if (isNumberStart(code2, getCharCode2(offset + 1), getCharCode2(offset + 2))) { consumeNumericToken(); } else { if (getCharCode2(offset + 1) === 45 && getCharCode2(offset + 2) === 62) { type2 = CDC; offset = offset + 3; } else { if (isIdentifierStart(code2, getCharCode2(offset + 1), getCharCode2(offset + 2))) { consumeIdentLikeToken(); } else { type2 = Delim; offset++; } } } break; // U+002E FULL STOP (.) case 46: if (isNumberStart(code2, getCharCode2(offset + 1), getCharCode2(offset + 2))) { consumeNumericToken(); } else { type2 = Delim; offset++; } break; // U+002F SOLIDUS (/) case 47: if (getCharCode2(offset + 1) === 42) { type2 = Comment; offset = source.indexOf("*/", offset + 2); offset = offset === -1 ? source.length : offset + 2; } else { type2 = Delim; offset++; } break; // U+003A COLON (:) case 58: type2 = Colon; offset++; break; // U+003B SEMICOLON (;) case 59: type2 = Semicolon; offset++; break; // U+003C LESS-THAN SIGN (<) case 60: if (getCharCode2(offset + 1) === 33 && getCharCode2(offset + 2) === 45 && getCharCode2(offset + 3) === 45) { type2 = CDO; offset = offset + 4; } else { type2 = Delim; offset++; } break; // U+0040 COMMERCIAL AT (@) case 64: if (isIdentifierStart(getCharCode2(offset + 1), getCharCode2(offset + 2), getCharCode2(offset + 3))) { type2 = AtKeyword; offset = consumeName(source, offset + 1); } else { type2 = Delim; offset++; } break; // U+005B LEFT SQUARE BRACKET ([) case 91: type2 = LeftSquareBracket; offset++; break; // U+005C REVERSE SOLIDUS (\) case 92: if (isValidEscape(code2, getCharCode2(offset + 1))) { consumeIdentLikeToken(); } else { type2 = Delim; offset++; } break; // U+005D RIGHT SQUARE BRACKET (]) case 93: type2 = RightSquareBracket; offset++; break; // U+007B LEFT CURLY BRACKET ({) case 123: type2 = LeftCurlyBracket; offset++; break; // U+007D RIGHT CURLY BRACKET (}) case 125: type2 = RightCurlyBracket; offset++; break; // digit case DigitCategory: consumeNumericToken(); break; // name-start code point case NameStartCategory: consumeIdentLikeToken(); break; // EOF // case EofCategory: // Return an . // break; // anything else default: type2 = Delim; offset++; } onToken(type2, start, start = offset); } } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/utils/List.js var releasedCursors = null; var List = class _List { static createItem(data) { return { prev: null, next: null, data }; } constructor() { this.head = null; this.tail = null; this.cursor = null; } createItem(data) { return _List.createItem(data); } // cursor helpers allocateCursor(prev, next) { let cursor; if (releasedCursors !== null) { cursor = releasedCursors; releasedCursors = releasedCursors.cursor; cursor.prev = prev; cursor.next = next; cursor.cursor = this.cursor; } else { cursor = { prev, next, cursor: this.cursor }; } this.cursor = cursor; return cursor; } releaseCursor() { const { cursor } = this; this.cursor = cursor.cursor; cursor.prev = null; cursor.next = null; cursor.cursor = releasedCursors; releasedCursors = cursor; } updateCursors(prevOld, prevNew, nextOld, nextNew) { let { cursor } = this; while (cursor !== null) { if (cursor.prev === prevOld) { cursor.prev = prevNew; } if (cursor.next === nextOld) { cursor.next = nextNew; } cursor = cursor.cursor; } } *[Symbol.iterator]() { for (let cursor = this.head; cursor !== null; cursor = cursor.next) { yield cursor.data; } } // getters get size() { let size = 0; for (let cursor = this.head; cursor !== null; cursor = cursor.next) { size++; } return size; } get isEmpty() { return this.head === null; } get first() { return this.head && this.head.data; } get last() { return this.tail && this.tail.data; } // convertors fromArray(array) { let cursor = null; this.head = null; for (let data of array) { const item = _List.createItem(data); if (cursor !== null) { cursor.next = item; } else { this.head = item; } item.prev = cursor; cursor = item; } this.tail = cursor; return this; } toArray() { return [...this]; } toJSON() { return [...this]; } // array-like methods forEach(fn, thisArg = this) { const cursor = this.allocateCursor(null, this.head); while (cursor.next !== null) { const item = cursor.next; cursor.next = item.next; fn.call(thisArg, item.data, item, this); } this.releaseCursor(); } forEachRight(fn, thisArg = this) { const cursor = this.allocateCursor(this.tail, null); while (cursor.prev !== null) { const item = cursor.prev; cursor.prev = item.prev; fn.call(thisArg, item.data, item, this); } this.releaseCursor(); } reduce(fn, initialValue, thisArg = this) { let cursor = this.allocateCursor(null, this.head); let acc = initialValue; let item; while (cursor.next !== null) { item = cursor.next; cursor.next = item.next; acc = fn.call(thisArg, acc, item.data, item, this); } this.releaseCursor(); return acc; } reduceRight(fn, initialValue, thisArg = this) { let cursor = this.allocateCursor(this.tail, null); let acc = initialValue; let item; while (cursor.prev !== null) { item = cursor.prev; cursor.prev = item.prev; acc = fn.call(thisArg, acc, item.data, item, this); } this.releaseCursor(); return acc; } some(fn, thisArg = this) { for (let cursor = this.head; cursor !== null; cursor = cursor.next) { if (fn.call(thisArg, cursor.data, cursor, this)) { return true; } } return false; } map(fn, thisArg = this) { const result = new _List(); for (let cursor = this.head; cursor !== null; cursor = cursor.next) { result.appendData(fn.call(thisArg, cursor.data, cursor, this)); } return result; } filter(fn, thisArg = this) { const result = new _List(); for (let cursor = this.head; cursor !== null; cursor = cursor.next) { if (fn.call(thisArg, cursor.data, cursor, this)) { result.appendData(cursor.data); } } return result; } nextUntil(start, fn, thisArg = this) { if (start === null) { return; } const cursor = this.allocateCursor(null, start); while (cursor.next !== null) { const item = cursor.next; cursor.next = item.next; if (fn.call(thisArg, item.data, item, this)) { break; } } this.releaseCursor(); } prevUntil(start, fn, thisArg = this) { if (start === null) { return; } const cursor = this.allocateCursor(start, null); while (cursor.prev !== null) { const item = cursor.prev; cursor.prev = item.prev; if (fn.call(thisArg, item.data, item, this)) { break; } } this.releaseCursor(); } // mutation clear() { this.head = null; this.tail = null; } copy() { const result = new _List(); for (let data of this) { result.appendData(data); } return result; } prepend(item) { this.updateCursors(null, item, this.head, item); if (this.head !== null) { this.head.prev = item; item.next = this.head; } else { this.tail = item; } this.head = item; return this; } prependData(data) { return this.prepend(_List.createItem(data)); } append(item) { return this.insert(item); } appendData(data) { return this.insert(_List.createItem(data)); } insert(item, before = null) { if (before !== null) { this.updateCursors(before.prev, item, before, item); if (before.prev === null) { if (this.head !== before) { throw new Error("before doesn't belong to list"); } this.head = item; before.prev = item; item.next = before; this.updateCursors(null, item); } else { before.prev.next = item; item.prev = before.prev; before.prev = item; item.next = before; } } else { this.updateCursors(this.tail, item, null, item); if (this.tail !== null) { this.tail.next = item; item.prev = this.tail; } else { this.head = item; } this.tail = item; } return this; } insertData(data, before) { return this.insert(_List.createItem(data), before); } remove(item) { this.updateCursors(item, item.prev, item, item.next); if (item.prev !== null) { item.prev.next = item.next; } else { if (this.head !== item) { throw new Error("item doesn't belong to list"); } this.head = item.next; } if (item.next !== null) { item.next.prev = item.prev; } else { if (this.tail !== item) { throw new Error("item doesn't belong to list"); } this.tail = item.prev; } item.prev = null; item.next = null; return item; } push(data) { this.insert(_List.createItem(data)); } pop() { return this.tail !== null ? this.remove(this.tail) : null; } unshift(data) { this.prepend(_List.createItem(data)); } shift() { return this.head !== null ? this.remove(this.head) : null; } prependList(list) { return this.insertList(list, this.head); } appendList(list) { return this.insertList(list); } insertList(list, before) { if (list.head === null) { return this; } if (before !== void 0 && before !== null) { this.updateCursors(before.prev, list.tail, before, list.head); if (before.prev !== null) { before.prev.next = list.head; list.head.prev = before.prev; } else { this.head = list.head; } before.prev = list.tail; list.tail.next = before; } else { this.updateCursors(this.tail, list.tail, null, list.head); if (this.tail !== null) { this.tail.next = list.head; list.head.prev = this.tail; } else { this.head = list.head; } this.tail = list.tail; } list.head = null; list.tail = null; return this; } replace(oldItem, newItemOrList) { if ("head" in newItemOrList) { this.insertList(newItemOrList, oldItem); } else { this.insert(newItemOrList, oldItem); } this.remove(oldItem); } }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/utils/create-custom-error.js function createCustomError(name51, message) { const error = Object.create(SyntaxError.prototype); const errorStack = new Error(); return Object.assign(error, { name: name51, message, get stack() { return (errorStack.stack || "").replace(/^(.+\n){1,3}/, `${name51}: ${message} `); } }); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/parser/SyntaxError.js var MAX_LINE_LENGTH = 100; var OFFSET_CORRECTION = 60; var TAB_REPLACEMENT = " "; function sourceFragment({ source, line, column, baseLine, baseColumn }, extraLines) { function processLines(start, end) { return lines.slice(start, end).map( (line2, idx) => String(start + idx + 1).padStart(maxNumLength) + " |" + line2 ).join("\n"); } const prelines = "\n".repeat(Math.max(baseLine - 1, 0)); const precolumns = " ".repeat(Math.max(baseColumn - 1, 0)); const lines = (prelines + precolumns + source).split(/\r\n?|\n|\f/); const startLine = Math.max(1, line - extraLines) - 1; const endLine = Math.min(line + extraLines, lines.length + 1); const maxNumLength = Math.max(4, String(endLine).length) + 1; let cutLeft = 0; column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length; if (column > MAX_LINE_LENGTH) { cutLeft = column - OFFSET_CORRECTION + 3; column = OFFSET_CORRECTION - 2; } for (let i = startLine; i <= endLine; i++) { if (i >= 0 && i < lines.length) { lines[i] = lines[i].replace(/\t/g, TAB_REPLACEMENT); lines[i] = (cutLeft > 0 && lines[i].length > cutLeft ? "\u2026" : "") + lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) + (lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? "\u2026" : ""); } } return [ processLines(startLine, line), new Array(column + maxNumLength + 2).join("-") + "^", processLines(line, endLine) ].filter(Boolean).join("\n").replace(/^(\s+\d+\s+\|\n)+/, "").replace(/\n(\s+\d+\s+\|)+$/, ""); } function SyntaxError2(message, source, offset, line, column, baseLine = 1, baseColumn = 1) { const error = Object.assign(createCustomError("SyntaxError", message), { source, offset, line, column, sourceFragment(extraLines) { return sourceFragment({ source, line, column, baseLine, baseColumn }, isNaN(extraLines) ? 0 : extraLines); }, get formattedMessage() { return `Parse error: ${message} ` + sourceFragment({ source, line, column, baseLine, baseColumn }, 2); } }); return error; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/parser/sequence.js function readSequence(recognizer) { const children = this.createList(); let space = false; const context = { recognizer }; while (!this.eof) { switch (this.tokenType) { case Comment: this.next(); continue; case WhiteSpace: space = true; this.next(); continue; } let child = recognizer.getNode.call(this, context); if (child === void 0) { break; } if (space) { if (recognizer.onWhiteSpace) { recognizer.onWhiteSpace.call(this, child, children, context); } space = false; } children.push(child); } if (space && recognizer.onWhiteSpace) { recognizer.onWhiteSpace.call(this, null, children, context); } return children; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/parser/create.js var NOOP = () => { }; var EXCLAMATIONMARK = 33; var NUMBERSIGN = 35; var SEMICOLON = 59; var LEFTCURLYBRACKET = 123; var NULL = 0; function createParseContext(name51) { return function() { return this[name51](); }; } function fetchParseValues(dict) { const result = /* @__PURE__ */ Object.create(null); for (const name51 of Object.keys(dict)) { const item = dict[name51]; const fn = item.parse || item; if (fn) { result[name51] = fn; } } return result; } function processConfig(config) { const parseConfig = { context: /* @__PURE__ */ Object.create(null), features: Object.assign(/* @__PURE__ */ Object.create(null), config.features), scope: Object.assign(/* @__PURE__ */ Object.create(null), config.scope), atrule: fetchParseValues(config.atrule), pseudo: fetchParseValues(config.pseudo), node: fetchParseValues(config.node) }; for (const [name51, context] of Object.entries(config.parseContext)) { switch (typeof context) { case "function": parseConfig.context[name51] = context; break; case "string": parseConfig.context[name51] = createParseContext(context); break; } } return { config: parseConfig, ...parseConfig, ...parseConfig.node }; } function createParser(config) { let source = ""; let filename = ""; let needPositions = false; let onParseError = NOOP; let onParseErrorThrow = false; const locationMap = new OffsetToLocation(); const parser4 = Object.assign(new TokenStream(), processConfig(config || {}), { parseAtrulePrelude: true, parseRulePrelude: true, parseValue: true, parseCustomProperty: false, readSequence, consumeUntilBalanceEnd: () => 0, consumeUntilLeftCurlyBracket(code2) { return code2 === LEFTCURLYBRACKET ? 1 : 0; }, consumeUntilLeftCurlyBracketOrSemicolon(code2) { return code2 === LEFTCURLYBRACKET || code2 === SEMICOLON ? 1 : 0; }, consumeUntilExclamationMarkOrSemicolon(code2) { return code2 === EXCLAMATIONMARK || code2 === SEMICOLON ? 1 : 0; }, consumeUntilSemicolonIncluded(code2) { return code2 === SEMICOLON ? 2 : 0; }, createList() { return new List(); }, createSingleNodeList(node) { return new List().appendData(node); }, getFirstListNode(list) { return list && list.first; }, getLastListNode(list) { return list && list.last; }, parseWithFallback(consumer, fallback) { const startIndex = this.tokenIndex; try { return consumer.call(this); } catch (e) { if (onParseErrorThrow) { throw e; } this.skip(startIndex - this.tokenIndex); const fallbackNode = fallback.call(this); onParseErrorThrow = true; onParseError(e, fallbackNode); onParseErrorThrow = false; return fallbackNode; } }, lookupNonWSType(offset) { let type2; do { type2 = this.lookupType(offset++); if (type2 !== WhiteSpace && type2 !== Comment) { return type2; } } while (type2 !== NULL); return NULL; }, charCodeAt(offset) { return offset >= 0 && offset < source.length ? source.charCodeAt(offset) : 0; }, substring(offsetStart, offsetEnd) { return source.substring(offsetStart, offsetEnd); }, substrToCursor(start) { return this.source.substring(start, this.tokenStart); }, cmpChar(offset, charCode) { return cmpChar(source, offset, charCode); }, cmpStr(offsetStart, offsetEnd, str2) { return cmpStr(source, offsetStart, offsetEnd, str2); }, consume(tokenType2) { const start = this.tokenStart; this.eat(tokenType2); return this.substrToCursor(start); }, consumeFunctionName() { const name51 = source.substring(this.tokenStart, this.tokenEnd - 1); this.eat(Function2); return name51; }, consumeNumber(type2) { const number3 = source.substring(this.tokenStart, consumeNumber(source, this.tokenStart)); this.eat(type2); return number3; }, eat(tokenType2) { if (this.tokenType !== tokenType2) { const tokenName = names_default[tokenType2].slice(0, -6).replace(/-/g, " ").replace(/^./, (m) => m.toUpperCase()); let message = `${/[[\](){}]/.test(tokenName) ? `"${tokenName}"` : tokenName} is expected`; let offset = this.tokenStart; switch (tokenType2) { case Ident: if (this.tokenType === Function2 || this.tokenType === Url) { offset = this.tokenEnd - 1; message = "Identifier is expected but function found"; } else { message = "Identifier is expected"; } break; case Hash: if (this.isDelim(NUMBERSIGN)) { this.next(); offset++; message = "Name is expected"; } break; case Percentage: if (this.tokenType === Number2) { offset = this.tokenEnd; message = "Percent sign is expected"; } break; } this.error(message, offset); } this.next(); }, eatIdent(name51) { if (this.tokenType !== Ident || this.lookupValue(0, name51) === false) { this.error(`Identifier "${name51}" is expected`); } this.next(); }, eatDelim(code2) { if (!this.isDelim(code2)) { this.error(`Delim "${String.fromCharCode(code2)}" is expected`); } this.next(); }, getLocation(start, end) { if (needPositions) { return locationMap.getLocationRange( start, end, filename ); } return null; }, getLocationFromList(list) { if (needPositions) { const head = this.getFirstListNode(list); const tail = this.getLastListNode(list); return locationMap.getLocationRange( head !== null ? head.loc.start.offset - locationMap.startOffset : this.tokenStart, tail !== null ? tail.loc.end.offset - locationMap.startOffset : this.tokenStart, filename ); } return null; }, error(message, offset) { const location = typeof offset !== "undefined" && offset < source.length ? locationMap.getLocation(offset) : this.eof ? locationMap.getLocation(findWhiteSpaceStart(source, source.length - 1)) : locationMap.getLocation(this.tokenStart); throw new SyntaxError2( message || "Unexpected input", source, location.offset, location.line, location.column, locationMap.startLine, locationMap.startColumn ); } }); const parse53 = function(source_, options) { source = source_; options = options || {}; parser4.setSource(source, tokenize); locationMap.setSource( source, options.offset, options.line, options.column ); filename = options.filename || ""; needPositions = Boolean(options.positions); onParseError = typeof options.onParseError === "function" ? options.onParseError : NOOP; onParseErrorThrow = false; parser4.parseAtrulePrelude = "parseAtrulePrelude" in options ? Boolean(options.parseAtrulePrelude) : true; parser4.parseRulePrelude = "parseRulePrelude" in options ? Boolean(options.parseRulePrelude) : true; parser4.parseValue = "parseValue" in options ? Boolean(options.parseValue) : true; parser4.parseCustomProperty = "parseCustomProperty" in options ? Boolean(options.parseCustomProperty) : false; const { context = "default", onComment } = options; if (context in parser4.context === false) { throw new Error("Unknown context `" + context + "`"); } if (typeof onComment === "function") { parser4.forEachToken((type2, start, end) => { if (type2 === Comment) { const loc = parser4.getLocation(start, end); const value = cmpStr(source, end - 2, end, "*/") ? source.slice(start + 2, end - 2) : source.slice(start + 2, end); onComment(value, loc); } }); } const ast = parser4.context[context].call(parser4, options); if (!parser4.eof) { parser4.error(); } return ast; }; return Object.assign(parse53, { SyntaxError: SyntaxError2, config: parser4.config }); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/generator/sourceMap.js var import_source_map_generator = __toESM(require_source_map_generator(), 1); var trackNodes = /* @__PURE__ */ new Set(["Atrule", "Selector", "Declaration"]); function generateSourceMap(handlers2) { const map2 = new import_source_map_generator.SourceMapGenerator(); const generated = { line: 1, column: 0 }; const original = { line: 0, // should be zero to add first mapping column: 0 }; const activatedGenerated = { line: 1, column: 0 }; const activatedMapping = { generated: activatedGenerated }; let line = 1; let column = 0; let sourceMappingActive = false; const origHandlersNode = handlers2.node; handlers2.node = function(node) { if (node.loc && node.loc.start && trackNodes.has(node.type)) { const nodeLine = node.loc.start.line; const nodeColumn = node.loc.start.column - 1; if (original.line !== nodeLine || original.column !== nodeColumn) { original.line = nodeLine; original.column = nodeColumn; generated.line = line; generated.column = column; if (sourceMappingActive) { sourceMappingActive = false; if (generated.line !== activatedGenerated.line || generated.column !== activatedGenerated.column) { map2.addMapping(activatedMapping); } } sourceMappingActive = true; map2.addMapping({ source: node.loc.source, original, generated }); } } origHandlersNode.call(this, node); if (sourceMappingActive && trackNodes.has(node.type)) { activatedGenerated.line = line; activatedGenerated.column = column; } }; const origHandlersEmit = handlers2.emit; handlers2.emit = function(value, type2, auto) { for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) === 10) { line++; column = 0; } else { column++; } } origHandlersEmit(value, type2, auto); }; const origHandlersResult = handlers2.result; handlers2.result = function() { if (sourceMappingActive) { map2.addMapping(activatedMapping); } return { css: origHandlersResult(), map: map2 }; }; return handlers2; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/generator/token-before.js var token_before_exports = {}; __export(token_before_exports, { safe: () => safe, spec: () => spec }); var PLUSSIGN = 43; var HYPHENMINUS = 45; var code = (type2, value) => { if (type2 === Delim) { type2 = value; } if (typeof type2 === "string") { const charCode = type2.charCodeAt(0); return charCode > 127 ? 32768 : charCode << 8; } return type2; }; var specPairs = [ [Ident, Ident], [Ident, Function2], [Ident, Url], [Ident, BadUrl], [Ident, "-"], [Ident, Number2], [Ident, Percentage], [Ident, Dimension], [Ident, CDC], [Ident, LeftParenthesis], [AtKeyword, Ident], [AtKeyword, Function2], [AtKeyword, Url], [AtKeyword, BadUrl], [AtKeyword, "-"], [AtKeyword, Number2], [AtKeyword, Percentage], [AtKeyword, Dimension], [AtKeyword, CDC], [Hash, Ident], [Hash, Function2], [Hash, Url], [Hash, BadUrl], [Hash, "-"], [Hash, Number2], [Hash, Percentage], [Hash, Dimension], [Hash, CDC], [Dimension, Ident], [Dimension, Function2], [Dimension, Url], [Dimension, BadUrl], [Dimension, "-"], [Dimension, Number2], [Dimension, Percentage], [Dimension, Dimension], [Dimension, CDC], ["#", Ident], ["#", Function2], ["#", Url], ["#", BadUrl], ["#", "-"], ["#", Number2], ["#", Percentage], ["#", Dimension], ["#", CDC], // https://github.com/w3c/csswg-drafts/pull/6874 ["-", Ident], ["-", Function2], ["-", Url], ["-", BadUrl], ["-", "-"], ["-", Number2], ["-", Percentage], ["-", Dimension], ["-", CDC], // https://github.com/w3c/csswg-drafts/pull/6874 [Number2, Ident], [Number2, Function2], [Number2, Url], [Number2, BadUrl], [Number2, Number2], [Number2, Percentage], [Number2, Dimension], [Number2, "%"], [Number2, CDC], // https://github.com/w3c/csswg-drafts/pull/6874 ["@", Ident], ["@", Function2], ["@", Url], ["@", BadUrl], ["@", "-"], ["@", CDC], // https://github.com/w3c/csswg-drafts/pull/6874 [".", Number2], [".", Percentage], [".", Dimension], ["+", Number2], ["+", Percentage], ["+", Dimension], ["/", "*"] ]; var safePairs = specPairs.concat([ [Ident, Hash], [Dimension, Hash], [Hash, Hash], [AtKeyword, LeftParenthesis], [AtKeyword, String2], [AtKeyword, Colon], [Percentage, Percentage], [Percentage, Dimension], [Percentage, Function2], [Percentage, "-"], [RightParenthesis, Ident], [RightParenthesis, Function2], [RightParenthesis, Percentage], [RightParenthesis, Dimension], [RightParenthesis, Hash], [RightParenthesis, "-"] ]); function createMap(pairs2) { const isWhiteSpaceRequired = new Set( pairs2.map(([prev, next]) => code(prev) << 16 | code(next)) ); return function(prevCode, type2, value) { const nextCode = code(type2, value); const nextCharCode = value.charCodeAt(0); const emitWs = nextCharCode === HYPHENMINUS && type2 !== Ident && type2 !== Function2 && type2 !== CDC || nextCharCode === PLUSSIGN ? isWhiteSpaceRequired.has(prevCode << 16 | nextCharCode << 8) : isWhiteSpaceRequired.has(prevCode << 16 | nextCode); if (emitWs) { this.emit(" ", WhiteSpace, true); } return nextCode; }; } var spec = createMap(specPairs); var safe = createMap(safePairs); // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/generator/create.js var REVERSESOLIDUS = 92; function processChildren(node, delimeter) { if (typeof delimeter === "function") { let prev = null; node.children.forEach((node2) => { if (prev !== null) { delimeter.call(this, prev); } this.node(node2); prev = node2; }); return; } node.children.forEach(this.node, this); } function processChunk(chunk) { tokenize(chunk, (type2, start, end) => { this.token(type2, chunk.slice(start, end)); }); } function createGenerator(config) { const types3 = /* @__PURE__ */ new Map(); for (let [name51, item] of Object.entries(config.node)) { const fn = item.generate || item; if (typeof fn === "function") { types3.set(name51, item.generate || item); } } return function(node, options) { let buffer = ""; let prevCode = 0; let handlers2 = { node(node2) { if (types3.has(node2.type)) { types3.get(node2.type).call(publicApi, node2); } else { throw new Error("Unknown node type: " + node2.type); } }, tokenBefore: safe, token(type2, value) { prevCode = this.tokenBefore(prevCode, type2, value); this.emit(value, type2, false); if (type2 === Delim && value.charCodeAt(0) === REVERSESOLIDUS) { this.emit("\n", WhiteSpace, true); } }, emit(value) { buffer += value; }, result() { return buffer; } }; if (options) { if (typeof options.decorator === "function") { handlers2 = options.decorator(handlers2); } if (options.sourceMap) { handlers2 = generateSourceMap(handlers2); } if (options.mode in token_before_exports) { handlers2.tokenBefore = token_before_exports[options.mode]; } } const publicApi = { node: (node2) => handlers2.node(node2), children: processChildren, token: (type2, value) => handlers2.token(type2, value), tokenize: processChunk }; handlers2.node(node); return handlers2.result(); }; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/convertor/create.js function createConvertor(walk3) { return { fromPlainObject(ast) { walk3(ast, { enter(node) { if (node.children && node.children instanceof List === false) { node.children = new List().fromArray(node.children); } } }); return ast; }, toPlainObject(ast) { walk3(ast, { leave(node) { if (node.children && node.children instanceof List) { node.children = node.children.toArray(); } } }); return ast; } }; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/walker/create.js var { hasOwnProperty: hasOwnProperty2 } = Object.prototype; var noop = function() { }; function ensureFunction(value) { return typeof value === "function" ? value : noop; } function invokeForType(fn, type2) { return function(node, item, list) { if (node.type === type2) { fn.call(this, node, item, list); } }; } function getWalkersFromStructure(name51, nodeType) { const structure50 = nodeType.structure; const walkers = []; for (const key in structure50) { if (hasOwnProperty2.call(structure50, key) === false) { continue; } let fieldTypes = structure50[key]; const walker = { name: key, type: false, nullable: false }; if (!Array.isArray(fieldTypes)) { fieldTypes = [fieldTypes]; } for (const fieldType of fieldTypes) { if (fieldType === null) { walker.nullable = true; } else if (typeof fieldType === "string") { walker.type = "node"; } else if (Array.isArray(fieldType)) { walker.type = "list"; } } if (walker.type) { walkers.push(walker); } } if (walkers.length) { return { context: nodeType.walkContext, fields: walkers }; } return null; } function getTypesFromConfig(config) { const types3 = {}; for (const name51 in config.node) { if (hasOwnProperty2.call(config.node, name51)) { const nodeType = config.node[name51]; if (!nodeType.structure) { throw new Error("Missed `structure` field in `" + name51 + "` node type definition"); } types3[name51] = getWalkersFromStructure(name51, nodeType); } } return types3; } function createTypeIterator(config, reverse) { const fields = config.fields.slice(); const contextName = config.context; const useContext = typeof contextName === "string"; if (reverse) { fields.reverse(); } return function(node, context, walk3, walkReducer) { let prevContextValue; if (useContext) { prevContextValue = context[contextName]; context[contextName] = node; } for (const field of fields) { const ref = node[field.name]; if (!field.nullable || ref) { if (field.type === "list") { const breakWalk = reverse ? ref.reduceRight(walkReducer, false) : ref.reduce(walkReducer, false); if (breakWalk) { return true; } } else if (walk3(ref)) { return true; } } } if (useContext) { context[contextName] = prevContextValue; } }; } function createFastTraveralMap({ StyleSheet, Atrule, Rule: Rule2, Block, DeclarationList }) { return { Atrule: { StyleSheet, Atrule, Rule: Rule2, Block }, Rule: { StyleSheet, Atrule, Rule: Rule2, Block }, Declaration: { StyleSheet, Atrule, Rule: Rule2, Block, DeclarationList } }; } function createWalker(config) { const types3 = getTypesFromConfig(config); const iteratorsNatural = {}; const iteratorsReverse = {}; const breakWalk = Symbol("break-walk"); const skipNode = Symbol("skip-node"); for (const name51 in types3) { if (hasOwnProperty2.call(types3, name51) && types3[name51] !== null) { iteratorsNatural[name51] = createTypeIterator(types3[name51], false); iteratorsReverse[name51] = createTypeIterator(types3[name51], true); } } const fastTraversalIteratorsNatural = createFastTraveralMap(iteratorsNatural); const fastTraversalIteratorsReverse = createFastTraveralMap(iteratorsReverse); const walk3 = function(root, options) { function walkNode(node, item, list) { const enterRet = enter.call(context, node, item, list); if (enterRet === breakWalk) { return true; } if (enterRet === skipNode) { return false; } if (iterators.hasOwnProperty(node.type)) { if (iterators[node.type](node, context, walkNode, walkReducer)) { return true; } } if (leave.call(context, node, item, list) === breakWalk) { return true; } return false; } let enter = noop; let leave = noop; let iterators = iteratorsNatural; let walkReducer = (ret, data, item, list) => ret || walkNode(data, item, list); const context = { break: breakWalk, skip: skipNode, root, stylesheet: null, atrule: null, atrulePrelude: null, rule: null, selector: null, block: null, declaration: null, function: null }; if (typeof options === "function") { enter = options; } else if (options) { enter = ensureFunction(options.enter); leave = ensureFunction(options.leave); if (options.reverse) { iterators = iteratorsReverse; } if (options.visit) { if (fastTraversalIteratorsNatural.hasOwnProperty(options.visit)) { iterators = options.reverse ? fastTraversalIteratorsReverse[options.visit] : fastTraversalIteratorsNatural[options.visit]; } else if (!types3.hasOwnProperty(options.visit)) { throw new Error("Bad value `" + options.visit + "` for `visit` option (should be: " + Object.keys(types3).sort().join(", ") + ")"); } enter = invokeForType(enter, options.visit); leave = invokeForType(leave, options.visit); } } if (enter === noop && leave === noop) { throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function"); } walkNode(root); }; walk3.break = breakWalk; walk3.skip = skipNode; walk3.find = function(ast, fn) { let found = null; walk3(ast, function(node, item, list) { if (fn.call(this, node, item, list)) { found = node; return breakWalk; } }); return found; }; walk3.findLast = function(ast, fn) { let found = null; walk3(ast, { reverse: true, enter(node, item, list) { if (fn.call(this, node, item, list)) { found = node; return breakWalk; } } }); return found; }; walk3.findAll = function(ast, fn) { const found = []; walk3(ast, function(node, item, list) { if (fn.call(this, node, item, list)) { found.push(node); } }); return found; }; return walk3; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/definition-syntax/generate.js function noop2(value) { return value; } function generateMultiplier(multiplier) { const { min, max, comma } = multiplier; if (min === 0 && max === 0) { return comma ? "#?" : "*"; } if (min === 0 && max === 1) { return "?"; } if (min === 1 && max === 0) { return comma ? "#" : "+"; } if (min === 1 && max === 1) { return ""; } return (comma ? "#" : "") + (min === max ? "{" + min + "}" : "{" + min + "," + (max !== 0 ? max : "") + "}"); } function generateTypeOpts(node) { switch (node.type) { case "Range": return " [" + (node.min === null ? "-\u221E" : node.min) + "," + (node.max === null ? "\u221E" : node.max) + "]"; default: throw new Error("Unknown node type `" + node.type + "`"); } } function generateSequence(node, decorate, forceBraces, compact) { const combinator = node.combinator === " " || compact ? node.combinator : " " + node.combinator + " "; const result = node.terms.map((term) => internalGenerate(term, decorate, forceBraces, compact)).join(combinator); if (node.explicit || forceBraces) { return (compact || result[0] === "," ? "[" : "[ ") + result + (compact ? "]" : " ]"); } return result; } function internalGenerate(node, decorate, forceBraces, compact) { let result; switch (node.type) { case "Group": result = generateSequence(node, decorate, forceBraces, compact) + (node.disallowEmpty ? "!" : ""); break; case "Multiplier": return internalGenerate(node.term, decorate, forceBraces, compact) + decorate(generateMultiplier(node), node); case "Boolean": result = ""; break; case "Type": result = "<" + node.name + (node.opts ? decorate(generateTypeOpts(node.opts), node.opts) : "") + ">"; break; case "Property": result = "<'" + node.name + "'>"; break; case "Keyword": result = node.name; break; case "AtKeyword": result = "@" + node.name; break; case "Function": result = node.name + "("; break; case "String": case "Token": result = node.value; break; case "Comma": result = ","; break; default: throw new Error("Unknown node type `" + node.type + "`"); } return decorate(result, node); } function generate(node, options) { let decorate = noop2; let forceBraces = false; let compact = false; if (typeof options === "function") { decorate = options; } else if (options) { forceBraces = Boolean(options.forceBraces); compact = Boolean(options.compact); if (typeof options.decorate === "function") { decorate = options.decorate; } } return internalGenerate(node, decorate, forceBraces, compact); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/error.js var defaultLoc = { offset: 0, line: 1, column: 1 }; function locateMismatch(matchResult, node) { const tokens = matchResult.tokens; const longestMatch = matchResult.longestMatch; const mismatchNode = longestMatch < tokens.length ? tokens[longestMatch].node || null : null; const badNode = mismatchNode !== node ? mismatchNode : null; let mismatchOffset = 0; let mismatchLength = 0; let entries = 0; let css2 = ""; let start; let end; for (let i = 0; i < tokens.length; i++) { const token = tokens[i].value; if (i === longestMatch) { mismatchLength = token.length; mismatchOffset = css2.length; } if (badNode !== null && tokens[i].node === badNode) { if (i <= longestMatch) { entries++; } else { entries = 0; } } css2 += token; } if (longestMatch === tokens.length || entries > 1) { start = fromLoc(badNode || node, "end") || buildLoc(defaultLoc, css2); end = buildLoc(start); } else { start = fromLoc(badNode, "start") || buildLoc(fromLoc(node, "start") || defaultLoc, css2.slice(0, mismatchOffset)); end = fromLoc(badNode, "end") || buildLoc(start, css2.substr(mismatchOffset, mismatchLength)); } return { css: css2, mismatchOffset, mismatchLength, start, end }; } function fromLoc(node, point) { const value = node && node.loc && node.loc[point]; if (value) { return "line" in value ? buildLoc(value) : value; } return null; } function buildLoc({ offset, line, column }, extra) { const loc = { offset, line, column }; if (extra) { const lines = extra.split(/\n|\r\n?|\f/); loc.offset += extra.length; loc.line += lines.length - 1; loc.column = lines.length === 1 ? loc.column + extra.length : lines.pop().length + 1; } return loc; } var SyntaxReferenceError = function(type2, referenceName) { const error = createCustomError( "SyntaxReferenceError", type2 + (referenceName ? " `" + referenceName + "`" : "") ); error.reference = referenceName; return error; }; var SyntaxMatchError = function(message, syntax, node, matchResult) { const error = createCustomError("SyntaxMatchError", message); const { css: css2, mismatchOffset, mismatchLength, start, end } = locateMismatch(matchResult, node); error.rawMessage = message; error.syntax = syntax ? generate(syntax) : ""; error.css = css2; error.mismatchOffset = mismatchOffset; error.mismatchLength = mismatchLength; error.message = message + "\n syntax: " + error.syntax + "\n value: " + (css2 || "") + "\n --------" + new Array(error.mismatchOffset + 1).join("-") + "^"; Object.assign(error, start); error.loc = { source: node && node.loc && node.loc.source || "", start, end }; return error; }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/utils/names.js var keywords = /* @__PURE__ */ new Map(); var properties = /* @__PURE__ */ new Map(); var HYPHENMINUS2 = 45; var keyword = getKeywordDescriptor; var property = getPropertyDescriptor; function isCustomProperty(str2, offset) { offset = offset || 0; return str2.length - offset >= 2 && str2.charCodeAt(offset) === HYPHENMINUS2 && str2.charCodeAt(offset + 1) === HYPHENMINUS2; } function getVendorPrefix(str2, offset) { offset = offset || 0; if (str2.length - offset >= 3) { if (str2.charCodeAt(offset) === HYPHENMINUS2 && str2.charCodeAt(offset + 1) !== HYPHENMINUS2) { const secondDashIndex = str2.indexOf("-", offset + 2); if (secondDashIndex !== -1) { return str2.substring(offset, secondDashIndex + 1); } } } return ""; } function getKeywordDescriptor(keyword3) { if (keywords.has(keyword3)) { return keywords.get(keyword3); } const name51 = keyword3.toLowerCase(); let descriptor = keywords.get(name51); if (descriptor === void 0) { const custom2 = isCustomProperty(name51, 0); const vendor = !custom2 ? getVendorPrefix(name51, 0) : ""; descriptor = Object.freeze({ basename: name51.substr(vendor.length), name: name51, prefix: vendor, vendor, custom: custom2 }); } keywords.set(keyword3, descriptor); return descriptor; } function getPropertyDescriptor(property2) { if (properties.has(property2)) { return properties.get(property2); } let name51 = property2; let hack = property2[0]; if (hack === "/") { hack = property2[1] === "/" ? "//" : "/"; } else if (hack !== "_" && hack !== "*" && hack !== "$" && hack !== "#" && hack !== "+" && hack !== "&") { hack = ""; } const custom2 = isCustomProperty(name51, hack.length); if (!custom2) { name51 = name51.toLowerCase(); if (properties.has(name51)) { const descriptor2 = properties.get(name51); properties.set(property2, descriptor2); return descriptor2; } } const vendor = !custom2 ? getVendorPrefix(name51, hack.length) : ""; const prefix = name51.substr(0, hack.length + vendor.length); const descriptor = Object.freeze({ basename: name51.substr(prefix.length), name: name51.substr(hack.length), hack, vendor, prefix, custom: custom2 }); properties.set(property2, descriptor); return descriptor; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/generic-const.js var cssWideKeywords = [ "initial", "inherit", "unset", "revert", "revert-layer" ]; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/generic-an-plus-b.js var PLUSSIGN2 = 43; var HYPHENMINUS3 = 45; var N2 = 110; var DISALLOW_SIGN = true; var ALLOW_SIGN = false; function isDelim(token, code2) { return token !== null && token.type === Delim && token.value.charCodeAt(0) === code2; } function skipSC(token, offset, getNextToken) { while (token !== null && (token.type === WhiteSpace || token.type === Comment)) { token = getNextToken(++offset); } return offset; } function checkInteger(token, valueOffset, disallowSign, offset) { if (!token) { return 0; } const code2 = token.value.charCodeAt(valueOffset); if (code2 === PLUSSIGN2 || code2 === HYPHENMINUS3) { if (disallowSign) { return 0; } valueOffset++; } for (; valueOffset < token.value.length; valueOffset++) { if (!isDigit(token.value.charCodeAt(valueOffset))) { return 0; } } return offset + 1; } function consumeB(token, offset_, getNextToken) { let sign = false; let offset = skipSC(token, offset_, getNextToken); token = getNextToken(offset); if (token === null) { return offset_; } if (token.type !== Number2) { if (isDelim(token, PLUSSIGN2) || isDelim(token, HYPHENMINUS3)) { sign = true; offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); if (token === null || token.type !== Number2) { return 0; } } else { return offset_; } } if (!sign) { const code2 = token.value.charCodeAt(0); if (code2 !== PLUSSIGN2 && code2 !== HYPHENMINUS3) { return 0; } } return checkInteger(token, sign ? 0 : 1, sign, offset); } function anPlusB(token, getNextToken) { let offset = 0; if (!token) { return 0; } if (token.type === Number2) { return checkInteger(token, 0, ALLOW_SIGN, offset); } else if (token.type === Ident && token.value.charCodeAt(0) === HYPHENMINUS3) { if (!cmpChar(token.value, 1, N2)) { return 0; } switch (token.value.length) { // #endregion // #region n - signless-integer case 2: return consumeB(getNextToken(++offset), offset, getNextToken); // #endregion // #region n- signless-integer case 3: if (token.value.charCodeAt(2) !== HYPHENMINUS3) { return 0; } offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); // default: if (token.value.charCodeAt(2) !== HYPHENMINUS3) { return 0; } return checkInteger(token, 3, DISALLOW_SIGN, offset); } } else if (token.type === Ident || isDelim(token, PLUSSIGN2) && getNextToken(offset + 1).type === Ident) { if (token.type !== Ident) { token = getNextToken(++offset); } if (token === null || !cmpChar(token.value, 0, N2)) { return 0; } switch (token.value.length) { // '+'? n // '+'? n // '+'? n ['+' | '-'] case 1: return consumeB(getNextToken(++offset), offset, getNextToken); // '+'? n- case 2: if (token.value.charCodeAt(1) !== HYPHENMINUS3) { return 0; } offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); // '+'? default: if (token.value.charCodeAt(1) !== HYPHENMINUS3) { return 0; } return checkInteger(token, 2, DISALLOW_SIGN, offset); } } else if (token.type === Dimension) { let code2 = token.value.charCodeAt(0); let sign = code2 === PLUSSIGN2 || code2 === HYPHENMINUS3 ? 1 : 0; let i = sign; for (; i < token.value.length; i++) { if (!isDigit(token.value.charCodeAt(i))) { break; } } if (i === sign) { return 0; } if (!cmpChar(token.value, i, N2)) { return 0; } if (i + 1 === token.value.length) { return consumeB(getNextToken(++offset), offset, getNextToken); } else { if (token.value.charCodeAt(i + 1) !== HYPHENMINUS3) { return 0; } if (i + 2 === token.value.length) { offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); } else { return checkInteger(token, i + 2, DISALLOW_SIGN, offset); } } } return 0; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/generic-urange.js var PLUSSIGN3 = 43; var HYPHENMINUS4 = 45; var QUESTIONMARK = 63; var U = 117; function isDelim2(token, code2) { return token !== null && token.type === Delim && token.value.charCodeAt(0) === code2; } function startsWith(token, code2) { return token.value.charCodeAt(0) === code2; } function hexSequence(token, offset, allowDash) { let hexlen = 0; for (let pos = offset; pos < token.value.length; pos++) { const code2 = token.value.charCodeAt(pos); if (code2 === HYPHENMINUS4 && allowDash && hexlen !== 0) { hexSequence(token, offset + hexlen + 1, false); return 6; } if (!isHexDigit(code2)) { return 0; } if (++hexlen > 6) { return 0; } ; } return hexlen; } function withQuestionMarkSequence(consumed, length2, getNextToken) { if (!consumed) { return 0; } while (isDelim2(getNextToken(length2), QUESTIONMARK)) { if (++consumed > 6) { return 0; } length2++; } return length2; } function urange(token, getNextToken) { let length2 = 0; if (token === null || token.type !== Ident || !cmpChar(token.value, 0, U)) { return 0; } token = getNextToken(++length2); if (token === null) { return 0; } if (isDelim2(token, PLUSSIGN3)) { token = getNextToken(++length2); if (token === null) { return 0; } if (token.type === Ident) { return withQuestionMarkSequence(hexSequence(token, 0, true), ++length2, getNextToken); } if (isDelim2(token, QUESTIONMARK)) { return withQuestionMarkSequence(1, ++length2, getNextToken); } return 0; } if (token.type === Number2) { const consumedHexLength = hexSequence(token, 1, true); if (consumedHexLength === 0) { return 0; } token = getNextToken(++length2); if (token === null) { return length2; } if (token.type === Dimension || token.type === Number2) { if (!startsWith(token, HYPHENMINUS4) || !hexSequence(token, 1, false)) { return 0; } return length2 + 1; } return withQuestionMarkSequence(consumedHexLength, length2, getNextToken); } if (token.type === Dimension) { return withQuestionMarkSequence(hexSequence(token, 1, true), ++length2, getNextToken); } return 0; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/generic.js var calcFunctionNames = ["calc(", "-moz-calc(", "-webkit-calc("]; var balancePair2 = /* @__PURE__ */ new Map([ [Function2, RightParenthesis], [LeftParenthesis, RightParenthesis], [LeftSquareBracket, RightSquareBracket], [LeftCurlyBracket, RightCurlyBracket] ]); function charCodeAt(str2, index) { return index < str2.length ? str2.charCodeAt(index) : 0; } function eqStr(actual, expected) { return cmpStr(actual, 0, actual.length, expected); } function eqStrAny(actual, expected) { for (let i = 0; i < expected.length; i++) { if (eqStr(actual, expected[i])) { return true; } } return false; } function isPostfixIeHack(str2, offset) { if (offset !== str2.length - 2) { return false; } return charCodeAt(str2, offset) === 92 && // U+005C REVERSE SOLIDUS (\) isDigit(charCodeAt(str2, offset + 1)); } function outOfRange(opts, value, numEnd) { if (opts && opts.type === "Range") { const num = Number( numEnd !== void 0 && numEnd !== value.length ? value.substr(0, numEnd) : value ); if (isNaN(num)) { return true; } if (opts.min !== null && num < opts.min && typeof opts.min !== "string") { return true; } if (opts.max !== null && num > opts.max && typeof opts.max !== "string") { return true; } } return false; } function consumeFunction(token, getNextToken) { let balanceCloseType = 0; let balanceStash = []; let length2 = 0; scan: do { switch (token.type) { case RightCurlyBracket: case RightParenthesis: case RightSquareBracket: if (token.type !== balanceCloseType) { break scan; } balanceCloseType = balanceStash.pop(); if (balanceStash.length === 0) { length2++; break scan; } break; case Function2: case LeftParenthesis: case LeftSquareBracket: case LeftCurlyBracket: balanceStash.push(balanceCloseType); balanceCloseType = balancePair2.get(token.type); break; } length2++; } while (token = getNextToken(length2)); return length2; } function calc(next) { return function(token, getNextToken, opts) { if (token === null) { return 0; } if (token.type === Function2 && eqStrAny(token.value, calcFunctionNames)) { return consumeFunction(token, getNextToken); } return next(token, getNextToken, opts); }; } function tokenType(expectedTokenType) { return function(token) { if (token === null || token.type !== expectedTokenType) { return 0; } return 1; }; } function customIdent(token) { if (token === null || token.type !== Ident) { return 0; } const name51 = token.value.toLowerCase(); if (eqStrAny(name51, cssWideKeywords)) { return 0; } if (eqStr(name51, "default")) { return 0; } return 1; } function dashedIdent(token) { if (token === null || token.type !== Ident) { return 0; } if (charCodeAt(token.value, 0) !== 45 || charCodeAt(token.value, 1) !== 45) { return 0; } return 1; } function customPropertyName(token) { if (!dashedIdent(token)) { return 0; } if (token.value === "--") { return 0; } return 1; } function hexColor(token) { if (token === null || token.type !== Hash) { return 0; } const length2 = token.value.length; if (length2 !== 4 && length2 !== 5 && length2 !== 7 && length2 !== 9) { return 0; } for (let i = 1; i < length2; i++) { if (!isHexDigit(charCodeAt(token.value, i))) { return 0; } } return 1; } function idSelector(token) { if (token === null || token.type !== Hash) { return 0; } if (!isIdentifierStart(charCodeAt(token.value, 1), charCodeAt(token.value, 2), charCodeAt(token.value, 3))) { return 0; } return 1; } function declarationValue(token, getNextToken) { if (!token) { return 0; } let balanceCloseType = 0; let balanceStash = []; let length2 = 0; scan: do { switch (token.type) { // ... , , case BadString: case BadUrl: break scan; // ... unmatched <)-token>, <]-token>, or <}-token>, case RightCurlyBracket: case RightParenthesis: case RightSquareBracket: if (token.type !== balanceCloseType) { break scan; } balanceCloseType = balanceStash.pop(); break; // ... or top-level tokens case Semicolon: if (balanceCloseType === 0) { break scan; } break; // ... or tokens with a value of "!" case Delim: if (balanceCloseType === 0 && token.value === "!") { break scan; } break; case Function2: case LeftParenthesis: case LeftSquareBracket: case LeftCurlyBracket: balanceStash.push(balanceCloseType); balanceCloseType = balancePair2.get(token.type); break; } length2++; } while (token = getNextToken(length2)); return length2; } function anyValue(token, getNextToken) { if (!token) { return 0; } let balanceCloseType = 0; let balanceStash = []; let length2 = 0; scan: do { switch (token.type) { // ... does not contain , , case BadString: case BadUrl: break scan; // ... unmatched <)-token>, <]-token>, or <}-token>, case RightCurlyBracket: case RightParenthesis: case RightSquareBracket: if (token.type !== balanceCloseType) { break scan; } balanceCloseType = balanceStash.pop(); break; case Function2: case LeftParenthesis: case LeftSquareBracket: case LeftCurlyBracket: balanceStash.push(balanceCloseType); balanceCloseType = balancePair2.get(token.type); break; } length2++; } while (token = getNextToken(length2)); return length2; } function dimension(type2) { if (type2) { type2 = new Set(type2); } return function(token, getNextToken, opts) { if (token === null || token.type !== Dimension) { return 0; } const numberEnd = consumeNumber(token.value, 0); if (type2 !== null) { const reverseSolidusOffset = token.value.indexOf("\\", numberEnd); const unit = reverseSolidusOffset === -1 || !isPostfixIeHack(token.value, reverseSolidusOffset) ? token.value.substr(numberEnd) : token.value.substring(numberEnd, reverseSolidusOffset); if (type2.has(unit.toLowerCase()) === false) { return 0; } } if (outOfRange(opts, token.value, numberEnd)) { return 0; } return 1; }; } function percentage(token, getNextToken, opts) { if (token === null || token.type !== Percentage) { return 0; } if (outOfRange(opts, token.value, token.value.length - 1)) { return 0; } return 1; } function zero(next) { if (typeof next !== "function") { next = function() { return 0; }; } return function(token, getNextToken, opts) { if (token !== null && token.type === Number2) { if (Number(token.value) === 0) { return 1; } } return next(token, getNextToken, opts); }; } function number(token, getNextToken, opts) { if (token === null) { return 0; } const numberEnd = consumeNumber(token.value, 0); const isNumber = numberEnd === token.value.length; if (!isNumber && !isPostfixIeHack(token.value, numberEnd)) { return 0; } if (outOfRange(opts, token.value, numberEnd)) { return 0; } return 1; } function integer(token, getNextToken, opts) { if (token === null || token.type !== Number2) { return 0; } let i = charCodeAt(token.value, 0) === 43 || // U+002B PLUS SIGN (+) charCodeAt(token.value, 0) === 45 ? 1 : 0; for (; i < token.value.length; i++) { if (!isDigit(charCodeAt(token.value, i))) { return 0; } } if (outOfRange(opts, token.value, i)) { return 0; } return 1; } var tokenTypes = { "ident-token": tokenType(Ident), "function-token": tokenType(Function2), "at-keyword-token": tokenType(AtKeyword), "hash-token": tokenType(Hash), "string-token": tokenType(String2), "bad-string-token": tokenType(BadString), "url-token": tokenType(Url), "bad-url-token": tokenType(BadUrl), "delim-token": tokenType(Delim), "number-token": tokenType(Number2), "percentage-token": tokenType(Percentage), "dimension-token": tokenType(Dimension), "whitespace-token": tokenType(WhiteSpace), "CDO-token": tokenType(CDO), "CDC-token": tokenType(CDC), "colon-token": tokenType(Colon), "semicolon-token": tokenType(Semicolon), "comma-token": tokenType(Comma), "[-token": tokenType(LeftSquareBracket), "]-token": tokenType(RightSquareBracket), "(-token": tokenType(LeftParenthesis), ")-token": tokenType(RightParenthesis), "{-token": tokenType(LeftCurlyBracket), "}-token": tokenType(RightCurlyBracket) }; var productionTypes = { // token type aliases "string": tokenType(String2), "ident": tokenType(Ident), // percentage "percentage": calc(percentage), // numeric "zero": zero(), "number": calc(number), "integer": calc(integer), // complex types "custom-ident": customIdent, "dashed-ident": dashedIdent, "custom-property-name": customPropertyName, "hex-color": hexColor, "id-selector": idSelector, // element( ) "an-plus-b": anPlusB, "urange": urange, "declaration-value": declarationValue, "any-value": anyValue }; function createDemensionTypes(units) { const { angle: angle2, decibel: decibel2, frequency: frequency2, flex: flex2, length: length2, resolution: resolution2, semitones: semitones2, time: time2 } = units || {}; return { "dimension": calc(dimension(null)), "angle": calc(dimension(angle2)), "decibel": calc(dimension(decibel2)), "frequency": calc(dimension(frequency2)), "flex": calc(dimension(flex2)), "length": calc(zero(dimension(length2))), "resolution": calc(dimension(resolution2)), "semitones": calc(dimension(semitones2)), "time": calc(dimension(time2)) }; } function createGenericTypes(units) { return { ...tokenTypes, ...productionTypes, ...createDemensionTypes(units) }; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/units.js var units_exports = {}; __export(units_exports, { angle: () => angle, decibel: () => decibel, flex: () => flex, frequency: () => frequency, length: () => length, resolution: () => resolution, semitones: () => semitones, time: () => time }); var length = [ // absolute length units https://www.w3.org/TR/css-values-3/#lengths "cm", "mm", "q", "in", "pt", "pc", "px", // font-relative length units https://drafts.csswg.org/css-values-4/#font-relative-lengths "em", "rem", "ex", "rex", "cap", "rcap", "ch", "rch", "ic", "ric", "lh", "rlh", // viewport-percentage lengths https://drafts.csswg.org/css-values-4/#viewport-relative-lengths "vw", "svw", "lvw", "dvw", "vh", "svh", "lvh", "dvh", "vi", "svi", "lvi", "dvi", "vb", "svb", "lvb", "dvb", "vmin", "svmin", "lvmin", "dvmin", "vmax", "svmax", "lvmax", "dvmax", // container relative lengths https://drafts.csswg.org/css-contain-3/#container-lengths "cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax" ]; var angle = ["deg", "grad", "rad", "turn"]; var time = ["s", "ms"]; var frequency = ["hz", "khz"]; var resolution = ["dpi", "dpcm", "dppx", "x"]; var flex = ["fr"]; var decibel = ["db"]; var semitones = ["st"]; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/definition-syntax/SyntaxError.js function SyntaxError3(message, input, offset) { return Object.assign(createCustomError("SyntaxError", message), { input, offset, rawMessage: message, message: message + "\n " + input + "\n--" + new Array((offset || input.length) + 1).join("-") + "^" }); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/definition-syntax/scanner.js var TAB = 9; var N3 = 10; var F2 = 12; var R2 = 13; var SPACE = 32; var NAME_CHAR = new Uint8Array(128).map( (_, idx) => /[a-zA-Z0-9\-]/.test(String.fromCharCode(idx)) ? 1 : 0 ); var Scanner = class { constructor(str2) { this.str = str2; this.pos = 0; } charCodeAt(pos) { return pos < this.str.length ? this.str.charCodeAt(pos) : 0; } charCode() { return this.charCodeAt(this.pos); } isNameCharCode(code2 = this.charCode()) { return code2 < 128 && NAME_CHAR[code2] === 1; } nextCharCode() { return this.charCodeAt(this.pos + 1); } nextNonWsCode(pos) { return this.charCodeAt(this.findWsEnd(pos)); } skipWs() { this.pos = this.findWsEnd(this.pos); } findWsEnd(pos) { for (; pos < this.str.length; pos++) { const code2 = this.str.charCodeAt(pos); if (code2 !== R2 && code2 !== N3 && code2 !== F2 && code2 !== SPACE && code2 !== TAB) { break; } } return pos; } substringToPos(end) { return this.str.substring(this.pos, this.pos = end); } eat(code2) { if (this.charCode() !== code2) { this.error("Expect `" + String.fromCharCode(code2) + "`"); } this.pos++; } peek() { return this.pos < this.str.length ? this.str.charAt(this.pos++) : ""; } error(message) { throw new SyntaxError3(message, this.str, this.pos); } scanSpaces() { return this.substringToPos(this.findWsEnd(this.pos)); } scanWord() { let end = this.pos; for (; end < this.str.length; end++) { const code2 = this.str.charCodeAt(end); if (code2 >= 128 || NAME_CHAR[code2] === 0) { break; } } if (this.pos === end) { this.error("Expect a keyword"); } return this.substringToPos(end); } scanNumber() { let end = this.pos; for (; end < this.str.length; end++) { const code2 = this.str.charCodeAt(end); if (code2 < 48 || code2 > 57) { break; } } if (this.pos === end) { this.error("Expect a number"); } return this.substringToPos(end); } scanString() { const end = this.str.indexOf("'", this.pos + 1); if (end === -1) { this.pos = this.str.length; this.error("Expect an apostrophe"); } return this.substringToPos(end + 1); } }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/definition-syntax/parse.js var TAB2 = 9; var N4 = 10; var F3 = 12; var R3 = 13; var SPACE2 = 32; var EXCLAMATIONMARK2 = 33; var NUMBERSIGN2 = 35; var AMPERSAND = 38; var APOSTROPHE = 39; var LEFTPARENTHESIS = 40; var RIGHTPARENTHESIS = 41; var ASTERISK = 42; var PLUSSIGN4 = 43; var COMMA = 44; var HYPERMINUS = 45; var LESSTHANSIGN = 60; var GREATERTHANSIGN = 62; var QUESTIONMARK2 = 63; var COMMERCIALAT = 64; var LEFTSQUAREBRACKET = 91; var RIGHTSQUAREBRACKET = 93; var LEFTCURLYBRACKET2 = 123; var VERTICALLINE = 124; var RIGHTCURLYBRACKET = 125; var INFINITY = 8734; var COMBINATOR_PRECEDENCE = { " ": 1, "&&": 2, "||": 3, "|": 4 }; function readMultiplierRange(scanner) { let min = null; let max = null; scanner.eat(LEFTCURLYBRACKET2); scanner.skipWs(); min = scanner.scanNumber(scanner); scanner.skipWs(); if (scanner.charCode() === COMMA) { scanner.pos++; scanner.skipWs(); if (scanner.charCode() !== RIGHTCURLYBRACKET) { max = scanner.scanNumber(scanner); scanner.skipWs(); } } else { max = min; } scanner.eat(RIGHTCURLYBRACKET); return { min: Number(min), max: max ? Number(max) : 0 }; } function readMultiplier(scanner) { let range = null; let comma = false; switch (scanner.charCode()) { case ASTERISK: scanner.pos++; range = { min: 0, max: 0 }; break; case PLUSSIGN4: scanner.pos++; range = { min: 1, max: 0 }; break; case QUESTIONMARK2: scanner.pos++; range = { min: 0, max: 1 }; break; case NUMBERSIGN2: scanner.pos++; comma = true; if (scanner.charCode() === LEFTCURLYBRACKET2) { range = readMultiplierRange(scanner); } else if (scanner.charCode() === QUESTIONMARK2) { scanner.pos++; range = { min: 0, max: 0 }; } else { range = { min: 1, max: 0 }; } break; case LEFTCURLYBRACKET2: range = readMultiplierRange(scanner); break; default: return null; } return { type: "Multiplier", comma, min: range.min, max: range.max, term: null }; } function maybeMultiplied(scanner, node) { const multiplier = readMultiplier(scanner); if (multiplier !== null) { multiplier.term = node; if (scanner.charCode() === NUMBERSIGN2 && scanner.charCodeAt(scanner.pos - 1) === PLUSSIGN4) { return maybeMultiplied(scanner, multiplier); } return multiplier; } return node; } function maybeToken(scanner) { const ch = scanner.peek(); if (ch === "") { return null; } return maybeMultiplied(scanner, { type: "Token", value: ch }); } function readProperty(scanner) { let name51; scanner.eat(LESSTHANSIGN); scanner.eat(APOSTROPHE); name51 = scanner.scanWord(); scanner.eat(APOSTROPHE); scanner.eat(GREATERTHANSIGN); return maybeMultiplied(scanner, { type: "Property", name: name51 }); } function readTypeRange(scanner) { let min = null; let max = null; let sign = 1; scanner.eat(LEFTSQUAREBRACKET); if (scanner.charCode() === HYPERMINUS) { scanner.peek(); sign = -1; } if (sign == -1 && scanner.charCode() === INFINITY) { scanner.peek(); } else { min = sign * Number(scanner.scanNumber(scanner)); if (scanner.isNameCharCode()) { min += scanner.scanWord(); } } scanner.skipWs(); scanner.eat(COMMA); scanner.skipWs(); if (scanner.charCode() === INFINITY) { scanner.peek(); } else { sign = 1; if (scanner.charCode() === HYPERMINUS) { scanner.peek(); sign = -1; } max = sign * Number(scanner.scanNumber(scanner)); if (scanner.isNameCharCode()) { max += scanner.scanWord(); } } scanner.eat(RIGHTSQUAREBRACKET); return { type: "Range", min, max }; } function readType(scanner) { let name51; let opts = null; scanner.eat(LESSTHANSIGN); name51 = scanner.scanWord(); if (name51 === "boolean-expr") { scanner.eat(LEFTSQUAREBRACKET); const implicitGroup = readImplicitGroup(scanner, RIGHTSQUAREBRACKET); scanner.eat(RIGHTSQUAREBRACKET); scanner.eat(GREATERTHANSIGN); return maybeMultiplied(scanner, { type: "Boolean", term: implicitGroup.terms.length === 1 ? implicitGroup.terms[0] : implicitGroup }); } if (scanner.charCode() === LEFTPARENTHESIS && scanner.nextCharCode() === RIGHTPARENTHESIS) { scanner.pos += 2; name51 += "()"; } if (scanner.charCodeAt(scanner.findWsEnd(scanner.pos)) === LEFTSQUAREBRACKET) { scanner.skipWs(); opts = readTypeRange(scanner); } scanner.eat(GREATERTHANSIGN); return maybeMultiplied(scanner, { type: "Type", name: name51, opts }); } function readKeywordOrFunction(scanner) { const name51 = scanner.scanWord(); if (scanner.charCode() === LEFTPARENTHESIS) { scanner.pos++; return { type: "Function", name: name51 }; } return maybeMultiplied(scanner, { type: "Keyword", name: name51 }); } function regroupTerms(terms, combinators) { function createGroup(terms2, combinator2) { return { type: "Group", terms: terms2, combinator: combinator2, disallowEmpty: false, explicit: false }; } let combinator; combinators = Object.keys(combinators).sort((a, b) => COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b]); while (combinators.length > 0) { combinator = combinators.shift(); let i = 0; let subgroupStart = 0; for (; i < terms.length; i++) { const term = terms[i]; if (term.type === "Combinator") { if (term.value === combinator) { if (subgroupStart === -1) { subgroupStart = i - 1; } terms.splice(i, 1); i--; } else { if (subgroupStart !== -1 && i - subgroupStart > 1) { terms.splice( subgroupStart, i - subgroupStart, createGroup(terms.slice(subgroupStart, i), combinator) ); i = subgroupStart + 1; } subgroupStart = -1; } } } if (subgroupStart !== -1 && combinators.length) { terms.splice( subgroupStart, i - subgroupStart, createGroup(terms.slice(subgroupStart, i), combinator) ); } } return combinator; } function readImplicitGroup(scanner, stopCharCode) { const combinators = /* @__PURE__ */ Object.create(null); const terms = []; let token; let prevToken = null; let prevTokenPos = scanner.pos; while (scanner.charCode() !== stopCharCode && (token = peek(scanner, stopCharCode))) { if (token.type !== "Spaces") { if (token.type === "Combinator") { if (prevToken === null || prevToken.type === "Combinator") { scanner.pos = prevTokenPos; scanner.error("Unexpected combinator"); } combinators[token.value] = true; } else if (prevToken !== null && prevToken.type !== "Combinator") { combinators[" "] = true; terms.push({ type: "Combinator", value: " " }); } terms.push(token); prevToken = token; prevTokenPos = scanner.pos; } } if (prevToken !== null && prevToken.type === "Combinator") { scanner.pos -= prevTokenPos; scanner.error("Unexpected combinator"); } return { type: "Group", terms, combinator: regroupTerms(terms, combinators) || " ", disallowEmpty: false, explicit: false }; } function readGroup(scanner, stopCharCode) { let result; scanner.eat(LEFTSQUAREBRACKET); result = readImplicitGroup(scanner, stopCharCode); scanner.eat(RIGHTSQUAREBRACKET); result.explicit = true; if (scanner.charCode() === EXCLAMATIONMARK2) { scanner.pos++; result.disallowEmpty = true; } return result; } function peek(scanner, stopCharCode) { let code2 = scanner.charCode(); switch (code2) { case RIGHTSQUAREBRACKET: break; case LEFTSQUAREBRACKET: return maybeMultiplied(scanner, readGroup(scanner, stopCharCode)); case LESSTHANSIGN: return scanner.nextCharCode() === APOSTROPHE ? readProperty(scanner) : readType(scanner); case VERTICALLINE: return { type: "Combinator", value: scanner.substringToPos( scanner.pos + (scanner.nextCharCode() === VERTICALLINE ? 2 : 1) ) }; case AMPERSAND: scanner.pos++; scanner.eat(AMPERSAND); return { type: "Combinator", value: "&&" }; case COMMA: scanner.pos++; return { type: "Comma" }; case APOSTROPHE: return maybeMultiplied(scanner, { type: "String", value: scanner.scanString() }); case SPACE2: case TAB2: case N4: case R3: case F3: return { type: "Spaces", value: scanner.scanSpaces() }; case COMMERCIALAT: code2 = scanner.nextCharCode(); if (scanner.isNameCharCode(code2)) { scanner.pos++; return { type: "AtKeyword", name: scanner.scanWord() }; } return maybeToken(scanner); case ASTERISK: case PLUSSIGN4: case QUESTIONMARK2: case NUMBERSIGN2: case EXCLAMATIONMARK2: break; case LEFTCURLYBRACKET2: code2 = scanner.nextCharCode(); if (code2 < 48 || code2 > 57) { return maybeToken(scanner); } break; default: if (scanner.isNameCharCode(code2)) { return readKeywordOrFunction(scanner); } return maybeToken(scanner); } } function parse(source) { const scanner = new Scanner(source); const result = readImplicitGroup(scanner); if (scanner.pos !== source.length) { scanner.error("Unexpected input"); } if (result.terms.length === 1 && result.terms[0].type === "Group") { return result.terms[0]; } return result; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/definition-syntax/walk.js var noop3 = function() { }; function ensureFunction2(value) { return typeof value === "function" ? value : noop3; } function walk(node, options, context) { function walk3(node2) { enter.call(context, node2); switch (node2.type) { case "Group": node2.terms.forEach(walk3); break; case "Multiplier": case "Boolean": walk3(node2.term); break; case "Type": case "Property": case "Keyword": case "AtKeyword": case "Function": case "String": case "Token": case "Comma": break; default: throw new Error("Unknown type: " + node2.type); } leave.call(context, node2); } let enter = noop3; let leave = noop3; if (typeof options === "function") { enter = options; } else if (options) { enter = ensureFunction2(options.enter); leave = ensureFunction2(options.leave); } if (enter === noop3 && leave === noop3) { throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function"); } walk3(node, context); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/prepare-tokens.js var astToTokens = { decorator(handlers2) { const tokens = []; let curNode = null; return { ...handlers2, node(node) { const tmp = curNode; curNode = node; handlers2.node.call(this, node); curNode = tmp; }, emit(value, type2, auto) { tokens.push({ type: type2, value, node: auto ? null : curNode }); }, result() { return tokens; } }; } }; function stringToTokens(str2) { const tokens = []; tokenize( str2, (type2, start, end) => tokens.push({ type: type2, value: str2.slice(start, end), node: null }) ); return tokens; } function prepare_tokens_default(value, syntax) { if (typeof value === "string") { return stringToTokens(value); } return syntax.generate(value, astToTokens); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/match-graph.js var MATCH = { type: "Match" }; var MISMATCH = { type: "Mismatch" }; var DISALLOW_EMPTY = { type: "DisallowEmpty" }; var LEFTPARENTHESIS2 = 40; var RIGHTPARENTHESIS2 = 41; function createCondition(match, thenBranch, elseBranch) { if (thenBranch === MATCH && elseBranch === MISMATCH) { return match; } if (match === MATCH && thenBranch === MATCH && elseBranch === MATCH) { return match; } if (match.type === "If" && match.else === MISMATCH && thenBranch === MATCH) { thenBranch = match.then; match = match.match; } return { type: "If", match, then: thenBranch, else: elseBranch }; } function isFunctionType(name51) { return name51.length > 2 && name51.charCodeAt(name51.length - 2) === LEFTPARENTHESIS2 && name51.charCodeAt(name51.length - 1) === RIGHTPARENTHESIS2; } function isEnumCapatible(term) { return term.type === "Keyword" || term.type === "AtKeyword" || term.type === "Function" || term.type === "Type" && isFunctionType(term.name); } function groupNode(terms, combinator = " ", explicit = false) { return { type: "Group", terms, combinator, disallowEmpty: false, explicit }; } function replaceTypeInGraph(node, replacements, visited = /* @__PURE__ */ new Set()) { if (!visited.has(node)) { visited.add(node); switch (node.type) { case "If": node.match = replaceTypeInGraph(node.match, replacements, visited); node.then = replaceTypeInGraph(node.then, replacements, visited); node.else = replaceTypeInGraph(node.else, replacements, visited); break; case "Type": return replacements[node.name] || node; } } return node; } function buildGroupMatchGraph(combinator, terms, atLeastOneTermMatched) { switch (combinator) { case " ": { let result = MATCH; for (let i = terms.length - 1; i >= 0; i--) { const term = terms[i]; result = createCondition( term, result, MISMATCH ); } ; return result; } case "|": { let result = MISMATCH; let map2 = null; for (let i = terms.length - 1; i >= 0; i--) { let term = terms[i]; if (isEnumCapatible(term)) { if (map2 === null && i > 0 && isEnumCapatible(terms[i - 1])) { map2 = /* @__PURE__ */ Object.create(null); result = createCondition( { type: "Enum", map: map2 }, MATCH, result ); } if (map2 !== null) { const key = (isFunctionType(term.name) ? term.name.slice(0, -1) : term.name).toLowerCase(); if (key in map2 === false) { map2[key] = term; continue; } } } map2 = null; result = createCondition( term, MATCH, result ); } ; return result; } case "&&": { if (terms.length > 5) { return { type: "MatchOnce", terms, all: true }; } let result = MISMATCH; for (let i = terms.length - 1; i >= 0; i--) { const term = terms[i]; let thenClause; if (terms.length > 1) { thenClause = buildGroupMatchGraph( combinator, terms.filter(function(newGroupTerm) { return newGroupTerm !== term; }), false ); } else { thenClause = MATCH; } result = createCondition( term, thenClause, result ); } ; return result; } case "||": { if (terms.length > 5) { return { type: "MatchOnce", terms, all: false }; } let result = atLeastOneTermMatched ? MATCH : MISMATCH; for (let i = terms.length - 1; i >= 0; i--) { const term = terms[i]; let thenClause; if (terms.length > 1) { thenClause = buildGroupMatchGraph( combinator, terms.filter(function(newGroupTerm) { return newGroupTerm !== term; }), true ); } else { thenClause = MATCH; } result = createCondition( term, thenClause, result ); } ; return result; } } } function buildMultiplierMatchGraph(node) { let result = MATCH; let matchTerm = buildMatchGraphInternal(node.term); if (node.max === 0) { matchTerm = createCondition( matchTerm, DISALLOW_EMPTY, MISMATCH ); result = createCondition( matchTerm, null, // will be a loop MISMATCH ); result.then = createCondition( MATCH, MATCH, result // make a loop ); if (node.comma) { result.then.else = createCondition( { type: "Comma", syntax: node }, result, MISMATCH ); } } else { for (let i = node.min || 1; i <= node.max; i++) { if (node.comma && result !== MATCH) { result = createCondition( { type: "Comma", syntax: node }, result, MISMATCH ); } result = createCondition( matchTerm, createCondition( MATCH, MATCH, result ), MISMATCH ); } } if (node.min === 0) { result = createCondition( MATCH, MATCH, result ); } else { for (let i = 0; i < node.min - 1; i++) { if (node.comma && result !== MATCH) { result = createCondition( { type: "Comma", syntax: node }, result, MISMATCH ); } result = createCondition( matchTerm, result, MISMATCH ); } } return result; } function buildMatchGraphInternal(node) { if (typeof node === "function") { return { type: "Generic", fn: node }; } switch (node.type) { case "Group": { let result = buildGroupMatchGraph( node.combinator, node.terms.map(buildMatchGraphInternal), false ); if (node.disallowEmpty) { result = createCondition( result, DISALLOW_EMPTY, MISMATCH ); } return result; } case "Multiplier": return buildMultiplierMatchGraph(node); // https://drafts.csswg.org/css-values-5/#boolean case "Boolean": { const term = buildMatchGraphInternal(node.term); const matchNode = buildMatchGraphInternal(groupNode([ groupNode([ { type: "Keyword", name: "not" }, { type: "Type", name: "!boolean-group" } ]), groupNode([ { type: "Type", name: "!boolean-group" }, groupNode([ { type: "Multiplier", comma: false, min: 0, max: 0, term: groupNode([ { type: "Keyword", name: "and" }, { type: "Type", name: "!boolean-group" } ]) }, { type: "Multiplier", comma: false, min: 0, max: 0, term: groupNode([ { type: "Keyword", name: "or" }, { type: "Type", name: "!boolean-group" } ]) } ], "|") ]) ], "|")); const booleanGroup = buildMatchGraphInternal( groupNode([ { type: "Type", name: "!term" }, groupNode([ { type: "Token", value: "(" }, { type: "Type", name: "!self" }, { type: "Token", value: ")" } ]), { type: "Type", name: "general-enclosed" } ], "|") ); replaceTypeInGraph(booleanGroup, { "!term": term, "!self": matchNode }); replaceTypeInGraph(matchNode, { "!boolean-group": booleanGroup }); return matchNode; } case "Type": case "Property": return { type: node.type, name: node.name, syntax: node }; case "Keyword": return { type: node.type, name: node.name.toLowerCase(), syntax: node }; case "AtKeyword": return { type: node.type, name: "@" + node.name.toLowerCase(), syntax: node }; case "Function": return { type: node.type, name: node.name.toLowerCase() + "(", syntax: node }; case "String": if (node.value.length === 3) { return { type: "Token", value: node.value.charAt(1), syntax: node }; } return { type: node.type, value: node.value.substr(1, node.value.length - 2).replace(/\\'/g, "'"), syntax: node }; case "Token": return { type: node.type, value: node.value, syntax: node }; case "Comma": return { type: node.type, syntax: node }; default: throw new Error("Unknown node type:", node.type); } } function buildMatchGraph(syntaxTree2, ref) { if (typeof syntaxTree2 === "string") { syntaxTree2 = parse(syntaxTree2); } return { type: "MatchGraph", match: buildMatchGraphInternal(syntaxTree2), syntax: ref || null, source: syntaxTree2 }; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/match.js var { hasOwnProperty: hasOwnProperty3 } = Object.prototype; var STUB = 0; var TOKEN = 1; var OPEN_SYNTAX = 2; var CLOSE_SYNTAX = 3; var EXIT_REASON_MATCH = "Match"; var EXIT_REASON_MISMATCH = "Mismatch"; var EXIT_REASON_ITERATION_LIMIT = "Maximum iteration number exceeded (please fill an issue on https://github.com/csstree/csstree/issues)"; var ITERATION_LIMIT = 15e3; var totalIterationCount = 0; function reverseList(list) { let prev = null; let next = null; let item = list; while (item !== null) { next = item.prev; item.prev = prev; prev = item; item = next; } return prev; } function areStringsEqualCaseInsensitive(testStr, referenceStr) { if (testStr.length !== referenceStr.length) { return false; } for (let i = 0; i < testStr.length; i++) { const referenceCode = referenceStr.charCodeAt(i); let testCode = testStr.charCodeAt(i); if (testCode >= 65 && testCode <= 90) { testCode = testCode | 32; } if (testCode !== referenceCode) { return false; } } return true; } function isContextEdgeDelim(token) { if (token.type !== Delim) { return false; } return token.value !== "?"; } function isCommaContextStart(token) { if (token === null) { return true; } return token.type === Comma || token.type === Function2 || token.type === LeftParenthesis || token.type === LeftSquareBracket || token.type === LeftCurlyBracket || isContextEdgeDelim(token); } function isCommaContextEnd(token) { if (token === null) { return true; } return token.type === RightParenthesis || token.type === RightSquareBracket || token.type === RightCurlyBracket || token.type === Delim && token.value === "/"; } function internalMatch(tokens, state, syntaxes) { function moveToNextToken() { do { tokenIndex++; token = tokenIndex < tokens.length ? tokens[tokenIndex] : null; } while (token !== null && (token.type === WhiteSpace || token.type === Comment)); } function getNextToken(offset) { const nextIndex = tokenIndex + offset; return nextIndex < tokens.length ? tokens[nextIndex] : null; } function stateSnapshotFromSyntax(nextState, prev) { return { nextState, matchStack, syntaxStack, thenStack, tokenIndex, prev }; } function pushThenStack(nextState) { thenStack = { nextState, matchStack, syntaxStack, prev: thenStack }; } function pushElseStack(nextState) { elseStack = stateSnapshotFromSyntax(nextState, elseStack); } function addTokenToMatch() { matchStack = { type: TOKEN, syntax: state.syntax, token, prev: matchStack }; moveToNextToken(); syntaxStash = null; if (tokenIndex > longestMatch) { longestMatch = tokenIndex; } } function openSyntax() { syntaxStack = { syntax: state.syntax, opts: state.syntax.opts || syntaxStack !== null && syntaxStack.opts || null, prev: syntaxStack }; matchStack = { type: OPEN_SYNTAX, syntax: state.syntax, token: matchStack.token, prev: matchStack }; } function closeSyntax() { if (matchStack.type === OPEN_SYNTAX) { matchStack = matchStack.prev; } else { matchStack = { type: CLOSE_SYNTAX, syntax: syntaxStack.syntax, token: matchStack.token, prev: matchStack }; } syntaxStack = syntaxStack.prev; } let syntaxStack = null; let thenStack = null; let elseStack = null; let syntaxStash = null; let iterationCount = 0; let exitReason = null; let token = null; let tokenIndex = -1; let longestMatch = 0; let matchStack = { type: STUB, syntax: null, token: null, prev: null }; moveToNextToken(); while (exitReason === null && ++iterationCount < ITERATION_LIMIT) { switch (state.type) { case "Match": if (thenStack === null) { if (token !== null) { if (tokenIndex !== tokens.length - 1 || token.value !== "\\0" && token.value !== "\\9") { state = MISMATCH; break; } } exitReason = EXIT_REASON_MATCH; break; } state = thenStack.nextState; if (state === DISALLOW_EMPTY) { if (thenStack.matchStack === matchStack) { state = MISMATCH; break; } else { state = MATCH; } } while (thenStack.syntaxStack !== syntaxStack) { closeSyntax(); } thenStack = thenStack.prev; break; case "Mismatch": if (syntaxStash !== null && syntaxStash !== false) { if (elseStack === null || tokenIndex > elseStack.tokenIndex) { elseStack = syntaxStash; syntaxStash = false; } } else if (elseStack === null) { exitReason = EXIT_REASON_MISMATCH; break; } state = elseStack.nextState; thenStack = elseStack.thenStack; syntaxStack = elseStack.syntaxStack; matchStack = elseStack.matchStack; tokenIndex = elseStack.tokenIndex; token = tokenIndex < tokens.length ? tokens[tokenIndex] : null; elseStack = elseStack.prev; break; case "MatchGraph": state = state.match; break; case "If": if (state.else !== MISMATCH) { pushElseStack(state.else); } if (state.then !== MATCH) { pushThenStack(state.then); } state = state.match; break; case "MatchOnce": state = { type: "MatchOnceBuffer", syntax: state, index: 0, mask: 0 }; break; case "MatchOnceBuffer": { const terms = state.syntax.terms; if (state.index === terms.length) { if (state.mask === 0 || state.syntax.all) { state = MISMATCH; break; } state = MATCH; break; } if (state.mask === (1 << terms.length) - 1) { state = MATCH; break; } for (; state.index < terms.length; state.index++) { const matchFlag = 1 << state.index; if ((state.mask & matchFlag) === 0) { pushElseStack(state); pushThenStack({ type: "AddMatchOnce", syntax: state.syntax, mask: state.mask | matchFlag }); state = terms[state.index++]; break; } } break; } case "AddMatchOnce": state = { type: "MatchOnceBuffer", syntax: state.syntax, index: 0, mask: state.mask }; break; case "Enum": if (token !== null) { let name51 = token.value.toLowerCase(); if (name51.indexOf("\\") !== -1) { name51 = name51.replace(/\\[09].*$/, ""); } if (hasOwnProperty3.call(state.map, name51)) { state = state.map[name51]; break; } } state = MISMATCH; break; case "Generic": { const opts = syntaxStack !== null ? syntaxStack.opts : null; const lastTokenIndex2 = tokenIndex + Math.floor(state.fn(token, getNextToken, opts)); if (!isNaN(lastTokenIndex2) && lastTokenIndex2 > tokenIndex) { while (tokenIndex < lastTokenIndex2) { addTokenToMatch(); } state = MATCH; } else { state = MISMATCH; } break; } case "Type": case "Property": { const syntaxDict = state.type === "Type" ? "types" : "properties"; const dictSyntax = hasOwnProperty3.call(syntaxes, syntaxDict) ? syntaxes[syntaxDict][state.name] : null; if (!dictSyntax || !dictSyntax.match) { throw new Error( "Bad syntax reference: " + (state.type === "Type" ? "<" + state.name + ">" : "<'" + state.name + "'>") ); } if (syntaxStash !== false && token !== null && state.type === "Type") { const lowPriorityMatching = ( // https://drafts.csswg.org/css-values-4/#custom-idents // When parsing positionally-ambiguous keywords in a property value, a production // can only claim the keyword if no other unfulfilled production can claim it. state.name === "custom-ident" && token.type === Ident || // https://drafts.csswg.org/css-values-4/#lengths // ... if a `0` could be parsed as either a or a in a property (such as line-height), // it must parse as a state.name === "length" && token.value === "0" ); if (lowPriorityMatching) { if (syntaxStash === null) { syntaxStash = stateSnapshotFromSyntax(state, elseStack); } state = MISMATCH; break; } } openSyntax(); state = dictSyntax.matchRef || dictSyntax.match; break; } case "Keyword": { const name51 = state.name; if (token !== null) { let keywordName = token.value; if (keywordName.indexOf("\\") !== -1) { keywordName = keywordName.replace(/\\[09].*$/, ""); } if (areStringsEqualCaseInsensitive(keywordName, name51)) { addTokenToMatch(); state = MATCH; break; } } state = MISMATCH; break; } case "AtKeyword": case "Function": if (token !== null && areStringsEqualCaseInsensitive(token.value, state.name)) { addTokenToMatch(); state = MATCH; break; } state = MISMATCH; break; case "Token": if (token !== null && token.value === state.value) { addTokenToMatch(); state = MATCH; break; } state = MISMATCH; break; case "Comma": if (token !== null && token.type === Comma) { if (isCommaContextStart(matchStack.token)) { state = MISMATCH; } else { addTokenToMatch(); state = isCommaContextEnd(token) ? MISMATCH : MATCH; } } else { state = isCommaContextStart(matchStack.token) || isCommaContextEnd(token) ? MATCH : MISMATCH; } break; case "String": let string2 = ""; let lastTokenIndex = tokenIndex; for (; lastTokenIndex < tokens.length && string2.length < state.value.length; lastTokenIndex++) { string2 += tokens[lastTokenIndex].value; } if (areStringsEqualCaseInsensitive(string2, state.value)) { while (tokenIndex < lastTokenIndex) { addTokenToMatch(); } state = MATCH; } else { state = MISMATCH; } break; default: throw new Error("Unknown node type: " + state.type); } } totalIterationCount += iterationCount; switch (exitReason) { case null: console.warn("[csstree-match] BREAK after " + ITERATION_LIMIT + " iterations"); exitReason = EXIT_REASON_ITERATION_LIMIT; matchStack = null; break; case EXIT_REASON_MATCH: while (syntaxStack !== null) { closeSyntax(); } break; default: matchStack = null; } return { tokens, reason: exitReason, iterations: iterationCount, match: matchStack, longestMatch }; } function matchAsTree(tokens, matchGraph, syntaxes) { const matchResult = internalMatch(tokens, matchGraph, syntaxes || {}); if (matchResult.match === null) { return matchResult; } let item = matchResult.match; let host = matchResult.match = { syntax: matchGraph.syntax || null, match: [] }; const hostStack = [host]; item = reverseList(item).prev; while (item !== null) { switch (item.type) { case OPEN_SYNTAX: host.match.push(host = { syntax: item.syntax, match: [] }); hostStack.push(host); break; case CLOSE_SYNTAX: hostStack.pop(); host = hostStack[hostStack.length - 1]; break; default: host.match.push({ syntax: item.syntax || null, token: item.token.value, node: item.token.node }); } item = item.prev; } return matchResult; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/trace.js var trace_exports = {}; __export(trace_exports, { getTrace: () => getTrace, isKeyword: () => isKeyword, isProperty: () => isProperty, isType: () => isType }); function getTrace(node) { function shouldPutToTrace(syntax) { if (syntax === null) { return false; } return syntax.type === "Type" || syntax.type === "Property" || syntax.type === "Keyword"; } function hasMatch(matchNode) { if (Array.isArray(matchNode.match)) { for (let i = 0; i < matchNode.match.length; i++) { if (hasMatch(matchNode.match[i])) { if (shouldPutToTrace(matchNode.syntax)) { result.unshift(matchNode.syntax); } return true; } } } else if (matchNode.node === node) { result = shouldPutToTrace(matchNode.syntax) ? [matchNode.syntax] : []; return true; } return false; } let result = null; if (this.matched !== null) { hasMatch(this.matched); } return result; } function isType(node, type2) { return testNode(this, node, (match) => match.type === "Type" && match.name === type2); } function isProperty(node, property2) { return testNode(this, node, (match) => match.type === "Property" && match.name === property2); } function isKeyword(node) { return testNode(this, node, (match) => match.type === "Keyword"); } function testNode(match, node, fn) { const trace = getTrace.call(match, node); if (trace === null) { return false; } return trace.some(fn); } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/search.js function getFirstMatchNode(matchNode) { if ("node" in matchNode) { return matchNode.node; } return getFirstMatchNode(matchNode.match[0]); } function getLastMatchNode(matchNode) { if ("node" in matchNode) { return matchNode.node; } return getLastMatchNode(matchNode.match[matchNode.match.length - 1]); } function matchFragments(lexer2, ast, match, type2, name51) { function findFragments(matchNode) { if (matchNode.syntax !== null && matchNode.syntax.type === type2 && matchNode.syntax.name === name51) { const start = getFirstMatchNode(matchNode); const end = getLastMatchNode(matchNode); lexer2.syntax.walk(ast, function(node, item, list) { if (node === start) { const nodes = new List(); do { nodes.appendData(item.data); if (item.data === end) { break; } item = item.next; } while (item !== null); fragments.push({ parent: list, nodes }); } }); } if (Array.isArray(matchNode.match)) { matchNode.match.forEach(findFragments); } } const fragments = []; if (match.matched !== null) { findFragments(match.matched); } return fragments; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/structure.js var { hasOwnProperty: hasOwnProperty4 } = Object.prototype; function isValidNumber(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value && value >= 0; } function isValidLocation(loc) { return Boolean(loc) && isValidNumber(loc.offset) && isValidNumber(loc.line) && isValidNumber(loc.column); } function createNodeStructureChecker(type2, fields) { return function checkNode(node, warn) { if (!node || node.constructor !== Object) { return warn(node, "Type of node should be an Object"); } for (let key in node) { let valid = true; if (hasOwnProperty4.call(node, key) === false) { continue; } if (key === "type") { if (node.type !== type2) { warn(node, "Wrong node type `" + node.type + "`, expected `" + type2 + "`"); } } else if (key === "loc") { if (node.loc === null) { continue; } else if (node.loc && node.loc.constructor === Object) { if (typeof node.loc.source !== "string") { key += ".source"; } else if (!isValidLocation(node.loc.start)) { key += ".start"; } else if (!isValidLocation(node.loc.end)) { key += ".end"; } else { continue; } } valid = false; } else if (fields.hasOwnProperty(key)) { valid = false; for (let i = 0; !valid && i < fields[key].length; i++) { const fieldType = fields[key][i]; switch (fieldType) { case String: valid = typeof node[key] === "string"; break; case Boolean: valid = typeof node[key] === "boolean"; break; case null: valid = node[key] === null; break; default: if (typeof fieldType === "string") { valid = node[key] && node[key].type === fieldType; } else if (Array.isArray(fieldType)) { valid = node[key] instanceof List; } } } } else { warn(node, "Unknown field `" + key + "` for " + type2 + " node type"); } if (!valid) { warn(node, "Bad value for `" + type2 + "." + key + "`"); } } for (const key in fields) { if (hasOwnProperty4.call(fields, key) && hasOwnProperty4.call(node, key) === false) { warn(node, "Field `" + type2 + "." + key + "` is missed"); } } }; } function genTypesList(fieldTypes, path) { const docsTypes = []; for (let i = 0; i < fieldTypes.length; i++) { const fieldType = fieldTypes[i]; if (fieldType === String || fieldType === Boolean) { docsTypes.push(fieldType.name.toLowerCase()); } else if (fieldType === null) { docsTypes.push("null"); } else if (typeof fieldType === "string") { docsTypes.push(fieldType); } else if (Array.isArray(fieldType)) { docsTypes.push("List<" + (genTypesList(fieldType, path) || "any") + ">"); } else { throw new Error("Wrong value `" + fieldType + "` in `" + path + "` structure definition"); } } return docsTypes.join(" | "); } function processStructure(name51, nodeType) { const structure50 = nodeType.structure; const fields = { type: String, loc: true }; const docs = { type: '"' + name51 + '"' }; for (const key in structure50) { if (hasOwnProperty4.call(structure50, key) === false) { continue; } const fieldTypes = fields[key] = Array.isArray(structure50[key]) ? structure50[key].slice() : [structure50[key]]; docs[key] = genTypesList(fieldTypes, name51 + "." + key); } return { docs, check: createNodeStructureChecker(name51, fields) }; } function getStructureFromConfig(config) { const structure50 = {}; if (config.node) { for (const name51 in config.node) { if (hasOwnProperty4.call(config.node, name51)) { const nodeType = config.node[name51]; if (nodeType.structure) { structure50[name51] = processStructure(name51, nodeType); } else { throw new Error("Missed `structure` field in `" + name51 + "` node type definition"); } } } } return structure50; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/lexer/Lexer.js function dumpMapSyntax(map2, compact, syntaxAsAst) { const result = {}; for (const name51 in map2) { if (map2[name51].syntax) { result[name51] = syntaxAsAst ? map2[name51].syntax : generate(map2[name51].syntax, { compact }); } } return result; } function dumpAtruleMapSyntax(map2, compact, syntaxAsAst) { const result = {}; for (const [name51, atrule] of Object.entries(map2)) { result[name51] = { prelude: atrule.prelude && (syntaxAsAst ? atrule.prelude.syntax : generate(atrule.prelude.syntax, { compact })), descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst) }; } return result; } function valueHasVar(tokens) { for (let i = 0; i < tokens.length; i++) { if (tokens[i].value.toLowerCase() === "var(") { return true; } } return false; } function syntaxHasTopLevelCommaMultiplier(syntax) { const singleTerm = syntax.terms[0]; return syntax.explicit === false && syntax.terms.length === 1 && singleTerm.type === "Multiplier" && singleTerm.comma === true; } function buildMatchResult(matched, error, iterations) { return { matched, iterations, error, ...trace_exports }; } function matchSyntax(lexer2, syntax, value, useCssWideKeywords) { const tokens = prepare_tokens_default(value, lexer2.syntax); let result; if (valueHasVar(tokens)) { return buildMatchResult(null, new Error("Matching for a tree with var() is not supported")); } if (useCssWideKeywords) { result = matchAsTree(tokens, lexer2.cssWideKeywordsSyntax, lexer2); } if (!useCssWideKeywords || !result.match) { result = matchAsTree(tokens, syntax.match, lexer2); if (!result.match) { return buildMatchResult( null, new SyntaxMatchError(result.reason, syntax.syntax, value, result), result.iterations ); } } return buildMatchResult(result.match, null, result.iterations); } var Lexer = class { constructor(config, syntax, structure50) { this.cssWideKeywords = cssWideKeywords; this.syntax = syntax; this.generic = false; this.units = { ...units_exports }; this.atrules = /* @__PURE__ */ Object.create(null); this.properties = /* @__PURE__ */ Object.create(null); this.types = /* @__PURE__ */ Object.create(null); this.structure = structure50 || getStructureFromConfig(config); if (config) { if (config.cssWideKeywords) { this.cssWideKeywords = config.cssWideKeywords; } if (config.units) { for (const group of Object.keys(units_exports)) { if (Array.isArray(config.units[group])) { this.units[group] = config.units[group]; } } } if (config.types) { for (const [name51, type2] of Object.entries(config.types)) { this.addType_(name51, type2); } } if (config.generic) { this.generic = true; for (const [name51, value] of Object.entries(createGenericTypes(this.units))) { this.addType_(name51, value); } } if (config.atrules) { for (const [name51, atrule] of Object.entries(config.atrules)) { this.addAtrule_(name51, atrule); } } if (config.properties) { for (const [name51, property2] of Object.entries(config.properties)) { this.addProperty_(name51, property2); } } } this.cssWideKeywordsSyntax = buildMatchGraph(this.cssWideKeywords.join(" | ")); } checkStructure(ast) { function collectWarning(node, message) { warns.push({ node, message }); } const structure50 = this.structure; const warns = []; this.syntax.walk(ast, function(node) { if (structure50.hasOwnProperty(node.type)) { structure50[node.type].check(node, collectWarning); } else { collectWarning(node, "Unknown node type `" + node.type + "`"); } }); return warns.length ? warns : false; } createDescriptor(syntax, type2, name51, parent = null) { const ref = { type: type2, name: name51 }; const descriptor = { type: type2, name: name51, parent, serializable: typeof syntax === "string" || syntax && typeof syntax.type === "string", syntax: null, match: null, matchRef: null // used for properties when a syntax referenced as <'property'> in other syntax definitions }; if (typeof syntax === "function") { descriptor.match = buildMatchGraph(syntax, ref); } else { if (typeof syntax === "string") { Object.defineProperty(descriptor, "syntax", { get() { Object.defineProperty(descriptor, "syntax", { value: parse(syntax) }); return descriptor.syntax; } }); } else { descriptor.syntax = syntax; } Object.defineProperty(descriptor, "match", { get() { Object.defineProperty(descriptor, "match", { value: buildMatchGraph(descriptor.syntax, ref) }); return descriptor.match; } }); if (type2 === "Property") { Object.defineProperty(descriptor, "matchRef", { get() { const syntax2 = descriptor.syntax; const value = syntaxHasTopLevelCommaMultiplier(syntax2) ? buildMatchGraph({ ...syntax2, terms: [syntax2.terms[0].term] }, ref) : null; Object.defineProperty(descriptor, "matchRef", { value }); return value; } }); } } return descriptor; } addAtrule_(name51, syntax) { if (!syntax) { return; } this.atrules[name51] = { type: "Atrule", name: name51, prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, "AtrulePrelude", name51) : null, descriptors: syntax.descriptors ? Object.keys(syntax.descriptors).reduce( (map2, descName) => { map2[descName] = this.createDescriptor(syntax.descriptors[descName], "AtruleDescriptor", descName, name51); return map2; }, /* @__PURE__ */ Object.create(null) ) : null }; } addProperty_(name51, syntax) { if (!syntax) { return; } this.properties[name51] = this.createDescriptor(syntax, "Property", name51); } addType_(name51, syntax) { if (!syntax) { return; } this.types[name51] = this.createDescriptor(syntax, "Type", name51); } checkAtruleName(atruleName) { if (!this.getAtrule(atruleName)) { return new SyntaxReferenceError("Unknown at-rule", "@" + atruleName); } } checkAtrulePrelude(atruleName, prelude) { const error = this.checkAtruleName(atruleName); if (error) { return error; } const atrule = this.getAtrule(atruleName); if (!atrule.prelude && prelude) { return new SyntaxError("At-rule `@" + atruleName + "` should not contain a prelude"); } if (atrule.prelude && !prelude) { if (!matchSyntax(this, atrule.prelude, "", false).matched) { return new SyntaxError("At-rule `@" + atruleName + "` should contain a prelude"); } } } checkAtruleDescriptorName(atruleName, descriptorName) { const error = this.checkAtruleName(atruleName); if (error) { return error; } const atrule = this.getAtrule(atruleName); const descriptor = keyword(descriptorName); if (!atrule.descriptors) { return new SyntaxError("At-rule `@" + atruleName + "` has no known descriptors"); } if (!atrule.descriptors[descriptor.name] && !atrule.descriptors[descriptor.basename]) { return new SyntaxReferenceError("Unknown at-rule descriptor", descriptorName); } } checkPropertyName(propertyName2) { if (!this.getProperty(propertyName2)) { return new SyntaxReferenceError("Unknown property", propertyName2); } } matchAtrulePrelude(atruleName, prelude) { const error = this.checkAtrulePrelude(atruleName, prelude); if (error) { return buildMatchResult(null, error); } const atrule = this.getAtrule(atruleName); if (!atrule.prelude) { return buildMatchResult(null, null); } return matchSyntax(this, atrule.prelude, prelude || "", false); } matchAtruleDescriptor(atruleName, descriptorName, value) { const error = this.checkAtruleDescriptorName(atruleName, descriptorName); if (error) { return buildMatchResult(null, error); } const atrule = this.getAtrule(atruleName); const descriptor = keyword(descriptorName); return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false); } matchDeclaration(node) { if (node.type !== "Declaration") { return buildMatchResult(null, new Error("Not a Declaration node")); } return this.matchProperty(node.property, node.value); } matchProperty(propertyName2, value) { if (property(propertyName2).custom) { return buildMatchResult(null, new Error("Lexer matching doesn't applicable for custom properties")); } const error = this.checkPropertyName(propertyName2); if (error) { return buildMatchResult(null, error); } return matchSyntax(this, this.getProperty(propertyName2), value, true); } matchType(typeName2, value) { const typeSyntax = this.getType(typeName2); if (!typeSyntax) { return buildMatchResult(null, new SyntaxReferenceError("Unknown type", typeName2)); } return matchSyntax(this, typeSyntax, value, false); } match(syntax, value) { if (typeof syntax !== "string" && (!syntax || !syntax.type)) { return buildMatchResult(null, new SyntaxReferenceError("Bad syntax")); } if (typeof syntax === "string" || !syntax.match) { syntax = this.createDescriptor(syntax, "Type", "anonymous"); } return matchSyntax(this, syntax, value, false); } findValueFragments(propertyName2, value, type2, name51) { return matchFragments(this, value, this.matchProperty(propertyName2, value), type2, name51); } findDeclarationValueFragments(declaration, type2, name51) { return matchFragments(this, declaration.value, this.matchDeclaration(declaration), type2, name51); } findAllFragments(ast, type2, name51) { const result = []; this.syntax.walk(ast, { visit: "Declaration", enter: (declaration) => { result.push.apply(result, this.findDeclarationValueFragments(declaration, type2, name51)); } }); return result; } getAtrule(atruleName, fallbackBasename = true) { const atrule = keyword(atruleName); const atruleEntry = atrule.vendor && fallbackBasename ? this.atrules[atrule.name] || this.atrules[atrule.basename] : this.atrules[atrule.name]; return atruleEntry || null; } getAtrulePrelude(atruleName, fallbackBasename = true) { const atrule = this.getAtrule(atruleName, fallbackBasename); return atrule && atrule.prelude || null; } getAtruleDescriptor(atruleName, name51) { return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators ? this.atrules[atruleName].declarators[name51] || null : null; } getProperty(propertyName2, fallbackBasename = true) { const property2 = property(propertyName2); const propertyEntry = property2.vendor && fallbackBasename ? this.properties[property2.name] || this.properties[property2.basename] : this.properties[property2.name]; return propertyEntry || null; } getType(name51) { return hasOwnProperty.call(this.types, name51) ? this.types[name51] : null; } validate() { function syntaxRef(name51, isType2) { return isType2 ? `<${name51}>` : `<'${name51}'>`; } function validate(syntax, name51, broken, descriptor) { if (broken.has(name51)) { return broken.get(name51); } broken.set(name51, false); if (descriptor.syntax !== null) { walk(descriptor.syntax, function(node) { if (node.type !== "Type" && node.type !== "Property") { return; } const map2 = node.type === "Type" ? syntax.types : syntax.properties; const brokenMap = node.type === "Type" ? brokenTypes : brokenProperties; if (!hasOwnProperty.call(map2, node.name)) { errors.push(`${syntaxRef(name51, broken === brokenTypes)} used missed syntax definition ${syntaxRef(node.name, node.type === "Type")}`); broken.set(name51, true); } else if (validate(syntax, node.name, brokenMap, map2[node.name])) { errors.push(`${syntaxRef(name51, broken === brokenTypes)} used broken syntax definition ${syntaxRef(node.name, node.type === "Type")}`); broken.set(name51, true); } }, this); } } const errors = []; let brokenTypes = /* @__PURE__ */ new Map(); let brokenProperties = /* @__PURE__ */ new Map(); for (const key in this.types) { validate(this, key, brokenTypes, this.types[key]); } for (const key in this.properties) { validate(this, key, brokenProperties, this.properties[key]); } const brokenTypesArray = [...brokenTypes.keys()].filter((name51) => brokenTypes.get(name51)); const brokenPropertiesArray = [...brokenProperties.keys()].filter((name51) => brokenProperties.get(name51)); if (brokenTypesArray.length || brokenPropertiesArray.length) { return { errors, types: brokenTypesArray, properties: brokenPropertiesArray }; } return null; } dump(syntaxAsAst, pretty) { return { generic: this.generic, cssWideKeywords: this.cssWideKeywords, units: this.units, types: dumpMapSyntax(this.types, !pretty, syntaxAsAst), properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst), atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst) }; } toString() { return JSON.stringify(this.dump()); } }; // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/syntax/config/mix.js function appendOrSet(a, b) { if (typeof b === "string" && /^\s*\|/.test(b)) { return typeof a === "string" ? a + b : b.replace(/^\s*\|\s*/, ""); } return b || null; } function sliceProps(obj, props) { const result = /* @__PURE__ */ Object.create(null); for (const [key, value] of Object.entries(obj)) { if (value) { result[key] = {}; for (const prop of Object.keys(value)) { if (props.includes(prop)) { result[key][prop] = value[prop]; } } } } return result; } function mix(dest, src) { const result = { ...dest }; for (const [prop, value] of Object.entries(src)) { switch (prop) { case "generic": result[prop] = Boolean(value); break; case "cssWideKeywords": result[prop] = dest[prop] ? [...dest[prop], ...value] : value || []; break; case "units": result[prop] = { ...dest[prop] }; for (const [name51, patch] of Object.entries(value)) { result[prop][name51] = Array.isArray(patch) ? patch : []; } break; case "atrules": result[prop] = { ...dest[prop] }; for (const [name51, atrule] of Object.entries(value)) { const exists = result[prop][name51] || {}; const current = result[prop][name51] = { prelude: exists.prelude || null, descriptors: { ...exists.descriptors } }; if (!atrule) { continue; } current.prelude = atrule.prelude ? appendOrSet(current.prelude, atrule.prelude) : current.prelude || null; for (const [descriptorName, descriptorValue] of Object.entries(atrule.descriptors || {})) { current.descriptors[descriptorName] = descriptorValue ? appendOrSet(current.descriptors[descriptorName], descriptorValue) : null; } if (!Object.keys(current.descriptors).length) { current.descriptors = null; } } break; case "types": case "properties": result[prop] = { ...dest[prop] }; for (const [name51, syntax] of Object.entries(value)) { result[prop][name51] = appendOrSet(result[prop][name51], syntax); } break; case "scope": case "features": result[prop] = { ...dest[prop] }; for (const [name51, props] of Object.entries(value)) { result[prop][name51] = { ...result[prop][name51], ...props }; } break; case "parseContext": result[prop] = { ...dest[prop], ...value }; break; case "atrule": case "pseudo": result[prop] = { ...dest[prop], ...sliceProps(value, ["parse"]) }; break; case "node": result[prop] = { ...dest[prop], ...sliceProps(value, ["name", "structure", "parse", "generate", "walkContext"]) }; break; } } return result; } // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/lib/syntax/create.js function createSyntax(config) { const parse53 = createParser(config); const walk3 = createWalker(config); const generate52 = createGenerator(config); const { fromPlainObject: fromPlainObject2, toPlainObject: toPlainObject2 } = createConvertor(walk3); const syntax = { lexer: null, createLexer: (config2) => new Lexer(config2, syntax, syntax.lexer.structure), tokenize, parse: parse53, generate: generate52, walk: walk3, find: walk3.find, findLast: walk3.findLast, findAll: walk3.findAll, fromPlainObject: fromPlainObject2, toPlainObject: toPlainObject2, fork(extension) { const base3 = mix({}, config); return createSyntax( typeof extension === "function" ? extension(base3) : mix(base3, extension) ); } }; syntax.lexer = new Lexer({ generic: config.generic, cssWideKeywords: config.cssWideKeywords, units: config.units, types: config.types, atrules: config.atrules, properties: config.properties, node: config.node }, syntax); return syntax; } var create_default = (config) => createSyntax(mix({}, config)); // node_modules/.pnpm/css-tree@3.1.0/node_modules/css-tree/dist/data.js var data_default = { "generic": true, "cssWideKeywords": [ "initial", "inherit", "unset", "revert", "revert-layer" ], "units": { "angle": [ "deg", "grad", "rad", "turn" ], "decibel": [ "db" ], "flex": [ "fr" ], "frequency": [ "hz", "khz" ], "length": [ "cm", "mm", "q", "in", "pt", "pc", "px", "em", "rem", "ex", "rex", "cap", "rcap", "ch", "rch", "ic", "ric", "lh", "rlh", "vw", "svw", "lvw", "dvw", "vh", "svh", "lvh", "dvh", "vi", "svi", "lvi", "dvi", "vb", "svb", "lvb", "dvb", "vmin", "svmin", "lvmin", "dvmin", "vmax", "svmax", "lvmax", "dvmax", "cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax" ], "resolution": [ "dpi", "dpcm", "dppx", "x" ], "semitones": [ "st" ], "time": [ "s", "ms" ] }, "types": { "abs()": "abs( )", "absolute-size": "xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large", "acos()": "acos( )", "alpha-value": "|", "angle-percentage": "|", "angular-color-hint": "", "angular-color-stop": "&&?", "angular-color-stop-list": "[ [, ]?]# , ", "animateable-feature": "scroll-position|contents|", "asin()": "asin( )", "atan()": "atan( )", "atan2()": "atan2( , )", "attachment": "scroll|fixed|local", "attr()": "attr( ? [, ]? )", "attr-matcher": "['~'|'|'|'^'|'$'|'*']? '='", "attr-modifier": "i|s", "attribute-selector": "'[' ']'|'[' [|] ? ']'", "auto-repeat": "repeat( [auto-fill|auto-fit] , [? ]+ ? )", "auto-track-list": "[? [|]]* ? [? [|]]* ?", "axis": "block|inline|x|y", "baseline-position": "[first|last]? baseline", "basic-shape": "||||||", "bg-image": "none|", "bg-layer": "|| [/ ]?||||||||", "bg-position": "[[left|center|right|top|bottom|]|[left|center|right|] [top|center|bottom|]|[center|[left|right] ?]&&[center|[top|bottom] ?]]", "bg-size": "[|auto]{1,2}|cover|contain", "blur()": "blur( )", "blend-mode": "normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity", "box": "border-box|padding-box|content-box", "brightness()": "brightness( )", "calc()": "calc( )", "calc-sum": " [['+'|'-'] ]*", "calc-product": " ['*' |'/' ]*", "calc-value": "||||( )", "calc-constant": "e|pi|infinity|-infinity|NaN", "cf-final-image": "|", "cf-mixing-image": "?&&", "circle()": "circle( []? [at ]? )", "clamp()": "clamp( #{3} )", "class-selector": "'.' ", "clip-source": "", "color": "|currentColor||||<-non-standard-color>", "color-stop": "|", "color-stop-angle": "{1,2}", "color-stop-length": "{1,2}", "color-stop-list": "[ [, ]?]# , ", "color-interpolation-method": "in [| ?|]", "combinator": "'>'|'+'|'~'|['|' '|']", "common-lig-values": "[common-ligatures|no-common-ligatures]", "compat-auto": "searchfield|textarea|push-button|slider-horizontal|checkbox|radio|square-button|menulist|listbox|meter|progress-bar|button", "composite-style": "clear|copy|source-over|source-in|source-out|source-atop|destination-over|destination-in|destination-out|destination-atop|xor", "compositing-operator": "add|subtract|intersect|exclude", "compound-selector": "[? *]!", "compound-selector-list": "#", "complex-selector": " [? ]*", "complex-selector-list": "#", "conic-gradient()": "conic-gradient( [from ]? [at ]? , )", "contextual-alt-values": "[contextual|no-contextual]", "content-distribution": "space-between|space-around|space-evenly|stretch", "content-list": "[|contents||||||]+", "content-position": "center|start|end|flex-start|flex-end", "content-replacement": "", "contrast()": "contrast( [] )", "cos()": "cos( )", "counter": "|", "counter()": "counter( , ? )", "counter-name": "", "counter-style": "|symbols( )", "counter-style-name": "", "counters()": "counters( , , ? )", "cross-fade()": "cross-fade( , ? )", "cubic-bezier-timing-function": "ease|ease-in|ease-out|ease-in-out|cubic-bezier( , , , )", "deprecated-system-color": "ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText", "discretionary-lig-values": "[discretionary-ligatures|no-discretionary-ligatures]", "display-box": "contents|none", "display-inside": "flow|flow-root|table|flex|grid|ruby", "display-internal": "table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption|ruby-base|ruby-text|ruby-base-container|ruby-text-container", "display-legacy": "inline-block|inline-list-item|inline-table|inline-flex|inline-grid", "display-listitem": "?&&[flow|flow-root]?&&list-item", "display-outside": "block|inline|run-in", "drop-shadow()": "drop-shadow( {2,3} ? )", "east-asian-variant-values": "[jis78|jis83|jis90|jis04|simplified|traditional]", "east-asian-width-values": "[full-width|proportional-width]", "element()": "element( , [first|start|last|first-except]? )|element( )", "ellipse()": "ellipse( [{2}]? [at ]? )", "ending-shape": "circle|ellipse", "env()": "env( , ? )", "exp()": "exp( )", "explicit-track-list": "[? ]+ ?", "family-name": "|+", "feature-tag-value": " [|on|off]?", "feature-type": "@stylistic|@historical-forms|@styleset|@character-variant|@swash|@ornaments|@annotation", "feature-value-block": " '{' '}'", "feature-value-block-list": "+", "feature-value-declaration": " : + ;", "feature-value-declaration-list": "", "feature-value-name": "", "fill-rule": "nonzero|evenodd", "filter-function": "|||||||||", "filter-function-list": "[|]+", "final-bg-layer": "<'background-color'>|||| [/ ]?||||||||", "fixed-breadth": "", "fixed-repeat": "repeat( [] , [? ]+ ? )", "fixed-size": "|minmax( , )|minmax( , )", "font-stretch-absolute": "normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|", "font-variant-css21": "[normal|small-caps]", "font-weight-absolute": "normal|bold|", "frequency-percentage": "|", "general-enclosed": "[ ? )]|[( ? )]", "generic-family": "|||<-non-standard-generic-family>", "generic-name": "serif|sans-serif|cursive|fantasy|monospace", "geometry-box": "|fill-box|stroke-box|view-box", "gradient": "||||||<-legacy-gradient>", "grayscale()": "grayscale( )", "grid-line": "auto||[&&?]|[span&&[||]]", "historical-lig-values": "[historical-ligatures|no-historical-ligatures]", "hsl()": "hsl( [/ ]? )|hsl( , , , ? )", "hsla()": "hsla( [/ ]? )|hsla( , , , ? )", "hue": "|", "hue-rotate()": "hue-rotate( )", "hue-interpolation-method": "[shorter|longer|increasing|decreasing] hue", "hwb()": "hwb( [|none] [|none] [|none] [/ [|none]]? )", "hypot()": "hypot( # )", "image": "||||||", "image()": "image( ? [? , ?]! )", "image-set()": "image-set( # )", "image-set-option": "[|] [||type( )]", "image-src": "|", "image-tags": "ltr|rtl", "inflexible-breadth": "|min-content|max-content|auto", "inset()": "inset( {1,4} [round <'border-radius'>]? )", "invert()": "invert( )", "keyframes-name": "|", "keyframe-block": "# { }", "keyframe-block-list": "+", "keyframe-selector": "from|to|| ", "lab()": "lab( [||none] [||none] [||none] [/ [|none]]? )", "layer()": "layer( )", "layer-name": " ['.' ]*", "lch()": "lch( [||none] [||none] [|none] [/ [|none]]? )", "leader()": "leader( )", "leader-type": "dotted|solid|space|", "length-percentage": "|", "light-dark()": "light-dark( , )", "line-names": "'[' * ']'", "line-name-list": "[|]+", "line-style": "none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset", "line-width": "|thin|medium|thick", "linear-color-hint": "", "linear-color-stop": " ?", "linear-gradient()": "linear-gradient( [[|to ]||]? , )", "log()": "log( , ? )", "mask-layer": "|| [/ ]?||||||[|no-clip]||||", "mask-position": "[|left|center|right] [|top|center|bottom]?", "mask-reference": "none||", "mask-source": "", "masking-mode": "alpha|luminance|match-source", "matrix()": "matrix( #{6} )", "matrix3d()": "matrix3d( #{16} )", "max()": "max( # )", "media-and": " [and ]+", "media-condition": "|||", "media-condition-without-or": "||", "media-feature": "( [||] )", "media-in-parens": "( )||", "media-not": "not ", "media-or": " [or ]+", "media-query": "|[not|only]? [and ]?", "media-query-list": "#", "media-type": "", "mf-boolean": "", "mf-name": "", "mf-plain": " : ", "mf-range": " ['<'|'>']? '='? | ['<'|'>']? '='? | '<' '='? '<' '='? | '>' '='? '>' '='? ", "mf-value": "|||", "min()": "min( # )", "minmax()": "minmax( [|min-content|max-content|auto] , [||min-content|max-content|auto] )", "mod()": "mod( , )", "name-repeat": "repeat( [|auto-fill] , + )", "named-color": "transparent|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen", "namespace-prefix": "", "ns-prefix": "[|'*']? '|'", "number-percentage": "|", "numeric-figure-values": "[lining-nums|oldstyle-nums]", "numeric-fraction-values": "[diagonal-fractions|stacked-fractions]", "numeric-spacing-values": "[proportional-nums|tabular-nums]", "nth": "|even|odd", "opacity()": "opacity( [] )", "overflow-position": "unsafe|safe", "outline-radius": "|", "page-body": "? [; ]?| ", "page-margin-box": " '{' '}'", "page-margin-box-type": "@top-left-corner|@top-left|@top-center|@top-right|@top-right-corner|@bottom-left-corner|@bottom-left|@bottom-center|@bottom-right|@bottom-right-corner|@left-top|@left-middle|@left-bottom|@right-top|@right-middle|@right-bottom", "page-selector-list": "[#]?", "page-selector": "+| *", "page-size": "A5|A4|A3|B5|B4|JIS-B5|JIS-B4|letter|legal|ledger", "path()": "path( [ ,]? )", "paint()": "paint( , ? )", "perspective()": "perspective( [|none] )", "polygon()": "polygon( ? , [ ]# )", "polar-color-space": "hsl|hwb|lch|oklch", "position": "[[left|center|right]||[top|center|bottom]|[left|center|right|] [top|center|bottom|]?|[[left|right] ]&&[[top|bottom] ]]", "pow()": "pow( , )", "pseudo-class-selector": "':' |':' ')'", "pseudo-element-selector": "':' |", "pseudo-page": ": [left|right|first|blank]", "quote": "open-quote|close-quote|no-open-quote|no-close-quote", "radial-gradient()": "radial-gradient( [||]? [at ]? , )", "ratio": " [/ ]?", "ray()": "ray( &&?&&contain?&&[at ]? )", "ray-size": "closest-side|closest-corner|farthest-side|farthest-corner|sides", "rectangular-color-space": "srgb|srgb-linear|display-p3|a98-rgb|prophoto-rgb|rec2020|lab|oklab|xyz|xyz-d50|xyz-d65", "relative-selector": "? ", "relative-selector-list": "#", "relative-size": "larger|smaller", "rem()": "rem( , )", "repeat-style": "repeat-x|repeat-y|[repeat|space|round|no-repeat]{1,2}", "repeating-conic-gradient()": "repeating-conic-gradient( [from ]? [at ]? , )", "repeating-linear-gradient()": "repeating-linear-gradient( [|to ]? , )", "repeating-radial-gradient()": "repeating-radial-gradient( [||]? [at ]? , )", "reversed-counter-name": "reversed( )", "rgb()": "rgb( {3} [/ ]? )|rgb( {3} [/ ]? )|rgb( #{3} , ? )|rgb( #{3} , ? )", "rgba()": "rgba( {3} [/ ]? )|rgba( {3} [/ ]? )|rgba( #{3} , ? )|rgba( #{3} , ? )", "rotate()": "rotate( [|] )", "rotate3d()": "rotate3d( , , , [|] )", "rotateX()": "rotateX( [|] )", "rotateY()": "rotateY( [|] )", "rotateZ()": "rotateZ( [|] )", "round()": "round( ? , , )", "rounding-strategy": "nearest|up|down|to-zero", "saturate()": "saturate( )", "scale()": "scale( [|]#{1,2} )", "scale3d()": "scale3d( [|]#{3} )", "scaleX()": "scaleX( [|] )", "scaleY()": "scaleY( [|] )", "scaleZ()": "scaleZ( [|] )", "scroll()": "scroll( [||]? )", "scroller": "root|nearest|self", "self-position": "center|start|end|self-start|self-end|flex-start|flex-end", "shape-radius": "|closest-side|farthest-side", "sign()": "sign( )", "skew()": "skew( [|] , [|]? )", "skewX()": "skewX( [|] )", "skewY()": "skewY( [|] )", "sepia()": "sepia( )", "shadow": "inset?&&{2,4}&&?", "shadow-t": "[{2,3}&&?]", "shape": "rect( , , , )|rect( )", "shape-box": "|margin-box", "side-or-corner": "[left|right]||[top|bottom]", "sin()": "sin( )", "single-animation": "<'animation-duration'>||||<'animation-delay'>||||||||||[none|]||", "single-animation-direction": "normal|reverse|alternate|alternate-reverse", "single-animation-fill-mode": "none|forwards|backwards|both", "single-animation-iteration-count": "infinite|", "single-animation-play-state": "running|paused", "single-animation-timeline": "auto|none|||", "single-transition": "[none|]||