@arcadia-eternity/content-sdk 4.3.4 → 4.4.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.
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 +171 -0
  17. package/dist/content-workspace.js +981 -0
  18. package/dist/debug-environments.d.ts +117 -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 +13 -0
  49. package/dist/pack-project.js +179 -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
@@ -0,0 +1,273 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { WorkspaceError } from './workspace.js';
4
+ import { playersFromTeams } from './project-teams.js';
5
+ import { errorCode, errorMessage, isRecord } from './types.js';
6
+ const operations = new Set(['create', 'read', 'events', 'action', 'reset', 'close']);
7
+ const idPattern = /^[a-z0-9][a-z0-9_-]{0,79}$/;
8
+ function fail(code, message) {
9
+ throw new WorkspaceError(code, message);
10
+ }
11
+ function setup(input) {
12
+ if (!isRecord(input) ||
13
+ !Array.isArray(input.teamIds) ||
14
+ input.teamIds.length !== 2 ||
15
+ input.teamIds.some((id) => typeof id !== 'string' || !idPattern.test(id)))
16
+ fail('BATTLE_INPUT_INVALID', '请选择两个已保存的项目队伍标识');
17
+ if (typeof input.seed !== 'string' || !input.seed.length || input.seed.length > 200)
18
+ fail('BATTLE_INPUT_INVALID', '自动调试需要 1–200 字符的固定随机种子');
19
+ return { teamIds: [...input.teamIds], seed: input.seed };
20
+ }
21
+ /** Independent battles over the captured candidate. Never receives the human preview's host or drafts. */
22
+ export class PreviewAutomation {
23
+ prepared;
24
+ readTeams;
25
+ #sessions = new Map();
26
+ #queue = Promise.resolve();
27
+ #closed = false;
28
+ constructor(prepared, { readTeams = async () => prepared.teams } = {}) {
29
+ this.prepared = prepared;
30
+ this.readTeams = readTeams;
31
+ }
32
+ call(operation, input = {}) {
33
+ if (!operations.has(operation))
34
+ return Promise.reject(new WorkspaceError('BATTLE_OPERATION_INVALID', '不支持的战斗调试操作'));
35
+ if (!input || typeof input !== 'object' || Array.isArray(input))
36
+ return Promise.reject(new WorkspaceError('BATTLE_INPUT_INVALID', '战斗参数需要对象'));
37
+ const next = this.#queue
38
+ .catch(() => { })
39
+ .then(async () => {
40
+ if (this.#closed)
41
+ fail('BATTLE_HOST_CLOSED', '试玩宿主已关闭');
42
+ return this.#call(operation, input);
43
+ });
44
+ this.#queue = next;
45
+ return next;
46
+ }
47
+ async #create(input = undefined, previous) {
48
+ const config = setup(input);
49
+ const teams = await this.readTeams();
50
+ const players = playersFromTeams(teams, config.teamIds);
51
+ const teamVersions = Object.fromEntries(config.teamIds.map(id => [id, teams.find(team => team.id === id)?.version]));
52
+ const system = await this.prepared.createBattleSession(config.seed, {
53
+ ai: true,
54
+ players,
55
+ // IDs from the saved teams are deterministic and local to this separate battle.
56
+ runtimeIds: false,
57
+ battleOptions: { timerConfig: { enabled: false } },
58
+ });
59
+ const entry = {
60
+ ...config,
61
+ teamVersions,
62
+ sessionId: previous?.sessionId ?? randomUUID(),
63
+ revision: previous ? previous.revision + 1 : 0,
64
+ playerId: (await system.getState(undefined, true)).players[0].id,
65
+ system,
66
+ events: [],
67
+ cursor: previous?.cursor ?? 0,
68
+ eventFloor: previous?.cursor ?? 0,
69
+ };
70
+ entry.unsubscribe = entry.system.BattleEvent((message) => {
71
+ entry.events.push({ cursor: ++entry.cursor, revision: entry.revision, message });
72
+ if (entry.events.length > 4096)
73
+ entry.eventFloor = entry.events.shift()?.cursor ?? entry.eventFloor;
74
+ }, { showHidden: true });
75
+ try {
76
+ await this.#bounded(entry, () => entry.system.ready());
77
+ entry.lastState = await entry.system.getState(undefined, true);
78
+ return entry;
79
+ }
80
+ catch (error) {
81
+ await this.#dispose(entry);
82
+ throw error;
83
+ }
84
+ }
85
+ async #bounded(entry, action) {
86
+ let timer;
87
+ try {
88
+ return await Promise.race([
89
+ action(),
90
+ new Promise((_, reject) => {
91
+ timer = setTimeout(() => reject(new WorkspaceError('BATTLE_TIMEOUT', '战斗未到达下一个决策点;此自动调试对局已关闭')), 10000);
92
+ }),
93
+ ]);
94
+ }
95
+ catch (error) {
96
+ if (errorCode(error) === 'BATTLE_TIMEOUT') {
97
+ if (this.#sessions.get(entry.sessionId) === entry)
98
+ this.#sessions.delete(entry.sessionId);
99
+ await this.#dispose(entry);
100
+ }
101
+ throw error;
102
+ }
103
+ finally {
104
+ clearTimeout(timer);
105
+ }
106
+ }
107
+ async #dispose(entry) {
108
+ await entry.system.cleanup();
109
+ }
110
+ async #read(entry) {
111
+ let pending;
112
+ if (!entry.failure) {
113
+ try {
114
+ pending = await this.#bounded(entry, () => entry.system.waitForPendingDecision());
115
+ entry.lastState = await entry.system.getState(undefined, true);
116
+ }
117
+ catch (error) {
118
+ if (errorCode(error) === 'BATTLE_TIMEOUT')
119
+ throw error;
120
+ // Keep revision and evidence discoverable after engine failure so reset/close remain version checked.
121
+ entry.failure = {
122
+ code: errorCode(error) ?? 'BATTLE_EXECUTION_FAILED',
123
+ message: errorMessage(error),
124
+ };
125
+ await this.#dispose(entry);
126
+ }
127
+ }
128
+ const failure = entry.failure;
129
+ return {
130
+ sessionId: entry.sessionId,
131
+ revision: entry.revision,
132
+ seed: entry.seed,
133
+ teamIds: [...entry.teamIds],
134
+ teamVersions: { ...entry.teamVersions },
135
+ playerId: entry.playerId,
136
+ state: entry.lastState,
137
+ stateCurrent: !failure,
138
+ ...(failure ? { failure } : {}),
139
+ selections: failure ? [] : (pending?.selections[0] ?? []),
140
+ cursor: entry.cursor,
141
+ };
142
+ }
143
+ async #call(operation, input) {
144
+ if (operation === 'create') {
145
+ if (this.#sessions.size >= 4)
146
+ fail('BATTLE_SESSION_LIMIT', '请先关闭一个自动调试对局(最多四个)');
147
+ const entry = await this.#create(input);
148
+ this.#sessions.set(entry.sessionId, entry);
149
+ return this.#read(entry);
150
+ }
151
+ const sessionId = input.sessionId;
152
+ if (typeof sessionId !== 'string')
153
+ fail('BATTLE_SESSION_UNKNOWN', '自动调试对局不存在或已关闭;用户试玩不接受此操作');
154
+ const entry = this.#sessions.get(sessionId);
155
+ if (!entry)
156
+ fail('BATTLE_SESSION_UNKNOWN', '自动调试对局不存在或已关闭;用户试玩不接受此操作');
157
+ if (operation === 'read')
158
+ return this.#read(entry);
159
+ if (operation === 'events') {
160
+ const afterCursor = typeof input.afterCursor === 'number' ? input.afterCursor : 0, limit = typeof input.limit === 'number' ? input.limit : 50;
161
+ if (!Number.isSafeInteger(afterCursor) ||
162
+ afterCursor < 0 ||
163
+ afterCursor > entry.cursor ||
164
+ !Number.isInteger(limit) ||
165
+ limit < 1 ||
166
+ limit > 100)
167
+ fail('BATTLE_INPUT_INVALID', '事件游标无效,条数须为 1–100');
168
+ if (afterCursor < entry.eventFloor)
169
+ fail('BATTLE_EVENTS_EXPIRED', '事件已过期或对局已重置,请重新读取状态并采用最新游标');
170
+ const events = [];
171
+ let size = 0;
172
+ for (const event of entry.events) {
173
+ if (event.cursor <= afterCursor)
174
+ continue;
175
+ const bytes = Buffer.byteLength(JSON.stringify(event));
176
+ if (size + bytes > 128 * 1024) {
177
+ if (!events.length)
178
+ fail('BATTLE_EVENT_TOO_LARGE', '单条事件超过 128 KiB,请读取战斗状态');
179
+ break;
180
+ }
181
+ events.push(event);
182
+ size += bytes;
183
+ if (events.length === limit)
184
+ break;
185
+ }
186
+ const nextCursor = events.at(-1)?.cursor ?? afterCursor;
187
+ return {
188
+ sessionId: entry.sessionId,
189
+ revision: entry.revision,
190
+ events,
191
+ nextCursor,
192
+ cursor: entry.cursor,
193
+ hasMore: nextCursor < entry.cursor,
194
+ };
195
+ }
196
+ if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision !== entry.revision)
197
+ fail('BATTLE_REVISION_CONFLICT', '对局已改变,请重新读取状态与可用行动;不能重放旧操作');
198
+ if (operation === 'close') {
199
+ await this.#dispose(entry);
200
+ this.#sessions.delete(entry.sessionId);
201
+ return { sessionId: entry.sessionId, revision: entry.revision + 1, closed: true };
202
+ }
203
+ if (operation === 'reset') {
204
+ // Invalid replacement inputs leave this automation battle intact as well.
205
+ const replacement = await this.#create({ seed: input.seed ?? entry.seed, teamIds: input.teamIds ?? entry.teamIds }, entry);
206
+ await this.#dispose(entry);
207
+ this.#sessions.set(entry.sessionId, replacement);
208
+ return this.#read(replacement);
209
+ }
210
+ const current = await this.#read(entry);
211
+ if (!current.selections.some(selection => isDeepStrictEqual(selection, input.selection)))
212
+ fail('BATTLE_ACTION_INVALID', '请选择当前返回的可用行动;不能操作对手或用户的对局');
213
+ entry.revision++;
214
+ try {
215
+ await this.#bounded(entry, () => entry.system.submitAction(input.selection));
216
+ }
217
+ catch (error) {
218
+ if (errorCode(error) === 'BATTLE_TIMEOUT')
219
+ throw error;
220
+ // Submission may already have changed the battle before failing. Never offer replay with the old revision.
221
+ entry.failure = {
222
+ code: errorCode(error) ?? 'BATTLE_EXECUTION_FAILED',
223
+ message: errorMessage(error),
224
+ };
225
+ await this.#dispose(entry);
226
+ }
227
+ return this.#read(entry);
228
+ }
229
+ async close() {
230
+ this.#closed = true;
231
+ await this.#queue.catch(() => { });
232
+ await Promise.allSettled([...this.#sessions.values()].map(entry => this.#dispose(entry)));
233
+ this.#sessions.clear();
234
+ }
235
+ }
236
+ /** The caller resolves endpoint from its bound project's preview receipt; no arbitrary host or method is accepted. */
237
+ export async function callPreviewControl(endpoint, operation, input = {}) {
238
+ if (!operations.has(operation))
239
+ fail('BATTLE_OPERATION_INVALID', '不支持的战斗调试操作');
240
+ let url;
241
+ try {
242
+ url = new URL(endpoint);
243
+ }
244
+ catch {
245
+ fail('PREVIEW_UNAVAILABLE', '试玩地址无效,请重新准备');
246
+ }
247
+ if (url.protocol !== 'http:' ||
248
+ url.hostname !== '127.0.0.1' ||
249
+ !url.port ||
250
+ !/^\/[a-f0-9]{48}$/.test(url.pathname) ||
251
+ url.username ||
252
+ url.password ||
253
+ url.search ||
254
+ url.hash)
255
+ fail('PREVIEW_UNAVAILABLE', '需要此项目的本机试玩宿主');
256
+ let response;
257
+ try {
258
+ response = await fetch(`${url.href}/automation/${operation}`, {
259
+ method: 'POST',
260
+ headers: { 'content-type': 'application/json' },
261
+ body: JSON.stringify(input),
262
+ signal: AbortSignal.timeout(15000),
263
+ redirect: 'error',
264
+ });
265
+ }
266
+ catch {
267
+ fail('PREVIEW_UNAVAILABLE', '试玩宿主不可用或请求超时;请查询任务并重新读取对局,不要直接重放行动');
268
+ }
269
+ const data = (await response.json());
270
+ if (!response.ok)
271
+ fail(typeof data.code === 'string' ? data.code : 'BATTLE_CONTROL_FAILED', typeof data.error === 'string' ? data.error : '战斗调试失败');
272
+ return data.result;
273
+ }
@@ -0,0 +1,24 @@
1
+ import { prepareContentPack } from './testing.js';
2
+ type PreviewOptions = NonNullable<Parameters<typeof prepareContentPack>[1]>;
3
+ interface StartPreviewOptions extends PreviewOptions {
4
+ clientUrl?: string;
5
+ signal?: AbortSignal;
6
+ }
7
+ /** A captured npm candidate, with each battle in a dedicated Worker and each package in Arena.
8
+ * The existing client consumes public metadata and IBattleSystem messages.
9
+ */
10
+ export declare function startPreview(root: string, { clientUrl, signal, ...environmentOptions }?: StartPreviewOptions): Promise<{
11
+ endpoint: string;
12
+ clientPath: string;
13
+ candidate: import("./environment.js").ContentCandidate;
14
+ environmentLock: {
15
+ file: string;
16
+ version: string;
17
+ } | undefined;
18
+ sourceRevisions: Record<string, string>;
19
+ url?: string | undefined;
20
+ close: () => Promise<void>;
21
+ closed: boolean;
22
+ }>;
23
+ export declare function previewCommand(): Promise<void>;
24
+ export {};
@@ -0,0 +1,332 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { createServer } from 'node:http';
4
+ import { randomBytes, createHash } from 'node:crypto';
5
+ import { createReadStream } from 'node:fs';
6
+ import { setGlobalLogger } from '@arcadia-eternity/battle/engine';
7
+ import { buildDisplayCatalog, buildDisplayLocales, mapPresentationResources, } from '@arcadia-eternity/pack-loader/native';
8
+ import { prepareContentPack } from './testing.js';
9
+ import { PreviewAutomation } from './preview-control.js';
10
+ import { AuthorWorkspace } from './workspace.js';
11
+ import { ProjectTeams } from './project-teams.js';
12
+ import { errorCode, errorMessage, isRecord } from './types.js';
13
+ /** A captured npm candidate, with each battle in a dedicated Worker and each package in Arena.
14
+ * The existing client consumes public metadata and IBattleSystem messages.
15
+ */
16
+ export async function startPreview(root, { clientUrl, signal, ...environmentOptions } = {}) {
17
+ const prepared = await prepareContentPack(root, environmentOptions);
18
+ const automation = new PreviewAutomation(prepared, {
19
+ async readTeams() {
20
+ // Candidate rules stay fixed; every new automated battle uses saved teams from the source project.
21
+ const workspace = await AuthorWorkspace.open(environmentOptions.lockRoot ?? root, { watch: false });
22
+ try {
23
+ return await new ProjectTeams(workspace).list();
24
+ }
25
+ finally {
26
+ await workspace.close();
27
+ }
28
+ },
29
+ });
30
+ const token = randomBytes(24).toString('hex');
31
+ let endpoint = '', system, unsubscribe, detachTimers = [], closing;
32
+ let closed = false;
33
+ let events = [], sequence = 0;
34
+ const methodNames = [
35
+ 'ready',
36
+ 'getState',
37
+ 'getAvailableSelection',
38
+ 'submitAction',
39
+ 'isTimerEnabled',
40
+ 'getPlayerTimerState',
41
+ 'getAllPlayerTimerStates',
42
+ 'getTimerConfig',
43
+ 'startAnimation',
44
+ 'endAnimation',
45
+ 'createRuntimeSnapshot',
46
+ 'restoreRuntimeSnapshot',
47
+ ];
48
+ const methods = new Set(methodNames);
49
+ const assets = new Map();
50
+ const catalog = buildDisplayCatalog(prepared.environment.data, [], prepared.environment.presentation);
51
+ for (const pkg of prepared.environment.presentation)
52
+ for (const asset of pkg.resources)
53
+ assets.set(`${pkg.namespace}/${asset.id}`, asset);
54
+ const content = {
55
+ ...catalog,
56
+ locales: buildDisplayLocales(prepared.environment.presentation, {}, catalog),
57
+ };
58
+ function resource(owner, reference) {
59
+ const namespace = typeof reference === 'object' ? reference.namespace : owner;
60
+ const id = typeof reference === 'object' ? reference.id : reference;
61
+ const pkg = prepared.environment.presentation.find(item => item.namespace === namespace || (!item.namespace && item.projectId === namespace));
62
+ const asset = pkg?.manifest.resources.find(item => item.id === id);
63
+ if (!pkg || !asset)
64
+ throw new Error(`RESOURCE_REFERENCE: ${namespace}/${id}`);
65
+ return asset.kind === 'http' ? asset.source : `${endpoint}/assets/${encodeURIComponent(`${pkg.namespace}/${id}`)}`;
66
+ }
67
+ let displayCatalog;
68
+ function publicContent() {
69
+ if (displayCatalog)
70
+ return displayCatalog;
71
+ const result = structuredClone(content);
72
+ for (const kind of ['species', 'skills', 'marks'])
73
+ for (const row of result[kind])
74
+ if (row.presentation) {
75
+ const namespace = row.id.includes(':') ? row.id.slice(0, row.id.indexOf(':')) : '';
76
+ row.presentation = mapPresentationResources(row.presentation, ref => resource(namespace, ref));
77
+ }
78
+ displayCatalog = result;
79
+ return displayCatalog;
80
+ }
81
+ function manualSetup() {
82
+ try {
83
+ return { players: prepared.defaultPlayers() };
84
+ }
85
+ catch (error) {
86
+ const message = errorMessage(error);
87
+ if (!message.startsWith('TEAM_MISSING:'))
88
+ throw error;
89
+ const ids = Object.keys(prepared.teamVersions);
90
+ const players = ids.length
91
+ ? prepared.loadTeams([ids[0], ids[1] ?? ids[0]])
92
+ : [0, 1].map(side => ({ id: String(side).repeat(21), name: side === 0 ? '我方' : '对方', team: [] }));
93
+ return {
94
+ players,
95
+ warning: `默认队伍 ${message.slice('TEAM_MISSING:'.length).trim()} 已不存在。请从项目库选择队伍;自动测试仍按项目配置检查默认队伍。`,
96
+ };
97
+ }
98
+ }
99
+ async function reset(players = undefined, options = {}) {
100
+ // Validate and construct first: a bad test team must not destroy the current match.
101
+ const seed = typeof options.rngSeed === 'string' ? options.rngSeed : 'author-preview';
102
+ const nextSystem = await prepared.createBattleSession(seed, {
103
+ ai: true,
104
+ players: players ?? manualSetup().players,
105
+ runtimeIds: true,
106
+ battleOptions: options,
107
+ });
108
+ unsubscribe?.();
109
+ detachTimers.forEach(detach => detach());
110
+ detachTimers = [];
111
+ try {
112
+ await system?.cleanup();
113
+ }
114
+ catch (error) {
115
+ await nextSystem.cleanup();
116
+ throw error;
117
+ }
118
+ events = [];
119
+ sequence = 0;
120
+ system = nextSystem;
121
+ const initial = await system.getState(undefined, true);
122
+ unsubscribe = system.BattleEvent((message) => {
123
+ events.push({ cursor: ++sequence, message });
124
+ // A bounded stream fails explicitly if a client falls behind; it never skips deltas.
125
+ if (events.length > 4096)
126
+ events.shift();
127
+ }, { viewerId: initial.players[0].id, showHidden: false });
128
+ const timerTypes = [
129
+ 'timerStart',
130
+ 'timerUpdate',
131
+ 'timerPause',
132
+ 'timerResume',
133
+ 'timerTimeout',
134
+ 'teamSelectionTimerStart',
135
+ 'teamSelectionTimerStop',
136
+ 'teamSelectionTimeout',
137
+ 'timerSnapshot',
138
+ 'timerStateChange',
139
+ 'animationStart',
140
+ 'animationEnd',
141
+ ];
142
+ detachTimers = timerTypes.map(type => system.onTimerEvent(type, data => {
143
+ events.push({ cursor: ++sequence, timer: { type, data } });
144
+ if (events.length > 4096)
145
+ events.shift();
146
+ }));
147
+ return system.getState(undefined, true);
148
+ }
149
+ const server = createServer(async (request, response) => {
150
+ const json = (status, value) => {
151
+ response.writeHead(status, { 'content-type': 'application/json' });
152
+ response.end(JSON.stringify(value));
153
+ };
154
+ response.setHeader('cache-control', 'no-store');
155
+ response.setHeader('access-control-allow-origin', '*');
156
+ response.setHeader('access-control-allow-headers', 'content-type');
157
+ response.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS');
158
+ response.setHeader('access-control-allow-private-network', 'true');
159
+ response.setHeader('referrer-policy', 'no-referrer');
160
+ try {
161
+ const url = new URL(request.url ?? '/', endpoint || 'http://127.0.0.1');
162
+ if (!url.pathname.startsWith(`/${token}/`))
163
+ return json(403, { error: 'PREVIEW_UNAUTHORIZED' });
164
+ if (request.method === 'OPTIONS') {
165
+ response.writeHead(204);
166
+ response.end();
167
+ return;
168
+ }
169
+ const route = url.pathname.slice(token.length + 2);
170
+ if (request.method === 'GET' && route === 'content')
171
+ return json(200, {
172
+ content: publicContent(),
173
+ candidate: prepared.candidate,
174
+ teams: prepared.teams,
175
+ draftKey: createHash('sha256')
176
+ .update(resolve(environmentOptions.lockRoot ?? root))
177
+ .digest('hex'),
178
+ ...manualSetup(),
179
+ active: !!system,
180
+ });
181
+ if (request.method === 'GET' && route === 'events') {
182
+ const after = Number(url.searchParams.get('after'));
183
+ if (!Number.isSafeInteger(after) || after < 0 || after < (events[0]?.cursor ?? 1) - 1)
184
+ return json(409, { error: 'PREVIEW_EVENTS_EXPIRED' });
185
+ return json(200, { events: events.filter(event => event.cursor > after), cursor: sequence });
186
+ }
187
+ if (request.method === 'GET' && route.startsWith('assets/')) {
188
+ const asset = assets.get(decodeURIComponent(route.slice(7)));
189
+ if (!asset)
190
+ return json(404, { error: 'RESOURCE_NOT_FOUND' });
191
+ response.writeHead(200, { 'content-type': asset.mime ?? 'application/octet-stream' });
192
+ createReadStream(asset.file)
193
+ .on('error', () => response.destroy())
194
+ .pipe(response);
195
+ return;
196
+ }
197
+ if (request.method !== 'POST')
198
+ return json(404, { error: 'NOT_FOUND' });
199
+ let body = '';
200
+ for await (const chunk of request) {
201
+ body += chunk;
202
+ if (Buffer.byteLength(body) > 2 * 1024 * 1024)
203
+ return json(413, { error: 'REQUEST_TOO_LARGE' });
204
+ }
205
+ const input = JSON.parse(body || '{}');
206
+ if (route.startsWith('automation/'))
207
+ return json(200, { result: await automation.call(route.slice('automation/'.length), input) });
208
+ const { args = [] } = input;
209
+ if (!Array.isArray(args))
210
+ throw new Error('INVALID_ARGUMENTS');
211
+ if (route === 'configure') {
212
+ if (!Array.isArray(args[0]) || args[0].length !== 2)
213
+ throw new Error('请配置双方测试队伍');
214
+ if (args[1] !== undefined && !isRecord(args[1]))
215
+ throw new Error('INVALID_OPTIONS');
216
+ return json(200, { result: await reset(args[0], args[1]) });
217
+ }
218
+ if (route === 'open') {
219
+ const state = system ? await system.getState(undefined, true) : await reset();
220
+ const outcome = events.findLast(event => event.message?.type === 'BATTLE_END')?.message?.data;
221
+ return json(200, { result: { state, cursor: sequence, outcome } });
222
+ }
223
+ if (route === 'cleanup') {
224
+ unsubscribe?.();
225
+ detachTimers.forEach(detach => detach());
226
+ detachTimers = [];
227
+ await system?.cleanup();
228
+ system = undefined;
229
+ return json(200, { result: null });
230
+ }
231
+ if (!methods.has(route) || !system)
232
+ return json(400, { error: 'PREVIEW_NOT_ACTIVE' });
233
+ const method = system[route];
234
+ if (typeof method !== 'function')
235
+ return json(400, { error: 'PREVIEW_NOT_ACTIVE' });
236
+ return json(200, {
237
+ result: (await method.apply(system, args)) ?? null,
238
+ });
239
+ }
240
+ catch (error) {
241
+ const code = errorCode(error);
242
+ json(code === 'BATTLE_REVISION_CONFLICT' ? 409 : 400, {
243
+ error: errorMessage(error),
244
+ ...(code ? { code } : {}),
245
+ });
246
+ }
247
+ });
248
+ async function close() {
249
+ closing ??= (async () => {
250
+ closed = true;
251
+ signal?.removeEventListener('abort', close);
252
+ server.closeAllConnections();
253
+ await new Promise(resolve => server.close(resolve));
254
+ unsubscribe?.();
255
+ detachTimers.forEach(detach => detach());
256
+ await system?.cleanup();
257
+ await automation.close();
258
+ await prepared.dispose();
259
+ })();
260
+ return closing;
261
+ }
262
+ try {
263
+ await new Promise((resolve, reject) => {
264
+ server.once('error', reject);
265
+ server.listen(0, '127.0.0.1', resolve);
266
+ });
267
+ const address = server.address();
268
+ if (!address || typeof address === 'string')
269
+ throw new Error('PREVIEW_ADDRESS_INVALID');
270
+ endpoint = `http://127.0.0.1:${address.port}/${token}`;
271
+ signal?.addEventListener('abort', close, { once: true });
272
+ if (signal?.aborted) {
273
+ await close();
274
+ throw new Error('PREVIEW_CANCELLED');
275
+ }
276
+ const clientPath = `/content/preview?endpoint=${encodeURIComponent(endpoint)}`;
277
+ return {
278
+ endpoint,
279
+ clientPath,
280
+ candidate: prepared.candidate,
281
+ environmentLock: prepared.environmentLock,
282
+ sourceRevisions: prepared.sourceRevisions,
283
+ ...(clientUrl ? { url: new URL(clientPath, clientUrl).href } : {}),
284
+ close,
285
+ get closed() {
286
+ return closed;
287
+ },
288
+ };
289
+ }
290
+ catch (error) {
291
+ await close();
292
+ throw error;
293
+ }
294
+ }
295
+ export async function previewCommand() {
296
+ setGlobalLogger({ debug() { }, info() { }, warn() { }, error() { } });
297
+ const controller = new AbortController();
298
+ const stop = () => controller.abort();
299
+ process.once('SIGINT', stop);
300
+ process.once('SIGTERM', stop);
301
+ process.once('disconnect', stop);
302
+ try {
303
+ const preview = await startPreview(process.cwd(), {
304
+ clientUrl: process.env.ARCADIA_PREVIEW_CLIENT_URL,
305
+ signal: controller.signal,
306
+ environmentId: process.env.ARCADIA_DEBUG_ENVIRONMENT ?? 'default',
307
+ offline: !process.env.ARCADIA_DEBUG_ENVIRONMENT || process.env.ARCADIA_DEBUG_ENVIRONMENT === 'default',
308
+ lockRoot: process.env.ARCADIA_DEBUG_ROOT,
309
+ sources: process.env.ARCADIA_DEBUG_ROOT ? await readSourceMappings(process.env.ARCADIA_DEBUG_ROOT) : {},
310
+ });
311
+ const { endpoint, clientPath, candidate, environmentLock, sourceRevisions, url } = preview;
312
+ console.log(`ARCADIA_RESULT=${JSON.stringify({ preview: { endpoint, clientPath, url }, candidate, environmentLock, sourceRevisions })}`);
313
+ if (!controller.signal.aborted)
314
+ await new Promise(resolve => controller.signal.addEventListener('abort', resolve, { once: true }));
315
+ await preview.close();
316
+ }
317
+ finally {
318
+ process.removeListener('SIGINT', stop);
319
+ process.removeListener('SIGTERM', stop);
320
+ process.removeListener('disconnect', stop);
321
+ }
322
+ }
323
+ async function readSourceMappings(root) {
324
+ try {
325
+ return JSON.parse(await readFile(join(root, '.arcadia/debug-sources.json'), 'utf8'));
326
+ }
327
+ catch (error) {
328
+ if (errorCode(error) === 'ENOENT')
329
+ return {};
330
+ throw error;
331
+ }
332
+ }
@@ -0,0 +1,51 @@
1
+ import { type AuthorWorkspace } from './workspace.js';
2
+ import { z } from 'zod';
3
+ /** Team envelope and portable pet fields are shared with author reference discovery. */
4
+ export declare const teamEnvelopeSchema: z.ZodObject<{
5
+ schemaVersion: z.ZodLiteral<1>;
6
+ id: z.ZodString;
7
+ name: z.ZodString;
8
+ team: z.ZodArray<z.ZodUnknown>;
9
+ }, z.core.$strict>;
10
+ export declare const portablePetSchema: Record<string, unknown>;
11
+ export declare const TeamDocumentSchema: z.ZodObject<{
12
+ schemaVersion: z.ZodLiteral<1>;
13
+ id: z.ZodString;
14
+ name: z.ZodString;
15
+ team: z.ZodArray<z.ZodPipe<z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodTransform<{
16
+ [k: string]: unknown;
17
+ }, Record<string, unknown>>>>;
18
+ }, z.core.$strict>;
19
+ /** Portable team documents contain configurations, never battle or editor identities. */
20
+ export type TeamDocument = z.infer<typeof TeamDocumentSchema>;
21
+ type PortablePet = TeamDocument['team'][number];
22
+ export interface ProjectTeam {
23
+ id: string;
24
+ name: string;
25
+ team: PortablePet[];
26
+ version: string;
27
+ }
28
+ export declare function teamDocument(value: unknown): TeamDocument;
29
+ /** Copy saved team documents into independent players with deterministic, battle-local identities. */
30
+ export declare function playersFromTeams(teamLibrary: ProjectTeam[], ids: string[]): {
31
+ id: string;
32
+ name: string;
33
+ team: {
34
+ id: string;
35
+ }[];
36
+ }[];
37
+ export declare class ProjectTeams {
38
+ workspace: AuthorWorkspace;
39
+ constructor(workspace: AuthorWorkspace);
40
+ file(id: string): string;
41
+ list(): Promise<ProjectTeam[]>;
42
+ save({ document, expectedVersion, }: {
43
+ document: unknown;
44
+ expectedVersion: string | null;
45
+ }): Promise<ProjectTeam>;
46
+ remove({ id, expectedVersion }: {
47
+ id: string;
48
+ expectedVersion: string | null;
49
+ }): Promise<void>;
50
+ }
51
+ export {};