@auto-mas/auto-mas-plugin-adapter-hsr 0.0.0-stage → 0.2.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,74 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { runProcess } from '../execution.js';
5
+ import { assertWindowsProgramIdle, configName, existingPath, optionalText, prepareExecutable } from './native.js';
6
+ import { profilesIn } from './profile-options.js';
7
+ const sraProgram = (input) => prepareExecutable(input, 'SRA-cli.exe', ['sra-cli.exe']);
8
+ export function sraConfigRoot() {
9
+ const appData = process.env.APPDATA;
10
+ return join(appData && isAbsolute(appData) ? appData : join(homedir(), '.config'), 'SRA', 'configs');
11
+ }
12
+ export async function sraProfiles(input) {
13
+ if (input.engine !== 'sra' && input.engine !== 'combined')
14
+ return null;
15
+ const command = input.engine === 'combined' ? input.sraCommand : input.command;
16
+ if (!command)
17
+ return [];
18
+ await sraProgram({ command });
19
+ return profilesIn(sraConfigRoot());
20
+ }
21
+ const singleTasks = {
22
+ start: 'StartGameTask', power: 'TrailblazePowerTask', reward: 'ReceiveRewardsTask',
23
+ };
24
+ export async function sraLaunch(config, account, mode = 'full') {
25
+ const { command, installRoot: cwd } = await sraProgram(config);
26
+ const sraProfile = configName(optionalText(account, 'sraProfile') || optionalText(config, 'sraProfile'), 'SRA 原生配置');
27
+ const pathname = await existingPath(join(sraConfigRoot(), `${sraProfile}.json`), 'SRA 原生配置文件');
28
+ if (/["\u0000-\u001f]/u.test(pathname))
29
+ throw new Error('SRA 配置路径含不支持的字符');
30
+ try {
31
+ const value = JSON.parse((await readFile(pathname, 'utf8')).replace(/^\uFEFF/u, ''));
32
+ if (!value || typeof value !== 'object' || Array.isArray(value))
33
+ throw new Error('SRA 配置的根节点必须是对象');
34
+ }
35
+ catch (error) {
36
+ throw new Error('SRA 原生配置无法读取,请在 SRA 中核对档案', { cause: error });
37
+ }
38
+ const run = mode === 'full' ? `run "${pathname}"` : `single ${singleTasks[mode]} --config "${pathname}"`;
39
+ return { command, cwd, sraProfile, args: ['--no-admin', '--inline', run, 'quit'] };
40
+ }
41
+ export function sraObservation(mode = 'full') {
42
+ let reportedCompletion = false;
43
+ let skipped = false;
44
+ let errorOutput;
45
+ return {
46
+ consume(text) {
47
+ const line = text.replace(/\u001b\[[0-9;]*m/gu, '').trim();
48
+ if (mode === 'full' && /\bAll tasks completed\.$/u.test(line))
49
+ reportedCompletion = true;
50
+ if (mode !== 'full' && /(?:任务\s+['"].+['"]\s+已完成。|Task\s+['"].+['"]\s+(?:completed|has been completed)\.|Задача\s+['"].+['"]\s+завершен[ао]?\.)$/iu.test(line)) {
51
+ reportedCompletion = true;
52
+ }
53
+ if (/没有选中的任务|no (?:selected tasks|tasks (?:were )?selected)|нет выбранных задач/iu.test(line))
54
+ skipped = true;
55
+ if (/\[FAIL\]|(?:^|\s)ERROR(?:\s|:|\])|Traceback \(most recent call last\)/u.test(line))
56
+ errorOutput = line.slice(0, 400);
57
+ },
58
+ finish() {
59
+ if (skipped)
60
+ throw new Error('所选 SRA 配置没有启用可运行的任务');
61
+ if (!reportedCompletion)
62
+ throw new Error(`SRA 未报告任务完成${errorOutput ? `:${errorOutput}` : ''}`);
63
+ },
64
+ };
65
+ }
66
+ export async function runSra(script, options, mode = 'full') {
67
+ const launch = await sraLaunch(script.adapterConfig ?? {}, script.accountConfig ?? {}, mode);
68
+ await assertWindowsProgramIdle(launch.command, options.signal);
69
+ const observation = sraObservation(mode);
70
+ await runProcess({ ...script, ...launch, env: { ...script.env, PYTHONIOENCODING: 'utf-8' } }, {
71
+ ...options, log: line => { options.log(line); observation.consume(line); },
72
+ });
73
+ observation.finish();
74
+ }
@@ -0,0 +1,66 @@
1
+ export function generalResultRules(input) {
2
+ const read = (key) => {
3
+ const value = typeof input[key] === 'string' ? input[key].trim() : '';
4
+ if (value.length > 300 || /[\r\n]/u.test(value))
5
+ throw new Error('日志匹配内容必须是 300 字符以内的单行文本');
6
+ return value || undefined;
7
+ };
8
+ const startupText = read('startupText');
9
+ const successText = read('successText');
10
+ const failureText = read('failureText');
11
+ const startupTimeout = startupText ? Number(input.startupTimeout ?? 30) : undefined;
12
+ if (startupTimeout !== undefined && (!Number.isInteger(startupTimeout) || startupTimeout < 1 || startupTimeout > 300)) {
13
+ throw new Error('启动检查时限必须介于 1 至 300 秒');
14
+ }
15
+ return { startupText, startupTimeout, successText, failureText };
16
+ }
17
+ export async function withGeneralResult(script, options, dispatch) {
18
+ const source = script.adapterConfig && typeof script.adapterConfig === 'object'
19
+ ? script.adapterConfig : script;
20
+ const { startupText, startupTimeout, successText, failureText } = generalResultRules(source);
21
+ if (!startupText && !successText && !failureText)
22
+ return dispatch(script, options);
23
+ const monitor = new AbortController();
24
+ let ready = false;
25
+ let success = false;
26
+ let deadline;
27
+ const markReady = () => {
28
+ if (ready || monitor.signal.aborted)
29
+ return;
30
+ ready = true;
31
+ clearTimeout(deadline);
32
+ options.started?.();
33
+ };
34
+ try {
35
+ await dispatch(script, {
36
+ ...options,
37
+ signal: AbortSignal.any([options.signal, monitor.signal]),
38
+ started: () => {
39
+ if (!startupText)
40
+ return markReady();
41
+ if (ready || deadline)
42
+ return;
43
+ deadline = setTimeout(() => monitor.abort(new Error('启动检查超时:未检测到配置的日志文本')), startupTimeout * 1000);
44
+ deadline.unref();
45
+ },
46
+ log(line) {
47
+ options.log(line);
48
+ if (failureText && line.includes(failureText))
49
+ monitor.abort(new Error('匹配到配置的失败日志'));
50
+ if (successText && line.includes(successText))
51
+ success = true;
52
+ if (startupText && line.includes(startupText))
53
+ markReady();
54
+ },
55
+ });
56
+ options.signal.throwIfAborted();
57
+ monitor.signal.throwIfAborted();
58
+ if (startupText && !ready)
59
+ throw new Error('脚本已退出,但未检测到配置的启动日志');
60
+ if (successText && !success)
61
+ throw new Error('脚本已退出,但未检测到配置的成功日志');
62
+ }
63
+ finally {
64
+ clearTimeout(deadline);
65
+ }
66
+ }
@@ -0,0 +1,97 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { adbEnvironment } from '../emulator-managers.js';
4
+ import { readLines, terminateTree } from './process.js';
5
+ export { inspectProject } from './project.js';
6
+ const workerPath = fileURLToPath(new URL('./worker.js', import.meta.url));
7
+ export async function runMaa(input, options) {
8
+ const { signal, log, started, launchProcess } = options;
9
+ signal.throwIfAborted();
10
+ const env = { ...adbEnvironment(input.adbServerPort), ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}) };
11
+ if (launchProcess) {
12
+ await launchProcess({ command: process.execPath, args: [workerPath, '--mas-stdio'], env,
13
+ stdin: JSON.stringify({ type: 'run', input }) }, options);
14
+ return;
15
+ }
16
+ await new Promise((resolve, reject) => {
17
+ const worker = fork(workerPath, [], {
18
+ detached: process.platform !== 'win32',
19
+ env: { ...process.env, ...env },
20
+ execArgv: [],
21
+ windowsHide: true,
22
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
23
+ });
24
+ const processes = new Set();
25
+ let result;
26
+ let workerError;
27
+ let stopTimer;
28
+ let deadline;
29
+ let settled = false;
30
+ function abort() {
31
+ if (worker.connected)
32
+ worker.send({ type: 'stop' }, () => undefined);
33
+ stopTimer = setTimeout(() => {
34
+ log('MaaFramework stop deadline reached. Terminating the worker and its project processes.');
35
+ if (worker.pid)
36
+ void terminateTree(worker.pid);
37
+ for (const pid of processes)
38
+ void terminateTree(pid);
39
+ deadline = setTimeout(() => {
40
+ if (worker.connected)
41
+ worker.disconnect();
42
+ worker.stdout?.destroy();
43
+ worker.stderr?.destroy();
44
+ worker.unref();
45
+ void finish(null, null);
46
+ }, 2_000);
47
+ }, 5_000);
48
+ }
49
+ async function finish(code, exitSignal) {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(stopTimer);
54
+ clearTimeout(deadline);
55
+ signal.removeEventListener('abort', abort);
56
+ await Promise.all([...processes].map(terminateTree));
57
+ if (signal.aborted)
58
+ reject(signal.reason);
59
+ else if (result?.error)
60
+ reject(result.error);
61
+ else if (workerError)
62
+ reject(workerError);
63
+ else if (code === 0 && result)
64
+ resolve();
65
+ else
66
+ reject(new Error(`MaaFramework worker exited before completing (${exitSignal ?? code ?? 'unknown status'}).`));
67
+ }
68
+ readLines(worker.stdout, log);
69
+ readLines(worker.stderr, (line) => log(`[MaaFramework stderr] ${line}`));
70
+ worker.on('message', (message) => {
71
+ if (message.type === 'process-started')
72
+ processes.add(message.pid);
73
+ if (message.type === 'process-exited')
74
+ processes.delete(message.pid);
75
+ if (message.type === 'failed')
76
+ result = { error: new Error(message.error) };
77
+ if (message.type === 'done')
78
+ result = {};
79
+ });
80
+ worker.once('error', (error) => { workerError = error; });
81
+ worker.once('spawn', () => {
82
+ try {
83
+ started?.('MaaFramework Worker 已启动');
84
+ }
85
+ catch (error) {
86
+ workerError = error instanceof Error ? error : new Error(String(error));
87
+ abort();
88
+ }
89
+ });
90
+ worker.once('close', (code, exitSignal) => void finish(code, exitSignal));
91
+ worker.send({ type: 'run', input }, (error) => {
92
+ if (error)
93
+ workerError = error;
94
+ });
95
+ signal.addEventListener('abort', abort, { once: true });
96
+ });
97
+ }
@@ -0,0 +1,34 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
+ export const managedProjectManifest = '.automasc-maafw.json';
4
+ export const projectIdPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/u;
5
+ export function withinProject(root, path) {
6
+ const displacement = relative(root, path);
7
+ return !isAbsolute(displacement) && displacement !== '..' && !displacement.startsWith(`..${sep}`);
8
+ }
9
+ export async function readManagedProject(root) {
10
+ const source = await readFile(join(root, managedProjectManifest), 'utf8').catch(error => {
11
+ if (error.code === 'ENOENT')
12
+ return undefined;
13
+ throw error;
14
+ });
15
+ if (source === undefined)
16
+ return undefined;
17
+ const record = JSON.parse(source);
18
+ if (record?.schema !== 1 || typeof record.id !== 'string' || !projectIdPattern.test(record.id) ||
19
+ typeof record.name !== 'string' || typeof record.label !== 'string' || typeof record.source !== 'string' || !isAbsolute(record.source) ||
20
+ typeof record.current !== 'string' || !Array.isArray(record.revisions) || !record.revisions.some(item => item?.id === record.current) ||
21
+ record.revisions.some(item => !item || typeof item.id !== 'string' || !projectIdPattern.test(item.id) || typeof item.created !== 'string')) {
22
+ throw new Error('MaaFramework 项目记录有误,请检查副本目录');
23
+ }
24
+ return record;
25
+ }
26
+ export async function managedRevisionPath(root, revision) {
27
+ if (!projectIdPattern.test(revision))
28
+ throw new Error('MaaFramework 项目版本标识无效');
29
+ const canonicalRoot = await realpath(root);
30
+ const selected = await realpath(join(root, 'revisions', revision));
31
+ if (!withinProject(canonicalRoot, selected) || selected === canonicalRoot)
32
+ throw new Error('MaaFramework 项目版本目录超出项目范围');
33
+ return selected;
34
+ }
@@ -0,0 +1,80 @@
1
+ import { mkdtemp, realpath, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { runProcess } from '../execution.js';
5
+ import { adbEnvironment } from '../emulator-managers.js';
6
+ import { runMaa } from './index.js';
7
+ import { nativeWorkerSource } from './native-worker-source.js';
8
+ import { bindNodeAgent, readNodeAgentEnvironment } from './node-agent-path.js';
9
+ import { loadProject, planRun } from './project.js';
10
+ const framework = process.platform === 'win32' ? 'MaaFramework.dll' : process.platform === 'darwin' ? 'libMaaFramework.dylib' : 'libMaaFramework.so';
11
+ export async function nativeRuntimePaths(python, libraries) {
12
+ if (!python && !libraries)
13
+ return undefined;
14
+ if (!python || !libraries)
15
+ throw new Error('请一并选择匹配的 Python 解释器与 MaaFramework 原生库目录');
16
+ if (!isAbsolute(python) || !await stat(python).then(item => item.isFile(), () => false))
17
+ throw new Error('请选择有效的原生运行器 Python 可执行文件');
18
+ if (!isAbsolute(libraries))
19
+ throw new Error('请选择 MaaFramework 原生库的绝对目录');
20
+ const path = await realpath(libraries).catch(() => { throw new Error('MaaFramework 原生库目录不存在'); });
21
+ if (!await stat(join(path, framework)).then(item => item.isFile(), () => false))
22
+ throw new Error(`MaaFramework 原生库目录缺少 ${framework}`);
23
+ return { nativePython: python, nativeLibraries: path };
24
+ }
25
+ async function invoke(paths, job, options, adbServerPort) {
26
+ const request = JSON.stringify({ nativeLibraries: paths.nativeLibraries, job });
27
+ let version;
28
+ let failure;
29
+ const args = ['-u', '-X', 'utf8', '-c', nativeWorkerSource];
30
+ const proc = { command: paths.nativePython, args, cwd: job?.directory, env: adbEnvironment(adbServerPort) };
31
+ const execution = { ...options, log(line) {
32
+ if (line.startsWith('MAS_MAA_NATIVE_DONE '))
33
+ version = line.slice('MAS_MAA_NATIVE_DONE '.length);
34
+ else if (line.startsWith('MAS_MAA_NATIVE_ERROR '))
35
+ failure = line.slice('MAS_MAA_NATIVE_ERROR '.length);
36
+ else
37
+ options.log(line);
38
+ } };
39
+ try {
40
+ if (options.launchProcess) {
41
+ await options.launchProcess({ ...proc, stdin: request }, execution);
42
+ }
43
+ else {
44
+ const temp = await mkdtemp(join(tmpdir(), 'masc-maafw-native-'));
45
+ try {
46
+ const path = join(temp, 'request.json');
47
+ await writeFile(path, request, { flag: 'wx', mode: 0o600 });
48
+ await runProcess({ id: 'maafw-native', adapter: 'maafw', name: 'MaaFramework 原生运行器', ...proc, args: [...args, path] }, execution);
49
+ }
50
+ finally {
51
+ await rm(temp, { recursive: true, force: true });
52
+ }
53
+ }
54
+ }
55
+ catch (error) {
56
+ options.signal.throwIfAborted();
57
+ throw new Error(failure || 'MaaFramework 原生运行器异常退出,请检查已安装的 maafw Python 绑定与原生库', { cause: error });
58
+ }
59
+ if (!version)
60
+ throw new Error(failure || 'MaaFramework 原生运行器未返回成功结果');
61
+ return version;
62
+ }
63
+ export async function probeNativeMaa(python, libraries) {
64
+ const paths = (await nativeRuntimePaths(python, libraries));
65
+ const version = await invoke(paths, undefined, { signal: AbortSignal.timeout(15_000), log: () => { } });
66
+ return { version, ...paths };
67
+ }
68
+ export async function runMaaSelected(input, options) {
69
+ const native = await nativeRuntimePaths(input.nativePython, input.nativeLibraries);
70
+ if (!native)
71
+ return runMaa(input, options);
72
+ const project = await loadProject(input.projectPath);
73
+ const plan = planRun(project, input);
74
+ const nodeAgent = input.agentNodeRoot && await readNodeAgentEnvironment(input.agentNodeRoot, project.directory) || undefined;
75
+ const { adbPath, address, windowHandle, agentPython } = input;
76
+ await invoke(native, { ...plan, directory: project.directory, input: { adbPath, address, windowHandle, agentPython },
77
+ agents: plan.agents.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
78
+ pretasks: plan.pretasks.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
79
+ }, options, input.adbServerPort);
80
+ }