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