@arcadia-eternity/content-sdk 4.3.3 → 4.4.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.
Files changed (121) hide show
  1. package/README.md +3 -3
  2. package/bin/arcadia-content-mcp.mjs +2 -0
  3. package/bin/arcadia-content.mjs +2 -0
  4. package/dist/asset-inspect.d.ts +30 -0
  5. package/dist/asset-inspect.js +84 -0
  6. package/dist/author-api.d.ts +48 -0
  7. package/dist/author-api.js +128 -0
  8. package/dist/author-reference.d.ts +61 -0
  9. package/dist/author-reference.js +130 -0
  10. package/dist/build-content.d.ts +2 -0
  11. package/dist/build-content.js +29 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/cli.js +81 -0
  14. package/dist/content-query.d.ts +30 -0
  15. package/dist/content-query.js +326 -0
  16. package/dist/content-workspace.d.ts +204 -0
  17. package/dist/content-workspace.js +981 -0
  18. package/dist/debug-environments.d.ts +96 -0
  19. package/dist/debug-environments.js +135 -0
  20. package/dist/demo.d.ts +1 -0
  21. package/dist/demo.js +18 -0
  22. package/dist/effect-build.d.ts +3 -0
  23. package/dist/effect-build.js +44 -0
  24. package/dist/environment-rules.d.ts +7 -0
  25. package/dist/environment-rules.js +94 -0
  26. package/dist/environment.d.ts +48 -0
  27. package/dist/environment.js +184 -0
  28. package/dist/job-journal.d.ts +19 -0
  29. package/dist/job-journal.js +110 -0
  30. package/dist/jobs.d.ts +103 -0
  31. package/dist/jobs.js +626 -0
  32. package/dist/lib/content.d.ts +24 -0
  33. package/dist/lib/content.js +106 -0
  34. package/dist/lib/presentation.d.ts +26 -0
  35. package/dist/lib/presentation.js +252 -0
  36. package/dist/lib/yaml-sharing.d.ts +16 -0
  37. package/dist/lib/yaml-sharing.js +130 -0
  38. package/dist/managed-projects.d.ts +37 -0
  39. package/dist/managed-projects.js +305 -0
  40. package/dist/managed-sources.d.ts +28 -0
  41. package/dist/managed-sources.js +541 -0
  42. package/dist/mcp-contracts.d.ts +420 -0
  43. package/dist/mcp-contracts.js +146 -0
  44. package/dist/mcp.d.ts +2 -0
  45. package/dist/mcp.js +228 -0
  46. package/dist/module-path.d.ts +1 -0
  47. package/dist/module-path.js +8 -0
  48. package/dist/pack-project.d.ts +10 -0
  49. package/dist/pack-project.js +178 -0
  50. package/dist/preview-control.d.ts +17 -0
  51. package/dist/preview-control.js +273 -0
  52. package/dist/preview.d.ts +24 -0
  53. package/dist/preview.js +332 -0
  54. package/dist/project-teams.d.ts +51 -0
  55. package/dist/project-teams.js +106 -0
  56. package/dist/project.d.ts +18 -0
  57. package/dist/project.js +146 -0
  58. package/dist/rename.d.ts +2 -0
  59. package/dist/rename.js +128 -0
  60. package/dist/setup.d.ts +2 -0
  61. package/dist/setup.js +117 -0
  62. package/dist/source-lock.d.ts +9 -0
  63. package/dist/source-lock.js +117 -0
  64. package/dist/template/README.md +2 -0
  65. package/dist/template/docs/presentation.md +3 -3
  66. package/dist/template/package.json +3 -7
  67. package/dist/template/test/pack.test.mjs +10 -7
  68. package/dist/testing.d.ts +58 -0
  69. package/dist/testing.js +205 -0
  70. package/dist/types.d.ts +5 -0
  71. package/dist/types.js +14 -0
  72. package/dist/workbench-context.d.ts +10 -0
  73. package/dist/workbench-context.js +27 -0
  74. package/dist/workspace-cli.d.ts +1 -0
  75. package/dist/workspace-cli.js +66 -0
  76. package/dist/workspace-materials.d.ts +19 -0
  77. package/dist/workspace-materials.js +165 -0
  78. package/dist/workspace.d.ts +190 -0
  79. package/dist/workspace.js +726 -0
  80. package/package.json +34 -27
  81. package/dist/asset-inspect.mjs +0 -67
  82. package/dist/author-api.mjs +0 -112
  83. package/dist/author-reference.mjs +0 -121
  84. package/dist/build-content.mjs +0 -30
  85. package/dist/cli.mjs +0 -76
  86. package/dist/content-query.mjs +0 -283
  87. package/dist/content-workspace.d.mts +0 -161
  88. package/dist/content-workspace.mjs +0 -936
  89. package/dist/debug-environments.mjs +0 -154
  90. package/dist/demo.mjs +0 -22
  91. package/dist/effect-build.d.mts +0 -2
  92. package/dist/effect-build.mjs +0 -46
  93. package/dist/environment-rules.d.mts +0 -5
  94. package/dist/environment-rules.mjs +0 -92
  95. package/dist/environment.mjs +0 -183
  96. package/dist/job-journal.mjs +0 -94
  97. package/dist/jobs.mjs +0 -579
  98. package/dist/lib/content.mjs +0 -95
  99. package/dist/lib/presentation.mjs +0 -240
  100. package/dist/lib/yaml-sharing.mjs +0 -101
  101. package/dist/managed-projects.d.mts +0 -35
  102. package/dist/managed-projects.mjs +0 -303
  103. package/dist/managed-sources.d.mts +0 -19
  104. package/dist/managed-sources.mjs +0 -503
  105. package/dist/mcp-contracts.mjs +0 -153
  106. package/dist/mcp.mjs +0 -369
  107. package/dist/pack-project.mjs +0 -157
  108. package/dist/preview-control.mjs +0 -260
  109. package/dist/preview.mjs +0 -313
  110. package/dist/project-teams.mjs +0 -98
  111. package/dist/project.mjs +0 -140
  112. package/dist/rename.mjs +0 -112
  113. package/dist/setup.mjs +0 -134
  114. package/dist/source-lock.mjs +0 -103
  115. package/dist/testing.mjs +0 -204
  116. package/dist/workbench-context.mjs +0 -18
  117. package/dist/workspace-cli.mjs +0 -60
  118. package/dist/workspace-materials.mjs +0 -153
  119. package/dist/workspace.mjs +0 -684
  120. /package/dist/{index.d.mts → index.d.ts} +0 -0
  121. /package/dist/{index.mjs → index.js} +0 -0
package/dist/jobs.js ADDED
@@ -0,0 +1,626 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { cp, mkdir, mkdtemp, rm, symlink, readFile } from 'node:fs/promises';
5
+ import { join, dirname } from 'node:path';
6
+ import { tmpdir } from 'node:os';
7
+ import { AuthorWorkspace, WorkspaceError, diagnostic } from './workspace.js';
8
+ import { JobJournal } from './job-journal.js';
9
+ import { siblingModulePath } from './module-path.js';
10
+ const cli = siblingModulePath('cli');
11
+ const terminal = new Set(['succeeded', 'failed', 'cancelled', 'interrupted']);
12
+ const outputLimit = 1024 * 1024;
13
+ function queryError(message) {
14
+ throw new WorkspaceError('TASK_QUERY_INVALID', message);
15
+ }
16
+ function integer(value, minimum, maximum, name) {
17
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum)
18
+ queryError(`${name} 超出范围`);
19
+ return value;
20
+ }
21
+ function outputRange(job) {
22
+ const text = typeof job.output === 'string' ? job.output : '';
23
+ // Receipts written by older versions have no cursor; their retained output starts at zero.
24
+ const end = Number.isSafeInteger(job.outputCursor) ? Math.max(job.outputCursor, text.length) : text.length;
25
+ return { text, start: end - text.length, end };
26
+ }
27
+ function resultSummary(result) {
28
+ if (!result || typeof result !== 'object')
29
+ return undefined;
30
+ const record = result;
31
+ const summary = {};
32
+ for (const key of [
33
+ 'candidate',
34
+ 'preview',
35
+ 'environmentLock',
36
+ 'sourceRevisions',
37
+ 'filename',
38
+ 'integrity',
39
+ 'shasum',
40
+ 'winner',
41
+ 'turns',
42
+ 'environmentRevision',
43
+ 'packageName',
44
+ ])
45
+ if (record[key] !== undefined)
46
+ summary[key] = structuredClone(record[key]);
47
+ if (Array.isArray(record.files))
48
+ summary.fileCount = record.files.length;
49
+ return summary;
50
+ }
51
+ function jobSummary(job, details = false) {
52
+ const { start, end } = outputRange(job);
53
+ const summary = {
54
+ jobId: job.jobId,
55
+ kind: job.kind,
56
+ state: job.state,
57
+ phase: job.phase ?? job.state,
58
+ stale: !!job.stale,
59
+ sourceRevision: job.sourceRevision,
60
+ contentRevision: job.contentRevision,
61
+ environmentId: job.environmentId,
62
+ createdAt: job.createdAt,
63
+ ...(job.finishedAt ? { finishedAt: job.finishedAt } : {}),
64
+ diagnosticCount: job.diagnostics.length,
65
+ outputStartCursor: start,
66
+ outputCursor: end,
67
+ };
68
+ if (details) {
69
+ summary.diagnostics = job.diagnostics.slice(0, 100).map((item) => ({
70
+ ...item,
71
+ message: typeof item.message === 'string' ? item.message.slice(0, 4000) : item.message,
72
+ }));
73
+ summary.diagnosticsTruncated =
74
+ job.diagnostics.length > 100 || job.diagnostics.some(item => item.message?.length > 4000);
75
+ const result = resultSummary(job.result);
76
+ if (result)
77
+ summary.result = result;
78
+ }
79
+ return summary;
80
+ }
81
+ /** Fixed author commands; no renderer or MCP-provided executable strings. */
82
+ export class AuthorJobs {
83
+ workspace;
84
+ execute;
85
+ env;
86
+ executable;
87
+ #jobs = new Map();
88
+ #active;
89
+ #closed = false;
90
+ #starting;
91
+ #changed;
92
+ #previews = new Map();
93
+ #journal;
94
+ #sync = Promise.resolve();
95
+ #timer;
96
+ #waiters = new Set();
97
+ constructor(workspace, { execute = false, env = process.env, executable = process.execPath, } = {}) {
98
+ this.workspace = workspace;
99
+ this.execute = execute;
100
+ this.env = Object.fromEntries(Object.entries(env).filter(([key]) => /^(PATH|HOME|USERPROFILE|SystemRoot|WINDIR|TEMP|TMP|TMPDIR|LANG|LC_ALL|ARCADIA_NPM_CLI|ARCADIA_PREVIEW_CLIENT_URL|npm_config_cache)$/i.test(key)));
101
+ this.executable = executable;
102
+ this.#changed = ({ file } = {}) => {
103
+ for (const { job } of this.#jobs.values())
104
+ if (terminal.has(job.state) &&
105
+ !(job.kind === 'preview' && (file?.startsWith('debug/teams/') || file === job.result?.environmentLock?.file)))
106
+ job.stale = true;
107
+ this.#notify();
108
+ };
109
+ workspace.on('change', this.#changed);
110
+ if (!workspace.readOnly && workspace.root)
111
+ this.#journal = new JobJournal(workspace.root);
112
+ }
113
+ get closed() {
114
+ return this.#closed;
115
+ }
116
+ get hasLivePreviews() {
117
+ return this.#previews.size > 0;
118
+ }
119
+ async initialize() {
120
+ await this.refresh();
121
+ this.#timer = setInterval(() => {
122
+ void this.#checkpoint().catch(() => { });
123
+ }, 250);
124
+ this.#timer.unref();
125
+ }
126
+ #checkpoint() {
127
+ this.#sync = this.#sync
128
+ .catch(() => { })
129
+ .then(async () => {
130
+ if (!this.#journal)
131
+ return;
132
+ for (const { job, controller } of this.#jobs.values()) {
133
+ if (!controller)
134
+ continue;
135
+ if ((!terminal.has(job.state) || this.#previews.has(job.jobId)) && (await this.#journal.cancelled(job.jobId)))
136
+ this.cancel(job.jobId);
137
+ await this.#journal.save(job, this.#previews.has(job.jobId));
138
+ }
139
+ });
140
+ return this.#sync;
141
+ }
142
+ async #dependenciesCurrent(job) {
143
+ const revisions = Object.entries(job.result?.sourceRevisions ?? {});
144
+ if (!revisions.length)
145
+ return true;
146
+ try {
147
+ const mappings = JSON.parse(await readFile(join(this.workspace.root, '.arcadia/debug-sources.json'), 'utf8'));
148
+ for (const [name, revision] of revisions) {
149
+ if (typeof mappings[name] !== 'string')
150
+ return false;
151
+ const source = await AuthorWorkspace.open(mappings[name], { watch: false });
152
+ try {
153
+ if ((await source.revision({ contentOnly: true })) !== revision)
154
+ return false;
155
+ }
156
+ finally {
157
+ await source.close();
158
+ }
159
+ }
160
+ return true;
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ async refresh() {
167
+ await this.#checkpoint();
168
+ if (!this.#journal)
169
+ return;
170
+ const revision = await this.workspace.revision();
171
+ const contentRevision = await this.workspace.revision({ contentOnly: true });
172
+ for (const { job } of this.#jobs.values())
173
+ if (terminal.has(job.state))
174
+ job.stale ||=
175
+ job.kind === 'preview'
176
+ ? job.contentRevision !== contentRevision || !(await this.#dependenciesCurrent(job))
177
+ : job.sourceRevision !== revision;
178
+ await this.#refreshReceipts({ revision, contentRevision });
179
+ }
180
+ async #refreshReceipts(revisions) {
181
+ if (!this.#journal)
182
+ return;
183
+ const receipts = await this.#journal.read();
184
+ const present = new Set(receipts.map(receipt => receipt.job.jobId));
185
+ for (const [id, control] of this.#jobs)
186
+ if (!control.controller && !present.has(id))
187
+ this.#jobs.delete(id);
188
+ for (const receipt of receipts) {
189
+ if (this.#jobs.get(receipt.job.jobId)?.controller)
190
+ continue;
191
+ receipt.job.stale ||= this.#jobs.get(receipt.job.jobId)?.job.stale ?? false;
192
+ if (revisions)
193
+ receipt.job.stale ||=
194
+ receipt.job.kind === 'preview'
195
+ ? receipt.job.contentRevision !== revisions.contentRevision ||
196
+ !(await this.#dependenciesCurrent(receipt.job))
197
+ : receipt.job.sourceRevision !== revisions.revision;
198
+ this.#jobs.set(receipt.job.jobId, { job: receipt.job, live: receipt.live });
199
+ }
200
+ }
201
+ async start({ kind, sourceRevision, environmentId = 'default', }) {
202
+ if (this.workspace.assertWritable)
203
+ await this.workspace.assertWritable();
204
+ if (this.#closed)
205
+ throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭');
206
+ if (!['check', 'test', 'demo', 'preview', 'pack'].includes(kind))
207
+ throw new WorkspaceError('TASK_INVALID', '不支持的作者任务');
208
+ if (kind !== 'check' && !this.execute)
209
+ throw new WorkspaceError('EXECUTION_DISABLED', '此会话未启用项目代码执行');
210
+ if (this.#active)
211
+ throw new WorkspaceError('TASK_BUSY', '请等待或取消当前任务');
212
+ if (kind === 'preview' && this.#previews.size >= 4)
213
+ throw new WorkspaceError('PREVIEW_LIMIT', '请先停止一个旧试玩,再准备新候选');
214
+ if (typeof environmentId !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(environmentId))
215
+ throw new WorkspaceError('ENVIRONMENT_INVALID', '环境标识无效');
216
+ const jobId = randomUUID();
217
+ // Reserve before fingerprinting so concurrent starts cannot race.
218
+ this.#active = jobId;
219
+ let started = () => { };
220
+ this.#starting = new Promise(resolve => {
221
+ started = resolve;
222
+ });
223
+ try {
224
+ const revision = await this.workspace.revision();
225
+ if (this.#closed)
226
+ throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭');
227
+ if (sourceRevision && sourceRevision !== revision)
228
+ throw new WorkspaceError('REVISION_CONFLICT', '项目已改变,请重新读取');
229
+ const job = {
230
+ jobId,
231
+ kind,
232
+ sourceRevision: revision,
233
+ contentRevision: await this.workspace.revision({ contentOnly: true }),
234
+ environmentId,
235
+ preparationRevision: await this.workspace.revision({
236
+ contentOnly: true,
237
+ excludeFile: environmentId === 'default' ? undefined : `debug/environments/${environmentId}.package-lock.json`,
238
+ }),
239
+ state: 'queued',
240
+ phase: 'queued',
241
+ stale: false,
242
+ output: '',
243
+ outputCursor: 0,
244
+ diagnostics: [],
245
+ createdAt: Date.now(),
246
+ };
247
+ const control = { job, controller: new AbortController() };
248
+ this.#jobs.set(jobId, control);
249
+ for (const [id, value] of this.#jobs) {
250
+ if (this.#jobs.size <= 30)
251
+ break;
252
+ if (terminal.has(value.job.state) && !this.#previews.has(id) && !value.live) {
253
+ this.#jobs.delete(id);
254
+ await this.#journal?.remove(id);
255
+ }
256
+ }
257
+ await this.#checkpoint();
258
+ control.done = this.#run(control).finally(() => {
259
+ this.#active = undefined;
260
+ });
261
+ return this.get(jobId);
262
+ }
263
+ catch (error) {
264
+ this.#jobs.delete(jobId);
265
+ this.#active = undefined;
266
+ throw error;
267
+ }
268
+ finally {
269
+ started();
270
+ this.#starting = undefined;
271
+ }
272
+ }
273
+ get(jobId) {
274
+ const control = this.#jobs.get(jobId);
275
+ if (!control)
276
+ throw new WorkspaceError('TASK_UNKNOWN', '任务不存在或已过期');
277
+ return structuredClone(control.job);
278
+ }
279
+ list() {
280
+ return [...this.#jobs.keys()].map(id => this.get(id)).sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
281
+ }
282
+ /** Compact task discovery; listing never switches or replaces a desktop preview. */
283
+ async queryJobs({ offset = 0, limit = 20, state, kind, } = {}) {
284
+ integer(offset, 0, Number.MAX_SAFE_INTEGER, 'offset');
285
+ integer(limit, 1, 100, 'limit');
286
+ if (state !== undefined && !['queued', 'running', ...terminal].includes(state))
287
+ queryError('任务状态无效');
288
+ if (kind !== undefined && !['check', 'test', 'demo', 'preview', 'pack'].includes(kind))
289
+ queryError('任务类型无效');
290
+ await this.refresh();
291
+ const rows = [...this.#jobs.values()]
292
+ .map(({ job }) => job)
293
+ .filter(job => (!state || job.state === state) && (!kind || job.kind === kind))
294
+ .sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0) || a.jobId.localeCompare(b.jobId));
295
+ return {
296
+ total: rows.length,
297
+ offset,
298
+ nextOffset: offset + limit < rows.length ? offset + limit : null,
299
+ items: rows.slice(offset, offset + limit).map(job => jobSummary(job)),
300
+ };
301
+ }
302
+ /** Wait for changes without repeatedly hashing every project file. */
303
+ async queryJob({ jobId, waitMs = 0, afterCursor, includeOutput = false, limit = 16384, }) {
304
+ integer(waitMs, 0, 10000, 'waitMs');
305
+ integer(limit, 1, 65536, 'limit');
306
+ if (afterCursor !== undefined)
307
+ integer(afterCursor, 0, Number.MAX_SAFE_INTEGER, 'afterCursor');
308
+ if (typeof includeOutput !== 'boolean')
309
+ queryError('includeOutput 需要布尔值');
310
+ await this.refresh();
311
+ let job = this.get(jobId);
312
+ if (afterCursor !== undefined && afterCursor > outputRange(job).end)
313
+ queryError('日志游标超出当前输出');
314
+ const observed = JSON.stringify(jobSummary(job, true));
315
+ const deadline = Date.now() + waitMs;
316
+ while (!this.#closed &&
317
+ !terminal.has(job.state) &&
318
+ (afterCursor === undefined || outputRange(job).end <= afterCursor) &&
319
+ JSON.stringify(jobSummary(job, true)) === observed &&
320
+ Date.now() < deadline) {
321
+ await this.#wait(Math.min(250, deadline - Date.now()));
322
+ // Peer receipts are checkpointed by their owner. This does not mutate peer tasks.
323
+ await this.#refreshReceipts();
324
+ job = this.get(jobId);
325
+ }
326
+ const summary = jobSummary(job, true);
327
+ if (includeOutput)
328
+ summary.output = this.#output(jobId, afterCursor ?? 0, limit);
329
+ return summary;
330
+ }
331
+ async readJobOutput({ jobId, cursor = 0, limit = 16384 }) {
332
+ integer(cursor, 0, Number.MAX_SAFE_INTEGER, 'cursor');
333
+ integer(limit, 1, 65536, 'limit');
334
+ await this.#refreshReceipts();
335
+ return this.#output(jobId, cursor, limit);
336
+ }
337
+ #output(jobId, cursor, limit) {
338
+ const { text, start, end } = outputRange(this.get(jobId));
339
+ if (cursor > end)
340
+ queryError('日志游标超出当前输出');
341
+ const first = Math.max(cursor, start);
342
+ const nextCursor = Math.min(first + limit, end);
343
+ return {
344
+ jobId,
345
+ text: text.slice(first - start, nextCursor - start),
346
+ cursor: first,
347
+ nextCursor,
348
+ endCursor: end,
349
+ truncated: cursor < start,
350
+ hasMore: nextCursor < end,
351
+ unit: 'utf16',
352
+ };
353
+ }
354
+ #notify() {
355
+ for (const wake of this.#waiters)
356
+ wake();
357
+ }
358
+ #wait(milliseconds) {
359
+ return new Promise(resolve => {
360
+ const wake = () => {
361
+ clearTimeout(timer);
362
+ this.#waiters.delete(wake);
363
+ resolve();
364
+ };
365
+ const timer = setTimeout(wake, milliseconds);
366
+ this.#waiters.add(wake);
367
+ });
368
+ }
369
+ cancel(jobId) {
370
+ const control = this.#jobs.get(jobId);
371
+ if (!control)
372
+ throw new WorkspaceError('TASK_UNKNOWN', '任务不存在');
373
+ if (!control.controller) {
374
+ if (!terminal.has(control.job.state) || control.live)
375
+ return (this.#journal?.requestCancel(jobId) ?? Promise.resolve()).then(() => this.get(jobId));
376
+ return this.get(jobId);
377
+ }
378
+ if (!terminal.has(control.job.state) || this.#previews.has(jobId)) {
379
+ control.controller.abort();
380
+ if (this.#previews.has(jobId))
381
+ control.job.state = 'cancelled';
382
+ this.#notify();
383
+ }
384
+ return this.get(jobId);
385
+ }
386
+ async #run({ job, controller }) {
387
+ if (!controller)
388
+ throw new WorkspaceError('TASK_INVALID', '任务缺少控制信号');
389
+ const signal = controller.signal;
390
+ const timeout = setTimeout(() => controller.abort(), 180000);
391
+ let state = 'succeeded';
392
+ let capture;
393
+ try {
394
+ job.state = 'running';
395
+ job.phase = 'preparing';
396
+ this.#notify();
397
+ if (job.kind === 'preview') {
398
+ capture = await mkdtemp(join(tmpdir(), 'arcadia-author-candidate-'));
399
+ for (const entry of await this.workspace.files()) {
400
+ if (signal.aborted)
401
+ throw new WorkspaceError('TASK_CANCELLED', '任务已取消');
402
+ if (entry.error)
403
+ throw new WorkspaceError('SOURCE_INVALID', entry.error, entry.file);
404
+ const target = join(capture, entry.file);
405
+ await mkdir(dirname(target), { recursive: true });
406
+ await cp(await this.workspace.path(entry.file), target);
407
+ }
408
+ await symlink(join(this.workspace.root, 'node_modules'), join(capture, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
409
+ if ((await this.workspace.revision({ contentOnly: true })) !== job.contentRevision)
410
+ throw new WorkspaceError('PREVIEW_STALE', '复制候选期间源码已改变,请重试');
411
+ }
412
+ if (job.kind === 'check') {
413
+ const snapshot = await this.workspace.snapshot();
414
+ job.diagnostics.push(...snapshot.diagnostics);
415
+ if (snapshot.diagnostics.length)
416
+ throw new WorkspaceError('CHECK_FAILED', '源数据检查失败');
417
+ await this.#process([cli, 'check'], job, signal);
418
+ }
419
+ else if (job.kind === 'pack')
420
+ await this.#process([cli, 'pack'], job, signal);
421
+ else {
422
+ await this.#process([cli, 'build'], job, signal, false, capture);
423
+ if (job.kind === 'demo' || job.kind === 'preview')
424
+ await this.#process([cli, job.kind], job, signal, job.kind === 'preview', capture);
425
+ else {
426
+ const files = (await this.workspace.files()).filter(entry => /^(test|tests)\/.+\.test\.(mjs|js|cjs)$/.test(entry.file));
427
+ if (!files.length)
428
+ throw new WorkspaceError('TESTS_MISSING', '未发现 test/ 或 tests/ 下的 *.test.mjs/js/cjs 场景');
429
+ await this.#process(['--test', '--test-reporter=tap', ...files.map(entry => entry.file)], job, signal);
430
+ }
431
+ }
432
+ }
433
+ catch (error) {
434
+ state = signal.aborted ? 'cancelled' : 'failed';
435
+ job.diagnostics.push(diagnostic(error));
436
+ }
437
+ finally {
438
+ clearTimeout(timeout);
439
+ try {
440
+ if (job.kind === 'preview' && job.result?.environmentLock) {
441
+ const expected = job.result.environmentLock;
442
+ const actual = await this.workspace.read(expected.file);
443
+ const revision = await this.workspace.revision({ contentOnly: true, excludeFile: expected.file });
444
+ if (actual.version === expected.version && revision === job.preparationRevision)
445
+ job.contentRevision = await this.workspace.revision({ contentOnly: true });
446
+ }
447
+ job.stale =
448
+ job.kind === 'preview'
449
+ ? (await this.workspace.revision({ contentOnly: true })) !== job.contentRevision ||
450
+ !(await this.#dependenciesCurrent(job))
451
+ : (await this.workspace.revision()) !== job.sourceRevision;
452
+ if (job.stale && job.kind === 'preview') {
453
+ controller.abort();
454
+ state = 'failed';
455
+ job.diagnostics.push(diagnostic(new WorkspaceError('PREVIEW_STALE', '准备期间源码已改变,请重新试玩')));
456
+ }
457
+ }
458
+ catch (error) {
459
+ job.stale = true;
460
+ job.diagnostics.push(diagnostic(error));
461
+ }
462
+ job.finishedAt = new Date().toISOString();
463
+ if (capture && !this.#previews.has(job.jobId))
464
+ await rm(capture, { recursive: true, force: true });
465
+ job.state = state;
466
+ job.phase = state === 'succeeded' && job.kind === 'preview' ? 'ready' : 'finished';
467
+ this.#notify();
468
+ }
469
+ }
470
+ async #process(args, job, signal, preview = false, capture = undefined) {
471
+ if (signal.aborted)
472
+ throw new WorkspaceError('TASK_CANCELLED', '任务已取消');
473
+ const phases = {
474
+ check: 'checking',
475
+ build: 'building',
476
+ pack: 'packing',
477
+ preview: 'starting-preview',
478
+ demo: 'running-demo',
479
+ };
480
+ job.phase = phases[args[1]] ?? 'testing';
481
+ this.#notify();
482
+ await new Promise((resolve, reject) => {
483
+ const child = spawn(this.executable, args, {
484
+ cwd: capture ?? this.workspace.root,
485
+ env: {
486
+ ...this.env,
487
+ ELECTRON_RUN_AS_NODE: '1',
488
+ ARCADIA_AUTHOR_RESULT: '1',
489
+ ...(preview ? { ARCADIA_DEBUG_ENVIRONMENT: job.environmentId, ARCADIA_DEBUG_ROOT: this.workspace.root } : {}),
490
+ },
491
+ stdio: ['ignore', 'pipe', 'pipe', ...(preview ? ['ipc'] : [])],
492
+ windowsHide: true,
493
+ detached: process.platform !== 'win32',
494
+ });
495
+ let killTimer;
496
+ const kill = (force) => {
497
+ try {
498
+ if (child.pid === undefined)
499
+ return;
500
+ if (process.platform !== 'win32')
501
+ process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM');
502
+ else
503
+ child.kill(force ? 'SIGKILL' : 'SIGTERM');
504
+ }
505
+ catch {
506
+ /* Already exited. */
507
+ }
508
+ };
509
+ const abort = () => {
510
+ kill(false);
511
+ killTimer = setTimeout(() => kill(true), 1500);
512
+ };
513
+ signal.addEventListener('abort', abort, { once: true });
514
+ if (signal.aborted)
515
+ abort();
516
+ let buffer = '', ready = false;
517
+ const output = (text) => {
518
+ if (!text)
519
+ return;
520
+ job.outputCursor = outputRange(job).end + text.length;
521
+ job.output = (job.output + text).slice(-outputLimit);
522
+ this.#notify();
523
+ if (!preview || ready)
524
+ return;
525
+ buffer += text;
526
+ let newline;
527
+ while ((newline = buffer.indexOf('\n')) >= 0) {
528
+ const line = buffer.slice(0, newline);
529
+ buffer = buffer.slice(newline + 1);
530
+ if (!line.startsWith('ARCADIA_RESULT='))
531
+ continue;
532
+ try {
533
+ const result = JSON.parse(line.slice('ARCADIA_RESULT='.length));
534
+ if (!result.preview?.endpoint || signal.aborted)
535
+ continue;
536
+ job.result = result;
537
+ ready = true;
538
+ resolve();
539
+ }
540
+ catch {
541
+ /* Preserve incomplete or malformed output for diagnosis. */
542
+ }
543
+ }
544
+ };
545
+ let finished = () => { };
546
+ if (preview)
547
+ this.#previews.set(job.jobId, new Promise(resolve => {
548
+ finished = resolve;
549
+ }));
550
+ for (const stream of [child.stdout, child.stderr]) {
551
+ if (!stream)
552
+ continue;
553
+ const decoder = new StringDecoder('utf8');
554
+ stream.on('data', (chunk) => output(decoder.write(chunk)));
555
+ stream.on('end', () => output(decoder.end()));
556
+ }
557
+ child.once('error', reject);
558
+ child.once('close', code => {
559
+ if (preview) {
560
+ this.#previews.delete(job.jobId);
561
+ const released = capture ? rm(capture, { recursive: true, force: true }) : Promise.resolve();
562
+ void released.then(finished, (error) => {
563
+ job.diagnostics.push(diagnostic(error));
564
+ finished();
565
+ });
566
+ if (ready) {
567
+ job.state = signal.aborted ? 'cancelled' : 'failed';
568
+ this.#notify();
569
+ if (!signal.aborted)
570
+ job.diagnostics.push(diagnostic(new WorkspaceError('PREVIEW_EXITED', '试玩进程已退出,请重新准备')));
571
+ }
572
+ }
573
+ clearTimeout(killTimer);
574
+ signal.removeEventListener('abort', abort);
575
+ for (const raw of job.output.split('\n')) {
576
+ const line = raw.replace(/^# /, '');
577
+ if (line.startsWith('ARCADIA_RESULT=')) {
578
+ try {
579
+ job.result = JSON.parse(line.slice('ARCADIA_RESULT='.length));
580
+ }
581
+ catch {
582
+ /* Keep malformed output in the log. */
583
+ }
584
+ }
585
+ const match = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.+)$/.exec(line);
586
+ if (match)
587
+ job.diagnostics.push({
588
+ code: match[4],
589
+ severity: 'error',
590
+ file: match[1],
591
+ line: Number(match[2]),
592
+ column: Number(match[3]),
593
+ message: match[5],
594
+ });
595
+ }
596
+ if (code === 0 && !signal.aborted)
597
+ resolve();
598
+ else
599
+ reject(new WorkspaceError(signal.aborted ? 'TASK_CANCELLED' : 'TASK_FAILED', signal.aborted ? '任务已取消或超过三分钟' : `作者命令失败(${code}),请查看诊断与输出`));
600
+ });
601
+ });
602
+ }
603
+ /** Stop previews owned by this host and wait for their processes and temporary files to be released. */
604
+ async stopPreviews() {
605
+ await this.#starting;
606
+ const previews = [...this.#jobs.values()].filter(({ job, controller }) => job.kind === 'preview' && controller);
607
+ const released = [...this.#previews.values()];
608
+ for (const { job } of previews)
609
+ this.cancel(job.jobId);
610
+ await Promise.allSettled(previews.map(control => control.done));
611
+ await Promise.allSettled([...released, ...this.#previews.values()]);
612
+ }
613
+ async close() {
614
+ this.#closed = true;
615
+ this.#notify();
616
+ this.workspace.off('change', this.#changed);
617
+ await this.#starting;
618
+ clearInterval(this.#timer);
619
+ for (const control of this.#jobs.values())
620
+ if (control.controller && (!terminal.has(control.job.state) || this.#previews.has(control.job.jobId)))
621
+ control.controller.abort();
622
+ await Promise.allSettled([...this.#jobs.values()].map(control => control.done));
623
+ await Promise.allSettled([...this.#previews.values()]);
624
+ await this.#checkpoint();
625
+ }
626
+ }
@@ -0,0 +1,24 @@
1
+ import type { Document } from 'yaml';
2
+ declare const sourceKinds: readonly ["species", "skills", "marks", "behaviors", "presentations", "resources"];
3
+ type SourceKind = (typeof sourceKinds)[number];
4
+ export interface ContentSource {
5
+ kind: SourceKind;
6
+ file: string;
7
+ text: string;
8
+ document: Document | undefined;
9
+ value: unknown;
10
+ records: Array<Record<string, unknown> & {
11
+ id: string;
12
+ }>;
13
+ }
14
+ /** Editable source files; each file may hold one record or an array of records. */
15
+ export declare function readContentSources(root: string): Promise<ContentSource[]>;
16
+ /** File names and grouping do not enter runtime IDs or record ordering. */
17
+ export declare function assembleContent(sources: ContentSource[]): {
18
+ data: {
19
+ [k: string]: (Record<string, unknown> & {
20
+ id: string;
21
+ })[];
22
+ };
23
+ };
24
+ export {};