@2kog/kacha 0.0.0-stage → 0.1.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 (40) hide show
  1. package/README.md +63 -2
  2. package/bin/init-project.js +63 -0
  3. package/bin/kacha.js +51 -0
  4. package/index.html +5 -0
  5. package/package.json +45 -4
  6. package/server/asset-directories.js +65 -0
  7. package/server/asset-watch.js +35 -0
  8. package/server/character-assets.js +399 -0
  9. package/server/image-assets.js +652 -0
  10. package/server/index.js +15 -0
  11. package/server/project-brand.js +56 -0
  12. package/server/project-paths.js +4 -0
  13. package/server/project-settings.js +55 -0
  14. package/src/App.vue +34 -0
  15. package/src/assets/css/workbench.css +272 -0
  16. package/src/assets/img/rabbit-mark.svg +1 -0
  17. package/src/components/AssetDeleteButton.vue +53 -0
  18. package/src/components/AssetHistory.vue +40 -0
  19. package/src/components/AssetStoryEditor.vue +32 -0
  20. package/src/components/AssetTagInput.vue +26 -0
  21. package/src/components/ProjectMarkdown.vue +33 -0
  22. package/src/i18n/en.json +163 -0
  23. package/src/i18n/index.js +40 -0
  24. package/src/layouts/WorkbenchLayout.vue +61 -0
  25. package/src/main.js +7 -0
  26. package/src/router/index.js +38 -0
  27. package/src/service/assets.js +13 -0
  28. package/src/service/project-markdown.js +26 -0
  29. package/src/views/assets/AudioAssets.vue +325 -0
  30. package/src/views/assets/CharacterAssets.vue +412 -0
  31. package/src/views/assets/ImageAssets.vue +456 -0
  32. package/src/views/settings/ProjectSettings.vue +80 -0
  33. package/templates/project/AGENTS.md +14 -0
  34. package/templates/project/README.md +7 -0
  35. package/templates/project/assets/audio/README.md +5 -0
  36. package/templates/project/assets/characters/README.md +5 -0
  37. package/templates/project/assets/other/README.md +3 -0
  38. package/templates/project/assets/props/README.md +3 -0
  39. package/templates/project/assets/scenes/README.md +3 -0
  40. package/vite.config.js +10 -0
@@ -0,0 +1,652 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import { constants, createReadStream } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { randomUUID } from 'node:crypto'
5
+ import { assetRoot } from './project-paths.js'
6
+ import { assetId, deleteAssetDirectory, isAssetFolderName, scanAssets } from './asset-directories.js'
7
+
8
+ const types = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.avif': 'image/avif' }
9
+ const audioTypes = { '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.flac': 'audio/flac', '.aac': 'audio/aac' }
10
+ const audioGroups = { music: '音乐', effect: '音效', dialogue: '台词' }
11
+ const otherGroups = { graphic: '图形与字标', effect: '特效', delivery: '交付版' }
12
+ const otherFolders = { graphic: 'extend' }
13
+ const sceneGroups = { view: '机位', season: '季节', time: '时间', weather: '天气', layout: '空间定位', detail: '局部与陈设' }
14
+ const sceneFolders = { view: 'views', season: 'seasons', time: 'time', weather: 'weather', layout: 'layout', detail: 'details' }
15
+ const propGroups = { angle: '角度', portrait: '特写' }
16
+ const propFolders = { angle: 'angles', portrait: 'portraits' }
17
+ const legacyPropTypes = { object: '实体道具', wearable: '穿戴与配饰', graphic: '标识与字标' }
18
+ const statuses = { adopted: '已采用', candidate: '候选', reference: '参考' }
19
+ const error = (status, message) => Object.assign(new Error(message), { status })
20
+ const sort = (a, b) => a.localeCompare(b, 'zh-CN', { numeric: true })
21
+
22
+ async function read(file, fallback = '') {
23
+ try {
24
+ return await fs.readFile(file, 'utf8')
25
+ } catch (cause) {
26
+ if (cause.code === 'ENOENT') return fallback
27
+ throw cause
28
+ }
29
+ }
30
+
31
+ async function entries(dir) {
32
+ try {
33
+ return await fs.readdir(dir, { withFileTypes: true })
34
+ } catch (cause) {
35
+ if (cause.code === 'ENOENT') return []
36
+ throw cause
37
+ }
38
+ }
39
+
40
+ async function localFile(base, name) {
41
+ if (typeof name !== 'string') return null
42
+ const file = path.resolve(base, name)
43
+ if (!file.startsWith(base + path.sep) || await fs.realpath(file).catch(() => null) !== file) return null
44
+ return (await fs.stat(file)).isFile() ? file : null
45
+ }
46
+
47
+ const mediaUrl = (file, library) => library.mediaPath + '?file=' + encodeURIComponent(path.relative(library.root, file))
48
+ const meta = async dir => JSON.parse(await read(path.join(dir, 'index.json'), '{}'))
49
+
50
+ async function picture(dir, entry, includePrompt, library) {
51
+ const file = await localFile(dir, entry.file)
52
+ const result = {
53
+ ...entry,
54
+ url: file ? mediaUrl(file, library) + '&modified=' + (await fs.stat(file)).mtimeMs : null,
55
+ }
56
+ if (includePrompt && !Object.hasOwn(entry, 'prompt') && entry.promptRecord) {
57
+ const recordPath = await localFile(dir, entry.promptRecord)
58
+ if (recordPath) {
59
+ const record = JSON.parse(await read(recordPath))
60
+ const item = (entry.promptEntry || []).reduce((value, key) => value?.[key], record)
61
+ result.prompt = typeof item?.prompt === 'string' ? item.prompt : item?.prompt?.text
62
+ }
63
+ }
64
+ return result
65
+ }
66
+
67
+ async function imagePaths(dir, formats, prefix = '') {
68
+ const files = []
69
+ for (const item of await entries(path.join(dir, prefix))) {
70
+ const relative = path.join(prefix, item.name)
71
+ if (item.name.startsWith('.') || item.name === '生成记录' || item.name === 'archive') continue
72
+ if (item.isDirectory()) files.push(...await imagePaths(dir, formats, relative))
73
+ if (item.isFile() && formats[path.extname(item.name).toLowerCase()]) files.push(relative)
74
+ }
75
+ return files.sort(sort)
76
+ }
77
+
78
+ function savedPropTags(data) {
79
+ if (Array.isArray(data.tags)) return data.tags.filter(tag => typeof tag === 'string')
80
+ return Object.hasOwn(legacyPropTypes, data.propType) ? [legacyPropTypes[data.propType]] : []
81
+ }
82
+
83
+ function normalizeTags(tags) {
84
+ if (!Array.isArray(tags) || tags.some(tag => typeof tag !== 'string')) {
85
+ throw error(400, '标签必须是文本数组')
86
+ }
87
+ return [...new Set(tags.map(tag => tag.trim()).filter(Boolean))]
88
+ }
89
+
90
+ const isRootCover = file => /^index\.(png|jpe?g|webp|avif)$/i.test(file)
91
+ const savedAssetTags = data => Array.isArray(data.tags) ? data.tags.filter(tag => typeof tag === 'string') : []
92
+ const retainedImageFiles = data => Array.isArray(data.retainedImages) ? data.retainedImages : []
93
+
94
+ function propCategory(image) {
95
+ if (image.file?.startsWith(propFolders.angle + '/')) return 'angle'
96
+ if (image.file?.startsWith(propFolders.portrait + '/')) return 'portrait'
97
+ return ['view', 'angle'].includes(image.category) ? 'angle' : 'portrait'
98
+ }
99
+
100
+ async function folderImages(dir, data, library) {
101
+ const indexedImages = Array.isArray(data.images) ? data.images : []
102
+ const images = library.isProp
103
+ ? indexedImages.map(image => ({ ...image, category: propCategory(image) }))
104
+ : indexedImages
105
+ const registered = new Set([...images.map(image => image.file), ...retainedImageFiles(data)])
106
+ const ids = new Set(images.map(image => image.id))
107
+ const rootImages = (await entries(dir)).filter(file => file.isFile() && isRootCover(file.name)).map(file => file.name).sort(sort)
108
+ const current = images.find(image => image.id === data.mainImage)
109
+ const coverFile = rootImages.includes(current?.file) ? current.file : rootImages[0]
110
+ const discovered = (file, category, label) => {
111
+ let id = file
112
+ for (let sequence = 2; ids.has(id); sequence++) id = file + '#' + sequence
113
+ ids.add(id)
114
+ return { id, file, label, category, status: 'reference' }
115
+ }
116
+ const inPropGallery = library.isProp && Object.values(propFolders).some(folder => current?.file?.startsWith(folder + '/'))
117
+ const cover = coverFile
118
+ ? images.find(image => image.file === coverFile) || discovered(coverFile, library.defaultCategory, '主图')
119
+ : inPropGallery ? undefined : current
120
+ const variants = await Promise.all(Object.entries(library.galleryFolders).map(async ([category, folder]) => {
121
+ const location = path.join(dir, folder)
122
+ if (await fs.realpath(location).catch(() => null) !== location) return []
123
+ return (await imagePaths(dir, types, folder)).filter(file => !registered.has(file))
124
+ .map(file => ({ file, category }))
125
+ }))
126
+ const items = images.filter(image => !isRootCover(image.file) || image === cover)
127
+ if (cover && !items.includes(cover)) items.unshift(cover)
128
+ return {
129
+ items: [...items, ...variants.flatMap(group => group.map(({ file, category }) => discovered(file, category, path.parse(file).name)))],
130
+ cover,
131
+ }
132
+ }
133
+
134
+ function assetTags(data, groupPath, defaults) {
135
+ const hidden = Array.isArray(data.hiddenGroupTags) ? data.hiddenGroupTags : []
136
+ return [...new Set([...defaults, ...groupPath.filter(tag => !hidden.includes(tag))])]
137
+ }
138
+
139
+ function saveTags(data, tags, groups, defaults) {
140
+ data.tags = tags.filter(tag => !groups.includes(tag) || defaults.includes(tag))
141
+ const hidden = groups.filter(tag => !tags.includes(tag))
142
+ if (hidden.length) data.hiddenGroupTags = hidden
143
+ else delete data.hiddenGroupTags
144
+ }
145
+
146
+ async function describe(dir, full, library, groupPath = []) {
147
+ const data = await meta(dir)
148
+ const { items: images, cover } = !library.isAudio ? await folderImages(dir, data, library) : {
149
+ items: Array.isArray(data[library.entriesKey]) ? data[library.entriesKey] : [],
150
+ cover: data[library.entriesKey]?.find(image => image.id === data[library.mainKey]),
151
+ }
152
+ const result = {
153
+ id: assetId(library.root, dir),
154
+ groupPath,
155
+ name: data.name || path.basename(dir),
156
+ count: images.length,
157
+ ...(library.isAudio ? {
158
+ type: data.type || '',
159
+ categories: data.type ? [data.type] : [...new Set(images.map(item => item.category))],
160
+ } : {}),
161
+ cover: cover ? await picture(dir, cover, full && !library.isAudio, library) : null,
162
+ }
163
+ const saved = library.isProp ? savedPropTags(data) : savedAssetTags(data)
164
+ result.tags = library.isAudio ? saved : assetTags(data, groupPath, saved)
165
+ if (full) result.note = typeof data.note === 'string' ? data.note : ''
166
+ if (library.isProp) result.transparentPreview = data.propType === 'graphic'
167
+ if (!full) return result
168
+ const archive = path.join(dir, 'archive')
169
+ const history = []
170
+ if (await fs.realpath(archive).catch(() => null) === archive) {
171
+ const legacy = []
172
+ for (const item of await entries(archive)) {
173
+ if (item.name.startsWith('.') || item.name === '生成记录') continue
174
+ if (item.isDirectory()) {
175
+ const version = path.join(archive, item.name)
176
+ const previous = await meta(version)
177
+ const files = previous[library.entriesKey] || (await imagePaths(version, library.formats)).map(file => ({ file, label: path.basename(file) }))
178
+ const listed = data.history?.find(entry => entry.version === item.name)
179
+ const directoryDate = /^\d{4}-\d{2}-\d{2}(?=-|$)/.exec(item.name)?.[0]
180
+ history.push({
181
+ version: item.name,
182
+ note: listed?.note,
183
+ images: await Promise.all(files.map(entry => picture(version, entry, true, library))),
184
+ ...(!library.isAudio ? {
185
+ story: await read(path.join(version, 'README.md')),
186
+ createdAt: listed?.archivedAt || directoryDate || (await fs.stat(version)).birthtime.toISOString(),
187
+ timeSource: listed?.archivedAt || directoryDate ? 'archive' : 'directory',
188
+ } : {}),
189
+ })
190
+ } else if (item.isFile() && library.formats[path.extname(item.name).toLowerCase()]) {
191
+ legacy.push(await picture(archive, { file: item.name, label: item.name }, false, library))
192
+ }
193
+ }
194
+ if (legacy.length) {
195
+ history.push({
196
+ version: '早期归档',
197
+ images: legacy,
198
+ ...(!library.isAudio ? {
199
+ createdAt: (await fs.stat(archive)).birthtime.toISOString(),
200
+ timeSource: 'directory',
201
+ } : {}),
202
+ })
203
+ }
204
+ }
205
+ return {
206
+ ...result, groups: library.groups, statuses,
207
+ story: await read(path.join(dir, 'README.md')),
208
+ images: await Promise.all(images.map(entry => picture(dir, entry, true, library))),
209
+ history: history.sort((a, b) => sort(b.version, a.version)),
210
+ }
211
+ }
212
+
213
+ function newAssetDirectory(name, library) {
214
+ if (typeof name !== 'string' || !name.trim() || name !== name.trim() || !isAssetFolderName(name) || /[/\\:\u0000-\u001f]/.test(name)) {
215
+ throw error(400, library.label + '名称无效')
216
+ }
217
+ return path.join(library.root, name)
218
+ }
219
+
220
+ async function existingAsset(id, library) {
221
+ const asset = (await scanAssets(library.root, library.isAudio ? undefined : isRootCover)).find(entry => entry.id === id)
222
+ if (!asset) throw error(404, '找不到' + library.label + '目录')
223
+ return asset
224
+ }
225
+
226
+ async function write(file, content) {
227
+ const temp = path.join(path.dirname(file), '.' + randomUUID() + '.tmp')
228
+ try {
229
+ await fs.writeFile(temp, content)
230
+ await fs.rename(temp, file)
231
+ } finally {
232
+ await fs.rm(temp, { force: true })
233
+ }
234
+ }
235
+ const writeIndex = (dir, data) => write(path.join(dir, 'index.json'), JSON.stringify(data, null, 2) + '\n')
236
+
237
+ async function savePrevious(dir, data, library, { image, file: previous, story, note }) {
238
+ const archive = path.join(dir, 'archive')
239
+ await fs.mkdir(archive, { recursive: true })
240
+ if (await fs.realpath(archive) !== archive) throw error(400, '归档目录必须位于' + library.label + '目录内')
241
+ const versions = await entries(archive)
242
+ const number = Math.max(0, ...versions.map(item => Number(/^\d{4}-\d{2}-\d{2}-v(\d+)$/.exec(item.name)?.[1] || 0))) + 1
243
+ const date = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date())
244
+ const version = date + '-v' + String(number).padStart(3, '0')
245
+ const draft = path.join(archive, '.' + randomUUID())
246
+ await fs.mkdir(draft)
247
+ try {
248
+ const items = []
249
+ if (previous) {
250
+ const file = path.basename(previous)
251
+ await fs.copyFile(previous, path.join(draft, file))
252
+ const { url, promptRecord, promptEntry, ...saved } = await picture(dir, image, true, library)
253
+ items.push({ ...saved, file })
254
+ }
255
+ if (typeof story === 'string') await write(path.join(draft, 'README.md'), story)
256
+ await writeIndex(draft, { [library.entriesKey]: items })
257
+ await fs.rename(draft, path.join(archive, version))
258
+ } finally {
259
+ await fs.rm(draft, { recursive: true, force: true })
260
+ }
261
+ data.history = [...(data.history || []), { version, note, ...(!library.isAudio ? { archivedAt: new Date().toISOString() } : {}) }]
262
+ return path.join(archive, version)
263
+ }
264
+
265
+ function sceneConditions(conditions) {
266
+ return Object.fromEntries(['season', 'time', 'weather']
267
+ .filter(key => typeof conditions?.[key] === 'string' && conditions[key].trim())
268
+ .map(key => [key, conditions[key].trim()]))
269
+ }
270
+
271
+ function readUpload(upload, library) {
272
+ const { filename, base64, category, status, label, prompt, conditions } = upload
273
+ const ext = typeof filename === 'string' && path.extname(filename).toLowerCase()
274
+ if (!Object.hasOwn(library.formats, ext) || !Object.hasOwn(library.groups, category) || !Object.hasOwn(statuses, status)
275
+ || typeof label !== 'string' || !label.trim() || typeof prompt !== 'string' || typeof base64 !== 'string') {
276
+ throw error(400, '请填写素材名称、分类、状态并选择支持的文件')
277
+ }
278
+ const bytes = Buffer.from(base64, 'base64')
279
+ if (!bytes.length || bytes.length > 30 * 1024 * 1024) throw error(400, '请选择 30 MB 以内的文件')
280
+ const variants = sceneConditions(conditions)
281
+ return {
282
+ ext, bytes,
283
+ fields: { label: label.trim(), category, status, prompt, ...(Object.keys(variants).length ? { conditions: variants } : {}) },
284
+ }
285
+ }
286
+
287
+ async function fileExists(file) {
288
+ return Boolean(await fs.lstat(file).catch(cause => {
289
+ if (cause.code !== 'ENOENT') throw cause
290
+ return null
291
+ }))
292
+ }
293
+
294
+ async function galleryFile(dir, category, label, ext, library) {
295
+ const folders = library.galleryFolders
296
+ const folder = Object.hasOwn(folders, category) ? folders[category] : folders[library.defaultCategory]
297
+ const location = path.join(dir, folder)
298
+ await fs.mkdir(location, { recursive: true })
299
+ if (await fs.realpath(location) !== location) throw error(400, '素材目录必须位于' + library.label + '目录内')
300
+ const stem = [...label.replace(/[/\\:\u0000-\u001f]/g, '-').replace(/^\.+/, '').trim()].slice(0, 50).join('') || library.label + '图'
301
+ let file = folder + '/' + stem + ext
302
+ for (let sequence = 2; await fileExists(path.join(dir, file)); sequence++) {
303
+ file = folder + '/' + stem + '-' + sequence + ext
304
+ }
305
+ return file
306
+ }
307
+
308
+ async function updateImageFields(dir, data, image, file, changes, library) {
309
+ const { label = image?.label, category = image?.category, status = image?.status, prompt } = changes
310
+ if (!file || typeof label !== 'string' || !label.trim() || category !== image.category
311
+ || !Object.hasOwn(statuses, status) || typeof prompt !== 'string') {
312
+ throw error(400, '请填写有效的素材名称、状态和生成词')
313
+ }
314
+ const previous = await picture(dir, image, true, library)
315
+ const promptChanged = prompt !== (previous.prompt || '')
316
+ const archive = promptChanged && previous.prompt && await savePrevious(dir, data, library, {
317
+ image, file, note: '修改「' + image.label + '」生成词',
318
+ })
319
+ try {
320
+ image.label = label.trim()
321
+ image.status = status
322
+ if (Object.hasOwn(changes, 'conditions')) {
323
+ const conditions = sceneConditions(changes.conditions)
324
+ if (Object.keys(conditions).length) image.conditions = conditions
325
+ else delete image.conditions
326
+ }
327
+ if (promptChanged) {
328
+ image.prompt = prompt
329
+ delete image.promptRecord
330
+ delete image.promptEntry
331
+ }
332
+ await writeIndex(dir, data)
333
+ } catch (cause) {
334
+ if (archive) await fs.rm(archive, { recursive: true, force: true })
335
+ throw cause
336
+ }
337
+ }
338
+
339
+ async function updateFolderMedia(dir, data, patch, library) {
340
+ const { items, cover } = await folderImages(dir, data, library)
341
+ data.images = items
342
+ data.mainImage = cover?.id || null
343
+ const upload = patch.image
344
+ if (library.isProp && !upload) throw error(400, '请在主图页签单独上传主图')
345
+ const old = items.find(image => image.id === (upload?.id || patch.mainImage))
346
+ const before = old && await localFile(dir, old.file)
347
+ if (upload?.id && !old) throw error(404, '找不到要替换的素材')
348
+
349
+ if (upload && !Object.hasOwn(upload, 'base64')) {
350
+ return updateImageFields(dir, data, old, before, upload, library)
351
+ }
352
+
353
+ if (!upload && !before) throw error(400, '请选择存在的图片')
354
+ if (!upload && old === cover && isRootCover(old.file)) return
355
+
356
+ const promotion = !upload
357
+ if (library.isProp && old && (old === cover) !== (upload.main === true)) {
358
+ throw error(400, '请在对应页签替换图片')
359
+ }
360
+ if (upload?.main && old && cover && old !== cover) throw error(400, '请先设置主图,再替换图片')
361
+ const main = promotion || upload.main === true || (old && old === cover) || (!library.isProp && !cover && upload.main !== false)
362
+ const { ext, fields, bytes } = promotion
363
+ ? { ext: path.extname(before).toLowerCase(), fields: old, bytes: await fs.readFile(before) }
364
+ : readUpload(upload, library)
365
+ if (!Object.hasOwn(library.formats, ext)) throw error(400, '图片格式不受支持')
366
+ const previous = promotion ? cover : old || (main ? cover : null)
367
+ const previousFile = previous && await localFile(dir, previous.file)
368
+ const previousCover = previousFile && isRootCover(previous.file)
369
+ const sameFormat = previousCover && path.extname(previous.file).toLowerCase() === ext
370
+ const file = main ? (sameFormat ? previous.file : 'index' + ext) : await galleryFile(dir, fields.category, fields.label, ext, library)
371
+ const target = path.join(dir, file)
372
+ if (!sameFormat && await fileExists(target)) throw error(409, '已有同名主图,请先整理' + library.label + '目录')
373
+
374
+ const note = promotion ? '变更主图' : '替换「' + previous?.label + '」'
375
+ let archive
376
+ let demotedFile
377
+ let wroteTarget = false
378
+ let removedPrevious = false
379
+ try {
380
+ if (previousFile) archive = await savePrevious(dir, data, library, { image: previous, file: previousFile, note })
381
+ if (promotion && previousCover && previous !== old) {
382
+ const variant = await galleryFile(dir, previous.category, previous.label, path.extname(previous.file), library)
383
+ await fs.copyFile(previousFile, path.join(dir, variant), constants.COPYFILE_EXCL)
384
+ demotedFile = variant
385
+ previous.file = demotedFile
386
+ }
387
+ await write(target, bytes)
388
+ wroteTarget = true
389
+ if (previousCover && previousFile !== target) {
390
+ await fs.unlink(previousFile)
391
+ removedPrevious = true
392
+ }
393
+
394
+ const replaced = promotion ? old : previous
395
+ if (replaced && !isRootCover(replaced.file)) {
396
+ data.retainedImages = [...new Set([...retainedImageFiles(data), replaced.file])]
397
+ }
398
+ const entry = { id: replaced?.id || randomUUID(), ...fields, file }
399
+ data.images = replaced ? items.map(image => image === replaced ? entry : image) : [...items, entry]
400
+ if (main) data.mainImage = entry.id
401
+ await writeIndex(dir, data)
402
+ } catch (cause) {
403
+ if (wroteTarget) await fs.rm(target, { force: true })
404
+ if (removedPrevious || (wroteTarget && sameFormat)) {
405
+ await fs.copyFile(path.join(archive, path.basename(previousFile)), previousFile)
406
+ }
407
+ if (demotedFile) await fs.rm(path.join(dir, demotedFile), { force: true })
408
+ if (archive) await fs.rm(archive, { recursive: true, force: true })
409
+ throw cause
410
+ }
411
+ }
412
+
413
+ async function updateImageAssetMetadata(dir, data, patch, library, groups) {
414
+ if (typeof patch.story === 'string') {
415
+ const file = path.join(dir, 'README.md')
416
+ const oldStory = await read(file, null)
417
+ if (patch.story === (oldStory || '')) return
418
+ const archive = oldStory && await savePrevious(dir, data, library, { story: oldStory, note: '修改' + library.label + '说明' })
419
+ try {
420
+ await write(file, patch.story)
421
+ if (archive) await writeIndex(dir, data)
422
+ } catch (cause) {
423
+ if (archive) {
424
+ await write(file, oldStory)
425
+ await fs.rm(archive, { recursive: true, force: true })
426
+ }
427
+ throw cause
428
+ }
429
+ } else if (['name', 'tags', 'note'].some(key => Object.hasOwn(patch, key))
430
+ || (library.isAudio && Object.hasOwn(patch, 'type'))) {
431
+ if (library.isAudio && Object.hasOwn(patch, 'type')) {
432
+ if (patch.type !== '' && !Object.hasOwn(library.groups, patch.type)) throw error(400, '请选择有效的音频类型')
433
+ if (patch.type) data.type = patch.type
434
+ else delete data.type
435
+ }
436
+ if (Object.hasOwn(patch, 'name')) {
437
+ const name = typeof patch.name === 'string' ? patch.name.trim() : ''
438
+ if (!name) throw error(400, '请输入' + library.label + '名称')
439
+ data.name = name
440
+ }
441
+ if (Object.hasOwn(patch, 'note')) {
442
+ if (typeof patch.note !== 'string') throw error(400, '备注必须是文本')
443
+ data.note = patch.note
444
+ }
445
+ if (Object.hasOwn(patch, 'tags')) {
446
+ const saved = library.isProp ? savedPropTags(data) : savedAssetTags(data)
447
+ const tags = normalizeTags(patch.tags)
448
+ if (library.isAudio) data.tags = tags
449
+ else saveTags(data, tags, groups, saved)
450
+ }
451
+ await writeIndex(dir, data)
452
+ } else {
453
+ throw error(400, '没有可保存的内容')
454
+ }
455
+ }
456
+
457
+ async function update(dir, patch, library, groups) {
458
+ const data = await meta(dir)
459
+ if (!library.isAudio) {
460
+ if (patch.image || typeof patch.mainImage === 'string') {
461
+ await updateFolderMedia(dir, data, patch, library)
462
+ } else {
463
+ await updateImageAssetMetadata(dir, data, patch, library, groups)
464
+ }
465
+ return describe(dir, true, library, groups)
466
+ }
467
+ const items = data[library.entriesKey] ??= []
468
+ const upload = patch.track
469
+ if (upload) {
470
+ const { id } = upload
471
+ const old = items.find(entry => entry.id === id)
472
+ if (id && !old) throw error(404, '找不到要替换的素材')
473
+ const previous = old && await localFile(dir, old.file)
474
+ const { ext, bytes, fields } = readUpload(library.isAudio && data.type ? { ...upload, category: data.type } : upload, library)
475
+ const imageId = old?.id || randomUUID()
476
+ const mediaDir = path.join(dir, library.mediaFolder)
477
+ await fs.mkdir(mediaDir, { recursive: true })
478
+ if (await fs.realpath(mediaDir) !== mediaDir) throw error(400, '素材目录必须位于' + library.label + '目录内')
479
+ const file = library.mediaFolder + '/' + randomUUID() + ext
480
+ await write(path.join(dir, file), bytes)
481
+ let archive
482
+ try {
483
+ if (previous) archive = await savePrevious(dir, data, library, { image: old, file: previous, note: '替换「' + old.label + '」' })
484
+ const entry = {
485
+ id: imageId, file, ...fields,
486
+ source: typeof upload.source === 'string' ? upload.source.trim() : '',
487
+ usage: typeof upload.usage === 'string' ? upload.usage.trim() : '',
488
+ loop: upload.loop === true,
489
+ }
490
+ data[library.entriesKey] = old ? items.map(image => image === old ? entry : image) : [...items, entry]
491
+ data[library.mainKey] ||= imageId
492
+ await writeIndex(dir, data)
493
+ } catch (cause) {
494
+ await fs.rm(path.join(dir, file), { force: true })
495
+ if (archive) await fs.rm(archive, { recursive: true, force: true })
496
+ throw cause
497
+ }
498
+ } else if (typeof patch.mainImage === 'string') {
499
+ const selected = items.find(image => image.id === patch.mainImage)
500
+ if (!selected || !await localFile(dir, selected.file)) throw error(400, '请选择存在的图片')
501
+ data[library.mainKey] = selected.id
502
+ await writeIndex(dir, data)
503
+ } else if (typeof patch.story === 'string') {
504
+ await write(path.join(dir, 'README.md'), patch.story)
505
+ } else {
506
+ await updateImageAssetMetadata(dir, data, patch, library, groups)
507
+ }
508
+ return describe(dir, true, library, groups)
509
+ }
510
+
511
+ async function readBody(req) {
512
+ const chunks = []
513
+ let length = 0
514
+ for await (const chunk of req) {
515
+ length += chunk.length
516
+ if (length > 41 * 1024 * 1024) throw error(413, '文件大小超过 30 MB')
517
+ chunks.push(chunk)
518
+ }
519
+ try {
520
+ return JSON.parse(Buffer.concat(chunks))
521
+ } catch {
522
+ throw error(400, '请求格式无效')
523
+ }
524
+ }
525
+
526
+ async function streamAudio(file, req, res) {
527
+ const { size } = await fs.stat(file)
528
+ res.setHeader('Accept-Ranges', 'bytes')
529
+ const range = req.headers.range
530
+ if (!range) {
531
+ res.setHeader('Content-Length', size)
532
+ return createReadStream(file).on('error', () => res.destroy()).pipe(res)
533
+ }
534
+ const match = /^bytes=(\d*)-(\d*)$/.exec(range)
535
+ const start = match?.[1] ? Number(match[1]) : Math.max(size - Number(match?.[2]), 0)
536
+ const end = match?.[1] && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1
537
+ if (!match || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end) {
538
+ res.statusCode = 416
539
+ res.setHeader('Content-Range', 'bytes */' + size)
540
+ return res.end()
541
+ }
542
+ res.statusCode = 206
543
+ res.setHeader('Content-Range', 'bytes ' + start + '-' + end + '/' + size)
544
+ res.setHeader('Content-Length', end - start + 1)
545
+ return createReadStream(file, { start, end }).on('error', () => res.destroy()).pipe(res)
546
+ }
547
+
548
+ export function imageAssets(kind) {
549
+ const isProp = kind === 'props'
550
+ const isAudio = kind === 'audio'
551
+ const library = {
552
+ isProp, isAudio,
553
+ entriesKey: isAudio ? 'tracks' : 'images',
554
+ mainKey: isAudio ? 'mainTrack' : 'mainImage',
555
+ mediaFolder: isAudio ? 'tracks' : 'images',
556
+ galleryFolders: ({ props: propFolders, scenes: sceneFolders, other: otherFolders })[kind],
557
+ defaultCategory: ({ props: 'angle', scenes: 'view', other: 'graphic' })[kind],
558
+ formats: isAudio ? audioTypes : types,
559
+ root: assetRoot(kind),
560
+ mediaPath: '/' + ({ props: 'prop', scenes: 'scene', audio: 'audio', other: 'other' })[kind] + '-media',
561
+ groups: ({ props: propGroups, scenes: sceneGroups, audio: audioGroups, other: otherGroups })[kind],
562
+ label: ({ props: '道具', scenes: '场景', audio: '音频', other: '其他素材' })[kind],
563
+ }
564
+ const apiPath = '/api/' + kind
565
+ let mutations = Promise.resolve()
566
+ return {
567
+ name: 'workbench-' + kind,
568
+ configureServer(server) {
569
+ server.middlewares.use(async (req, res, next) => {
570
+ const request = new URL(req.url, 'http://localhost')
571
+ if (![apiPath, library.mediaPath].includes(request.pathname)) return next()
572
+ try {
573
+ if (req.method === 'GET') await mutations
574
+ if (request.pathname === library.mediaPath) {
575
+ const file = await localFile(library.root, request.searchParams.get('file'))
576
+ const mime = file && library.formats[path.extname(file).toLowerCase()]
577
+ if (req.method !== 'GET' || !mime) throw error(404, '素材不存在')
578
+ res.setHeader('Content-Type', mime)
579
+ res.setHeader('Cache-Control', 'no-cache')
580
+ if (isAudio) {
581
+ await streamAudio(file, req, res)
582
+ return
583
+ }
584
+ createReadStream(file).on('error', () => res.destroy()).pipe(res)
585
+ return
586
+ }
587
+ const id = request.searchParams.get('id')
588
+ let result
589
+ if (req.method === 'GET') {
590
+ if (id) {
591
+ const asset = await existingAsset(id, library)
592
+ result = await describe(asset.dir, true, library, asset.groups)
593
+ } else {
594
+ const assets = await scanAssets(library.root, library.isAudio ? undefined : isRootCover)
595
+ result = await Promise.all(assets.sort((a, b) => sort(a.id, b.id)).map(asset => describe(asset.dir, false, library, asset.groups)))
596
+ }
597
+ } else if (['PATCH', 'POST', 'DELETE'].includes(req.method)) {
598
+ if (req.headers['x-workbench'] !== 'local') throw error(403, '请求来源无效')
599
+ const patch = req.method === 'DELETE' ? null : await readBody(req)
600
+ const operation = mutations.then(async () => {
601
+ if (req.method === 'DELETE') {
602
+ const asset = await existingAsset(id, library)
603
+ return deleteAssetDirectory(library.root, asset.dir)
604
+ }
605
+ if (req.method === 'PATCH') {
606
+ const asset = await existingAsset(id, library)
607
+ return update(asset.dir, patch, library, asset.groups)
608
+ }
609
+ const tags = Object.hasOwn(patch, 'tags') ? normalizeTags(patch.tags) : []
610
+ const audioMetadata = {}
611
+ if (isAudio && Object.hasOwn(patch, 'type')) {
612
+ if (!Object.hasOwn(library.groups, patch.type)) throw error(400, '请选择有效的音频类型')
613
+ audioMetadata.type = patch.type
614
+ }
615
+ if (isAudio && Object.hasOwn(patch, 'note')) {
616
+ if (typeof patch.note !== 'string') throw error(400, '备注必须是文本')
617
+ audioMetadata.note = patch.note
618
+ }
619
+ const dir = newAssetDirectory(patch.name, library)
620
+ await fs.mkdir(dir).catch(cause => {
621
+ if (cause.code === 'EEXIST') throw error(409, '已有同名' + library.label)
622
+ throw cause
623
+ })
624
+ const folders = library.galleryFolders ? Object.values(library.galleryFolders) : [library.mediaFolder]
625
+ await Promise.all(folders.map(folder => fs.mkdir(path.join(dir, folder))))
626
+ await fs.mkdir(path.join(dir, 'archive'))
627
+ await write(path.join(dir, 'README.md'), '')
628
+ await writeIndex(dir, {
629
+ name: patch.name,
630
+ tags,
631
+ ...audioMetadata,
632
+ [library.mainKey]: null, [library.entriesKey]: [], history: [],
633
+ })
634
+ return describe(dir, true, library)
635
+ })
636
+ mutations = operation.catch(() => {})
637
+ result = await operation
638
+ } else {
639
+ throw error(405, '请求方法不支持')
640
+ }
641
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
642
+ res.setHeader('Cache-Control', 'no-store')
643
+ res.end(JSON.stringify(result))
644
+ } catch (cause) {
645
+ res.statusCode = cause.status || 500
646
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
647
+ res.end(JSON.stringify({ error: cause.message }))
648
+ }
649
+ })
650
+ },
651
+ }
652
+ }
@@ -0,0 +1,15 @@
1
+ import { assetWatch } from './asset-watch.js'
2
+ import { characterAssets } from './character-assets.js'
3
+ import { imageAssets } from './image-assets.js'
4
+ import { projectBrand } from './project-brand.js'
5
+ import { projectSettings } from './project-settings.js'
6
+
7
+ export function workbenchPlugins() {
8
+ return [
9
+ characterAssets(),
10
+ ...['scenes', 'props', 'other', 'audio'].map(imageAssets),
11
+ projectSettings(),
12
+ projectBrand(),
13
+ assetWatch(),
14
+ ]
15
+ }