@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
@@ -1,684 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- import { createReadStream } from 'node:fs'
3
- import { lstat, mkdir, readdir, readFile, realpath, unlink } from 'node:fs/promises'
4
- import { dirname, extname, isAbsolute, join, relative, sep } from 'node:path'
5
- import { EventEmitter } from 'node:events'
6
- import { isDeepStrictEqual } from 'node:util'
7
- import YAML from 'yaml'
8
- import chokidar from 'chokidar'
9
- import writeFileAtomic from 'write-file-atomic'
10
- import { resourceReferences, bindingPresentation, validResourceId, validAssetPath } from './lib/presentation.mjs'
11
- import { yamlSharing, recordSharing, changedSharedField, sharingSignature } from './lib/yaml-sharing.mjs'
12
- import { withSourceLock } from './source-lock.mjs'
13
-
14
- const ignored = new Set(['node_modules', 'dist', '.git', '.arcadia', '.DS_Store', 'Thumbs.db'])
15
- const kinds = ['species', 'skills', 'marks', 'behaviors', 'presentations', 'resources']
16
- const basePackageName = '@arcadia-eternity/data-pack-base'
17
- const baseProjectId = 'arcadia-eternity.base'
18
- const isBaseManifest = manifest => manifest.name === basePackageName || manifest.arcadia?.projectId === baseProjectId
19
- const textLimit = 2 * 1024 * 1024
20
- const hash = value => createHash('sha256').update(value).digest('hex')
21
- const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
22
- export class WorkspaceError extends Error {
23
- constructor(code, message, file) {
24
- super(message)
25
- this.code = code
26
- this.file = file
27
- }
28
- }
29
- const fail = (code, message, file) => {
30
- throw new WorkspaceError(code, message, file)
31
- }
32
- export function diagnostic(error) {
33
- return {
34
- code: error.code ?? 'WORKSPACE_ERROR',
35
- severity: 'error',
36
- message: error.message,
37
- ...(error.file ? { file: error.file } : {}),
38
- }
39
- }
40
- function parse(text, file) {
41
- try {
42
- let doc
43
- const lineCounter = new YAML.LineCounter()
44
- const value =
45
- extname(file) === '.json'
46
- ? JSON.parse(text)
47
- : (doc = YAML.parseDocument(text, { merge: true, lineCounter })).toJS({ maxAliasCount: 100 })
48
- if (doc?.errors.length) throw doc.errors[0]
49
- if (!isDeepStrictEqual(JSON.parse(JSON.stringify(value)), value)) throw new Error('数据必须是有限的 JSON 值')
50
- return { value, doc, lineCounter, sharedFields: yamlSharing(doc, lineCounter) }
51
- } catch (error) {
52
- fail('SOURCE_INVALID', error.message, file)
53
- }
54
- }
55
- function safeValue(value) {
56
- if (Array.isArray(value)) value.forEach(safeValue)
57
- else if (object(value))
58
- for (const [key, entry] of Object.entries(value)) {
59
- if (['__proto__', 'prototype', 'constructor', '<<'].includes(key)) fail('SOURCE_INVALID', `不支持的字段:${key}`)
60
- safeValue(entry)
61
- }
62
- else if (value !== null && !['string', 'boolean', 'number'].includes(typeof value))
63
- fail('SOURCE_INVALID', '不支持的数据值')
64
- if (typeof value === 'number' && !Number.isFinite(value)) fail('SOURCE_INVALID', '数值必须有限')
65
- }
66
- // Change individual YAML nodes so comments and unrelated records survive a form save.
67
- function updateNodes(doc, before, after, path = []) {
68
- if (isDeepStrictEqual(before, after)) return
69
- if (
70
- (object(before) && object(after)) ||
71
- (Array.isArray(before) && Array.isArray(after) && before.length === after.length)
72
- ) {
73
- for (const key of Object.keys(before)) if (!Object.hasOwn(after, key)) doc.deleteIn([...path, key])
74
- for (const key of Object.keys(after))
75
- updateNodes(doc, before[key], after[key], [...path, Array.isArray(after) ? Number(key) : key])
76
- } else if (!path.length) doc.contents = doc.createNode(after)
77
- else doc.setIn(path, after)
78
- }
79
-
80
- function serializeForm({ value, doc, sharedFields }, next, file, original) {
81
- const changed = changedSharedField(sharedFields, value, next)
82
- if (changed)
83
- fail('SHARED_FIELD_READ_ONLY', `共享字段 ${changed.path.join('.') || '整个对象'} 请在外部编辑器修改`, file)
84
- if (isDeepStrictEqual(value, next)) return original
85
- if (!doc) return JSON.stringify(next, null, 2) + '\n'
86
- const signature = sharingSignature(doc)
87
- updateNodes(doc, value, next)
88
- const text = String(doc)
89
- const saved = parse(text, file)
90
- if (!isDeepStrictEqual(saved.value, next) || !isDeepStrictEqual(sharingSignature(saved.doc), signature))
91
- fail('SOURCE_STRUCTURE_CHANGED', '此次修改无法保留 YAML 共享结构,请在外部编辑器处理', file)
92
- return text
93
- }
94
-
95
- /** Ordinary source files are authoritative. No project database or generated-output writes. */
96
- export class AuthorWorkspace extends EventEmitter {
97
- #watcher
98
- #queues = new Map()
99
- #dirty = new Set()
100
- #closed = false
101
- constructor(root) {
102
- super()
103
- this.root = root
104
- }
105
- static async open(directory, { watch = true, readOnly = false, published = false } = {}) {
106
- const workspace = new AuthorWorkspace(await realpath(directory))
107
- const manifest = JSON.parse((await workspace.read('package.json')).text)
108
- workspace.published = published
109
- workspace.readOnly = readOnly || published || isBaseManifest(manifest)
110
- if (isBaseManifest(manifest) && (!published || !manifest.arcadia)) {
111
- const pack = JSON.parse((await workspace.read('pack.json')).text)
112
- if (pack.id !== baseProjectId) fail('PROJECT_INVALID', '基础包身份不一致', 'pack.json')
113
- workspace.baseProject = { projectId: pack.id, namespace: pack.id }
114
- }
115
- if (
116
- !workspace.baseProject &&
117
- (!object(manifest.arcadia) ||
118
- typeof manifest.arcadia.projectId !== 'string' ||
119
- typeof manifest.arcadia.namespace !== 'string')
120
- )
121
- fail('PROJECT_INVALID', '请选择包含 arcadia 身份的 npm 内容包源项目', 'package.json')
122
- if (watch) {
123
- workspace.#watcher = chokidar.watch(workspace.root, {
124
- ignoreInitial: true,
125
- ignored: path =>
126
- relative(workspace.root, path)
127
- .split(sep)
128
- .some(part => (ignored.has(part) && !(workspace.published && part === 'dist')) || part.endsWith('.tgz')),
129
- atomic: true,
130
- awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
131
- followSymlinks: false,
132
- })
133
- workspace.#watcher.on('all', (type, path) =>
134
- workspace.emit('change', { type, file: relative(workspace.root, path).split(sep).join('/') }),
135
- )
136
- await new Promise((resolve, reject) => {
137
- workspace.#watcher.once('ready', resolve)
138
- workspace.#watcher.once('error', reject)
139
- })
140
- workspace.#watcher.on('error', error =>
141
- workspace.emit('change', { type: 'rescan', diagnostic: diagnostic(error) }),
142
- )
143
- }
144
- return workspace
145
- }
146
- async assertWritable() {
147
- if (this.readOnly || isBaseManifest(JSON.parse((await this.read('package.json')).text)))
148
- fail('WRITE_DISABLED', '此内容包为只读,请在自己的内容包中创作。')
149
- }
150
- async path(file, { create = false } = {}) {
151
- if (this.#closed) fail('WORKSPACE_CLOSED', '工作区已关闭')
152
- if (
153
- typeof file !== 'string' ||
154
- !file ||
155
- isAbsolute(file) ||
156
- file.includes('\\') ||
157
- file.includes('\0') ||
158
- file.includes(':')
159
- )
160
- fail('PATH_INVALID', '需要项目内相对路径')
161
- const parts = file.split('/')
162
- if (
163
- parts.some(
164
- part => !part || part === '.' || part === '..' || (ignored.has(part) && !(this.published && part === 'dist')),
165
- )
166
- )
167
- fail('PATH_INVALID', '此路径不是可编辑源文件', file)
168
- if ((await realpath(this.root)) !== this.root) fail('PATH_INVALID', '项目目录已改变,请重新打开')
169
- let current = this.root
170
- for (let index = 0; index < parts.length; index++) {
171
- current = join(current, parts[index])
172
- try {
173
- const info = await lstat(current)
174
- if (info.isSymbolicLink() || (index < parts.length - 1 ? !info.isDirectory() : !info.isFile()))
175
- fail('PATH_INVALID', '源路径必须是普通文件/目录', file)
176
- } catch (error) {
177
- if (create && error.code === 'ENOENT') continue
178
- throw error
179
- }
180
- }
181
- return current
182
- }
183
- async read(file) {
184
- const path = await this.path(file)
185
- if ((await lstat(path)).size > textLimit) fail('SOURCE_TOO_LARGE', '文本超过 2 MiB,请在外部编辑器打开', file)
186
- const bytes = await readFile(path)
187
- if (bytes.length > textLimit || bytes.includes(0)) fail('SOURCE_INVALID', '文件不是受支持的源文本', file)
188
- return { file, text: bytes.toString('utf8'), version: hash(bytes) }
189
- }
190
- async files() {
191
- const result = []
192
- const walk = async (directory, prefix = '') => {
193
- for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>
194
- a.name.localeCompare(b.name),
195
- )) {
196
- if ((ignored.has(entry.name) && !(this.published && entry.name === 'dist')) || entry.name.endsWith('.tgz'))
197
- continue
198
- const file = prefix + entry.name
199
- if (entry.isSymbolicLink()) {
200
- result.push({ file, error: '不支持符号链接' })
201
- continue
202
- }
203
- if (entry.isDirectory()) await walk(join(directory, entry.name), file + '/')
204
- else if (entry.isFile()) {
205
- const info = await lstat(await this.path(file))
206
- result.push({ file, size: info.size, modified: info.mtimeMs })
207
- }
208
- if (result.length > 10000) fail('SOURCE_TOO_LARGE', '项目超过 10000 个源文件')
209
- }
210
- }
211
- await walk(this.root)
212
- return result
213
- }
214
- async revision({ contentOnly = false, excludeFile } = {}) {
215
- const hashes = []
216
- for (const entry of await this.files()) {
217
- if (entry.file === excludeFile || (contentOnly && entry.file.startsWith('debug/teams/'))) continue
218
- if (entry.error) fail('PATH_INVALID', entry.error, entry.file)
219
- const digest = createHash('sha256')
220
- for await (const chunk of createReadStream(await this.path(entry.file))) digest.update(chunk)
221
- hashes.push([entry.file, digest.digest('hex')])
222
- }
223
- return hash(JSON.stringify(hashes))
224
- }
225
- async snapshot() {
226
- const manifest = JSON.parse((await this.read('package.json')).text)
227
- const project = this.baseProject ?? manifest.arcadia
228
- const readOnly = this.readOnly || isBaseManifest(manifest)
229
- const baseSources = new Map()
230
- if (this.baseProject) {
231
- const pack = JSON.parse((await this.read('pack.json')).text)
232
- for (const kind of kinds)
233
- for (const file of pack.data?.[kind] ?? []) baseSources.set(`${pack.paths?.dataDir ?? 'data'}/${file}`, kind)
234
- }
235
- const files = await this.files(),
236
- records = [],
237
- diagnostics = [],
238
- ids = new Set()
239
- const locales = {},
240
- localeSources = []
241
- if (this.published) {
242
- // Published views follow the declared runtime artifacts, even when stale raw sources ship alongside them.
243
- const content = await this.read(manifest.arcadia.content)
244
- const data = JSON.parse(content.text).data
245
- safeValue(data)
246
- if (!object(data)) fail('SOURCE_INVALID', '安装包缺少内容数据', content.file)
247
- const add = (kind, record, source, index) => {
248
- if (!object(record) || typeof record.id !== 'string') fail('SOURCE_INVALID', '安装内容缺少 ID', source.file)
249
- records.push({ kind, record, file: source.file, version: source.version, index, sharedFields: [] })
250
- }
251
- for (const kind of ['species', 'skills', 'marks', 'behaviors']) {
252
- if (data[kind] !== undefined && !Array.isArray(data[kind]))
253
- fail('SOURCE_INVALID', '安装内容需要数组', content.file)
254
- for (const [index, record] of (data[kind] ?? []).entries()) add(kind, record, content, index)
255
- }
256
- if (manifest.arcadia.presentation) {
257
- const source = await this.read(manifest.arcadia.presentation)
258
- const presentation = JSON.parse(source.text)
259
- safeValue(presentation)
260
- if (presentation.version !== 2) fail('SOURCE_INVALID', '安装包需要 v2 表现格式', source.file)
261
- for (const [index, record] of (presentation.bindings ?? []).entries())
262
- add('presentations', record, source, index)
263
- for (const [index, resource] of (presentation.resources ?? []).entries()) {
264
- const kind = resource.mime?.startsWith('image/')
265
- ? 'image'
266
- : resource.mime?.startsWith('audio/')
267
- ? 'audio'
268
- : 'swf'
269
- add(
270
- 'resources',
271
- { id: resource.id, kind, source: resource.source, ...(resource.tags ? { tags: resource.tags } : {}) },
272
- source,
273
- index,
274
- )
275
- }
276
- for (const [language, namespaces] of Object.entries(presentation.locales ?? {})) {
277
- for (const [namespace, entries] of Object.entries(namespaces)) {
278
- localeSources.push({
279
- file: source.file,
280
- version: source.version,
281
- language,
282
- namespace,
283
- entries,
284
- sharedFields: [],
285
- })
286
- }
287
- }
288
- }
289
- }
290
- for (const entry of this.published ? [] : files) {
291
- if (entry.error) {
292
- diagnostics.push({ code: 'PATH_INVALID', severity: 'error', file: entry.file, message: entry.error })
293
- continue
294
- }
295
- const match = baseSources.has(entry.file)
296
- ? [entry.file, baseSources.get(entry.file)]
297
- : /^data\/(species|skills|marks|behaviors|presentations|resources)\/.+\.(json|ya?ml)$/.exec(entry.file)
298
- const locale = /^locales\/([^/]+)\/([^/]+)\.(json|ya?ml)$/.exec(entry.file)
299
- if (
300
- this.baseProject &&
301
- locale &&
302
- !['species', 'skill', 'mark', 'mark_ability', 'mark_emblem', 'mark_global'].includes(locale[2])
303
- )
304
- continue
305
- if (!match && !locale) continue
306
- try {
307
- const source = await this.read(entry.file),
308
- { value, doc, lineCounter, sharedFields } = parse(source.text, entry.file)
309
- if (locale) {
310
- if (
311
- !object(value) ||
312
- Object.values(value).some(
313
- entry =>
314
- !object(entry) ||
315
- Object.entries(entry).some(
316
- ([key, text]) => !['name', 'description'].includes(key) || typeof text !== 'string',
317
- ),
318
- )
319
- )
320
- fail('SOURCE_INVALID', '语言文件需要以对象 ID 映射名称与描述文本', entry.file)
321
- safeValue(value)
322
- locales[entry.file] = value
323
- localeSources.push({
324
- file: entry.file,
325
- version: source.version,
326
- language: locale[1],
327
- namespace: locale[2],
328
- entries: value,
329
- sharedFields,
330
- locations: Object.fromEntries(
331
- Object.keys(value).flatMap(id => {
332
- const node = doc?.getIn([id], true)
333
- if (!node?.range) return []
334
- const position = lineCounter.linePos(node.range[0])
335
- return [[id, { line: position.line, column: position.col }]]
336
- }),
337
- ),
338
- })
339
- continue
340
- }
341
- const values = Array.isArray(value) ? value : [value]
342
- for (const [index, record] of values.entries()) {
343
- if (!object(record) || typeof record.id !== 'string' || !record.id)
344
- fail('SOURCE_INVALID', '每条内容需要 ID', entry.file)
345
- const key = `${match[1]}:${record.id}`
346
- if (ids.has(key))
347
- diagnostics.push({
348
- code: 'DUPLICATE_ID',
349
- severity: 'error',
350
- file: entry.file,
351
- message: `重复内容 ID:${key}`,
352
- })
353
- ids.add(key)
354
- const node = doc?.getIn(Array.isArray(value) ? [index] : [], true)
355
- const position = node?.range ? lineCounter.linePos(node.range[0]) : undefined
356
- records.push({
357
- kind: match[1],
358
- file: entry.file,
359
- index: Array.isArray(value) ? index : null,
360
- version: source.version,
361
- record,
362
- sharedFields: recordSharing(sharedFields, Array.isArray(value) ? index : null),
363
- ...(position ? { line: position.line, column: position.col } : {}),
364
- })
365
- }
366
- } catch (error) {
367
- diagnostics.push(diagnostic(error))
368
- }
369
- }
370
- for (const row of records) {
371
- if (
372
- ['species', 'skills', 'marks'].includes(row.kind) &&
373
- ['presentation', 'assetRef', 'iconRef', 'sfxRef'].some(key => key in row.record)
374
- )
375
- diagnostics.push({
376
- code: 'PRESENTATION_MIGRATION_REQUIRED',
377
- severity: 'error',
378
- file: row.file,
379
- message: '此对象仍使用旧资源格式,请将表现与资源迁移到 data/presentations 和 data/resources。',
380
- })
381
- }
382
- const assets = records
383
- .filter(row => row.kind === 'resources')
384
- .map(row => ({
385
- id: row.record.id,
386
- file: row.record.source,
387
- definition: row.file,
388
- kind: row.record.kind,
389
- name: row.record.name ?? row.record.id,
390
- ...files.find(file => file.file === row.record.source),
391
- references: [],
392
- }))
393
- const byId = new Map(assets.map(row => [row.id, row]))
394
- const targets = new Set()
395
- for (const source of records.filter(row => row.kind === 'presentations')) {
396
- try {
397
- const target = source.record.target
398
- const key = JSON.stringify([target?.kind, target?.id])
399
- if (targets.has(key)) throw new Error(`重复表现关联:${key}`)
400
- targets.add(key)
401
- if (!records.some(row => row.kind === target?.kind && row.record.id === target?.id))
402
- throw new Error(`表现关联的对象不存在:${key}`)
403
- for (const ref of resourceReferences(bindingPresentation(source.record))) {
404
- if (typeof ref !== 'string') continue
405
- const resource = byId.get(ref)
406
- if (resource) resource.references.push({ file: source.file, kind: target.kind, id: target.id })
407
- else
408
- diagnostics.push({
409
- code: 'RESOURCE_MISSING',
410
- severity: 'error',
411
- file: source.file,
412
- message: `资源引用不存在:${ref}`,
413
- })
414
- }
415
- } catch (error) {
416
- diagnostics.push({ ...diagnostic(error), file: source.file })
417
- }
418
- }
419
- for (const resource of assets) {
420
- if (
421
- typeof resource.file !== 'string' ||
422
- (!/^https?:\/\//.test(resource.file) && !files.some(row => row.file === resource.file && !row.error))
423
- )
424
- diagnostics.push({
425
- code: 'RESOURCE_MISSING',
426
- severity: 'error',
427
- file: resource.definition,
428
- message: `素材位置已失效,请重新定位:${resource.id}`,
429
- })
430
- }
431
- return {
432
- protocolVersion: 1,
433
- root: this.root,
434
- project,
435
- name: this.baseProject ? '基础包' : manifest.name,
436
- version: manifest.version,
437
- records,
438
- files,
439
- assets,
440
- locales,
441
- localeSources,
442
- diagnostics,
443
- capabilities: {
444
- sourceEditing: !readOnly,
445
- structuredSaving: !readOnly,
446
- localeEditing: !readOnly,
447
- yamlSharing: 'read-only-fields',
448
- externalEditor: !readOnly,
449
- kinds,
450
- sdkApi: project.sdkApi,
451
- },
452
- }
453
- }
454
- setDirty(file, dirty) {
455
- if (dirty) this.#dirty.add(file)
456
- else this.#dirty.delete(file)
457
- }
458
- clearDirty() {
459
- this.#dirty.clear()
460
- }
461
- async asset(file) {
462
- if (!file.startsWith('assets/') && !(await this.snapshot()).assets.some(row => row.file === file))
463
- fail('PATH_INVALID', '请选择项目声明的素材', file)
464
- const path = await this.path(file)
465
- if ((await lstat(path)).size > 64 * 1024 * 1024) fail('SOURCE_TOO_LARGE', '素材超过 64 MiB', file)
466
- const bytes = await readFile(path)
467
- return { file, bytes, version: hash(bytes) }
468
- }
469
- async #serialize(file, action) {
470
- const pending = (this.#queues.get(file) ?? Promise.resolve())
471
- .catch(() => {})
472
- .then(() => withSourceLock(this.root, file, action))
473
- this.#queues.set(file, pending)
474
- try {
475
- return await pending
476
- } finally {
477
- if (this.#queues.get(file) === pending) this.#queues.delete(file)
478
- }
479
- }
480
- async #version(file) {
481
- try {
482
- return (await this.read(file)).version
483
- } catch (error) {
484
- if (error.code === 'ENOENT') return null
485
- throw error
486
- }
487
- }
488
- async #check(file, expectedVersion, fromForm) {
489
- await this.assertWritable()
490
- if (this.#dirty.has(file) && !fromForm) fail('UNSAVED_CHANGES', '此文件有未保存表单', file)
491
- if (expectedVersion !== (await this.#version(file)))
492
- fail('REVISION_CONFLICT', '文件已在外部修改,未保存输入仍保留', file)
493
- }
494
- async write({ file, expectedVersion, text }, { fromForm = false } = {}) {
495
- await this.assertWritable()
496
- if (typeof text !== 'string' || Buffer.byteLength(text) > textLimit)
497
- fail('SOURCE_TOO_LARGE', '源文本超过大小限制', file)
498
- await this.path(file, { create: true })
499
- return this.#serialize(file, async () => {
500
- const path = await this.path(file, { create: true })
501
- await this.#check(file, expectedVersion, fromForm)
502
- await mkdir(dirname(path), { recursive: true })
503
- await this.path(file, { create: true })
504
- await this.#check(file, expectedVersion, fromForm)
505
- await writeFileAtomic(path, text)
506
- if (fromForm) this.#dirty.delete(file)
507
- this.emit('change', { type: 'change', file })
508
- return { file, version: hash(text) }
509
- })
510
- }
511
- async remove({ file, expectedVersion }) {
512
- await this.assertWritable()
513
- await this.path(file, { create: true })
514
- return this.#serialize(file, async () => {
515
- await this.#check(file, expectedVersion, false)
516
- const path = await this.path(file)
517
- await unlink(path)
518
- this.emit('change', { type: 'unlink', file })
519
- })
520
- }
521
- async saveRecord({ file, expectedVersion, index = null, record }) {
522
- const { results } = await this.saveChanges(
523
- { changes: [{ kind: 'record', file, expectedVersion, index, record }] },
524
- { fromForm: true },
525
- )
526
- const result = results[0]
527
- if (!result.saved) fail(result.diagnostic.code, result.diagnostic.message, result.diagnostic.file ?? file)
528
- return { file: result.file, version: result.version }
529
- }
530
- /** Prepare the whole review first; commit each source once, reporting partial writes explicitly. */
531
- async saveChanges({ changes }, { fromForm = false } = {}) {
532
- await this.assertWritable()
533
- if (!Array.isArray(changes) || !changes.length || changes.length > 1000)
534
- fail('SOURCE_INVALID', '请选择 1–1000 项修改')
535
- const catalog = changes.some(change => ['locale', 'create-record'].includes(change?.kind))
536
- ? await this.snapshot()
537
- : undefined
538
- const created = new Set()
539
- for (const change of changes.filter(change => change?.kind === 'create-record')) {
540
- const kind = /^data\/(species|skills|marks|presentations|resources)\/.+\.(json|ya?ml)$/.exec(change.file)?.[1]
541
- if (!kind || !object(change.record) || typeof change.record.id !== 'string' || !change.record.id)
542
- fail('SOURCE_INVALID', '新建内容需要有效类型、ID 和源文件位置', change.file)
543
- const key = JSON.stringify([kind, change.record.id])
544
- if (created.has(key) || catalog.records.some(row => row.kind === kind && row.record.id === change.record.id))
545
- fail('DUPLICATE_ID', '此内容 ID 已存在,请使用其他标识', change.file)
546
- created.add(key)
547
- }
548
- const files = new Map(),
549
- targets = new Set()
550
- for (const change of changes) {
551
- const { file, expectedVersion, kind, record, index = null, id } = change
552
- const creating = kind === 'create-record'
553
- if (typeof expectedVersion !== 'string' && !(expectedVersion === null && (creating || kind === 'locale')))
554
- fail('SOURCE_INVALID', '保存需要已读取的源版本', file)
555
- if (creating && expectedVersion !== null) fail('SOURCE_INVALID', '新建内容不能覆盖已有文件', file)
556
- if (creating && index !== null) fail('SOURCE_INVALID', '新建内容需要独立文件,不能指定数组位置', file)
557
- const isLocale = kind === 'locale'
558
- if (kind !== 'record' && !isLocale && !creating) fail('SOURCE_INVALID', '不支持的修改类型', file)
559
- if (
560
- !(
561
- isLocale
562
- ? /^locales\/[^/]+\/[^/]+\.(json|ya?ml)$/
563
- : /^data\/(species|skills|marks|behaviors|presentations|resources)\/.+\.(json|ya?ml)$/
564
- ).test(file)
565
- )
566
- fail('PATH_INVALID', '请选择已有的内容或语言源文件', file)
567
- const key = JSON.stringify([file, isLocale ? id : index])
568
- if (targets.has(key)) fail('SOURCE_INVALID', '同一内容出现重复修改', file)
569
- targets.add(key)
570
- if (!files.has(file)) {
571
- if (this.#dirty.has(file) && !fromForm) fail('UNSAVED_CHANGES', '此文件有未保存表单', file)
572
- await this.path(file, { create: expectedVersion === null })
573
- const version = await this.#version(file)
574
- if (version !== expectedVersion) fail('REVISION_CONFLICT', '来源已改变或新建位置已被占用,请核对', file)
575
- const source = expectedVersion === null ? { file, version: null, text: '{}' } : await this.read(file)
576
- if (source.version !== expectedVersion)
577
- fail('REVISION_CONFLICT', '文件已改变,草稿仍保留,请核对外部变化', file)
578
- const parsed = parse(source.text, file)
579
- safeValue(parsed.value)
580
- files.set(file, { source, parsed, next: JSON.parse(JSON.stringify(parsed.value)) })
581
- }
582
- const prepared = files.get(file)
583
- if (prepared.source.version !== expectedVersion)
584
- fail('REVISION_CONFLICT', '同一文件的草稿版本不一致,请核对外部变化', file)
585
- safeValue(record)
586
- if (!object(record)) fail('SOURCE_INVALID', '保存内容必须是对象', file)
587
- if (!isLocale) {
588
- const sourceKind = file.split('/')[1]
589
- if (sourceKind === 'resources') {
590
- if (
591
- !validResourceId(record?.id) ||
592
- !['image', 'audio', 'swf'].includes(record?.kind) ||
593
- typeof record.source !== 'string' ||
594
- (!/^https?:\/\//.test(record.source) && !validAssetPath(record.source))
595
- )
596
- fail('SOURCE_INVALID', '资源需要稳定 ID、类型和项目内路径或 HTTP 地址', file)
597
- } else if (sourceKind === 'presentations') {
598
- if (
599
- !object(record?.target) ||
600
- !['species', 'skills', 'marks'].includes(record.target.kind) ||
601
- typeof record.target.id !== 'string'
602
- )
603
- fail('SOURCE_INVALID', '表现需要对应的内容对象', file)
604
- resourceReferences(bindingPresentation(record))
605
- } else if (['presentation', 'assetRef', 'iconRef', 'sfxRef'].some(key => key in record))
606
- fail('SOURCE_INVALID', '请将表现关联和资源定义分别保存到 data/presentations 与 data/resources', file)
607
- }
608
- if (isLocale) {
609
- if (
610
- typeof id !== 'string' ||
611
- !id ||
612
- ['__proto__', 'constructor', 'prototype'].includes(id) ||
613
- !object(prepared.next) ||
614
- !object(record) ||
615
- Object.entries(record).some(
616
- ([key, value]) => !['name', 'description'].includes(key) || typeof value !== 'string',
617
- )
618
- )
619
- fail('SOURCE_INVALID', '名称与描述需要文本值', file)
620
- const namespace = /^locales\/[^/]+\/([^/]+)\.(json|ya?ml)$/.exec(file)?.[1]
621
- const contentKind = {
622
- species: 'species',
623
- skill: 'skills',
624
- mark: 'marks',
625
- mark_ability: 'marks',
626
- mark_emblem: 'marks',
627
- mark_global: 'marks',
628
- }[namespace]
629
- if (
630
- !contentKind ||
631
- catalog.records.filter(row => row.kind === contentKind && row.record.id === id).length +
632
- Number(created.has(JSON.stringify([contentKind, id]))) !==
633
- 1
634
- )
635
- fail('SOURCE_INVALID', '名称与描述需要对应唯一的已有内容对象', file)
636
- prepared.next[id] = record
637
- } else {
638
- if (!object(record) || typeof record.id !== 'string' || !record.id) fail('SOURCE_INVALID', '内容需要 ID', file)
639
- if (creating) {
640
- prepared.next = record
641
- continue
642
- }
643
- const before =
644
- index === null
645
- ? prepared.next
646
- : Array.isArray(prepared.next) && Number.isInteger(index)
647
- ? prepared.next[index]
648
- : undefined
649
- if (!object(before) || before.id !== record.id) fail('SOURCE_INVALID', '内容位置或身份已改变,请核对来源', file)
650
- if (index === null) prepared.next = record
651
- else prepared.next[index] = record
652
- }
653
- }
654
- const prepared = [...files]
655
- .map(([file, { source, parsed, next }]) => ({
656
- file,
657
- expectedVersion: source.version,
658
- text:
659
- source.version === null
660
- ? extname(file) === '.json'
661
- ? JSON.stringify(next, null, 2) + '\n'
662
- : YAML.stringify(next)
663
- : serializeForm(parsed, next, file, source.text),
664
- }))
665
- .sort((a, b) => Number(a.file.startsWith('locales/')) - Number(b.file.startsWith('locales/')))
666
- const results = []
667
- for (const change of prepared) {
668
- try {
669
- const result = await this.write(change, { fromForm })
670
- results.push({ ...result, saved: true })
671
- } catch (error) {
672
- results.push({ file: change.file, saved: false, diagnostic: diagnostic(error) })
673
- break
674
- }
675
- }
676
- return { results, complete: results.length === prepared.length && results.every(result => result.saved) }
677
- }
678
- async close() {
679
- this.#closed = true
680
- await this.#watcher?.close()
681
- await Promise.allSettled(this.#queues.values())
682
- this.removeAllListeners()
683
- }
684
- }
File without changes
File without changes