@nsnanocat/preference-panes 0.9.16 → 1.1.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/dist/web.js ADDED
@@ -0,0 +1,1202 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ class URLSearchParams {
5
+ constructor(params, onUpdate) {
6
+ switch (typeof params) {
7
+ case "string": {
8
+ if (params.length === 0)
9
+ break;
10
+ if (params.startsWith("?"))
11
+ params = params.slice(1);
12
+ const pairs = params.split("&").map(pair => {
13
+ const separator = pair.indexOf("=");
14
+ return separator < 0 ? [pair, ""] : [pair.slice(0, separator), pair.slice(separator + 1)];
15
+ });
16
+ pairs.forEach(([key, value]) => {
17
+ this.#params.push(key ? this.#decodeQueryComponent(key) : key);
18
+ this.#values.push(this.#decodeQueryComponent(value));
19
+ });
20
+ break;
21
+ }
22
+ case "object":
23
+ if (Array.isArray(params)) {
24
+ Object.entries(params).forEach(([key, value]) => {
25
+ this.#params.push(key);
26
+ this.#values.push(value);
27
+ });
28
+ }
29
+ else if (Symbol.iterator in Object(params)) {
30
+ for (const [key, value] of params) {
31
+ this.#params.push(key);
32
+ this.#values.push(value);
33
+ }
34
+ }
35
+ break;
36
+ }
37
+ this.#updateSearchString(this.#params, this.#values);
38
+ this.#onUpdate = onUpdate;
39
+ }
40
+ // Create 2 seperate arrays for the params and values to make management and lookup easier.
41
+ #param = "";
42
+ #params = [];
43
+ #values = [];
44
+ #onUpdate;
45
+ #decodeQueryComponent(str) {
46
+ return decodeURIComponent(str.replace(/\+/g, " "));
47
+ }
48
+ #encodeQueryComponent(str) {
49
+ return encodeURIComponent(str)
50
+ .replace(/%20/g, "+")
51
+ .replace(/[!'()~]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
52
+ }
53
+ // Update the search property of the URL instance with the new params and values.
54
+ #updateSearchString(params, values) {
55
+ if (params.length === 0)
56
+ this.#param = "";
57
+ else
58
+ this.#param = params
59
+ .map((param, index) => {
60
+ switch (typeof values[index]) {
61
+ case "object":
62
+ return `${this.#encodeQueryComponent(param)}=${this.#encodeQueryComponent(JSON.stringify(values[index]))}`;
63
+ case "boolean":
64
+ case "number":
65
+ case "string":
66
+ return `${this.#encodeQueryComponent(param)}=${this.#encodeQueryComponent(values[index])}`;
67
+ case "undefined":
68
+ default:
69
+ return this.#encodeQueryComponent(param);
70
+ }
71
+ })
72
+ .join("&");
73
+ this.#onUpdate?.(this.#param);
74
+ }
75
+ // Add a given param with a given value to the end.
76
+ append(name, value) {
77
+ this.#params.push(name);
78
+ this.#values.push(value);
79
+ this.#updateSearchString(this.#params, this.#values);
80
+ }
81
+ // Remove all occurances of a given param
82
+ delete(name, value) {
83
+ while (this.#params.indexOf(name) > -1) {
84
+ this.#values.splice(this.#params.indexOf(name), 1);
85
+ this.#params.splice(this.#params.indexOf(name), 1);
86
+ }
87
+ this.#updateSearchString(this.#params, this.#values);
88
+ }
89
+ // Return an array to be structured in this way: [[param1, value1], [param2, value2]] to mimic the native method's ES6 iterator.
90
+ entries() {
91
+ return this.#params.map((param, index) => [param, this.#values[index]]);
92
+ }
93
+ // Return the value matched to the first occurance of a given param.
94
+ get(name) {
95
+ return this.#values[this.#params.indexOf(name)];
96
+ }
97
+ // Return all values matched to all occurances of a given param.
98
+ getAll(name) {
99
+ return this.#values.filter((value, index) => this.#params[index] === name);
100
+ }
101
+ // Return a boolean to indicate whether a given param exists.
102
+ has(name, value) {
103
+ return this.#params.indexOf(name) > -1;
104
+ }
105
+ // Return an array of the param names to mimic the native method's ES6 iterator.
106
+ keys() {
107
+ return this.#params;
108
+ }
109
+ // Set a given param to a given value.
110
+ set(name, value) {
111
+ if (this.#params.indexOf(name) === -1) {
112
+ this.append(name, value); // If the given param doesn't already exist, append it.
113
+ }
114
+ else {
115
+ let first = true;
116
+ const newValues = [];
117
+ // If the param already exists, change the value of the first occurance and remove any remaining occurances.
118
+ this.#params = this.#params.filter((currentParam, index) => {
119
+ if (currentParam !== name) {
120
+ newValues.push(this.#values[index]);
121
+ return true;
122
+ // If the currentParam matches the one being changed and it's the first one, keep the param and change its value to the given one.
123
+ }
124
+ else if (first) {
125
+ first = false;
126
+ newValues.push(value);
127
+ return true;
128
+ }
129
+ // If the currentParam matches the one being changed, but it's not the first, remove it.
130
+ return false;
131
+ });
132
+ this.#values = newValues;
133
+ this.#updateSearchString(this.#params, this.#values);
134
+ }
135
+ }
136
+ // Sort all key/value pairs, if any, by their keys then by their values.
137
+ sort() {
138
+ // Call entries to make sorting easier, then rewrite the params and values in the new order.
139
+ const sortedPairs = this.entries().sort();
140
+ this.#params = [];
141
+ this.#values = [];
142
+ sortedPairs.forEach(pair => {
143
+ this.#params.push(pair[0]);
144
+ this.#values.push(pair[1]);
145
+ });
146
+ this.#updateSearchString(this.#params, this.#values);
147
+ }
148
+ // Return the search string without the '?'.
149
+ toString = () => this.#param;
150
+ // Return and array of the param values to mimic the native method's ES6 iterator..
151
+ values = () => this.#values.values();
152
+ }
153
+
154
+ class URL {
155
+ constructor(url, base) {
156
+ switch (typeof url) {
157
+ case "string": {
158
+ const urlIsValid = /^(blob:|file:)?[a-zA-z]+:\/\/.*/.test(url);
159
+ const baseIsValid = base ? /^(blob:|file:)?[a-zA-z]+:\/\/.*/.test(base) : false;
160
+ // If a string is passed for url instead of location or link, then set the properties of the URL instance.
161
+ if (urlIsValid)
162
+ this.href = url;
163
+ // If the url isn't valid, but the base is, then prepend the base to the url.
164
+ else if (baseIsValid)
165
+ this.href = base + url;
166
+ // If no valid url or base is given, then throw a type error.
167
+ else
168
+ throw new TypeError('URL string is not valid. If using a relative url, a second argument needs to be passed representing the base URL. Example: new URL("relative/path", "http://www.example.com");');
169
+ break;
170
+ }
171
+ case "object":
172
+ break;
173
+ default:
174
+ throw new TypeError("Invalid argument type.");
175
+ }
176
+ }
177
+ #url = {
178
+ hash: "",
179
+ host: "",
180
+ hostname: "",
181
+ href: "",
182
+ password: "",
183
+ pathname: "",
184
+ port: Number.NaN,
185
+ protocol: "",
186
+ search: "",
187
+ searchParams: new URLSearchParams(""),
188
+ username: "",
189
+ };
190
+ // refer: http://www.ietf.org/rfc/rfc3986.txt
191
+ static #URLRegExp = /^(?<scheme>([^:\/?#]+):)?(?:\/\/(?<authority>[^\/?#]*))?(?<path>[^?#]*)(?<query>\?([^#]*))?(?<hash>#(.*))?$/;
192
+ static #AuthorityRegExp = /^(?<authentication>(?<username>[^:]*)(:(?<password>[^@]*))?@)?(?<hostname>[^:]+)(:(?<port>\d+))?$/;
193
+ get hash() {
194
+ return this.#url.hash;
195
+ }
196
+ set hash(value) {
197
+ if (value.length !== 0) {
198
+ if (value.startsWith("#"))
199
+ value = value.slice(1);
200
+ this.#url.hash = `#${encodeURIComponent(value)}`;
201
+ }
202
+ }
203
+ get host() {
204
+ return this.port.length > 0 ? `${this.hostname}:${this.port}` : this.hostname;
205
+ }
206
+ set host(value) {
207
+ [this.hostname, this.port] = value.split(":", 2);
208
+ }
209
+ get hostname() {
210
+ return encodeURIComponent(this.#url.hostname);
211
+ }
212
+ set hostname(value) {
213
+ this.#url.hostname = value ?? "";
214
+ }
215
+ get href() {
216
+ let authority = "";
217
+ if (this.username.length > 0) {
218
+ authority += this.username;
219
+ if (this.password.length > 0)
220
+ authority += `:${this.password}`;
221
+ authority += "@";
222
+ }
223
+ return `${this.protocol}//${authority}${this.host}${this.pathname}${this.search}${this.hash}`;
224
+ }
225
+ set href(value) {
226
+ if (value.startsWith("blob:") || value.startsWith("file:"))
227
+ value = value.slice(5);
228
+ const urlMatch = value.match(URL.#URLRegExp);
229
+ if (!urlMatch)
230
+ throw new TypeError("Invalid URL format.");
231
+ this.protocol = urlMatch.groups.scheme ?? "";
232
+ const authorityMatch = urlMatch.groups.authority.match(URL.#AuthorityRegExp);
233
+ this.username = authorityMatch.groups.username ?? "";
234
+ this.password = authorityMatch.groups.password ?? "";
235
+ this.hostname = authorityMatch.groups.hostname ?? "";
236
+ this.port = authorityMatch.groups.port ?? "";
237
+ this.pathname = urlMatch.groups.path ?? "";
238
+ this.search = urlMatch.groups.query ?? "";
239
+ this.hash = urlMatch.groups.hash ?? "";
240
+ }
241
+ get origin() {
242
+ return `${this.protocol}//${this.host}`;
243
+ }
244
+ get password() {
245
+ return encodeURIComponent(this.#url.password);
246
+ }
247
+ set password(value) {
248
+ if (this.username.length > 0)
249
+ this.#url.password = value ?? "";
250
+ }
251
+ get pathname() {
252
+ return `/${this.#url.pathname}`;
253
+ }
254
+ set pathname(value) {
255
+ value = `${value}`;
256
+ if (value.startsWith("/"))
257
+ value = value.slice(1);
258
+ this.#url.pathname = value;
259
+ }
260
+ get port() {
261
+ if (Number.isNaN(this.#url.port))
262
+ return "";
263
+ const port = this.#url.port.toString();
264
+ if (this.protocol === "ftp:" && port === "21")
265
+ return "";
266
+ if (this.protocol === "http:" && port === "80")
267
+ return "";
268
+ if (this.protocol === "https:" && port === "443")
269
+ return "";
270
+ return port;
271
+ }
272
+ set port(value) {
273
+ switch (value) {
274
+ case "":
275
+ this.#url.port = Number.NaN;
276
+ break;
277
+ default: {
278
+ const port = Number.parseInt(value, 10);
279
+ if (port >= 0 && port < 65535)
280
+ this.#url.port = port;
281
+ }
282
+ }
283
+ }
284
+ get protocol() {
285
+ return `${this.#url.protocol}:`;
286
+ }
287
+ set protocol(value) {
288
+ if (value.endsWith(":"))
289
+ value = value.slice(0, -1);
290
+ this.#url.protocol = value;
291
+ }
292
+ get search() {
293
+ if (this.#url.search.length > 0)
294
+ return `?${this.#url.search}`;
295
+ else
296
+ return "";
297
+ }
298
+ set search(value) {
299
+ value = `${value}`;
300
+ if (value.startsWith("?"))
301
+ value = value.slice(1);
302
+ this.#url.search = value;
303
+ this.#url.searchParams = new URLSearchParams(this.#url.search, search => {
304
+ this.#url.search = search;
305
+ });
306
+ }
307
+ get searchParams() {
308
+ return this.#url.searchParams;
309
+ }
310
+ get username() {
311
+ return encodeURIComponent(this.#url.username);
312
+ }
313
+ set username(value) {
314
+ this.#url.username = value ?? "";
315
+ }
316
+ static parse = (url, base) => new URL(url, base);
317
+ /**
318
+ * Returns the string representation of the URL.
319
+ *
320
+ * @returns {string} The href of the URL.
321
+ */
322
+ toString = () => this.href;
323
+ /**
324
+ * Converts the URL object properties to a JSON string.
325
+ *
326
+ * @returns {string} A JSON string representation of the URL object.
327
+ */
328
+ toJSON = () => JSON.stringify({
329
+ hash: this.hash,
330
+ host: this.host,
331
+ hostname: this.hostname,
332
+ href: this.href,
333
+ origin: this.origin,
334
+ password: this.password,
335
+ pathname: this.pathname,
336
+ port: this.port,
337
+ protocol: this.protocol,
338
+ search: this.search,
339
+ searchParams: this.searchParams,
340
+ username: this.username,
341
+ });
342
+ }
343
+
344
+ /**
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)}
367
+ */
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
+ })();
392
+
393
+ /**
394
+ * 统一日志工具,兼容各脚本平台、Worker 与 Node.js。
395
+ * Unified logger compatible with script platforms, Worker, and Node.js.
396
+ *
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`
403
+ *
404
+ * @example
405
+ * Console.logLevel = "debug";
406
+ * Console.debug("only shown when level >= DEBUG");
407
+ * Console.logLevel = 2; // WARN
408
+ */
409
+ class Console {
410
+ static #counts = new Map([]);
411
+ static #groups = [];
412
+ static #times = new Map([]);
413
+
414
+ /**
415
+ * 清空控制台(当前为空实现)。
416
+ * Clear console (currently a no-op).
417
+ *
418
+ * @returns {void}
419
+ */
420
+ static clear = () => {};
421
+
422
+ /**
423
+ * 增加计数器并打印当前值。
424
+ * Increment counter and print the current value.
425
+ *
426
+ * @param {string} [label="default"] 计数器名称 / Counter label.
427
+ * @returns {void}
428
+ */
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
+ };
440
+
441
+ /**
442
+ * 重置计数器。
443
+ * Reset a counter.
444
+ *
445
+ * @param {string} [label="default"] 计数器名称 / Counter label.
446
+ * @returns {void}
447
+ */
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;
457
+ }
458
+ };
459
+
460
+ /**
461
+ * 输出调试日志。
462
+ * Print debug logs.
463
+ *
464
+ * @param {...any} msg 日志内容 / Log messages.
465
+ * @returns {void}
466
+ */
467
+ static debug = (...msg) => {
468
+ if (Console.#level < 4) return;
469
+ msg = msg.map(m => `🅱️ ${m}`);
470
+ Console.log(...msg);
471
+ };
472
+
473
+ /**
474
+ * 输出错误日志。
475
+ * Print error logs.
476
+ *
477
+ * @param {...any} msg 日志内容 / Log messages.
478
+ * @returns {void}
479
+ */
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);
498
+ }
499
+
500
+ /**
501
+ * `error` 的别名。
502
+ * Alias of `error`.
503
+ *
504
+ * @param {...any} msg 日志内容 / Log messages.
505
+ * @returns {void}
506
+ */
507
+ static exception = (...msg) => Console.error(...msg);
508
+
509
+ /**
510
+ * 进入日志分组。
511
+ * Enter a log group.
512
+ *
513
+ * @param {string} label 分组名 / Group label.
514
+ * @returns {number}
515
+ */
516
+ static group = label => Console.#groups.unshift(label);
517
+
518
+ /**
519
+ * 退出日志分组。
520
+ * Exit the latest log group.
521
+ *
522
+ * @returns {*}
523
+ */
524
+ static groupEnd = () => Console.#groups.shift();
525
+
526
+ /**
527
+ * 输出信息日志。
528
+ * Print info logs.
529
+ *
530
+ * @param {...any} msg 日志内容 / Log messages.
531
+ * @returns {void}
532
+ */
533
+ static info(...msg) {
534
+ if (Console.#level < 3) return;
535
+ msg = msg.map(m => `ℹ️ ${m}`);
536
+ Console.log(...msg);
537
+ }
538
+
539
+ static #level = 3;
540
+
541
+ /**
542
+ * 获取日志级别文本。
543
+ * Get current log level text.
544
+ *
545
+ * @returns {"OFF"|"ERROR"|"WARN"|"INFO"|"DEBUG"|"ALL"}
546
+ */
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
+ }
564
+
565
+ /**
566
+ * 设置日志级别。
567
+ * Set current log level.
568
+ *
569
+ * @param {number|string} level 级别值 / Level value.
570
+ */
571
+ static set logLevel(level) {
572
+ switch (typeof level) {
573
+ case "string":
574
+ level = level.toLowerCase();
575
+ break;
576
+ case "number":
577
+ break;
578
+ case "undefined":
579
+ default:
580
+ level = "warn";
581
+ break;
582
+ }
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;
591
+ break;
592
+ case 2:
593
+ case "warn":
594
+ case "warning":
595
+ default:
596
+ Console.#level = 2;
597
+ break;
598
+ case 3:
599
+ case "info":
600
+ Console.#level = 3;
601
+ break;
602
+ case 4:
603
+ case "debug":
604
+ Console.#level = 4;
605
+ break;
606
+ case 5:
607
+ case "all":
608
+ Console.#level = 5;
609
+ break;
610
+ }
611
+ }
612
+
613
+ /**
614
+ * 输出通用日志。
615
+ * Print generic logs.
616
+ *
617
+ * 说明:
618
+ * Notes:
619
+ * - 多行字符串参数会按换行拆分为多个独立日志项。
620
+ * - Multi-line string arguments are split into multiple log entries by line breaks.
621
+ *
622
+ * @param {...any} msg 日志内容 / Log messages.
623
+ * @returns {void}
624
+ */
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];
640
+ }
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
+ };
649
+
650
+ /**
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.
662
+ *
663
+ * @param {string} [label="default"] 计时器名称 / Timer label.
664
+ * @returns {boolean}
665
+ */
666
+ static timeEnd = (label = "default") => Console.#times.delete(label);
667
+
668
+ /**
669
+ * 输出当前计时器耗时。
670
+ * Print elapsed time for a timer.
671
+ *
672
+ * @param {string} [label="default"] 计时器名称 / Timer label.
673
+ * @returns {void}
674
+ */
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`);
679
+ };
680
+
681
+ /**
682
+ * 输出警告日志。
683
+ * Print warning logs.
684
+ *
685
+ * @param {...any} msg 日志内容 / Log messages.
686
+ * @returns {void}
687
+ */
688
+ static warn(...msg) {
689
+ if (Console.#level < 2) return;
690
+ msg = msg.map(m => `⚠️ ${m}`);
691
+ Console.log(...msg);
692
+ }
693
+ }
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 {
715
+ /**
716
+ * HTML 特殊字符转义。
717
+ * Escape HTML special characters.
718
+ *
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 (中文)}
723
+ */
724
+ static escape(string) {
725
+ const map = {
726
+ "&": "&amp;",
727
+ "<": "&lt;",
728
+ ">": "&gt;",
729
+ '"': "&quot;",
730
+ "'": "&#39;",
731
+ };
732
+ return string.replace(/[&<>"']/g, m => map[m]);
733
+ }
734
+
735
+ /**
736
+ * 按路径读取对象值。
737
+ * Get object value by path.
738
+ *
739
+ * @param {object} [object={}] 目标对象 / Target object.
740
+ * @param {string|string[]} [path=""] 路径 / Path.
741
+ * @param {*} [defaultValue=undefined] 默认值 / Default value.
742
+ * @returns {*}
743
+ * @see {@link https://lodash.com/docs/#get lodash.get}
744
+ * @see {@link https://www.lodashjs.com/docs/lodash.get lodash.get (中文)}
745
+ */
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);
750
+
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;
755
+ }
756
+
757
+ /**
758
+ * 递归合并源对象的自身可枚举属性到目标对象
759
+ * Recursively merge source enumerable properties into target object.
760
+ * @description 简化版 lodash.merge,用于合并配置对象
761
+ * @description A simplified lodash.merge for config merging.
762
+ *
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
+ }
834
+ }
835
+
836
+ return object;
837
+ }
838
+
839
+ /**
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 (中文)}
848
+ */
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;
853
+ }
854
+
855
+ /**
856
+ * 删除对象指定路径并返回对象。
857
+ * Omit paths from object and return the same object.
858
+ *
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 (中文)}
864
+ */
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
+ }
870
+
871
+ /**
872
+ * 仅保留对象指定键(第一层)。
873
+ * Pick selected keys from object (top level only).
874
+ *
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 (中文)}
880
+ */
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
+ }
886
+
887
+ /**
888
+ * 按路径写入对象值。
889
+ * Set object value by path.
890
+ *
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 (中文)}
897
+ */
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
+ }
903
+
904
+ /**
905
+ * 将点路径或数组下标路径转换为数组。
906
+ * Convert dot/array-index path string into path segments.
907
+ *
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 (中文)}
912
+ */
913
+ static toPath(value) {
914
+ return value
915
+ .replace(/\[(\d+)\]/g, ".$1")
916
+ .split(".")
917
+ .filter(Boolean);
918
+ }
919
+
920
+ /**
921
+ * HTML 实体反转义。
922
+ * Unescape HTML entities.
923
+ *
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 (中文)}
928
+ */
929
+ static unescape(string) {
930
+ const map = {
931
+ "&amp;": "&",
932
+ "&lt;": "<",
933
+ "&gt;": ">",
934
+ "&quot;": '"',
935
+ "&#39;": "'",
936
+ };
937
+ return string.replace(/&amp;|&lt;|&gt;|&quot;|&#39;/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
+ /**
964
+ * HTTP 状态码文本映射表。
965
+ * HTTP status code to status text map.
966
+ *
967
+ * 主要用途:
968
+ * Primary usage:
969
+ * - 为 Quantumult X 的 `$done` 状态行拼接提供状态文本
970
+ * - Provide status text for Quantumult X `$done` status-line composition
971
+ * - QX 在部分场景要求 `status` 为完整状态行(如 `HTTP/1.1 200 OK`)
972
+ * - QX may require full status line (e.g. `HTTP/1.1 200 OK`) in some cases
973
+ *
974
+ * 参考:
975
+ * Reference:
976
+ * - https://github.com/crossutility/Quantumult-X/raw/refs/heads/master/sample-rewrite-response-header.js
977
+ *
978
+ * @type {Record<number, string>}
979
+ */
980
+ const StatusTexts = {
981
+ 100: "Continue",
982
+ 101: "Switching Protocols",
983
+ 102: "Processing",
984
+ 103: "Early Hints",
985
+ 200: "OK",
986
+ 201: "Created",
987
+ 202: "Accepted",
988
+ 203: "Non-Authoritative Information",
989
+ 204: "No Content",
990
+ 205: "Reset Content",
991
+ 206: "Partial Content",
992
+ 207: "Multi-Status",
993
+ 208: "Already Reported",
994
+ 226: "IM Used",
995
+ 300: "Multiple Choices",
996
+ 301: "Moved Permanently",
997
+ 302: "Found",
998
+ 304: "Not Modified",
999
+ 307: "Temporary Redirect",
1000
+ 308: "Permanent Redirect",
1001
+ 400: "Bad Request",
1002
+ 401: "Unauthorized",
1003
+ 402: "Payment Required",
1004
+ 403: "Forbidden",
1005
+ 404: "Not Found",
1006
+ 405: "Method Not Allowed",
1007
+ 406: "Not Acceptable",
1008
+ 407: "Proxy Authentication Required",
1009
+ 408: "Request Timeout",
1010
+ 409: "Conflict",
1011
+ 410: "Gone",
1012
+ 411: "Length Required",
1013
+ 412: "Precondition Failed",
1014
+ 413: "Content Too Large",
1015
+ 414: "URI Too Long",
1016
+ 415: "Unsupported Media Type",
1017
+ 416: "Range Not Satisfiable",
1018
+ 417: "Expectation Failed",
1019
+ 418: "I'm a teapot",
1020
+ 421: "Misdirected Request",
1021
+ 422: "Unprocessable Entity",
1022
+ 423: "Locked",
1023
+ 424: "Failed Dependency",
1024
+ 425: "Too Early",
1025
+ 426: "Upgrade Required",
1026
+ 428: "Precondition Required",
1027
+ 429: "Too Many Requests",
1028
+ 431: "Request Header Fields Too Large",
1029
+ 451: "Unavailable For Legal Reasons",
1030
+ 500: "Internal Server Error",
1031
+ 501: "Not Implemented",
1032
+ 502: "Bad Gateway",
1033
+ 503: "Service Unavailable",
1034
+ 504: "Gateway Timeout",
1035
+ 505: "HTTP Version Not Supported",
1036
+ 506: "Variant Also Negotiates",
1037
+ 507: "Insufficient Storage",
1038
+ 508: "Loop Detected",
1039
+ 510: "Not Extended",
1040
+ 511: "Network Authentication Required",
1041
+ };
1042
+
1043
+ /**
1044
+ * `done` 的统一入参结构。
1045
+ * Unified `done` input payload.
1046
+ *
1047
+ * @typedef {object} DonePayload
1048
+ * @property {number|string} [status] 响应状态码或状态行 / Response status code or status line.
1049
+ * @property {string} [url] 响应 URL / Response URL.
1050
+ * @property {Record<string, any>} [headers] 响应头 / Response headers.
1051
+ * @property {string|ArrayBuffer|ArrayBufferView} [body] 响应体 / Response body.
1052
+ * @property {ArrayBuffer} [bodyBytes] 二进制响应体 / Binary response body.
1053
+ * @property {string} [policy] 指定策略名 / Preferred policy name.
1054
+ */
1055
+
1056
+ /**
1057
+ * 结束脚本执行并按平台转换参数。
1058
+ * Complete script execution with platform-specific parameter mapping.
1059
+ *
1060
+ * 说明:
1061
+ * Notes:
1062
+ * - 这是调用入口,平台原生 `$done` 差异在内部处理
1063
+ * - This is the call entry and native `$done` differences are handled internally
1064
+ * - Worker 不调用 `$done` 或退出进程,仅记录日志
1065
+ * - Worker neither calls `$done` nor exits the process; it only logs
1066
+ * - Node.js 不调用 `$done`,而是直接退出进程
1067
+ * - Node.js does not call `$done`; it exits the process directly
1068
+ * - 未识别平台仅记录结束日志,不会强制退出
1069
+ * - Unknown runtimes only log completion and do not force an exit
1070
+ *
1071
+ * @param {DonePayload} [object={}] 统一响应对象 / Unified response object.
1072
+ * @returns {void}
1073
+ */
1074
+ function done(object = {}) {
1075
+ switch ($app) {
1076
+ case "Surge":
1077
+ if (object.policy) Lodash.set(object, "headers.X-Surge-Policy", object.policy);
1078
+ Console.log("🚩 执行结束!", `🕛 ${new Date().getTime() / 1000 - $script.startTime} 秒`);
1079
+ $done(object);
1080
+ break;
1081
+ case "Loon":
1082
+ if (object.policy) object.node = object.policy;
1083
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
1084
+ $done(object);
1085
+ break;
1086
+ case "Stash":
1087
+ if (object.policy) Lodash.set(object, "headers.X-Stash-Selected-Proxy", encodeURI(object.policy));
1088
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
1089
+ $done(object);
1090
+ break;
1091
+ case "Egern":
1092
+ Console.log("🚩 执行结束!");
1093
+ $done(object);
1094
+ break;
1095
+ case "Shadowrocket":
1096
+ Console.log("🚩 执行结束!");
1097
+ $done(object);
1098
+ break;
1099
+ case "Quantumult X":
1100
+ if (object.policy) Lodash.set(object, "opts.policy", object.policy);
1101
+ object = Lodash.pick(object, ["status", "url", "headers", "body", "bodyBytes"]);
1102
+ switch (typeof object.status) {
1103
+ case "number":
1104
+ object.status = `HTTP/1.1 ${object.status} ${StatusTexts[object.status]}`;
1105
+ break;
1106
+ case "string":
1107
+ case "undefined":
1108
+ break;
1109
+ default:
1110
+ throw new TypeError(`${Function.name}: 参数类型错误, status 必须为数字或字符串`);
1111
+ }
1112
+ if (object.body instanceof ArrayBuffer) {
1113
+ object.bodyBytes = object.body;
1114
+ object.body = undefined;
1115
+ } else if (ArrayBuffer.isView(object.body)) {
1116
+ object.bodyBytes = object.body.buffer.slice(object.body.byteOffset, object.body.byteLength + object.body.byteOffset);
1117
+ object.body = undefined;
1118
+ } else if (object.body) object.bodyBytes = undefined;
1119
+ Console.log("🚩 执行结束!");
1120
+ $done(object);
1121
+ break;
1122
+ case "Worker":
1123
+ Console.log("🚩 执行结束!");
1124
+ break;
1125
+ case "Node.js":
1126
+ Console.log("🚩 执行结束!");
1127
+ process.exit(1);
1128
+ break;
1129
+ default:
1130
+ Console.log("🚩 执行结束!");
1131
+ break;
1132
+ }
1133
+ }
1134
+
1135
+ 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/index.mjs?v=1.1.0\"></script>\n </body>\n</html>\n"},"/settings/assets/index.mjs":{"type":"text/javascript","body":"/**\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 * 校验原始路径片段,不进行 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 数组、app 或订阅转换为浏览器字段定义。\n * Normalize a BoxJS array, app or subscription into browser field definitions.\n * @param {unknown} config 原始 BoxJS JSON / Raw BoxJS JSON.\n * @param {string} [module] API 模块路径段;省略时要求输入只有一个模块 / API module path segment; omission requires exactly one module.\n * @returns {import(\"../index.js\").ModuleDefinition} 浏览器字段定义 / Browser field definition.\n */\nfunction normalizeBoxJs(config, module) {\n if (!config || typeof config !== \"object\") throw new TypeError(\"Expected BoxJS JSON\");\n const document = JSON.parse(JSON.stringify(config));\n const apps = Array.isArray(document) ? [{ settings: document }] : (document.apps ?? [document]);\n if (!Array.isArray(apps)) throw new TypeError(\"Expected BoxJS apps array\");\n const 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 name = parts[0];\n let target = modules.get(name);\n if (!target) {\n target = { module: name, storageKey, entries: [], owners: new Set() };\n modules.set(name, target);\n }\n if (target.storageKey !== storageKey) throw new TypeError(`A module must use one storage root: ${name}`);\n target.entries.push(entry);\n target.owners.add(app);\n }\n }\n if (module === undefined && modules.size !== 1) throw new TypeError(\"Import BoxJS JSON for exactly one module\");\n const target = module === undefined ? modules.values().next().value : modules.get(module);\n if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const metadata = normalizeMetadata(target.owners.size === 1 ? presentation([...target.owners][0]) : {});\n const fields = [];\n for (const entry of target.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: ${target.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: target.module,\n storageKey: target.storageKey,\n fields,\n settingsPath: common,\n ...(Object.keys(metadata).length ? { metadata } : {}),\n };\n}\n\n/**\n * 保留字段所属 app 的原始展示信息。\n * Retain raw presentation metadata from the app owning the fields.\n * @param {object} source BoxJS app / BoxJS app.\n * @returns {Record<string, unknown>} 原始展示信息 / Raw presentation metadata.\n */\nfunction presentation(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 result[key] = source[key];\n }\n return result;\n}\n\n/**\n * 校验供浏览器展示的标准 BoxJS 元数据。\n * Validate standard BoxJS metadata used by the browser renderer.\n * @param {Record<string, unknown>} source 原始展示元数据 / Raw presentation metadata.\n * @returns {import(\"../index.js\").BoxJSMetadata} 规范化展示元数据 / Normalized presentation metadata.\n */\nfunction normalizeMetadata(source) {\n const result = {};\n for (const [key, value] of Object.entries(source)) {\n const multiple = key === \"icons\" || key === \"descs\";\n const values = multiple ? value : [value];\n if (!Array.isArray(values) || values.some(item => typeof item !== \"string\")) throw new TypeError(`Invalid BoxJS app ${key}`);\n result[key] = multiple ? [...values] : value;\n }\n return result;\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 * 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 * 管理单模块页面的 API 请求、值快照和会话终止。\n * Manage API requests, value snapshots, and session termination for one module page.\n */\nclass PreferencesClient {\n #module;\n #configURL;\n #definition;\n #request;\n #notify;\n #timeout;\n #session = new AbortController();\n #values;\n #saving = false;\n\n /**\n * 创建只调用模块 API、不读取或解析 BoxJS 的页面客户端。\n * Create a page client that only calls the module API and never reads or parses BoxJS.\n * @param {import(\"./client.mjs\").PreferencesClientOptions} options API 模型、请求与通知 / API model, requests, and notifications.\n */\n constructor({ model, definition, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {\n this.#module = model.module;\n this.#configURL = model.configURL;\n this.#definition = definition;\n this.#request = request;\n this.#notify = notify;\n this.#timeout = timeout;\n this.#values = structuredClone(model.values);\n }\n\n /**\n * 获取当前字段定义和值的深拷贝,不发起网络请求。\n * Return a deep copy of the current field definition and values without a network request.\n * @returns {import(\"./client.mjs\").ModuleSnapshot} 会话快照 / Session snapshot.\n */\n snapshot() {\n return structuredClone({ definition: this.#definition, values: this.#values });\n }\n\n /**\n * 读取 Settings 子树。\n * Read the Settings subtree.\n * @returns {Promise<unknown>} Settings 内容或 undefined / Settings content or undefined.\n */\n async readSettings() {\n const response = await this.#send(\"get\", { scope: \"settings\" });\n return response.status === 404 ? undefined : response.json();\n }\n\n /**\n * 读取 Caches 子树。\n * Read the Caches subtree.\n * @returns {Promise<unknown>} Caches 内容或 undefined / Caches content or undefined.\n */\n async readCaches() {\n const response = await this.#send(\"get\", { scope: \"caches\" });\n return response.status === 404 ? undefined : response.json();\n }\n\n /**\n * 删除当前模块的 Caches 子树。\n * Delete the current module Caches subtree.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n clearCaches() {\n return this.#change(\"delete\", { scope: \"caches\" }, \"clearCaches\");\n }\n\n /**\n * 删除当前模块数据并恢复页面默认值。\n * Delete current module data and restore page defaults.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n reset() {\n return this.#change(\"delete\", { scope: \"module\" }, \"reset\");\n }\n\n /**\n * 终止当前页面仍在进行的请求。\n * Abort requests still owned by the current page.\n * @returns {void} 无返回值 / No return value.\n */\n leave() {\n this.#session.abort();\n }\n\n /**\n * 写入单个字段。\n * Write one field.\n * @param {string} key 字段路径 / Field path.\n * @param {unknown} value 已校验值 / Validated value.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n set(key, value) {\n return this.#change(\"set\", { key, value }, \"write\", key);\n }\n\n /**\n * 删除单个字段覆盖值。\n * Delete one field override.\n * @param {string} key 字段路径 / Field path.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n remove(key) {\n return this.#change(\"delete\", { key }, \"delete\", key);\n }\n\n /**\n * 向模块 API 发送 JSON 动作。\n * Send a JSON action to the module API.\n * @param {\"get\" | \"set\" | \"delete\"} action 模块动作 / Module action.\n * @param {unknown} payload JSON 请求体 / JSON request body.\n * @returns {Promise<Response>} 原始响应 / Raw response.\n */\n async #send(action, payload) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (this.#session.signal.aborted) abort();\n this.#session.signal.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(abort, this.#timeout);\n try {\n const response = await this.#request(`/api/${encodeURIComponent(this.#module)}/${action}`, {\n method: \"POST\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: controller.signal,\n headers: { \"Content-Type\": \"application/json\", \"X-PreferencePanes-JSON\": this.#configURL },\n body: JSON.stringify(payload),\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 this.#session.signal.removeEventListener(\"abort\", abort);\n }\n }\n\n /**\n * 执行写入动作;成功后只更新当前页面值。\n * Execute a mutation and update only the current page values after success.\n * @param {\"set\" | \"delete\"} action API 动作 / API action.\n * @param {Record<string, unknown>} payload JSON 请求体 / JSON request body.\n * @param {\"write\" | \"delete\" | \"clearCaches\" | \"reset\"} operation 通知操作 / Notification operation.\n * @param {string} [key] 字段路径 / Field path.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n async #change(action, payload, operation, key) {\n if (this.#saving) throw new Error(\"A settings write is already in progress\");\n this.#saving = true;\n try {\n await this.#send(action, payload);\n switch (operation) {\n case \"write\":\n this.#values[key] = structuredClone(payload.value);\n break;\n case \"delete\": {\n const field = this.#definition.fields.find(candidate => candidate.key === key);\n delete this.#values[key];\n if (field && Object.hasOwn(field, \"defaultValue\")) this.#values[key] = structuredClone(field.defaultValue);\n break;\n }\n case \"clearCaches\":\n break;\n case \"reset\":\n for (const field of this.#definition.fields) {\n delete this.#values[field.key];\n if (Object.hasOwn(field, \"defaultValue\")) this.#values[field.key] = structuredClone(field.defaultValue);\n }\n break;\n }\n this.#notify({ kind: \"success\", operation, module: this.#module, key });\n } catch (error) {\n this.#notify({ kind: \"error\", operation, module: this.#module, key, message: error.message });\n throw error;\n } finally {\n this.#saving = false;\n }\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 * 管理模块表单、导航、操作队列和短暂通知。\n * Manage the module form, navigation, operation queue, and transient notifications.\n */\nclass PreferencesPanel {\n #release;\n\n /**\n * 挂载 API 返回的模块模型表单。\n * Mount the module form returned by the API.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../index.js\").ModuleModel & {definition: import(\"../index.js\").ModuleDefinition}} model 已规范化模块模型 / Normalized module model.\n */\n constructor(root, model) {\n this.#release = this.#mount(root, model);\n }\n\n /**\n * 建立面板 DOM、交互和会话,并返回其释放操作。\n * Build panel DOM, interactions, and session, then return its release operation.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../index.js\").ModuleModel & {definition: import(\"../index.js\").ModuleDefinition}} model 已规范化模块模型 / Normalized module model.\n * @returns {() => void} 释放操作 / Release operation.\n */\n #mount(root, model) {\n const { definition } = model;\n const title = definition.metadata?.name ?? definition.module;\n const document = root.ownerDocument;\n const window = document.defaultView;\n const shell = element(\"div\", \"pp-panel\");\n shell.dataset.module = definition.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: definition.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 = new PreferencesClient({ model, definition, 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 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();\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 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();\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n });\n return queue;\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().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 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().values[field.key]);\n };\n perform(\n () => {\n if (!validValue(field, value)) {\n const error = new TypeError(\"Invalid setting value\");\n notify({ kind: \"error\", operation: \"write\", key: field.key, message: error.message });\n throw error;\n }\n return client.set(field.key, value);\n },\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();\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();\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(),\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(), 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(definition.module);\n return () => {\n destroyed = true;\n menu.destroy();\n window.frameElement?.removeEventListener(\"preferencepanes:action\", onAction);\n navigation?.destroy();\n generation++;\n if (active && !saving) client.leave();\n clearTimeout(timer);\n shell.remove();\n };\n }\n\n /**\n * 移除监听器、定时器、会话和挂载内容。\n * Remove listeners, timers, session, and mounted content.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#release();\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 * 管理模块设置视图的模型规范化、样式、主题同步和面板生命周期。\n * Manage model normalization, styles, theme synchronization, and panel lifecycle for a module settings view.\n */\nclass PreferencesView {\n #existing;\n #root;\n #base;\n #ownsBase;\n #custom;\n #previousTitle;\n #previousTheme;\n #systemTheme;\n #previousKeyboard;\n #host;\n #observer;\n #panel;\n\n /**\n * 使用模块 API 返回的模型挂载设置页。\n * Mount a settings page from the model returned by the module API.\n * @param {import(\"../index.js\").ModuleModel} model API 返回的模块模型 / Module model returned by the API.\n * @param {string} [css] 可选 CSS 正文 / Optional module-scoped CSS text.\n */\n constructor(model, css = \"\") {\n if (typeof css !== \"string\") throw new TypeError(\"CSS must be a string\");\n const definition = normalizeBoxJs(model.boxjs, model.module);\n const values = { ...model.values };\n for (const field of definition.fields) {\n if (values[field.key] === undefined) continue;\n values[field.key] = normalizeStoredValue(field, values[field.key]);\n if (!validValue(field, values[field.key])) throw new TypeError(`Invalid stored value: ${field.key}`);\n }\n for (const field of definition.fields) if (values[field.key] === undefined && Object.hasOwn(field, \"defaultValue\")) values[field.key] = structuredClone(field.defaultValue);\n const rendered = { ...model, definition, values };\n const metadata = definition.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\n this.#existing = document.querySelector(\"#preferences\");\n this.#root = this.#existing ?? element(\"main\", \"\");\n if (!this.#existing) {\n this.#root.id = \"preferences\";\n document.body.append(this.#root);\n }\n const styles = installDefaultStyles(document);\n this.#base = styles.element;\n this.#ownsBase = styles.owned;\n this.#custom = element(\"style\", \"\");\n this.#custom.textContent = css;\n document.head.append(this.#custom);\n this.#previousTitle = document.title;\n this.#previousTheme = document.documentElement.dataset.theme;\n this.#systemTheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n this.#previousKeyboard = document.documentElement.style.getPropertyValue(\"--pp-keyboard-height\");\n this.#host = window.frameElement?.ownerDocument.documentElement;\n this.#syncAppearance();\n this.#systemTheme.addEventListener(\"change\", this.#syncAppearance);\n if (this.#host) {\n this.#observer = new MutationObserver(this.#syncAppearance);\n this.#observer.observe(this.#host, { attributes: true, attributeFilter: [\"data-theme\", \"style\"] });\n }\n document.title = metadata.name ?? definition.module;\n try {\n this.#root.replaceChildren();\n this.#panel = new PreferencesPanel(this.#root, rendered);\n } catch (error) {\n this.destroy();\n throw error;\n }\n }\n\n /**\n * 跟随嵌入宿主的通用环境状态,不识别业务 App 或解析其 UA。\n * Follow generic host appearance without detecting a business App or parsing its UA.\n * @returns {void} 已同步主题与键盘避让 / Theme and keyboard clearance synchronized.\n */\n #syncAppearance = () => {\n const theme = this.#host?.dataset.theme ?? this.#previousTheme ?? (this.#systemTheme.matches ? \"dark\" : \"light\");\n document.documentElement.dataset.theme = theme;\n if (this.#host) document.documentElement.style.setProperty(\"--pp-keyboard-height\", this.#host.style.getPropertyValue(\"--pp-keyboard-height\"));\n };\n\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 this.#observer?.disconnect();\n this.#systemTheme.removeEventListener(\"change\", this.#syncAppearance);\n this.#panel?.destroy();\n if (this.#ownsBase) this.#base.remove();\n this.#custom.remove();\n if (this.#existing) this.#root.replaceChildren();\n else this.#root.remove();\n document.title = this.#previousTitle;\n if (this.#previousTheme === undefined) delete document.documentElement.dataset.theme;\n else document.documentElement.dataset.theme = this.#previousTheme;\n document.documentElement.style.setProperty(\"--pp-keyboard-height\", this.#previousKeyboard);\n }\n}\n\n/**\n * 管理模块文档的页面输入、初始请求、重载和错误状态。\n * Manage page inputs, initial requests, reloads, and error states for a module document.\n */\nclass ModulePage {\n #document;\n #window;\n #root;\n #view;\n\n /**\n * 创建模块页面控制器并安装基础样式。\n * Create the module page controller and install base styles.\n * @param {Document} document 模块文档 / Module document.\n */\n constructor(document) {\n this.#document = document;\n this.#window = document.defaultView;\n this.#root = document.querySelector(\"#preferences\");\n installDefaultStyles(document);\n this.#window.addEventListener(\"pageshow\", this.#show);\n }\n\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 */\n async start() {\n try {\n this.#view?.destroy();\n this.#view = undefined;\n this.#root.replaceChildren(statusView(\"读取设置…\"));\n const inputs = this.#readInputs();\n const apiURL = new URL(`/api/${encodeURIComponent(inputs.module)}`, inputs.url).href;\n const styleURL = this.#resourceURL(inputs.css, inputs.url);\n const [style, modelResponse] = await Promise.all([styleURL ? fetch(styleURL, { cache: \"no-store\", credentials: \"omit\" }) : null, fetch(apiURL, { cache: \"no-store\", credentials: \"omit\", headers: { Accept: \"application/json\", \"X-PreferencePanes-JSON\": inputs.json } })]);\n if ((style && style.status !== 200) || modelResponse.status !== 200) throw new Error(`HTTP ${modelResponse.status !== 200 ? modelResponse.status : style.status}`);\n this.#view = new PreferencesView(await modelResponse.json(), style ? await style.text() : \"\");\n } catch (error) {\n this.#root.replaceChildren(statusView(`加载失败:${error.message}`, () => this.start()));\n }\n }\n\n /**\n * 释放页面视图和页面级监听器。\n * Release the page view and page-level listener.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#window.removeEventListener(\"pageshow\", this.#show);\n this.#view?.destroy();\n this.#view = undefined;\n }\n\n /**\n * 读取嵌入参数、文档元数据或当前 URL 输入。\n * Read embedded parameters, document metadata, or current URL inputs.\n * @returns {ReturnType<typeof pageInputs>} 页面输入 / Page inputs.\n */\n #readInputs() {\n const context = this.#document.querySelector('meta[name=\"preference-panes-inputs\"]');\n const embedded = this.#window.frameElement?.dataset.preferencePanes;\n switch (true) {\n case embedded !== undefined:\n this.#document.documentElement.dataset.preferencePanesEmbedded = \"\";\n return JSON.parse(embedded);\n case context !== null:\n return JSON.parse(decodeURIComponent(context.content));\n default:\n return pageInputs(new URL(this.#window.location.href));\n }\n }\n\n /**\n * 将可选页面资源限制为 HTTP(S) 地址。\n * Restrict an optional page resource to an HTTP(S) URL.\n * @param {string | undefined} source 资源地址 / Resource location.\n * @param {string} baseURL 页面基准地址 / Page base URL.\n * @returns {string | null} 绝对资源地址 / Absolute resource URL.\n */\n #resourceURL(source, baseURL) {\n if (!source) return null;\n const url = new URL(source, baseURL);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Resources must use HTTP(S) URLs\");\n return url.href;\n }\n\n /**\n * 从前进后退缓存恢复时重新加载模块。\n * Reload the module when restored from the back-forward cache.\n * @param {PageTransitionEvent} event 页面显示事件 / Page show event.\n * @returns {void} 无返回值 / No return value.\n */\n #show = event => {\n if (event.persisted) this.start();\n };\n}\n\nnew ModulePage(document).start();\n\nexport { ModulePage };\n"},"/settings/assets/app.mjs":{"type":"text/javascript","body":"/**\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 * 校验原始路径片段,不进行 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 数组、app 或订阅转换为浏览器字段定义。\n * Normalize a BoxJS array, app or subscription into browser field definitions.\n * @param {unknown} config 原始 BoxJS JSON / Raw BoxJS JSON.\n * @param {string} [module] API 模块路径段;省略时要求输入只有一个模块 / API module path segment; omission requires exactly one module.\n * @returns {import(\"../index.js\").ModuleDefinition} 浏览器字段定义 / Browser field definition.\n */\nfunction normalizeBoxJs(config, module) {\n if (!config || typeof config !== \"object\") throw new TypeError(\"Expected BoxJS JSON\");\n const document = JSON.parse(JSON.stringify(config));\n const apps = Array.isArray(document) ? [{ settings: document }] : (document.apps ?? [document]);\n if (!Array.isArray(apps)) throw new TypeError(\"Expected BoxJS apps array\");\n const 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 name = parts[0];\n let target = modules.get(name);\n if (!target) {\n target = { module: name, storageKey, entries: [], owners: new Set() };\n modules.set(name, target);\n }\n if (target.storageKey !== storageKey) throw new TypeError(`A module must use one storage root: ${name}`);\n target.entries.push(entry);\n target.owners.add(app);\n }\n }\n if (module === undefined && modules.size !== 1) throw new TypeError(\"Import BoxJS JSON for exactly one module\");\n const target = module === undefined ? modules.values().next().value : modules.get(module);\n if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const metadata = normalizeMetadata(target.owners.size === 1 ? presentation([...target.owners][0]) : {});\n const fields = [];\n for (const entry of target.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: ${target.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: target.module,\n storageKey: target.storageKey,\n fields,\n settingsPath: common,\n ...(Object.keys(metadata).length ? { metadata } : {}),\n };\n}\n\n/**\n * 保留字段所属 app 的原始展示信息。\n * Retain raw presentation metadata from the app owning the fields.\n * @param {object} source BoxJS app / BoxJS app.\n * @returns {Record<string, unknown>} 原始展示信息 / Raw presentation metadata.\n */\nfunction presentation(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 result[key] = source[key];\n }\n return result;\n}\n\n/**\n * 校验供浏览器展示的标准 BoxJS 元数据。\n * Validate standard BoxJS metadata used by the browser renderer.\n * @param {Record<string, unknown>} source 原始展示元数据 / Raw presentation metadata.\n * @returns {import(\"../index.js\").BoxJSMetadata} 规范化展示元数据 / Normalized presentation metadata.\n */\nfunction normalizeMetadata(source) {\n const result = {};\n for (const [key, value] of Object.entries(source)) {\n const multiple = key === \"icons\" || key === \"descs\";\n const values = multiple ? value : [value];\n if (!Array.isArray(values) || values.some(item => typeof item !== \"string\")) throw new TypeError(`Invalid BoxJS app ${key}`);\n result[key] = multiple ? [...values] : value;\n }\n return result;\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 * 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 * 管理单模块页面的 API 请求、值快照和会话终止。\n * Manage API requests, value snapshots, and session termination for one module page.\n */\nclass PreferencesClient {\n #module;\n #configURL;\n #definition;\n #request;\n #notify;\n #timeout;\n #session = new AbortController();\n #values;\n #saving = false;\n\n /**\n * 创建只调用模块 API、不读取或解析 BoxJS 的页面客户端。\n * Create a page client that only calls the module API and never reads or parses BoxJS.\n * @param {import(\"./client.mjs\").PreferencesClientOptions} options API 模型、请求与通知 / API model, requests, and notifications.\n */\n constructor({ model, definition, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {\n this.#module = model.module;\n this.#configURL = model.configURL;\n this.#definition = definition;\n this.#request = request;\n this.#notify = notify;\n this.#timeout = timeout;\n this.#values = structuredClone(model.values);\n }\n\n /**\n * 获取当前字段定义和值的深拷贝,不发起网络请求。\n * Return a deep copy of the current field definition and values without a network request.\n * @returns {import(\"./client.mjs\").ModuleSnapshot} 会话快照 / Session snapshot.\n */\n snapshot() {\n return structuredClone({ definition: this.#definition, values: this.#values });\n }\n\n /**\n * 读取 Settings 子树。\n * Read the Settings subtree.\n * @returns {Promise<unknown>} Settings 内容或 undefined / Settings content or undefined.\n */\n async readSettings() {\n const response = await this.#send(\"get\", { scope: \"settings\" });\n return response.status === 404 ? undefined : response.json();\n }\n\n /**\n * 读取 Caches 子树。\n * Read the Caches subtree.\n * @returns {Promise<unknown>} Caches 内容或 undefined / Caches content or undefined.\n */\n async readCaches() {\n const response = await this.#send(\"get\", { scope: \"caches\" });\n return response.status === 404 ? undefined : response.json();\n }\n\n /**\n * 删除当前模块的 Caches 子树。\n * Delete the current module Caches subtree.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n clearCaches() {\n return this.#change(\"delete\", { scope: \"caches\" }, \"clearCaches\");\n }\n\n /**\n * 删除当前模块数据并恢复页面默认值。\n * Delete current module data and restore page defaults.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n reset() {\n return this.#change(\"delete\", { scope: \"module\" }, \"reset\");\n }\n\n /**\n * 终止当前页面仍在进行的请求。\n * Abort requests still owned by the current page.\n * @returns {void} 无返回值 / No return value.\n */\n leave() {\n this.#session.abort();\n }\n\n /**\n * 写入单个字段。\n * Write one field.\n * @param {string} key 字段路径 / Field path.\n * @param {unknown} value 已校验值 / Validated value.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n set(key, value) {\n return this.#change(\"set\", { key, value }, \"write\", key);\n }\n\n /**\n * 删除单个字段覆盖值。\n * Delete one field override.\n * @param {string} key 字段路径 / Field path.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n remove(key) {\n return this.#change(\"delete\", { key }, \"delete\", key);\n }\n\n /**\n * 向模块 API 发送 JSON 动作。\n * Send a JSON action to the module API.\n * @param {\"get\" | \"set\" | \"delete\"} action 模块动作 / Module action.\n * @param {unknown} payload JSON 请求体 / JSON request body.\n * @returns {Promise<Response>} 原始响应 / Raw response.\n */\n async #send(action, payload) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (this.#session.signal.aborted) abort();\n this.#session.signal.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(abort, this.#timeout);\n try {\n const response = await this.#request(`/api/${encodeURIComponent(this.#module)}/${action}`, {\n method: \"POST\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: controller.signal,\n headers: { \"Content-Type\": \"application/json\", \"X-PreferencePanes-JSON\": this.#configURL },\n body: JSON.stringify(payload),\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 this.#session.signal.removeEventListener(\"abort\", abort);\n }\n }\n\n /**\n * 执行写入动作;成功后只更新当前页面值。\n * Execute a mutation and update only the current page values after success.\n * @param {\"set\" | \"delete\"} action API 动作 / API action.\n * @param {Record<string, unknown>} payload JSON 请求体 / JSON request body.\n * @param {\"write\" | \"delete\" | \"clearCaches\" | \"reset\"} operation 通知操作 / Notification operation.\n * @param {string} [key] 字段路径 / Field path.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n async #change(action, payload, operation, key) {\n if (this.#saving) throw new Error(\"A settings write is already in progress\");\n this.#saving = true;\n try {\n await this.#send(action, payload);\n switch (operation) {\n case \"write\":\n this.#values[key] = structuredClone(payload.value);\n break;\n case \"delete\": {\n const field = this.#definition.fields.find(candidate => candidate.key === key);\n delete this.#values[key];\n if (field && Object.hasOwn(field, \"defaultValue\")) this.#values[key] = structuredClone(field.defaultValue);\n break;\n }\n case \"clearCaches\":\n break;\n case \"reset\":\n for (const field of this.#definition.fields) {\n delete this.#values[field.key];\n if (Object.hasOwn(field, \"defaultValue\")) this.#values[field.key] = structuredClone(field.defaultValue);\n }\n break;\n }\n this.#notify({ kind: \"success\", operation, module: this.#module, key });\n } catch (error) {\n this.#notify({ kind: \"error\", operation, module: this.#module, key, message: error.message });\n throw error;\n } finally {\n this.#saving = false;\n }\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 * 管理模块表单、导航、操作队列和短暂通知。\n * Manage the module form, navigation, operation queue, and transient notifications.\n */\nclass PreferencesPanel {\n #release;\n\n /**\n * 挂载 API 返回的模块模型表单。\n * Mount the module form returned by the API.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../index.js\").ModuleModel & {definition: import(\"../index.js\").ModuleDefinition}} model 已规范化模块模型 / Normalized module model.\n */\n constructor(root, model) {\n this.#release = this.#mount(root, model);\n }\n\n /**\n * 建立面板 DOM、交互和会话,并返回其释放操作。\n * Build panel DOM, interactions, and session, then return its release operation.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../index.js\").ModuleModel & {definition: import(\"../index.js\").ModuleDefinition}} model 已规范化模块模型 / Normalized module model.\n * @returns {() => void} 释放操作 / Release operation.\n */\n #mount(root, model) {\n const { definition } = model;\n const title = definition.metadata?.name ?? definition.module;\n const document = root.ownerDocument;\n const window = document.defaultView;\n const shell = element(\"div\", \"pp-panel\");\n shell.dataset.module = definition.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: definition.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 = new PreferencesClient({ model, definition, 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 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();\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 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();\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n });\n return queue;\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().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 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().values[field.key]);\n };\n perform(\n () => {\n if (!validValue(field, value)) {\n const error = new TypeError(\"Invalid setting value\");\n notify({ kind: \"error\", operation: \"write\", key: field.key, message: error.message });\n throw error;\n }\n return client.set(field.key, value);\n },\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();\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();\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(),\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(), 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(definition.module);\n return () => {\n destroyed = true;\n menu.destroy();\n window.frameElement?.removeEventListener(\"preferencepanes:action\", onAction);\n navigation?.destroy();\n generation++;\n if (active && !saving) client.leave();\n clearTimeout(timer);\n shell.remove();\n };\n }\n\n /**\n * 移除监听器、定时器、会话和挂载内容。\n * Remove listeners, timers, session, and mounted content.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#release();\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 * 管理模块设置视图的模型规范化、样式、主题同步和面板生命周期。\n * Manage model normalization, styles, theme synchronization, and panel lifecycle for a module settings view.\n */\nclass PreferencesView {\n #existing;\n #root;\n #base;\n #ownsBase;\n #custom;\n #previousTitle;\n #previousTheme;\n #systemTheme;\n #previousKeyboard;\n #host;\n #observer;\n #panel;\n\n /**\n * 使用模块 API 返回的模型挂载设置页。\n * Mount a settings page from the model returned by the module API.\n * @param {import(\"../index.js\").ModuleModel} model API 返回的模块模型 / Module model returned by the API.\n * @param {string} [css] 可选 CSS 正文 / Optional module-scoped CSS text.\n */\n constructor(model, css = \"\") {\n if (typeof css !== \"string\") throw new TypeError(\"CSS must be a string\");\n const definition = normalizeBoxJs(model.boxjs, model.module);\n const values = { ...model.values };\n for (const field of definition.fields) {\n if (values[field.key] === undefined) continue;\n values[field.key] = normalizeStoredValue(field, values[field.key]);\n if (!validValue(field, values[field.key])) throw new TypeError(`Invalid stored value: ${field.key}`);\n }\n for (const field of definition.fields) if (values[field.key] === undefined && Object.hasOwn(field, \"defaultValue\")) values[field.key] = structuredClone(field.defaultValue);\n const rendered = { ...model, definition, values };\n const metadata = definition.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\n this.#existing = document.querySelector(\"#preferences\");\n this.#root = this.#existing ?? element(\"main\", \"\");\n if (!this.#existing) {\n this.#root.id = \"preferences\";\n document.body.append(this.#root);\n }\n const styles = installDefaultStyles(document);\n this.#base = styles.element;\n this.#ownsBase = styles.owned;\n this.#custom = element(\"style\", \"\");\n this.#custom.textContent = css;\n document.head.append(this.#custom);\n this.#previousTitle = document.title;\n this.#previousTheme = document.documentElement.dataset.theme;\n this.#systemTheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n this.#previousKeyboard = document.documentElement.style.getPropertyValue(\"--pp-keyboard-height\");\n this.#host = window.frameElement?.ownerDocument.documentElement;\n this.#syncAppearance();\n this.#systemTheme.addEventListener(\"change\", this.#syncAppearance);\n if (this.#host) {\n this.#observer = new MutationObserver(this.#syncAppearance);\n this.#observer.observe(this.#host, { attributes: true, attributeFilter: [\"data-theme\", \"style\"] });\n }\n document.title = metadata.name ?? definition.module;\n try {\n this.#root.replaceChildren();\n this.#panel = new PreferencesPanel(this.#root, rendered);\n } catch (error) {\n this.destroy();\n throw error;\n }\n }\n\n /**\n * 跟随嵌入宿主的通用环境状态,不识别业务 App 或解析其 UA。\n * Follow generic host appearance without detecting a business App or parsing its UA.\n * @returns {void} 已同步主题与键盘避让 / Theme and keyboard clearance synchronized.\n */\n #syncAppearance = () => {\n const theme = this.#host?.dataset.theme ?? this.#previousTheme ?? (this.#systemTheme.matches ? \"dark\" : \"light\");\n document.documentElement.dataset.theme = theme;\n if (this.#host) document.documentElement.style.setProperty(\"--pp-keyboard-height\", this.#host.style.getPropertyValue(\"--pp-keyboard-height\"));\n };\n\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 this.#observer?.disconnect();\n this.#systemTheme.removeEventListener(\"change\", this.#syncAppearance);\n this.#panel?.destroy();\n if (this.#ownsBase) this.#base.remove();\n this.#custom.remove();\n if (this.#existing) this.#root.replaceChildren();\n else this.#root.remove();\n document.title = this.#previousTitle;\n if (this.#previousTheme === undefined) delete document.documentElement.dataset.theme;\n else document.documentElement.dataset.theme = this.#previousTheme;\n document.documentElement.style.setProperty(\"--pp-keyboard-height\", this.#previousKeyboard);\n }\n}\n\n/**\n * 管理模块文档的页面输入、初始请求、重载和错误状态。\n * Manage page inputs, initial requests, reloads, and error states for a module document.\n */\nclass ModulePage {\n #document;\n #window;\n #root;\n #view;\n\n /**\n * 创建模块页面控制器并安装基础样式。\n * Create the module page controller and install base styles.\n * @param {Document} document 模块文档 / Module document.\n */\n constructor(document) {\n this.#document = document;\n this.#window = document.defaultView;\n this.#root = document.querySelector(\"#preferences\");\n installDefaultStyles(document);\n this.#window.addEventListener(\"pageshow\", this.#show);\n }\n\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 */\n async start() {\n try {\n this.#view?.destroy();\n this.#view = undefined;\n this.#root.replaceChildren(statusView(\"读取设置…\"));\n const inputs = this.#readInputs();\n const apiURL = new URL(`/api/${encodeURIComponent(inputs.module)}`, inputs.url).href;\n const styleURL = this.#resourceURL(inputs.css, inputs.url);\n const [style, modelResponse] = await Promise.all([styleURL ? fetch(styleURL, { cache: \"no-store\", credentials: \"omit\" }) : null, fetch(apiURL, { cache: \"no-store\", credentials: \"omit\", headers: { Accept: \"application/json\", \"X-PreferencePanes-JSON\": inputs.json } })]);\n if ((style && style.status !== 200) || modelResponse.status !== 200) throw new Error(`HTTP ${modelResponse.status !== 200 ? modelResponse.status : style.status}`);\n this.#view = new PreferencesView(await modelResponse.json(), style ? await style.text() : \"\");\n } catch (error) {\n this.#root.replaceChildren(statusView(`加载失败:${error.message}`, () => this.start()));\n }\n }\n\n /**\n * 释放页面视图和页面级监听器。\n * Release the page view and page-level listener.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#window.removeEventListener(\"pageshow\", this.#show);\n this.#view?.destroy();\n this.#view = undefined;\n }\n\n /**\n * 读取嵌入参数、文档元数据或当前 URL 输入。\n * Read embedded parameters, document metadata, or current URL inputs.\n * @returns {ReturnType<typeof pageInputs>} 页面输入 / Page inputs.\n */\n #readInputs() {\n const context = this.#document.querySelector('meta[name=\"preference-panes-inputs\"]');\n const embedded = this.#window.frameElement?.dataset.preferencePanes;\n switch (true) {\n case embedded !== undefined:\n this.#document.documentElement.dataset.preferencePanesEmbedded = \"\";\n return JSON.parse(embedded);\n case context !== null:\n return JSON.parse(decodeURIComponent(context.content));\n default:\n return pageInputs(new URL(this.#window.location.href));\n }\n }\n\n /**\n * 将可选页面资源限制为 HTTP(S) 地址。\n * Restrict an optional page resource to an HTTP(S) URL.\n * @param {string | undefined} source 资源地址 / Resource location.\n * @param {string} baseURL 页面基准地址 / Page base URL.\n * @returns {string | null} 绝对资源地址 / Absolute resource URL.\n */\n #resourceURL(source, baseURL) {\n if (!source) return null;\n const url = new URL(source, baseURL);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Resources must use HTTP(S) URLs\");\n return url.href;\n }\n\n /**\n * 从前进后退缓存恢复时重新加载模块。\n * Reload the module when restored from the back-forward cache.\n * @param {PageTransitionEvent} event 页面显示事件 / Page show event.\n * @returns {void} 无返回值 / No return value.\n */\n #show = event => {\n if (event.persisted) this.start();\n };\n}\n\nnew ModulePage(document).start();\n\nexport { ModulePage };\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 * 模块探测请求选项。\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 {string} [json] BoxJS JSON 来源,将随探测请求头传递 / BoxJS JSON source sent in the probe header.\n * @property {number} [timeout] 超时毫秒数,默认 3500 / Timeout in milliseconds, defaults to 3500.\n */\n\n/**\n * 通过模块 API 的 HEAD 响应检测安装状态和业务版本。\n * Probe installation and business version from the module API HEAD response.\n * @param {string | URL} url 模块 API 地址 / Module API URL.\n * @param {ModuleProbeOptions} [options] 请求选项 / Request options.\n * @returns {Promise<Response>} 原始 HTTP 响应,可直接读取 status 和响应头 / Native HTTP response; read status and headers directly.\n */\nasync function probeModule(url, { fetch: request = globalThis.fetch, json, 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 return await request(url, { method: \"HEAD\", cache: \"no-store\", credentials: \"omit\", signal: controller.signal, headers: json ? { \"X-PreferencePanes-JSON\": json } : undefined });\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 模块 API 地址 / Module API URL.\n * @param {ModuleProbeOptions} [options] 请求选项 / Request options.\n * @returns {Promise<Response | undefined>} 原始响应;被取消时无返回值 / Native response; undefined when cancelled.\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 response = await probeModule(url, { ...options, signal: controller.signal });\n if (controller !== this.#controller) return response;\n const version = response.status === 200 ? response.headers.get(\"X-PreferencePanes-Version\")?.trim() || null : null;\n this.#render(response.status === 200 ? \"installed\" : \"missing\", version);\n return response;\n } catch (error) {\n if (controller !== this.#controller) return;\n if (externalSignal?.aborted) throw error;\n this.#render(\"missing\");\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"}};
1136
+
1137
+ /**
1138
+ * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。
1139
+ * Resolve module resource locations: headers override query parameters and module conventions.
1140
+ * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.
1141
+ * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.
1142
+ * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.
1143
+ */
1144
+ function pageInputs(url, headers = {}) {
1145
+ const match = /^\/settings\/([a-zA-Z0-9_-]+)\/?$/.exec(url.pathname);
1146
+ if (!match) throw new TypeError("Open a concrete module URL");
1147
+ const module = match[1];
1148
+ const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
1149
+ const json = values["x-preferencepanes-json"] ?? url.searchParams.get("json") ?? `/configs/${module}`;
1150
+ const css = values["x-preferencepanes-css"] ?? url.searchParams.get("css") ?? "";
1151
+ if (!json.trim()) throw new TypeError("JSON resource URL is required");
1152
+ return { url: url.href, module, json, css };
1153
+ }
1154
+
1155
+ /**
1156
+ * 返回模块页面及其公共浏览器资源,不处理 API、网络或持久化。
1157
+ * Serve module pages and common browser assets without handling APIs, network access or persistence.
1158
+ * @returns {void} 响应已交给代理宿主 / Response delivered to the proxy host.
1159
+ */
1160
+ function run() {
1161
+ const request = globalThis.$request;
1162
+ let result;
1163
+ try {
1164
+ const url = new URL(request.url);
1165
+ if (/^\/settings\/[a-zA-Z0-9_-]+\/?$/.test(url.pathname)) {
1166
+ if (!["GET", "HEAD"].includes(request.method)) result = response(request, 405, { error: "Method not allowed" });
1167
+ else {
1168
+ const inputs = encodeURIComponent(JSON.stringify(pageInputs(url, request.headers)));
1169
+ result = response(request, 200, assets.page.body.replace("</head>", `<meta name="preference-panes-inputs" content="${inputs}"></head>`), "text/html");
1170
+ }
1171
+ } else {
1172
+ const asset = assets[url.pathname];
1173
+ if (asset) result = ["GET", "HEAD"].includes(request.method) ? response(request, 200, asset.body, asset.type) : response(request, 405, { error: "Method not allowed" });
1174
+ }
1175
+ } catch (error) {
1176
+ console.error(`PreferencePanes Web: ${error.message}`);
1177
+ result = response(request, 500, { error: error.message });
1178
+ }
1179
+ if (!result) done({});
1180
+ else done($app === "Quantumult X" ? result : { response: result });
1181
+ }
1182
+
1183
+ /**
1184
+ * 构造静态资源响应,HEAD 请求不返回正文。
1185
+ * Build a static resource response without a body for HEAD requests.
1186
+ * @param {import("./index.js").SettingsRequest} request 代理请求 / Proxy request.
1187
+ * @param {number} status HTTP 状态 / HTTP status.
1188
+ * @param {unknown} body 响应正文 / Response body.
1189
+ * @param {string} [type] 媒体类型 / Media type.
1190
+ * @returns {import("./index.js").SettingsResponse} 静态资源响应 / Static resource response.
1191
+ */
1192
+ function response(request, status, body, type = "application/json") {
1193
+ return {
1194
+ status,
1195
+ headers: { "Content-Type": `${type}; charset=utf-8`, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },
1196
+ body: request.method === "HEAD" ? "" : type === "application/json" ? JSON.stringify(body) : body,
1197
+ };
1198
+ }
1199
+
1200
+ run();
1201
+
1202
+ })();