@2kog/kacha 0.1.2 → 0.2.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.
- package/README.md +49 -2
- package/bin/clone-project.js +88 -0
- package/bin/init-project.js +18 -26
- package/bin/kacha.js +23 -1
- package/bin/lfs-setup.js +75 -0
- package/bin/lfs-transfer.js +235 -0
- package/package.json +3 -1
- package/server/index.js +6 -0
- package/server/oss-collab-local.js +318 -0
- package/server/oss-collab-plan.js +270 -0
- package/server/oss-collab-remote.js +288 -0
- package/server/oss-sync-engine.js +434 -0
- package/server/project-brand.js +93 -2
- package/server/project-global.js +83 -0
- package/server/project-oss-sync.js +200 -0
- package/server/project-storage.js +164 -0
- package/skills/manage-assets/SKILL.md +11 -0
- package/skills/sync-jimeng-assets/SKILL.md +27 -0
- package/src/assets/css/workbench.css +227 -20
- package/src/components/AssetTagInput.vue +0 -2
- package/src/components/ProjectOssSync.vue +486 -0
- package/src/i18n/en.json +118 -0
- package/src/i18n/index.js +2 -5
- package/src/layouts/WorkbenchLayout.vue +277 -7
- package/src/main.js +1 -1
- package/src/service/jimeng.js +8 -0
- package/src/views/assets/AudioAssets.vue +12 -11
- package/src/views/assets/CharacterAssets.vue +122 -19
- package/src/views/assets/ImageAssets.vue +112 -30
- package/templates/project/.gitattributes +49 -0
- package/templates/project/AGENTS.md +10 -0
- package/templates/project/README.md +9 -1
- package/vite.config.js +1 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
+
import { constants, createWriteStream } from 'node:fs'
|
|
4
|
+
import { link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { devNull } from 'node:os'
|
|
6
|
+
import { dirname, extname, join } from 'node:path'
|
|
7
|
+
import { Transform } from 'node:stream'
|
|
8
|
+
import { pipeline } from 'node:stream/promises'
|
|
9
|
+
|
|
10
|
+
const multipartThreshold = 32 * 1024 * 1024
|
|
11
|
+
const partSize = 8 * 1024 * 1024
|
|
12
|
+
const excludedNames = ['.git', '.kacha', 'node_modules', '.env', '.env.*']
|
|
13
|
+
const sha256 = input => createHash('sha256').update(input).digest('hex')
|
|
14
|
+
|
|
15
|
+
function syncError(code) {
|
|
16
|
+
return Object.assign(new Error(code), { code })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function checkStopped(signal) {
|
|
20
|
+
if (signal?.aborted) throw syncError('OSS_SYNC_STOPPED')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isExcluded(name) {
|
|
24
|
+
const lower = name.toLowerCase()
|
|
25
|
+
return lower === '.git' || lower === '.kacha' || lower === 'node_modules' || lower === '.env' || lower.startsWith('.env.')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isSafeFile(file) {
|
|
29
|
+
return file.split('/').every(part => part && part !== '.' && part !== '..' && !isExcluded(part))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function ensureDirectory(directory) {
|
|
33
|
+
await mkdir(directory, { mode: 0o700 }).catch(error => {
|
|
34
|
+
if (error.code !== 'EEXIST') throw error
|
|
35
|
+
})
|
|
36
|
+
if (!(await lstat(directory)).isDirectory()) throw syncError('OSS_SYNC_STATE_FAILED')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function readJson(file) {
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse(await readFile(file, 'utf8'))
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error.code === 'ENOENT') return null
|
|
44
|
+
throw error
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function writeRecord(file, value) {
|
|
49
|
+
const temp = file + '.' + randomUUID() + '.tmp'
|
|
50
|
+
try {
|
|
51
|
+
await writeFile(temp, JSON.stringify(value) + '\n', { mode: 0o600, flag: 'wx' })
|
|
52
|
+
await rename(temp, file)
|
|
53
|
+
} catch {
|
|
54
|
+
throw syncError('OSS_SYNC_STATE_FAILED')
|
|
55
|
+
} finally {
|
|
56
|
+
await rm(temp, { force: true }).catch(() => {})
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function processIsAlive(pid) {
|
|
61
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return true
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 0)
|
|
64
|
+
return true
|
|
65
|
+
} catch (error) {
|
|
66
|
+
return error.code !== 'ESRCH'
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function reclaimLock(directory, lock, owner, candidate) {
|
|
71
|
+
const claims = []
|
|
72
|
+
let stale = owner
|
|
73
|
+
for (let attempt = 0; attempt < 32; attempt++) {
|
|
74
|
+
if (processIsAlive(stale.pid) || !/^[a-f0-9-]{36}$/.test(stale.token)) throw syncError('OSS_SYNC_BUSY')
|
|
75
|
+
const claim = join(directory, 'reclaim-' + stale.token)
|
|
76
|
+
try {
|
|
77
|
+
await link(candidate, claim)
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error.code !== 'EEXIST') throw error
|
|
80
|
+
stale = await readJson(claim)
|
|
81
|
+
if (!stale) return
|
|
82
|
+
claims.push(claim)
|
|
83
|
+
continue
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
if ((await readJson(lock))?.token === owner.token) await rm(lock, { force: true })
|
|
88
|
+
} finally {
|
|
89
|
+
await Promise.all([...claims, claim].map(file => rm(file, { force: true })))
|
|
90
|
+
}
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
throw syncError('OSS_SYNC_BUSY')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function acquireLock(directory) {
|
|
97
|
+
const lock = join(directory, 'engine.lock')
|
|
98
|
+
const token = randomUUID()
|
|
99
|
+
const candidate = join(directory, 'lock-' + token)
|
|
100
|
+
await writeFile(candidate, JSON.stringify({ pid: process.pid, token }), { mode: 0o600, flag: 'wx' })
|
|
101
|
+
try {
|
|
102
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
103
|
+
try {
|
|
104
|
+
await link(candidate, lock)
|
|
105
|
+
return async () => {
|
|
106
|
+
if ((await readJson(lock))?.token === token) await rm(lock, { force: true })
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error.code !== 'EEXIST') throw error
|
|
110
|
+
const owner = await readJson(lock)
|
|
111
|
+
if (!owner) continue
|
|
112
|
+
// Each immutable claim identifies its process. Another process can
|
|
113
|
+
// continue reclamation if the claimant itself was interrupted.
|
|
114
|
+
await reclaimLock(directory, lock, owner, candidate)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
throw syncError('OSS_SYNC_BUSY')
|
|
118
|
+
} finally {
|
|
119
|
+
await rm(candidate, { force: true })
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function runGit(root, args, { input, allowNoMatches = false, signal } = {}) {
|
|
124
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')))
|
|
125
|
+
env.GIT_CONFIG_NOSYSTEM = '1'
|
|
126
|
+
env.GIT_CONFIG_GLOBAL = devNull
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
const child = execFile('git', args, { cwd: root, env, encoding: 'buffer', signal, maxBuffer: 64 * 1024 * 1024 },
|
|
129
|
+
(error, output) => {
|
|
130
|
+
if (error && !(allowNoMatches && error.code === 1)) reject(error)
|
|
131
|
+
else resolve(output)
|
|
132
|
+
})
|
|
133
|
+
child.stdin.on('error', () => {})
|
|
134
|
+
child.stdin.end(input)
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function listNestedFiles(root, directory, signal) {
|
|
139
|
+
const files = []
|
|
140
|
+
const pending = [directory]
|
|
141
|
+
while (pending.length) {
|
|
142
|
+
checkStopped(signal)
|
|
143
|
+
const relative = pending.pop()
|
|
144
|
+
for (const entry of await readdir(join(root, relative), { withFileTypes: true })) {
|
|
145
|
+
if (isExcluded(entry.name)) continue
|
|
146
|
+
const file = relative + '/' + entry.name
|
|
147
|
+
if (entry.isDirectory()) pending.push(file)
|
|
148
|
+
else if (entry.isFile()) files.push(file)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return files
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function gitWorkTree(root, scratch, signal) {
|
|
155
|
+
const gitDirectory = join(scratch, 'git')
|
|
156
|
+
await runGit(root, ['init', '--bare', '--quiet', '--template=', gitDirectory], { signal })
|
|
157
|
+
return ['--git-dir=' + gitDirectory, '--work-tree=' + root, '-c', 'core.precomposeUnicode=false']
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function filterProjectFiles(root, scratch, files, signal, context) {
|
|
161
|
+
if (!files.length) return []
|
|
162
|
+
context ??= await gitWorkTree(root, scratch, signal)
|
|
163
|
+
const ignored = await runGit(root, [...context, 'check-ignore', '--no-index', '--stdin', '-z'], {
|
|
164
|
+
input: files.join('\0') + '\0', allowNoMatches: true, signal,
|
|
165
|
+
})
|
|
166
|
+
const omitted = new Set(ignored.toString('utf8').split('\0'))
|
|
167
|
+
return files.filter(file => !omitted.has(file))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function scanProject(root, scratch, signal) {
|
|
171
|
+
try {
|
|
172
|
+
const context = await gitWorkTree(root, scratch, signal)
|
|
173
|
+
const output = await runGit(root, [
|
|
174
|
+
...context, 'ls-files', '--others', '--exclude-per-directory=.gitignore',
|
|
175
|
+
...excludedNames.map(name => '--exclude=' + name), '-z',
|
|
176
|
+
], { signal })
|
|
177
|
+
|
|
178
|
+
const files = []
|
|
179
|
+
const nestedFiles = []
|
|
180
|
+
for (const entry of output.toString('utf8').split('\0')) {
|
|
181
|
+
const relative = entry.endsWith('/') ? entry.slice(0, -1) : entry
|
|
182
|
+
if (!isSafeFile(relative)) continue
|
|
183
|
+
if (entry.endsWith('/')) nestedFiles.push(...await listNestedFiles(root, relative, signal))
|
|
184
|
+
else files.push(relative)
|
|
185
|
+
}
|
|
186
|
+
files.push(...await filterProjectFiles(root, scratch, nestedFiles, signal, context))
|
|
187
|
+
const regular = []
|
|
188
|
+
for (const file of files) {
|
|
189
|
+
checkStopped(signal)
|
|
190
|
+
const localFile = join(root, file)
|
|
191
|
+
const info = await lstat(localFile).catch(error => {
|
|
192
|
+
if (error.code !== 'ENOENT') throw error
|
|
193
|
+
return null
|
|
194
|
+
})
|
|
195
|
+
if (info?.isFile()) regular.push({ file, size: info.size })
|
|
196
|
+
}
|
|
197
|
+
return regular
|
|
198
|
+
} catch {
|
|
199
|
+
checkStopped(signal)
|
|
200
|
+
throw syncError('OSS_SYNC_SCAN_FAILED')
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function sameFile(a, b) {
|
|
205
|
+
return a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino && a.size === b.size &&
|
|
206
|
+
a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function checkSource(file, previous) {
|
|
210
|
+
if (await realpath(dirname(file)) !== dirname(file) || !sameFile(previous, await lstat(file, { bigint: true }))) {
|
|
211
|
+
throw syncError('OSS_SYNC_FILE_CHANGED')
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function fingerprint(source, size, signal) {
|
|
216
|
+
const hash = createHash('sha256')
|
|
217
|
+
if (size > 0) {
|
|
218
|
+
for await (const chunk of source.createReadStream({ autoClose: false, start: 0, end: size - 1, signal })) {
|
|
219
|
+
hash.update(chunk)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
checkStopped(signal)
|
|
223
|
+
return hash.digest('hex')
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function createSnapshot(source, size, snapshot, signal) {
|
|
227
|
+
const hash = createHash('sha256')
|
|
228
|
+
if (!size) {
|
|
229
|
+
await writeFile(snapshot, '', { mode: 0o600, flag: 'wx' })
|
|
230
|
+
return hash.digest('hex')
|
|
231
|
+
}
|
|
232
|
+
const trackHash = new Transform({
|
|
233
|
+
transform(chunk, _encoding, callback) {
|
|
234
|
+
hash.update(chunk)
|
|
235
|
+
callback(null, chunk)
|
|
236
|
+
},
|
|
237
|
+
})
|
|
238
|
+
await pipeline(
|
|
239
|
+
source.createReadStream({ autoClose: false, start: 0, end: size - 1 }),
|
|
240
|
+
trackHash,
|
|
241
|
+
createWriteStream(snapshot, { mode: 0o600, flags: 'wx' }),
|
|
242
|
+
{ signal },
|
|
243
|
+
)
|
|
244
|
+
return hash.digest('hex')
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function readRecord(file) {
|
|
248
|
+
try {
|
|
249
|
+
return await readJson(file)
|
|
250
|
+
} catch {
|
|
251
|
+
throw syncError('OSS_SYNC_STATE_FAILED')
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function expiredCheckpoint(error) {
|
|
256
|
+
return error.name === 'abort' || error.code === 'NoSuchUpload' || error.status === 404
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function uploadFile({ client, file, key, snapshot, size, fingerprint, checkpoint, recordFile, signal, progress }) {
|
|
260
|
+
if (size < multipartThreshold) {
|
|
261
|
+
await client.put(key, snapshot)
|
|
262
|
+
return
|
|
263
|
+
}
|
|
264
|
+
const options = {
|
|
265
|
+
partSize,
|
|
266
|
+
parallel: 1,
|
|
267
|
+
async progress(fraction, current) {
|
|
268
|
+
if (current) {
|
|
269
|
+
const { file: _snapshot, ...state } = current
|
|
270
|
+
await writeRecord(recordFile, { file, fingerprint, checkpoint: state })
|
|
271
|
+
}
|
|
272
|
+
progress(Math.round(fraction * 100))
|
|
273
|
+
checkStopped(signal)
|
|
274
|
+
},
|
|
275
|
+
}
|
|
276
|
+
if (checkpoint?.name === key && checkpoint.fileSize === size && checkpoint.uploadId) {
|
|
277
|
+
options.checkpoint = { ...checkpoint, file: snapshot }
|
|
278
|
+
try {
|
|
279
|
+
await client.multipartUpload(key, snapshot, options)
|
|
280
|
+
return
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (!expiredCheckpoint(error)) throw error
|
|
283
|
+
checkStopped(signal)
|
|
284
|
+
await writeRecord(recordFile, { file, fingerprint })
|
|
285
|
+
delete options.checkpoint
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
await client.multipartUpload(key, snapshot, options)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function syncFile({ client, root, file, key, scratch, recordFile, signal, progress }) {
|
|
292
|
+
const localFile = join(root, file)
|
|
293
|
+
let snapshot
|
|
294
|
+
let source
|
|
295
|
+
let stage = 'read'
|
|
296
|
+
try {
|
|
297
|
+
if (await realpath(dirname(localFile)) !== dirname(localFile)) throw syncError('OSS_SYNC_FILE_CHANGED')
|
|
298
|
+
source = await open(localFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
299
|
+
const info = await source.stat({ bigint: true })
|
|
300
|
+
if (!info.isFile()) throw syncError('OSS_SYNC_FILE_CHANGED')
|
|
301
|
+
const size = Number(info.size)
|
|
302
|
+
const digest = await fingerprint(source, size, signal)
|
|
303
|
+
await checkSource(localFile, info)
|
|
304
|
+
const record = await readRecord(recordFile)
|
|
305
|
+
if (record?.completed === digest) return 'skipped'
|
|
306
|
+
snapshot = join(scratch, 'upload-' + randomUUID() + extname(file))
|
|
307
|
+
const copied = await createSnapshot(source, size, snapshot, signal)
|
|
308
|
+
await checkSource(localFile, info)
|
|
309
|
+
if (copied !== digest) throw syncError('OSS_SYNC_FILE_CHANGED')
|
|
310
|
+
await source.close()
|
|
311
|
+
source = null
|
|
312
|
+
checkStopped(signal)
|
|
313
|
+
|
|
314
|
+
stage = 'upload'
|
|
315
|
+
await uploadFile({
|
|
316
|
+
client, file, key, snapshot, size, fingerprint: digest, recordFile, signal, progress,
|
|
317
|
+
checkpoint: record?.fingerprint === digest ? record.checkpoint : null,
|
|
318
|
+
})
|
|
319
|
+
await writeRecord(recordFile, { file, completed: digest })
|
|
320
|
+
stage = 'read'
|
|
321
|
+
await checkSource(localFile, info)
|
|
322
|
+
return 'uploaded'
|
|
323
|
+
} catch (error) {
|
|
324
|
+
checkStopped(signal)
|
|
325
|
+
if (error.code === 'OSS_SYNC_STATE_FAILED') throw error
|
|
326
|
+
if (error.code === 'OSS_SYNC_FILE_CHANGED' || (stage === 'read' && ['ENOENT', 'ELOOP'].includes(error.code))) {
|
|
327
|
+
return { code: 'OSS_SYNC_FILE_CHANGED' }
|
|
328
|
+
}
|
|
329
|
+
if (stage === 'read') return { code: 'OSS_SYNC_FILE_UNREADABLE' }
|
|
330
|
+
const status = Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 ? error.status : undefined
|
|
331
|
+
return { code: 'OSS_SYNC_UPLOAD_FAILED', status }
|
|
332
|
+
} finally {
|
|
333
|
+
if (source) await source.close().catch(() => {})
|
|
334
|
+
if (snapshot) await rm(snapshot, { force: true }).catch(() => {})
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async function withSyncWorkspace(root, signal, run) {
|
|
339
|
+
let release
|
|
340
|
+
let scratch
|
|
341
|
+
try {
|
|
342
|
+
root = await realpath(root)
|
|
343
|
+
const cache = join(root, '.kacha')
|
|
344
|
+
const state = join(cache, 'oss-sync')
|
|
345
|
+
await ensureDirectory(cache)
|
|
346
|
+
await ensureDirectory(state)
|
|
347
|
+
release = await acquireLock(state)
|
|
348
|
+
checkStopped(signal)
|
|
349
|
+
for (const entry of await readdir(state, { withFileTypes: true })) {
|
|
350
|
+
if (entry.isDirectory() && /^work-[a-z0-9]{6}$/i.test(entry.name)) {
|
|
351
|
+
await rm(join(state, entry.name), { recursive: true })
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
scratch = await mkdtemp(join(state, 'work-'))
|
|
355
|
+
return await run({ root, state, scratch })
|
|
356
|
+
} finally {
|
|
357
|
+
if (scratch) await rm(scratch, { recursive: true, force: true }).catch(() => {})
|
|
358
|
+
if (release) await release().catch(() => {})
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export async function syncProject({ root: projectRoot, client, destination, onProgress, signal }) {
|
|
363
|
+
try {
|
|
364
|
+
return await withSyncWorkspace(projectRoot, signal, async ({ root, state, scratch }) => {
|
|
365
|
+
const job = {
|
|
366
|
+
phase: 'scanning', total: 0, uploaded: 0, skipped: 0, failed: 0,
|
|
367
|
+
currentFile: '', currentPercent: 0, totalBytes: 0, processedBytes: 0, failures: [],
|
|
368
|
+
}
|
|
369
|
+
const emit = () => {
|
|
370
|
+
const value = { ...job, failures: [...job.failures] }
|
|
371
|
+
onProgress?.(value)
|
|
372
|
+
return value
|
|
373
|
+
}
|
|
374
|
+
emit()
|
|
375
|
+
checkStopped(signal)
|
|
376
|
+
|
|
377
|
+
const prefix = (destination.prefix || '').replace(/^\/+|\/+$/g, '')
|
|
378
|
+
const records = join(state, sha256(JSON.stringify([destination.endpoint, destination.bucket, prefix])))
|
|
379
|
+
await ensureDirectory(records)
|
|
380
|
+
const files = await scanProject(root, scratch, signal)
|
|
381
|
+
job.total = files.length
|
|
382
|
+
job.totalBytes = files.reduce((total, entry) => total + entry.size, 0)
|
|
383
|
+
job.phase = 'uploading'
|
|
384
|
+
emit()
|
|
385
|
+
|
|
386
|
+
for (const { file, size } of files) {
|
|
387
|
+
checkStopped(signal)
|
|
388
|
+
job.currentFile = file
|
|
389
|
+
job.currentPercent = 0
|
|
390
|
+
emit()
|
|
391
|
+
const result = await syncFile({
|
|
392
|
+
client, root, file, key: prefix ? prefix + '/' + file : file, scratch, signal,
|
|
393
|
+
recordFile: join(records, sha256(file) + '.json'),
|
|
394
|
+
progress(percent) {
|
|
395
|
+
job.currentPercent = percent
|
|
396
|
+
emit()
|
|
397
|
+
},
|
|
398
|
+
})
|
|
399
|
+
if (typeof result === 'string') {
|
|
400
|
+
job[result]++
|
|
401
|
+
} else {
|
|
402
|
+
job.failed++
|
|
403
|
+
job.failures.push({ file, ...result })
|
|
404
|
+
}
|
|
405
|
+
job.processedBytes += size
|
|
406
|
+
job.currentFile = ''
|
|
407
|
+
job.currentPercent = 0
|
|
408
|
+
emit()
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return emit()
|
|
412
|
+
})
|
|
413
|
+
} catch (error) {
|
|
414
|
+
checkStopped(signal)
|
|
415
|
+
if (['OSS_SYNC_BUSY', 'OSS_SYNC_SCAN_FAILED', 'OSS_SYNC_STATE_FAILED'].includes(error.code)) throw error
|
|
416
|
+
throw syncError('OSS_SYNC_STATE_FAILED')
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export {
|
|
421
|
+
checkSource,
|
|
422
|
+
checkStopped,
|
|
423
|
+
createSnapshot,
|
|
424
|
+
ensureDirectory,
|
|
425
|
+
filterProjectFiles,
|
|
426
|
+
fingerprint,
|
|
427
|
+
readRecord,
|
|
428
|
+
sameFile,
|
|
429
|
+
scanProject,
|
|
430
|
+
syncError,
|
|
431
|
+
uploadFile,
|
|
432
|
+
withSyncWorkspace,
|
|
433
|
+
writeRecord,
|
|
434
|
+
}
|
package/server/project-brand.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
2
3
|
import path from 'node:path'
|
|
3
4
|
import { projectRoot } from './project-paths.js'
|
|
4
5
|
|
|
@@ -22,7 +23,11 @@ async function readBrand() {
|
|
|
22
23
|
const name = typeof metadata?.name === 'string' ? metadata.name.trim() : ''
|
|
23
24
|
const description = typeof metadata?.description === 'string' ? metadata.description.trim() : ''
|
|
24
25
|
const files = await readdir(config, { withFileTypes: true }).catch(() => [])
|
|
25
|
-
|
|
26
|
+
const preferred = metadata?.kacha?.logo
|
|
27
|
+
const extensions = Object.keys(logoTypes)
|
|
28
|
+
if (extensions.includes(preferred)) extensions.unshift(...extensions.splice(extensions.indexOf(preferred), 1))
|
|
29
|
+
for (const extension of extensions) {
|
|
30
|
+
const type = logoTypes[extension]
|
|
26
31
|
const filename = 'logo.' + extension
|
|
27
32
|
if (!files.some(file => file.name === filename && file.isFile())) continue
|
|
28
33
|
const image = await readFile(path.join(config, filename)).catch(() => null)
|
|
@@ -42,6 +47,92 @@ export function projectBrand() {
|
|
|
42
47
|
if (source === '\0' + id) return 'export default ' + JSON.stringify(await readBrand())
|
|
43
48
|
},
|
|
44
49
|
configureServer(server) {
|
|
50
|
+
let pendingSave = Promise.resolve()
|
|
51
|
+
server.middlewares.use('/api/project-config', async (req, res) => {
|
|
52
|
+
const send = (status, data) => {
|
|
53
|
+
res.statusCode = status
|
|
54
|
+
res.setHeader('Content-Type', 'application/json')
|
|
55
|
+
res.end(JSON.stringify(data))
|
|
56
|
+
}
|
|
57
|
+
if (req.method !== 'PUT') return send(405, {})
|
|
58
|
+
if (req.headers['content-type'] !== 'application/json') return send(415, {})
|
|
59
|
+
|
|
60
|
+
let fields
|
|
61
|
+
try {
|
|
62
|
+
const chunks = []
|
|
63
|
+
let size = 0
|
|
64
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
65
|
+
size += chunk.length
|
|
66
|
+
if (size > 3 * 1024 * 1024) {
|
|
67
|
+
req.resume()
|
|
68
|
+
return send(413, {})
|
|
69
|
+
}
|
|
70
|
+
chunks.push(chunk)
|
|
71
|
+
}
|
|
72
|
+
fields = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
73
|
+
} catch {
|
|
74
|
+
return send(400, {})
|
|
75
|
+
}
|
|
76
|
+
if (typeof fields?.name !== 'string' || typeof fields?.description !== 'string') return send(400, {})
|
|
77
|
+
const upload = fields.logo
|
|
78
|
+
let image
|
|
79
|
+
if (upload != null) {
|
|
80
|
+
if (!Object.hasOwn(logoTypes, upload.extension) || typeof upload.data !== 'string') return send(400, {})
|
|
81
|
+
image = Buffer.from(upload.data, 'base64')
|
|
82
|
+
if (!image.length || image.length > 2 * 1024 * 1024 || image.toString('base64') !== upload.data) return send(400, {})
|
|
83
|
+
}
|
|
84
|
+
const name = fields.name.trim()
|
|
85
|
+
const description = fields.description.trim()
|
|
86
|
+
const save = pendingSave.then(async () => {
|
|
87
|
+
const metadata = await readFile(manifest, 'utf8').then(JSON.parse).catch(error => {
|
|
88
|
+
if (error.code === 'ENOENT') return { private: true }
|
|
89
|
+
throw error
|
|
90
|
+
})
|
|
91
|
+
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) throw new Error('Invalid project manifest')
|
|
92
|
+
const temp = path.join(projectRoot, '.' + randomUUID() + '.tmp')
|
|
93
|
+
const logoTemp = path.join(config, path.basename(temp))
|
|
94
|
+
const updated = { ...metadata, name, description }
|
|
95
|
+
if (image) updated.kacha = { ...metadata.kacha, logo: upload.extension }
|
|
96
|
+
const logoPath = image ? path.join(config, 'logo.' + upload.extension) : null
|
|
97
|
+
let priorLogo
|
|
98
|
+
let logoWritten = false
|
|
99
|
+
try {
|
|
100
|
+
await writeFile(temp, JSON.stringify(updated, null, 2) + '\n')
|
|
101
|
+
if (image) {
|
|
102
|
+
await mkdir(config, { recursive: true })
|
|
103
|
+
priorLogo = await readFile(logoPath).catch(error => {
|
|
104
|
+
if (error.code !== 'ENOENT') throw error
|
|
105
|
+
})
|
|
106
|
+
await writeFile(logoTemp, image)
|
|
107
|
+
await rename(logoTemp, logoPath)
|
|
108
|
+
logoWritten = true
|
|
109
|
+
}
|
|
110
|
+
await rename(temp, manifest)
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (logoWritten) {
|
|
113
|
+
if (priorLogo) {
|
|
114
|
+
await writeFile(logoTemp, priorLogo)
|
|
115
|
+
await rename(logoTemp, logoPath)
|
|
116
|
+
} else {
|
|
117
|
+
await rm(logoPath, { force: true })
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
throw error
|
|
121
|
+
} finally {
|
|
122
|
+
await rm(temp, { force: true })
|
|
123
|
+
if (image) await rm(logoTemp, { force: true })
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
pendingSave = save.catch(() => {})
|
|
127
|
+
try {
|
|
128
|
+
await save
|
|
129
|
+
const module = server.moduleGraph.getModuleById('\0' + id)
|
|
130
|
+
if (module) server.moduleGraph.invalidateModule(module)
|
|
131
|
+
send(200, { name, description })
|
|
132
|
+
} catch {
|
|
133
|
+
send(500, {})
|
|
134
|
+
}
|
|
135
|
+
})
|
|
45
136
|
const refresh = filename => {
|
|
46
137
|
if (filename !== manifest && !filename.startsWith(path.join(config, 'logo.'))) return
|
|
47
138
|
const module = server.moduleGraph.getModuleById('\0' + id)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { projectRoot } from './project-paths.js'
|
|
5
|
+
|
|
6
|
+
const id = 'virtual:project-global'
|
|
7
|
+
const file = join(projectRoot, 'config', 'global.json')
|
|
8
|
+
|
|
9
|
+
async function readSettings() {
|
|
10
|
+
try {
|
|
11
|
+
const settings = JSON.parse(await readFile(file, 'utf8'))
|
|
12
|
+
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
|
|
13
|
+
throw new Error('Invalid global settings')
|
|
14
|
+
}
|
|
15
|
+
return settings
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error.code === 'ENOENT') return {}
|
|
18
|
+
throw error
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function projectGlobal() {
|
|
23
|
+
let pendingSave = Promise.resolve()
|
|
24
|
+
return {
|
|
25
|
+
name: 'workbench-project-global',
|
|
26
|
+
resolveId(source) {
|
|
27
|
+
if (source === id) return '\0' + id
|
|
28
|
+
},
|
|
29
|
+
async load(source) {
|
|
30
|
+
if (source !== '\0' + id) return
|
|
31
|
+
const { locale } = await readSettings().catch(() => ({}))
|
|
32
|
+
return 'export default ' + JSON.stringify({ locale, projectRoot })
|
|
33
|
+
},
|
|
34
|
+
configureServer(server) {
|
|
35
|
+
server.middlewares.use('/api/project-global', async (req, res) => {
|
|
36
|
+
const send = status => {
|
|
37
|
+
res.statusCode = status
|
|
38
|
+
res.end()
|
|
39
|
+
}
|
|
40
|
+
if (req.headers.origin && req.headers.origin !== 'http://' + req.headers.host) return send(403)
|
|
41
|
+
if (req.method !== 'PUT') return send(405)
|
|
42
|
+
if (req.headers['content-type'] !== 'application/json') return send(415)
|
|
43
|
+
let locale
|
|
44
|
+
try {
|
|
45
|
+
let body = ''
|
|
46
|
+
req.setEncoding('utf8')
|
|
47
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
48
|
+
body += chunk
|
|
49
|
+
if (body.length > 1024) {
|
|
50
|
+
req.resume()
|
|
51
|
+
return send(413)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
locale = JSON.parse(body)?.locale
|
|
55
|
+
} catch {
|
|
56
|
+
return send(400)
|
|
57
|
+
}
|
|
58
|
+
if (locale !== 'zh-CN' && locale !== 'en') return send(400)
|
|
59
|
+
|
|
60
|
+
const save = pendingSave.then(async () => {
|
|
61
|
+
const settings = await readSettings()
|
|
62
|
+
await mkdir(dirname(file), { recursive: true })
|
|
63
|
+
const temp = file + '.' + randomUUID() + '.tmp'
|
|
64
|
+
try {
|
|
65
|
+
await writeFile(temp, JSON.stringify({ ...settings, locale }, null, 2) + '\n')
|
|
66
|
+
await rename(temp, file)
|
|
67
|
+
} finally {
|
|
68
|
+
await rm(temp, { force: true })
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
pendingSave = save.catch(() => {})
|
|
72
|
+
try {
|
|
73
|
+
await save
|
|
74
|
+
const module = server.moduleGraph.getModuleById('\0' + id)
|
|
75
|
+
if (module) server.moduleGraph.invalidateModule(module)
|
|
76
|
+
return send(204)
|
|
77
|
+
} catch {
|
|
78
|
+
return send(500)
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|