@nsnanocat/preference-panes 0.9.15 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -15
- package/dist/api.js +1454 -967
- package/dist/module/app.mjs +296 -412
- package/dist/module/index.html +1 -1
- package/dist/module/navigation.mjs +17 -28
- package/dist/preference-panes.mjs +259 -374
- package/dist/web.js +1202 -0
- package/package.json +1 -1
- package/src/api.mjs +191 -0
- package/src/browser/ModuleStatus.mjs +17 -28
- package/src/browser/Navigation.d.mts +12 -32
- package/src/browser/app.mjs +5 -7
- package/src/{lib → browser}/boxjs.mjs +72 -16
- package/src/browser/client.d.mts +44 -129
- package/src/browser/client.mjs +61 -179
- package/src/browser/index.d.ts +7 -11
- package/src/browser/index.mjs +15 -7
- package/src/browser/panel.mjs +31 -22
- package/src/build.mjs +2 -3
- package/src/index.d.ts +16 -2
- package/src/web.mjs +52 -0
- package/src/BoxJS.mjs +0 -72
- package/src/Store.mjs +0 -114
- package/src/lib/response.mjs +0 -16
- package/src/proxy/handler.mjs +0 -39
- package/src/proxy/response.mjs +0 -16
package/dist/api.js
CHANGED
|
@@ -341,1065 +341,820 @@
|
|
|
341
341
|
});
|
|
342
342
|
}
|
|
343
343
|
|
|
344
|
-
var assets = {"page":{"type":"text/html","body":"<!doctype html>\n<html lang=\"zh-CN\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1,viewport-fit=cover\">\n <meta name=\"color-scheme\" content=\"light dark\">\n <title>Module Preferences</title>\n <style>body { margin: 0; }</style>\n </head>\n <body>\n <main id=\"preferences\"></main>\n <script type=\"module\" src=\"/settings/assets/app.mjs?v=0.9.15\"></script>\n </body>\n</html>\n"},"/settings/assets/app.mjs":{"type":"text/javascript","body":"/**\n * 校验原始路径片段,不进行 URL 编码转换。\n * Validate raw path segments without URL encoding conversion.\n * @param {string[]} parts 原始路径片段 / Raw path segments.\n * @returns {string[]} 同一数组,不复制或修改 / The same array without copying or mutation.\n * @throws {TypeError} 空片段、非法字符或原型属性名 / Empty segments, invalid characters or prototype property names.\n */\nfunction validatePathParts(parts) {\n if (!parts.every(part => typeof part === \"string\" && /^[a-zA-Z0-9_-]+$/.test(part) && ![\"__proto__\", \"prototype\", \"constructor\"].includes(part))) throw new TypeError(\"Invalid key path\");\n return parts;\n}\n\n/**\n * BoxJS 的共同目录:模块、存储根和展示元数据都来自同一份 JSON。\n * Shared BoxJS catalog deriving modules, storage roots and metadata from one JSON document.\n */\nclass BoxJS {\n /**\n * 建立路径索引,不解析控件类型,也不读写持久化存储。\n * Index field paths without interpreting controls or accessing persistence.\n * @param {unknown} input 字段数组、单个 app 或 apps 订阅 / Field array, app or apps subscription.\n */\n constructor(input) {\n if (!input || typeof input !== \"object\") throw new TypeError(\"Expected BoxJS JSON\");\n const document = JSON.parse(JSON.stringify(input));\n const apps = Array.isArray(document) ? [{ settings: document }] : (document.apps ?? [document]);\n if (!Array.isArray(apps)) throw new TypeError(\"Expected BoxJS apps array\");\n this.modules = new Map();\n for (const app of apps) {\n if (!app || !Array.isArray(app.settings)) throw new TypeError(\"Expected BoxJS settings array\");\n for (const entry of app.settings) {\n if (typeof entry.id !== \"string\") throw new TypeError(\"BoxJS settings require string IDs\");\n if (!entry.id.startsWith(\"@\")) {\n if (Array.isArray(document)) throw new TypeError(\"BoxJS settings require @root.path IDs\");\n continue;\n }\n const [storageKey, ...parts] = entry.id.slice(1).split(\".\");\n if (!storageKey || storageKey.startsWith(\"@\") || parts.length < 2) throw new TypeError(\"A BoxJS setting must be below a literal storage root and module\");\n validatePathParts(parts);\n const module = parts[0];\n let target = this.modules.get(module);\n if (!target) {\n target = { module, storageKey, entries: [], owners: new Set() };\n this.modules.set(module, target);\n }\n if (target.storageKey !== storageKey) throw new TypeError(`A module must use one storage root: ${module}`);\n target.entries.push(entry);\n target.owners.add(app);\n }\n }\n this.metadata = metadata(Array.isArray(document) ? {} : document);\n for (const target of this.modules.values()) target.metadata = target.owners.size === 1 ? metadata([...target.owners][0]) : {};\n }\n\n /**\n * 取得本次导入的唯一模块,避免把模块数据变成项目目录。\n * Get the single imported module without turning module data into a project directory.\n * @returns {object} 唯一模块的目录项 / The single module entry.\n */\n get module() {\n if (this.modules.size !== 1) throw new TypeError(\"Import BoxJS JSON for exactly one module\");\n return this.modules.values().next().value;\n }\n}\n\n/**\n * 保留标准 BoxJS 展示信息;script 仅为元数据,不执行。\n * Retain standard BoxJS presentation data; script is metadata only and never executed.\n * @param {object} source BoxJS app 或订阅 / BoxJS app or subscription.\n * @returns {object} 经过类型检查的展示信息 / Type-checked presentation metadata.\n */\nfunction metadata(source) {\n const result = {};\n for (const key of [\"id\", \"name\", \"author\", \"repo\", \"script\", \"icon\", \"description\", \"desc\", \"icons\", \"descs\"]) {\n if (source[key] === undefined) continue;\n const multiple = key === \"icons\" || key === \"descs\";\n const values = multiple ? source[key] : [source[key]];\n if (!Array.isArray(values) || values.some(item => typeof item !== \"string\")) throw new TypeError(`Invalid BoxJS app ${key}`);\n result[key] = multiple ? [...values] : source[key];\n }\n return result;\n}\n\n/**\n * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。\n * Resolve module resource locations: headers override query parameters and module conventions.\n * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.\n * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.\n * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.\n */\nfunction pageInputs(url, headers = {}) {\n const match = /^\\/settings\\/([a-zA-Z0-9_-]+)\\/?$/.exec(url.pathname);\n if (!match) throw new TypeError(\"Open a concrete module URL\");\n const module = match[1];\n const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));\n const json = values[\"x-preferencepanes-json\"] ?? url.searchParams.get(\"json\") ?? `/configs/${module}`;\n const css = values[\"x-preferencepanes-css\"] ?? url.searchParams.get(\"css\") ?? \"\";\n if (!json.trim()) throw new TypeError(\"JSON resource URL is required\");\n return { url: url.href, module, json, css };\n}\n\n/**\n * 创建元素,所有展示文本通过 textContent 写入。\n * Create elements and assign display text through textContent only.\n * @template {keyof HTMLElementTagNameMap} T\n * @param {T} tag 元素标签 / Element tag.\n * @param {string} className 样式类名 / CSS class.\n * @param {string} [text] 纯文本 / Plain text.\n * @returns {HTMLElementTagNameMap[T]} 创建的元素 / Created element.\n */\nfunction element(tag, className, text) {\n const node = document.createElement(tag);\n node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n}\n\n/**\n * 创建通用设置行;外部 CSS 可通过 pp 类名覆盖视觉样式。\n * Create a generic settings row whose appearance can be overridden through pp classes.\n * @template {\"div\" | \"label\"} T\n * @param {T} tag 行元素 / Row element.\n * @returns {HTMLElementTagNameMap[T]} 设置行 / Settings row.\n */\nfunction settingRow(tag) {\n return element(tag, \"pp-row\");\n}\n\n/**\n * 为标准 HTML 输入控件添加通用面板类名。\n * Add the generic panel class to a standard HTML input control.\n * @param {HTMLElement} control 已创建的原生控件 / Existing native control.\n * @returns {HTMLElement} 输入控件 / Input control.\n */\nfunction fieldControl(control) {\n control.classList.add(\"pp-editor\");\n return control;\n}\n\n/**\n * 元数据地址只允许 HTTP(S) 和相对地址。\n * Allow only HTTP(S) and relative metadata addresses.\n * @param {string} value 元数据地址 / Metadata address.\n * @returns {string} 完整地址 / Absolute address.\n */\nfunction resourceURL(value) {\n const url = new URL(value, document.baseURI);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Metadata URLs must use HTTP(S)\");\n return url.href;\n}\n\n/**\n * 创建覆盖可用内容区的通用读取状态,失败时可附加重试动作。\n * Create a shared status view that fills the available content area and may include retry.\n * @param {string} message 状态文本 / Status message.\n * @param {(() => unknown) | undefined} [retry] 重试动作 / Retry action.\n * @returns {HTMLElement} 居中状态视图 / Centered status view.\n */\nfunction statusView(message, retry) {\n const view = element(\"section\", \"pp-status\");\n view.setAttribute(\"role\", \"status\");\n view.setAttribute(\"aria-live\", \"polite\");\n const spinner = element(\"span\", \"pp-status-spinner\");\n spinner.setAttribute(\"aria-hidden\", \"true\");\n view.append(spinner, element(\"p\", \"pp-status-message\", message));\n if (retry) {\n const button = element(\"button\", \"pp-status-action\", \"重新读取\");\n button.type = \"button\";\n button.onclick = retry;\n view.append(button);\n }\n return view;\n}\n\n/**\n * 请求宿主确认;独立网页使用浏览器对话框。\n * Request confirmation from the host, using the browser dialog for standalone pages.\n * @param {Window} host 模块窗口 / Module window.\n * @param {string} message 确认内容 / Confirmation message.\n * @returns {Promise<boolean>} 用户是否确认 / Whether the user confirmed.\n */\nfunction requestConfirmation(host, message) {\n return new Promise((resolve, reject) => {\n const frame = host.frameElement;\n if (frame) {\n const event = new frame.ownerDocument.defaultView.CustomEvent(\"preferencepanes:confirm\", { cancelable: true, detail: { message, resolve, reject } });\n if (!frame.dispatchEvent(event)) return;\n }\n resolve(host.confirm(message));\n });\n}\n\n/**\n * 共用三点按钮和底部操作菜单;弹层挂载到文档根部,不受标题栏显示状态影响。\n * Shared overflow trigger and bottom action sheet; the layer is mounted at document level and remains independent of header visibility.\n */\nclass ActionMenu {\n #button;\n #layer;\n #items;\n #select;\n #document;\n #disabled = true;\n #key = event => {\n if (event.key === \"Escape\" && !this.#layer.hidden) {\n event.preventDefault();\n this.close();\n this.#button.focus();\n }\n };\n\n /**\n * 创建菜单,操作逻辑由调用方提供。\n * Create a menu whose actions are handled by the caller.\n * @param {(id: string) => void} select 菜单选择回调 / Selection callback.\n */\n constructor(select) {\n this.#document = document;\n this.#select = select;\n this.element = document.createElement(\"span\");\n const triggerRoot = this.element.attachShadow({ mode: \"open\" });\n triggerRoot.innerHTML = `<style>\n :host{display:inline-flex;width:44px;height:44px;color:inherit}\n :host([hidden]){display:none!important}\n button{width:44px;height:44px;padding:10px;font:inherit;cursor:pointer;border:0;color:inherit;background:none}\n button:disabled{opacity:.4;cursor:default}\n button:focus-visible{outline:2px solid currentColor;outline-offset:-3px}\n svg{display:block;width:24px;height:24px;fill:currentColor}\n </style><button type=\"button\" aria-label=\"更多操作\" aria-haspopup=\"menu\" aria-expanded=\"false\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"4\" cy=\"12\" r=\"2\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><circle cx=\"20\" cy=\"12\" r=\"2\"/></svg></button>`;\n this.#button = triggerRoot.querySelector(\"button\");\n this.#layer = document.createElement(\"span\");\n const layerRoot = this.#layer.attachShadow({ mode: \"open\" });\n layerRoot.innerHTML = `<style>\n :host{position:fixed;inset:0;z-index:2147483647;color:var(--pp-text,CanvasText);font:16px/1.4 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif}\n :host([hidden]){display:none!important}\n *,*::before,*::after{box-sizing:border-box}\n button{font:inherit;cursor:pointer;border:0;color:inherit;background:none}\n button:focus-visible{outline:2px solid var(--pp-accent,Highlight);outline-offset:-3px}\n #backdrop{position:absolute;inset:0;width:100%;height:100%;padding:0;background:#0008;animation:pp-fade-in .18s ease-out}\n #sheet{position:absolute;z-index:1;left:0;right:0;bottom:0;width:100%;max-width:540px;max-height:calc(100% - 24px);margin:auto;padding:8px 8px calc(8px + env(safe-area-inset-bottom));animation:pp-sheet-in .22s cubic-bezier(.2,.8,.2,1)}\n #items,#cancel{overflow:hidden;background:var(--pp-surface,Canvas);border:1px solid var(--pp-border,#8884);border-radius:14px;box-shadow:0 8px 28px #0004}\n #items{max-height:calc(100vh - 116px - env(safe-area-inset-bottom));overflow-y:auto;-webkit-overflow-scrolling:touch}\n #items button,#cancel{display:block;width:100%;min-height:54px;padding:14px 18px;text-align:center}\n #items button+button{border-top:1px solid var(--pp-border,#8884)}\n #items button[data-danger]{color:var(--pp-danger,#e45656)}\n #cancel{margin-top:8px;color:var(--pp-accent,Highlight);font-weight:600}\n @keyframes pp-fade-in{from{opacity:0}}\n @keyframes pp-sheet-in{from{transform:translateY(100%)}}\n @media (prefers-reduced-motion:reduce){#backdrop,#sheet{animation:none}}\n </style><button id=\"backdrop\" type=\"button\" tabindex=\"-1\" aria-label=\"关闭菜单\"></button><section id=\"sheet\" role=\"dialog\" aria-modal=\"true\" aria-label=\"更多操作\"><div id=\"items\" role=\"menu\"></div><button id=\"cancel\" type=\"button\">取消</button></section>`;\n this.#items = layerRoot.querySelector(\"#items\");\n this.#button.onclick = () => (this.#layer.hidden ? this.open() : this.close());\n layerRoot.querySelector(\"#backdrop\").onclick = () => {\n this.close();\n this.#button.focus();\n };\n layerRoot.querySelector(\"#cancel\").onclick = () => {\n this.close();\n this.#button.focus();\n };\n this.#items.onkeydown = event => {\n const items = [...this.#items.children];\n const index = items.indexOf(layerRoot.activeElement);\n const offsets = { ArrowDown: 1, ArrowUp: -1 };\n if (event.key in offsets) {\n event.preventDefault();\n items[(index + offsets[event.key] + items.length) % items.length].focus();\n }\n };\n document.body.append(this.#layer);\n document.addEventListener(\"keydown\", this.#key);\n this.update([]);\n }\n\n /**\n * 同步可用操作和忙碌状态,不重建菜单触发按钮。\n * Update actions and busy state without replacing the trigger button.\n * @param {Array<{id: string, label: string, destructive?: boolean}>} items 操作列表 / Actions.\n * @param {boolean} [disabled] 是否忙碌 / Whether operations are busy.\n * @returns {void} 无返回值 / No return value.\n */\n update(items, disabled = false) {\n this.close();\n this.#disabled = disabled || items.length === 0;\n this.#button.disabled = this.#disabled;\n this.#items.replaceChildren(\n ...items.map(item => {\n const button = this.#document.createElement(\"button\");\n button.type = \"button\";\n button.setAttribute(\"role\", \"menuitem\");\n button.textContent = item.label;\n button.toggleAttribute(\"data-danger\", Boolean(item.destructive));\n button.onclick = () => {\n this.close();\n this.#select(item.id);\n };\n return button;\n }),\n );\n }\n\n /**\n * 打开当前操作菜单。\n * Open the current action sheet.\n * @returns {void} 无返回值 / No return value.\n */\n open() {\n if (this.#disabled) return;\n const style = getComputedStyle(this.element);\n for (const property of [\"--pp-text\", \"--pp-surface\", \"--pp-border\", \"--pp-accent\", \"--pp-danger\"]) {\n const value = style.getPropertyValue(property);\n if (value) this.#layer.style.setProperty(property, value);\n }\n this.#layer.hidden = false;\n this.#button.setAttribute(\"aria-expanded\", \"true\");\n this.#items.firstElementChild.focus();\n }\n\n /**\n * 关闭菜单。\n * Close the menu.\n * @returns {void} 无返回值 / No return value.\n */\n close() {\n this.#layer.hidden = true;\n this.#button.setAttribute(\"aria-expanded\", \"false\");\n }\n\n /**\n * 移除监听器与节点。\n * Remove listeners and elements.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#document.removeEventListener(\"keydown\", this.#key);\n this.#layer.remove();\n this.element.remove();\n }\n}\n\n/**\n * 将 BoxJS 数组、app 或订阅转换为模块字段,保留原文件为唯一字段来源。\n * Normalize a BoxJS array, app or subscription using the source JSON as the field authority.\n * @param {unknown | BoxJS} config BoxJS JSON 或已解析目录 / BoxJS document or parsed catalog.\n * @param {string} module API 第一段模块名 / First API path segment.\n * @returns {import(\"../index.js\").ModuleDefinition} 存储根和字段 / Storage root and fields.\n * @throws {TypeError} 配置结构、字段路径、默认值或展示属性无效 / Invalid configuration, field path, default or presentation attribute.\n */\nfunction normalizeBoxJs(config, module) {\n validatePathParts([module]);\n const catalog = config instanceof BoxJS ? config : new BoxJS(config);\n const target = catalog.modules.get(module);\n if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const { entries, storageKey, metadata } = target;\n const fields = [];\n for (const entry of entries) {\n const parts = entry.id.slice(1).split(\".\").slice(1);\n const type = { boolean: \"boolean\", checkboxes: \"array\", selects: \"select\", text: \"string\", textarea: \"string\", number: \"number\" }[entry.type];\n if (!type) throw new TypeError(`Unsupported BoxJS control: ${entry.type}`);\n const field = {\n key: parts.join(\".\"),\n type: type === \"select\" ? typeof entry.val : type,\n\n name: entry.name,\n description: entry.desc ?? \"\",\n control: entry.type,\n ...(entry.placeholder === undefined ? {} : { placeholder: entry.placeholder }),\n ...(entry.rows === undefined ? {} : { rows: entry.rows }),\n ...(entry.autoGrow === undefined ? {} : { autoGrow: entry.autoGrow }),\n };\n if (type === \"select\" && ![\"string\", \"number\", \"boolean\"].includes(field.type)) throw new TypeError(`Select requires a scalar val: ${entry.id}`);\n if (entry.items) field.options = entry.items.map(item => ({ key: item.key, label: item.label }));\n if (Object.hasOwn(entry, \"val\")) field.defaultValue = normalizeStoredValue(field, entry.val);\n if (\n typeof field.name !== \"string\" ||\n (field.placeholder !== undefined && typeof field.placeholder !== \"string\") ||\n (field.rows !== undefined && (!Number.isInteger(field.rows) || field.rows < 1)) ||\n (field.autoGrow !== undefined && typeof field.autoGrow !== \"boolean\") ||\n fields.some(other => other.key === field.key || other.key.startsWith(`${field.key}.`) || field.key.startsWith(`${other.key}.`))\n )\n throw new TypeError(`Invalid or overlapping BoxJS field: ${entry.id}`);\n if (field.options && (new Set(field.options.map(item => item.key)).size !== field.options.length || field.options.some(item => !scalar(item.key) || typeof item.label !== \"string\"))) throw new TypeError(`Invalid options: ${entry.id}`);\n if (Object.hasOwn(field, \"defaultValue\") && !validValue(field, field.defaultValue)) throw new TypeError(`Invalid BoxJS val: ${entry.id}`);\n fields.push(field);\n }\n if (!fields.length) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const common = fields[0].key.split(\".\").slice(0, -1);\n for (const field of fields) while (!field.key.startsWith(`${common.join(\".\")}.`)) common.pop();\n return {\n module,\n storageKey,\n fields,\n settingsPath: common,\n ...(Object.keys(metadata).length ? { metadata } : {}),\n };\n}\n\n/**\n * 归一化 BoxJS 的字符串存储值,不改变普通文本内容。\n * Normalize BoxJS string persistence without changing free-text values.\n * @param {import(\"../index.js\").SettingsField} field 前端字段约束 / Frontend field constraints.\n * @param {unknown} value 存储值 / Stored value.\n * @returns {unknown} 转换后的控件值;是否允许写入由 validValue 单独校验 / Converted control value; write eligibility is checked separately by validValue.\n */\nfunction normalizeStoredValue(field, value) {\n switch (field.type) {\n case \"boolean\":\n if (value === \"true\" || value === \"false\") return value === \"true\";\n break;\n case \"number\":\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n break;\n case \"array\":\n if (typeof value === \"string\") value = value === \"\" || value === \"[]\" ? [] : value.split(\",\");\n break;\n }\n if (field.options) {\n const match = item => field.options.find(option => String(option.key) === String(item))?.key ?? item;\n return field.type === \"array\" && Array.isArray(value) ? value.map(match) : match(value);\n }\n return value;\n}\n\n/**\n * 校验支持的标量范围,包括文本长度与数值有限性。\n * Validate supported scalar bounds, including text length and numeric finiteness.\n * @param {unknown} value 待检查值 / Value to inspect.\n * @returns {boolean} 是否为有效标量 / Whether the scalar is valid.\n */\nfunction scalar(value) {\n switch (typeof value) {\n case \"boolean\":\n return true;\n case \"string\":\n return value.length <= 2048;\n case \"number\":\n return Number.isFinite(value);\n default:\n return false;\n }\n}\n\n/**\n * 检查值类型、数组唯一性及声明的选项,不进行转换。\n * Check value type, array uniqueness and declared choices without coercion.\n * @param {import(\"../index.js\").SettingsField} field 前端归一化字段 / Normalized frontend field.\n * @param {unknown} value 待写入的 JSON 值 / JSON value to write.\n * @returns {boolean} 是否符合字段约束 / Whether the value satisfies field constraints.\n */\nfunction validValue(field, value) {\n if (field.type === \"array\") {\n if (!Array.isArray(value) || value.some(item => !scalar(item)) || new Set(value).size !== value.length) return false;\n } else if (typeof value !== field.type || !scalar(value)) return false;\n return !field.options || (field.type === \"array\" ? value : [value]).every(item => field.options.some(option => option.key === item));\n}\n\n/**\n * 单个模块的临时会话;离开页面后丢弃。\n * Transient module session discarded when leaving the page.\n * @typedef {object} ModuleSession\n * @property {AbortController} controller 读取请求的取消控制器 / Abort controller for reads.\n * @property {import(\"../index.js\").ModuleDefinition | null} definition 加载完成的配置,加载中为 null / Loaded configuration, or null while loading.\n * @property {import(\"./client.mjs\").ModuleSnapshot[\"values\"]} values 当前显示值 / Current display values.\n * @property {boolean} saving 是否正在写入 / Whether a mutation is in progress.\n */\n\n/**\n * 创建页面会话缓存;打开时重读,选项操作仅在 HTTP 200 后更新缓存。\n * Create a page-session cache; reload on open and mutate cache only after HTTP 200.\n * @param {import(\"./client.mjs\").PreferencesClientOptions} options 包内目录、请求与通知 / Internal catalog, requests and notifications.\n * @returns {import(\"./client.mjs\").PreferencesClient} 通用客户端 / Generic client.\n */\nfunction createPreferencesClient({ catalog, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {\n /**\n * 模块会话表\n * Module session map.\n * @type {Map<string, ModuleSession>}\n */\n const sessions = new Map();\n /**\n * 用 form 发送完整存储键;读取 404 交给调用方处理。\n * Send a complete storage key as form data; callers handle missing reads.\n * @param {string} path 完整 @root.path / Complete @root.path.\n * @param {\"get\" | \"set\" | \"delete\"} action 存储操作 / Storage operation.\n * @param {unknown} body set 值,其它操作忽略 / Set value, ignored by other operations.\n * @param {AbortSignal | undefined} signal 会话取消信号 / Session cancellation signal.\n * @returns {Promise<Response>} 未消费正文的响应 / Response with an unread body.\n * @throws {Error} 非 200 且非数据 GET 404、超时、取消或网络错误 / Non-200 status except missing-data GETs, timeout, cancellation or network error.\n */\n async function send(path, action, body, signal) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (signal?.aborted) abort();\n signal?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(abort, timeout);\n try {\n const response = await request(`/api/${action}`, {\n method: \"POST\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: controller.signal,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams([[path, action === \"set\" ? JSON.stringify(body) : \"\"]]).toString(),\n });\n if (response.status !== 200 && !(action === \"get\" && response.status === 404)) throw new Error(`HTTP ${response.status}`);\n return response;\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n }\n }\n /**\n * 获取独立快照,避免调用方修改内部缓存。\n * Return an independent snapshot so callers cannot mutate the cache.\n * @param {string} module 已打开模块 / Open module.\n * @returns {import(\"./client.mjs\").ModuleSnapshot} 会话快照 / Session snapshot.\n * @throws {Error} 模块未完成加载 / Module has not finished loading.\n */\n const snapshot = module => {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n return structuredClone({ definition: state.definition, values: state.values });\n };\n /**\n * 串行修改单键,仅成功后更新仍存活的会话。\n * Serialize single-key mutations and update a still-active session only after success.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 完整点分字段路径 / Complete dotted field path.\n * @param {\"set\" | \"delete\"} action 写入或删除 / Write or delete.\n * @param {unknown} value 写入值,删除时忽略 / Write value, ignored for deletion.\n * @param {\"write\" | \"delete\" | \"clearCaches\" | \"reset\"} [operation] 操作类型 / Operation kind.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n * @throws {Error} 会话、字段、值或请求错误 / Session, field, value or request error.\n */\n async function change(module, key, action, value, operation = action === \"set\" ? \"write\" : \"delete\") {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n if (state.saving) throw new Error(\"A settings write is already in progress\");\n const field = state.definition.fields.find(field => field.key === key);\n state.saving = true;\n try {\n if ((operation === \"write\" || operation === \"delete\") && (!field || (action === \"set\" && !validValue(field, value)))) throw new TypeError(\"Invalid setting value\");\n await send(`@${state.definition.storageKey}.${key}`, action, value);\n if (sessions.get(module) === state) {\n switch (operation) {\n case \"write\":\n state.values[key] = structuredClone(value);\n break;\n case \"delete\":\n case \"clearCaches\":\n case \"reset\":\n for (const candidate of state.definition.fields) {\n if (candidate.key !== key && !candidate.key.startsWith(`${key}.`)) continue;\n delete state.values[candidate.key];\n if (Object.hasOwn(candidate, \"defaultValue\")) state.values[candidate.key] = structuredClone(candidate.defaultValue);\n }\n break;\n }\n }\n notify({ kind: \"success\", operation, module, key });\n } catch (error) {\n notify({ kind: \"error\", operation, module, key, message: error.message });\n throw error;\n } finally {\n state.saving = false;\n }\n }\n return {\n /**\n * 从已导入的 JSON 创建新会话,只读取一次设置值。\n * Create a session from imported JSON and read stored settings once.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {Promise<import(\"./client.mjs\").ModuleSnapshot>} 新快照 / New snapshot.\n * @throws {Error} 读取失败、会话被替换或写入尚未完成 / Read failure, replaced session or unfinished write.\n */\n async open(module) {\n const binding = catalog.modules.get(module);\n if (!binding) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const previous = sessions.get(module);\n if (previous?.saving) throw new Error(\"Cannot refresh while saving\");\n previous?.controller.abort();\n const state = { controller: new AbortController(), definition: null, values: {}, saving: false };\n sessions.set(module, state);\n try {\n const definition = normalizeBoxJs(catalog, module);\n const response = await send(`@${definition.storageKey}.${definition.settingsPath.join(\".\")}`, \"get\", undefined, state.controller.signal);\n let subtree = response.status === 404 ? {} : await response.json();\n if (typeof subtree === \"string\") subtree = JSON.parse(subtree);\n if (!subtree || typeof subtree !== \"object\" || Array.isArray(subtree)) throw new TypeError(\"Expected a settings subtree object\");\n if (sessions.get(module) !== state) throw new Error(\"Module session was replaced\");\n state.definition = definition;\n for (const field of definition.fields) {\n const stored = field.key\n .split(\".\")\n .slice(definition.settingsPath.length)\n .reduce((parent, part) => Object(parent)[part], subtree);\n const value = stored === undefined ? field.defaultValue : stored;\n if (value !== undefined) state.values[field.key] = normalizeStoredValue(field, value);\n }\n return snapshot(module);\n } catch (error) {\n if (sessions.get(module) === state) sessions.delete(module);\n throw error;\n }\n },\n snapshot,\n /**\n * 按需重新读取模块 Settings,不更新页面会话缓存。\n * Reread module Settings on demand without updating the page-session cache.\n * @param {string} module 已打开的模块 / Open module.\n * @returns {Promise<unknown>} 设置值,缺失为 undefined / Settings value, or undefined when absent.\n */\n async readSettings(module) {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n const response = await send(`@${state.definition.storageKey}.${state.definition.settingsPath.join(\".\")}`, \"get\", undefined, state.controller.signal);\n return response.status === 404 ? undefined : response.json();\n },\n /**\n * 按需读取模块 Caches,不自动读取其它设置。\n * Read module Caches on demand without refreshing other settings.\n * @param {string} module 已打开的模块 / Open module.\n * @returns {Promise<unknown>} 缓存值,缺失为 undefined / Cache value, or undefined when absent.\n */\n async readCaches(module) {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n const response = await send(`@${state.definition.storageKey}.${module}.Caches`, \"get\", undefined, state.controller.signal);\n return response.status === 404 ? undefined : response.json();\n },\n /**\n * 删除整个 Caches 节点,成功后不追加 GET。\n * Delete the entire Caches node without a follow-up GET.\n * @param {string} module 已打开模块 / Open module.\n * @returns {Promise<void>} 清理完成 / Cleanup completion.\n */\n clearCaches: module => change(module, `${module}.Caches`, \"delete\", undefined, \"clearCaches\"),\n /**\n * 删除整个模块持久化节点,以当前 BoxJS 默认值重置页面缓存。\n * Delete module persistence and reset the page cache using current BoxJS defaults.\n * @param {string} module 已打开模块 / Open module.\n * @returns {Promise<void>} 重置完成 / Reset completion.\n */\n reset: module => change(module, module, \"delete\", undefined, \"reset\"),\n /**\n * 取消读取并清除会话,不撤销已发送的写入。\n * Abort reads and clear the session without undoing dispatched writes.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {void} 无返回值 / No return value.\n */\n leave(module) {\n sessions.get(module)?.controller.abort();\n sessions.delete(module);\n },\n /**\n * 写入单键并更新当前会话。\n * Write one key and update the current session.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 点分字段路径 / Dotted field path.\n * @param {import(\"../index.js\").SettingsScalar | import(\"../index.js\").SettingsScalar[]} value 字段值 / Field value.\n * @returns {Promise<void>} 写入完成 / Write completion.\n */\n set: (module, key, value) => change(module, key, \"set\", value),\n /**\n * 删除单键覆盖值并显示默认值。\n * Delete one override and display its default value.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 点分字段路径 / Dotted field path.\n * @returns {Promise<void>} 删除完成 / Delete completion.\n */\n remove: (module, key) => change(module, key, \"delete\"),\n };\n}\n\n/**\n * 同一文档内的主页/子页导航;iframe 各自的实例通过浏览器联合历史协作。\n * Navigate home/detail views within a document; iframe instances cooperate through joint browser history.\n */\nclass Navigation extends EventTarget {\n #container;\n #home;\n #create;\n #window;\n #key = null;\n #view;\n #retiring;\n #controller;\n #animation;\n #scroll = new WeakMap();\n #onHistory = () => this.#route();\n #onPageShow = event => {\n if (event.persisted) this.#route(true);\n };\n\n /**\n * 根视图始终保留;工厂按需提供子页,可用 signal 取消离开后的异步加载。\n * Retain the home view and create details on demand; signal cancels async work after departure.\n * @param {HTMLElement} container 由调用方布局的页面容器 / Caller-styled view container.\n * @param {HTMLElement} home 已创建的主页节点 / Existing home view.\n * @param {(key: string, signal: AbortSignal) => HTMLElement | undefined} create 子页工厂;未知路径返回 undefined / Detail factory; undefined for unknown routes.\n */\n constructor(container, home, create) {\n super();\n this.#container = container;\n this.#home = home;\n this.#create = create;\n this.#window = container.ownerDocument.defaultView;\n container.replaceChildren(home);\n this.#window.addEventListener(\"popstate\", this.#onHistory);\n this.#window.addEventListener(\"hashchange\", this.#onHistory);\n this.#window.addEventListener(\"pageshow\", this.#onPageShow);\n this.#route();\n }\n\n /**\n * 当前子页键;空字符串表示主页。\n * Current detail key; empty means home.\n */\n get current() {\n return this.#key;\n }\n\n /**\n * 是否可以返回上一级或先前文档。\n * Whether a parent view or previous document is available.\n */\n get canGoBack() {\n return Boolean(this.#key) || this.#window.history.length > 1;\n }\n\n /**\n * 加入子页历史;使用文档自身 URL,避免 srcdoc 按宿主 base URL 跳转。\n * Push a detail using the document URL, avoiding srcdoc navigation against the host base URL.\n * @param {string} key 子页键 / Detail key.\n * @returns {void} 无返回值 / No return value.\n */\n open(key) {\n if (key === this.#key) return;\n const url = new URL(this.#window.location.href);\n url.hash = encodeURIComponent(key);\n this.#window.history.pushState({ ...this.#window.history.state, preferencePanesRoute: key }, \"\", url.href);\n this.#route();\n }\n\n /**\n * 沿浏览器联合历史返回,根页可退回宿主或上个文档。\n * Go back through joint history, including a host or previous document from home.\n * @returns {void} 无返回值 / No return value.\n */\n back() {\n if (this.canGoBack) this.#window.history.back();\n }\n\n /**\n * 解析 URL 并统一处理页面切换、加载取消与动画结束后的释放。\n * Resolve the URL and coordinate transitions, cancellation and release after animation.\n * @param {boolean} [reload] 从页面缓存恢复时重新创建子页 / Recreate a detail after bfcache restoration.\n * @returns {void} 无返回值 / No return value.\n */\n #route(reload = false) {\n const url = new URL(this.#window.location.href);\n let key;\n try {\n key = decodeURIComponent(url.hash.slice(1));\n } catch (error) {\n if (!(error instanceof URIError)) throw error;\n key = \"\";\n }\n if (!reload && key === this.#key) return;\n this.#controller?.abort();\n this.#controller = new AbortController();\n const next = key ? this.#create(key, this.#controller.signal) : undefined;\n if (!next) key = \"\";\n const history = this.#window.history;\n // 直接打开子页时建立一次主页历史;刷新不重复堆叠。\n // Seed home history once for direct details, without stacking entries on reload.\n if (url.hash && history.state?.preferencePanesRoute !== key) {\n url.hash = \"\";\n history.replaceState({ ...history.state, preferencePanesRoute: \"\" }, \"\", url.href);\n if (key) {\n url.hash = encodeURIComponent(key);\n history.pushState({ ...history.state, preferencePanesRoute: key }, \"\", url.href);\n }\n }\n const previous = this.#view;\n const position = previous ? this.#window.getComputedStyle(previous).transform : \"none\";\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#retiring = previous;\n if (previous) {\n this.#scroll.set(previous, previous.scrollTop);\n previous.inert = true;\n }\n this.#key = key;\n this.#view = next;\n this.#home.inert = Boolean(next);\n if (next) {\n next.inert = false;\n this.#container.append(next);\n next.scrollTop = this.#scroll.get(next) ?? 0;\n }\n const moving = next ?? previous;\n if (moving) {\n const animation = moving.animate([{ transform: next ? \"translateX(100%)\" : position }, { transform: next ? \"translateX(0)\" : \"translateX(100%)\" }], { duration: this.#window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches ? 0 : 280, easing: \"cubic-bezier(.22,.61,.36,1)\", fill: \"forwards\" });\n this.#animation = animation;\n animation.onfinish = () => {\n if (this.#animation !== animation) return;\n this.#retiring?.remove();\n this.#retiring = undefined;\n animation.cancel();\n this.#animation = undefined;\n };\n }\n this.dispatchEvent(new Event(\"change\"));\n }\n\n /**\n * 释放监听器、加载、动画和节点;调用方可重新创建导航。\n * Release listeners, loads, animations and nodes so callers can recreate navigation.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#window.removeEventListener(\"popstate\", this.#onHistory);\n this.#window.removeEventListener(\"hashchange\", this.#onHistory);\n this.#window.removeEventListener(\"pageshow\", this.#onPageShow);\n this.#controller?.abort();\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#view?.remove();\n this.#home.remove();\n }\n}\n\n/**\n * 挂载已导入 BoxJS 对应的模块表单和短暂通知。\n * Mount the imported BoxJS module form and transient notifications.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../BoxJS.mjs\").BoxJS} catalog 包内 BoxJS 目录 / Internal BoxJS catalog.\n * @returns {import(\"./index.js\").MountedPreferences} 面板生命周期句柄 / Panel lifecycle handle.\n */\nfunction mountPanel(root, catalog) {\n const title = catalog.module.metadata.name ?? catalog.module.module;\n const document = root.ownerDocument;\n const window = document.defaultView;\n const shell = element(\"div\", \"pp-panel\");\n shell.dataset.module = catalog.module.module;\n const header = element(\"header\", \"pp-header\");\n const back = element(\"button\", \"pp-back\", \"‹\");\n back.setAttribute(\"aria-label\", \"返回\");\n back.type = \"button\";\n const heading = element(\"h1\", \"pp-title\", title);\n const handlers = new Map();\n const menuItems = [\n { id: \"viewSettings\", label: \"查看设置\" },\n { id: \"viewCaches\", label: \"查看缓存\" },\n { id: \"clearCaches\", label: \"清空缓存\", destructive: true },\n { id: \"reset\", label: \"重置设置\", destructive: true },\n ];\n const menu = new ActionMenu(id => runAction(id));\n const trailing = element(\"span\", \"pp-nav-spacer\");\n trailing.append(menu.element);\n const viewport = element(\"div\", \"pp-viewport\");\n let toast;\n header.append(back, heading, trailing);\n shell.append(header, viewport);\n root.append(shell);\n // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。\n // Embedded mode publishes navigation state without host reads or mutations of the module DOM.\n const publishNavigation = () => {\n const actions = handlers.size ? menuItems : [];\n menu.update(actions, saving);\n const frame = window.frameElement;\n if (!frame?.dataset.preferencePanes) return;\n frame.dispatchEvent(\n new frame.ownerDocument.defaultView.CustomEvent(\"preferencepanes:change\", {\n detail: { title: heading.textContent, module: catalog.module.module, busy: saving, canGoBack: !back.disabled, actions },\n }),\n );\n };\n const onAction = event => {\n if (!saving && handlers.has(event.detail)) runAction(event.detail);\n };\n window.frameElement?.addEventListener(\"preferencepanes:action\", onAction);\n let timer,\n navigation,\n generation = 0,\n active = null,\n saving = false,\n destroyed = false;\n /**\n * 展示短暂通知,不刷新设置数据。\n * Display a transient notification without refreshing settings.\n * @param {{kind: \"success\" | \"error\", operation?: \"write\" | \"delete\" | \"clearCaches\" | \"reset\", message?: string}} event 操作结果 / Operation result.\n * @returns {void} 无返回值 / No return value.\n */\n const notify = event => {\n if (destroyed) return;\n let message;\n switch (true) {\n case event.kind === \"error\":\n message = `操作失败:${event.message}`;\n break;\n case event.operation === \"delete\":\n message = \"删除成功\";\n break;\n case event.operation === \"clearCaches\":\n message = \"Caches 已清空\";\n break;\n case event.operation === \"reset\":\n message = \"设置已重置\";\n break;\n default:\n message = \"修改成功\";\n break;\n }\n // 宿主接管时不创建网页 Toast,也不运行其计时器。\n // A host-owned notice creates no web Toast and starts no local timer.\n const frame = window.frameElement;\n if (frame && !frame.dispatchEvent(new frame.ownerDocument.defaultView.CustomEvent(\"preferencepanes:notice\", { cancelable: true, detail: { kind: event.kind, message } }))) return;\n if (!toast) {\n toast = element(\"div\", \"pp-toast\");\n toast.setAttribute(\"role\", \"status\");\n shell.append(toast);\n }\n toast.textContent = message;\n toast.dataset.kind = event.kind;\n toast.hidden = false;\n clearTimeout(timer);\n timer = setTimeout(() => {\n toast.hidden = true;\n }, 2400);\n };\n const client = createPreferencesClient({ catalog, notify });\n /**\n * 两种菜单入口共用异步错误处理,包含宿主确认框错误。\n * Share async error handling between both menus, including host-dialog errors.\n * @param {string} id 操作标识 / Action identifier.\n * @returns {Promise<void>} 操作已处理 / Action handled.\n */\n async function runAction(id) {\n try {\n await handlers.get(id)();\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n }\n }\n /**\n * 打开模块并忽略已过期的异步结果。\n * Open a module and ignore stale asynchronous results.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.\n */\n async function open(module) {\n const version = ++generation;\n active = module;\n back.disabled = window.history.length <= 1;\n heading.textContent = module;\n publishNavigation();\n viewport.replaceChildren(statusView(\"读取设置…\"));\n try {\n await client.open(module);\n if (version === generation) controls();\n } catch (error) {\n if (version !== generation) return;\n viewport.replaceChildren(statusView(`加载失败:${error.message}`, () => open(module)));\n publishNavigation();\n }\n }\n /**\n * 从会话快照创建控件与操作按钮,不重新读取网络配置。\n * Build controls and actions from the session snapshot without fetching config again.\n * @returns {void} 无返回值 / No return value.\n */\n function controls() {\n const { definition, values } = client.snapshot(active);\n heading.textContent = definition.metadata?.name || active;\n const view = element(\"section\", \"pp-fields\");\n /**\n * 挂载后执行的多行高度更新\n * Textarea sizing callbacks run after mounting.\n * @type {Array<() => void>}\n */\n const growingInputs = [];\n const editors = new Map();\n const summaries = [];\n const groups = new Map();\n let queue = Promise.resolve(),\n pendingWrites = 0;\n /**\n * 导航组件处理页面切换,表单只更新当前标题与返回按钮。\n * Let navigation own transitions; the form only updates the title and back button.\n * @returns {void} 无返回值 / No return value.\n */\n const updateNavigation = () => {\n const editor = editors.get(navigation.current);\n heading.textContent = editor?.title ?? definition.metadata?.name ?? active;\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n };\n /**\n * 串行执行模块操作,保持输入可编辑。\n * Serialize module actions while keeping inputs editable.\n * @param {() => Promise<void>} action 请求或写入 / Request or mutation.\n * @param {() => void} success 成功后的局部更新 / Local update after success.\n * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n function perform(action, success, failure = () => {}) {\n pendingWrites++;\n saving = true;\n back.disabled = true;\n publishNavigation();\n return (queue = queue\n .then(action)\n .then(() => {\n if (!destroyed) success();\n })\n .catch(() => {\n /* 请求层已通知错误。\n * The request layer has already reported the error. */\n if (!destroyed) failure();\n })\n .finally(() => {\n pendingWrites--;\n saving = pendingWrites > 0;\n if (destroyed && !saving) client.leave(active);\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n }));\n }\n const metadata = definition.metadata;\n if (metadata) {\n const info = element(\"div\", \"pp-module-info\");\n const details = element(\"div\", \"pp-module-details\");\n for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(element(\"p\", \"pp-description\", description));\n if (metadata.repo) {\n const link = element(\"a\", \"pp-module-source\", \"项目主页\");\n link.href = resourceURL(metadata.repo);\n link.target = \"_blank\";\n link.rel = \"noopener noreferrer\";\n details.append(link);\n }\n info.append(details);\n view.append(info);\n }\n for (const field of definition.fields) {\n const match = /^\\[([^\\]]+)\\]\\s*(.*)$/.exec(field.name);\n const group = match?.[1] ?? \"通用\";\n if (!groups.has(group)) {\n const section = element(\"section\", \"pp-group\");\n const rows = element(\"div\", \"pp-rows\");\n section.append(element(\"h2\", \"pp-group-title\", group), rows);\n groups.set(group, rows);\n view.append(section);\n }\n const row = settingRow(\"div\");\n row.classList.add(\"pp-field\");\n const label = element(\"div\", \"pp-label\");\n label.append(element(\"span\", \"pp-field-name\", match?.[2] ?? field.name));\n if (field.description) label.append(element(\"span\", \"pp-field-description\", field.description));\n row.append(label);\n const value = values[field.key];\n /**\n * 读取尚未保存的输入\n * Read the unsaved input.\n * @type {() => unknown}\n */\n let read;\n /**\n * 更新当前控件\n * Update the current control.\n * @type {(value: unknown) => void}\n */\n let write;\n let inputContainer = row;\n let eventName = \"change\";\n switch (true) {\n case Boolean(field.options) && field.type !== \"array\": {\n const select = element(\"select\", \"\");\n select.setAttribute(\"aria-label\", field.name);\n field.options.forEach((option, index) => {\n const item = element(\"option\", \"\", option.label);\n item.value = String(index);\n select.append(item);\n });\n write = value => {\n select.selectedIndex = field.options.findIndex(option => option.key === value);\n };\n row.append(fieldControl(select));\n read = () => field.options[select.selectedIndex]?.key;\n break;\n }\n case field.type === \"array\" && Boolean(field.options): {\n const page = element(\"section\", \"pp-choice-page\");\n if (field.description) page.append(element(\"p\", \"pp-description\", field.description));\n const choices = element(\"div\", \"pp-rows\");\n page.append(choices);\n inputContainer = choices;\n editors.set(field.key, { node: page, title: match?.[2] ?? field.name });\n const summary = element(\"span\", \"pp-summary\");\n const link = element(\"button\", \"pp-choice-link\");\n link.type = \"button\";\n link.setAttribute(\"aria-label\", field.name);\n link.append(summary, element(\"span\", \"pp-chevron\", \"›\"));\n row.append(link);\n const refresh = () => {\n const value = client.snapshot(active).values[field.key];\n summary.textContent =\n field.options\n .filter(option => Array.isArray(value) && value.includes(option.key))\n .map(option => option.label)\n .join(\"、\") || \"未选择\";\n };\n summaries.push(refresh);\n refresh();\n link.onclick = () => navigation.open(field.key);\n row.addEventListener(\"click\", event => {\n if (!link.contains(event.target)) link.click();\n });\n const inputs = field.options.map(option => {\n const label = settingRow(\"label\");\n label.classList.add(\"pp-choice\");\n label.textContent = option.label;\n const input = element(\"input\", \"\");\n input.type = \"checkbox\";\n input.setAttribute(\"aria-label\", option.label);\n label.append(input);\n choices.append(label);\n return { input, key: option.key };\n });\n read = () => inputs.filter(option => option.input.checked).map(option => option.key);\n write = value => {\n for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);\n };\n break;\n }\n case field.type === \"boolean\": {\n const toggle = element(\"input\", \"pp-switch\");\n toggle.type = \"checkbox\";\n toggle.setAttribute(\"switch\", \"\");\n toggle.setAttribute(\"role\", \"switch\");\n toggle.setAttribute(\"aria-label\", field.name);\n write = value => {\n toggle.checked = value === true;\n };\n read = () => toggle.checked;\n row.append(toggle);\n break;\n }\n default: {\n const multiline = field.control === \"textarea\" || field.type === \"array\";\n const input = element(multiline ? \"textarea\" : \"input\", \"\");\n if (multiline) row.classList.add(\"pp-multiline\");\n input.setAttribute(\"aria-label\", field.name);\n if (field.placeholder) input.placeholder = field.placeholder;\n if (multiline && field.rows) input.rows = field.rows;\n /**\n * 在挂载后根据内容调整高度,同时保留基础行数。\n * Size mounted textareas to their contents while retaining baseline rows.\n * @returns {void} 无返回值 / No return value.\n */\n const grow = () => {\n if (!multiline || !field.autoGrow || !input.isConnected) return;\n input.style.height = \"auto\";\n const baseline = input.getBoundingClientRect().height;\n const style = window.getComputedStyle(input);\n const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);\n input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;\n };\n if (multiline && field.autoGrow) {\n input.addEventListener(\"input\", grow);\n growingInputs.push(grow);\n }\n eventName = \"input\";\n if (!multiline) input.type = field.type === \"number\" ? \"number\" : \"text\";\n write = value => {\n input.value = field.type === \"array\" ? JSON.stringify(value ?? []) : (value ?? \"\");\n grow();\n };\n read = () => {\n switch (field.type) {\n case \"array\":\n return JSON.parse(input.value);\n case \"number\":\n return input.value === \"\" ? Number.NaN : Number(input.value);\n default:\n return input.value;\n }\n };\n row.append(fieldControl(input));\n break;\n }\n }\n write(value);\n let inputVersion = 0;\n inputContainer.addEventListener(eventName, event => {\n if (event.isComposing) return;\n const version = ++inputVersion,\n module = active;\n let value;\n try {\n value = read();\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n return;\n }\n const restore = () => {\n if (version === inputVersion) write(client.snapshot(module).values[field.key]);\n };\n perform(\n () => client.set(module, field.key, value),\n () => {\n for (const refresh of summaries) refresh();\n },\n restore,\n );\n });\n if (eventName === \"input\") inputContainer.addEventListener(\"compositionend\", event => event.target.dispatchEvent(new window.Event(\"input\", { bubbles: true })));\n groups.get(group).append(row);\n }\n const settingsPage = element(\"section\", \"pp-settings-page\");\n const settingsOutput = element(\"pre\", \"pp-cache\");\n settingsOutput.setAttribute(\"aria-label\", \"Settings 内容\");\n settingsPage.append(settingsOutput);\n editors.set(\"$settings\", { node: settingsPage, title: \"设置\" });\n handlers.set(\"viewSettings\", () => {\n if (saving) return;\n let value;\n return perform(\n async () => {\n try {\n value = await client.readSettings(active);\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n throw error;\n }\n },\n () => {\n settingsOutput.textContent = value === undefined ? \"暂无设置\" : JSON.stringify(value, null, 2);\n navigation.open(\"$settings\");\n },\n );\n });\n const cachePage = element(\"section\", \"pp-cache-page\");\n const output = element(\"pre\", \"pp-cache\");\n output.textContent = \"暂无缓存\";\n output.setAttribute(\"aria-label\", \"Caches 内容\");\n cachePage.append(output);\n editors.set(\"$caches\", { node: cachePage, title: \"缓存\" });\n handlers.set(\"viewCaches\", () => {\n if (saving) return;\n let value;\n return perform(\n async () => {\n try {\n value = await client.readCaches(active);\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n throw error;\n }\n },\n () => {\n output.textContent = value === undefined ? \"暂无缓存\" : JSON.stringify(value, null, 2);\n navigation.open(\"$caches\");\n },\n );\n });\n handlers.set(\"clearCaches\", async () => {\n if (saving) return;\n if (!(await requestConfirmation(window, `清空 ${active} 的全部 Caches?`)) || destroyed || saving) return;\n return perform(\n () => client.clearCaches(active),\n () => {\n output.textContent = \"暂无缓存\";\n },\n );\n });\n handlers.set(\"reset\", async () => {\n if (saving) return;\n if (!(await requestConfirmation(window, `重置 ${active} 的设置?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) || destroyed || saving) return;\n return perform(() => client.reset(active), controls);\n });\n navigation?.destroy();\n navigation = new Navigation(viewport, view, key => editors.get(key)?.node);\n navigation.addEventListener(\"change\", updateNavigation);\n for (const grow of growingInputs) grow();\n updateNavigation();\n }\n /**\n * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。\n * Loaded forms delegate back to navigation; loading views can return to the previous document.\n * @returns {void} 无返回值 / No return value.\n */\n back.onclick = () => {\n if (saving) return;\n if (navigation) navigation.back();\n else window.history.back();\n };\n open(catalog.module.module);\n return {\n /**\n * 移除监听器、定时器、会话和挂载内容。\n * Remove listeners, timers, session and mounted content.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n destroyed = true;\n menu.destroy();\n window.frameElement?.removeEventListener(\"preferencepanes:action\", onAction);\n navigation?.destroy();\n generation++;\n if (active && !saving) client.leave(active);\n clearTimeout(timer);\n shell.remove();\n },\n };\n}\n\nvar defaults = \"/* 通用默认样式只使用 pp 命名空间;项目可通过 CSS 输入覆盖变量和组件。\\n * Generic defaults use only the pp namespace; projects may override variables and components through CSS input. */\\n.pp-panel {\\n --pp-text: #18191c;\\n --pp-background: #f6f7f8;\\n --pp-surface: #fff;\\n --pp-field: #f1f2f3;\\n --pp-border: #e3e5e7;\\n --pp-muted: #797f87;\\n --pp-accent: #1677ff;\\n font:\\n 15px / 1.5 -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n sans-serif;\\n color: var(--pp-text);\\n background: var(--pp-background);\\n position: relative;\\n display: flex;\\n flex-direction: column;\\n width: 100%;\\n max-width: 100vw;\\n min-width: 0;\\n height: 100vh;\\n overflow: hidden;\\n}\\n\\n:root[data-theme=\\\"dark\\\"] .pp-panel {\\n --pp-text: #f1f2f3;\\n --pp-background: #0d0e0f;\\n --pp-surface: #18191c;\\n --pp-field: #2f3238;\\n --pp-border: #2f3238;\\n --pp-muted: #9499a0;\\n}\\n.pp-panel * {\\n box-sizing: border-box;\\n letter-spacing: 0;\\n}\\n.pp-header {\\n flex: none;\\n height: calc(52px + env(safe-area-inset-top));\\n padding: env(safe-area-inset-top) 12px 0;\\n display: flex;\\n align-items: center;\\n background: var(--pp-surface);\\n border-bottom: 1px solid var(--pp-border);\\n position: relative;\\n z-index: 2;\\n}\\n.pp-title {\\n flex: 1;\\n text-align: center;\\n font-size: 17px;\\n font-weight: 500;\\n margin: 0;\\n min-width: 0;\\n overflow-wrap: anywhere;\\n}\\n.pp-nav-spacer {\\n width: 44px;\\n flex: none;\\n}\\n.pp-panel button {\\n font: inherit;\\n cursor: pointer;\\n border: 0;\\n background: none;\\n color: inherit;\\n}\\n.pp-panel .pp-back {\\n width: 44px;\\n height: 44px;\\n flex: none;\\n font-size: 34px;\\n line-height: 32px;\\n padding: 0;\\n}\\n.pp-panel button:disabled {\\n opacity: 0.5;\\n cursor: wait;\\n}\\n.pp-viewport {\\n position: relative;\\n flex: 1;\\n min-width: 0;\\n min-height: 0;\\n overflow: hidden;\\n}\\n:root[data-preference-panes-embedded] .pp-header {\\n display: none;\\n}\\n@supports (height: 100dvh) {\\n .pp-panel {\\n height: 100dvh;\\n }\\n}\\n.pp-fields,\\n.pp-choice-page,\\n.pp-settings-page,\\n.pp-cache-page {\\n position: absolute;\\n inset: 0;\\n min-width: 0;\\n overflow-x: hidden;\\n overflow-y: auto;\\n padding: 12px max(16px, calc((100% - 688px) / 2)) calc(28px + env(safe-area-inset-bottom) + var(--pp-keyboard-height, 0px));\\n scroll-padding-bottom: var(--pp-keyboard-height, 0px);\\n background: var(--pp-background);\\n}\\n.pp-choice-link {\\n display: flex;\\n align-items: center;\\n justify-content: flex-end;\\n gap: 8px;\\n max-width: 45%;\\n min-width: 44px;\\n min-height: 44px;\\n padding: 0;\\n text-align: right;\\n flex: 1;\\n}\\n.pp-summary {\\n color: var(--pp-muted);\\n font-size: 13px;\\n line-height: 18px;\\n display: -webkit-box;\\n -webkit-line-clamp: 2;\\n -webkit-box-orient: vertical;\\n overflow: hidden;\\n overflow-wrap: anywhere;\\n}\\n.pp-chevron {\\n color: var(--pp-muted);\\n font-size: 22px;\\n flex: none;\\n}\\n.pp-editor {\\n flex: none;\\n width: 45%;\\n min-width: 0;\\n min-height: 36px;\\n padding: 8px 10px;\\n font: inherit;\\n color: var(--pp-text);\\n background: var(--pp-field);\\n border: 0;\\n border-radius: 6px;\\n}\\n.pp-panel .pp-multiline {\\n display: block;\\n}\\n.pp-multiline .pp-editor {\\n width: 100%;\\n margin-top: 10px;\\n}\\n.pp-panel [hidden] {\\n display: none !important;\\n}\\n.pp-label {\\n flex: 1;\\n min-width: 0;\\n display: flex;\\n flex-direction: column;\\n align-items: flex-start;\\n margin-right: 16px;\\n}\\n.pp-field-name {\\n color: var(--pp-text);\\n font-size: 15px;\\n}\\n.pp-field-description {\\n margin-top: 2px;\\n color: var(--pp-muted);\\n font-size: 12px;\\n}\\n.pp-group {\\n margin-top: 16px;\\n}\\n.pp-group-title {\\n margin: 0 0 8px;\\n color: var(--pp-muted);\\n font-size: 15px;\\n font-weight: 400;\\n}\\n.pp-row {\\n min-width: 0;\\n min-height: 48px;\\n padding: 16px;\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n background: var(--pp-surface);\\n border-bottom: 1px solid var(--pp-border);\\n}\\n.pp-rows > :last-child {\\n border-bottom: 0 !important;\\n}\\n.pp-switch {\\n flex: none;\\n accent-color: var(--pp-accent);\\n}\\n.pp-choice {\\n justify-content: space-between;\\n cursor: pointer;\\n}\\n.pp-choice input {\\n width: 20px;\\n height: 20px;\\n flex: none;\\n accent-color: var(--pp-accent);\\n margin: 0;\\n}\\n.pp-description {\\n font-size: 12px;\\n line-height: 1.6;\\n color: var(--pp-muted);\\n white-space: pre-wrap;\\n overflow-wrap: anywhere;\\n}\\n.pp-module-info {\\n display: flex;\\n gap: 12px;\\n margin: 12px 0;\\n}\\n.pp-module-details {\\n min-width: 0;\\n overflow-wrap: anywhere;\\n}\\n.pp-module-source {\\n color: inherit;\\n text-decoration: underline;\\n}\\n.pp-status {\\n position: fixed;\\n inset: 0;\\n display: grid;\\n place-content: center;\\n justify-items: center;\\n gap: 12px;\\n min-width: 0;\\n min-height: 0;\\n margin: 0;\\n padding: 24px;\\n color: var(--pp-muted, GrayText);\\n text-align: center;\\n background: var(--pp-background, Canvas);\\n}\\n.pp-viewport > .pp-status {\\n position: absolute;\\n}\\n.pp-status-spinner {\\n box-sizing: border-box;\\n width: 28px;\\n height: 28px;\\n border: 3px solid color-mix(in srgb, currentColor 25%, transparent);\\n border-top-color: var(--pp-accent, AccentColor);\\n border-radius: 50%;\\n animation: pp-status-spin 0.8s linear infinite;\\n}\\n.pp-status-message {\\n max-width: 100%;\\n margin: 0;\\n overflow-wrap: anywhere;\\n}\\n.pp-status-action {\\n min-width: 96px;\\n min-height: 44px;\\n padding: 8px 16px;\\n border: 0;\\n border-radius: 6px;\\n color: var(--pp-text, ButtonText);\\n font: inherit;\\n cursor: pointer;\\n background: var(--pp-surface, ButtonFace);\\n}\\n@keyframes pp-status-spin {\\n to {\\n transform: rotate(1turn);\\n }\\n}\\n.pp-cache {\\n white-space: pre-wrap;\\n overflow-wrap: anywhere;\\n}\\n.pp-toast {\\n pointer-events: none;\\n position: fixed;\\n bottom: calc(30px + env(safe-area-inset-bottom));\\n left: 50%;\\n transform: translateX(-50%);\\n max-width: 90vw;\\n padding: 10px 16px;\\n border-radius: 8px;\\n background: #333e;\\n color: white;\\n font-size: 13px;\\n z-index: 20;\\n}\\n.pp-toast[data-kind=\\\"error\\\"] {\\n background: #8d2424;\\n}\\n.pp-panel :focus-visible {\\n outline: 2px solid var(--pp-accent);\\n outline-offset: -2px;\\n}\\n\";\n\nconst selector = \"style[data-preference-panes-defaults]\";\n\n/**\n * 在文档中安装一次默认样式,并标记当前调用方是否拥有该节点。\n * Install default styles once and report whether the current caller owns the node.\n * @param {Document} document 目标文档 / Target document.\n * @returns {{element: HTMLStyleElement, owned: boolean}} 样式节点及所有权 / Style node and ownership.\n */\nfunction installDefaultStyles(document) {\n const existing = document.head.querySelector(selector);\n if (existing) return { element: existing, owned: false };\n const element = document.createElement(\"style\");\n element.dataset.preferencePanesDefaults = \"\";\n element.textContent = defaults;\n document.head.append(element);\n return { element, owned: true };\n}\n\n/**\n * 挂载模块设置页;默认样式由包提供,可选 CSS 仅作用于当前模块。\n * Mount a module page with package defaults and optional module-scoped CSS.\n * @param {import(\"../index.js\").BoxJSInput} boxjs 单个模块的 BoxJS JSON / BoxJS JSON for one module.\n * @param {string} [css] 可选 CSS 正文 / Optional CSS text.\n * @returns {import(\"./index.js\").MountedPreferences} 模块生命周期句柄 / Module lifecycle handle.\n */\nfunction mount(boxjs, css = \"\") {\n if (typeof css !== \"string\") throw new TypeError(\"CSS must be a string\");\n const catalog = boxjs instanceof BoxJS ? boxjs : new BoxJS(boxjs);\n const metadata = catalog.module.metadata;\n const image = metadata.icon || metadata.icons?.[1] || metadata.icons?.[0];\n if (image) resourceURL(image);\n if (metadata.repo) resourceURL(metadata.repo);\n const existing = document.querySelector(\"#preferences\");\n const root = existing ?? element(\"main\", \"\");\n if (!existing) {\n root.id = \"preferences\";\n document.body.append(root);\n }\n const { element: base, owned: ownsBase } = installDefaultStyles(document);\n const custom = element(\"style\", \"\");\n custom.textContent = css;\n document.head.append(custom);\n const previousTitle = document.title;\n const previousTheme = document.documentElement.dataset.theme;\n const systemTheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n const previousKeyboard = document.documentElement.style.getPropertyValue(\"--pp-keyboard-height\");\n const host = window.frameElement?.ownerDocument.documentElement;\n /**\n * 跟随嵌入宿主的通用环境状态,不识别业务 App 或解析其 UA。\n * Follow generic host appearance without detecting a business app or parsing its user agent.\n * @returns {void} 已同步主题与键盘避让 / Theme and keyboard clearance synchronized.\n */\n const syncAppearance = () => {\n const theme = host?.dataset.theme ?? previousTheme ?? (systemTheme.matches ? \"dark\" : \"light\");\n document.documentElement.dataset.theme = theme;\n if (host) document.documentElement.style.setProperty(\"--pp-keyboard-height\", host.style.getPropertyValue(\"--pp-keyboard-height\"));\n };\n let observer;\n syncAppearance();\n systemTheme.addEventListener(\"change\", syncAppearance);\n if (host) {\n observer = new MutationObserver(syncAppearance);\n observer.observe(host, { attributes: true, attributeFilter: [\"data-theme\", \"style\"] });\n }\n document.title = metadata.name ?? catalog.module.module;\n let panel;\n const view = {\n /**\n * 释放模块视图、样式与会话,不操作项目入口页。\n * Release the module view, styles and session without operating a project landing page.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n observer?.disconnect();\n systemTheme.removeEventListener(\"change\", syncAppearance);\n panel?.destroy();\n if (ownsBase) base.remove();\n custom.remove();\n if (existing) root.replaceChildren();\n else root.remove();\n document.title = previousTitle;\n if (previousTheme === undefined) delete document.documentElement.dataset.theme;\n else document.documentElement.dataset.theme = previousTheme;\n document.documentElement.style.setProperty(\"--pp-keyboard-height\", previousKeyboard);\n },\n };\n try {\n root.replaceChildren();\n panel = mountPanel(root, catalog);\n return view;\n } catch (error) {\n view.destroy();\n throw error;\n }\n}\n\ninstallDefaultStyles(document);\nlet view;\n/**\n * 从 URL 或代理传递的 Header 导入 JSON/CSS,支持独立文档与 srcdoc。\n * Import JSON/CSS from the URL or proxy-carried headers in standalone and srcdoc documents.\n * @returns {Promise<void>} 启动完成 / Startup completion.\n */\nasync function start() {\n try {\n view?.destroy();\n view = undefined;\n document.querySelector(\"#preferences\").replaceChildren(statusView(\"读取设置…\"));\n const context = document.querySelector('meta[name=\"preference-panes-inputs\"]');\n const embedded = window.frameElement?.dataset.preferencePanes;\n let inputs;\n switch (true) {\n case embedded !== undefined:\n inputs = JSON.parse(embedded);\n document.documentElement.dataset.preferencePanesEmbedded = \"\";\n break;\n case context !== null:\n inputs = JSON.parse(decodeURIComponent(context.content));\n break;\n default:\n inputs = pageInputs(new URL(location.href));\n }\n const resources = [inputs.json, inputs.css].map(source => {\n if (!source) return null;\n const url = new URL(source, inputs.url);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Resources must use HTTP(S) URLs\");\n return url.href;\n });\n const [data, style] = await Promise.all(resources.map(url => (url ? fetch(url, { cache: \"no-store\", credentials: \"omit\" }) : null)));\n if (data.status !== 200 || (style && style.status !== 200)) throw new Error(`HTTP ${data.status !== 200 ? data.status : style.status}`);\n const catalog = new BoxJS(await data.json());\n if (catalog.module.module !== inputs.module) throw new Error(\"Imported JSON does not match the module URL\");\n view = mount(catalog, style ? await style.text() : \"\");\n } catch (error) {\n document.querySelector(\"#preferences\").replaceChildren(statusView(`加载失败:${error.message}`, start));\n }\n}\nstart();\nwindow.addEventListener(\"pageshow\", event => {\n if (event.persisted) start();\n});\n"},"/settings/assets/navigation.mjs":{"type":"text/javascript","body":"/**\n * 共用三点按钮和底部操作菜单;弹层挂载到文档根部,不受标题栏显示状态影响。\n * Shared overflow trigger and bottom action sheet; the layer is mounted at document level and remains independent of header visibility.\n */\nclass ActionMenu {\n #button;\n #layer;\n #items;\n #select;\n #document;\n #disabled = true;\n #key = event => {\n if (event.key === \"Escape\" && !this.#layer.hidden) {\n event.preventDefault();\n this.close();\n this.#button.focus();\n }\n };\n\n /**\n * 创建菜单,操作逻辑由调用方提供。\n * Create a menu whose actions are handled by the caller.\n * @param {(id: string) => void} select 菜单选择回调 / Selection callback.\n */\n constructor(select) {\n this.#document = document;\n this.#select = select;\n this.element = document.createElement(\"span\");\n const triggerRoot = this.element.attachShadow({ mode: \"open\" });\n triggerRoot.innerHTML = `<style>\n :host{display:inline-flex;width:44px;height:44px;color:inherit}\n :host([hidden]){display:none!important}\n button{width:44px;height:44px;padding:10px;font:inherit;cursor:pointer;border:0;color:inherit;background:none}\n button:disabled{opacity:.4;cursor:default}\n button:focus-visible{outline:2px solid currentColor;outline-offset:-3px}\n svg{display:block;width:24px;height:24px;fill:currentColor}\n </style><button type=\"button\" aria-label=\"更多操作\" aria-haspopup=\"menu\" aria-expanded=\"false\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"4\" cy=\"12\" r=\"2\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><circle cx=\"20\" cy=\"12\" r=\"2\"/></svg></button>`;\n this.#button = triggerRoot.querySelector(\"button\");\n this.#layer = document.createElement(\"span\");\n const layerRoot = this.#layer.attachShadow({ mode: \"open\" });\n layerRoot.innerHTML = `<style>\n :host{position:fixed;inset:0;z-index:2147483647;color:var(--pp-text,CanvasText);font:16px/1.4 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif}\n :host([hidden]){display:none!important}\n *,*::before,*::after{box-sizing:border-box}\n button{font:inherit;cursor:pointer;border:0;color:inherit;background:none}\n button:focus-visible{outline:2px solid var(--pp-accent,Highlight);outline-offset:-3px}\n #backdrop{position:absolute;inset:0;width:100%;height:100%;padding:0;background:#0008;animation:pp-fade-in .18s ease-out}\n #sheet{position:absolute;z-index:1;left:0;right:0;bottom:0;width:100%;max-width:540px;max-height:calc(100% - 24px);margin:auto;padding:8px 8px calc(8px + env(safe-area-inset-bottom));animation:pp-sheet-in .22s cubic-bezier(.2,.8,.2,1)}\n #items,#cancel{overflow:hidden;background:var(--pp-surface,Canvas);border:1px solid var(--pp-border,#8884);border-radius:14px;box-shadow:0 8px 28px #0004}\n #items{max-height:calc(100vh - 116px - env(safe-area-inset-bottom));overflow-y:auto;-webkit-overflow-scrolling:touch}\n #items button,#cancel{display:block;width:100%;min-height:54px;padding:14px 18px;text-align:center}\n #items button+button{border-top:1px solid var(--pp-border,#8884)}\n #items button[data-danger]{color:var(--pp-danger,#e45656)}\n #cancel{margin-top:8px;color:var(--pp-accent,Highlight);font-weight:600}\n @keyframes pp-fade-in{from{opacity:0}}\n @keyframes pp-sheet-in{from{transform:translateY(100%)}}\n @media (prefers-reduced-motion:reduce){#backdrop,#sheet{animation:none}}\n </style><button id=\"backdrop\" type=\"button\" tabindex=\"-1\" aria-label=\"关闭菜单\"></button><section id=\"sheet\" role=\"dialog\" aria-modal=\"true\" aria-label=\"更多操作\"><div id=\"items\" role=\"menu\"></div><button id=\"cancel\" type=\"button\">取消</button></section>`;\n this.#items = layerRoot.querySelector(\"#items\");\n this.#button.onclick = () => (this.#layer.hidden ? this.open() : this.close());\n layerRoot.querySelector(\"#backdrop\").onclick = () => {\n this.close();\n this.#button.focus();\n };\n layerRoot.querySelector(\"#cancel\").onclick = () => {\n this.close();\n this.#button.focus();\n };\n this.#items.onkeydown = event => {\n const items = [...this.#items.children];\n const index = items.indexOf(layerRoot.activeElement);\n const offsets = { ArrowDown: 1, ArrowUp: -1 };\n if (event.key in offsets) {\n event.preventDefault();\n items[(index + offsets[event.key] + items.length) % items.length].focus();\n }\n };\n document.body.append(this.#layer);\n document.addEventListener(\"keydown\", this.#key);\n this.update([]);\n }\n\n /**\n * 同步可用操作和忙碌状态,不重建菜单触发按钮。\n * Update actions and busy state without replacing the trigger button.\n * @param {Array<{id: string, label: string, destructive?: boolean}>} items 操作列表 / Actions.\n * @param {boolean} [disabled] 是否忙碌 / Whether operations are busy.\n * @returns {void} 无返回值 / No return value.\n */\n update(items, disabled = false) {\n this.close();\n this.#disabled = disabled || items.length === 0;\n this.#button.disabled = this.#disabled;\n this.#items.replaceChildren(\n ...items.map(item => {\n const button = this.#document.createElement(\"button\");\n button.type = \"button\";\n button.setAttribute(\"role\", \"menuitem\");\n button.textContent = item.label;\n button.toggleAttribute(\"data-danger\", Boolean(item.destructive));\n button.onclick = () => {\n this.close();\n this.#select(item.id);\n };\n return button;\n }),\n );\n }\n\n /**\n * 打开当前操作菜单。\n * Open the current action sheet.\n * @returns {void} 无返回值 / No return value.\n */\n open() {\n if (this.#disabled) return;\n const style = getComputedStyle(this.element);\n for (const property of [\"--pp-text\", \"--pp-surface\", \"--pp-border\", \"--pp-accent\", \"--pp-danger\"]) {\n const value = style.getPropertyValue(property);\n if (value) this.#layer.style.setProperty(property, value);\n }\n this.#layer.hidden = false;\n this.#button.setAttribute(\"aria-expanded\", \"true\");\n this.#items.firstElementChild.focus();\n }\n\n /**\n * 关闭菜单。\n * Close the menu.\n * @returns {void} 无返回值 / No return value.\n */\n close() {\n this.#layer.hidden = true;\n this.#button.setAttribute(\"aria-expanded\", \"false\");\n }\n\n /**\n * 移除监听器与节点。\n * Remove listeners and elements.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#document.removeEventListener(\"keydown\", this.#key);\n this.#layer.remove();\n this.element.remove();\n }\n}\n\n/**\n * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。\n * Resolve module resource locations: headers override query parameters and module conventions.\n * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.\n * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.\n * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.\n */\nfunction pageInputs(url, headers = {}) {\n const match = /^\\/settings\\/([a-zA-Z0-9_-]+)\\/?$/.exec(url.pathname);\n if (!match) throw new TypeError(\"Open a concrete module URL\");\n const module = match[1];\n const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));\n const json = values[\"x-preferencepanes-json\"] ?? url.searchParams.get(\"json\") ?? `/configs/${module}`;\n const css = values[\"x-preferencepanes-css\"] ?? url.searchParams.get(\"css\") ?? \"\";\n if (!json.trim()) throw new TypeError(\"JSON resource URL is required\");\n return { url: url.href, module, json, css };\n}\n\n/**\n * 模块文档容器:原始 HTML 不改写,请求上下文随 iframe 元素传递。\n * Module document container: preserve HTML verbatim and carry request context on the iframe element.\n */\nclass ModuleFrame extends EventTarget {\n #url;\n #options;\n #controller = new AbortController();\n #abort = () => this.destroy();\n #state;\n #change = event => {\n this.#state = { ...event.detail, actions: event.detail.actions ?? [] };\n this.dispatchEvent(new Event(\"change\"));\n };\n #confirmation = event => {\n const request = new CustomEvent(\"confirm\", { cancelable: true, detail: event.detail });\n if (!this.dispatchEvent(request)) event.preventDefault();\n };\n #notice = event => {\n const notice = new CustomEvent(\"notice\", { cancelable: true, detail: event.detail });\n if (!this.dispatchEvent(notice)) event.preventDefault();\n };\n\n /**\n * 建立 iframe 与请求输入;调用方挂载 element 后调用 load。\n * Create the iframe and request inputs; callers mount element and then call load.\n * @param {string | URL} url 模块请求地址 / Module request URL.\n * @param {RequestInit} [options] 原生请求头和取消信号 / Native headers and cancellation signal.\n */\n constructor(url, options = {}) {\n super();\n this.#url = new URL(url, document.baseURI);\n this.#options = { ...options, headers: new Headers(options.headers) };\n const inputs = pageInputs(this.#url, Object.fromEntries(this.#options.headers));\n this.element = document.createElement(\"iframe\");\n this.element.title = `${inputs.module} 设置`;\n this.element.dataset.preferencePanes = JSON.stringify(inputs);\n this.element.addEventListener(\"preferencepanes:change\", this.#change);\n this.element.addEventListener(\"preferencepanes:confirm\", this.#confirmation);\n this.element.addEventListener(\"preferencepanes:notice\", this.#notice);\n this.#state = { title: inputs.module, module: inputs.module, busy: false, canGoBack: true, actions: [] };\n options.signal?.addEventListener(\"abort\", this.#abort, { once: true });\n }\n\n /**\n * 当前模块导航状态。\n * Current module navigation state.\n */\n get state() {\n return { ...this.#state };\n }\n\n /**\n * 获取原始 HTML;晚到响应在退出后不得重新挂载。\n * Fetch unmodified HTML; a late response must not remount after departure.\n * @returns {Promise<void>} HTML 已交给 iframe;表单状态通过 change 事件提供 / HTML assigned; form state is reported through change.\n */\n async load() {\n if (this.#options.signal?.aborted) this.destroy();\n const timer = setTimeout(() => this.#controller.abort(), 10000);\n try {\n const response = await fetch(this.#url, { cache: \"no-store\", credentials: \"omit\", ...this.#options, signal: this.#controller.signal });\n if (response.status !== 200) throw new Error(`HTTP ${response.status}`);\n const html = await response.text();\n this.#controller.signal.throwIfAborted();\n this.element.srcdoc = html;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * 使用 iframe 的联合历史返回;写入期间不导航。\n * Navigate joint iframe history back, except while a write is pending.\n * @returns {void} 无返回值 / No return value.\n */\n back() {\n if (!this.#state.busy && this.#state.canGoBack) this.element.contentWindow.history.back();\n }\n\n /**\n * 向模块发送菜单操作,不让宿主访问内部 DOM 或存储客户端。\n * Dispatch a menu action without host access to internal DOM or the storage client.\n * @param {string} id 当前可用操作 / Available action identifier.\n * @returns {void} 无返回值 / No return value.\n */\n perform(id) {\n if (this.#state.busy || !this.#state.actions.some(action => action.id === id)) throw new Error(\"Action is not available\");\n this.element.dispatchEvent(new CustomEvent(\"preferencepanes:action\", { detail: id }));\n }\n\n /**\n * 取消加载与事件订阅;节点保留到 Navigation 的退出动画结束。\n * Cancel loading and subscriptions; Navigation retains the node until its exit animation ends.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#controller.abort();\n this.#options.signal?.removeEventListener(\"abort\", this.#abort);\n this.element.removeEventListener(\"preferencepanes:change\", this.#change);\n this.element.removeEventListener(\"preferencepanes:confirm\", this.#confirmation);\n this.element.removeEventListener(\"preferencepanes:notice\", this.#notice);\n }\n}\n\n/**\n * 模块 JSON Mock 的 HEAD 探测结果。\n * Result returned by a module JSON Mock HEAD probe.\n * @typedef {object} ModuleProbeResult\n * @property {\"installed\" | \"missing\"} state 安装状态 / Installation state.\n * @property {string | null} version 业务版本,缺失时为 null / Business version, or null when absent.\n * @property {number | null} httpStatus HTTP 状态码,网络错误时为 null / HTTP status, or null for network errors.\n */\n\n/**\n * 模块探测请求选项。\n * Options for a module probe request.\n * @typedef {object} ModuleProbeOptions\n * @property {typeof globalThis.fetch} [fetch] 可注入的 fetch / Injectable fetch.\n * @property {AbortSignal} [signal] 外部取消信号 / External cancellation signal.\n * @property {number} [timeout] 超时毫秒数,默认 3500 / Timeout in milliseconds, defaults to 3500.\n */\n\n/**\n * 通过模块 JSON Mock 的 HEAD 响应检测安装状态和业务版本。\n * Detect module installation and business version from a module JSON Mock HEAD response.\n * @param {string | URL} url 配置 Mock 地址 / Configuration Mock URL.\n * @param {ModuleProbeOptions} [options] 请求选项 / Request options.\n * @returns {Promise<ModuleProbeResult>} 探测结果 / Probe result.\n * @throws {Error} 外部取消请求 / External cancellation.\n */\nasync function probeModule(url, { fetch: request = globalThis.fetch, signal, timeout = 3500 } = {}) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (signal?.aborted) abort();\n signal?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const response = await request(url, { method: \"HEAD\", cache: \"no-store\", credentials: \"omit\", signal: controller.signal });\n return response.status === 200 ? { state: \"installed\", version: response.headers.get(\"X-PreferencePanes-Version\")?.trim() || null, httpStatus: 200 } : { state: \"missing\", version: null, httpStatus: response.status };\n } catch (error) {\n if (signal?.aborted) throw error;\n return { state: \"missing\", version: null, httpStatus: null };\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n }\n}\n\n/**\n * 模块入口的固定状态行,只通过 HEAD 探测安装状态和业务版本。\n * Fixed module status row, probing installation and business version with HEAD only.\n */\nclass ModuleStatus extends EventTarget {\n #element;\n #controller;\n #state = { status: \"checking\", version: null };\n\n /**\n * 绑定调用方提供的状态行。\n * Bind a caller-owned status row.\n * @param {HTMLElement} element 状态文字容器 / Status text container.\n */\n constructor(element) {\n super();\n this.#element = element;\n this.#render(\"checking\");\n }\n\n /**\n * 当前安装状态与业务版本。\n * Current installation state and business version.\n */\n get state() {\n return { ...this.#state };\n }\n\n /**\n * 每次进入重新探测,取消旧请求并忽略其迟到结果。\n * Reprobe on entry, cancelling old requests and ignoring late results.\n * @param {string | URL} url 配置 Mock 地址 / Configuration Mock URL.\n * @param {ModuleProbeOptions} [options] 请求选项 / Request options.\n * @returns {Promise<ModuleProbeResult>} 探测结果 / Probe result.\n */\n async check(url, options = {}) {\n this.#controller?.abort();\n const controller = new AbortController();\n this.#controller = controller;\n const externalSignal = options.signal;\n const abort = () => controller.abort();\n if (externalSignal?.aborted) abort();\n externalSignal?.addEventListener(\"abort\", abort, { once: true });\n this.#render(\"checking\");\n try {\n const result = await probeModule(url, { ...options, signal: controller.signal });\n if (controller !== this.#controller) return result;\n this.#render(result.state, result.version);\n return result;\n } catch (error) {\n if (controller !== this.#controller) return { state: \"missing\", version: null, httpStatus: null };\n throw error;\n } finally {\n externalSignal?.removeEventListener(\"abort\", abort);\n }\n }\n\n /**\n * 更新状态标签,缺少版本时不伪造版本号。\n * Render the label without inventing a missing version.\n * @param {\"checking\" | \"installed\" | \"missing\"} status 状态 / State.\n * @param {string | null} [version] 业务版本 / Business version.\n * @returns {void} 无返回值 / No return value.\n */\n #render(status, version = null) {\n this.#state = { status, version: status === \"installed\" ? version : null };\n switch (status) {\n case \"checking\":\n this.#element.textContent = \"检测中\";\n break;\n case \"installed\":\n this.#element.textContent = version ?? \"版本未知\";\n break;\n case \"missing\":\n this.#element.textContent = \"未安装\";\n break;\n }\n this.#element.dataset.state = status;\n this.#element.title = this.#element.textContent;\n this.dispatchEvent(new Event(\"change\"));\n }\n\n /**\n * 释放尚未完成的探测。\n * Release pending probes.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#controller?.abort();\n this.#controller = undefined;\n }\n}\n\n/**\n * 同一文档内的主页/子页导航;iframe 各自的实例通过浏览器联合历史协作。\n * Navigate home/detail views within a document; iframe instances cooperate through joint browser history.\n */\nclass Navigation extends EventTarget {\n #container;\n #home;\n #create;\n #window;\n #key = null;\n #view;\n #retiring;\n #controller;\n #animation;\n #scroll = new WeakMap();\n #onHistory = () => this.#route();\n #onPageShow = event => {\n if (event.persisted) this.#route(true);\n };\n\n /**\n * 根视图始终保留;工厂按需提供子页,可用 signal 取消离开后的异步加载。\n * Retain the home view and create details on demand; signal cancels async work after departure.\n * @param {HTMLElement} container 由调用方布局的页面容器 / Caller-styled view container.\n * @param {HTMLElement} home 已创建的主页节点 / Existing home view.\n * @param {(key: string, signal: AbortSignal) => HTMLElement | undefined} create 子页工厂;未知路径返回 undefined / Detail factory; undefined for unknown routes.\n */\n constructor(container, home, create) {\n super();\n this.#container = container;\n this.#home = home;\n this.#create = create;\n this.#window = container.ownerDocument.defaultView;\n container.replaceChildren(home);\n this.#window.addEventListener(\"popstate\", this.#onHistory);\n this.#window.addEventListener(\"hashchange\", this.#onHistory);\n this.#window.addEventListener(\"pageshow\", this.#onPageShow);\n this.#route();\n }\n\n /**\n * 当前子页键;空字符串表示主页。\n * Current detail key; empty means home.\n */\n get current() {\n return this.#key;\n }\n\n /**\n * 是否可以返回上一级或先前文档。\n * Whether a parent view or previous document is available.\n */\n get canGoBack() {\n return Boolean(this.#key) || this.#window.history.length > 1;\n }\n\n /**\n * 加入子页历史;使用文档自身 URL,避免 srcdoc 按宿主 base URL 跳转。\n * Push a detail using the document URL, avoiding srcdoc navigation against the host base URL.\n * @param {string} key 子页键 / Detail key.\n * @returns {void} 无返回值 / No return value.\n */\n open(key) {\n if (key === this.#key) return;\n const url = new URL(this.#window.location.href);\n url.hash = encodeURIComponent(key);\n this.#window.history.pushState({ ...this.#window.history.state, preferencePanesRoute: key }, \"\", url.href);\n this.#route();\n }\n\n /**\n * 沿浏览器联合历史返回,根页可退回宿主或上个文档。\n * Go back through joint history, including a host or previous document from home.\n * @returns {void} 无返回值 / No return value.\n */\n back() {\n if (this.canGoBack) this.#window.history.back();\n }\n\n /**\n * 解析 URL 并统一处理页面切换、加载取消与动画结束后的释放。\n * Resolve the URL and coordinate transitions, cancellation and release after animation.\n * @param {boolean} [reload] 从页面缓存恢复时重新创建子页 / Recreate a detail after bfcache restoration.\n * @returns {void} 无返回值 / No return value.\n */\n #route(reload = false) {\n const url = new URL(this.#window.location.href);\n let key;\n try {\n key = decodeURIComponent(url.hash.slice(1));\n } catch (error) {\n if (!(error instanceof URIError)) throw error;\n key = \"\";\n }\n if (!reload && key === this.#key) return;\n this.#controller?.abort();\n this.#controller = new AbortController();\n const next = key ? this.#create(key, this.#controller.signal) : undefined;\n if (!next) key = \"\";\n const history = this.#window.history;\n // 直接打开子页时建立一次主页历史;刷新不重复堆叠。\n // Seed home history once for direct details, without stacking entries on reload.\n if (url.hash && history.state?.preferencePanesRoute !== key) {\n url.hash = \"\";\n history.replaceState({ ...history.state, preferencePanesRoute: \"\" }, \"\", url.href);\n if (key) {\n url.hash = encodeURIComponent(key);\n history.pushState({ ...history.state, preferencePanesRoute: key }, \"\", url.href);\n }\n }\n const previous = this.#view;\n const position = previous ? this.#window.getComputedStyle(previous).transform : \"none\";\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#retiring = previous;\n if (previous) {\n this.#scroll.set(previous, previous.scrollTop);\n previous.inert = true;\n }\n this.#key = key;\n this.#view = next;\n this.#home.inert = Boolean(next);\n if (next) {\n next.inert = false;\n this.#container.append(next);\n next.scrollTop = this.#scroll.get(next) ?? 0;\n }\n const moving = next ?? previous;\n if (moving) {\n const animation = moving.animate([{ transform: next ? \"translateX(100%)\" : position }, { transform: next ? \"translateX(0)\" : \"translateX(100%)\" }], { duration: this.#window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches ? 0 : 280, easing: \"cubic-bezier(.22,.61,.36,1)\", fill: \"forwards\" });\n this.#animation = animation;\n animation.onfinish = () => {\n if (this.#animation !== animation) return;\n this.#retiring?.remove();\n this.#retiring = undefined;\n animation.cancel();\n this.#animation = undefined;\n };\n }\n this.dispatchEvent(new Event(\"change\"));\n }\n\n /**\n * 释放监听器、加载、动画和节点;调用方可重新创建导航。\n * Release listeners, loads, animations and nodes so callers can recreate navigation.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#window.removeEventListener(\"popstate\", this.#onHistory);\n this.#window.removeEventListener(\"hashchange\", this.#onHistory);\n this.#window.removeEventListener(\"pageshow\", this.#onPageShow);\n this.#controller?.abort();\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#view?.remove();\n this.#home.remove();\n }\n}\n\nexport { ActionMenu, ModuleFrame, ModuleStatus, Navigation, probeModule };\n"}};
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。
|
|
348
|
-
* Resolve module resource locations: headers override query parameters and module conventions.
|
|
349
|
-
* @param {URL} url 已解析的页面请求地址 / Parsed page request URL.
|
|
350
|
-
* @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.
|
|
351
|
-
* @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.
|
|
352
|
-
*/
|
|
353
|
-
function pageInputs(url, headers = {}) {
|
|
354
|
-
const match = /^\/settings\/([a-zA-Z0-9_-]+)\/?$/.exec(url.pathname);
|
|
355
|
-
if (!match) throw new TypeError("Open a concrete module URL");
|
|
356
|
-
const module = match[1];
|
|
357
|
-
const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
|
|
358
|
-
const json = values["x-preferencepanes-json"] ?? url.searchParams.get("json") ?? `/configs/${module}`;
|
|
359
|
-
const css = values["x-preferencepanes-css"] ?? url.searchParams.get("css") ?? "";
|
|
360
|
-
if (!json.trim()) throw new TypeError("JSON resource URL is required");
|
|
361
|
-
return { url: url.href, module, json, css };
|
|
362
|
-
}
|
|
363
|
-
|
|
364
344
|
/**
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
345
|
+
* 当前运行平台名称(脚本平台优先,模块系统次之)。
|
|
346
|
+
* Current runtime platform name (script platform first, module system second).
|
|
347
|
+
*
|
|
348
|
+
* 识别顺序:
|
|
349
|
+
* Detection order:
|
|
350
|
+
* 1) `$task` -> Quantumult X
|
|
351
|
+
* 2) `$loon` -> Loon
|
|
352
|
+
* 3) `$rocket` -> Shadowrocket
|
|
353
|
+
* 4) `Egern` -> Egern
|
|
354
|
+
* 5) `$environment["surge-version"]` -> Surge
|
|
355
|
+
* 6) `$environment["stash-version"]` -> Stash
|
|
356
|
+
* 7) `Cloudflare` -> Worker
|
|
357
|
+
* 8) `process.versions.node` -> Node.js
|
|
358
|
+
* 9) 默认回落 -> undefined
|
|
359
|
+
* default fallback -> undefined
|
|
360
|
+
*
|
|
361
|
+
* 说明:
|
|
362
|
+
* Notes:
|
|
363
|
+
* - 使用 `'key' in globalThis`,避免 `Object.keys` 对不可枚举全局变量漏检。
|
|
364
|
+
* - Use `'key' in globalThis` to avoid missing non-enumerable globals with `Object.keys`.
|
|
365
|
+
*
|
|
366
|
+
* @type {("Quantumult X" | "Loon" | "Shadowrocket" | "Egern" | "Surge" | "Stash" | "Worker" | "Node.js" | undefined)}
|
|
372
367
|
*/
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
368
|
+
const $app = (() => {
|
|
369
|
+
const has = key => key in globalThis;
|
|
370
|
+
switch (true) {
|
|
371
|
+
case has("$task"):
|
|
372
|
+
return "Quantumult X";
|
|
373
|
+
case has("$loon"):
|
|
374
|
+
return "Loon";
|
|
375
|
+
case has("$rocket"):
|
|
376
|
+
return "Shadowrocket";
|
|
377
|
+
case has("Egern"):
|
|
378
|
+
return "Egern";
|
|
379
|
+
case Boolean(globalThis.$environment?.["surge-version"]):
|
|
380
|
+
return "Surge";
|
|
381
|
+
case Boolean(globalThis.$environment?.["stash-version"]):
|
|
382
|
+
return "Stash";
|
|
383
|
+
case has("Cloudflare"):
|
|
384
|
+
//case has("ServiceWorkerGlobalScope") && has("self") && has("caches") && has("scheduler"):
|
|
385
|
+
return "Worker";
|
|
386
|
+
case Boolean(globalThis.process?.versions?.node):
|
|
387
|
+
return "Node.js";
|
|
388
|
+
default:
|
|
389
|
+
return undefined;
|
|
390
|
+
}
|
|
391
|
+
})();
|
|
380
392
|
|
|
381
|
-
/* https://www.lodashjs.com */
|
|
382
393
|
/**
|
|
383
|
-
*
|
|
384
|
-
*
|
|
394
|
+
* 统一日志工具,兼容各脚本平台、Worker 与 Node.js。
|
|
395
|
+
* Unified logger compatible with script platforms, Worker, and Node.js.
|
|
385
396
|
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* -
|
|
389
|
-
* -
|
|
390
|
-
* -
|
|
391
|
-
* -
|
|
392
|
-
* - 导入时建议使用 `Lodash as _`,遵循 lodash 官方示例惯例
|
|
393
|
-
* - Use `Lodash as _` when importing, following official lodash example convention
|
|
397
|
+
* logLevel 用法:
|
|
398
|
+
* logLevel usage:
|
|
399
|
+
* - 可读: `Console.logLevel` 返回 `OFF|ERROR|WARN|INFO|DEBUG|ALL`
|
|
400
|
+
* - Read: `Console.logLevel` returns `OFF|ERROR|WARN|INFO|DEBUG|ALL`
|
|
401
|
+
* - 可写: 数字 `0~5` 或字符串 `off/error/warn/info/debug/all`
|
|
402
|
+
* - Write: number `0~5` or string `off/error/warn/info/debug/all`
|
|
394
403
|
*
|
|
395
|
-
*
|
|
396
|
-
*
|
|
397
|
-
*
|
|
398
|
-
*
|
|
404
|
+
* @example
|
|
405
|
+
* Console.logLevel = "debug";
|
|
406
|
+
* Console.debug("only shown when level >= DEBUG");
|
|
407
|
+
* Console.logLevel = 2; // WARN
|
|
399
408
|
*/
|
|
400
|
-
class
|
|
409
|
+
class Console {
|
|
410
|
+
static #counts = new Map([]);
|
|
411
|
+
static #groups = [];
|
|
412
|
+
static #times = new Map([]);
|
|
413
|
+
|
|
401
414
|
/**
|
|
402
|
-
*
|
|
403
|
-
*
|
|
415
|
+
* 清空控制台(当前为空实现)。
|
|
416
|
+
* Clear console (currently a no-op).
|
|
404
417
|
*
|
|
405
|
-
* @
|
|
406
|
-
* @returns {string}
|
|
407
|
-
* @see {@link https://lodash.com/docs/#escape lodash.escape}
|
|
408
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.escape lodash.escape (中文)}
|
|
418
|
+
* @returns {void}
|
|
409
419
|
*/
|
|
410
|
-
static
|
|
411
|
-
const map = {
|
|
412
|
-
"&": "&",
|
|
413
|
-
"<": "<",
|
|
414
|
-
">": ">",
|
|
415
|
-
'"': """,
|
|
416
|
-
"'": "'",
|
|
417
|
-
};
|
|
418
|
-
return string.replace(/[&<>"']/g, m => map[m]);
|
|
419
|
-
}
|
|
420
|
+
static clear = () => {};
|
|
420
421
|
|
|
421
422
|
/**
|
|
422
|
-
*
|
|
423
|
-
*
|
|
423
|
+
* 增加计数器并打印当前值。
|
|
424
|
+
* Increment counter and print the current value.
|
|
424
425
|
*
|
|
425
|
-
* @param {
|
|
426
|
-
* @
|
|
427
|
-
* @param {*} [defaultValue=undefined] 默认值 / Default value.
|
|
428
|
-
* @returns {*}
|
|
429
|
-
* @see {@link https://lodash.com/docs/#get lodash.get}
|
|
430
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.get lodash.get (中文)}
|
|
426
|
+
* @param {string} [label="default"] 计数器名称 / Counter label.
|
|
427
|
+
* @returns {void}
|
|
431
428
|
*/
|
|
432
|
-
static
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
429
|
+
static count = (label = "default") => {
|
|
430
|
+
switch (Console.#counts.has(label)) {
|
|
431
|
+
case true:
|
|
432
|
+
Console.#counts.set(label, Console.#counts.get(label) + 1);
|
|
433
|
+
break;
|
|
434
|
+
case false:
|
|
435
|
+
Console.#counts.set(label, 0);
|
|
436
|
+
break;
|
|
437
|
+
}
|
|
438
|
+
Console.log(`${label}: ${Console.#counts.get(label)}`);
|
|
439
|
+
};
|
|
442
440
|
|
|
443
441
|
/**
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
* @description 简化版 lodash.merge,用于合并配置对象
|
|
447
|
-
* @description A simplified lodash.merge for config merging.
|
|
448
|
-
*
|
|
449
|
-
* 适用情况:
|
|
450
|
-
* - 合并嵌套的配置/设置对象
|
|
451
|
-
* - 需要深度合并而非浅层覆盖的场景
|
|
452
|
-
* - 多个源对象依次合并到目标对象
|
|
453
|
-
*
|
|
454
|
-
* 限制:
|
|
455
|
-
* - 仅处理普通对象 (Plain Object),不处理 Date/RegExp 等特殊对象
|
|
456
|
-
* - Map/Set 仅支持同类型合并,不递归内部值
|
|
457
|
-
* - 数组会被直接覆盖,不会合并数组元素
|
|
458
|
-
* - 不处理循环引用,可能导致栈溢出
|
|
459
|
-
* - 不复制 Symbol 属性和不可枚举属性
|
|
460
|
-
* - 不保留原型链,仅处理自身属性
|
|
461
|
-
* - 会修改原始目标对象 (mutates target)
|
|
442
|
+
* 重置计数器。
|
|
443
|
+
* Reset a counter.
|
|
462
444
|
*
|
|
463
|
-
* @param {
|
|
464
|
-
* @
|
|
465
|
-
* @param {...object} sources - 源对象(可多个)
|
|
466
|
-
* @param {...object} sources - Source objects.
|
|
467
|
-
* @returns {object} 返回合并后的目标对象
|
|
468
|
-
* @returns {object} Merged target object.
|
|
469
|
-
* @see {@link https://lodash.com/docs/#merge lodash.merge}
|
|
470
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.merge lodash.merge (中文)}
|
|
471
|
-
* @example
|
|
472
|
-
* const target = { a: { b: 1 }, c: 2 };
|
|
473
|
-
* const source = { a: { d: 3 }, e: 4 };
|
|
474
|
-
* Lodash.merge(target, source);
|
|
475
|
-
* // => { a: { b: 1, d: 3 }, c: 2, e: 4 }
|
|
445
|
+
* @param {string} [label="default"] 计数器名称 / Counter label.
|
|
446
|
+
* @returns {void}
|
|
476
447
|
*/
|
|
477
|
-
static
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
switch (true) {
|
|
488
|
-
case Lodash.#isPlainObject(sourceValue) && Lodash.#isPlainObject(targetValue):
|
|
489
|
-
// 递归合并对象
|
|
490
|
-
object[key] = Lodash.merge(targetValue, sourceValue);
|
|
491
|
-
break;
|
|
492
|
-
case sourceValue instanceof Map && targetValue instanceof Map:
|
|
493
|
-
// 合并 Map(空 Map 跳过)
|
|
494
|
-
if (sourceValue.size > 0) {
|
|
495
|
-
for (const [k, v] of sourceValue) {
|
|
496
|
-
targetValue.set(k, v);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
break;
|
|
500
|
-
case sourceValue instanceof Set && targetValue instanceof Set:
|
|
501
|
-
// 合并 Set(空 Set 跳过)
|
|
502
|
-
if (sourceValue.size > 0) {
|
|
503
|
-
for (const v of sourceValue) {
|
|
504
|
-
targetValue.add(v);
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
break;
|
|
508
|
-
case Array.isArray(sourceValue) && sourceValue.length === 0 && targetValue !== undefined:
|
|
509
|
-
// 空数组不覆盖已有值
|
|
510
|
-
break;
|
|
511
|
-
case (sourceValue instanceof Map && sourceValue.size === 0 && targetValue !== undefined):
|
|
512
|
-
case (sourceValue instanceof Set && sourceValue.size === 0 && targetValue !== undefined):
|
|
513
|
-
// 空 Map/Set 不覆盖已有值
|
|
514
|
-
break;
|
|
515
|
-
case sourceValue !== undefined:
|
|
516
|
-
object[key] = sourceValue;
|
|
517
|
-
break;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
448
|
+
static countReset = (label = "default") => {
|
|
449
|
+
switch (Console.#counts.has(label)) {
|
|
450
|
+
case true:
|
|
451
|
+
Console.#counts.set(label, 0);
|
|
452
|
+
Console.log(`${label}: ${Console.#counts.get(label)}`);
|
|
453
|
+
break;
|
|
454
|
+
case false:
|
|
455
|
+
Console.warn(`Counter "${label}" doesn’t exist`);
|
|
456
|
+
break;
|
|
520
457
|
}
|
|
521
|
-
|
|
522
|
-
return object;
|
|
523
|
-
}
|
|
458
|
+
};
|
|
524
459
|
|
|
525
460
|
/**
|
|
526
|
-
*
|
|
527
|
-
*
|
|
528
|
-
*
|
|
529
|
-
* @param {
|
|
530
|
-
* @returns {
|
|
531
|
-
* @returns {boolean} Returns true when value is a plain object.
|
|
532
|
-
* @see {@link https://lodash.com/docs/#isPlainObject lodash.isPlainObject}
|
|
533
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.isPlainObject lodash.isPlainObject (中文)}
|
|
461
|
+
* 输出调试日志。
|
|
462
|
+
* Print debug logs.
|
|
463
|
+
*
|
|
464
|
+
* @param {...any} msg 日志内容 / Log messages.
|
|
465
|
+
* @returns {void}
|
|
534
466
|
*/
|
|
535
|
-
static
|
|
536
|
-
if (
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
}
|
|
467
|
+
static debug = (...msg) => {
|
|
468
|
+
if (Console.#level < 4) return;
|
|
469
|
+
msg = msg.map(m => `🅱️ ${m}`);
|
|
470
|
+
Console.log(...msg);
|
|
471
|
+
};
|
|
540
472
|
|
|
541
473
|
/**
|
|
542
|
-
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
* @param {object} [object={}] 目标对象 / Target object.
|
|
546
|
-
* @param {string|string[]} [paths=[]] 要删除的路径 / Paths to remove.
|
|
547
|
-
* @returns {object}
|
|
548
|
-
* @see {@link https://lodash.com/docs/#omit lodash.omit}
|
|
549
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.omit lodash.omit (中文)}
|
|
550
|
-
*/
|
|
551
|
-
static omit(object = {}, paths = []) {
|
|
552
|
-
if (!Array.isArray(paths)) paths = [paths.toString()];
|
|
553
|
-
paths.forEach(path => Lodash.unset(object, path));
|
|
554
|
-
return object;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
/**
|
|
558
|
-
* 仅保留对象指定键(第一层)。
|
|
559
|
-
* Pick selected keys from object (top level only).
|
|
474
|
+
* 输出错误日志。
|
|
475
|
+
* Print error logs.
|
|
560
476
|
*
|
|
561
|
-
* @param {
|
|
562
|
-
* @
|
|
563
|
-
* @returns {object}
|
|
564
|
-
* @see {@link https://lodash.com/docs/#pick lodash.pick}
|
|
565
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.pick lodash.pick (中文)}
|
|
477
|
+
* @param {...any} msg 日志内容 / Log messages.
|
|
478
|
+
* @returns {void}
|
|
566
479
|
*/
|
|
567
|
-
static
|
|
568
|
-
if (
|
|
569
|
-
|
|
570
|
-
|
|
480
|
+
static error(...msg) {
|
|
481
|
+
if (Console.#level < 1) return;
|
|
482
|
+
switch ($app) {
|
|
483
|
+
case "Surge":
|
|
484
|
+
case "Loon":
|
|
485
|
+
case "Stash":
|
|
486
|
+
case "Egern":
|
|
487
|
+
case "Shadowrocket":
|
|
488
|
+
case "Quantumult X":
|
|
489
|
+
default:
|
|
490
|
+
msg = msg.map(m => `❌ ${m}`);
|
|
491
|
+
break;
|
|
492
|
+
case "Worker":
|
|
493
|
+
case "Node.js":
|
|
494
|
+
msg = msg.map(m => `❌ ${m?.stack ?? m}`);
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
Console.log(...msg);
|
|
571
498
|
}
|
|
572
499
|
|
|
573
500
|
/**
|
|
574
|
-
*
|
|
575
|
-
*
|
|
501
|
+
* `error` 的别名。
|
|
502
|
+
* Alias of `error`.
|
|
576
503
|
*
|
|
577
|
-
* @param {
|
|
578
|
-
* @
|
|
579
|
-
* @param {*} value 写入值 / Value.
|
|
580
|
-
* @returns {object}
|
|
581
|
-
* @see {@link https://lodash.com/docs/#set lodash.set}
|
|
582
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.set lodash.set (中文)}
|
|
504
|
+
* @param {...any} msg 日志内容 / Log messages.
|
|
505
|
+
* @returns {void}
|
|
583
506
|
*/
|
|
584
|
-
static
|
|
585
|
-
if (!Array.isArray(path)) path = Lodash.toPath(path);
|
|
586
|
-
path.slice(0, -1).reduce((previousValue, currentValue, currentIndex) => (Object(previousValue[currentValue]) === previousValue[currentValue] ? previousValue[currentValue] : (previousValue[currentValue] = /^\d+$/.test(path[currentIndex + 1]) ? [] : {})), object)[path[path.length - 1]] = value;
|
|
587
|
-
return object;
|
|
588
|
-
}
|
|
507
|
+
static exception = (...msg) => Console.error(...msg);
|
|
589
508
|
|
|
590
509
|
/**
|
|
591
|
-
*
|
|
592
|
-
*
|
|
510
|
+
* 进入日志分组。
|
|
511
|
+
* Enter a log group.
|
|
593
512
|
*
|
|
594
|
-
* @param {string}
|
|
595
|
-
* @returns {
|
|
596
|
-
* @see {@link https://lodash.com/docs/#toPath lodash.toPath}
|
|
597
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.toPath lodash.toPath (中文)}
|
|
513
|
+
* @param {string} label 分组名 / Group label.
|
|
514
|
+
* @returns {number}
|
|
598
515
|
*/
|
|
599
|
-
static
|
|
600
|
-
return value
|
|
601
|
-
.replace(/\[(\d+)\]/g, ".$1")
|
|
602
|
-
.split(".")
|
|
603
|
-
.filter(Boolean);
|
|
604
|
-
}
|
|
516
|
+
static group = label => Console.#groups.unshift(label);
|
|
605
517
|
|
|
606
518
|
/**
|
|
607
|
-
*
|
|
608
|
-
*
|
|
519
|
+
* 退出日志分组。
|
|
520
|
+
* Exit the latest log group.
|
|
609
521
|
*
|
|
610
|
-
* @
|
|
611
|
-
* @returns {string}
|
|
612
|
-
* @see {@link https://lodash.com/docs/#unescape lodash.unescape}
|
|
613
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.unescape lodash.unescape (中文)}
|
|
522
|
+
* @returns {*}
|
|
614
523
|
*/
|
|
615
|
-
static
|
|
616
|
-
const map = {
|
|
617
|
-
"&": "&",
|
|
618
|
-
"<": "<",
|
|
619
|
-
">": ">",
|
|
620
|
-
""": '"',
|
|
621
|
-
"'": "'",
|
|
622
|
-
};
|
|
623
|
-
return string.replace(/&|<|>|"|'/g, m => map[m]);
|
|
624
|
-
}
|
|
524
|
+
static groupEnd = () => Console.#groups.shift();
|
|
625
525
|
|
|
626
526
|
/**
|
|
627
|
-
*
|
|
628
|
-
*
|
|
527
|
+
* 输出信息日志。
|
|
528
|
+
* Print info logs.
|
|
629
529
|
*
|
|
630
|
-
* @param {
|
|
631
|
-
* @
|
|
632
|
-
* @returns {boolean}
|
|
633
|
-
* @see {@link https://lodash.com/docs/#unset lodash.unset}
|
|
634
|
-
* @see {@link https://www.lodashjs.com/docs/lodash.unset lodash.unset (中文)}
|
|
530
|
+
* @param {...any} msg 日志内容 / Log messages.
|
|
531
|
+
* @returns {void}
|
|
635
532
|
*/
|
|
636
|
-
static
|
|
637
|
-
if (
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
delete previousValue[currentValue];
|
|
641
|
-
return true;
|
|
642
|
-
}
|
|
643
|
-
return Object(previousValue)[currentValue];
|
|
644
|
-
}, object);
|
|
645
|
-
return result;
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
/**
|
|
650
|
-
* 当前运行平台名称(脚本平台优先,模块系统次之)。
|
|
651
|
-
* Current runtime platform name (script platform first, module system second).
|
|
652
|
-
*
|
|
653
|
-
* 识别顺序:
|
|
654
|
-
* Detection order:
|
|
655
|
-
* 1) `$task` -> Quantumult X
|
|
656
|
-
* 2) `$loon` -> Loon
|
|
657
|
-
* 3) `$rocket` -> Shadowrocket
|
|
658
|
-
* 4) `Egern` -> Egern
|
|
659
|
-
* 5) `$environment["surge-version"]` -> Surge
|
|
660
|
-
* 6) `$environment["stash-version"]` -> Stash
|
|
661
|
-
* 7) `Cloudflare` -> Worker
|
|
662
|
-
* 8) `process.versions.node` -> Node.js
|
|
663
|
-
* 9) 默认回落 -> undefined
|
|
664
|
-
* default fallback -> undefined
|
|
665
|
-
*
|
|
666
|
-
* 说明:
|
|
667
|
-
* Notes:
|
|
668
|
-
* - 使用 `'key' in globalThis`,避免 `Object.keys` 对不可枚举全局变量漏检。
|
|
669
|
-
* - Use `'key' in globalThis` to avoid missing non-enumerable globals with `Object.keys`.
|
|
670
|
-
*
|
|
671
|
-
* @type {("Quantumult X" | "Loon" | "Shadowrocket" | "Egern" | "Surge" | "Stash" | "Worker" | "Node.js" | undefined)}
|
|
672
|
-
*/
|
|
673
|
-
const $app = (() => {
|
|
674
|
-
const has = key => key in globalThis;
|
|
675
|
-
switch (true) {
|
|
676
|
-
case has("$task"):
|
|
677
|
-
return "Quantumult X";
|
|
678
|
-
case has("$loon"):
|
|
679
|
-
return "Loon";
|
|
680
|
-
case has("$rocket"):
|
|
681
|
-
return "Shadowrocket";
|
|
682
|
-
case has("Egern"):
|
|
683
|
-
return "Egern";
|
|
684
|
-
case Boolean(globalThis.$environment?.["surge-version"]):
|
|
685
|
-
return "Surge";
|
|
686
|
-
case Boolean(globalThis.$environment?.["stash-version"]):
|
|
687
|
-
return "Stash";
|
|
688
|
-
case has("Cloudflare"):
|
|
689
|
-
//case has("ServiceWorkerGlobalScope") && has("self") && has("caches") && has("scheduler"):
|
|
690
|
-
return "Worker";
|
|
691
|
-
case Boolean(globalThis.process?.versions?.node):
|
|
692
|
-
return "Node.js";
|
|
693
|
-
default:
|
|
694
|
-
return undefined;
|
|
533
|
+
static info(...msg) {
|
|
534
|
+
if (Console.#level < 3) return;
|
|
535
|
+
msg = msg.map(m => `ℹ️ ${m}`);
|
|
536
|
+
Console.log(...msg);
|
|
695
537
|
}
|
|
696
|
-
})();
|
|
697
538
|
|
|
698
|
-
|
|
699
|
-
* 跨平台持久化存储适配器。
|
|
700
|
-
* Cross-platform persistent storage adapter.
|
|
701
|
-
*
|
|
702
|
-
* 设计目标:
|
|
703
|
-
* Design goal:
|
|
704
|
-
* - 仿照 Web Storage (`Storage`) 接口设计
|
|
705
|
-
* - Modeled after Web Storage (`Storage`) interface
|
|
706
|
-
* - 统一 VPN App 脚本环境中的持久化读写接口
|
|
707
|
-
* - Unify persistence APIs across VPN app script environments
|
|
708
|
-
*
|
|
709
|
-
* 支持后端:
|
|
710
|
-
* Supported backends:
|
|
711
|
-
* - Surge/Loon/Stash/Egern/Shadowrocket: `$persistentStore`
|
|
712
|
-
* - Quantumult X: `$prefs`
|
|
713
|
-
* - Worker: 内存缓存(非持久化)
|
|
714
|
-
* - Worker: in-memory cache (non-persistent)
|
|
715
|
-
* - Node.js: 由 Node.js ESM 入口注入持久化后端
|
|
716
|
-
* - Node.js: persistent backend injected by the Node.js ESM entry
|
|
717
|
-
*
|
|
718
|
-
* 支持路径键:
|
|
719
|
-
* Supports path key:
|
|
720
|
-
* - `@root.path.to.value`
|
|
721
|
-
*
|
|
722
|
-
* 与 Web Storage 的已知差异:
|
|
723
|
-
* Known differences from Web Storage:
|
|
724
|
-
* - 支持 `@key.path` 深路径读写(Web Storage 原生不支持)
|
|
725
|
-
* - Supports `@key.path` deep-path access (not native in Web Storage)
|
|
726
|
-
* - `removeItem/clear` 并非所有平台都可用
|
|
727
|
-
* - `removeItem/clear` are not available on every platform
|
|
728
|
-
* - 读取时会尝试 `JSON.parse`,写入对象会 `JSON.stringify`
|
|
729
|
-
* - Reads try `JSON.parse`, writes stringify objects
|
|
730
|
-
*
|
|
731
|
-
* @link https://developer.mozilla.org/en-US/docs/Web/API/Storage
|
|
732
|
-
* @link https://developer.mozilla.org/zh-CN/docs/Web/API/Storage
|
|
733
|
-
*/
|
|
734
|
-
class Storage {
|
|
735
|
-
/**
|
|
736
|
-
* Worker / Node.js 环境下的内存数据缓存。
|
|
737
|
-
* In-memory data cache for Worker / Node.js runtime.
|
|
738
|
-
*
|
|
739
|
-
* @type {Record<string, any>|null}
|
|
740
|
-
*/
|
|
741
|
-
static data = null;
|
|
539
|
+
static #level = 3;
|
|
742
540
|
|
|
743
541
|
/**
|
|
744
|
-
*
|
|
745
|
-
*
|
|
542
|
+
* 获取日志级别文本。
|
|
543
|
+
* Get current log level text.
|
|
746
544
|
*
|
|
747
|
-
* @
|
|
545
|
+
* @returns {"OFF"|"ERROR"|"WARN"|"INFO"|"DEBUG"|"ALL"}
|
|
748
546
|
*/
|
|
749
|
-
static
|
|
547
|
+
static get logLevel() {
|
|
548
|
+
switch (Console.#level) {
|
|
549
|
+
case 0:
|
|
550
|
+
return "OFF";
|
|
551
|
+
case 1:
|
|
552
|
+
return "ERROR";
|
|
553
|
+
case 2:
|
|
554
|
+
return "WARN";
|
|
555
|
+
case 3:
|
|
556
|
+
default:
|
|
557
|
+
return "INFO";
|
|
558
|
+
case 4:
|
|
559
|
+
return "DEBUG";
|
|
560
|
+
case 5:
|
|
561
|
+
return "ALL";
|
|
562
|
+
}
|
|
563
|
+
}
|
|
750
564
|
|
|
751
565
|
/**
|
|
752
|
-
*
|
|
753
|
-
*
|
|
566
|
+
* 设置日志级别。
|
|
567
|
+
* Set current log level.
|
|
754
568
|
*
|
|
755
|
-
* @
|
|
569
|
+
* @param {number|string} level 级别值 / Level value.
|
|
756
570
|
*/
|
|
757
|
-
static
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
* Regex for `@key.path` parsing.
|
|
762
|
-
*
|
|
763
|
-
* @type {RegExp}
|
|
764
|
-
*/
|
|
765
|
-
static #nameRegex = /^@(?<key>[^.]+)(?:\.(?<path>.*))?$/;
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* 读取存储值。
|
|
769
|
-
* Read value from persistent storage.
|
|
770
|
-
*
|
|
771
|
-
* @param {string} keyName 键名或路径键 / Key or path key.
|
|
772
|
-
* @param {*} [defaultValue=null] 默认值 / Default value when key is missing.
|
|
773
|
-
* @returns {*}
|
|
774
|
-
*/
|
|
775
|
-
static getItem(keyName, defaultValue = null) {
|
|
776
|
-
let keyValue = defaultValue;
|
|
777
|
-
// 如果以 @
|
|
778
|
-
switch (keyName.startsWith("@")) {
|
|
779
|
-
case true: {
|
|
780
|
-
const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
|
|
781
|
-
keyName = key;
|
|
782
|
-
let value = Storage.getItem(keyName, {});
|
|
783
|
-
if (typeof value !== "object") value = {};
|
|
784
|
-
keyValue = Lodash.get(value, path);
|
|
785
|
-
try {
|
|
786
|
-
keyValue = JSON.parse(keyValue);
|
|
787
|
-
} catch {}
|
|
571
|
+
static set logLevel(level) {
|
|
572
|
+
switch (typeof level) {
|
|
573
|
+
case "string":
|
|
574
|
+
level = level.toLowerCase();
|
|
788
575
|
break;
|
|
789
|
-
|
|
576
|
+
case "number":
|
|
577
|
+
break;
|
|
578
|
+
case "undefined":
|
|
790
579
|
default:
|
|
791
|
-
|
|
792
|
-
case "Surge":
|
|
793
|
-
case "Loon":
|
|
794
|
-
case "Stash":
|
|
795
|
-
case "Egern":
|
|
796
|
-
case "Shadowrocket":
|
|
797
|
-
keyValue = $persistentStore.read(keyName);
|
|
798
|
-
break;
|
|
799
|
-
case "Quantumult X":
|
|
800
|
-
keyValue = $prefs.valueForKey(keyName);
|
|
801
|
-
break;
|
|
802
|
-
case "Worker":
|
|
803
|
-
Storage.data = Storage.data ?? {};
|
|
804
|
-
keyValue = Storage.data[keyName];
|
|
805
|
-
break;
|
|
806
|
-
case "Node.js":
|
|
807
|
-
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
808
|
-
keyValue = Storage.data?.[keyName];
|
|
809
|
-
break;
|
|
810
|
-
default:
|
|
811
|
-
keyValue = Storage.data?.[keyName] || null;
|
|
812
|
-
break;
|
|
813
|
-
}
|
|
814
|
-
try {
|
|
815
|
-
keyValue = JSON.parse(keyValue);
|
|
816
|
-
} catch {
|
|
817
|
-
// do nothing
|
|
818
|
-
}
|
|
580
|
+
level = "warn";
|
|
819
581
|
break;
|
|
820
582
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
* @param {*} keyValue 写入值 / Value to store.
|
|
830
|
-
* @returns {boolean}
|
|
831
|
-
*/
|
|
832
|
-
static setItem(keyName = new String(), keyValue = new String()) {
|
|
833
|
-
let result = false;
|
|
834
|
-
switch (typeof keyValue) {
|
|
835
|
-
case "object":
|
|
836
|
-
keyValue = JSON.stringify(keyValue);
|
|
583
|
+
switch (level) {
|
|
584
|
+
case 0:
|
|
585
|
+
case "off":
|
|
586
|
+
Console.#level = 0;
|
|
587
|
+
break;
|
|
588
|
+
case 1:
|
|
589
|
+
case "error":
|
|
590
|
+
Console.#level = 1;
|
|
837
591
|
break;
|
|
592
|
+
case 2:
|
|
593
|
+
case "warn":
|
|
594
|
+
case "warning":
|
|
838
595
|
default:
|
|
839
|
-
|
|
596
|
+
Console.#level = 2;
|
|
840
597
|
break;
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
|
|
845
|
-
keyName = key;
|
|
846
|
-
let value = Storage.getItem(keyName, {});
|
|
847
|
-
if (typeof value !== "object") value = {};
|
|
848
|
-
Lodash.set(value, path, keyValue);
|
|
849
|
-
result = Storage.setItem(keyName, value);
|
|
598
|
+
case 3:
|
|
599
|
+
case "info":
|
|
600
|
+
Console.#level = 3;
|
|
850
601
|
break;
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
case "Shadowrocket":
|
|
859
|
-
result = $persistentStore.write(keyValue, keyName);
|
|
860
|
-
break;
|
|
861
|
-
case "Quantumult X":
|
|
862
|
-
result = $prefs.setValueForKey(keyValue, keyName);
|
|
863
|
-
break;
|
|
864
|
-
case "Worker":
|
|
865
|
-
Storage.data = Storage.data ?? {};
|
|
866
|
-
Storage.data[keyName] = keyValue;
|
|
867
|
-
result = true;
|
|
868
|
-
break;
|
|
869
|
-
case "Node.js":
|
|
870
|
-
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
871
|
-
Storage.data[keyName] = keyValue;
|
|
872
|
-
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
873
|
-
result = true;
|
|
874
|
-
break;
|
|
875
|
-
default:
|
|
876
|
-
result = Storage.data?.[keyName] || null;
|
|
877
|
-
break;
|
|
878
|
-
}
|
|
602
|
+
case 4:
|
|
603
|
+
case "debug":
|
|
604
|
+
Console.#level = 4;
|
|
605
|
+
break;
|
|
606
|
+
case 5:
|
|
607
|
+
case "all":
|
|
608
|
+
Console.#level = 5;
|
|
879
609
|
break;
|
|
880
610
|
}
|
|
881
|
-
return result;
|
|
882
611
|
}
|
|
883
612
|
|
|
884
613
|
/**
|
|
885
|
-
*
|
|
886
|
-
*
|
|
614
|
+
* 输出通用日志。
|
|
615
|
+
* Print generic logs.
|
|
887
616
|
*
|
|
888
|
-
*
|
|
889
|
-
*
|
|
890
|
-
* -
|
|
891
|
-
* -
|
|
892
|
-
* - 其余平台当前返回 `false`
|
|
617
|
+
* 说明:
|
|
618
|
+
* Notes:
|
|
619
|
+
* - 多行字符串参数会按换行拆分为多个独立日志项。
|
|
620
|
+
* - Multi-line string arguments are split into multiple log entries by line breaks.
|
|
893
621
|
*
|
|
894
|
-
* @param {
|
|
895
|
-
* @returns {
|
|
622
|
+
* @param {...any} msg 日志内容 / Log messages.
|
|
623
|
+
* @returns {void}
|
|
896
624
|
*/
|
|
897
|
-
static
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
625
|
+
static log = (...msg) => {
|
|
626
|
+
if (Console.#level === 0) return;
|
|
627
|
+
msg = msg.flatMap(log => {
|
|
628
|
+
switch (typeof log) {
|
|
629
|
+
case "object":
|
|
630
|
+
return [JSON.stringify(log)];
|
|
631
|
+
case "bigint":
|
|
632
|
+
case "number":
|
|
633
|
+
case "boolean":
|
|
634
|
+
return [log.toString()];
|
|
635
|
+
case "string":
|
|
636
|
+
return log.split(/\r?\n/u);
|
|
637
|
+
case "undefined":
|
|
638
|
+
default:
|
|
639
|
+
return [log];
|
|
908
640
|
}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
case "Shadowrocket":
|
|
918
|
-
result = false;
|
|
919
|
-
break;
|
|
920
|
-
case "Quantumult X":
|
|
921
|
-
result = $prefs.removeValueForKey(keyName);
|
|
922
|
-
break;
|
|
923
|
-
case "Worker":
|
|
924
|
-
Storage.data = Storage.data ?? {};
|
|
925
|
-
delete Storage.data[keyName];
|
|
926
|
-
result = true;
|
|
927
|
-
break;
|
|
928
|
-
case "Node.js":
|
|
929
|
-
// result = false;
|
|
930
|
-
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
931
|
-
delete Storage.data[keyName];
|
|
932
|
-
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
933
|
-
result = true;
|
|
934
|
-
break;
|
|
935
|
-
default:
|
|
936
|
-
result = false;
|
|
937
|
-
break;
|
|
938
|
-
}
|
|
939
|
-
break;
|
|
940
|
-
}
|
|
941
|
-
return result;
|
|
942
|
-
}
|
|
641
|
+
});
|
|
642
|
+
Console.#groups.forEach(group => {
|
|
643
|
+
msg = msg.map(log => ` ${log}`);
|
|
644
|
+
msg.unshift(`▼ ${group}:`);
|
|
645
|
+
});
|
|
646
|
+
msg = ["", ...msg];
|
|
647
|
+
console.log(msg.join("\n"));
|
|
648
|
+
};
|
|
943
649
|
|
|
944
650
|
/**
|
|
945
|
-
*
|
|
946
|
-
*
|
|
651
|
+
* 开始计时。
|
|
652
|
+
* Start timer.
|
|
653
|
+
*
|
|
654
|
+
* @param {string} [label="default"] 计时器名称 / Timer label.
|
|
655
|
+
* @returns {Map<string, number>}
|
|
656
|
+
*/
|
|
657
|
+
static time = (label = "default") => Console.#times.set(label, Date.now());
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* 结束计时并移除计时器。
|
|
661
|
+
* End timer and remove it.
|
|
947
662
|
*
|
|
663
|
+
* @param {string} [label="default"] 计时器名称 / Timer label.
|
|
948
664
|
* @returns {boolean}
|
|
949
665
|
*/
|
|
950
|
-
static
|
|
951
|
-
let result = false;
|
|
952
|
-
switch ($app) {
|
|
953
|
-
case "Surge":
|
|
954
|
-
case "Loon":
|
|
955
|
-
case "Stash":
|
|
956
|
-
case "Egern":
|
|
957
|
-
case "Shadowrocket":
|
|
958
|
-
result = false;
|
|
959
|
-
break;
|
|
960
|
-
case "Quantumult X":
|
|
961
|
-
result = $prefs.removeAllValues();
|
|
962
|
-
break;
|
|
963
|
-
case "Worker":
|
|
964
|
-
Storage.data = {};
|
|
965
|
-
result = true;
|
|
966
|
-
break;
|
|
967
|
-
case "Node.js":
|
|
968
|
-
// result = false;
|
|
969
|
-
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
970
|
-
Storage.data = {};
|
|
971
|
-
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
972
|
-
result = true;
|
|
973
|
-
break;
|
|
974
|
-
default:
|
|
975
|
-
result = false;
|
|
976
|
-
break;
|
|
977
|
-
}
|
|
978
|
-
return result;
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
/**
|
|
983
|
-
* 校验原始路径片段,不进行 URL 编码转换。
|
|
984
|
-
* Validate raw path segments without URL encoding conversion.
|
|
985
|
-
* @param {string[]} parts 原始路径片段 / Raw path segments.
|
|
986
|
-
* @returns {string[]} 同一数组,不复制或修改 / The same array without copying or mutation.
|
|
987
|
-
* @throws {TypeError} 空片段、非法字符或原型属性名 / Empty segments, invalid characters or prototype property names.
|
|
988
|
-
*/
|
|
989
|
-
function validatePathParts(parts) {
|
|
990
|
-
if (!parts.every(part => typeof part === "string" && /^[a-zA-Z0-9_-]+$/.test(part) && !["__proto__", "prototype", "constructor"].includes(part))) throw new TypeError("Invalid key path");
|
|
991
|
-
return parts;
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
/**
|
|
995
|
-
* 无配置绑定的本地存储桥接;form 字段名就是完整 @root.path。
|
|
996
|
-
* Unbound local storage bridge; the form field name is the complete @root.path.
|
|
997
|
-
*/
|
|
998
|
-
class Store {
|
|
999
|
-
/**
|
|
1000
|
-
* POST /api/get、set、delete;不下载配置、不解析控件、不鉴权。
|
|
1001
|
-
* POST /api/get, set or delete without config downloads, control parsing or authentication.
|
|
1002
|
-
* @param {import("./index.js").SettingsRequest} request 代理请求 / Proxy request.
|
|
1003
|
-
* @param {URL} [url] 已解析地址 / Parsed URL.
|
|
1004
|
-
* @returns {Promise<import("./index.js").SettingsResponse | undefined>} 操作结果 / Operation result.
|
|
1005
|
-
*/
|
|
1006
|
-
async handle(request, url = new URL(request.url)) {
|
|
1007
|
-
if (!url.pathname.startsWith("/api/")) return;
|
|
1008
|
-
const reply = (status, data) => response(request, status, data);
|
|
1009
|
-
const action = url.pathname.slice(5);
|
|
1010
|
-
if (!["get", "set", "delete"].includes(action)) return reply(404, { error: "Unknown action" });
|
|
1011
|
-
if (request.method !== "POST") return reply(405, { error: "Use POST with a form body" });
|
|
1012
|
-
const headers = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
1013
|
-
if (headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") return reply(415, { error: "Expected application/x-www-form-urlencoded" });
|
|
1014
|
-
if (typeof request.body !== "string" || request.body.length > 65536) return reply(400, { error: "Expected a form body up to 65536 characters" });
|
|
1015
|
-
let parts, value;
|
|
1016
|
-
try {
|
|
1017
|
-
const fields = request.body.split("&");
|
|
1018
|
-
if (fields.length !== 1) throw new TypeError("Send exactly one storage key");
|
|
1019
|
-
const separator = fields[0].indexOf("=");
|
|
1020
|
-
if (separator < 0) throw new TypeError("Expected @root.path=value");
|
|
1021
|
-
const key = decodeURIComponent(fields[0].slice(0, separator).replace(/\+/g, " "));
|
|
1022
|
-
value = decodeURIComponent(fields[0].slice(separator + 1).replace(/\+/g, " "));
|
|
1023
|
-
if (!key.startsWith("@")) throw new TypeError("Storage keys must start with @");
|
|
1024
|
-
parts = validatePathParts(key.slice(1).split("."));
|
|
1025
|
-
if (parts.length < 2) throw new TypeError("Specify a storage root and child path");
|
|
1026
|
-
} catch (error) {
|
|
1027
|
-
return reply(400, { error: error.message });
|
|
1028
|
-
}
|
|
1029
|
-
if (action === "set") {
|
|
1030
|
-
try {
|
|
1031
|
-
value = JSON.parse(value);
|
|
1032
|
-
} catch (error) {
|
|
1033
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
const [storageKey, ...path] = parts;
|
|
1037
|
-
try {
|
|
1038
|
-
const root = Storage.getItem(storageKey, {});
|
|
1039
|
-
if (!isRecord(root)) throw new TypeError("Stored root must be an object");
|
|
1040
|
-
const parent = storageParent(root, path, action === "set");
|
|
1041
|
-
const key = path.at(-1);
|
|
1042
|
-
switch (action) {
|
|
1043
|
-
case "get": {
|
|
1044
|
-
const result = parent ? Lodash.get(parent, [key]) : undefined;
|
|
1045
|
-
return result === undefined ? reply(404, { error: "Stored path does not exist" }) : reply(200, result);
|
|
1046
|
-
}
|
|
1047
|
-
case "set":
|
|
1048
|
-
Lodash.set(parent, [key], value);
|
|
1049
|
-
break;
|
|
1050
|
-
case "delete":
|
|
1051
|
-
if (parent) Lodash.unset(parent, [key]);
|
|
1052
|
-
break;
|
|
1053
|
-
}
|
|
1054
|
-
if (!Storage.setItem(storageKey, root)) throw new Error("Storage write failed");
|
|
1055
|
-
return reply(200, action === "set" ? { saved: true } : { deleted: true });
|
|
1056
|
-
} catch (error) {
|
|
1057
|
-
return reply(500, { error: error.message });
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
/**
|
|
1063
|
-
* 判断根节点是否为普通对象。
|
|
1064
|
-
* Determine whether a root node is a plain object.
|
|
1065
|
-
* @param {unknown} value 待检查值 / Value to inspect.
|
|
1066
|
-
* @returns {boolean} 是否为普通对象 / Whether this is a plain object.
|
|
1067
|
-
*/
|
|
1068
|
-
function isRecord(value) {
|
|
1069
|
-
return value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
/**
|
|
1073
|
-
* 遍历父路径,兼容旧存储中 JSON 字符串形式的中间节点。
|
|
1074
|
-
* Traverse parents, supporting legacy intermediate nodes serialized as JSON strings.
|
|
1075
|
-
* @param {Record<string, unknown>} root 存储根 / Storage root.
|
|
1076
|
-
* @param {string[]} parts 完整路径 / Complete path.
|
|
1077
|
-
* @param {boolean} create 是否创建缺失节点 / Whether to create missing parents.
|
|
1078
|
-
* @returns {object | undefined} 父节点,缺失且不创建时为 undefined / Parent, or undefined when absent and not creating.
|
|
1079
|
-
* @throws {TypeError} 无法继续遍历标量节点 / A scalar node cannot be traversed.
|
|
1080
|
-
*/
|
|
1081
|
-
function storageParent(root, parts, create) {
|
|
1082
|
-
let parent = root;
|
|
1083
|
-
for (const part of parts.slice(0, -1)) {
|
|
1084
|
-
let next = Lodash.get(parent, [part]);
|
|
1085
|
-
switch (typeof next) {
|
|
1086
|
-
case "undefined":
|
|
1087
|
-
if (!create) return;
|
|
1088
|
-
next = {};
|
|
1089
|
-
break;
|
|
1090
|
-
case "string":
|
|
1091
|
-
next = JSON.parse(next);
|
|
1092
|
-
break;
|
|
1093
|
-
}
|
|
1094
|
-
if (!isRecord(next) && !Array.isArray(next)) throw new TypeError("Stored parent is not an object or array");
|
|
1095
|
-
Lodash.set(parent, [part], next);
|
|
1096
|
-
parent = next;
|
|
1097
|
-
}
|
|
1098
|
-
return parent;
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
/**
|
|
1102
|
-
* 统一日志工具,兼容各脚本平台、Worker 与 Node.js。
|
|
1103
|
-
* Unified logger compatible with script platforms, Worker, and Node.js.
|
|
1104
|
-
*
|
|
1105
|
-
* logLevel 用法:
|
|
1106
|
-
* logLevel usage:
|
|
1107
|
-
* - 可读: `Console.logLevel` 返回 `OFF|ERROR|WARN|INFO|DEBUG|ALL`
|
|
1108
|
-
* - Read: `Console.logLevel` returns `OFF|ERROR|WARN|INFO|DEBUG|ALL`
|
|
1109
|
-
* - 可写: 数字 `0~5` 或字符串 `off/error/warn/info/debug/all`
|
|
1110
|
-
* - Write: number `0~5` or string `off/error/warn/info/debug/all`
|
|
1111
|
-
*
|
|
1112
|
-
* @example
|
|
1113
|
-
* Console.logLevel = "debug";
|
|
1114
|
-
* Console.debug("only shown when level >= DEBUG");
|
|
1115
|
-
* Console.logLevel = 2; // WARN
|
|
1116
|
-
*/
|
|
1117
|
-
class Console {
|
|
1118
|
-
static #counts = new Map([]);
|
|
1119
|
-
static #groups = [];
|
|
1120
|
-
static #times = new Map([]);
|
|
1121
|
-
|
|
1122
|
-
/**
|
|
1123
|
-
* 清空控制台(当前为空实现)。
|
|
1124
|
-
* Clear console (currently a no-op).
|
|
1125
|
-
*
|
|
1126
|
-
* @returns {void}
|
|
1127
|
-
*/
|
|
1128
|
-
static clear = () => {};
|
|
1129
|
-
|
|
1130
|
-
/**
|
|
1131
|
-
* 增加计数器并打印当前值。
|
|
1132
|
-
* Increment counter and print the current value.
|
|
1133
|
-
*
|
|
1134
|
-
* @param {string} [label="default"] 计数器名称 / Counter label.
|
|
1135
|
-
* @returns {void}
|
|
1136
|
-
*/
|
|
1137
|
-
static count = (label = "default") => {
|
|
1138
|
-
switch (Console.#counts.has(label)) {
|
|
1139
|
-
case true:
|
|
1140
|
-
Console.#counts.set(label, Console.#counts.get(label) + 1);
|
|
1141
|
-
break;
|
|
1142
|
-
case false:
|
|
1143
|
-
Console.#counts.set(label, 0);
|
|
1144
|
-
break;
|
|
1145
|
-
}
|
|
1146
|
-
Console.log(`${label}: ${Console.#counts.get(label)}`);
|
|
1147
|
-
};
|
|
1148
|
-
|
|
1149
|
-
/**
|
|
1150
|
-
* 重置计数器。
|
|
1151
|
-
* Reset a counter.
|
|
1152
|
-
*
|
|
1153
|
-
* @param {string} [label="default"] 计数器名称 / Counter label.
|
|
1154
|
-
* @returns {void}
|
|
1155
|
-
*/
|
|
1156
|
-
static countReset = (label = "default") => {
|
|
1157
|
-
switch (Console.#counts.has(label)) {
|
|
1158
|
-
case true:
|
|
1159
|
-
Console.#counts.set(label, 0);
|
|
1160
|
-
Console.log(`${label}: ${Console.#counts.get(label)}`);
|
|
1161
|
-
break;
|
|
1162
|
-
case false:
|
|
1163
|
-
Console.warn(`Counter "${label}" doesn’t exist`);
|
|
1164
|
-
break;
|
|
1165
|
-
}
|
|
1166
|
-
};
|
|
666
|
+
static timeEnd = (label = "default") => Console.#times.delete(label);
|
|
1167
667
|
|
|
1168
668
|
/**
|
|
1169
|
-
*
|
|
1170
|
-
* Print
|
|
669
|
+
* 输出当前计时器耗时。
|
|
670
|
+
* Print elapsed time for a timer.
|
|
1171
671
|
*
|
|
1172
|
-
* @param {
|
|
672
|
+
* @param {string} [label="default"] 计时器名称 / Timer label.
|
|
1173
673
|
* @returns {void}
|
|
1174
674
|
*/
|
|
1175
|
-
static
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
Console.
|
|
675
|
+
static timeLog = (label = "default") => {
|
|
676
|
+
const time = Console.#times.get(label);
|
|
677
|
+
if (time) Console.log(`${label}: ${Date.now() - time}ms`);
|
|
678
|
+
else Console.warn(`Timer "${label}" doesn’t exist`);
|
|
1179
679
|
};
|
|
1180
680
|
|
|
1181
681
|
/**
|
|
1182
|
-
*
|
|
1183
|
-
* Print
|
|
682
|
+
* 输出警告日志。
|
|
683
|
+
* Print warning logs.
|
|
1184
684
|
*
|
|
1185
685
|
* @param {...any} msg 日志内容 / Log messages.
|
|
1186
686
|
* @returns {void}
|
|
1187
687
|
*/
|
|
1188
|
-
static
|
|
1189
|
-
if (Console.#level <
|
|
1190
|
-
|
|
1191
|
-
case "Surge":
|
|
1192
|
-
case "Loon":
|
|
1193
|
-
case "Stash":
|
|
1194
|
-
case "Egern":
|
|
1195
|
-
case "Shadowrocket":
|
|
1196
|
-
case "Quantumult X":
|
|
1197
|
-
default:
|
|
1198
|
-
msg = msg.map(m => `❌ ${m}`);
|
|
1199
|
-
break;
|
|
1200
|
-
case "Worker":
|
|
1201
|
-
case "Node.js":
|
|
1202
|
-
msg = msg.map(m => `❌ ${m?.stack ?? m}`);
|
|
1203
|
-
break;
|
|
1204
|
-
}
|
|
688
|
+
static warn(...msg) {
|
|
689
|
+
if (Console.#level < 2) return;
|
|
690
|
+
msg = msg.map(m => `⚠️ ${m}`);
|
|
1205
691
|
Console.log(...msg);
|
|
1206
692
|
}
|
|
693
|
+
}
|
|
1207
694
|
|
|
695
|
+
/* https://www.lodashjs.com */
|
|
696
|
+
/**
|
|
697
|
+
* 轻量 Lodash 工具集。
|
|
698
|
+
* Lightweight Lodash-like utilities.
|
|
699
|
+
*
|
|
700
|
+
* 说明:
|
|
701
|
+
* Notes:
|
|
702
|
+
* - 这是 Lodash 的“部分方法”简化实现,不等价于完整 Lodash
|
|
703
|
+
* - This is a simplified subset, not a full Lodash implementation
|
|
704
|
+
* - 各方法语义可参考 Lodash 官方文档
|
|
705
|
+
* - Method semantics can be referenced from official Lodash docs
|
|
706
|
+
* - 导入时建议使用 `Lodash as _`,遵循 lodash 官方示例惯例
|
|
707
|
+
* - Use `Lodash as _` when importing, following official lodash example convention
|
|
708
|
+
*
|
|
709
|
+
* 参考:
|
|
710
|
+
* Reference:
|
|
711
|
+
* - https://www.lodashjs.com
|
|
712
|
+
* - https://lodash.com
|
|
713
|
+
*/
|
|
714
|
+
class Lodash {
|
|
1208
715
|
/**
|
|
1209
|
-
*
|
|
1210
|
-
*
|
|
1211
|
-
*
|
|
1212
|
-
* @param {...any} msg 日志内容 / Log messages.
|
|
1213
|
-
* @returns {void}
|
|
1214
|
-
*/
|
|
1215
|
-
static exception = (...msg) => Console.error(...msg);
|
|
1216
|
-
|
|
1217
|
-
/**
|
|
1218
|
-
* 进入日志分组。
|
|
1219
|
-
* Enter a log group.
|
|
716
|
+
* HTML 特殊字符转义。
|
|
717
|
+
* Escape HTML special characters.
|
|
1220
718
|
*
|
|
1221
|
-
* @param {string}
|
|
1222
|
-
* @returns {
|
|
719
|
+
* @param {string} string 输入文本 / Input text.
|
|
720
|
+
* @returns {string}
|
|
721
|
+
* @see {@link https://lodash.com/docs/#escape lodash.escape}
|
|
722
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.escape lodash.escape (中文)}
|
|
1223
723
|
*/
|
|
1224
|
-
static
|
|
724
|
+
static escape(string) {
|
|
725
|
+
const map = {
|
|
726
|
+
"&": "&",
|
|
727
|
+
"<": "<",
|
|
728
|
+
">": ">",
|
|
729
|
+
'"': """,
|
|
730
|
+
"'": "'",
|
|
731
|
+
};
|
|
732
|
+
return string.replace(/[&<>"']/g, m => map[m]);
|
|
733
|
+
}
|
|
1225
734
|
|
|
1226
735
|
/**
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
736
|
+
* 按路径读取对象值。
|
|
737
|
+
* Get object value by path.
|
|
1229
738
|
*
|
|
739
|
+
* @param {object} [object={}] 目标对象 / Target object.
|
|
740
|
+
* @param {string|string[]} [path=""] 路径 / Path.
|
|
741
|
+
* @param {*} [defaultValue=undefined] 默认值 / Default value.
|
|
1230
742
|
* @returns {*}
|
|
743
|
+
* @see {@link https://lodash.com/docs/#get lodash.get}
|
|
744
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.get lodash.get (中文)}
|
|
1231
745
|
*/
|
|
1232
|
-
static
|
|
746
|
+
static get(object = {}, path = "", defaultValue = undefined) {
|
|
747
|
+
// translate array case to dot case, then split with .
|
|
748
|
+
// a[0].b -> a.0.b -> ['a', '0', 'b']
|
|
749
|
+
if (!Array.isArray(path)) path = Lodash.toPath(path);
|
|
1233
750
|
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
* @param {...any} msg 日志内容 / Log messages.
|
|
1239
|
-
* @returns {void}
|
|
1240
|
-
*/
|
|
1241
|
-
static info(...msg) {
|
|
1242
|
-
if (Console.#level < 3) return;
|
|
1243
|
-
msg = msg.map(m => `ℹ️ ${m}`);
|
|
1244
|
-
Console.log(...msg);
|
|
751
|
+
const result = path.reduce((previousValue, currentValue) => {
|
|
752
|
+
return Object(previousValue)[currentValue]; // null undefined get attribute will throwError, Object() can return a object
|
|
753
|
+
}, object);
|
|
754
|
+
return result === undefined ? defaultValue : result;
|
|
1245
755
|
}
|
|
1246
756
|
|
|
1247
|
-
static #level = 3;
|
|
1248
|
-
|
|
1249
757
|
/**
|
|
1250
|
-
*
|
|
1251
|
-
*
|
|
758
|
+
* 递归合并源对象的自身可枚举属性到目标对象
|
|
759
|
+
* Recursively merge source enumerable properties into target object.
|
|
760
|
+
* @description 简化版 lodash.merge,用于合并配置对象
|
|
761
|
+
* @description A simplified lodash.merge for config merging.
|
|
1252
762
|
*
|
|
1253
|
-
*
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
763
|
+
* 适用情况:
|
|
764
|
+
* - 合并嵌套的配置/设置对象
|
|
765
|
+
* - 需要深度合并而非浅层覆盖的场景
|
|
766
|
+
* - 多个源对象依次合并到目标对象
|
|
767
|
+
*
|
|
768
|
+
* 限制:
|
|
769
|
+
* - 仅处理普通对象 (Plain Object),不处理 Date/RegExp 等特殊对象
|
|
770
|
+
* - Map/Set 仅支持同类型合并,不递归内部值
|
|
771
|
+
* - 数组会被直接覆盖,不会合并数组元素
|
|
772
|
+
* - 不处理循环引用,可能导致栈溢出
|
|
773
|
+
* - 不复制 Symbol 属性和不可枚举属性
|
|
774
|
+
* - 不保留原型链,仅处理自身属性
|
|
775
|
+
* - 会修改原始目标对象 (mutates target)
|
|
776
|
+
*
|
|
777
|
+
* @param {object} object - 目标对象
|
|
778
|
+
* @param {object} object - Target object.
|
|
779
|
+
* @param {...object} sources - 源对象(可多个)
|
|
780
|
+
* @param {...object} sources - Source objects.
|
|
781
|
+
* @returns {object} 返回合并后的目标对象
|
|
782
|
+
* @returns {object} Merged target object.
|
|
783
|
+
* @see {@link https://lodash.com/docs/#merge lodash.merge}
|
|
784
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.merge lodash.merge (中文)}
|
|
785
|
+
* @example
|
|
786
|
+
* const target = { a: { b: 1 }, c: 2 };
|
|
787
|
+
* const source = { a: { d: 3 }, e: 4 };
|
|
788
|
+
* Lodash.merge(target, source);
|
|
789
|
+
* // => { a: { b: 1, d: 3 }, c: 2, e: 4 }
|
|
790
|
+
*/
|
|
791
|
+
static merge(object, ...sources) {
|
|
792
|
+
if (object === null || object === undefined) return object;
|
|
793
|
+
|
|
794
|
+
for (const source of sources) {
|
|
795
|
+
if (source === null || source === undefined) continue;
|
|
796
|
+
|
|
797
|
+
for (const key of Object.keys(source)) {
|
|
798
|
+
const sourceValue = source[key];
|
|
799
|
+
const targetValue = object[key];
|
|
800
|
+
|
|
801
|
+
switch (true) {
|
|
802
|
+
case Lodash.#isPlainObject(sourceValue) && Lodash.#isPlainObject(targetValue):
|
|
803
|
+
// 递归合并对象
|
|
804
|
+
object[key] = Lodash.merge(targetValue, sourceValue);
|
|
805
|
+
break;
|
|
806
|
+
case sourceValue instanceof Map && targetValue instanceof Map:
|
|
807
|
+
// 合并 Map(空 Map 跳过)
|
|
808
|
+
if (sourceValue.size > 0) {
|
|
809
|
+
for (const [k, v] of sourceValue) {
|
|
810
|
+
targetValue.set(k, v);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
break;
|
|
814
|
+
case sourceValue instanceof Set && targetValue instanceof Set:
|
|
815
|
+
// 合并 Set(空 Set 跳过)
|
|
816
|
+
if (sourceValue.size > 0) {
|
|
817
|
+
for (const v of sourceValue) {
|
|
818
|
+
targetValue.add(v);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
break;
|
|
822
|
+
case Array.isArray(sourceValue) && sourceValue.length === 0 && targetValue !== undefined:
|
|
823
|
+
// 空数组不覆盖已有值
|
|
824
|
+
break;
|
|
825
|
+
case (sourceValue instanceof Map && sourceValue.size === 0 && targetValue !== undefined):
|
|
826
|
+
case (sourceValue instanceof Set && sourceValue.size === 0 && targetValue !== undefined):
|
|
827
|
+
// 空 Map/Set 不覆盖已有值
|
|
828
|
+
break;
|
|
829
|
+
case sourceValue !== undefined:
|
|
830
|
+
object[key] = sourceValue;
|
|
831
|
+
break;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
1270
834
|
}
|
|
835
|
+
|
|
836
|
+
return object;
|
|
1271
837
|
}
|
|
1272
838
|
|
|
1273
839
|
/**
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
*
|
|
1277
|
-
* @param {
|
|
840
|
+
* 判断值是否为普通对象 (Plain Object)
|
|
841
|
+
* Check whether a value is a plain object.
|
|
842
|
+
* @param {*} value - 要检查的值
|
|
843
|
+
* @param {*} value - Value to check.
|
|
844
|
+
* @returns {boolean} 如果是普通对象返回 true
|
|
845
|
+
* @returns {boolean} Returns true when value is a plain object.
|
|
846
|
+
* @see {@link https://lodash.com/docs/#isPlainObject lodash.isPlainObject}
|
|
847
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.isPlainObject lodash.isPlainObject (中文)}
|
|
1278
848
|
*/
|
|
1279
|
-
static
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
break;
|
|
1284
|
-
case "number":
|
|
1285
|
-
break;
|
|
1286
|
-
case "undefined":
|
|
1287
|
-
default:
|
|
1288
|
-
level = "warn";
|
|
1289
|
-
break;
|
|
1290
|
-
}
|
|
1291
|
-
switch (level) {
|
|
1292
|
-
case 0:
|
|
1293
|
-
case "off":
|
|
1294
|
-
Console.#level = 0;
|
|
1295
|
-
break;
|
|
1296
|
-
case 1:
|
|
1297
|
-
case "error":
|
|
1298
|
-
Console.#level = 1;
|
|
1299
|
-
break;
|
|
1300
|
-
case 2:
|
|
1301
|
-
case "warn":
|
|
1302
|
-
case "warning":
|
|
1303
|
-
default:
|
|
1304
|
-
Console.#level = 2;
|
|
1305
|
-
break;
|
|
1306
|
-
case 3:
|
|
1307
|
-
case "info":
|
|
1308
|
-
Console.#level = 3;
|
|
1309
|
-
break;
|
|
1310
|
-
case 4:
|
|
1311
|
-
case "debug":
|
|
1312
|
-
Console.#level = 4;
|
|
1313
|
-
break;
|
|
1314
|
-
case 5:
|
|
1315
|
-
case "all":
|
|
1316
|
-
Console.#level = 5;
|
|
1317
|
-
break;
|
|
1318
|
-
}
|
|
849
|
+
static #isPlainObject(value) {
|
|
850
|
+
if (value === null || typeof value !== "object") return false;
|
|
851
|
+
const proto = Object.getPrototypeOf(value);
|
|
852
|
+
return proto === null || proto === Object.prototype;
|
|
1319
853
|
}
|
|
1320
854
|
|
|
1321
855
|
/**
|
|
1322
|
-
*
|
|
1323
|
-
*
|
|
1324
|
-
*
|
|
1325
|
-
* 说明:
|
|
1326
|
-
* Notes:
|
|
1327
|
-
* - 多行字符串参数会按换行拆分为多个独立日志项。
|
|
1328
|
-
* - Multi-line string arguments are split into multiple log entries by line breaks.
|
|
856
|
+
* 删除对象指定路径并返回对象。
|
|
857
|
+
* Omit paths from object and return the same object.
|
|
1329
858
|
*
|
|
1330
|
-
* @param {
|
|
1331
|
-
* @
|
|
859
|
+
* @param {object} [object={}] 目标对象 / Target object.
|
|
860
|
+
* @param {string|string[]} [paths=[]] 要删除的路径 / Paths to remove.
|
|
861
|
+
* @returns {object}
|
|
862
|
+
* @see {@link https://lodash.com/docs/#omit lodash.omit}
|
|
863
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.omit lodash.omit (中文)}
|
|
1332
864
|
*/
|
|
1333
|
-
static
|
|
1334
|
-
if (
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
return [JSON.stringify(log)];
|
|
1339
|
-
case "bigint":
|
|
1340
|
-
case "number":
|
|
1341
|
-
case "boolean":
|
|
1342
|
-
return [log.toString()];
|
|
1343
|
-
case "string":
|
|
1344
|
-
return log.split(/\r?\n/u);
|
|
1345
|
-
case "undefined":
|
|
1346
|
-
default:
|
|
1347
|
-
return [log];
|
|
1348
|
-
}
|
|
1349
|
-
});
|
|
1350
|
-
Console.#groups.forEach(group => {
|
|
1351
|
-
msg = msg.map(log => ` ${log}`);
|
|
1352
|
-
msg.unshift(`▼ ${group}:`);
|
|
1353
|
-
});
|
|
1354
|
-
msg = ["", ...msg];
|
|
1355
|
-
console.log(msg.join("\n"));
|
|
1356
|
-
};
|
|
865
|
+
static omit(object = {}, paths = []) {
|
|
866
|
+
if (!Array.isArray(paths)) paths = [paths.toString()];
|
|
867
|
+
paths.forEach(path => Lodash.unset(object, path));
|
|
868
|
+
return object;
|
|
869
|
+
}
|
|
1357
870
|
|
|
1358
871
|
/**
|
|
1359
|
-
*
|
|
1360
|
-
*
|
|
872
|
+
* 仅保留对象指定键(第一层)。
|
|
873
|
+
* Pick selected keys from object (top level only).
|
|
1361
874
|
*
|
|
1362
|
-
* @param {
|
|
1363
|
-
* @
|
|
875
|
+
* @param {object} [object={}] 目标对象 / Target object.
|
|
876
|
+
* @param {string|string[]} [paths=[]] 需要保留的键 / Keys to keep.
|
|
877
|
+
* @returns {object}
|
|
878
|
+
* @see {@link https://lodash.com/docs/#pick lodash.pick}
|
|
879
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.pick lodash.pick (中文)}
|
|
1364
880
|
*/
|
|
1365
|
-
static
|
|
881
|
+
static pick(object = {}, paths = []) {
|
|
882
|
+
if (!Array.isArray(paths)) paths = [paths.toString()];
|
|
883
|
+
const filteredEntries = Object.entries(object).filter(([key, value]) => paths.includes(key));
|
|
884
|
+
return Object.fromEntries(filteredEntries);
|
|
885
|
+
}
|
|
1366
886
|
|
|
1367
887
|
/**
|
|
1368
|
-
*
|
|
1369
|
-
*
|
|
888
|
+
* 按路径写入对象值。
|
|
889
|
+
* Set object value by path.
|
|
1370
890
|
*
|
|
1371
|
-
* @param {
|
|
1372
|
-
* @
|
|
891
|
+
* @param {object} object 目标对象 / Target object.
|
|
892
|
+
* @param {string|string[]} path 路径 / Path.
|
|
893
|
+
* @param {*} value 写入值 / Value.
|
|
894
|
+
* @returns {object}
|
|
895
|
+
* @see {@link https://lodash.com/docs/#set lodash.set}
|
|
896
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.set lodash.set (中文)}
|
|
1373
897
|
*/
|
|
1374
|
-
static
|
|
898
|
+
static set(object, path, value) {
|
|
899
|
+
if (!Array.isArray(path)) path = Lodash.toPath(path);
|
|
900
|
+
path.slice(0, -1).reduce((previousValue, currentValue, currentIndex) => (Object(previousValue[currentValue]) === previousValue[currentValue] ? previousValue[currentValue] : (previousValue[currentValue] = /^\d+$/.test(path[currentIndex + 1]) ? [] : {})), object)[path[path.length - 1]] = value;
|
|
901
|
+
return object;
|
|
902
|
+
}
|
|
1375
903
|
|
|
1376
904
|
/**
|
|
1377
|
-
*
|
|
1378
|
-
*
|
|
905
|
+
* 将点路径或数组下标路径转换为数组。
|
|
906
|
+
* Convert dot/array-index path string into path segments.
|
|
1379
907
|
*
|
|
1380
|
-
* @param {string}
|
|
1381
|
-
* @returns {
|
|
908
|
+
* @param {string} value 路径字符串 / Path string.
|
|
909
|
+
* @returns {string[]}
|
|
910
|
+
* @see {@link https://lodash.com/docs/#toPath lodash.toPath}
|
|
911
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.toPath lodash.toPath (中文)}
|
|
1382
912
|
*/
|
|
1383
|
-
static
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
913
|
+
static toPath(value) {
|
|
914
|
+
return value
|
|
915
|
+
.replace(/\[(\d+)\]/g, ".$1")
|
|
916
|
+
.split(".")
|
|
917
|
+
.filter(Boolean);
|
|
918
|
+
}
|
|
1388
919
|
|
|
1389
920
|
/**
|
|
1390
|
-
*
|
|
1391
|
-
*
|
|
921
|
+
* HTML 实体反转义。
|
|
922
|
+
* Unescape HTML entities.
|
|
1392
923
|
*
|
|
1393
|
-
* @param {
|
|
1394
|
-
* @returns {
|
|
924
|
+
* @param {string} string 输入文本 / Input text.
|
|
925
|
+
* @returns {string}
|
|
926
|
+
* @see {@link https://lodash.com/docs/#unescape lodash.unescape}
|
|
927
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.unescape lodash.unescape (中文)}
|
|
1395
928
|
*/
|
|
1396
|
-
static
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
929
|
+
static unescape(string) {
|
|
930
|
+
const map = {
|
|
931
|
+
"&": "&",
|
|
932
|
+
"<": "<",
|
|
933
|
+
">": ">",
|
|
934
|
+
""": '"',
|
|
935
|
+
"'": "'",
|
|
936
|
+
};
|
|
937
|
+
return string.replace(/&|<|>|"|'/g, m => map[m]);
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* 删除对象路径对应的值。
|
|
942
|
+
* Remove value by object path.
|
|
943
|
+
*
|
|
944
|
+
* @param {object} [object={}] 目标对象 / Target object.
|
|
945
|
+
* @param {string|string[]} [path=""] 路径 / Path.
|
|
946
|
+
* @returns {boolean}
|
|
947
|
+
* @see {@link https://lodash.com/docs/#unset lodash.unset}
|
|
948
|
+
* @see {@link https://www.lodashjs.com/docs/lodash.unset lodash.unset (中文)}
|
|
949
|
+
*/
|
|
950
|
+
static unset(object = {}, path = "") {
|
|
951
|
+
if (!Array.isArray(path)) path = Lodash.toPath(path);
|
|
952
|
+
const result = path.reduce((previousValue, currentValue, currentIndex) => {
|
|
953
|
+
if (currentIndex === path.length - 1) {
|
|
954
|
+
delete previousValue[currentValue];
|
|
955
|
+
return true;
|
|
956
|
+
}
|
|
957
|
+
return Object(previousValue)[currentValue];
|
|
958
|
+
}, object);
|
|
959
|
+
return result;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/* https://github.com/ljharb/qs */
|
|
964
|
+
/**
|
|
965
|
+
* 轻量 `qs` 查询字符串工具。
|
|
966
|
+
* Lightweight `qs` query-string utilities.
|
|
967
|
+
*
|
|
968
|
+
* 说明:
|
|
969
|
+
* Notes:
|
|
970
|
+
* - 参考 `qs` 的 `parse` / `stringify` 接口设计
|
|
971
|
+
* - Modeled after the `qs` `parse` / `stringify` API
|
|
972
|
+
* - `parse` 保持当前项目原有 `$argument` 字符串解析语义
|
|
973
|
+
* - `parse` preserves the existing `$argument` string parsing semantics
|
|
974
|
+
* - `stringify` 基于项目内 `Lodash` 路径能力展开对象
|
|
975
|
+
* - `stringify` expands objects via the in-project `Lodash` path helpers
|
|
976
|
+
*
|
|
977
|
+
* 参考:
|
|
978
|
+
* Reference:
|
|
979
|
+
* - https://github.com/ljharb/qs
|
|
980
|
+
* - https://www.npmjs.com/package/qs
|
|
981
|
+
*/
|
|
982
|
+
class qs {
|
|
983
|
+
/**
|
|
984
|
+
* 将查询字符串解析为对象。
|
|
985
|
+
* Parse a query string into an object.
|
|
986
|
+
*
|
|
987
|
+
* @param {string | Record<string, unknown> | null | undefined} [query=""] 查询字符串或对象 / Query string or object.
|
|
988
|
+
* @returns {Record<string, unknown>}
|
|
989
|
+
*/
|
|
990
|
+
static parse(query) {
|
|
991
|
+
let result = {};
|
|
992
|
+
switch (typeof query) {
|
|
993
|
+
case "string": {
|
|
994
|
+
const source = query.replace(/^\?/, "");
|
|
995
|
+
if (!source) break;
|
|
996
|
+
const obj = Object.fromEntries(
|
|
997
|
+
source
|
|
998
|
+
.split("&")
|
|
999
|
+
.filter(Boolean)
|
|
1000
|
+
.map(item => {
|
|
1001
|
+
const [rawKey = "", rawValue = ""] = item.split("=", 2);
|
|
1002
|
+
const key = qs.#decode(rawKey).replace(/\[([^\[\]]+)\]/g, ".$1");
|
|
1003
|
+
return [key, qs.#decode(rawValue).replace(/\"/g, "")];
|
|
1004
|
+
}),
|
|
1005
|
+
);
|
|
1006
|
+
Object.keys(obj).forEach(key => Lodash.set(result, key, obj[key]));
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
1009
|
+
case "object": {
|
|
1010
|
+
switch (query) {
|
|
1011
|
+
case null:
|
|
1012
|
+
break;
|
|
1013
|
+
default: {
|
|
1014
|
+
const obj = {};
|
|
1015
|
+
Object.keys(query).forEach(key => Lodash.set(obj, key, query[key]));
|
|
1016
|
+
result = obj;
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
break;
|
|
1021
|
+
}
|
|
1022
|
+
case "undefined":
|
|
1023
|
+
result = {};
|
|
1024
|
+
break;
|
|
1025
|
+
}
|
|
1026
|
+
return result;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* 将对象序列化为查询字符串。
|
|
1031
|
+
* Serialize an object into a query string.
|
|
1032
|
+
*
|
|
1033
|
+
* @param {Record<string, unknown>} [object={}] 输入对象 / Input object.
|
|
1034
|
+
* @returns {string}
|
|
1035
|
+
*/
|
|
1036
|
+
static stringify(object = {}) {
|
|
1037
|
+
if (!object || typeof object !== "object") return "";
|
|
1038
|
+
|
|
1039
|
+
const entries = [];
|
|
1040
|
+
Object.keys(object).forEach(key => qs.#collect(object, key, entries));
|
|
1041
|
+
|
|
1042
|
+
if (entries.length === 0) return "";
|
|
1043
|
+
return entries
|
|
1044
|
+
.map(([key, value]) => `${qs.#encode(qs.#formatPath(key))}=${qs.#encode(value)}`)
|
|
1045
|
+
.join("&");
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/**
|
|
1049
|
+
* 收集待序列化的键值对。
|
|
1050
|
+
* Collect key-value pairs for stringification.
|
|
1051
|
+
*
|
|
1052
|
+
* @param {Record<string, unknown>} object 输入对象 / Input object.
|
|
1053
|
+
* @param {string} path 当前路径 / Current path.
|
|
1054
|
+
* @param {[string, string][]} entries 输出数组 / Output entries.
|
|
1055
|
+
* @returns {void}
|
|
1056
|
+
*/
|
|
1057
|
+
static #collect(object, path, entries) {
|
|
1058
|
+
const value = Lodash.get(object, path);
|
|
1059
|
+
if (value === undefined) return;
|
|
1060
|
+
if (value === null) {
|
|
1061
|
+
entries.push([path, ""]);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
if (Array.isArray(value)) {
|
|
1065
|
+
value.forEach((item, index) => {
|
|
1066
|
+
if (item === undefined) return;
|
|
1067
|
+
qs.#collect(object, `${path}[${index}]`, entries);
|
|
1068
|
+
});
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
if (qs.#isPlainObject(value)) {
|
|
1072
|
+
Object.keys(value).forEach(key => qs.#collect(object, `${path}.${key}`, entries));
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
entries.push([path, String(value)]);
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/**
|
|
1079
|
+
* 使用 `Lodash.toPath` 规范化输出路径。
|
|
1080
|
+
* Normalize output path via `Lodash.toPath`.
|
|
1081
|
+
*
|
|
1082
|
+
* @param {string} path 原始路径 / Raw path.
|
|
1083
|
+
* @returns {string}
|
|
1084
|
+
*/
|
|
1085
|
+
static #formatPath(path) {
|
|
1086
|
+
const [head, ...tail] = Lodash.toPath(path);
|
|
1087
|
+
return tail.reduce((result, segment) => (/^\d+$/.test(segment) ? `${result}[${segment}]` : `${result}.${segment}`), head);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/**
|
|
1091
|
+
* 判断值是否为普通对象。
|
|
1092
|
+
* Check whether a value is a plain object.
|
|
1093
|
+
*
|
|
1094
|
+
* @param {unknown} value 输入值 / Input value.
|
|
1095
|
+
* @returns {boolean}
|
|
1096
|
+
*/
|
|
1097
|
+
static #isPlainObject(value) {
|
|
1098
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1099
|
+
const proto = Object.getPrototypeOf(value);
|
|
1100
|
+
return proto === null || proto === Object.prototype;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* 编码查询字符串片段。
|
|
1105
|
+
* Encode a query-string fragment.
|
|
1106
|
+
*
|
|
1107
|
+
* @param {string} value 原始值 / Raw value.
|
|
1108
|
+
* @returns {string}
|
|
1109
|
+
*/
|
|
1110
|
+
static #encode(value) {
|
|
1111
|
+
return encodeURIComponent(value);
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* 解码查询字符串片段。
|
|
1116
|
+
* Decode a query-string fragment.
|
|
1117
|
+
*
|
|
1118
|
+
* @param {string} value 编码值 / Encoded value.
|
|
1119
|
+
* @returns {string}
|
|
1120
|
+
*/
|
|
1121
|
+
static #decode(value) {
|
|
1122
|
+
return decodeURIComponent(value.replace(/\+/g, " "));
|
|
1400
1123
|
}
|
|
1401
1124
|
}
|
|
1402
1125
|
|
|
1126
|
+
/**
|
|
1127
|
+
* 统一 `$argument` 输入格式并展开深路径。
|
|
1128
|
+
* Normalize `$argument` input format and expand deep paths.
|
|
1129
|
+
*
|
|
1130
|
+
* 平台差异:
|
|
1131
|
+
* Platform differences:
|
|
1132
|
+
* - Surge / Stash / Egern 常见为字符串参数: `a=1&b=2`
|
|
1133
|
+
* - Surge / Stash / Egern usually pass string args: `a=1&b=2`
|
|
1134
|
+
* - Loon 支持字符串和对象两种形态
|
|
1135
|
+
* - Loon supports both string and object forms
|
|
1136
|
+
* - Quantumult X / Shadowrocket 一般不提供 `$argument`
|
|
1137
|
+
* - Quantumult X / Shadowrocket usually do not expose `$argument`
|
|
1138
|
+
*
|
|
1139
|
+
* 执行时机:
|
|
1140
|
+
* Execution timing:
|
|
1141
|
+
* - 该模块为即时执行模块,`import` 时立即处理全局 `$argument`
|
|
1142
|
+
* - This module executes immediately and mutates global `$argument` on import
|
|
1143
|
+
*
|
|
1144
|
+
* 归一化规则补充:
|
|
1145
|
+
* Normalization details:
|
|
1146
|
+
* - 使用 `globalThis.$argument` 读写,避免运行环境下未声明变量引用问题
|
|
1147
|
+
* - Read/write via `globalThis.$argument` to avoid undeclared variable access
|
|
1148
|
+
* - 当 `$argument` 为 `null` 或 `undefined` 时,会重置为 `{}`
|
|
1149
|
+
* - When `$argument` is `null` or `undefined`, it is normalized to `{}`
|
|
1150
|
+
*/
|
|
1151
|
+
(() => {
|
|
1152
|
+
Console.debug("☑️ $argument");
|
|
1153
|
+
globalThis.$argument = qs.parse(globalThis.$argument);
|
|
1154
|
+
if (globalThis.$argument.LogLevel) Console.logLevel = globalThis.$argument.LogLevel;
|
|
1155
|
+
Console.debug("✅ $argument", `$argument: ${JSON.stringify(globalThis.$argument)}`);
|
|
1156
|
+
})();
|
|
1157
|
+
|
|
1403
1158
|
/**
|
|
1404
1159
|
* HTTP 状态码文本映射表。
|
|
1405
1160
|
* HTTP status code to status text map.
|
|
@@ -1573,50 +1328,782 @@
|
|
|
1573
1328
|
}
|
|
1574
1329
|
|
|
1575
1330
|
/**
|
|
1576
|
-
*
|
|
1577
|
-
*
|
|
1578
|
-
*
|
|
1579
|
-
* @
|
|
1331
|
+
* 统一请求参数。
|
|
1332
|
+
* Unified request payload.
|
|
1333
|
+
*
|
|
1334
|
+
* @typedef {object} FetchRequest
|
|
1335
|
+
* @property {string} url 请求地址 / Request URL.
|
|
1336
|
+
* @property {string} [method] 请求方法 / HTTP method.
|
|
1337
|
+
* @property {Record<string, any>} [headers] 请求头 / Request headers.
|
|
1338
|
+
* @property {string|ArrayBuffer|ArrayBufferView|object} [body] 请求体 / Request body.
|
|
1339
|
+
* @property {ArrayBuffer} [bodyBytes] 二进制请求体 / Binary request body.
|
|
1340
|
+
* @property {number|string} [timeout] 超时(秒或毫秒)/ Timeout (seconds or milliseconds).
|
|
1341
|
+
* @property {string} [policy] 指定策略 / Preferred policy.
|
|
1342
|
+
* @property {boolean} [redirection] 是否跟随重定向 / Whether to follow redirects.
|
|
1343
|
+
* @property {boolean} ["auto-redirect"] 平台重定向字段 / Platform redirect flag.
|
|
1344
|
+
* @property {boolean|number|string} ["auto-cookie"] Worker / Node.js Cookie 开关 / Worker / Node.js Cookie toggle.
|
|
1345
|
+
* @property {Record<string, any>} [opts] 平台扩展字段 / Platform extension fields.
|
|
1580
1346
|
*/
|
|
1581
|
-
function complete(result) {
|
|
1582
|
-
if (!result) {
|
|
1583
|
-
done({});
|
|
1584
|
-
return;
|
|
1585
|
-
}
|
|
1586
|
-
done($app === "Quantumult X" ? result : { response: result });
|
|
1587
|
-
}
|
|
1588
1347
|
|
|
1589
1348
|
/**
|
|
1590
|
-
*
|
|
1591
|
-
*
|
|
1592
|
-
*
|
|
1349
|
+
* 统一响应结构。
|
|
1350
|
+
* Unified response payload.
|
|
1351
|
+
*
|
|
1352
|
+
* @typedef {object} FetchResponse
|
|
1353
|
+
* @property {boolean} ok 请求是否成功 / Whether request is successful.
|
|
1354
|
+
* @property {number} status 状态码 / HTTP status code.
|
|
1355
|
+
* @property {number} [statusCode] 状态码别名 / Status code alias.
|
|
1356
|
+
* @property {string} [statusText] 状态文本 / HTTP status text.
|
|
1357
|
+
* @property {Record<string, any>} [headers] 响应头 / Response headers.
|
|
1358
|
+
* @property {string|ArrayBuffer} [body] 响应体 / Response body.
|
|
1359
|
+
* @property {ArrayBuffer} [bodyBytes] 二进制响应体 / Binary response body.
|
|
1593
1360
|
*/
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* 跨平台 `fetch` 适配层。
|
|
1364
|
+
* Cross-platform `fetch` adapter.
|
|
1365
|
+
*
|
|
1366
|
+
* 设计目标:
|
|
1367
|
+
* Design goal:
|
|
1368
|
+
* - 仿照 Web API `fetch`(`Window.fetch`)接口设计
|
|
1369
|
+
* - Modeled after Web API `fetch` (`Window.fetch`)
|
|
1370
|
+
* - 统一 VPN App、Worker 与 Node.js 环境中的请求调用
|
|
1371
|
+
* - Unify request calls across VPN apps, Worker, and Node.js
|
|
1372
|
+
*
|
|
1373
|
+
* 功能:
|
|
1374
|
+
* Features:
|
|
1375
|
+
* - 统一 Quantumult X / Loon / Surge / Stash / Egern / Shadowrocket / Worker / Node.js 请求接口
|
|
1376
|
+
* - Normalize request APIs across Quantumult X / Loon / Surge / Stash / Egern / Shadowrocket / Worker / Node.js
|
|
1377
|
+
* - 统一返回体字段(`ok/status/statusText/body/bodyBytes`)
|
|
1378
|
+
* - Normalize response fields (`ok/status/statusText/body/bodyBytes`)
|
|
1379
|
+
*
|
|
1380
|
+
* 与 Web `fetch` 的已知差异:
|
|
1381
|
+
* Known differences from Web `fetch`:
|
|
1382
|
+
* - 支持 `policy`、`auto-redirect` 等平台扩展字段
|
|
1383
|
+
* - Supports platform extension fields like `policy` and `auto-redirect`
|
|
1384
|
+
* - Worker / Node.js 共享基于 `fetch` 的请求分支
|
|
1385
|
+
* - Worker / Node.js share the `fetch`-based request branch
|
|
1386
|
+
* - Node.js ESM 的 `auto-cookie` 由 `fetch.node.mjs` 处理,本文件只使用宿主 `fetch`
|
|
1387
|
+
* - Node.js ESM `auto-cookie` is handled by `fetch.node.mjs`; this module only uses the host `fetch`
|
|
1388
|
+
* - 非浏览器平台通过 `$httpClient/$task` 实现,不是原生 Fetch 实现
|
|
1389
|
+
* - Non-browser platforms use `$httpClient/$task` instead of native Fetch engine
|
|
1390
|
+
* - 返回结构包含 `statusCode/bodyBytes` 等兼容字段
|
|
1391
|
+
* - Response includes compatibility fields like `statusCode/bodyBytes`
|
|
1392
|
+
*
|
|
1393
|
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch
|
|
1394
|
+
* @link https://developer.mozilla.org/zh-CN/docs/Web/API/Window/fetch
|
|
1395
|
+
* @async
|
|
1396
|
+
* @param {FetchRequest|string} resource 请求对象或 URL / Request object or URL string.
|
|
1397
|
+
* @param {Partial<FetchRequest>} [options={}] 追加参数 / Extra options.
|
|
1398
|
+
* @returns {Promise<FetchResponse>}
|
|
1399
|
+
*/
|
|
1400
|
+
async function fetch(resource, options = {}) {
|
|
1401
|
+
// 初始化参数。
|
|
1402
|
+
// Initialize request input.
|
|
1403
|
+
switch (typeof resource) {
|
|
1404
|
+
case "object":
|
|
1405
|
+
resource = { ...options, ...resource };
|
|
1406
|
+
break;
|
|
1407
|
+
case "string":
|
|
1408
|
+
resource = { ...options, url: resource };
|
|
1409
|
+
break;
|
|
1410
|
+
case "undefined":
|
|
1411
|
+
default:
|
|
1412
|
+
throw new TypeError(`${Function.name}: 参数类型错误, resource 必须为对象或字符串`);
|
|
1413
|
+
}
|
|
1414
|
+
// 自动判断请求方法。
|
|
1415
|
+
// Infer the HTTP method automatically.
|
|
1416
|
+
if (!resource.method) {
|
|
1417
|
+
resource.method = "GET";
|
|
1418
|
+
if (resource.body ?? resource.bodyBytes) resource.method = "POST";
|
|
1419
|
+
}
|
|
1420
|
+
// 移除需要由底层实现自动生成的请求头。
|
|
1421
|
+
// Remove headers that should be generated by the underlying runtime.
|
|
1422
|
+
delete resource.headers?.Host;
|
|
1423
|
+
delete resource.headers?.[":authority"];
|
|
1424
|
+
delete resource.headers?.["Content-Length"];
|
|
1425
|
+
delete resource.headers?.["content-length"];
|
|
1426
|
+
// 统一请求方法为小写,方便后续索引平台 API。
|
|
1427
|
+
// Normalize the method to lowercase for platform API lookups.
|
|
1428
|
+
const method = resource.method.toLocaleLowerCase();
|
|
1429
|
+
// 默认请求超时时间为 5 秒。
|
|
1430
|
+
// Default request timeout to 5 seconds.
|
|
1431
|
+
if (!resource.timeout) resource.timeout = 5;
|
|
1432
|
+
if (resource.timeout) {
|
|
1433
|
+
resource.timeout = Number.parseInt(resource.timeout, 10);
|
|
1434
|
+
// 统一先转换为秒,大于 500 视为毫秒输入。
|
|
1435
|
+
// Convert to seconds first and treat values above 500 as milliseconds.
|
|
1436
|
+
if (resource.timeout > 500) resource.timeout = Math.round(resource.timeout / 1000);
|
|
1437
|
+
}
|
|
1438
|
+
if (resource.timeout) {
|
|
1439
|
+
switch ($app) {
|
|
1440
|
+
case "Loon":
|
|
1441
|
+
case "Quantumult X":
|
|
1442
|
+
case "Worker":
|
|
1443
|
+
case "Node.js":
|
|
1444
|
+
// 这些平台要求毫秒,因此把秒重新换算为毫秒。
|
|
1445
|
+
// These platforms expect milliseconds, so convert seconds back to milliseconds.
|
|
1446
|
+
resource.timeout = resource.timeout * 1000;
|
|
1447
|
+
break;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
// 根据当前平台选择请求实现。
|
|
1451
|
+
// Select the request engine for the current platform.
|
|
1452
|
+
switch ($app) {
|
|
1453
|
+
case "Loon":
|
|
1454
|
+
case "Surge":
|
|
1455
|
+
case "Stash":
|
|
1456
|
+
case "Egern":
|
|
1457
|
+
case "Shadowrocket":
|
|
1458
|
+
// 转换通用请求参数到 `$httpClient` 语义。
|
|
1459
|
+
// Map shared request fields to `$httpClient` semantics.
|
|
1460
|
+
if (resource.policy) {
|
|
1461
|
+
switch ($app) {
|
|
1462
|
+
case "Loon":
|
|
1463
|
+
resource.node = resource.policy;
|
|
1464
|
+
break;
|
|
1465
|
+
case "Stash":
|
|
1466
|
+
Lodash.set(resource, "headers.X-Stash-Selected-Proxy", encodeURI(resource.policy));
|
|
1467
|
+
break;
|
|
1468
|
+
case "Shadowrocket":
|
|
1469
|
+
Lodash.set(resource, "headers.X-Surge-Proxy", resource.policy);
|
|
1470
|
+
break;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
if (typeof resource.redirection === "boolean") resource["auto-redirect"] = resource.redirection;
|
|
1474
|
+
// 优先把 `bodyBytes` 映射回 `$httpClient` 能接受的 `body`。
|
|
1475
|
+
// Prefer mapping `bodyBytes` back to the `body` field expected by `$httpClient`.
|
|
1476
|
+
if (resource.bodyBytes && !resource.body) {
|
|
1477
|
+
resource.body = resource.bodyBytes;
|
|
1478
|
+
resource.bodyBytes = undefined;
|
|
1479
|
+
}
|
|
1480
|
+
// 根据 `Accept` 推断是否需要二进制响应体。
|
|
1481
|
+
// Infer whether the response should be treated as binary from `Accept`.
|
|
1482
|
+
switch ((resource.headers?.Accept || resource.headers?.accept)?.split(";")?.[0]) {
|
|
1483
|
+
case "application/protobuf":
|
|
1484
|
+
case "application/x-protobuf":
|
|
1485
|
+
case "application/vnd.google.protobuf":
|
|
1486
|
+
case "application/vnd.apple.flatbuffer":
|
|
1487
|
+
case "application/grpc":
|
|
1488
|
+
case "application/grpc-web":
|
|
1489
|
+
case "application/grpc+proto":
|
|
1490
|
+
case "application/octet-stream":
|
|
1491
|
+
resource["binary-mode"] = true;
|
|
1492
|
+
break;
|
|
1493
|
+
}
|
|
1494
|
+
// 发送 `$httpClient` 请求并归一化返回结构。
|
|
1495
|
+
// Send the `$httpClient` request and normalize the response payload.
|
|
1496
|
+
return new Promise((resolve, reject) => {
|
|
1497
|
+
globalThis.$httpClient[method](resource, (error, response, body) => {
|
|
1498
|
+
if (error) reject(error);
|
|
1499
|
+
else {
|
|
1500
|
+
response.ok = /^2\d\d$/.test(response.status);
|
|
1501
|
+
response.statusCode = response.status;
|
|
1502
|
+
response.statusText = StatusTexts[response.status];
|
|
1503
|
+
if (body) {
|
|
1504
|
+
response.body = body;
|
|
1505
|
+
if (resource["binary-mode"] == true) response.bodyBytes = body;
|
|
1506
|
+
}
|
|
1507
|
+
resolve(response);
|
|
1508
|
+
}
|
|
1509
|
+
});
|
|
1510
|
+
});
|
|
1511
|
+
case "Quantumult X":
|
|
1512
|
+
// 转换 Quantumult X 专有请求参数。
|
|
1513
|
+
// Map request fields to Quantumult X specific options.
|
|
1514
|
+
if (resource.policy) Lodash.set(resource, "opts.policy", resource.policy);
|
|
1515
|
+
if (typeof resource["auto-redirect"] === "boolean") Lodash.set(resource, "opts.redirection", resource["auto-redirect"]);
|
|
1516
|
+
// Quantumult X 使用 `bodyBytes` 传输二进制请求体。
|
|
1517
|
+
// Quantumult X uses `bodyBytes` for binary request payloads.
|
|
1518
|
+
if (resource.body instanceof ArrayBuffer) {
|
|
1519
|
+
resource.bodyBytes = resource.body;
|
|
1520
|
+
resource.body = undefined;
|
|
1521
|
+
} else if (ArrayBuffer.isView(resource.body)) {
|
|
1522
|
+
resource.bodyBytes = resource.body.buffer.slice(resource.body.byteOffset, resource.body.byteLength + resource.body.byteOffset);
|
|
1523
|
+
resource.body = undefined;
|
|
1524
|
+
} else if (resource.body) resource.bodyBytes = undefined;
|
|
1525
|
+
// 发送请求,并用 `Promise.race` 提供统一超时保护。
|
|
1526
|
+
// Send the request and enforce timeout with `Promise.race`.
|
|
1527
|
+
return Promise.race([
|
|
1528
|
+
globalThis.$task.fetch(resource).then(
|
|
1529
|
+
response => {
|
|
1530
|
+
response.ok = /^2\d\d$/.test(response.statusCode);
|
|
1531
|
+
response.status = response.statusCode;
|
|
1532
|
+
response.statusText = StatusTexts[response.status];
|
|
1533
|
+
switch ((response.headers?.["Content-Type"] ?? response.headers?.["content-type"])?.split(";")?.[0]) {
|
|
1534
|
+
case "application/protobuf":
|
|
1535
|
+
case "application/x-protobuf":
|
|
1536
|
+
case "application/vnd.google.protobuf":
|
|
1537
|
+
case "application/vnd.apple.flatbuffer":
|
|
1538
|
+
case "application/grpc":
|
|
1539
|
+
case "application/grpc-web":
|
|
1540
|
+
case "application/grpc+proto":
|
|
1541
|
+
case "application/octet-stream":
|
|
1542
|
+
response.body = response.bodyBytes;
|
|
1543
|
+
break;
|
|
1544
|
+
}
|
|
1545
|
+
response.bodyBytes = undefined;
|
|
1546
|
+
return response;
|
|
1547
|
+
},
|
|
1548
|
+
reason => Promise.reject(reason.error),
|
|
1549
|
+
),
|
|
1550
|
+
new Promise((resolve, reject) => {
|
|
1551
|
+
setTimeout(() => {
|
|
1552
|
+
reject(new Error(`${Function.name}: 请求超时, 请检查网络后重试`));
|
|
1553
|
+
}, resource.timeout);
|
|
1554
|
+
}),
|
|
1555
|
+
]);
|
|
1556
|
+
case "Worker":
|
|
1557
|
+
case "Node.js":
|
|
1558
|
+
default: {
|
|
1559
|
+
let request;
|
|
1560
|
+
let timeout;
|
|
1561
|
+
let shouldWrapError = false;
|
|
1562
|
+
switch ($app) {
|
|
1563
|
+
case "Worker":
|
|
1564
|
+
case "Node.js":
|
|
1565
|
+
switch (typeof globalThis.fetch) {
|
|
1566
|
+
case "function":
|
|
1567
|
+
break;
|
|
1568
|
+
default:
|
|
1569
|
+
throw new Error(`${Function.name}: 当前运行环境不支持 Fetch API`);
|
|
1570
|
+
}
|
|
1571
|
+
// 将通用字段映射到 Worker / Node.js Fetch 语义。
|
|
1572
|
+
// Map shared fields to Worker / Node.js Fetch semantics.
|
|
1573
|
+
resource.redirect = resource.redirection ? "follow" : "manual";
|
|
1574
|
+
request = resource;
|
|
1575
|
+
timeout = resource.timeout;
|
|
1576
|
+
shouldWrapError = true;
|
|
1577
|
+
break;
|
|
1578
|
+
default: {
|
|
1579
|
+
// 未识别宿主也可使用完整标准 Fetch API;不将能力推断为宿主类型。
|
|
1580
|
+
// An unrecognized host may still use the complete standard Fetch API; capability does not imply a host type.
|
|
1581
|
+
if (typeof globalThis.fetch !== "function" || typeof globalThis.Headers !== "function" || typeof globalThis.Request !== "function" || typeof globalThis.Response !== "function") {
|
|
1582
|
+
throw new Error(`${Function.name}: 当前运行环境不支持 Fetch API`);
|
|
1583
|
+
}
|
|
1584
|
+
const { url, bodyBytes, redirection, timeout: _timeout, policy: _policy, "auto-redirect": _autoRedirect, "auto-cookie": _autoCookie, opts: _opts, ...fetchOptions } = resource;
|
|
1585
|
+
if (bodyBytes !== undefined && fetchOptions.body === undefined) fetchOptions.body = bodyBytes;
|
|
1586
|
+
fetchOptions.redirect = redirection ? "follow" : "manual";
|
|
1587
|
+
request = { url, ...fetchOptions };
|
|
1588
|
+
timeout = resource.timeout * 1000;
|
|
1589
|
+
break;
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
const { url, ...options } = request;
|
|
1593
|
+
// 发起请求并归一化响应头、文本与二进制响应体。
|
|
1594
|
+
// Send the request and normalize headers, text, and binary response data.
|
|
1595
|
+
const responsePromise = globalThis.fetch(url, options).then(async response => {
|
|
1596
|
+
const bodyBytes = await response.arrayBuffer();
|
|
1597
|
+
let headers;
|
|
1598
|
+
try {
|
|
1599
|
+
headers = response.headers.raw();
|
|
1600
|
+
} catch {
|
|
1601
|
+
headers = Array.from(response.headers.entries()).reduce((acc, [key, value]) => {
|
|
1602
|
+
acc[key] = acc[key] ? [...acc[key], value] : [value];
|
|
1603
|
+
return acc;
|
|
1604
|
+
}, {});
|
|
1605
|
+
}
|
|
1606
|
+
return {
|
|
1607
|
+
ok: response.ok ?? /^2\d\d$/.test(response.status),
|
|
1608
|
+
status: response.status,
|
|
1609
|
+
statusCode: response.status,
|
|
1610
|
+
statusText: response.statusText,
|
|
1611
|
+
body: new TextDecoder("utf-8").decode(bodyBytes),
|
|
1612
|
+
bodyBytes: bodyBytes,
|
|
1613
|
+
headers: Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, key.toLowerCase() !== "set-cookie" ? value.toString() : value])),
|
|
1614
|
+
};
|
|
1615
|
+
});
|
|
1616
|
+
return Promise.race([
|
|
1617
|
+
shouldWrapError ? responsePromise.catch(error => Promise.reject(error.message)) : responsePromise,
|
|
1618
|
+
new Promise((_resolve, reject) => {
|
|
1619
|
+
setTimeout(() => {
|
|
1620
|
+
reject(new Error(`${Function.name}: 请求超时, 请检查网络后重试`));
|
|
1621
|
+
}, timeout);
|
|
1622
|
+
}),
|
|
1623
|
+
]);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1619
1626
|
}
|
|
1620
|
-
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* 跨平台持久化存储适配器。
|
|
1630
|
+
* Cross-platform persistent storage adapter.
|
|
1631
|
+
*
|
|
1632
|
+
* 设计目标:
|
|
1633
|
+
* Design goal:
|
|
1634
|
+
* - 仿照 Web Storage (`Storage`) 接口设计
|
|
1635
|
+
* - Modeled after Web Storage (`Storage`) interface
|
|
1636
|
+
* - 统一 VPN App 脚本环境中的持久化读写接口
|
|
1637
|
+
* - Unify persistence APIs across VPN app script environments
|
|
1638
|
+
*
|
|
1639
|
+
* 支持后端:
|
|
1640
|
+
* Supported backends:
|
|
1641
|
+
* - Surge/Loon/Stash/Egern/Shadowrocket: `$persistentStore`
|
|
1642
|
+
* - Quantumult X: `$prefs`
|
|
1643
|
+
* - Worker: 内存缓存(非持久化)
|
|
1644
|
+
* - Worker: in-memory cache (non-persistent)
|
|
1645
|
+
* - Node.js: 由 Node.js ESM 入口注入持久化后端
|
|
1646
|
+
* - Node.js: persistent backend injected by the Node.js ESM entry
|
|
1647
|
+
*
|
|
1648
|
+
* 支持路径键:
|
|
1649
|
+
* Supports path key:
|
|
1650
|
+
* - `@root.path.to.value`
|
|
1651
|
+
*
|
|
1652
|
+
* 与 Web Storage 的已知差异:
|
|
1653
|
+
* Known differences from Web Storage:
|
|
1654
|
+
* - 支持 `@key.path` 深路径读写(Web Storage 原生不支持)
|
|
1655
|
+
* - Supports `@key.path` deep-path access (not native in Web Storage)
|
|
1656
|
+
* - `removeItem/clear` 并非所有平台都可用
|
|
1657
|
+
* - `removeItem/clear` are not available on every platform
|
|
1658
|
+
* - 读取时会尝试 `JSON.parse`,写入对象会 `JSON.stringify`
|
|
1659
|
+
* - Reads try `JSON.parse`, writes stringify objects
|
|
1660
|
+
*
|
|
1661
|
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/Storage
|
|
1662
|
+
* @link https://developer.mozilla.org/zh-CN/docs/Web/API/Storage
|
|
1663
|
+
*/
|
|
1664
|
+
class Storage {
|
|
1665
|
+
/**
|
|
1666
|
+
* Worker / Node.js 环境下的内存数据缓存。
|
|
1667
|
+
* In-memory data cache for Worker / Node.js runtime.
|
|
1668
|
+
*
|
|
1669
|
+
* @type {Record<string, any>|null}
|
|
1670
|
+
*/
|
|
1671
|
+
static data = null;
|
|
1672
|
+
|
|
1673
|
+
/**
|
|
1674
|
+
* Node.js 持久化文件名。
|
|
1675
|
+
* Data file name used in Node.js.
|
|
1676
|
+
*
|
|
1677
|
+
* @type {string}
|
|
1678
|
+
*/
|
|
1679
|
+
static dataFile = "box.dat";
|
|
1680
|
+
|
|
1681
|
+
/**
|
|
1682
|
+
* Node.js ESM 入口注入的存储后端。
|
|
1683
|
+
* Storage backend injected by the Node.js ESM entry.
|
|
1684
|
+
*
|
|
1685
|
+
* @type {{load: (dataFile: string) => Record<string, any>, write: (dataFile: string, data: Record<string, any>) => void}|null}
|
|
1686
|
+
*/
|
|
1687
|
+
static nodeBackend = null;
|
|
1688
|
+
|
|
1689
|
+
/**
|
|
1690
|
+
* `@key.path` 解析正则。
|
|
1691
|
+
* Regex for `@key.path` parsing.
|
|
1692
|
+
*
|
|
1693
|
+
* @type {RegExp}
|
|
1694
|
+
*/
|
|
1695
|
+
static #nameRegex = /^@(?<key>[^.]+)(?:\.(?<path>.*))?$/;
|
|
1696
|
+
|
|
1697
|
+
/**
|
|
1698
|
+
* 读取存储值。
|
|
1699
|
+
* Read value from persistent storage.
|
|
1700
|
+
*
|
|
1701
|
+
* @param {string} keyName 键名或路径键 / Key or path key.
|
|
1702
|
+
* @param {*} [defaultValue=null] 默认值 / Default value when key is missing.
|
|
1703
|
+
* @returns {*}
|
|
1704
|
+
*/
|
|
1705
|
+
static getItem(keyName, defaultValue = null) {
|
|
1706
|
+
let keyValue = defaultValue;
|
|
1707
|
+
// 如果以 @
|
|
1708
|
+
switch (keyName.startsWith("@")) {
|
|
1709
|
+
case true: {
|
|
1710
|
+
const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
|
|
1711
|
+
keyName = key;
|
|
1712
|
+
let value = Storage.getItem(keyName, {});
|
|
1713
|
+
if (typeof value !== "object") value = {};
|
|
1714
|
+
keyValue = Lodash.get(value, path);
|
|
1715
|
+
try {
|
|
1716
|
+
keyValue = JSON.parse(keyValue);
|
|
1717
|
+
} catch {}
|
|
1718
|
+
break;
|
|
1719
|
+
}
|
|
1720
|
+
default:
|
|
1721
|
+
switch ($app) {
|
|
1722
|
+
case "Surge":
|
|
1723
|
+
case "Loon":
|
|
1724
|
+
case "Stash":
|
|
1725
|
+
case "Egern":
|
|
1726
|
+
case "Shadowrocket":
|
|
1727
|
+
keyValue = $persistentStore.read(keyName);
|
|
1728
|
+
break;
|
|
1729
|
+
case "Quantumult X":
|
|
1730
|
+
keyValue = $prefs.valueForKey(keyName);
|
|
1731
|
+
break;
|
|
1732
|
+
case "Worker":
|
|
1733
|
+
Storage.data = Storage.data ?? {};
|
|
1734
|
+
keyValue = Storage.data[keyName];
|
|
1735
|
+
break;
|
|
1736
|
+
case "Node.js":
|
|
1737
|
+
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
1738
|
+
keyValue = Storage.data?.[keyName];
|
|
1739
|
+
break;
|
|
1740
|
+
default:
|
|
1741
|
+
keyValue = Storage.data?.[keyName] || null;
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
try {
|
|
1745
|
+
keyValue = JSON.parse(keyValue);
|
|
1746
|
+
} catch {
|
|
1747
|
+
// do nothing
|
|
1748
|
+
}
|
|
1749
|
+
break;
|
|
1750
|
+
}
|
|
1751
|
+
return keyValue ?? defaultValue;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
/**
|
|
1755
|
+
* 写入存储值。
|
|
1756
|
+
* Write value into persistent storage.
|
|
1757
|
+
*
|
|
1758
|
+
* @param {string} keyName 键名或路径键 / Key or path key.
|
|
1759
|
+
* @param {*} keyValue 写入值 / Value to store.
|
|
1760
|
+
* @returns {boolean}
|
|
1761
|
+
*/
|
|
1762
|
+
static setItem(keyName = new String(), keyValue = new String()) {
|
|
1763
|
+
let result = false;
|
|
1764
|
+
switch (typeof keyValue) {
|
|
1765
|
+
case "object":
|
|
1766
|
+
keyValue = JSON.stringify(keyValue);
|
|
1767
|
+
break;
|
|
1768
|
+
default:
|
|
1769
|
+
keyValue = String(keyValue);
|
|
1770
|
+
break;
|
|
1771
|
+
}
|
|
1772
|
+
switch (keyName.startsWith("@")) {
|
|
1773
|
+
case true: {
|
|
1774
|
+
const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
|
|
1775
|
+
keyName = key;
|
|
1776
|
+
let value = Storage.getItem(keyName, {});
|
|
1777
|
+
if (typeof value !== "object") value = {};
|
|
1778
|
+
Lodash.set(value, path, keyValue);
|
|
1779
|
+
result = Storage.setItem(keyName, value);
|
|
1780
|
+
break;
|
|
1781
|
+
}
|
|
1782
|
+
default:
|
|
1783
|
+
switch ($app) {
|
|
1784
|
+
case "Surge":
|
|
1785
|
+
case "Loon":
|
|
1786
|
+
case "Stash":
|
|
1787
|
+
case "Egern":
|
|
1788
|
+
case "Shadowrocket":
|
|
1789
|
+
result = $persistentStore.write(keyValue, keyName);
|
|
1790
|
+
break;
|
|
1791
|
+
case "Quantumult X":
|
|
1792
|
+
result = $prefs.setValueForKey(keyValue, keyName);
|
|
1793
|
+
break;
|
|
1794
|
+
case "Worker":
|
|
1795
|
+
Storage.data = Storage.data ?? {};
|
|
1796
|
+
Storage.data[keyName] = keyValue;
|
|
1797
|
+
result = true;
|
|
1798
|
+
break;
|
|
1799
|
+
case "Node.js":
|
|
1800
|
+
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
1801
|
+
Storage.data[keyName] = keyValue;
|
|
1802
|
+
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
1803
|
+
result = true;
|
|
1804
|
+
break;
|
|
1805
|
+
default:
|
|
1806
|
+
result = Storage.data?.[keyName] || null;
|
|
1807
|
+
break;
|
|
1808
|
+
}
|
|
1809
|
+
break;
|
|
1810
|
+
}
|
|
1811
|
+
return result;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* 删除存储值。
|
|
1816
|
+
* Remove value from persistent storage.
|
|
1817
|
+
*
|
|
1818
|
+
* 平台说明:
|
|
1819
|
+
* Platform notes:
|
|
1820
|
+
* - Quantumult X: `$prefs.removeValueForKey`
|
|
1821
|
+
* - Surge: 通过 `$persistentStore.write(null, keyName)` 删除
|
|
1822
|
+
* - 其余平台当前返回 `false`
|
|
1823
|
+
*
|
|
1824
|
+
* @param {string} keyName 键名或路径键 / Key or path key.
|
|
1825
|
+
* @returns {boolean}
|
|
1826
|
+
*/
|
|
1827
|
+
static removeItem(keyName) {
|
|
1828
|
+
let result = false;
|
|
1829
|
+
switch (keyName.startsWith("@")) {
|
|
1830
|
+
case true: {
|
|
1831
|
+
const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
|
|
1832
|
+
keyName = key;
|
|
1833
|
+
let value = Storage.getItem(keyName);
|
|
1834
|
+
if (typeof value !== "object") value = {};
|
|
1835
|
+
Lodash.unset(value, path);
|
|
1836
|
+
result = Storage.setItem(keyName, value);
|
|
1837
|
+
break;
|
|
1838
|
+
}
|
|
1839
|
+
default:
|
|
1840
|
+
switch ($app) {
|
|
1841
|
+
case "Surge":
|
|
1842
|
+
result = $persistentStore.write(null, keyName);
|
|
1843
|
+
break;
|
|
1844
|
+
case "Loon":
|
|
1845
|
+
case "Stash":
|
|
1846
|
+
case "Egern":
|
|
1847
|
+
case "Shadowrocket":
|
|
1848
|
+
result = false;
|
|
1849
|
+
break;
|
|
1850
|
+
case "Quantumult X":
|
|
1851
|
+
result = $prefs.removeValueForKey(keyName);
|
|
1852
|
+
break;
|
|
1853
|
+
case "Worker":
|
|
1854
|
+
Storage.data = Storage.data ?? {};
|
|
1855
|
+
delete Storage.data[keyName];
|
|
1856
|
+
result = true;
|
|
1857
|
+
break;
|
|
1858
|
+
case "Node.js":
|
|
1859
|
+
// result = false;
|
|
1860
|
+
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
1861
|
+
delete Storage.data[keyName];
|
|
1862
|
+
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
1863
|
+
result = true;
|
|
1864
|
+
break;
|
|
1865
|
+
default:
|
|
1866
|
+
result = false;
|
|
1867
|
+
break;
|
|
1868
|
+
}
|
|
1869
|
+
break;
|
|
1870
|
+
}
|
|
1871
|
+
return result;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
/**
|
|
1875
|
+
* 清空存储。
|
|
1876
|
+
* Clear storage.
|
|
1877
|
+
*
|
|
1878
|
+
* @returns {boolean}
|
|
1879
|
+
*/
|
|
1880
|
+
static clear() {
|
|
1881
|
+
let result = false;
|
|
1882
|
+
switch ($app) {
|
|
1883
|
+
case "Surge":
|
|
1884
|
+
case "Loon":
|
|
1885
|
+
case "Stash":
|
|
1886
|
+
case "Egern":
|
|
1887
|
+
case "Shadowrocket":
|
|
1888
|
+
result = false;
|
|
1889
|
+
break;
|
|
1890
|
+
case "Quantumult X":
|
|
1891
|
+
result = $prefs.removeAllValues();
|
|
1892
|
+
break;
|
|
1893
|
+
case "Worker":
|
|
1894
|
+
Storage.data = {};
|
|
1895
|
+
result = true;
|
|
1896
|
+
break;
|
|
1897
|
+
case "Node.js":
|
|
1898
|
+
// result = false;
|
|
1899
|
+
Storage.data = Storage.nodeBackend.load(Storage.dataFile);
|
|
1900
|
+
Storage.data = {};
|
|
1901
|
+
Storage.nodeBackend.write(Storage.dataFile, Storage.data);
|
|
1902
|
+
result = true;
|
|
1903
|
+
break;
|
|
1904
|
+
default:
|
|
1905
|
+
result = false;
|
|
1906
|
+
break;
|
|
1907
|
+
}
|
|
1908
|
+
return result;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/**
|
|
1913
|
+
* 校验原始路径片段,不进行 URL 编码转换。
|
|
1914
|
+
* Validate raw path segments without URL encoding conversion.
|
|
1915
|
+
* @param {string[]} parts 原始路径片段 / Raw path segments.
|
|
1916
|
+
* @returns {string[]} 同一数组,不复制或修改 / The same array without copying or mutation.
|
|
1917
|
+
* @throws {TypeError} 空片段、非法字符或原型属性名 / Empty segments, invalid characters or prototype property names.
|
|
1918
|
+
*/
|
|
1919
|
+
function validatePathParts(parts) {
|
|
1920
|
+
if (!parts.every(part => typeof part === "string" && /^[a-zA-Z0-9_-]+$/.test(part) && !["__proto__", "prototype", "constructor"].includes(part))) throw new TypeError("Invalid key path");
|
|
1921
|
+
return parts;
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
const MISSING = Symbol("missing");
|
|
1925
|
+
|
|
1926
|
+
/**
|
|
1927
|
+
* PreferencePanes 后端 API,只处理模块数据和持久化请求。
|
|
1928
|
+
* PreferencePanes backend API handling only module data and persistence requests.
|
|
1929
|
+
*/
|
|
1930
|
+
class API {
|
|
1931
|
+
/**
|
|
1932
|
+
* 处理当前代理请求并将结果交给宿主。
|
|
1933
|
+
* Handle the current proxy request and deliver its result to the host.
|
|
1934
|
+
* @returns {Promise<void>} 响应已交给代理宿主 / Response delivered to the proxy host.
|
|
1935
|
+
*/
|
|
1936
|
+
async run() {
|
|
1937
|
+
const request = globalThis.$request;
|
|
1938
|
+
let result;
|
|
1939
|
+
try {
|
|
1940
|
+
result = await this.handle(request);
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
console.error(`PreferencePanes: ${error.message}`);
|
|
1943
|
+
result = this.#response(request, error.status ?? 500, { error: error.message });
|
|
1944
|
+
}
|
|
1945
|
+
if (!result) done({});
|
|
1946
|
+
else done($app === "Quantumult X" ? result : { response: result });
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
/**
|
|
1950
|
+
* 处理 `/api/{module}` 及其动作,不接管页面或静态资源。
|
|
1951
|
+
* Handle `/api/{module}` and its actions without intercepting pages or static assets.
|
|
1952
|
+
* @param {import("./index.js").SettingsRequest} request 代理请求 / Proxy request.
|
|
1953
|
+
* @returns {Promise<import("./index.js").SettingsResponse | undefined>} API 响应或未接管 / API response or pass-through.
|
|
1954
|
+
*/
|
|
1955
|
+
async handle(request) {
|
|
1956
|
+
const url = new URL(request.url);
|
|
1957
|
+
const match = /^\/api\/([a-zA-Z0-9_-]+)(?:\/(get|set|delete))?\/?$/.exec(url.pathname);
|
|
1958
|
+
if (!match) return;
|
|
1959
|
+
const [, module, action] = match;
|
|
1960
|
+
const configURL = this.#configURL(request, url, module);
|
|
1961
|
+
switch (true) {
|
|
1962
|
+
case !action && request.method === "HEAD":
|
|
1963
|
+
return this.#probe(request, configURL);
|
|
1964
|
+
case !action && request.method === "GET":
|
|
1965
|
+
return this.#model(request, module, configURL);
|
|
1966
|
+
case Boolean(action) && request.method === "POST":
|
|
1967
|
+
return this.#action(request, module, action, configURL);
|
|
1968
|
+
default:
|
|
1969
|
+
return this.#response(request, 405, { error: "Use GET or HEAD for module reads, POST for module actions" });
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
#configURL(request, url, module) {
|
|
1974
|
+
const headers = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
1975
|
+
const source = headers["x-preferencepanes-json"] ?? `/configs/${module}`;
|
|
1976
|
+
if (/^https?:\/\//i.test(source)) return source;
|
|
1977
|
+
if (/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(source)) throw Object.assign(new TypeError("BoxJS resources must use HTTP(S) URLs"), { status: 400 });
|
|
1978
|
+
return `${url.origin}/${source.replace(/^\/+/, "")}`;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
async #probe(request, configURL) {
|
|
1982
|
+
let result;
|
|
1983
|
+
try {
|
|
1984
|
+
result = await fetch({ url: configURL, method: "HEAD", timeout: 5000, headers: { Accept: "application/json" } });
|
|
1985
|
+
} catch (error) {
|
|
1986
|
+
return this.#response(request, 502, { error: error.message });
|
|
1987
|
+
}
|
|
1988
|
+
const version = this.#header(result.headers, "x-preferencepanes-version");
|
|
1989
|
+
return this.#response(request, result.statusCode ?? result.status, undefined, version ? { "X-PreferencePanes-Version": version } : {});
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
async #model(request, module, configURL) {
|
|
1993
|
+
const loaded = await this.#load(module, configURL);
|
|
1994
|
+
const values = {};
|
|
1995
|
+
for (const entry of loaded.entries) {
|
|
1996
|
+
const value = Storage.getItem(entry.id, MISSING);
|
|
1997
|
+
if (value !== MISSING) values[entry.id.slice(loaded.storageKey.length + 2)] = value;
|
|
1998
|
+
}
|
|
1999
|
+
return this.#response(request, 200, { module, boxjs: loaded.boxjs, values, configURL }, loaded.version ? { "X-PreferencePanes-Version": loaded.version } : {});
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
async #action(request, module, action, configURL) {
|
|
2003
|
+
const payload = this.#jsonBody(request);
|
|
2004
|
+
const target = await this.#load(module, configURL);
|
|
2005
|
+
switch (action) {
|
|
2006
|
+
case "get": {
|
|
2007
|
+
const value = Storage.getItem(payload?.scope ? this.#scopePath(target, payload.scope) : this.#storagePath(target, payload?.key), MISSING);
|
|
2008
|
+
return value === MISSING ? this.#response(request, 404, { error: "Stored path does not exist" }) : this.#response(request, 200, value);
|
|
2009
|
+
}
|
|
2010
|
+
case "set":
|
|
2011
|
+
if (!Object.hasOwn(payload ?? {}, "value")) throw Object.assign(new TypeError("A value is required"), { status: 400 });
|
|
2012
|
+
if (!Storage.setItem(this.#storagePath(target, payload.key), payload.value)) throw new Error("Storage write failed");
|
|
2013
|
+
return this.#response(request, 200, { saved: true });
|
|
2014
|
+
case "delete": {
|
|
2015
|
+
const path = payload?.scope ? this.#scopePath(target, payload.scope) : this.#storagePath(target, payload?.key);
|
|
2016
|
+
if (!Storage.removeItem(path)) throw new Error("Storage write failed");
|
|
2017
|
+
return this.#response(request, 200, { deleted: true });
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
async #load(module, configURL) {
|
|
2023
|
+
let result;
|
|
2024
|
+
try {
|
|
2025
|
+
result = await fetch({ url: configURL, method: "GET", timeout: 5000, headers: { Accept: "application/json" } });
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
throw Object.assign(new Error(`Configuration request failed: ${error.message}`), { status: 502 });
|
|
2028
|
+
}
|
|
2029
|
+
const status = result.statusCode ?? result.status;
|
|
2030
|
+
if (status !== 200) throw Object.assign(new Error(`Configuration HTTP ${status}`), { status });
|
|
2031
|
+
try {
|
|
2032
|
+
const body = typeof result.body === "string" ? result.body : new TextDecoder().decode(result.body);
|
|
2033
|
+
const boxjs = JSON.parse(body);
|
|
2034
|
+
const apps = Array.isArray(boxjs) ? [{ settings: boxjs }] : (boxjs.apps ?? [boxjs]);
|
|
2035
|
+
if (!Array.isArray(apps)) throw new TypeError("Expected BoxJS apps array");
|
|
2036
|
+
const entries = [];
|
|
2037
|
+
let storageKey;
|
|
2038
|
+
for (const app of apps) {
|
|
2039
|
+
if (!app || !Array.isArray(app.settings)) throw new TypeError("Expected BoxJS settings array");
|
|
2040
|
+
for (const entry of app.settings) {
|
|
2041
|
+
if (typeof entry.id !== "string") throw new TypeError("BoxJS settings require string IDs");
|
|
2042
|
+
if (!entry.id.startsWith("@")) {
|
|
2043
|
+
if (Array.isArray(boxjs)) throw new TypeError("BoxJS settings require @root.path IDs");
|
|
2044
|
+
continue;
|
|
2045
|
+
}
|
|
2046
|
+
const [root, ...parts] = entry.id.slice(1).split(".");
|
|
2047
|
+
if (!root || root.startsWith("@") || parts.length < 2) throw new TypeError("A BoxJS setting must be below a literal storage root and module");
|
|
2048
|
+
validatePathParts(parts);
|
|
2049
|
+
if (parts[0] !== module) continue;
|
|
2050
|
+
if (storageKey && storageKey !== root) throw new TypeError(`A module must use one storage root: ${module}`);
|
|
2051
|
+
storageKey = root;
|
|
2052
|
+
entries.push(entry);
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
if (!entries.length) throw new TypeError(`No BoxJS settings for module: ${module}`);
|
|
2056
|
+
return { boxjs, entries, module, storageKey, version: this.#header(result.headers, "x-preferencepanes-version") };
|
|
2057
|
+
} catch (error) {
|
|
2058
|
+
throw Object.assign(new Error(`Invalid BoxJS: ${error.message}`), { status: 422 });
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
#jsonBody(request) {
|
|
2063
|
+
const headers = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
2064
|
+
if (headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/json") throw Object.assign(new TypeError("Expected application/json"), { status: 415 });
|
|
2065
|
+
if (typeof request.body !== "string" || request.body.length > 65536) throw Object.assign(new TypeError("Expected a JSON body up to 65536 characters"), { status: 400 });
|
|
2066
|
+
try {
|
|
2067
|
+
return JSON.parse(request.body);
|
|
2068
|
+
} catch (error) {
|
|
2069
|
+
throw Object.assign(error, { status: 400 });
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
#storagePath(target, key) {
|
|
2074
|
+
if (typeof key !== "string") throw Object.assign(new TypeError("A BoxJS field path is required"), { status: 400 });
|
|
2075
|
+
const path = `@${target.storageKey}.${key}`;
|
|
2076
|
+
if (!target.entries.some(entry => entry.id === path)) throw Object.assign(new TypeError(`Unknown BoxJS field: ${key}`), { status: 400 });
|
|
2077
|
+
return path;
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
#scopePath(target, scope) {
|
|
2081
|
+
switch (scope) {
|
|
2082
|
+
case "settings":
|
|
2083
|
+
return `@${target.storageKey}.${target.module}.Settings`;
|
|
2084
|
+
case "caches":
|
|
2085
|
+
return `@${target.storageKey}.${target.module}.Caches`;
|
|
2086
|
+
case "module":
|
|
2087
|
+
return `@${target.storageKey}.${target.module}`;
|
|
2088
|
+
default:
|
|
2089
|
+
throw Object.assign(new TypeError("Scope must be settings, caches or module"), { status: 400 });
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
#response(request, status, body, extraHeaders = {}) {
|
|
2094
|
+
return {
|
|
2095
|
+
status,
|
|
2096
|
+
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", ...extraHeaders },
|
|
2097
|
+
body: request.method === "HEAD" ? "" : JSON.stringify(body),
|
|
2098
|
+
};
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
#header(headers, name) {
|
|
2102
|
+
const entry = Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === name);
|
|
2103
|
+
return entry?.[1] === undefined ? undefined : String(entry[1]).trim();
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
new API().run();
|
|
1621
2108
|
|
|
1622
2109
|
})();
|