@auto-mas/auto-mas-plugin-maa-updates 0.0.0-stage → 0.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.
@@ -0,0 +1,207 @@
1
+ import { open, readdir, realpath, stat } from 'node:fs/promises';
2
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { runProcess } from '../execution.js';
6
+ export const executableField = (label) => ({ key: 'command', label, kind: 'hostpath', required: true });
7
+ export const directoryField = (key, label) => ({ key, label, kind: 'hostpath', directory: true, required: true });
8
+ export const windowsOnly = () => process.platform === 'win32' ? undefined : '此执行器需要 Windows 桌面会话';
9
+ export function optionalText(input, key) {
10
+ const value = input[key];
11
+ if (value === undefined || value === null)
12
+ return '';
13
+ if (typeof value !== 'string' || /[\u0000-\u001f]/u.test(value))
14
+ throw new Error(`${key} 必须是单行文本`);
15
+ return value.trim();
16
+ }
17
+ export function requiredText(input, key, label) {
18
+ const value = optionalText(input, key);
19
+ if (!value)
20
+ throw new Error(`请填写${label}`);
21
+ return value;
22
+ }
23
+ export function configName(value, label) {
24
+ if (!value || value.startsWith('-') || value.endsWith('.') || /[/\\:*?"<>|]/u.test(value)) {
25
+ throw new Error(`${label}必须是配置名称`);
26
+ }
27
+ return value;
28
+ }
29
+ export async function existingPath(path, label, directory = false) {
30
+ if (!isAbsolute(path))
31
+ throw new Error(`${label}必须是绝对路径`);
32
+ const resolved = await realpath(path).catch(error => {
33
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
34
+ throw new Error(`${label}不存在`);
35
+ throw error;
36
+ });
37
+ const info = await stat(resolved);
38
+ if (directory ? !info.isDirectory() : !info.isFile())
39
+ throw new Error(`${label}类型有误`);
40
+ return resolved;
41
+ }
42
+ export async function prepareExecutable(input, label, names) {
43
+ const command = await existingPath(requiredText(input, 'command', label), label);
44
+ if (!names.includes(basename(command).toLowerCase()))
45
+ throw new Error(`请选择 ${names.join(' 或 ')} 文件`);
46
+ return { command, installRoot: dirname(command) };
47
+ }
48
+ export async function assertWindowsProgramIdle(command, signal) {
49
+ signal.throwIfAborted();
50
+ const pidList = await new Promise((resolve, reject) => execFile('powershell.exe', [
51
+ '-NoProfile', '-NonInteractive', '-Command', [
52
+ '$ErrorActionPreference = "Stop"',
53
+ '$name = [System.IO.Path]::GetFileNameWithoutExtension($env:MAS_NATIVE_PROGRAM)',
54
+ 'Get-Process | Where-Object { $_.ProcessName -eq $name -and (!$_.Path -or $_.Path -eq $env:MAS_NATIVE_PROGRAM) } | Select-Object -ExpandProperty Id',
55
+ ].join('\n'),
56
+ ], { env: { ...process.env, MAS_NATIVE_PROGRAM: command }, windowsHide: true, signal, timeout: 8000 }, (error, stdout) => {
57
+ if (error)
58
+ reject(new Error(`无法检查 ${basename(command)} 是否已打开`, { cause: error }));
59
+ else
60
+ resolve(stdout);
61
+ }));
62
+ if (pidList.trim())
63
+ throw new Error(`请先关闭正在运行的 ${basename(command)}`);
64
+ }
65
+ export async function openNativeEditor(command, cwd, close) {
66
+ const unavailable = windowsOnly();
67
+ if (unavailable)
68
+ throw new Error(unavailable);
69
+ await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
70
+ const process = spawn(command, [], { cwd, detached: true, stdio: 'ignore', shell: false });
71
+ if (close)
72
+ process.once('close', close);
73
+ await new Promise((resolve, reject) => {
74
+ process.once('spawn', resolve);
75
+ process.once('error', reject);
76
+ });
77
+ process.unref();
78
+ }
79
+ async function followLogs(spec, consume) {
80
+ const cursors = new Map();
81
+ async function scan(baseline) {
82
+ const entries = await readdir(spec.directory, { withFileTypes: true }).catch(error => {
83
+ if (error.code === 'ENOENT')
84
+ return [];
85
+ throw error;
86
+ });
87
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
88
+ if (!entry.isFile() || !spec.filenames.test(entry.name))
89
+ continue;
90
+ const handle = await open(join(spec.directory, entry.name), 'r').catch(error => {
91
+ if (error.code === 'ENOENT')
92
+ return undefined;
93
+ throw error;
94
+ });
95
+ if (!handle)
96
+ continue;
97
+ try {
98
+ const { dev, ino, size } = await handle.stat();
99
+ const id = `${dev}:${ino}`;
100
+ const previous = cursors.get(entry.name);
101
+ const cursor = previous?.id === id && previous.offset <= size ? previous : {
102
+ id, offset: baseline ? size : 0, decoder: new StringDecoder('utf8'), partial: '',
103
+ };
104
+ cursors.set(entry.name, cursor);
105
+ const buffer = Buffer.allocUnsafe(64 * 1024);
106
+ while (cursor.offset < size) {
107
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, size - cursor.offset), cursor.offset);
108
+ if (!bytesRead)
109
+ break;
110
+ cursor.offset += bytesRead;
111
+ const lines = (cursor.partial + cursor.decoder.write(buffer.subarray(0, bytesRead))).split('\n');
112
+ cursor.partial = (lines.pop() ?? '').slice(-16000);
113
+ for (const line of lines)
114
+ consume(line.replace(/\r$/u, ''));
115
+ }
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ }
122
+ await scan(true);
123
+ return async (final = false) => {
124
+ await scan(false);
125
+ if (final)
126
+ for (const cursor of cursors.values()) {
127
+ const remainder = cursor.partial + cursor.decoder.end();
128
+ if (remainder)
129
+ consume(remainder.replace(/\r$/u, ''));
130
+ }
131
+ };
132
+ }
133
+ export async function runObservedProcess(script, options, files, observation, closeOnCompletion = false) {
134
+ let completedAt;
135
+ const completion = new AbortController();
136
+ const signal = closeOnCompletion ? AbortSignal.any([options.signal, completion.signal]) : options.signal;
137
+ const consume = (line, source) => {
138
+ options.log(line);
139
+ observation.consume(line, source);
140
+ if (observation.complete)
141
+ completedAt ??= Date.now();
142
+ };
143
+ const scan = await followLogs(files, line => consume(line, 'file'));
144
+ let pending;
145
+ let logError;
146
+ const interval = setInterval(() => {
147
+ if (pending || logError)
148
+ return;
149
+ pending = scan().then(() => {
150
+ if (closeOnCompletion && completedAt !== undefined && Date.now() - completedAt >= 1500) {
151
+ completion.abort(new Error('上游任务已结束'));
152
+ }
153
+ }).catch(error => { logError = error; }).finally(() => { pending = undefined; });
154
+ }, 500);
155
+ let processError;
156
+ try {
157
+ await runProcess(script, { ...options, signal, log: line => consume(line, 'process') });
158
+ }
159
+ catch (error) {
160
+ processError = error;
161
+ }
162
+ finally {
163
+ clearInterval(interval);
164
+ await pending;
165
+ }
166
+ options.signal.throwIfAborted();
167
+ if (logError)
168
+ throw logError;
169
+ await scan(true);
170
+ observation.finish(processError === completion.signal.reason ? undefined : processError);
171
+ }
172
+ export function nativeAdapter(builder) {
173
+ return async (script, options) => {
174
+ options.signal.throwIfAborted();
175
+ const launch = await builder(script.adapterConfig ?? {}, script.accountConfig ?? {});
176
+ const { logs, ...command } = launch;
177
+ const processScript = { ...script, ...command, env: { ...script.env, ...command.env } };
178
+ if (!logs)
179
+ return runProcess(processScript, options);
180
+ let success = false;
181
+ let terminal = !logs.terminal;
182
+ let failure;
183
+ return runObservedProcess(processScript, options, logs, {
184
+ consume(line, source) {
185
+ if (source !== 'file')
186
+ return;
187
+ if (logs.success.test(line)) {
188
+ success = true;
189
+ if (logs.successClearsFailure)
190
+ failure = undefined;
191
+ }
192
+ terminal ||= Boolean(logs.terminal?.test(line));
193
+ if (logs.failure?.test(line))
194
+ failure = line.slice(0, 400);
195
+ },
196
+ get complete() { return success && terminal; },
197
+ finish(processError) {
198
+ if (failure)
199
+ throw new Error(failure);
200
+ if (processError)
201
+ throw processError;
202
+ if (!success || !terminal)
203
+ throw new Error('上游日志未报告完成,请查看上游配置与本次运行日志');
204
+ },
205
+ }, logs.closeOnCompletion);
206
+ };
207
+ }
@@ -0,0 +1,38 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ export function profileOption(key, label, source, scope, required = false) {
4
+ return { key, label, kind: 'select', source, sourceBy: scope, required };
5
+ }
6
+ export function scopedProfileOptions(ctx, adapter, name, find) {
7
+ ctx.inject(['mas.ui', 'mas.scripts'], scope => {
8
+ const scripts = scope.get('mas.scripts');
9
+ const ui = scope.get('mas.ui');
10
+ ui.scope(scope, undefined, { [name]: input => {
11
+ if (typeof input.scriptId !== 'string')
12
+ return find(input);
13
+ const script = scripts.get(input.scriptId);
14
+ if (!script || script.adapter !== adapter)
15
+ throw new Error('未找到对应专项托管');
16
+ return find(script.adapterConfig ?? {});
17
+ } });
18
+ });
19
+ }
20
+ export async function profilesIn(directory, extensions = ['.json']) {
21
+ const profiles = new Map();
22
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
23
+ if (error.code === 'ENOENT')
24
+ return [];
25
+ throw error;
26
+ });
27
+ for (const entry of entries) {
28
+ const ext = extname(entry.name);
29
+ if (!entry.isFile() || !extensions.includes(ext))
30
+ continue;
31
+ const name = entry.name.slice(0, -ext.length);
32
+ if (!name.trim() || name !== name.trim() || name.startsWith('-') || name.endsWith('.') || /[\u0000-\u001f/\\:*?"<>|]/u.test(name))
33
+ continue;
34
+ profiles.set(name, (profiles.get(name) ?? 0) + 1);
35
+ }
36
+ return [...profiles].filter(([, count]) => count === 1).sort(([a], [b]) => a.localeCompare(b))
37
+ .map(([name]) => ({ value: name, label: name }));
38
+ }
@@ -0,0 +1,75 @@
1
+ import { runProcess } from './execution.js';
2
+ import { maaLaunch } from './game-plugins/maa.js';
3
+ import { Schema } from './schema.js';
4
+ const Config = Schema.object({
5
+ before: Schema.boolean().default(false).description('明日方舟托管开始前运行 MaaCore 和资源更新。'),
6
+ after: Schema.boolean().default(false).description('明日方舟托管结束后运行 MaaCore 和资源更新。取消的运行会跳过更新。'),
7
+ failurePolicy: Schema.union([
8
+ Schema.const('warn').description('记录警告并继续'),
9
+ Schema.const('fail').description('将本次运行标记为失败'),
10
+ ]).default('warn').role('radio').description('MAA 更新失败或超时时的处理方式。'),
11
+ timeoutSeconds: Schema.natural().min(1).max(1800).default(300).description('每次 MAA 更新的超时秒数。'),
12
+ });
13
+ export function createMaaUpdateFeature(execute = runProcess) {
14
+ return {
15
+ id: 'maa-updates', name: 'MAA 更新', description: '在明日方舟托管前后运行官方 MaaCore 和资源更新。',
16
+ component: { Config, apply(ctx, config) {
17
+ if (!config.before && !config.after)
18
+ return;
19
+ const plugin = new AbortController();
20
+ ctx.effect(() => () => plugin.abort(new Error('MAA 更新插件已停用')));
21
+ ctx.on('mas/script-resource-keys', (script, keys) => {
22
+ if (script.adapter === 'maa')
23
+ keys.add('maa:shared-runtime');
24
+ });
25
+ async function update(script, options, timing) {
26
+ const timeout = AbortSignal.timeout(config.timeoutSeconds * 1000);
27
+ const signal = AbortSignal.any([options.signal, plugin.signal, timeout]);
28
+ const log = (line) => options.log(`[MAA 更新] ${line}`);
29
+ options.report?.('script-update', 'started', `${timing}更新 MaaCore 和资源`);
30
+ log('开始更新 MaaCore 和资源');
31
+ try {
32
+ signal.throwIfAborted();
33
+ const { command, env } = maaLaunch(script.adapterConfig ?? {}, script.accountConfig ?? {});
34
+ // Official update targets the installation. Device profiles only apply to task runs.
35
+ await execute({ ...script, command, env, args: ['update', '--batch'] }, { signal, log });
36
+ signal.throwIfAborted();
37
+ log('更新检查完成');
38
+ options.report?.('script-update', 'completed', `${timing}更新检查完成`);
39
+ }
40
+ catch (error) {
41
+ if (options.signal.aborted) {
42
+ options.report?.('script-update', 'cancelled', `${timing}更新已取消`);
43
+ options.signal.throwIfAborted();
44
+ }
45
+ if (plugin.signal.aborted) {
46
+ log('插件已停用,已取消更新');
47
+ options.report?.('script-update', 'cancelled', `${timing}更新因插件停用而取消`);
48
+ return;
49
+ }
50
+ const detail = timeout.aborted ? `更新超时(${config.timeoutSeconds} 秒)` : error instanceof Error ? error.message : String(error);
51
+ const message = `更新失败:${detail}`;
52
+ log(message);
53
+ options.report?.('script-update', 'failed', `${timing}${message}`);
54
+ if (config.failurePolicy === 'fail')
55
+ throw new Error(`MAA ${message}`, { cause: error });
56
+ }
57
+ }
58
+ if (config.before)
59
+ ctx.on('mas/before-script', (script, options) => {
60
+ if (script.adapter === 'maa')
61
+ return update(script, options, '运行前');
62
+ });
63
+ if (config.after)
64
+ ctx.on('mas/after-script', (script, options, outcome) => {
65
+ if (script.adapter !== 'maa')
66
+ return;
67
+ if (outcome === 'cancelled' || options.signal.aborted) {
68
+ options.report?.('script-update', 'skipped', '运行已取消,跳过运行后更新');
69
+ return;
70
+ }
71
+ return update(script, options, '运行后');
72
+ });
73
+ } },
74
+ };
75
+ }
@@ -0,0 +1 @@
1
+ export const runPhases = ['prepare-game', 'start-script', 'complete-script', 'finish-task'];
@@ -0,0 +1,353 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import Schemastery from 'schemastery';
3
+ export const Schema = Object.assign(Schemastery, {
4
+ path(options = {}) {
5
+ return Schemastery.string().role('path', options);
6
+ },
7
+ });
8
+ function plain(value) {
9
+ if (!value || typeof value !== 'object' || Array.isArray(value))
10
+ return false;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ return prototype === Object.prototype || prototype === null;
13
+ }
14
+ function entries(value) {
15
+ return Object.entries(value).filter(([key]) => key !== '__proto__');
16
+ }
17
+ function own(value, key) {
18
+ return Object.hasOwn(value, key) ? value[key] : undefined;
19
+ }
20
+ export function isSchema(value) {
21
+ if (typeof value !== 'function')
22
+ return false;
23
+ const schema = value;
24
+ return schema[Symbol.for('schemastery')] === true && typeof schema.type === 'string' && plain(schema.meta);
25
+ }
26
+ function encode(value, parents = new Set()) {
27
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
28
+ return value;
29
+ if (typeof value === 'number')
30
+ return Number.isFinite(value) ? value : null;
31
+ if (value instanceof Date)
32
+ return value.toJSON();
33
+ if (value instanceof RegExp)
34
+ return { source: value.source, flags: value.flags };
35
+ if (!(Array.isArray(value) || plain(value)) || parents.has(value))
36
+ return undefined;
37
+ parents.add(value);
38
+ const result = Array.isArray(value)
39
+ ? value.map(item => encode(item, parents) ?? null)
40
+ : Object.fromEntries(entries(value).flatMap(([key, item]) => {
41
+ const encoded = encode(item, parents);
42
+ return encoded === undefined ? [] : [[key, encoded]];
43
+ }));
44
+ parents.delete(value);
45
+ return result;
46
+ }
47
+ function copyInput(value, copies = new WeakMap()) {
48
+ if (!(Array.isArray(value) || plain(value)))
49
+ return value;
50
+ if (copies.has(value))
51
+ return copies.get(value);
52
+ if (Array.isArray(value)) {
53
+ const result = [];
54
+ copies.set(value, result);
55
+ for (const item of value)
56
+ result.push(copyInput(item, copies));
57
+ return result;
58
+ }
59
+ const result = {};
60
+ copies.set(value, result);
61
+ for (const [key, item] of entries(value))
62
+ result[key] = copyInput(item, copies);
63
+ return result;
64
+ }
65
+ function secret(meta) {
66
+ return meta?.role === 'secret' || meta?.role === 'password' || meta?.password === true || meta?.writeOnly === true;
67
+ }
68
+ function privateValue(meta) {
69
+ return meta?.hidden === true || secret(meta);
70
+ }
71
+ function lazyTarget(schema) {
72
+ if (isSchema(schema.inner))
73
+ return schema.inner;
74
+ const target = schema.builder?.();
75
+ if (!isSchema(target))
76
+ throw new TypeError('Schemastery lazy builder must return a schema');
77
+ return new Schema({ ...target, meta: { ...schema.meta, ...target.meta } });
78
+ }
79
+ export function describeSchema(schema) {
80
+ const visible = new WeakMap();
81
+ const protectedNodes = new WeakMap();
82
+ const defaults = [];
83
+ let nextId = 0;
84
+ function describe(source, inherited = false) {
85
+ const isPrivate = inherited || privateValue(source.meta);
86
+ const seen = isPrivate ? protectedNodes : visible;
87
+ const previous = seen.get(source);
88
+ if (previous !== undefined)
89
+ return { type: 'ref', ref: previous };
90
+ const id = nextId++;
91
+ seen.set(source, id);
92
+ const effective = source.type === 'lazy' ? lazyTarget(source) : source;
93
+ const meta = encode(effective.meta);
94
+ const protectsChildren = isPrivate || privateValue(meta);
95
+ const node = { type: effective.type, id };
96
+ if (protectsChildren) {
97
+ delete meta.default;
98
+ delete meta.extra;
99
+ }
100
+ if (isPrivate && !privateValue(meta))
101
+ meta.hidden = true;
102
+ if (Object.keys(meta).length)
103
+ node.meta = meta;
104
+ if (Object.hasOwn(meta, 'default'))
105
+ defaults.push(node);
106
+ if (effective.inner && isSchema(effective.inner))
107
+ node.inner = describe(effective.inner, protectsChildren);
108
+ if (effective.sKey)
109
+ node.key = describe(effective.sKey, protectsChildren);
110
+ if (effective.list)
111
+ node.list = effective.list.map(item => describe(item, protectsChildren));
112
+ if (effective.dict)
113
+ node.dict = Object.fromEntries(Object.entries(effective.dict)
114
+ .filter(([key]) => key !== '__proto__').map(([key, item]) => [key, describe(item, protectsChildren)]));
115
+ if (effective.bits)
116
+ node.bits = Object.fromEntries(Object.entries(effective.bits).filter(([key]) => key !== '__proto__'));
117
+ if (effective.type === 'is' && effective.constructor)
118
+ node.className = typeof effective.constructor === 'string' ? effective.constructor : effective.constructor.name;
119
+ if (effective.type === 'transform' && effective.preserve !== undefined)
120
+ node.preserve = effective.preserve;
121
+ const value = protectsChildren ? undefined : encode(effective.value);
122
+ if (value !== undefined)
123
+ node.value = value;
124
+ return node;
125
+ }
126
+ const root = describe(schema);
127
+ const refs = indexNodes(root);
128
+ for (const node of defaults) {
129
+ const value = expose([node], node.meta.default, refs);
130
+ if (value === undefined)
131
+ delete node.meta.default;
132
+ else
133
+ node.meta.default = value;
134
+ }
135
+ return root;
136
+ }
137
+ function indexNodes(root) {
138
+ const refs = new Map();
139
+ const walk = (node) => {
140
+ if (!node || node.type === 'ref')
141
+ return;
142
+ if (node.id !== undefined)
143
+ refs.set(node.id, node);
144
+ walk(node.inner);
145
+ walk(node.key);
146
+ node.list?.forEach(walk);
147
+ Object.values(node.dict ?? {}).forEach(walk);
148
+ };
149
+ walk(root);
150
+ return refs;
151
+ }
152
+ function fits(node, value, refs, visited = new Set()) {
153
+ if (value == null || visited.has(node))
154
+ return true;
155
+ visited.add(node);
156
+ if (node.type === 'ref' && node.ref !== undefined) {
157
+ const target = refs.get(node.ref);
158
+ return !target || fits(target, value, refs, visited);
159
+ }
160
+ if (node.type === 'const')
161
+ return !Object.hasOwn(node, 'value') || isDeepStrictEqual(node.value, value);
162
+ if (node.type === 'string' || node.type === 'number' || node.type === 'boolean')
163
+ return typeof value === node.type;
164
+ if (node.type === 'array' || node.type === 'tuple')
165
+ return Array.isArray(value);
166
+ if (node.type === 'object' || node.type === 'dict') {
167
+ if (!plain(value))
168
+ return false;
169
+ return Object.entries(node.dict ?? {}).every(([key, child]) => {
170
+ const field = child.type === 'ref' && child.ref !== undefined ? refs.get(child.ref) : child;
171
+ return field?.type !== 'const' || fits(field, own(value, key), refs, new Set(visited));
172
+ });
173
+ }
174
+ if (node.type === 'transform' && node.inner)
175
+ return fits(node.inner, value, refs, visited);
176
+ if (node.type === 'intersect')
177
+ return node.list?.every(item => fits(item, value, refs, new Set(visited))) ?? true;
178
+ if (node.type === 'union')
179
+ return node.list?.some(item => fits(item, value, refs, new Set(visited))) ?? true;
180
+ return true;
181
+ }
182
+ function expand(input, value, refs) {
183
+ const seen = new Set();
184
+ function visit(node) {
185
+ if (!node || seen.has(node))
186
+ return;
187
+ seen.add(node);
188
+ if (node.type === 'ref')
189
+ visit(node.ref === undefined ? undefined : refs.get(node.ref));
190
+ if (node.type === 'transform')
191
+ visit(node.inner);
192
+ if (node.type === 'intersect')
193
+ node.list?.forEach(visit);
194
+ if (node.type === 'union' && node.list) {
195
+ const matching = node.list.filter(branch => fits(branch, value, refs));
196
+ const branches = matching.length ? matching : node.list;
197
+ branches.forEach(visit);
198
+ }
199
+ }
200
+ input.forEach(visit);
201
+ return [...seen];
202
+ }
203
+ function at(nodes, key) {
204
+ return nodes.flatMap(node => {
205
+ let child;
206
+ if (typeof key === 'number')
207
+ child = node.type === 'array' ? node.inner : node.type === 'tuple' ? node.list?.[key] : undefined;
208
+ else if (node.type === 'dict')
209
+ child = node.inner;
210
+ else if (node.type === 'object' && Object.hasOwn(node.dict ?? {}, key))
211
+ child = node.dict?.[key];
212
+ return child ? [child] : [];
213
+ });
214
+ }
215
+ function hidesKeys(node, refs) {
216
+ return node.type === 'dict' && node.key && expand([node.key], undefined, refs).some(key => privateValue(key.meta));
217
+ }
218
+ function locked(node, refs) {
219
+ return node.meta?.hidden === true || node.meta?.disabled === true || node.meta?.readonly === true || hidesKeys(node, refs);
220
+ }
221
+ function expose(input, value, refs) {
222
+ const nodes = expand(input, value, refs);
223
+ if (nodes.some(node => privateValue(node.meta) || hidesKeys(node, refs)))
224
+ return undefined;
225
+ if (Array.isArray(value))
226
+ return value.map((item, key) => expose(at(nodes, key), item, refs) ?? null);
227
+ if (!plain(value))
228
+ return encode(value);
229
+ const typed = nodes.some(node => node.type === 'object');
230
+ return Object.fromEntries(entries(value).flatMap(([key, item]) => {
231
+ const rules = at(nodes, key);
232
+ if (typed && !rules.length)
233
+ return [];
234
+ const visible = expose(rules, item, refs);
235
+ return visible === undefined ? [] : [[key, visible]];
236
+ }));
237
+ }
238
+ export function publicConfig(node, value) {
239
+ return expose([node], value, indexNodes(node));
240
+ }
241
+ function rowSources(before, after, prior, draft, refs) {
242
+ const oldRows = prior.map((value, index) => {
243
+ const rules = at(before, index);
244
+ return { value, visible: expose(rules, value, refs) };
245
+ });
246
+ if (oldRows.every(row => isDeepStrictEqual(row.visible, row.value)))
247
+ return prior;
248
+ const visibleDraft = draft.map((item, index) => expose(at(after, index), item, refs));
249
+ if (oldRows.length === draft.length && oldRows.every((row, index) => isDeepStrictEqual(row.visible, visibleDraft[index])))
250
+ return prior;
251
+ const signature = (value) => JSON.stringify(value, (_, item) => {
252
+ if (!plain(item))
253
+ return item;
254
+ return Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]]));
255
+ });
256
+ const positions = new Map();
257
+ oldRows.forEach((row, index) => {
258
+ const key = signature(row.visible);
259
+ positions.set(key, positions.has(key) ? null : index);
260
+ });
261
+ const matched = new Set();
262
+ const sources = visibleDraft.map(value => {
263
+ const index = positions.get(signature(value));
264
+ if (typeof index === 'number' && !matched.has(index)) {
265
+ matched.add(index);
266
+ return oldRows[index].value;
267
+ }
268
+ return undefined;
269
+ });
270
+ if (sources.includes(undefined) && oldRows.some((row, index) => !matched.has(index) && !isDeepStrictEqual(row.visible, row.value))) {
271
+ throw new TypeError('无法对应包含密钥或隐藏值的配置行。请分开保存删除和新增操作。');
272
+ }
273
+ return sources;
274
+ }
275
+ function merge(previousSchemas, draftSchemas, prior, draft, refs) {
276
+ const before = expand(previousSchemas, prior, refs);
277
+ let sample = draft ?? prior;
278
+ if (plain(draft)) {
279
+ const previous = plain(prior) ? prior : {};
280
+ const candidate = { ...previous, ...draft };
281
+ for (const [key] of entries(draft)) {
282
+ const value = own(previous, key);
283
+ if (expand(at(before, key), value, refs).some(node => locked(node, refs))) {
284
+ if (value === undefined)
285
+ delete candidate[key];
286
+ else
287
+ candidate[key] = value;
288
+ }
289
+ }
290
+ sample = candidate;
291
+ }
292
+ const after = expand(draftSchemas, sample, refs);
293
+ if (after.some(node => locked(node, refs)))
294
+ return copyInput(prior);
295
+ if (after.some(node => secret(node.meta))) {
296
+ return draft == null || typeof draft === 'string' && !draft.trim() ? copyInput(prior) : copyInput(draft);
297
+ }
298
+ if (draft === undefined && before.some(node => privateValue(node.meta)))
299
+ return undefined;
300
+ if (Array.isArray(draft)) {
301
+ const previous = Array.isArray(prior) ? prior : [];
302
+ const sources = before.some(node => node.type === 'array') ? rowSources(before, after, previous, draft, refs) : previous;
303
+ return draft.map((item, key) => merge(at(before, key), at(after, key), sources[key], item, refs));
304
+ }
305
+ const previous = plain(prior) ? prior : {};
306
+ if (plain(draft) || draft === undefined && plain(prior)) {
307
+ const next = plain(draft) ? draft : {};
308
+ const keys = new Set(entries(next).map(([key]) => key));
309
+ for (const [key] of entries(previous)) {
310
+ if (draft === undefined || after.some(node => node.type === 'object' && Object.hasOwn(node.dict ?? {}, key)))
311
+ keys.add(key);
312
+ }
313
+ const result = Object.fromEntries([...keys].flatMap(key => {
314
+ const value = merge(at(before, key), at(after, key), own(previous, key), own(next, key), refs);
315
+ return value === undefined ? [] : [[key, value]];
316
+ }));
317
+ return draft === undefined && !Object.keys(result).length ? undefined : result;
318
+ }
319
+ return copyInput(draft);
320
+ }
321
+ export function mergeConfig(node, prior, draft) {
322
+ return merge([node], [node], prior, draft, indexNodes(node));
323
+ }
324
+ export function parseConfig(schema, value) {
325
+ if (!isSchema(schema))
326
+ throw new TypeError('Configuration schema must be a Schemastery schema');
327
+ const validate = schema['~standard'].validate;
328
+ let result;
329
+ try {
330
+ result = validate(copyInput(value));
331
+ }
332
+ catch (error) {
333
+ if ([...indexNodes(describeSchema(schema)).values()].some(node => privateValue(node.meta)))
334
+ throw new TypeError('Invalid configuration value');
335
+ throw error;
336
+ }
337
+ if (result instanceof Promise)
338
+ throw new TypeError('Schemastery configuration validation must be synchronous');
339
+ if (!result.issues)
340
+ return result.value;
341
+ // Upstream messages can quote the input or the contents of an entire union.
342
+ const graph = indexNodes(describeSchema(schema));
343
+ const nodes = [...graph.values()];
344
+ const protectedSchema = nodes.some(node => privateValue(node.meta));
345
+ const privateKeys = nodes.some(node => hidesKeys(node, graph));
346
+ const messages = result.issues.map(issue => {
347
+ if (!protectedSchema)
348
+ return issue.message;
349
+ const path = !privateKeys && issue.path?.map(segment => typeof segment === 'object' ? segment.key : segment).join('.');
350
+ return path ? `${path}: invalid configuration value` : 'Invalid configuration value';
351
+ });
352
+ throw new TypeError(messages.join('\n'));
353
+ }