openprototype 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -115
- package/README.zh-CN.md +244 -0
- package/bin/cli.js +153 -6
- package/lib/config.js +6 -0
- package/lib/service-manager.js +452 -0
- package/package.json +3 -1
- package/product/demo/pc/index.html +180 -9
- package/product/demo/pc/nav-tree.json +4 -4
- package/proto-kit.config.json +3 -0
- package/runtime/server.js +81 -13
- package/runtime/service-runner.js +138 -0
- package/runtime/shared/common/prd-panel.js +55 -5
- package/runtime/shell/agent-panel.css +65 -0
- package/runtime/shell/agent-panel.js +62 -20
- package/scripts/check/service-smoke-test.js +172 -0
- package/scripts/check/sync-nav-tree.js +29 -1
- package/scripts/postinstall.js +52 -0
- package/templates/product-shell/index.html +180 -9
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const http = require('http');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const { spawnSync } = require('child_process');
|
|
9
|
+
const { loadConfig, CONFIG_FILENAME } = require('./config');
|
|
10
|
+
|
|
11
|
+
const PKG_ROOT = path.resolve(__dirname, '..');
|
|
12
|
+
const RUNNER_SOURCE = path.join(PKG_ROOT, 'runtime', 'service-runner.js');
|
|
13
|
+
const SERVICE_PREFIX = 'io.openprototype.project';
|
|
14
|
+
|
|
15
|
+
function canonicalProjectRoot(projectRoot) {
|
|
16
|
+
const resolved = path.resolve(projectRoot || process.cwd());
|
|
17
|
+
try { return fs.realpathSync(resolved); } catch { return resolved; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function projectServiceId(projectRoot, platform) {
|
|
21
|
+
const canonical = canonicalProjectRoot(projectRoot);
|
|
22
|
+
const input = (platform || process.platform) === 'win32' ? canonical.toLowerCase() : canonical;
|
|
23
|
+
return crypto.createHash('sha256').update(input).digest('hex').slice(0, 16);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isSupportedPlatform(platform) {
|
|
27
|
+
return (platform || process.platform) === 'darwin' || (platform || process.platform) === 'win32';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isLoopbackHost(host) {
|
|
31
|
+
const value = String(host || '').toLowerCase();
|
|
32
|
+
return value === 'localhost' || value === '::1' || value === '0:0:0:0:0:0:0:1' || /^127(?:\.\d{1,3}){3}$/.test(value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function serviceBaseDir(platform) {
|
|
36
|
+
if ((platform || process.platform) === 'darwin') {
|
|
37
|
+
return path.join(os.homedir(), 'Library', 'Application Support', 'openprototype');
|
|
38
|
+
}
|
|
39
|
+
if ((platform || process.platform) === 'win32') {
|
|
40
|
+
return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'OpenPrototype');
|
|
41
|
+
}
|
|
42
|
+
return path.join(os.homedir(), '.openprototype');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function servicePaths(projectRoot, platform) {
|
|
46
|
+
const actualPlatform = platform || process.platform;
|
|
47
|
+
const serviceId = projectServiceId(projectRoot, actualPlatform);
|
|
48
|
+
const baseDir = serviceBaseDir(actualPlatform);
|
|
49
|
+
const serviceDir = path.join(baseDir, 'services', serviceId);
|
|
50
|
+
const label = `${SERVICE_PREFIX}.${serviceId}`;
|
|
51
|
+
return {
|
|
52
|
+
serviceId,
|
|
53
|
+
baseDir,
|
|
54
|
+
serviceDir,
|
|
55
|
+
runnerPath: path.join(serviceDir, 'service-runner.js'),
|
|
56
|
+
manifestPath: path.join(serviceDir, 'manifest.json'),
|
|
57
|
+
logPath: path.join(baseDir, 'logs', `${serviceId}.log`),
|
|
58
|
+
label,
|
|
59
|
+
taskName: `OpenPrototype-${serviceId}`,
|
|
60
|
+
plistPath: path.join(os.homedir(), 'Library', 'LaunchAgents', `${label}.plist`)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function packageVersion() {
|
|
65
|
+
try { return JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8')).version || 'unknown'; }
|
|
66
|
+
catch { return 'unknown'; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function projectContext(projectRoot) {
|
|
70
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
71
|
+
const config = loadConfig(root);
|
|
72
|
+
if (!config.hasConfigFile) throw new Error(`当前项目没有 ${CONFIG_FILENAME},请先运行 openprototype init`);
|
|
73
|
+
const paths = servicePaths(root);
|
|
74
|
+
return {
|
|
75
|
+
root,
|
|
76
|
+
config,
|
|
77
|
+
paths,
|
|
78
|
+
manifest: {
|
|
79
|
+
schemaVersion: 1,
|
|
80
|
+
serviceId: paths.serviceId,
|
|
81
|
+
platform: process.platform,
|
|
82
|
+
projectRoot: root,
|
|
83
|
+
configPath: config.configFile,
|
|
84
|
+
packageRoot: PKG_ROOT,
|
|
85
|
+
packageVersion: packageVersion(),
|
|
86
|
+
serverPath: path.join(PKG_ROOT, 'runtime', 'server.js'),
|
|
87
|
+
nodePath: process.execPath,
|
|
88
|
+
port: config.port,
|
|
89
|
+
host: config.host,
|
|
90
|
+
logPath: paths.logPath,
|
|
91
|
+
label: paths.label,
|
|
92
|
+
taskName: paths.taskName,
|
|
93
|
+
installedAt: new Date().toISOString()
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function readManifest(manifestPath) {
|
|
99
|
+
try { return JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { return null; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function writeJson(file, data) {
|
|
103
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
104
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function xmlEscape(value) {
|
|
108
|
+
return String(value)
|
|
109
|
+
.replace(/&/g, '&')
|
|
110
|
+
.replace(/</g, '<')
|
|
111
|
+
.replace(/>/g, '>')
|
|
112
|
+
.replace(/"/g, '"')
|
|
113
|
+
.replace(/'/g, ''');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function commandResult(command, args, options) {
|
|
117
|
+
return spawnSync(command, args, Object.assign({ encoding: 'utf8', windowsHide: true }, options));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function commandError(result, fallback) {
|
|
121
|
+
return String((result && (result.stderr || result.stdout)) || fallback || '系统命令执行失败').trim();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function launchDomain() {
|
|
125
|
+
return `gui/${typeof process.getuid === 'function' ? process.getuid() : ''}`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function macPlist(manifest, paths) {
|
|
129
|
+
const args = [manifest.nodePath, paths.runnerPath, '--manifest', paths.manifestPath]
|
|
130
|
+
.map((item) => ` <string>${xmlEscape(item)}</string>`).join('\n');
|
|
131
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
132
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
133
|
+
<plist version="1.0">
|
|
134
|
+
<dict>
|
|
135
|
+
<key>Label</key><string>${xmlEscape(paths.label)}</string>
|
|
136
|
+
<key>ProgramArguments</key>
|
|
137
|
+
<array>
|
|
138
|
+
${args}
|
|
139
|
+
</array>
|
|
140
|
+
<key>WorkingDirectory</key><string>${xmlEscape(manifest.projectRoot)}</string>
|
|
141
|
+
<key>RunAtLoad</key><true/>
|
|
142
|
+
<key>KeepAlive</key>
|
|
143
|
+
<dict><key>SuccessfulExit</key><false/></dict>
|
|
144
|
+
<key>ProcessType</key><string>Background</string>
|
|
145
|
+
<key>ThrottleInterval</key><integer>10</integer>
|
|
146
|
+
<key>StandardOutPath</key><string>${xmlEscape(manifest.logPath)}</string>
|
|
147
|
+
<key>StandardErrorPath</key><string>${xmlEscape(manifest.logPath)}</string>
|
|
148
|
+
</dict>
|
|
149
|
+
</plist>
|
|
150
|
+
`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function windowsAccount() {
|
|
154
|
+
const result = commandResult('whoami.exe', []);
|
|
155
|
+
if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
|
|
156
|
+
const domain = process.env.USERDOMAIN;
|
|
157
|
+
const user = process.env.USERNAME;
|
|
158
|
+
return domain && user ? `${domain}\\${user}` : user;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function quoteWindowsArg(value) {
|
|
162
|
+
const input = String(value);
|
|
163
|
+
return `"${input.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, '$1$1')}"`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function windowsTaskXml(manifest, paths) {
|
|
167
|
+
const account = windowsAccount();
|
|
168
|
+
const argumentsText = [paths.runnerPath, '--manifest', paths.manifestPath].map(quoteWindowsArg).join(' ');
|
|
169
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
170
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
171
|
+
<RegistrationInfo><Description>openprototype project service</Description></RegistrationInfo>
|
|
172
|
+
<Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xmlEscape(account)}</UserId></LogonTrigger></Triggers>
|
|
173
|
+
<Principals><Principal id="Author"><UserId>${xmlEscape(account)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
|
|
174
|
+
<Settings>
|
|
175
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
176
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
177
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
178
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
179
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
180
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
181
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
182
|
+
<Enabled>true</Enabled>
|
|
183
|
+
<Hidden>false</Hidden>
|
|
184
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
185
|
+
<Priority>7</Priority>
|
|
186
|
+
<RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure>
|
|
187
|
+
</Settings>
|
|
188
|
+
<Actions Context="Author">
|
|
189
|
+
<Exec><Command>${xmlEscape(manifest.nodePath)}</Command><Arguments>${xmlEscape(argumentsText)}</Arguments><WorkingDirectory>${xmlEscape(manifest.projectRoot)}</WorkingDirectory></Exec>
|
|
190
|
+
</Actions>
|
|
191
|
+
</Task>
|
|
192
|
+
`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function healthHost(host) {
|
|
196
|
+
return String(host || '').includes(':') ? '::1' : '127.0.0.1';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function inspectHealth(port, host, timeoutMs) {
|
|
200
|
+
return new Promise((resolve) => {
|
|
201
|
+
let connected = false;
|
|
202
|
+
const req = http.request({
|
|
203
|
+
hostname: healthHost(host),
|
|
204
|
+
port,
|
|
205
|
+
path: '/api/health',
|
|
206
|
+
method: 'GET',
|
|
207
|
+
timeout: timeoutMs || 800
|
|
208
|
+
}, (res) => {
|
|
209
|
+
let body = '';
|
|
210
|
+
res.setEncoding('utf8');
|
|
211
|
+
res.on('data', (chunk) => { body += chunk; });
|
|
212
|
+
res.on('end', () => {
|
|
213
|
+
try {
|
|
214
|
+
resolve({ occupied: true, health: res.statusCode === 200 ? JSON.parse(body) : null, statusCode: res.statusCode });
|
|
215
|
+
} catch {
|
|
216
|
+
resolve({ occupied: true, health: null, statusCode: res.statusCode });
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
req.on('socket', (socket) => socket.once('connect', () => { connected = true; }));
|
|
221
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
222
|
+
req.on('error', () => resolve({ occupied: connected, health: null, statusCode: null }));
|
|
223
|
+
req.end();
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function waitForHealth(manifest, timeoutMs) {
|
|
228
|
+
const deadline = Date.now() + (timeoutMs || 10000);
|
|
229
|
+
while (Date.now() < deadline) {
|
|
230
|
+
const probe = await inspectHealth(manifest.port, manifest.host, 500);
|
|
231
|
+
if (probe.health && probe.health.serviceId === manifest.serviceId) return probe.health;
|
|
232
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function macStop(paths) {
|
|
238
|
+
commandResult('launchctl', ['bootout', `${launchDomain()}/${paths.label}`]);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function macStart(paths) {
|
|
242
|
+
let result = commandResult('launchctl', ['bootstrap', launchDomain(), paths.plistPath]);
|
|
243
|
+
if (result.status !== 0 && !/already loaded|service is already loaded/i.test(commandError(result))) {
|
|
244
|
+
result = commandResult('launchctl', ['load', '-w', paths.plistPath]);
|
|
245
|
+
if (result.status !== 0 && !/already loaded/i.test(commandError(result))) {
|
|
246
|
+
throw new Error(commandError(result, '无法加载 macOS LaunchAgent'));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
commandResult('launchctl', ['kickstart', '-k', `${launchDomain()}/${paths.label}`]);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function windowsStop(paths) {
|
|
253
|
+
commandResult('schtasks.exe', ['/End', '/TN', paths.taskName]);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function windowsStart(paths) {
|
|
257
|
+
const result = commandResult('schtasks.exe', ['/Run', '/TN', paths.taskName]);
|
|
258
|
+
if (result.status !== 0) throw new Error(commandError(result, '无法启动 Windows 计划任务'));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function stopPlatformService(paths, platform) {
|
|
262
|
+
if (platform === 'darwin') macStop(paths);
|
|
263
|
+
else if (platform === 'win32') windowsStop(paths);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function startPlatformService(paths, platform) {
|
|
267
|
+
if (platform === 'darwin') macStart(paths);
|
|
268
|
+
else if (platform === 'win32') windowsStart(paths);
|
|
269
|
+
else throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function registerPlatformService(manifest, paths, platform) {
|
|
273
|
+
if (platform === 'darwin') {
|
|
274
|
+
fs.mkdirSync(path.dirname(paths.plistPath), { recursive: true });
|
|
275
|
+
fs.writeFileSync(paths.plistPath, macPlist(manifest, paths));
|
|
276
|
+
macStart(paths);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (platform === 'win32') {
|
|
280
|
+
const xmlPath = path.join(paths.serviceDir, 'task.xml');
|
|
281
|
+
fs.writeFileSync(xmlPath, '\ufeff' + windowsTaskXml(manifest, paths), 'utf16le');
|
|
282
|
+
const result = commandResult('schtasks.exe', ['/Create', '/TN', paths.taskName, '/XML', xmlPath, '/F']);
|
|
283
|
+
try { fs.unlinkSync(xmlPath); } catch {}
|
|
284
|
+
if (result.status !== 0) throw new Error(commandError(result, '无法注册 Windows 计划任务'));
|
|
285
|
+
windowsStart(paths);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function unregisterPlatformService(paths, platform) {
|
|
292
|
+
stopPlatformService(paths, platform);
|
|
293
|
+
if (platform === 'darwin') {
|
|
294
|
+
try { fs.unlinkSync(paths.plistPath); } catch {}
|
|
295
|
+
} else if (platform === 'win32') {
|
|
296
|
+
commandResult('schtasks.exe', ['/Delete', '/TN', paths.taskName, '/F']);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function installService(options) {
|
|
301
|
+
const opts = options || {};
|
|
302
|
+
if (!isSupportedPlatform()) throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
303
|
+
const context = projectContext(opts.projectRoot);
|
|
304
|
+
const { config, manifest, paths } = context;
|
|
305
|
+
if (config.service && config.service.autoInstall === false && !opts.explicit) {
|
|
306
|
+
return { skipped: true, reason: 'service.autoInstall=false', serviceId: paths.serviceId };
|
|
307
|
+
}
|
|
308
|
+
if (!isLoopbackHost(config.host) && !opts.allowLan) {
|
|
309
|
+
throw new Error(`当前 host=${config.host} 会长期暴露到局域网;如确认需要,请使用 service install --allow-lan`);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const probe = await inspectHealth(config.port, config.host, 1000);
|
|
313
|
+
if (probe.occupied && (!probe.health || probe.health.serviceId !== paths.serviceId)) {
|
|
314
|
+
throw new Error(`端口 ${config.port} 已被${probe.health && probe.health.serviceId ? '另一个 openprototype 项目' : '其他进程'}占用`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
stopPlatformService(paths, process.platform);
|
|
318
|
+
fs.mkdirSync(paths.serviceDir, { recursive: true });
|
|
319
|
+
fs.mkdirSync(path.dirname(paths.logPath), { recursive: true });
|
|
320
|
+
fs.copyFileSync(RUNNER_SOURCE, paths.runnerPath);
|
|
321
|
+
try { fs.chmodSync(paths.runnerPath, 0o700); } catch {}
|
|
322
|
+
writeJson(paths.manifestPath, manifest);
|
|
323
|
+
registerPlatformService(manifest, paths, process.platform);
|
|
324
|
+
|
|
325
|
+
const health = await waitForHealth(manifest, 10000);
|
|
326
|
+
if (!health) throw new Error(`服务已注册,但未能在 10 秒内通过健康检查;请查看 ${paths.logPath}`);
|
|
327
|
+
return { skipped: false, registered: true, running: true, health, manifest, paths };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function registrationExists(paths, platform) {
|
|
331
|
+
if (platform === 'darwin') return fs.existsSync(paths.plistPath);
|
|
332
|
+
if (platform === 'win32') return commandResult('schtasks.exe', ['/Query', '/TN', paths.taskName]).status === 0;
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async function serviceStatus(projectRoot) {
|
|
337
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
338
|
+
const paths = servicePaths(root);
|
|
339
|
+
const manifest = readManifest(paths.manifestPath);
|
|
340
|
+
const supported = isSupportedPlatform();
|
|
341
|
+
const registered = supported && registrationExists(paths, process.platform);
|
|
342
|
+
const config = loadConfig(root);
|
|
343
|
+
const port = manifest ? manifest.port : config.port;
|
|
344
|
+
const host = manifest ? manifest.host : config.host;
|
|
345
|
+
const probe = port ? await inspectHealth(port, host, 800) : { occupied: false, health: null };
|
|
346
|
+
const ownsPort = !!(probe.health && probe.health.serviceId === paths.serviceId);
|
|
347
|
+
const stale = !!(manifest && (!fs.existsSync(manifest.projectRoot) || !fs.existsSync(manifest.serverPath) || !fs.existsSync(manifest.nodePath)));
|
|
348
|
+
const configDrift = !!(manifest && (manifest.port !== config.port || manifest.host !== config.host));
|
|
349
|
+
const installedVersion = packageVersion();
|
|
350
|
+
const runtimeVersion = ownsPort ? probe.health.version : (manifest && manifest.packageVersion);
|
|
351
|
+
const versionDrift = !!(manifest && runtimeVersion && runtimeVersion !== installedVersion);
|
|
352
|
+
const nodeDrift = !!(manifest && manifest.nodePath !== process.execPath);
|
|
353
|
+
let state = 'unregistered';
|
|
354
|
+
if (ownsPort) state = 'running';
|
|
355
|
+
else if (probe.occupied) state = 'port-conflict';
|
|
356
|
+
else if (stale) state = 'stale';
|
|
357
|
+
else if (registered) state = 'stopped';
|
|
358
|
+
return {
|
|
359
|
+
supported,
|
|
360
|
+
platform: process.platform,
|
|
361
|
+
serviceId: paths.serviceId,
|
|
362
|
+
state,
|
|
363
|
+
registered,
|
|
364
|
+
running: ownsPort,
|
|
365
|
+
stale,
|
|
366
|
+
port,
|
|
367
|
+
host,
|
|
368
|
+
pid: ownsPort ? probe.health.pid : null,
|
|
369
|
+
version: runtimeVersion,
|
|
370
|
+
installedVersion,
|
|
371
|
+
configDrift,
|
|
372
|
+
versionDrift,
|
|
373
|
+
nodeDrift,
|
|
374
|
+
startedAt: ownsPort ? probe.health.startedAt : null,
|
|
375
|
+
logPath: paths.logPath,
|
|
376
|
+
projectRoot: root,
|
|
377
|
+
manifestPath: paths.manifestPath
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async function startService(projectRoot) {
|
|
382
|
+
if (!isSupportedPlatform()) throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
383
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
384
|
+
const paths = servicePaths(root);
|
|
385
|
+
const manifest = readManifest(paths.manifestPath);
|
|
386
|
+
if (!manifest || !registrationExists(paths, process.platform)) throw new Error('服务尚未安装,请先运行 openprototype service install');
|
|
387
|
+
const current = await serviceStatus(root);
|
|
388
|
+
if (current.running) return current;
|
|
389
|
+
startPlatformService(paths, process.platform);
|
|
390
|
+
const health = await waitForHealth(manifest, 10000);
|
|
391
|
+
if (!health) throw new Error(`服务未能通过健康检查,请查看 ${paths.logPath}`);
|
|
392
|
+
return serviceStatus(root);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function stopService(projectRoot) {
|
|
396
|
+
if (!isSupportedPlatform()) throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
397
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
398
|
+
const paths = servicePaths(root);
|
|
399
|
+
stopPlatformService(paths, process.platform);
|
|
400
|
+
return { serviceId: paths.serviceId, stopped: true };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function uninstallService(projectRoot) {
|
|
404
|
+
if (!isSupportedPlatform()) throw new Error('常驻服务目前仅支持 macOS 和 Windows');
|
|
405
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
406
|
+
const paths = servicePaths(root);
|
|
407
|
+
unregisterPlatformService(paths, process.platform);
|
|
408
|
+
try { fs.rmSync(paths.serviceDir, { recursive: true, force: true }); } catch {}
|
|
409
|
+
return { serviceId: paths.serviceId, uninstalled: true, logPath: paths.logPath };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function pruneServices() {
|
|
413
|
+
if (!isSupportedPlatform()) return [];
|
|
414
|
+
const servicesDir = path.join(serviceBaseDir(), 'services');
|
|
415
|
+
let names = [];
|
|
416
|
+
try { names = fs.readdirSync(servicesDir); } catch { return []; }
|
|
417
|
+
const removed = [];
|
|
418
|
+
for (const name of names) {
|
|
419
|
+
const manifest = readManifest(path.join(servicesDir, name, 'manifest.json'));
|
|
420
|
+
if (!manifest) continue;
|
|
421
|
+
const valid = fs.existsSync(manifest.projectRoot) && fs.existsSync(manifest.configPath) && fs.existsSync(manifest.serverPath) && fs.existsSync(manifest.nodePath);
|
|
422
|
+
if (valid) continue;
|
|
423
|
+
const paths = servicePaths(manifest.projectRoot, manifest.platform || process.platform);
|
|
424
|
+
unregisterPlatformService(paths, manifest.platform || process.platform);
|
|
425
|
+
try { fs.rmSync(path.join(servicesDir, name), { recursive: true, force: true }); } catch {}
|
|
426
|
+
removed.push({ serviceId: manifest.serviceId || name, projectRoot: manifest.projectRoot });
|
|
427
|
+
}
|
|
428
|
+
return removed;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function readLog(projectRoot, lineCount) {
|
|
432
|
+
const paths = servicePaths(canonicalProjectRoot(projectRoot));
|
|
433
|
+
let content = '';
|
|
434
|
+
try { content = fs.readFileSync(paths.logPath, 'utf8'); } catch {}
|
|
435
|
+
const lines = content.split(/\r?\n/);
|
|
436
|
+
return { path: paths.logPath, content: lines.slice(-1 * (lineCount || 100)).join('\n') };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
module.exports = {
|
|
440
|
+
installService,
|
|
441
|
+
startService,
|
|
442
|
+
stopService,
|
|
443
|
+
uninstallService,
|
|
444
|
+
pruneServices,
|
|
445
|
+
serviceStatus,
|
|
446
|
+
readLog,
|
|
447
|
+
projectServiceId,
|
|
448
|
+
servicePaths,
|
|
449
|
+
isSupportedPlatform,
|
|
450
|
+
isLoopbackHost,
|
|
451
|
+
inspectHealth
|
|
452
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openprototype",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "本地原型工作台:左侧树形导航 + 中间原型预览 + 右侧 AI Agent(OpenCode)。PRD 与 HTML/JS 原型协作,含自动化检查。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"prototype",
|
|
@@ -28,10 +28,12 @@
|
|
|
28
28
|
"scripts": {
|
|
29
29
|
"serve": "node runtime/server.js",
|
|
30
30
|
"start": "node runtime/server.js",
|
|
31
|
+
"postinstall": "node scripts/postinstall.js",
|
|
31
32
|
"check": "node scripts/check/run-checks.js",
|
|
32
33
|
"check:changed": "node scripts/check/run-checks.js --changed",
|
|
33
34
|
"check:static": "node scripts/check/static-check.js",
|
|
34
35
|
"check:smoke": "node scripts/check/smoke-test.js",
|
|
36
|
+
"check:service": "node scripts/check/service-smoke-test.js",
|
|
35
37
|
"nav:sync": "node scripts/check/sync-nav-tree.js",
|
|
36
38
|
"doctor": "node bin/cli.js doctor",
|
|
37
39
|
"postinstall:browser": "playwright install chromium"
|