dsh-edt-projects 0.11.0 → 0.12.1

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,1089 @@
1
+ // Окружение 1C:EDT для git worktree: настройки, файлы состояния, порт,
2
+ // установка EDT и проверка готовности.
3
+ //
4
+ // Модуль намеренно не запускает процессы: подъёмом занимается
5
+ // workspace-run.mjs, а плагин (lib/index.js) только читает состояние и решает,
6
+ // когда его запустить. Так все функции здесь можно тестировать на временных
7
+ // каталогах и с подменёнными зависимостями.
8
+ //
9
+ // Схема `build/` повторяет проверенную opencode-раскладку, поэтому окружение,
10
+ // поднятое opencode в том же worktree, плагин принимает как готовое.
11
+ import { execFileSync } from 'node:child_process';
12
+ import {
13
+ appendFileSync,
14
+ closeSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ openSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ readlinkSync,
21
+ readSync,
22
+ renameSync,
23
+ rmSync,
24
+ statSync,
25
+ writeFileSync,
26
+ } from 'node:fs';
27
+ import { createServer, connect } from 'node:net';
28
+ import { homedir } from 'node:os';
29
+ import path from 'node:path';
30
+
31
+ import { DEFAULTS } from './schema.mjs';
32
+
33
+ /** Корень окружения внутри worktree. */
34
+ export const BUILD_DIR = 'build';
35
+
36
+ /** Имена файлов состояния внутри `<root>/build`. */
37
+ export const FILE_NAMES = {
38
+ port: 'edt-mcp-port',
39
+ pid: 'edt-mcp.pid',
40
+ ready: 'edt-mcp-ready',
41
+ failed: 'edt-mcp-failed',
42
+ imported: 'edt-imported',
43
+ progress: 'init-progress.json',
44
+ script: 'import.script',
45
+ snapshot: 'workspace.json',
46
+ lock: 'init.lock',
47
+ runLock: 'init-run.lock',
48
+ logs: 'logs',
49
+ };
50
+
51
+ /** Платформы, на которых ищем установленный EDT по умолчанию. */
52
+ const EDT_ROOTS = {
53
+ win32: ['C:\\Program Files\\1C\\1CE\\components', 'C:\\Program Files (x86)\\1C\\1CE\\components'],
54
+ linux: ['/opt/1C/1CE/components'],
55
+ };
56
+
57
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
58
+ const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
59
+
60
+ /** Путь файла состояния. */
61
+ export const filePath = (buildDir, key) => path.join(buildDir, FILE_NAMES[key]);
62
+
63
+ /** Путь к prefs MCP-сервера EDT внутри workspace. */
64
+ export function prefsPath(buildDir) {
65
+ return path.join(
66
+ buildDir,
67
+ 'ws',
68
+ '.metadata',
69
+ '.plugins',
70
+ 'org.eclipse.core.runtime',
71
+ '.settings',
72
+ 'com.ditrix.edt.mcp.server.prefs',
73
+ );
74
+ }
75
+
76
+ /** Каталог, где EDT хранит зарегистрированные проекты workspace. */
77
+ export function registeredProjectsDir(buildDir) {
78
+ return path.join(buildDir, 'ws', '.metadata', '.plugins', 'org.eclipse.core.resources', '.projects');
79
+ }
80
+
81
+ /**
82
+ * Настройки окружения с учётом переменных DSH_1C_EDT_HOME / DSH_1C_EDT_IMPORT.
83
+ * @param raw секция workspace из настроек плагина.
84
+ * @param env окружение процесса.
85
+ */
86
+ export function normalizeWorkspaceSettings(raw = {}, env = process.env) {
87
+ const defaults = DEFAULTS.workspace;
88
+ const value = isObject(raw) ? raw : {};
89
+ const pick = (key, fallback) => (value[key] === undefined ? fallback : value[key]);
90
+ const positive = (candidate, fallback) => (Number.isFinite(candidate) && candidate > 0 ? Math.floor(candidate) : fallback);
91
+ const port = (candidate, fallback) =>
92
+ Number.isInteger(candidate) && candidate >= 1 && candidate <= 65535 ? candidate : fallback;
93
+
94
+ let importMode = pick('import', defaults.import);
95
+ if (importMode !== true && importMode !== false) importMode = 'auto';
96
+ const envImport = env?.DSH_1C_EDT_IMPORT;
97
+ if (typeof envImport === 'string' && envImport.trim() !== '') {
98
+ const lowered = envImport.trim().toLowerCase();
99
+ if (['1', 'true', 'yes', 'on'].includes(lowered)) importMode = true;
100
+ else if (['0', 'false', 'no', 'off'].includes(lowered)) importMode = false;
101
+ }
102
+
103
+ const ports = isObject(value.ports) ? value.ports : {};
104
+ const min = port(ports.min, defaults.ports.min);
105
+ const max = port(ports.max, defaults.ports.max);
106
+
107
+ return {
108
+ enabled: pick('enabled', defaults.enabled) !== false,
109
+ root: text(value.root) ?? '',
110
+ home: {
111
+ win32: text(value.home?.win32) ?? '',
112
+ linux: text(value.home?.linux) ?? '',
113
+ },
114
+ vm: text(value.vm) ?? '',
115
+ xmxIde: text(value.xmxIde) ?? defaults.xmxIde,
116
+ xmxImport: text(value.xmxImport) ?? defaults.xmxImport,
117
+ import: importMode,
118
+ importTimeout: positive(value.importTimeout, defaults.importTimeout),
119
+ startTimeout: positive(value.startTimeout, defaults.startTimeout),
120
+ projects: Array.isArray(value.projects) ? value.projects.filter((item) => text(item) !== undefined).map((item) => item.trim()) : [],
121
+ ports: min <= max ? { min, max } : { min: Math.min(min, max), max: Math.max(min, max) },
122
+ stopOnSessionEnd: pick('stopOnSessionEnd', defaults.stopOnSessionEnd) !== false,
123
+ plainText: pick('plainText', defaults.plainText) !== false,
124
+ formScreenshots: pick('formScreenshots', defaults.formScreenshots) !== false,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Куда поднимать окружение для этой сессии.
130
+ *
131
+ * Автостарт включается только в linked worktree: основной checkout работает
132
+ * с уже запущенным вручную EDT. Если в task space несколько включённых
133
+ * репозиториев, берётся первый (отсортированный) и выдаётся предупреждение;
134
+ * `workspace.root` позволяет выбрать явно.
135
+ */
136
+ export function resolveWorkspaceTarget({ cwd, config, repositories = [], env = process.env } = {}) {
137
+ const settings = normalizeWorkspaceSettings(config?.workspace, env);
138
+ if (!settings.enabled) return { state: 'off', reason: 'disabled', settings };
139
+ if (!Array.isArray(repositories) || repositories.length === 0) {
140
+ return {
141
+ state: 'error',
142
+ reason: 'no-repository',
143
+ settings,
144
+ message: 'каталог сессии не является git-репозиторием и не содержит репозиториев первого уровня',
145
+ };
146
+ }
147
+
148
+ const worktrees = repositories.filter((repo) => repo?.isWorktree === true && typeof repo.root === 'string');
149
+ if (worktrees.length === 0) return { state: 'off', reason: 'main-checkout', settings };
150
+
151
+ const warnings = [];
152
+ const repo = worktrees[0];
153
+ if (worktrees.length > 1) {
154
+ warnings.push(
155
+ `несколько worktree (${worktrees.map((item) => item.root).join(', ')}); выбран ${repo.root}. Укажите workspace.root, чтобы выбрать другой.`,
156
+ );
157
+ }
158
+
159
+ const configured = settings.root;
160
+ const root =
161
+ configured === ''
162
+ ? repo.root
163
+ : path.isAbsolute(configured)
164
+ ? path.normalize(configured)
165
+ : path.resolve(repo.root, configured);
166
+ const buildDir = path.join(root, BUILD_DIR);
167
+
168
+ return {
169
+ state: 'ok',
170
+ settings,
171
+ repo,
172
+ mainRoot: repo.mainRoot,
173
+ root,
174
+ buildDir,
175
+ wsDir: path.join(buildDir, 'ws'),
176
+ isWorktree: true,
177
+ rootSource: configured === '' ? 'repo' : 'config',
178
+ warnings,
179
+ };
180
+ }
181
+
182
+ // --- проекты EDT ------------------------------------------------------------
183
+
184
+ /** Есть ли в каталоге Eclipse-проект. */
185
+ export function hasProjectFile(dir) {
186
+ try {
187
+ return statSync(path.join(dir, '.project')).isFile();
188
+ } catch {
189
+ return false;
190
+ }
191
+ }
192
+
193
+ const hasWildcard = (segment) => segment.includes('*') || segment.includes('?');
194
+
195
+ function matchSegment(name, segment) {
196
+ if (!hasWildcard(segment)) return name.toLowerCase() === segment.toLowerCase();
197
+ const pattern = segment
198
+ .split('')
199
+ .map((char) => {
200
+ if (char === '*') return '.*';
201
+ if (char === '?') return '.';
202
+ return char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
203
+ })
204
+ .join('');
205
+ return new RegExp(`^${pattern}$`, 'i').test(name);
206
+ }
207
+
208
+ function walkPattern(dir, segments, out) {
209
+ if (segments.length === 0) {
210
+ out.push(dir);
211
+ return;
212
+ }
213
+ const [head, ...rest] = segments;
214
+ if (head === '') {
215
+ walkPattern(dir, rest, out);
216
+ return;
217
+ }
218
+ if (head === '..') {
219
+ walkPattern(path.dirname(dir), rest, out);
220
+ return;
221
+ }
222
+ if (!hasWildcard(head)) {
223
+ const next = path.join(dir, head);
224
+ if (existsSync(next)) walkPattern(next, rest, out);
225
+ return;
226
+ }
227
+ let entries;
228
+ try {
229
+ entries = readdirSync(dir, { withFileTypes: true });
230
+ } catch {
231
+ return;
232
+ }
233
+ for (const entry of entries) {
234
+ if (!entry.isDirectory() || !matchSegment(entry.name, head)) continue;
235
+ walkPattern(path.join(dir, entry.name), rest, out);
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Разворачивает шаблон EDT-проекта в каталоги с `.project`.
241
+ * Поддерживает `*`/`?` в любом сегменте и абсолютные пути.
242
+ */
243
+ export function expandProjectPattern(root, pattern) {
244
+ const raw = String(pattern ?? '').trim();
245
+ if (raw === '') return [];
246
+ const isAbsolute = path.isAbsolute(raw);
247
+ const absolute = isAbsolute ? path.resolve(raw) : undefined;
248
+ const startDir = isAbsolute ? path.parse(absolute).root : root;
249
+ const relative = isAbsolute ? path.relative(startDir, absolute) : raw;
250
+ const segments = relative.split(/[\\/]+/).filter((segment) => segment !== '' && segment !== '.');
251
+ const out = [];
252
+ walkPattern(startDir, segments, out);
253
+ return out.filter(hasProjectFile);
254
+ }
255
+
256
+ const dedupePaths = (paths) => {
257
+ const seen = new Set();
258
+ const out = [];
259
+ for (const item of paths) {
260
+ const key = path.resolve(item);
261
+ if (seen.has(key)) continue;
262
+ seen.add(key);
263
+ out.push(key);
264
+ }
265
+ return out.sort((left, right) => left.localeCompare(right, undefined, { sensitivity: 'base' }));
266
+ };
267
+
268
+ /**
269
+ * Проекты EDT для импорта: шаблоны из настроек либо автопоиск каталогов
270
+ * с `.project` до трёх уровней (кроме build, node_modules и скрытых).
271
+ */
272
+ export function discoverProjects(root, patterns = [], { maxDepth = 3 } = {}) {
273
+ if (Array.isArray(patterns) && patterns.length > 0) {
274
+ const matched = [];
275
+ for (const pattern of patterns) matched.push(...expandProjectPattern(root, pattern));
276
+ return dedupePaths(matched);
277
+ }
278
+
279
+ const found = [];
280
+ const queue = [{ dir: path.resolve(root), depth: 0 }];
281
+ while (queue.length > 0) {
282
+ const { dir, depth } = queue.shift();
283
+ if (hasProjectFile(dir)) {
284
+ found.push(dir);
285
+ continue;
286
+ }
287
+ if (depth >= maxDepth) continue;
288
+ let entries;
289
+ try {
290
+ entries = readdirSync(dir, { withFileTypes: true });
291
+ } catch {
292
+ continue;
293
+ }
294
+ for (const entry of entries) {
295
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'build' || entry.name === 'node_modules') continue;
296
+ queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
297
+ }
298
+ }
299
+ return [...new Set(found)].sort((left, right) => left.localeCompare(right, undefined, { sensitivity: 'base' }));
300
+ }
301
+
302
+ /** Текст скрипта импорта для `1cedtcli -file`. */
303
+ export function importScriptText(projects) {
304
+ const lines = (projects ?? [])
305
+ .filter((item) => typeof item === 'string' && item.trim() !== '')
306
+ .map((item) => `import --project "${item}"`);
307
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
308
+ }
309
+
310
+ // --- prefs EDT-MCP ----------------------------------------------------------
311
+
312
+ /** Дописывает значения в prefs, сохраняя остальные ключи. */
313
+ export function mergePrefsText(current, values = {}) {
314
+ const map = new Map();
315
+ for (const line of String(current ?? '').split(/\r?\n/)) {
316
+ const index = line.indexOf('=');
317
+ if (index > 0) map.set(line.slice(0, index), line.slice(index + 1));
318
+ }
319
+ for (const [key, value] of Object.entries(values)) map.set(key, String(value));
320
+ let out = 'eclipse.preferences.version=1\n';
321
+ for (const [key, value] of map) {
322
+ if (key === 'eclipse.preferences.version') continue;
323
+ out += `${key}=${value}\n`;
324
+ }
325
+ return out;
326
+ }
327
+
328
+ /** Значения инструментов, отключённых в EDT-MCP по умолчанию. */
329
+ export const DEFAULT_DISABLED_TOOLS = ['git', 'ask_workmate', 'get_form_screenshot'];
330
+
331
+ /** Значение ключа prefs (первое вхождение). */
332
+ export function prefValue(text, key) {
333
+ for (const line of String(text ?? '').split(/\r?\n/)) {
334
+ const index = line.indexOf('=');
335
+ if (index > 0 && line.slice(0, index) === key) return line.slice(index + 1);
336
+ }
337
+ return undefined;
338
+ }
339
+
340
+ /** Список отключённых инструментов из prefs (или дефолт EDT-MCP). */
341
+ function disabledToolsList(current) {
342
+ const raw = prefValue(current, 'mcpDisabledTools');
343
+ return (raw === undefined ? DEFAULT_DISABLED_TOOLS : raw.split(','))
344
+ .map((item) => item.trim())
345
+ .filter((item) => item !== '');
346
+ }
347
+
348
+ function disabledToolsWithout(current, tool) {
349
+ return [...new Set(disabledToolsList(current).filter((item) => item !== tool))].join(',');
350
+ }
351
+
352
+ function disabledToolsWith(current, tool) {
353
+ return [...new Set([...disabledToolsList(current), tool])].join(',');
354
+ }
355
+
356
+ /** Содержимое prefs EDT-MCP этого workspace (undefined — файла нет). */
357
+ export function readPrefs(buildDir) {
358
+ return readText(prefsPath(buildDir));
359
+ }
360
+
361
+ /** prefs, включающие MCP-сервер EDT на нужном порту при старте. */
362
+ export function writePrefs(buildDir, port, options = {}) {
363
+ const file = prefsPath(buildDir);
364
+ mkdirSync(path.dirname(file), { recursive: true });
365
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
366
+ const values = {
367
+ mcpServerHttpEnabled: 'true',
368
+ mcpServerAutoStart: 'true',
369
+ mcpServerPort: port,
370
+ // DSH не рендерит embedded resource: markdown-инструменты EDT-MCP должны
371
+ // отдавать текст (Plain text mode).
372
+ mcpPlainTextMode: String(options.plainText !== false),
373
+ };
374
+ // get_form_screenshot выключен в EDT-MCP по умолчанию. Список всегда
375
+ // приводим к настройке: при true убираем инструмент, при false — возвращаем,
376
+ // иначе prefs от прошлого запуска оставят его включённым.
377
+ values.mcpDisabledTools =
378
+ options.formScreenshots !== false
379
+ ? disabledToolsWithout(current, 'get_form_screenshot')
380
+ : disabledToolsWith(current, 'get_form_screenshot');
381
+ const next = mergePrefsText(current, values);
382
+ atomicWrite(file, next);
383
+ return file;
384
+ }
385
+
386
+ // --- порт -------------------------------------------------------------------
387
+
388
+ /** Свободен ли порт на loopback. */
389
+ export function isPortFree(port, host = '127.0.0.1') {
390
+ return new Promise((resolve) => {
391
+ const server = createServer();
392
+ server.once('error', () => resolve(false));
393
+ server.once('listening', () => server.close(() => resolve(true)));
394
+ server.listen(port, host);
395
+ });
396
+ }
397
+
398
+ /**
399
+ * Случайный свободный порт из диапазона, не занятый самим плагином.
400
+ * @param range { min, max }
401
+ * @param deps.isFree проверка занятости (для тестов).
402
+ * @param deps.used уже использованные порты.
403
+ */
404
+ export async function pickFreePort(range, deps = {}) {
405
+ const probe = deps.isFree ?? isPortFree;
406
+ const used = deps.used ?? new Set();
407
+ const random = deps.random ?? Math.random;
408
+ const min = Number(range?.min);
409
+ const max = Number(range?.max);
410
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min < 1 || max < min) {
411
+ throw new Error(`некорректный диапазон портов: ${range?.min}..${range?.max}`);
412
+ }
413
+ const span = max - min + 1;
414
+ for (let attempt = 0; attempt < span; attempt++) {
415
+ const port = min + Math.floor(random() * span);
416
+ if (used.has(port)) continue;
417
+ if (await probe(port)) return port;
418
+ used.add(port);
419
+ }
420
+ throw new Error(`нет свободного порта в диапазоне ${min}..${max}`);
421
+ }
422
+
423
+ /** Порт, занятый нашим процессом (для проверки готовности). */
424
+ export function isPortOpen(port, host = '127.0.0.1', timeoutMs = 1000) {
425
+ return new Promise((resolve) => {
426
+ const socket = connect({ host, port });
427
+ const done = (ok) => {
428
+ socket.destroy();
429
+ resolve(ok);
430
+ };
431
+ socket.setTimeout(timeoutMs);
432
+ socket.once('connect', () => done(true));
433
+ socket.once('timeout', () => done(false));
434
+ socket.once('error', () => done(false));
435
+ });
436
+ }
437
+
438
+ // --- файлы состояния --------------------------------------------------------
439
+
440
+ /** Атомарная запись: временный файл рядом и rename. */
441
+ export function atomicWrite(file, content) {
442
+ mkdirSync(path.dirname(file), { recursive: true });
443
+ const tmp = `${file}.tmp`;
444
+ try {
445
+ writeFileSync(tmp, content, 'utf8');
446
+ renameSync(tmp, file);
447
+ } catch (error) {
448
+ try {
449
+ rmSync(tmp, { force: true });
450
+ } catch {
451
+ // временный файл мог не создаться — это не мешает исходной ошибке
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+
457
+ const readText = (file) => {
458
+ try {
459
+ return readFileSync(file, 'utf8');
460
+ } catch {
461
+ return undefined;
462
+ }
463
+ };
464
+
465
+ const readJson = (file) => {
466
+ const content = readText(file);
467
+ if (content === undefined) return undefined;
468
+ try {
469
+ return JSON.parse(content);
470
+ } catch {
471
+ return undefined;
472
+ }
473
+ };
474
+
475
+ /** Порт MCP-сервера EDT или null. */
476
+ export function readPort(buildDir) {
477
+ const content = readText(filePath(buildDir, 'port'));
478
+ if (content === undefined) return null;
479
+ const value = Number.parseInt(content.trim(), 10);
480
+ return Number.isInteger(value) && value > 0 && value <= 65535 ? value : null;
481
+ }
482
+
483
+ export function writePort(buildDir, port) {
484
+ atomicWrite(filePath(buildDir, 'port'), String(port));
485
+ }
486
+
487
+ /** `{ pid, startedAt }` процесса EDT или null. */
488
+ export function readPid(buildDir) {
489
+ const value = readJson(filePath(buildDir, 'pid'));
490
+ const pid = Number.parseInt(value?.pid, 10);
491
+ if (!Number.isInteger(pid) || pid <= 0) return null;
492
+ return { pid, startedAt: typeof value?.startedAt === 'string' ? value.startedAt : undefined };
493
+ }
494
+
495
+ export function writePid(buildDir, pid, now = new Date()) {
496
+ atomicWrite(filePath(buildDir, 'pid'), JSON.stringify({ pid, startedAt: now.toISOString() }));
497
+ }
498
+
499
+ /** Отметка времени из файла-маркера. */
500
+ export function readStamp(buildDir, key) {
501
+ return readText(filePath(buildDir, key))?.trim() || undefined;
502
+ }
503
+
504
+ export function writeStamp(buildDir, key, now = new Date()) {
505
+ atomicWrite(filePath(buildDir, key), now.toISOString());
506
+ }
507
+
508
+ export function removeStamp(buildDir, key) {
509
+ try {
510
+ rmSync(filePath(buildDir, key), { force: true });
511
+ } catch {
512
+ // маркера могло не быть
513
+ }
514
+ }
515
+
516
+ /** Что импортировали в workspace: `{ projects, at }` или null. */
517
+ export function readImported(buildDir) {
518
+ return readJson(filePath(buildDir, 'imported')) ?? null;
519
+ }
520
+
521
+ export function writeImported(buildDir, projects, now = new Date()) {
522
+ atomicWrite(filePath(buildDir, 'imported'), JSON.stringify({ projects, at: now.toISOString() }));
523
+ }
524
+
525
+ /** Прогресс подъёма: `{ startedAt, edt: { phase, since, updated, detail } }`. */
526
+ export function readProgress(buildDir) {
527
+ return readJson(filePath(buildDir, 'progress')) ?? null;
528
+ }
529
+
530
+ /**
531
+ * @param now момент записи (для тестов передаётся явно: `since` не должен
532
+ * зависеть от разрешения часов).
533
+ */
534
+ export function writeProgress(buildDir, kind, phase, detail, now = new Date(), extra = undefined) {
535
+ const prev = readProgress(buildDir) ?? { startedAt: now.toISOString() };
536
+ const stamp = now.toISOString();
537
+ const was = prev[kind];
538
+ prev[kind] = { phase, since: was?.phase === phase && was.since ? was.since : stamp, updated: stamp };
539
+ if (detail !== undefined) prev[kind].detail = detail;
540
+ if (extra !== undefined && typeof extra === 'object') Object.assign(prev[kind], extra);
541
+ atomicWrite(filePath(buildDir, 'progress'), `${JSON.stringify(prev, null, 2)}\n`);
542
+ }
543
+
544
+ export function clearProgress(buildDir) {
545
+ for (const file of [filePath(buildDir, 'progress'), `${filePath(buildDir, 'progress')}.tmp`]) {
546
+ try {
547
+ rmSync(file, { force: true });
548
+ } catch {
549
+ // прогресса могло не быть
550
+ }
551
+ }
552
+ }
553
+
554
+ /** Последняя непустая строка файла, обрезанная до maxLen. */
555
+ export function tailFile(file, maxLen = 200) {
556
+ const content = readText(file);
557
+ if (content === undefined) return null;
558
+ const lines = content.split(/\r?\n/).filter((line) => line.trim() !== '');
559
+ return lines.length === 0 ? null : lines[lines.length - 1].slice(0, maxLen);
560
+ }
561
+
562
+ /** Длина буфера без обрезанной многобайтовой UTF-8 последовательности. */
563
+ function completeUtf8Length(buffer) {
564
+ let index = buffer.length - 1;
565
+ let continuation = 0;
566
+ while (index >= 0 && (buffer[index] & 0xc0) === 0x80 && continuation < 3) {
567
+ index -= 1;
568
+ continuation += 1;
569
+ }
570
+ if (index < 0) return buffer.length;
571
+ const lead = buffer[index];
572
+ let needed;
573
+ if ((lead & 0x80) === 0) needed = 1;
574
+ else if ((lead & 0xe0) === 0xc0) needed = 2;
575
+ else if ((lead & 0xf0) === 0xe0) needed = 3;
576
+ else if ((lead & 0xf8) === 0xf0) needed = 4;
577
+ else return buffer.length;
578
+ const have = buffer.length - index;
579
+ return have >= needed ? buffer.length : index;
580
+ }
581
+
582
+ /** Читает файл с байтового смещения (для растущего workspace `.metadata/.log`). */
583
+ export function readFromOffset(file, offset, { maxBytes = 512 * 1024 } = {}) {
584
+ let fd;
585
+ try {
586
+ fd = openSync(file, 'r');
587
+ const size = statSync(file).size;
588
+ const start = Math.max(0, Math.min(offset ?? 0, size));
589
+ const length = Math.min(Math.max(0, size - start), maxBytes);
590
+ if (length === 0) return { text: '', offset: size };
591
+ const buffer = Buffer.alloc(length);
592
+ readSync(fd, buffer, 0, length, start);
593
+ const complete = completeUtf8Length(buffer);
594
+ return {
595
+ text: buffer.subarray(0, complete).toString('utf8'),
596
+ // Следующий вызов дочитает остаток, а не пропустит его.
597
+ offset: start + complete,
598
+ };
599
+ } catch {
600
+ return { text: '', offset: offset ?? 0 };
601
+ } finally {
602
+ if (fd !== undefined) closeSync(fd);
603
+ }
604
+ }
605
+
606
+ const PROJECT_STARTED = /Project context is started:\s*(.+?)\s*$/;
607
+ const PROJECT_STARTING = /Project context is being started:\s*(.+?)(?:\s+\([A-Z_]+\))?\s*$/;
608
+
609
+ /**
610
+ * Прогресс импорта по `build/ws/.metadata/.log`: сколько проектов стартовало
611
+ * и какой проект сейчас в работе. Счётчик ограничен `total`.
612
+ */
613
+ export function parseImportProgress(text, total = 0) {
614
+ const started = new Set();
615
+ let lastStarted;
616
+ let lastStarting;
617
+ for (const line of String(text ?? '').split(/\r?\n/)) {
618
+ const startedMatch = PROJECT_STARTED.exec(line);
619
+ if (startedMatch !== null) {
620
+ lastStarted = startedMatch[1].trim();
621
+ started.add(lastStarted);
622
+ continue;
623
+ }
624
+ const startingMatch = PROJECT_STARTING.exec(line);
625
+ if (startingMatch !== null) lastStarting = startingMatch[1].trim();
626
+ }
627
+ const count = total > 0 ? Math.min(started.size, total) : started.size;
628
+ const current = lastStarting !== undefined && !started.has(lastStarting) ? lastStarting : lastStarted;
629
+ return { started: [...started], startedCount: count, total, current };
630
+ }
631
+
632
+ /** Свежий кусок metadata-лога, прогресс импорта и полезные строки. */
633
+ export function importDigest(buildDir, offset, total, deps = {}) {
634
+ const file = path.join(buildDir, 'ws', '.metadata', '.log');
635
+ const { text, offset: next } = (deps.readFromOffset ?? readFromOffset)(file, offset);
636
+ const progress = parseImportProgress(text, total);
637
+ const lines = text
638
+ .split(/\r?\n/)
639
+ .filter((line) => /Project context|CPU overload|Memory \d+ MB|!ERROR|Exception/.test(line));
640
+ return { ...progress, offset: next, lines, text };
641
+ }
642
+
643
+ /** Копирует значимые строки импорта в build/logs/edt-import.log. */
644
+ export function appendImportDigest(buildDir, lines) {
645
+ if (!Array.isArray(lines) || lines.length === 0) return;
646
+ const file = path.join(buildDir, 'logs', 'edt-import.log');
647
+ mkdirSync(path.dirname(file), { recursive: true });
648
+ appendFileSync(file, `${lines.join('\n')}\n`, 'utf8');
649
+ }
650
+
651
+ /**
652
+ * Признак нехватки памяти при импорте: `CPU overload. Memory X MB used of Y MB`
653
+ * или явный `CPU overload`. Возвращает последнее измерение, если загрузка ≥85 %.
654
+ */
655
+ export function importMemoryWarning(text) {
656
+ const matches = [...String(text ?? '').matchAll(/Memory\s+(\d+)\s+MB\s+used\s+of\s+(\d+)\s+MB/gi)];
657
+ const last = matches.at(-1);
658
+ const cpuOverload = /CPU overload/i.test(String(text ?? ''));
659
+ if (last === undefined) return cpuOverload ? { cpuOverload: true } : undefined;
660
+ const used = Number.parseInt(last[1], 10);
661
+ const total = Number.parseInt(last[2], 10);
662
+ if (!Number.isFinite(used) || !Number.isFinite(total) || total <= 0) return undefined;
663
+ const ratio = used / total;
664
+ return ratio >= 0.85 || cpuOverload ? { used, total, ratio, cpuOverload } : undefined;
665
+ }
666
+
667
+ /** Снимок настроек окружения — для диагностики и фонового процесса. */
668
+ export function buildWorkspaceSnapshot({ root, buildDir, wsDir, mainRoot, settings, projects, now = new Date() }) {
669
+ return {
670
+ version: 1,
671
+ root,
672
+ buildDir,
673
+ wsDir,
674
+ mainRoot,
675
+ createdAt: now.toISOString(),
676
+ settings,
677
+ projects,
678
+ };
679
+ }
680
+
681
+ export function writeWorkspaceSnapshot(buildDir, snapshot) {
682
+ atomicWrite(filePath(buildDir, 'snapshot'), `${JSON.stringify(snapshot, null, 2)}\n`);
683
+ }
684
+
685
+ export function readWorkspaceSnapshot(buildDir) {
686
+ return readJson(filePath(buildDir, 'snapshot'));
687
+ }
688
+
689
+ /**
690
+ * Снимок для конкретного worktree: пути, настройки и найденные проекты EDT.
691
+ * Пишется один раз перед подъёмом; фоновый процесс читает его, а не настройки
692
+ * плагина — так окружение поднимается ровно по тому, что было в момент старта.
693
+ */
694
+ export function prepareWorkspaceSnapshot({ root, mainRoot, settings, patterns, now = new Date() }) {
695
+ const buildDir = path.join(root, BUILD_DIR);
696
+ const projects = discoverProjects(root, patterns ?? settings?.projects ?? []);
697
+ return buildWorkspaceSnapshot({
698
+ root,
699
+ buildDir,
700
+ wsDir: path.join(buildDir, 'ws'),
701
+ mainRoot,
702
+ settings,
703
+ projects,
704
+ now,
705
+ });
706
+ }
707
+
708
+ // --- процессы ---------------------------------------------------------------
709
+
710
+ /** Имя образа процесса на Windows (`1cedt.exe`) или null. */
711
+ export function parseTasklistImage(output) {
712
+ const line = String(output ?? '')
713
+ .split(/\r?\n/)
714
+ .find((item) => item.trim().startsWith('"'));
715
+ if (line === undefined) return null;
716
+ const match = /^"([^"]+)"/.exec(line);
717
+ return match ? match[1].toLowerCase() : null;
718
+ }
719
+
720
+ export function processImage(pid, { platform = process.platform, run = execFileSync } = {}) {
721
+ try {
722
+ if (platform === 'win32') {
723
+ const output = run('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true });
724
+ return parseTasklistImage(output);
725
+ }
726
+ return path.basename(readlinkSync(`/proc/${pid}/exe`)).toLowerCase();
727
+ } catch {
728
+ return null;
729
+ }
730
+ }
731
+
732
+ /** Жив ли процесс; при указании образов — того ли он типа. */
733
+ export function pidAlive(pid, images = null, deps = {}) {
734
+ if (!Number.isInteger(pid) || pid <= 0) return false;
735
+ try {
736
+ process.kill(pid, 0);
737
+ } catch {
738
+ return false;
739
+ }
740
+ if (!Array.isArray(images) || images.length === 0) return true;
741
+ const image = (deps.processImage ?? processImage)(pid, deps);
742
+ if (!image) return true;
743
+ return images.some((candidate) => image.includes(String(candidate).toLowerCase()));
744
+ }
745
+
746
+ /** Останавливает дерево процессов: сначала мягко, потом принудительно. */
747
+ export function killTree(pid, { force = false, platform = process.platform, run = execFileSync, kill = process.kill } = {}) {
748
+ try {
749
+ if (platform === 'win32') {
750
+ const args = force ? ['/PID', String(pid), '/T', '/F'] : ['/PID', String(pid), '/T'];
751
+ run('taskkill', args, { stdio: 'ignore', windowsHide: true });
752
+ } else {
753
+ try {
754
+ kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
755
+ } catch {
756
+ kill(pid, force ? 'SIGKILL' : 'SIGTERM');
757
+ }
758
+ }
759
+ } catch {
760
+ // процесс уже мог завершиться
761
+ }
762
+ }
763
+
764
+ // --- установка EDT ----------------------------------------------------------
765
+
766
+ const MCP_BUNDLE = /com\.ditrix\.edt\.mcp\.server|ditrix/i;
767
+
768
+ function bundleNames(dir) {
769
+ try {
770
+ return readdirSync(dir).filter((name) => MCP_BUNDLE.test(name));
771
+ } catch {
772
+ return [];
773
+ }
774
+ }
775
+
776
+ /** Значение ключа Eclipse `config.ini` (без разбора секций). */
777
+ function iniValue(text, key) {
778
+ const match = new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*=\\s*(.+)$`, 'm').exec(String(text ?? ''));
779
+ return match === null ? undefined : match[1].trim();
780
+ }
781
+
782
+ /** `file\:configuration/` -> абсолютный путь. */
783
+ function resolveEclipsePath(value, baseDir) {
784
+ if (typeof value !== 'string' || value === '') return undefined;
785
+ const raw = value.replace(/\\:/g, ':').replace(/^file:/i, '');
786
+ if (raw === '') return undefined;
787
+ return path.isAbsolute(raw) ? path.normalize(raw) : path.resolve(baseDir, raw);
788
+ }
789
+
790
+ /** Области конфигурации, в которых Eclipse ищет бандлы. */
791
+ function configurationAreas(home, { platform = process.platform, eclipseRoots } = {}) {
792
+ const areas = [];
793
+ if (typeof home === 'string' && home !== '') {
794
+ // Сам каталог установки: <home>/plugins и <home>/features.
795
+ areas.push(home);
796
+ const configDir = path.join(home, 'configuration');
797
+ areas.push(configDir);
798
+ try {
799
+ const shared = iniValue(readFileSync(path.join(configDir, 'config.ini'), 'utf8'), 'osgi.sharedConfiguration.area');
800
+ const resolved = resolveEclipsePath(shared, configDir);
801
+ if (resolved !== undefined && resolved !== configDir) areas.push(resolved);
802
+ } catch {
803
+ // config.ini может отсутствовать — не мешает проверке установки
804
+ }
805
+ try {
806
+ const ini = readFileSync(path.join(home, platform === 'win32' ? '1cedt.ini' : '1cedt.ini'), 'utf8');
807
+ const line = /^-configuration\s+(.+)$/m.exec(ini)?.[1]?.trim();
808
+ const resolved = resolveEclipsePath(line, home);
809
+ if (resolved !== undefined) areas.push(resolved);
810
+ } catch {
811
+ // 1cedt.ini может отсутствовать
812
+ }
813
+ }
814
+
815
+ const homeDir = platform === 'win32' ? homedir() : (process.env.HOME ?? homedir());
816
+ for (const root of eclipseRoots ?? [path.join(homeDir, '.eclipse')]) {
817
+ let entries;
818
+ try {
819
+ entries = readdirSync(root, { withFileTypes: true });
820
+ } catch {
821
+ continue;
822
+ }
823
+ for (const entry of entries) {
824
+ if (!entry.isDirectory() || !/^org\.eclipse\.platform_/.test(entry.name)) continue;
825
+ areas.push(path.join(root, entry.name, 'configuration'));
826
+ }
827
+ }
828
+ return [...new Set(areas)];
829
+ }
830
+
831
+ /**
832
+ * Где реально лежит EDT-MCP: установка, shared area или пользовательская
833
+ * configuration area (`~/.eclipse/org.eclipse.platform_*`). Это подсказка для
834
+ * диагностики, а не критерий выбора установки.
835
+ * @returns {{ found: boolean, evidence: string[] }}
836
+ */
837
+ export function mcpEvidence(home, options = {}) {
838
+ const evidence = [];
839
+ for (const area of configurationAreas(home, options)) {
840
+ for (const sub of ['plugins', 'features']) {
841
+ const hits = bundleNames(path.join(area, sub));
842
+ if (hits.length > 0) evidence.push(`${path.join(area, sub)}: ${hits[0]}`);
843
+ }
844
+ const bundles = path.join(area, 'org.eclipse.equinox.simpleconfigurator', 'bundles.info');
845
+ try {
846
+ if (MCP_BUNDLE.test(readFileSync(bundles, 'utf8'))) evidence.push(bundles);
847
+ } catch {
848
+ // bundles.info может отсутствовать
849
+ }
850
+ }
851
+ return { found: evidence.length > 0, evidence };
852
+ }
853
+
854
+ /** Установлен ли в этой EDT плагин EDT-MCP (обёртка над mcpEvidence). */
855
+ export function hasMcpBundle(home, options = {}) {
856
+ return mcpEvidence(home, options).found;
857
+ }
858
+
859
+ const VERSION_PATTERN = /^1c-edt-(\d{4})\.(\d+)\.(\d+)\+(\d+)-/;
860
+
861
+ /** Версия установки EDT для сортировки (null — не установка EDT). */
862
+ export function edtVersionOf(name) {
863
+ const match = VERSION_PATTERN.exec(String(name ?? ''));
864
+ if (match === null) return null;
865
+ return match.slice(1).map((part) => Number.parseInt(part, 10));
866
+ }
867
+
868
+ const compareVersion = (left, right) => {
869
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
870
+ const diff = (left[index] ?? 0) - (right[index] ?? 0);
871
+ if (diff !== 0) return diff;
872
+ }
873
+ return 0;
874
+ };
875
+
876
+ /**
877
+ * Установка EDT: явная из настроек/`DSH_1C_EDT_HOME` либо старшая найденная.
878
+ * Наличие EDT-MCP в файлах — только диагностическая подсказка: бандл может
879
+ * стоять в пользовательской configuration area, а окончательно готовность
880
+ * подтверждает `/health`.
881
+ * @returns {{ home?: string, bin?: string, cli?: string, mcpBundle?: boolean,
882
+ * mcpEvidence?: string[], source?: string, error?: string }}
883
+ */
884
+ export function detectEdtHome(settings, { platform = process.platform, env = process.env, roots, eclipseRoots } = {}) {
885
+ const binary = platform === 'win32' ? '1cedt.exe' : '1cedt';
886
+ const cli = platform === 'win32' ? '1cedtcli.exe' : '1cedtcli';
887
+ const explicit = text(env?.DSH_1C_EDT_HOME) ?? text(settings?.home?.[platform]);
888
+ if (explicit !== undefined) {
889
+ const home = path.normalize(explicit);
890
+ const bin = path.join(home, binary);
891
+ if (!existsSync(bin)) return { error: `в ${home} нет ${binary}`, home };
892
+ const cliPath = path.join(home, cli);
893
+ const evidence = mcpEvidence(home, { platform, env, eclipseRoots });
894
+ return {
895
+ home,
896
+ bin,
897
+ cli: existsSync(cliPath) ? cliPath : undefined,
898
+ mcpBundle: evidence.found,
899
+ mcpEvidence: evidence.evidence,
900
+ source: text(env?.DSH_1C_EDT_HOME) ? 'env' : 'config',
901
+ };
902
+ }
903
+
904
+ const searchRoots = roots ?? EDT_ROOTS[platform] ?? [];
905
+ const candidates = [];
906
+ for (const root of searchRoots) {
907
+ let entries;
908
+ try {
909
+ entries = readdirSync(root, { withFileTypes: true });
910
+ } catch {
911
+ continue;
912
+ }
913
+ for (const entry of entries) {
914
+ if (!entry.isDirectory()) continue;
915
+ const version = edtVersionOf(entry.name);
916
+ if (version === null) continue;
917
+ const home = path.join(root, entry.name);
918
+ if (!existsSync(path.join(home, binary))) continue;
919
+ candidates.push({ home, version });
920
+ }
921
+ }
922
+ if (candidates.length === 0) {
923
+ return { error: `1C:EDT не найден; задайте workspace.home или DSH_1C_EDT_HOME (искали в ${searchRoots.join(', ')})` };
924
+ }
925
+ // Выбор только по версии: наличие бандла не должно решать, какую установку
926
+ // запускать (бандл может лежать в пользовательской configuration area).
927
+ candidates.sort((left, right) => compareVersion(right.version, left.version));
928
+ const chosen = candidates[0];
929
+ const cliPath = path.join(chosen.home, cli);
930
+ const evidence = mcpEvidence(chosen.home, { platform, env, eclipseRoots });
931
+ return {
932
+ home: chosen.home,
933
+ bin: path.join(chosen.home, binary),
934
+ cli: existsSync(cliPath) ? cliPath : undefined,
935
+ mcpBundle: evidence.found,
936
+ mcpEvidence: evidence.evidence,
937
+ source: 'autodetect',
938
+ };
939
+ }
940
+
941
+ /**
942
+ * Требования EDT к Java из `1cedt.ini`: major из
943
+ * `-Dosgi.requiredJavaVersion` и явный `-vm` (до `-vmargs`), если задан.
944
+ */
945
+ export function requiredJava(home, { platform = process.platform } = {}) {
946
+ const result = { major: undefined, vm: undefined };
947
+ if (typeof home !== 'string' || home === '') return result;
948
+ let ini;
949
+ try {
950
+ ini = readFileSync(path.join(home, '1cedt.ini'), 'utf8');
951
+ } catch {
952
+ return result;
953
+ }
954
+ const major = /-Dosgi\.requiredJavaVersion=(\d+)/.exec(ini)?.[1];
955
+ if (major !== undefined) result.major = Number.parseInt(major, 10);
956
+
957
+ const lines = ini.split(/\r?\n/);
958
+ const vmargsAt = lines.findIndex((line) => line.trim() === '-vmargs');
959
+ const launchLines = vmargsAt === -1 ? lines : lines.slice(0, vmargsAt);
960
+ const vmAt = launchLines.findIndex((line) => line.trim() === '-vm');
961
+ let vm;
962
+ if (vmAt !== -1) {
963
+ vm = launchLines.slice(vmAt + 1).find((line) => line.trim() !== '')?.trim();
964
+ } else {
965
+ vm = /^\s*-vm\s+(.+)$/m.exec(launchLines.join('\n'))?.[1]?.trim();
966
+ }
967
+ if (vm !== undefined && vm !== '') {
968
+ result.vm = path.isAbsolute(vm) ? path.normalize(vm) : path.resolve(home, vm);
969
+ }
970
+ return result;
971
+ }
972
+
973
+ /** JDK рядом с установкой EDT: `{ major, path }`, по убыванию major. */
974
+ function jdkCandidates(components, javaBinary) {
975
+ let entries;
976
+ try {
977
+ entries = readdirSync(components, { withFileTypes: true });
978
+ } catch {
979
+ return [];
980
+ }
981
+ const candidates = [];
982
+ for (const entry of entries) {
983
+ if (!entry.isDirectory()) continue;
984
+ const major = /jdk-(?:full-)?(\d+)/i.exec(entry.name)?.[1];
985
+ if (major === undefined) continue;
986
+ const bin = path.join(components, entry.name, 'bin', javaBinary);
987
+ if (!existsSync(bin)) continue;
988
+ candidates.push({ major: Number.parseInt(major, 10), path: bin });
989
+ }
990
+ return candidates.sort((left, right) => right.major - left.major);
991
+ }
992
+
993
+ /**
994
+ * Java для EDT: явная настройка → `-vm` из ini → JDK рядом с установкой по
995
+ * требуемой major (точная, затем ближайшая старшая, затем старшая доступная).
996
+ */
997
+ export function resolveEdtVm(settings, home, { platform = process.platform, env = process.env } = {}) {
998
+ const explicit = text(env?.DSH_1C_EDT_VM) ?? text(settings?.vm);
999
+ if (explicit !== undefined) return explicit;
1000
+ if (typeof home !== 'string' || home === '') return undefined;
1001
+
1002
+ const required = requiredJava(home, { platform });
1003
+ if (required.vm !== undefined && existsSync(required.vm)) return required.vm;
1004
+
1005
+ const javaBinary = platform === 'win32' ? 'javaw.exe' : 'java';
1006
+ const candidates = jdkCandidates(path.dirname(home), javaBinary);
1007
+ if (candidates.length === 0) return undefined;
1008
+ if (required.major === undefined) return candidates[0].path;
1009
+
1010
+ const exact = candidates.find((candidate) => candidate.major === required.major);
1011
+ if (exact !== undefined) return exact.path;
1012
+ const newer = [...candidates].reverse().find((candidate) => candidate.major >= required.major);
1013
+ return (newer ?? candidates[0]).path;
1014
+ }
1015
+
1016
+ /** Аргументы запуска EDT GUI с отдельным workspace. */
1017
+ export function guiArgs({ wsDir, xmx, vm, nativeFormBufferedLayoutRender = false }) {
1018
+ const args = ['-nosplash', '-data', wsDir, '--launcher.appendVmargs'];
1019
+ if (typeof vm === 'string' && vm !== '') args.push('-vm', vm);
1020
+ args.push('-vmargs', `-Xmx${xmx}`);
1021
+ // Требование EDT-MCP для get_form_screenshot: свойство должно идти после
1022
+ // -vmargs. На Windows включает буферизованный рендер форм на всю сессию.
1023
+ if (nativeFormBufferedLayoutRender) args.push('-DnativeFormBufferedLayoutRender=true');
1024
+ return args;
1025
+ }
1026
+
1027
+ /** Аргументы `1cedtcli` для импорта проектов. */
1028
+ export function importArgs({ wsDir, timeout, xmxImport }, scriptPath) {
1029
+ return ['-data', wsDir, '-timeout', String(timeout), '-vmargs', `-Xmx${xmxImport}`, '-file', scriptPath];
1030
+ }
1031
+
1032
+ /** Адрес проверки готовности EDT-MCP (не требует токена). */
1033
+ export function healthUrl(port) {
1034
+ return `http://127.0.0.1:${port}/health`;
1035
+ }
1036
+
1037
+ /** Отвечает ли MCP-сервер EDT на health-запрос. */
1038
+ export async function probeHealth(port, deps = {}) {
1039
+ if (!Number.isInteger(port) || port <= 0) return false;
1040
+ const implementation = deps.fetchImpl ?? globalThis.fetch;
1041
+ if (typeof implementation !== 'function') return false;
1042
+ try {
1043
+ const response = await implementation(healthUrl(port), { signal: AbortSignal.timeout(deps.timeoutMs ?? 3000) });
1044
+ // /health EDT отвечает 200; 3xx/4xx на этом порту — посторонний сервис.
1045
+ return response.status >= 200 && response.status < 300;
1046
+ } catch {
1047
+ return false;
1048
+ }
1049
+ }
1050
+
1051
+ // --- состояние --------------------------------------------------------------
1052
+
1053
+ /**
1054
+ * Состояние окружения по файлам. Живость процесса проверяется только когда
1055
+ * передан `alive` (по умолчанию — настоящая проверка pid).
1056
+ * @returns {{ exists: boolean, label: string, port: number|null, pid: object|null, ready: boolean,
1057
+ * failed: boolean, imported: object|null, progress: object|null }}
1058
+ */
1059
+ export function stateOf(buildDir, deps = {}) {
1060
+ const alive = deps.alive ?? ((pid) => pidAlive(pid, ['1cedt']));
1061
+ const exists = existsSync(buildDir);
1062
+ const port = readPort(buildDir);
1063
+ const pid = readPid(buildDir);
1064
+ const ready = existsSync(filePath(buildDir, 'ready'));
1065
+ const failed = existsSync(filePath(buildDir, 'failed'));
1066
+ const imported = readImported(buildDir);
1067
+ const progress = readProgress(buildDir);
1068
+ const running = pid !== null && alive(pid.pid);
1069
+
1070
+ let label;
1071
+ if (!exists) label = 'absent';
1072
+ else if (failed) label = 'failed';
1073
+ else if (ready) label = running ? 'ready' : 'stale';
1074
+ else if (running) label = 'starting';
1075
+ else if (progress?.edt?.phase === 'failed') label = 'failed';
1076
+ else if (progress?.edt?.phase !== undefined && !['failed', 'ready'].includes(progress.edt.phase)) label = 'starting';
1077
+ else label = 'stopped';
1078
+
1079
+ return { exists, label, port, pid, ready, failed, imported, progress };
1080
+ }
1081
+
1082
+ /** Человеческая длительность от ISO-момента. */
1083
+ export function formatElapsed(sinceIso, nowMs = Date.now()) {
1084
+ const started = Date.parse(String(sinceIso ?? ''));
1085
+ if (Number.isNaN(started)) return '?';
1086
+ const seconds = Math.max(0, Math.round((nowMs - started) / 1000));
1087
+ const minutes = Math.floor(seconds / 60);
1088
+ return minutes > 0 ? `${minutes}m ${String(seconds % 60).padStart(2, '0')}s` : `${seconds}s`;
1089
+ }