@nsnanocat/preference-panes 0.5.0 → 0.6.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 CHANGED
@@ -93,10 +93,14 @@ import { readFile, writeFile } from "node:fs/promises";
93
93
 
94
94
  const runtime = await readFile(new URL(import.meta.resolve("@nsnanocat/preference-panes/dist/preference-panes.proxy.js")), "utf8");
95
95
  const installation = JSON.parse(await readFile("installation.json", "utf8"));
96
- await writeFile("Module.request.js", `${runtime}\nPreferencePanes.runPreferences(${JSON.stringify(installation)});\n`);
96
+ await writeFile("PreferencePanes.request.js", `${runtime}\nPreferencePanes.runPreferences(${JSON.stringify(installation)});\n`);
97
97
  ~~~
98
98
 
99
- 业务插件的代理规则直接引用托管站点的 Module.request.js;无需 npm 依赖、业务 Request 接入代码或额外构建脚本。生成文件把可信安装映射与通用执行端放在一起,不依赖平台是否支持 $argument,Quantumult X 也使用同一文件。所有代理平台判断、done 适配、异常响应、资源下载和读写都由本包完成。API 不下载安装 JSON 或 BoxJS。
99
+ 通用运行时由独立 PreferencePanes 代理模块安装一次,统一匹配 /api/ 与页面资源;业务插件不再安装读写或页面规则,只提供 /configs/{module} 的配置 Mock。安装映射的 module 可以是模块名数组,例如 ["Module", "Other"],统一模块只能访问声明范围。生成文件不依赖 $argument,Quantumult X 也使用同一文件。API 不下载安装 JSON 或 BoxJS。
100
+
101
+ 独立模块不得匹配 /configs/,资源映射也不得为配置 Mock 提供兜底。主菜单每次进入只 HEAD 配置 Mock;HTTP 200 启用入口,打开后 GET 并解析 JSON。配置缺失、无有效字段或解析失败时不读取设置 API、不生成设置表单。API 可达不代表某个业务模块提供了设置界面。
102
+
103
+ Surge/Loon 的业务插件使用原生 JSON Mock。需要脚本响应配置的平台,由托管站点将包内 dist/preference-panes.config.js 与 `PreferencePanes.mockConfiguration(BoxJS_JSON)` 拼接生成配置响应文件。该文件只支持 GET/HEAD,不包含存储、网络下载或页面处理;它只安装在业务插件的 /configs/{module} 规则中。关闭业务插件后 Mock 消失,独立通用模块继续启用也不会误判该设置入口可用。
100
104
 
101
105
  以下是包内部处理器接受的安装映射形状;也可供需要手动集成的宿主使用:
102
106
 
@@ -108,14 +112,13 @@ const handler = new PreferencesHandler({
108
112
  storageKey: "Root",
109
113
  module: "Module",
110
114
  resources: [
111
- { pattern: "^/configs/Module$", source: "https://example.org/settings/assets/Module.boxjs.json", contentType: "application/json" },
112
115
  { pattern: "^/settings/(?:[a-zA-Z0-9_-]+/?)?$", source: "https://example.org/settings/assets/index.html", contentType: "text/html" }
113
116
  ]
114
117
  });
115
118
  const response = await handler.handle($request);
116
119
  ~~~
117
120
 
118
- 资源 pattern 匹配 pathname,下载源必须避开拦截路径。只有命中静态资源的 GET/HEAD 才下载文件;API 由 SettingsHandler 直接处理,读写不会下载 BoxJS。业务插件只保留安装规则和配置 Mock;其业务请求脚本不负责设置接口。
121
+ 资源 pattern 匹配 pathname,下载源必须避开拦截路径。只有命中静态资源的 GET/HEAD 才下载文件;API 由 SettingsHandler 直接处理,读写不会下载 BoxJS。业务插件只保留配置 Mock;页面与 API 安装规则全部属于独立 PreferencePanes 模块。
119
122
 
120
123
  ## BoxJS 兼容
121
124
 
@@ -141,6 +144,6 @@ npm run apifox:check
141
144
  npm pack --dry-run
142
145
  ~~~
143
146
 
144
- 构建生成 dist/preference-panes.mjs、读取宿主参数的 dist/preference-panes.request.js、供托管站点配置的 dist/preference-panes.proxy.js,以及可直接部署的 dist/settings/{index.html,app.mjs,panel.css,home.css}。托管仓库直接从依赖包复制,不读取业务插件的前端构建目录。0.5.0 将独立代理执行入口也交给本包,保留既有存储契约与页面交互。
147
+ 构建生成 dist/preference-panes.mjs、读取宿主参数的 dist/preference-panes.request.js、供托管站点配置的 dist/preference-panes.proxy.js、仅返回配置的 dist/preference-panes.config.js,以及可直接部署的 dist/settings/{index.html,app.mjs,panel.css,home.css}0.6.0 支持独立模块统一处理多个业务模块,并将配置 Mock 与通用读写安装彻底分开。
145
148
 
146
149
  [完整接口说明](apifox/guide.md) · [Apifox JSON](apifox/preference-panes.apifox.json) · [同步方式](apifox/README.md) · [发布工作流](.github/RELEASING.md)
@@ -0,0 +1,816 @@
1
+ var PreferencePanes = (function (exports) {
2
+ 'use strict';
3
+
4
+ /**
5
+ * 当前运行平台名称(脚本平台优先,模块系统次之)。
6
+ * Current runtime platform name (script platform first, module system second).
7
+ *
8
+ * 识别顺序:
9
+ * Detection order:
10
+ * 1) `$task` -> Quantumult X
11
+ * 2) `$loon` -> Loon
12
+ * 3) `$rocket` -> Shadowrocket
13
+ * 4) `Egern` -> Egern
14
+ * 5) `$environment["surge-version"]` -> Surge
15
+ * 6) `$environment["stash-version"]` -> Stash
16
+ * 7) `Cloudflare` -> Worker
17
+ * 8) `process.versions.node` -> Node.js
18
+ * 9) 默认回落 -> undefined
19
+ * default fallback -> undefined
20
+ *
21
+ * 说明:
22
+ * Notes:
23
+ * - 使用 `'key' in globalThis`,避免 `Object.keys` 对不可枚举全局变量漏检。
24
+ * - Use `'key' in globalThis` to avoid missing non-enumerable globals with `Object.keys`.
25
+ *
26
+ * @type {("Quantumult X" | "Loon" | "Shadowrocket" | "Egern" | "Surge" | "Stash" | "Worker" | "Node.js" | undefined)}
27
+ */
28
+ const $app = (() => {
29
+ const has = key => key in globalThis;
30
+ switch (true) {
31
+ case has("$task"):
32
+ return "Quantumult X";
33
+ case has("$loon"):
34
+ return "Loon";
35
+ case has("$rocket"):
36
+ return "Shadowrocket";
37
+ case has("Egern"):
38
+ return "Egern";
39
+ case Boolean(globalThis.$environment?.["surge-version"]):
40
+ return "Surge";
41
+ case Boolean(globalThis.$environment?.["stash-version"]):
42
+ return "Stash";
43
+ case has("Cloudflare"):
44
+ //case has("ServiceWorkerGlobalScope") && has("self") && has("caches") && has("scheduler"):
45
+ return "Worker";
46
+ case Boolean(globalThis.process?.versions?.node):
47
+ return "Node.js";
48
+ default:
49
+ return undefined;
50
+ }
51
+ })();
52
+
53
+ /**
54
+ * 统一日志工具,兼容各脚本平台、Worker 与 Node.js。
55
+ * Unified logger compatible with script platforms, Worker, and Node.js.
56
+ *
57
+ * logLevel 用法:
58
+ * logLevel usage:
59
+ * - 可读: `Console.logLevel` 返回 `OFF|ERROR|WARN|INFO|DEBUG|ALL`
60
+ * - Read: `Console.logLevel` returns `OFF|ERROR|WARN|INFO|DEBUG|ALL`
61
+ * - 可写: 数字 `0~5` 或字符串 `off/error/warn/info/debug/all`
62
+ * - Write: number `0~5` or string `off/error/warn/info/debug/all`
63
+ *
64
+ * @example
65
+ * Console.logLevel = "debug";
66
+ * Console.debug("only shown when level >= DEBUG");
67
+ * Console.logLevel = 2; // WARN
68
+ */
69
+ class Console {
70
+ static #counts = new Map([]);
71
+ static #groups = [];
72
+ static #times = new Map([]);
73
+
74
+ /**
75
+ * 清空控制台(当前为空实现)。
76
+ * Clear console (currently a no-op).
77
+ *
78
+ * @returns {void}
79
+ */
80
+ static clear = () => {};
81
+
82
+ /**
83
+ * 增加计数器并打印当前值。
84
+ * Increment counter and print the current value.
85
+ *
86
+ * @param {string} [label="default"] 计数器名称 / Counter label.
87
+ * @returns {void}
88
+ */
89
+ static count = (label = "default") => {
90
+ switch (Console.#counts.has(label)) {
91
+ case true:
92
+ Console.#counts.set(label, Console.#counts.get(label) + 1);
93
+ break;
94
+ case false:
95
+ Console.#counts.set(label, 0);
96
+ break;
97
+ }
98
+ Console.log(`${label}: ${Console.#counts.get(label)}`);
99
+ };
100
+
101
+ /**
102
+ * 重置计数器。
103
+ * Reset a counter.
104
+ *
105
+ * @param {string} [label="default"] 计数器名称 / Counter label.
106
+ * @returns {void}
107
+ */
108
+ static countReset = (label = "default") => {
109
+ switch (Console.#counts.has(label)) {
110
+ case true:
111
+ Console.#counts.set(label, 0);
112
+ Console.log(`${label}: ${Console.#counts.get(label)}`);
113
+ break;
114
+ case false:
115
+ Console.warn(`Counter "${label}" doesn’t exist`);
116
+ break;
117
+ }
118
+ };
119
+
120
+ /**
121
+ * 输出调试日志。
122
+ * Print debug logs.
123
+ *
124
+ * @param {...any} msg 日志内容 / Log messages.
125
+ * @returns {void}
126
+ */
127
+ static debug = (...msg) => {
128
+ if (Console.#level < 4) return;
129
+ msg = msg.map(m => `🅱️ ${m}`);
130
+ Console.log(...msg);
131
+ };
132
+
133
+ /**
134
+ * 输出错误日志。
135
+ * Print error logs.
136
+ *
137
+ * @param {...any} msg 日志内容 / Log messages.
138
+ * @returns {void}
139
+ */
140
+ static error(...msg) {
141
+ if (Console.#level < 1) return;
142
+ switch ($app) {
143
+ case "Surge":
144
+ case "Loon":
145
+ case "Stash":
146
+ case "Egern":
147
+ case "Shadowrocket":
148
+ case "Quantumult X":
149
+ default:
150
+ msg = msg.map(m => `❌ ${m}`);
151
+ break;
152
+ case "Worker":
153
+ case "Node.js":
154
+ msg = msg.map(m => `❌ ${m?.stack ?? m}`);
155
+ break;
156
+ }
157
+ Console.log(...msg);
158
+ }
159
+
160
+ /**
161
+ * `error` 的别名。
162
+ * Alias of `error`.
163
+ *
164
+ * @param {...any} msg 日志内容 / Log messages.
165
+ * @returns {void}
166
+ */
167
+ static exception = (...msg) => Console.error(...msg);
168
+
169
+ /**
170
+ * 进入日志分组。
171
+ * Enter a log group.
172
+ *
173
+ * @param {string} label 分组名 / Group label.
174
+ * @returns {number}
175
+ */
176
+ static group = label => Console.#groups.unshift(label);
177
+
178
+ /**
179
+ * 退出日志分组。
180
+ * Exit the latest log group.
181
+ *
182
+ * @returns {*}
183
+ */
184
+ static groupEnd = () => Console.#groups.shift();
185
+
186
+ /**
187
+ * 输出信息日志。
188
+ * Print info logs.
189
+ *
190
+ * @param {...any} msg 日志内容 / Log messages.
191
+ * @returns {void}
192
+ */
193
+ static info(...msg) {
194
+ if (Console.#level < 3) return;
195
+ msg = msg.map(m => `ℹ️ ${m}`);
196
+ Console.log(...msg);
197
+ }
198
+
199
+ static #level = 3;
200
+
201
+ /**
202
+ * 获取日志级别文本。
203
+ * Get current log level text.
204
+ *
205
+ * @returns {"OFF"|"ERROR"|"WARN"|"INFO"|"DEBUG"|"ALL"}
206
+ */
207
+ static get logLevel() {
208
+ switch (Console.#level) {
209
+ case 0:
210
+ return "OFF";
211
+ case 1:
212
+ return "ERROR";
213
+ case 2:
214
+ return "WARN";
215
+ case 3:
216
+ default:
217
+ return "INFO";
218
+ case 4:
219
+ return "DEBUG";
220
+ case 5:
221
+ return "ALL";
222
+ }
223
+ }
224
+
225
+ /**
226
+ * 设置日志级别。
227
+ * Set current log level.
228
+ *
229
+ * @param {number|string} level 级别值 / Level value.
230
+ */
231
+ static set logLevel(level) {
232
+ switch (typeof level) {
233
+ case "string":
234
+ level = level.toLowerCase();
235
+ break;
236
+ case "number":
237
+ break;
238
+ case "undefined":
239
+ default:
240
+ level = "warn";
241
+ break;
242
+ }
243
+ switch (level) {
244
+ case 0:
245
+ case "off":
246
+ Console.#level = 0;
247
+ break;
248
+ case 1:
249
+ case "error":
250
+ Console.#level = 1;
251
+ break;
252
+ case 2:
253
+ case "warn":
254
+ case "warning":
255
+ default:
256
+ Console.#level = 2;
257
+ break;
258
+ case 3:
259
+ case "info":
260
+ Console.#level = 3;
261
+ break;
262
+ case 4:
263
+ case "debug":
264
+ Console.#level = 4;
265
+ break;
266
+ case 5:
267
+ case "all":
268
+ Console.#level = 5;
269
+ break;
270
+ }
271
+ }
272
+
273
+ /**
274
+ * 输出通用日志。
275
+ * Print generic logs.
276
+ *
277
+ * 说明:
278
+ * Notes:
279
+ * - 多行字符串参数会按换行拆分为多个独立日志项。
280
+ * - Multi-line string arguments are split into multiple log entries by line breaks.
281
+ *
282
+ * @param {...any} msg 日志内容 / Log messages.
283
+ * @returns {void}
284
+ */
285
+ static log = (...msg) => {
286
+ if (Console.#level === 0) return;
287
+ msg = msg.flatMap(log => {
288
+ switch (typeof log) {
289
+ case "object":
290
+ return [JSON.stringify(log)];
291
+ case "bigint":
292
+ case "number":
293
+ case "boolean":
294
+ return [log.toString()];
295
+ case "string":
296
+ return log.split(/\r?\n/u);
297
+ case "undefined":
298
+ default:
299
+ return [log];
300
+ }
301
+ });
302
+ Console.#groups.forEach(group => {
303
+ msg = msg.map(log => ` ${log}`);
304
+ msg.unshift(`▼ ${group}:`);
305
+ });
306
+ msg = ["", ...msg];
307
+ console.log(msg.join("\n"));
308
+ };
309
+
310
+ /**
311
+ * 开始计时。
312
+ * Start timer.
313
+ *
314
+ * @param {string} [label="default"] 计时器名称 / Timer label.
315
+ * @returns {Map<string, number>}
316
+ */
317
+ static time = (label = "default") => Console.#times.set(label, Date.now());
318
+
319
+ /**
320
+ * 结束计时并移除计时器。
321
+ * End timer and remove it.
322
+ *
323
+ * @param {string} [label="default"] 计时器名称 / Timer label.
324
+ * @returns {boolean}
325
+ */
326
+ static timeEnd = (label = "default") => Console.#times.delete(label);
327
+
328
+ /**
329
+ * 输出当前计时器耗时。
330
+ * Print elapsed time for a timer.
331
+ *
332
+ * @param {string} [label="default"] 计时器名称 / Timer label.
333
+ * @returns {void}
334
+ */
335
+ static timeLog = (label = "default") => {
336
+ const time = Console.#times.get(label);
337
+ if (time) Console.log(`${label}: ${Date.now() - time}ms`);
338
+ else Console.warn(`Timer "${label}" doesn’t exist`);
339
+ };
340
+
341
+ /**
342
+ * 输出警告日志。
343
+ * Print warning logs.
344
+ *
345
+ * @param {...any} msg 日志内容 / Log messages.
346
+ * @returns {void}
347
+ */
348
+ static warn(...msg) {
349
+ if (Console.#level < 2) return;
350
+ msg = msg.map(m => `⚠️ ${m}`);
351
+ Console.log(...msg);
352
+ }
353
+ }
354
+
355
+ /* https://www.lodashjs.com */
356
+ /**
357
+ * 轻量 Lodash 工具集。
358
+ * Lightweight Lodash-like utilities.
359
+ *
360
+ * 说明:
361
+ * Notes:
362
+ * - 这是 Lodash 的“部分方法”简化实现,不等价于完整 Lodash
363
+ * - This is a simplified subset, not a full Lodash implementation
364
+ * - 各方法语义可参考 Lodash 官方文档
365
+ * - Method semantics can be referenced from official Lodash docs
366
+ * - 导入时建议使用 `Lodash as _`,遵循 lodash 官方示例惯例
367
+ * - Use `Lodash as _` when importing, following official lodash example convention
368
+ *
369
+ * 参考:
370
+ * Reference:
371
+ * - https://www.lodashjs.com
372
+ * - https://lodash.com
373
+ */
374
+ class Lodash {
375
+ /**
376
+ * HTML 特殊字符转义。
377
+ * Escape HTML special characters.
378
+ *
379
+ * @param {string} string 输入文本 / Input text.
380
+ * @returns {string}
381
+ * @see {@link https://lodash.com/docs/#escape lodash.escape}
382
+ * @see {@link https://www.lodashjs.com/docs/lodash.escape lodash.escape (中文)}
383
+ */
384
+ static escape(string) {
385
+ const map = {
386
+ "&": "&amp;",
387
+ "<": "&lt;",
388
+ ">": "&gt;",
389
+ '"': "&quot;",
390
+ "'": "&#39;",
391
+ };
392
+ return string.replace(/[&<>"']/g, m => map[m]);
393
+ }
394
+
395
+ /**
396
+ * 按路径读取对象值。
397
+ * Get object value by path.
398
+ *
399
+ * @param {object} [object={}] 目标对象 / Target object.
400
+ * @param {string|string[]} [path=""] 路径 / Path.
401
+ * @param {*} [defaultValue=undefined] 默认值 / Default value.
402
+ * @returns {*}
403
+ * @see {@link https://lodash.com/docs/#get lodash.get}
404
+ * @see {@link https://www.lodashjs.com/docs/lodash.get lodash.get (中文)}
405
+ */
406
+ static get(object = {}, path = "", defaultValue = undefined) {
407
+ // translate array case to dot case, then split with .
408
+ // a[0].b -> a.0.b -> ['a', '0', 'b']
409
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
410
+
411
+ const result = path.reduce((previousValue, currentValue) => {
412
+ return Object(previousValue)[currentValue]; // null undefined get attribute will throwError, Object() can return a object
413
+ }, object);
414
+ return result === undefined ? defaultValue : result;
415
+ }
416
+
417
+ /**
418
+ * 递归合并源对象的自身可枚举属性到目标对象
419
+ * Recursively merge source enumerable properties into target object.
420
+ * @description 简化版 lodash.merge,用于合并配置对象
421
+ * @description A simplified lodash.merge for config merging.
422
+ *
423
+ * 适用情况:
424
+ * - 合并嵌套的配置/设置对象
425
+ * - 需要深度合并而非浅层覆盖的场景
426
+ * - 多个源对象依次合并到目标对象
427
+ *
428
+ * 限制:
429
+ * - 仅处理普通对象 (Plain Object),不处理 Date/RegExp 等特殊对象
430
+ * - Map/Set 仅支持同类型合并,不递归内部值
431
+ * - 数组会被直接覆盖,不会合并数组元素
432
+ * - 不处理循环引用,可能导致栈溢出
433
+ * - 不复制 Symbol 属性和不可枚举属性
434
+ * - 不保留原型链,仅处理自身属性
435
+ * - 会修改原始目标对象 (mutates target)
436
+ *
437
+ * @param {object} object - 目标对象
438
+ * @param {object} object - Target object.
439
+ * @param {...object} sources - 源对象(可多个)
440
+ * @param {...object} sources - Source objects.
441
+ * @returns {object} 返回合并后的目标对象
442
+ * @returns {object} Merged target object.
443
+ * @see {@link https://lodash.com/docs/#merge lodash.merge}
444
+ * @see {@link https://www.lodashjs.com/docs/lodash.merge lodash.merge (中文)}
445
+ * @example
446
+ * const target = { a: { b: 1 }, c: 2 };
447
+ * const source = { a: { d: 3 }, e: 4 };
448
+ * Lodash.merge(target, source);
449
+ * // => { a: { b: 1, d: 3 }, c: 2, e: 4 }
450
+ */
451
+ static merge(object, ...sources) {
452
+ if (object === null || object === undefined) return object;
453
+
454
+ for (const source of sources) {
455
+ if (source === null || source === undefined) continue;
456
+
457
+ for (const key of Object.keys(source)) {
458
+ const sourceValue = source[key];
459
+ const targetValue = object[key];
460
+
461
+ switch (true) {
462
+ case Lodash.#isPlainObject(sourceValue) && Lodash.#isPlainObject(targetValue):
463
+ // 递归合并对象
464
+ object[key] = Lodash.merge(targetValue, sourceValue);
465
+ break;
466
+ case sourceValue instanceof Map && targetValue instanceof Map:
467
+ // 合并 Map(空 Map 跳过)
468
+ if (sourceValue.size > 0) {
469
+ for (const [k, v] of sourceValue) {
470
+ targetValue.set(k, v);
471
+ }
472
+ }
473
+ break;
474
+ case sourceValue instanceof Set && targetValue instanceof Set:
475
+ // 合并 Set(空 Set 跳过)
476
+ if (sourceValue.size > 0) {
477
+ for (const v of sourceValue) {
478
+ targetValue.add(v);
479
+ }
480
+ }
481
+ break;
482
+ case Array.isArray(sourceValue) && sourceValue.length === 0 && targetValue !== undefined:
483
+ // 空数组不覆盖已有值
484
+ break;
485
+ case (sourceValue instanceof Map && sourceValue.size === 0 && targetValue !== undefined):
486
+ case (sourceValue instanceof Set && sourceValue.size === 0 && targetValue !== undefined):
487
+ // 空 Map/Set 不覆盖已有值
488
+ break;
489
+ case sourceValue !== undefined:
490
+ object[key] = sourceValue;
491
+ break;
492
+ }
493
+ }
494
+ }
495
+
496
+ return object;
497
+ }
498
+
499
+ /**
500
+ * 判断值是否为普通对象 (Plain Object)
501
+ * Check whether a value is a plain object.
502
+ * @param {*} value - 要检查的值
503
+ * @param {*} value - Value to check.
504
+ * @returns {boolean} 如果是普通对象返回 true
505
+ * @returns {boolean} Returns true when value is a plain object.
506
+ * @see {@link https://lodash.com/docs/#isPlainObject lodash.isPlainObject}
507
+ * @see {@link https://www.lodashjs.com/docs/lodash.isPlainObject lodash.isPlainObject (中文)}
508
+ */
509
+ static #isPlainObject(value) {
510
+ if (value === null || typeof value !== "object") return false;
511
+ const proto = Object.getPrototypeOf(value);
512
+ return proto === null || proto === Object.prototype;
513
+ }
514
+
515
+ /**
516
+ * 删除对象指定路径并返回对象。
517
+ * Omit paths from object and return the same object.
518
+ *
519
+ * @param {object} [object={}] 目标对象 / Target object.
520
+ * @param {string|string[]} [paths=[]] 要删除的路径 / Paths to remove.
521
+ * @returns {object}
522
+ * @see {@link https://lodash.com/docs/#omit lodash.omit}
523
+ * @see {@link https://www.lodashjs.com/docs/lodash.omit lodash.omit (中文)}
524
+ */
525
+ static omit(object = {}, paths = []) {
526
+ if (!Array.isArray(paths)) paths = [paths.toString()];
527
+ paths.forEach(path => Lodash.unset(object, path));
528
+ return object;
529
+ }
530
+
531
+ /**
532
+ * 仅保留对象指定键(第一层)。
533
+ * Pick selected keys from object (top level only).
534
+ *
535
+ * @param {object} [object={}] 目标对象 / Target object.
536
+ * @param {string|string[]} [paths=[]] 需要保留的键 / Keys to keep.
537
+ * @returns {object}
538
+ * @see {@link https://lodash.com/docs/#pick lodash.pick}
539
+ * @see {@link https://www.lodashjs.com/docs/lodash.pick lodash.pick (中文)}
540
+ */
541
+ static pick(object = {}, paths = []) {
542
+ if (!Array.isArray(paths)) paths = [paths.toString()];
543
+ const filteredEntries = Object.entries(object).filter(([key, value]) => paths.includes(key));
544
+ return Object.fromEntries(filteredEntries);
545
+ }
546
+
547
+ /**
548
+ * 按路径写入对象值。
549
+ * Set object value by path.
550
+ *
551
+ * @param {object} object 目标对象 / Target object.
552
+ * @param {string|string[]} path 路径 / Path.
553
+ * @param {*} value 写入值 / Value.
554
+ * @returns {object}
555
+ * @see {@link https://lodash.com/docs/#set lodash.set}
556
+ * @see {@link https://www.lodashjs.com/docs/lodash.set lodash.set (中文)}
557
+ */
558
+ static set(object, path, value) {
559
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
560
+ 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;
561
+ return object;
562
+ }
563
+
564
+ /**
565
+ * 将点路径或数组下标路径转换为数组。
566
+ * Convert dot/array-index path string into path segments.
567
+ *
568
+ * @param {string} value 路径字符串 / Path string.
569
+ * @returns {string[]}
570
+ * @see {@link https://lodash.com/docs/#toPath lodash.toPath}
571
+ * @see {@link https://www.lodashjs.com/docs/lodash.toPath lodash.toPath (中文)}
572
+ */
573
+ static toPath(value) {
574
+ return value
575
+ .replace(/\[(\d+)\]/g, ".$1")
576
+ .split(".")
577
+ .filter(Boolean);
578
+ }
579
+
580
+ /**
581
+ * HTML 实体反转义。
582
+ * Unescape HTML entities.
583
+ *
584
+ * @param {string} string 输入文本 / Input text.
585
+ * @returns {string}
586
+ * @see {@link https://lodash.com/docs/#unescape lodash.unescape}
587
+ * @see {@link https://www.lodashjs.com/docs/lodash.unescape lodash.unescape (中文)}
588
+ */
589
+ static unescape(string) {
590
+ const map = {
591
+ "&amp;": "&",
592
+ "&lt;": "<",
593
+ "&gt;": ">",
594
+ "&quot;": '"',
595
+ "&#39;": "'",
596
+ };
597
+ return string.replace(/&amp;|&lt;|&gt;|&quot;|&#39;/g, m => map[m]);
598
+ }
599
+
600
+ /**
601
+ * 删除对象路径对应的值。
602
+ * Remove value by object path.
603
+ *
604
+ * @param {object} [object={}] 目标对象 / Target object.
605
+ * @param {string|string[]} [path=""] 路径 / Path.
606
+ * @returns {boolean}
607
+ * @see {@link https://lodash.com/docs/#unset lodash.unset}
608
+ * @see {@link https://www.lodashjs.com/docs/lodash.unset lodash.unset (中文)}
609
+ */
610
+ static unset(object = {}, path = "") {
611
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
612
+ const result = path.reduce((previousValue, currentValue, currentIndex) => {
613
+ if (currentIndex === path.length - 1) {
614
+ delete previousValue[currentValue];
615
+ return true;
616
+ }
617
+ return Object(previousValue)[currentValue];
618
+ }, object);
619
+ return result;
620
+ }
621
+ }
622
+
623
+ /**
624
+ * HTTP 状态码文本映射表。
625
+ * HTTP status code to status text map.
626
+ *
627
+ * 主要用途:
628
+ * Primary usage:
629
+ * - 为 Quantumult X 的 `$done` 状态行拼接提供状态文本
630
+ * - Provide status text for Quantumult X `$done` status-line composition
631
+ * - QX 在部分场景要求 `status` 为完整状态行(如 `HTTP/1.1 200 OK`)
632
+ * - QX may require full status line (e.g. `HTTP/1.1 200 OK`) in some cases
633
+ *
634
+ * 参考:
635
+ * Reference:
636
+ * - https://github.com/crossutility/Quantumult-X/raw/refs/heads/master/sample-rewrite-response-header.js
637
+ *
638
+ * @type {Record<number, string>}
639
+ */
640
+ const StatusTexts = {
641
+ 100: "Continue",
642
+ 101: "Switching Protocols",
643
+ 102: "Processing",
644
+ 103: "Early Hints",
645
+ 200: "OK",
646
+ 201: "Created",
647
+ 202: "Accepted",
648
+ 203: "Non-Authoritative Information",
649
+ 204: "No Content",
650
+ 205: "Reset Content",
651
+ 206: "Partial Content",
652
+ 207: "Multi-Status",
653
+ 208: "Already Reported",
654
+ 226: "IM Used",
655
+ 300: "Multiple Choices",
656
+ 301: "Moved Permanently",
657
+ 302: "Found",
658
+ 304: "Not Modified",
659
+ 307: "Temporary Redirect",
660
+ 308: "Permanent Redirect",
661
+ 400: "Bad Request",
662
+ 401: "Unauthorized",
663
+ 402: "Payment Required",
664
+ 403: "Forbidden",
665
+ 404: "Not Found",
666
+ 405: "Method Not Allowed",
667
+ 406: "Not Acceptable",
668
+ 407: "Proxy Authentication Required",
669
+ 408: "Request Timeout",
670
+ 409: "Conflict",
671
+ 410: "Gone",
672
+ 411: "Length Required",
673
+ 412: "Precondition Failed",
674
+ 413: "Content Too Large",
675
+ 414: "URI Too Long",
676
+ 415: "Unsupported Media Type",
677
+ 416: "Range Not Satisfiable",
678
+ 417: "Expectation Failed",
679
+ 418: "I'm a teapot",
680
+ 421: "Misdirected Request",
681
+ 422: "Unprocessable Entity",
682
+ 423: "Locked",
683
+ 424: "Failed Dependency",
684
+ 425: "Too Early",
685
+ 426: "Upgrade Required",
686
+ 428: "Precondition Required",
687
+ 429: "Too Many Requests",
688
+ 431: "Request Header Fields Too Large",
689
+ 451: "Unavailable For Legal Reasons",
690
+ 500: "Internal Server Error",
691
+ 501: "Not Implemented",
692
+ 502: "Bad Gateway",
693
+ 503: "Service Unavailable",
694
+ 504: "Gateway Timeout",
695
+ 505: "HTTP Version Not Supported",
696
+ 506: "Variant Also Negotiates",
697
+ 507: "Insufficient Storage",
698
+ 508: "Loop Detected",
699
+ 510: "Not Extended",
700
+ 511: "Network Authentication Required",
701
+ };
702
+
703
+ /**
704
+ * `done` 的统一入参结构。
705
+ * Unified `done` input payload.
706
+ *
707
+ * @typedef {object} DonePayload
708
+ * @property {number|string} [status] 响应状态码或状态行 / Response status code or status line.
709
+ * @property {string} [url] 响应 URL / Response URL.
710
+ * @property {Record<string, any>} [headers] 响应头 / Response headers.
711
+ * @property {string|ArrayBuffer|ArrayBufferView} [body] 响应体 / Response body.
712
+ * @property {ArrayBuffer} [bodyBytes] 二进制响应体 / Binary response body.
713
+ * @property {string} [policy] 指定策略名 / Preferred policy name.
714
+ */
715
+
716
+ /**
717
+ * 结束脚本执行并按平台转换参数。
718
+ * Complete script execution with platform-specific parameter mapping.
719
+ *
720
+ * 说明:
721
+ * Notes:
722
+ * - 这是调用入口,平台原生 `$done` 差异在内部处理
723
+ * - This is the call entry and native `$done` differences are handled internally
724
+ * - Worker 不调用 `$done` 或退出进程,仅记录日志
725
+ * - Worker neither calls `$done` nor exits the process; it only logs
726
+ * - Node.js 不调用 `$done`,而是直接退出进程
727
+ * - Node.js does not call `$done`; it exits the process directly
728
+ * - 未识别平台仅记录结束日志,不会强制退出
729
+ * - Unknown runtimes only log completion and do not force an exit
730
+ *
731
+ * @param {DonePayload} [object={}] 统一响应对象 / Unified response object.
732
+ * @returns {void}
733
+ */
734
+ function done(object = {}) {
735
+ switch ($app) {
736
+ case "Surge":
737
+ if (object.policy) Lodash.set(object, "headers.X-Surge-Policy", object.policy);
738
+ Console.log("🚩 执行结束!", `🕛 ${new Date().getTime() / 1000 - $script.startTime} 秒`);
739
+ $done(object);
740
+ break;
741
+ case "Loon":
742
+ if (object.policy) object.node = object.policy;
743
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
744
+ $done(object);
745
+ break;
746
+ case "Stash":
747
+ if (object.policy) Lodash.set(object, "headers.X-Stash-Selected-Proxy", encodeURI(object.policy));
748
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
749
+ $done(object);
750
+ break;
751
+ case "Egern":
752
+ Console.log("🚩 执行结束!");
753
+ $done(object);
754
+ break;
755
+ case "Shadowrocket":
756
+ Console.log("🚩 执行结束!");
757
+ $done(object);
758
+ break;
759
+ case "Quantumult X":
760
+ if (object.policy) Lodash.set(object, "opts.policy", object.policy);
761
+ object = Lodash.pick(object, ["status", "url", "headers", "body", "bodyBytes"]);
762
+ switch (typeof object.status) {
763
+ case "number":
764
+ object.status = `HTTP/1.1 ${object.status} ${StatusTexts[object.status]}`;
765
+ break;
766
+ case "string":
767
+ case "undefined":
768
+ break;
769
+ default:
770
+ throw new TypeError(`${Function.name}: 参数类型错误, status 必须为数字或字符串`);
771
+ }
772
+ if (object.body instanceof ArrayBuffer) {
773
+ object.bodyBytes = object.body;
774
+ object.body = undefined;
775
+ } else if (ArrayBuffer.isView(object.body)) {
776
+ object.bodyBytes = object.body.buffer.slice(object.body.byteOffset, object.body.byteLength + object.body.byteOffset);
777
+ object.body = undefined;
778
+ } else if (object.body) object.bodyBytes = undefined;
779
+ Console.log("🚩 执行结束!");
780
+ $done(object);
781
+ break;
782
+ case "Worker":
783
+ Console.log("🚩 执行结束!");
784
+ break;
785
+ case "Node.js":
786
+ Console.log("🚩 执行结束!");
787
+ process.exit(1);
788
+ break;
789
+ default:
790
+ Console.log("🚩 执行结束!");
791
+ break;
792
+ }
793
+ }
794
+
795
+ /**
796
+ * 为没有原生远程 Mock 的代理返回 BoxJS JSON,不提供存储或页面处理。
797
+ * Return BoxJS JSON on proxies without native remote Mock, without storage or page handling.
798
+ * @param {unknown} config 构建时嵌入的 BoxJS JSON / BoxJS JSON embedded at build time.
799
+ * @returns {void} 将响应交给宿主 / Deliver the response to the host.
800
+ */
801
+ function mockConfiguration(config) {
802
+ const method = globalThis.$request.method;
803
+ const allowed = method === "GET" || method === "HEAD";
804
+ const response = {
805
+ status: allowed ? 200 : 405,
806
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", Allow: "GET, HEAD" },
807
+ body: method === "HEAD" ? "" : JSON.stringify(allowed ? config : { error: "Method not allowed" }),
808
+ };
809
+ done($app === "Quantumult X" ? response : { response });
810
+ }
811
+
812
+ exports.mockConfiguration = mockConfiguration;
813
+
814
+ return exports;
815
+
816
+ })({});
@@ -1916,8 +1916,8 @@ var PreferencePanes = (function (exports) {
1916
1916
  #origin;
1917
1917
  /** @type {string} 安装配置中的存储根 / Storage root from installation config. */
1918
1918
  #storageKey;
1919
- /** @type {string} 安装配置中的模块 / Module from installation config. */
1920
- #module;
1919
+ /** @type {Set<string>} 独立模块允许访问的业务模块 / Business modules allowed by the standalone installation. */
1920
+ #modules;
1921
1921
  /** @type {string} 页面标记头 / Page marker header. */
1922
1922
  #requestHeader;
1923
1923
 
@@ -1931,11 +1931,13 @@ var PreferencePanes = (function (exports) {
1931
1931
  const target = new URL(origin);
1932
1932
  if (target.protocol !== "https:" || target.pathname !== "/" || target.search || target.hash || target.username || target.password) throw new TypeError("origin must be an HTTPS origin");
1933
1933
  if (typeof storageKey !== "string" || !storageKey || storageKey.startsWith("@")) throw new TypeError("storageKey must be a literal root key");
1934
- validatePathParts([module]);
1934
+ const modules = Array.isArray(module) ? module : [module];
1935
+ if (!modules.length) throw new TypeError("At least one module is required");
1936
+ validatePathParts(modules);
1935
1937
  if (!/^[a-z][a-z0-9-]*$/i.test(requestHeader)) throw new TypeError("Invalid requestHeader");
1936
1938
  this.#origin = target.origin;
1937
1939
  this.#storageKey = storageKey;
1938
- this.#module = module;
1940
+ this.#modules = new Set(modules);
1939
1941
  this.#requestHeader = requestHeader;
1940
1942
  }
1941
1943
 
@@ -1956,7 +1958,7 @@ var PreferencePanes = (function (exports) {
1956
1958
  } catch (error) {
1957
1959
  return reply(400, { error: error.message });
1958
1960
  }
1959
- if (parts[0] !== this.#module) return reply(404, { error: "Module is not handled" });
1961
+ if (!this.#modules.has(parts[0])) return reply(404, { error: "Module is not handled" });
1960
1962
  const requestHeaders = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
1961
1963
  if (requestHeaders[this.#requestHeader.toLowerCase()] !== "1" || (requestHeaders.origin && requestHeaders.origin !== this.#origin)) return reply(403, { error: "Forbidden settings client" });
1962
1964
  let value;
@@ -1916,8 +1916,8 @@
1916
1916
  #origin;
1917
1917
  /** @type {string} 安装配置中的存储根 / Storage root from installation config. */
1918
1918
  #storageKey;
1919
- /** @type {string} 安装配置中的模块 / Module from installation config. */
1920
- #module;
1919
+ /** @type {Set<string>} 独立模块允许访问的业务模块 / Business modules allowed by the standalone installation. */
1920
+ #modules;
1921
1921
  /** @type {string} 页面标记头 / Page marker header. */
1922
1922
  #requestHeader;
1923
1923
 
@@ -1931,11 +1931,13 @@
1931
1931
  const target = new URL(origin);
1932
1932
  if (target.protocol !== "https:" || target.pathname !== "/" || target.search || target.hash || target.username || target.password) throw new TypeError("origin must be an HTTPS origin");
1933
1933
  if (typeof storageKey !== "string" || !storageKey || storageKey.startsWith("@")) throw new TypeError("storageKey must be a literal root key");
1934
- validatePathParts([module]);
1934
+ const modules = Array.isArray(module) ? module : [module];
1935
+ if (!modules.length) throw new TypeError("At least one module is required");
1936
+ validatePathParts(modules);
1935
1937
  if (!/^[a-z][a-z0-9-]*$/i.test(requestHeader)) throw new TypeError("Invalid requestHeader");
1936
1938
  this.#origin = target.origin;
1937
1939
  this.#storageKey = storageKey;
1938
- this.#module = module;
1940
+ this.#modules = new Set(modules);
1939
1941
  this.#requestHeader = requestHeader;
1940
1942
  }
1941
1943
 
@@ -1956,7 +1958,7 @@
1956
1958
  } catch (error) {
1957
1959
  return reply(400, { error: error.message });
1958
1960
  }
1959
- if (parts[0] !== this.#module) return reply(404, { error: "Module is not handled" });
1961
+ if (!this.#modules.has(parts[0])) return reply(404, { error: "Module is not handled" });
1960
1962
  const requestHeaders = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
1961
1963
  if (requestHeaders[this.#requestHeader.toLowerCase()] !== "1" || (requestHeaders.origin && requestHeaders.origin !== this.#origin)) return reply(403, { error: "Forbidden settings client" });
1962
1964
  let value;
@@ -5,11 +5,11 @@
5
5
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6
6
  <meta name="color-scheme" content="light dark">
7
7
  <title>Preferences</title>
8
- <link rel="stylesheet" href="/settings/assets/panel.css?v=0.5.0">
9
- <link rel="stylesheet" href="/settings/assets/home.css?v=0.5.0">
8
+ <link rel="stylesheet" href="/settings/assets/panel.css?v=0.6.0">
9
+ <link rel="stylesheet" href="/settings/assets/home.css?v=0.6.0">
10
10
  </head>
11
11
  <body>
12
12
  <main id="preferences"></main>
13
- <script type="module" src="/settings/assets/app.mjs?v=0.5.0"></script>
13
+ <script type="module" src="/settings/assets/app.mjs?v=0.6.0"></script>
14
14
  </body>
15
15
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nsnanocat/preference-panes",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Shared settings API runtime for JavaScript proxy modules",
5
5
  "author": "VirgilClyne <Virgil@nanocat.me>",
6
6
  "homepage": "https://NSNanoCat.github.io/preference-panes",
@@ -30,6 +30,7 @@
30
30
  "./dist/preference-panes.mjs": "./dist/preference-panes.mjs",
31
31
  "./dist/preference-panes.request.js": "./dist/preference-panes.request.js",
32
32
  "./dist/preference-panes.proxy.js": "./dist/preference-panes.proxy.js",
33
+ "./dist/preference-panes.config.js": "./dist/preference-panes.config.js",
33
34
  "./dist/settings/*": "./dist/settings/*"
34
35
  },
35
36
  "types": "src/index.d.ts",
@@ -12,8 +12,8 @@ export class SettingsHandler {
12
12
  #origin;
13
13
  /** @type {string} 安装配置中的存储根 / Storage root from installation config. */
14
14
  #storageKey;
15
- /** @type {string} 安装配置中的模块 / Module from installation config. */
16
- #module;
15
+ /** @type {Set<string>} 独立模块允许访问的业务模块 / Business modules allowed by the standalone installation. */
16
+ #modules;
17
17
  /** @type {string} 页面标记头 / Page marker header. */
18
18
  #requestHeader;
19
19
 
@@ -27,11 +27,13 @@ export class SettingsHandler {
27
27
  const target = new URL(origin);
28
28
  if (target.protocol !== "https:" || target.pathname !== "/" || target.search || target.hash || target.username || target.password) throw new TypeError("origin must be an HTTPS origin");
29
29
  if (typeof storageKey !== "string" || !storageKey || storageKey.startsWith("@")) throw new TypeError("storageKey must be a literal root key");
30
- validatePathParts([module]);
30
+ const modules = Array.isArray(module) ? module : [module];
31
+ if (!modules.length) throw new TypeError("At least one module is required");
32
+ validatePathParts(modules);
31
33
  if (!/^[a-z][a-z0-9-]*$/i.test(requestHeader)) throw new TypeError("Invalid requestHeader");
32
34
  this.#origin = target.origin;
33
35
  this.#storageKey = storageKey;
34
- this.#module = module;
36
+ this.#modules = new Set(modules);
35
37
  this.#requestHeader = requestHeader;
36
38
  }
37
39
 
@@ -52,7 +54,7 @@ export class SettingsHandler {
52
54
  } catch (error) {
53
55
  return reply(400, { error: error.message });
54
56
  }
55
- if (parts[0] !== this.#module) return reply(404, { error: "Module is not handled" });
57
+ if (!this.#modules.has(parts[0])) return reply(404, { error: "Module is not handled" });
56
58
  const requestHeaders = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
57
59
  if (requestHeaders[this.#requestHeader.toLowerCase()] !== "1" || (requestHeaders.origin && requestHeaders.origin !== this.#origin)) return reply(403, { error: "Forbidden settings client" });
58
60
  let value;
package/src/index.d.ts CHANGED
@@ -79,8 +79,8 @@ export interface SettingsHandlerOptions {
79
79
  origin: string;
80
80
  /** 顶层持久化键,不能使用 @ 路径语法 / Literal top-level storage key, without @ path syntax. */
81
81
  storageKey: string;
82
- /** /api/ 后的模块段,只能访问该模块内的数据 / Module segment following /api/; access stays within this module. */
83
- module: string;
82
+ /** /api/ 后允许访问的模块;独立通用模块可声明多个 / Allowed module segments following /api/; a standalone installation can declare several. */
83
+ module: string | string[];
84
84
  /** 默认 X-Settings-Client,值必须为 1;不是认证凭据 / Defaults to X-Settings-Client with value 1; not an authentication credential. */
85
85
  requestHeader?: string;
86
86
  }
@@ -0,0 +1,19 @@
1
+ import { $app } from "@nsnanocat/util/lib/app.mjs";
2
+ import { done } from "@nsnanocat/util/lib/done.mjs";
3
+
4
+ /**
5
+ * 为没有原生远程 Mock 的代理返回 BoxJS JSON,不提供存储或页面处理。
6
+ * Return BoxJS JSON on proxies without native remote Mock, without storage or page handling.
7
+ * @param {unknown} config 构建时嵌入的 BoxJS JSON / BoxJS JSON embedded at build time.
8
+ * @returns {void} 将响应交给宿主 / Deliver the response to the host.
9
+ */
10
+ export function mockConfiguration(config) {
11
+ const method = globalThis.$request.method;
12
+ const allowed = method === "GET" || method === "HEAD";
13
+ const response = {
14
+ status: allowed ? 200 : 405,
15
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", Allow: "GET, HEAD" },
16
+ body: method === "HEAD" ? "" : JSON.stringify(allowed ? config : { error: "Method not allowed" }),
17
+ };
18
+ done($app === "Quantumult X" ? response : { response });
19
+ }