@arcadia-eternity/content-sdk 0.0.0-stage → 4.2.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/dist/asset-inspect.mjs +67 -0
  4. package/dist/author-api.mjs +112 -0
  5. package/dist/author-reference.mjs +121 -0
  6. package/dist/build-content.mjs +30 -0
  7. package/dist/cli.mjs +74 -0
  8. package/dist/content-query.mjs +283 -0
  9. package/dist/content-workspace.d.mts +161 -0
  10. package/dist/content-workspace.mjs +936 -0
  11. package/dist/debug-environments.mjs +154 -0
  12. package/dist/demo.mjs +22 -0
  13. package/dist/environment-rules.d.mts +5 -0
  14. package/dist/environment-rules.mjs +92 -0
  15. package/dist/environment.mjs +183 -0
  16. package/dist/index.d.mts +1 -0
  17. package/dist/index.mjs +1 -0
  18. package/dist/job-journal.mjs +94 -0
  19. package/dist/jobs.mjs +579 -0
  20. package/dist/lib/content.mjs +95 -0
  21. package/dist/lib/presentation.mjs +240 -0
  22. package/dist/lib/yaml-sharing.mjs +101 -0
  23. package/dist/managed-projects.d.mts +35 -0
  24. package/dist/managed-projects.mjs +303 -0
  25. package/dist/managed-sources.d.mts +19 -0
  26. package/dist/managed-sources.mjs +503 -0
  27. package/dist/mcp-contracts.mjs +153 -0
  28. package/dist/mcp.mjs +369 -0
  29. package/dist/pack-project.mjs +156 -0
  30. package/dist/preview-control.mjs +260 -0
  31. package/dist/preview.mjs +313 -0
  32. package/dist/project-teams.mjs +98 -0
  33. package/dist/project.mjs +140 -0
  34. package/dist/rename.mjs +112 -0
  35. package/dist/setup.mjs +134 -0
  36. package/dist/source-lock.mjs +103 -0
  37. package/dist/template/LICENSE +21 -0
  38. package/dist/template/README.md +17 -0
  39. package/dist/template/arcadia.config.mjs +2 -0
  40. package/dist/template/assets/marks/slow.png +0 -0
  41. package/dist/template/assets/pets/frostling-battle.png +0 -0
  42. package/dist/template/assets/pets/frostling-icon.png +0 -0
  43. package/dist/template/assets/pets/frostling-portrait.png +0 -0
  44. package/dist/template/data/marks/slow.yaml +18 -0
  45. package/dist/template/data/presentations/main.yaml +34 -0
  46. package/dist/template/data/resources/main.yaml +21 -0
  47. package/dist/template/data/skills/rest.yaml +6 -0
  48. package/dist/template/data/skills/strike.yaml +14 -0
  49. package/dist/template/data/species/pet-swf.yaml +36 -0
  50. package/dist/template/data/species/pet.yaml +34 -0
  51. package/dist/template/debug/teams/blue.yaml +25 -0
  52. package/dist/template/debug/teams/orange.yaml +25 -0
  53. package/dist/template/docs/presentation.md +21 -0
  54. package/dist/template/locales/en/mark.yaml +5 -0
  55. package/dist/template/locales/en/skill.yaml +12 -0
  56. package/dist/template/locales/en/species.yaml +6 -0
  57. package/dist/template/locales/zh-CN/mark.yaml +4 -0
  58. package/dist/template/locales/zh-CN/skill.yaml +10 -0
  59. package/dist/template/locales/zh-CN/species.yaml +6 -0
  60. package/dist/template/package.json +44 -0
  61. package/dist/template/skills/arcadia-content-authoring/SKILL.md +23 -0
  62. package/dist/template/skills/arcadia-content-authoring/references/project-sources.md +15 -0
  63. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +37 -0
  64. package/dist/template/skills/seer2-recreate-pet/SKILL.md +82 -0
  65. package/dist/template/skills/seer2-recreate-pet/references/mechanics-and-validation.md +47 -0
  66. package/dist/template/skills/seer2-recreate-pet/references/project-conventions.md +32 -0
  67. package/dist/template/skills/seer2-recreate-pet/references/testing.md +50 -0
  68. package/dist/template/src/effects.ts +44 -0
  69. package/dist/template/test/pack.test.mjs +178 -0
  70. package/dist/template/tsconfig.json +15 -0
  71. package/dist/testing.mjs +204 -0
  72. package/dist/workbench-context.mjs +18 -0
  73. package/dist/workspace-cli.mjs +60 -0
  74. package/dist/workspace-materials.mjs +153 -0
  75. package/dist/workspace.mjs +684 -0
  76. package/package.json +68 -3
@@ -0,0 +1,19 @@
1
+ export type ManagedSource =
2
+ | { kind: 'archive'; file: string }
3
+ | { kind: 'directory'; directory: string }
4
+ | { kind: 'url'; url: string; integrity?: string }
5
+ | { kind: 'git'; url: string; commit: string; artifactPath?: string }
6
+ export interface SourceAcquisitionOptions {
7
+ destination: string
8
+ signal?: AbortSignal
9
+ maxBytes?: number
10
+ maxFiles?: number
11
+ timeoutMs?: number
12
+ }
13
+ export function acquireSource(
14
+ source: ManagedSource,
15
+ options: SourceAcquisitionOptions,
16
+ ): Promise<{
17
+ directory: string
18
+ provenance: Record<string, string>
19
+ }>
@@ -0,0 +1,503 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { constants, createReadStream } from 'node:fs'
4
+ import { mkdir, open, readdir, lstat, realpath, rm, writeFile } from 'node:fs/promises'
5
+ import { dirname, isAbsolute, join, relative } from 'node:path'
6
+ import { promisify } from 'node:util'
7
+ import { Parser } from 'tar'
8
+ import yauzl from 'yauzl'
9
+
10
+ const exec = promisify(execFile)
11
+ const fail = code => Object.assign(new Error(code), { code })
12
+ const forbidden = name =>
13
+ ['.git', '.ssh', '.aws', '.npmrc', '.netrc', 'node_modules'].includes(name.toLowerCase()) ||
14
+ /^\.env(?:\.|$)/i.test(name)
15
+ const safePath = value => {
16
+ if (
17
+ typeof value !== 'string' ||
18
+ !value ||
19
+ value.length > 2048 ||
20
+ value.includes('\\') ||
21
+ /[\p{Cc}:]/u.test(value) ||
22
+ isAbsolute(value)
23
+ )
24
+ throw fail('SOURCE_PATH_INVALID')
25
+ const clean = value.replace(/\/$/, '').replace(/^\.\//, '')
26
+ if (
27
+ !clean ||
28
+ clean
29
+ .split('/')
30
+ .some(
31
+ part =>
32
+ !part ||
33
+ part === '.' ||
34
+ part === '..' ||
35
+ /[. ]$/.test(part) ||
36
+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part),
37
+ )
38
+ )
39
+ throw fail('SOURCE_PATH_INVALID')
40
+ return clean
41
+ }
42
+ const httpsUrl = value => {
43
+ const url = new URL(value)
44
+ if (url.protocol !== 'https:' || url.username || url.password || url.hash) throw fail('SOURCE_URL_INVALID')
45
+ return url
46
+ }
47
+ const publicUrl = value => {
48
+ const url = httpsUrl(value)
49
+ url.search = ''
50
+ return url.href
51
+ }
52
+
53
+ function boundedFiles(options) {
54
+ const names = new Set()
55
+ const files = []
56
+ let size = 0
57
+ let entries = 0
58
+ function track(name) {
59
+ options.signal.throwIfAborted()
60
+ name = safePath(name)
61
+ if (++entries > options.maxFiles) throw fail('SOURCE_LIMIT')
62
+ const key = name.normalize('NFC').toLowerCase()
63
+ if (names.has(key)) throw fail('SOURCE_PATH_DUPLICATE')
64
+ names.add(key)
65
+ return name
66
+ }
67
+ return {
68
+ files,
69
+ directory: track,
70
+ add(name, bytes) {
71
+ name = track(name)
72
+ if ((size += bytes.length) > options.maxBytes) throw fail('SOURCE_LIMIT')
73
+ if (!name.split('/').some(forbidden)) files.push({ name, bytes })
74
+ },
75
+ checkSize(size) {
76
+ if (!Number.isSafeInteger(size) || size < 0 || size > options.maxBytes) throw fail('SOURCE_LIMIT')
77
+ },
78
+ }
79
+ }
80
+ async function readBounded(stream, expectedSize, options) {
81
+ if (!Number.isSafeInteger(expectedSize) || expectedSize < 0 || expectedSize > options.maxBytes)
82
+ throw fail('SOURCE_LIMIT')
83
+ return new Promise((resolve, reject) => {
84
+ const chunks = []
85
+ let size = 0,
86
+ settled = false
87
+ const finish = error => {
88
+ if (settled) return
89
+ settled = true
90
+ options.signal.removeEventListener('abort', abort)
91
+ if (error) {
92
+ reject(error)
93
+ stream.destroy()
94
+ } else resolve(Buffer.concat(chunks, size))
95
+ }
96
+ const abort = () => finish(options.signal.reason ?? fail('SOURCE_CANCELLED'))
97
+ options.signal.addEventListener('abort', abort, { once: true })
98
+ stream.on('error', finish)
99
+ stream.on('data', chunk => {
100
+ if (settled) return
101
+ size += chunk.length
102
+ if (size > expectedSize || size > options.maxBytes) return finish(fail('SOURCE_LIMIT'))
103
+ chunks.push(Buffer.from(chunk))
104
+ })
105
+ stream.on('end', () => finish(size === expectedSize ? undefined : fail('SOURCE_SIZE_CHANGED')))
106
+ stream.on('close', () => {
107
+ if (!settled) finish(fail('SOURCE_STREAM_CLOSED'))
108
+ })
109
+ if (options.signal.aborted) abort()
110
+ })
111
+ }
112
+ async function tarFiles(file, options) {
113
+ const output = boundedFiles(options)
114
+ await new Promise((resolve, reject) => {
115
+ const input = createReadStream(file)
116
+ const parser = new Parser({ strict: true, maxMetaEntrySize: 64 * 1024, maxDecompressionRatio: 1000 })
117
+ let failed = false
118
+ const stop = error => {
119
+ if (failed) return
120
+ failed = true
121
+ options.signal.removeEventListener('abort', abort)
122
+ input.destroy()
123
+ parser.abort(error)
124
+ reject(error)
125
+ }
126
+ const abort = () => stop(options.signal.reason ?? fail('SOURCE_CANCELLED'))
127
+ options.signal.addEventListener('abort', abort, { once: true })
128
+ parser.on('entry', entry => {
129
+ try {
130
+ if (entry.type === 'Directory' && ['.', './'].includes(entry.path)) {
131
+ entry.resume()
132
+ return
133
+ }
134
+ const name = safePath(entry.path)
135
+ if (entry.type === 'Directory') {
136
+ output.directory(name)
137
+ entry.resume()
138
+ return
139
+ }
140
+ if (!['File', 'OldFile', 'ContiguousFile'].includes(entry.type)) throw fail('SOURCE_LINK_FORBIDDEN')
141
+ output.checkSize(entry.size)
142
+ const chunks = []
143
+ let size = 0
144
+ entry.on('data', chunk => {
145
+ if (failed) return
146
+ size += chunk.length
147
+ if (size > entry.size || size > options.maxBytes) return stop(fail('SOURCE_LIMIT'))
148
+ chunks.push(Buffer.from(chunk))
149
+ })
150
+ entry.on('end', () => {
151
+ if (failed) return
152
+ try {
153
+ if (size !== entry.size) throw fail('SOURCE_SIZE_CHANGED')
154
+ output.add(name, Buffer.concat(chunks, size))
155
+ } catch (error) {
156
+ stop(error)
157
+ }
158
+ })
159
+ entry.on('error', stop)
160
+ entry.resume()
161
+ } catch (error) {
162
+ stop(error)
163
+ }
164
+ })
165
+ input.on('error', stop)
166
+ parser.on('error', stop)
167
+ parser.on('end', () => {
168
+ options.signal.removeEventListener('abort', abort)
169
+ if (!failed) resolve()
170
+ })
171
+ input.pipe(parser)
172
+ })
173
+ return output.files
174
+ }
175
+ async function zipFiles(file, options) {
176
+ const output = boundedFiles(options)
177
+ const zip = await new Promise((resolve, reject) =>
178
+ yauzl.open(file, { lazyEntries: true, validateEntrySizes: true, strictFileNames: true }, (error, value) =>
179
+ error ? reject(error) : resolve(value),
180
+ ),
181
+ )
182
+ let abort
183
+ try {
184
+ await new Promise((resolve, reject) => {
185
+ abort = () => {
186
+ zip.close()
187
+ reject(options.signal.reason ?? fail('SOURCE_CANCELLED'))
188
+ }
189
+ options.signal.addEventListener('abort', abort, { once: true })
190
+ zip.on('error', reject)
191
+ zip.on('end', () => {
192
+ options.signal.removeEventListener('abort', abort)
193
+ resolve()
194
+ })
195
+ zip.on('entry', entry => {
196
+ void (async () => {
197
+ const name = safePath(entry.fileName)
198
+ const kind = (entry.externalFileAttributes >>> 16) & 0o170000
199
+ if (kind !== 0 && kind !== 0o100000 && kind !== 0o040000) throw fail('SOURCE_LINK_FORBIDDEN')
200
+ if (entry.generalPurposeBitFlag & 1) throw fail('SOURCE_ENCRYPTED_ARCHIVE')
201
+ if (entry.fileName.endsWith('/')) {
202
+ output.directory(name)
203
+ zip.readEntry()
204
+ return
205
+ }
206
+ output.checkSize(entry.uncompressedSize)
207
+ const stream = await new Promise((resolve, reject) =>
208
+ zip.openReadStream(entry, (error, value) => (error ? reject(error) : resolve(value))),
209
+ )
210
+ output.add(name, await readBounded(stream, entry.uncompressedSize, options))
211
+ zip.readEntry()
212
+ })().catch(error => {
213
+ zip.close()
214
+ reject(error)
215
+ })
216
+ })
217
+ zip.readEntry()
218
+ })
219
+ } finally {
220
+ options.signal.removeEventListener('abort', abort)
221
+ zip.close()
222
+ }
223
+ return output.files
224
+ }
225
+ async function directoryFiles(directory, options) {
226
+ const root = await realpath(directory)
227
+ const output = boundedFiles(options)
228
+ async function walk(path, prefix = '') {
229
+ options.signal.throwIfAborted()
230
+ const resolved = await realpath(path)
231
+ const rel = relative(root, resolved)
232
+ if ((rel && (isAbsolute(rel) || rel === '..' || rel.startsWith('../'))) || (await lstat(path)).isSymbolicLink())
233
+ throw fail('SOURCE_LINK_FORBIDDEN')
234
+ for (const entry of await readdir(path, { withFileTypes: true })) {
235
+ const name = prefix ? prefix + '/' + entry.name : entry.name
236
+ safePath(name)
237
+ if (forbidden(entry.name)) {
238
+ output.directory(name)
239
+ continue
240
+ }
241
+ const file = join(path, entry.name)
242
+ if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw fail('SOURCE_LINK_FORBIDDEN')
243
+ if (entry.isDirectory()) {
244
+ output.directory(name)
245
+ await walk(file, name)
246
+ } else {
247
+ const before = await lstat(file)
248
+ if (!before.isFile()) throw fail('SOURCE_LINK_FORBIDDEN')
249
+ output.checkSize(before.size)
250
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
251
+ try {
252
+ const actualPath = await realpath(file)
253
+ const rel = relative(root, actualPath)
254
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../')) throw fail('SOURCE_LINK_FORBIDDEN')
255
+ const bytes = await readBounded(handle.createReadStream({ autoClose: false }), before.size, options)
256
+ const after = await handle.stat()
257
+ if (before.ino !== after.ino || before.size !== bytes.length || before.mtimeMs !== after.mtimeMs)
258
+ throw fail('SOURCE_CHANGED')
259
+ output.add(name, bytes)
260
+ } finally {
261
+ await handle.close()
262
+ }
263
+ }
264
+ }
265
+ }
266
+ await walk(root)
267
+ return output.files
268
+ }
269
+ async function download(source, file, options) {
270
+ let url = httpsUrl(source.url)
271
+ for (let redirects = 0; redirects <= 5; redirects++) {
272
+ const response = await fetch(url, { redirect: 'manual', signal: options.signal })
273
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
274
+ await response.body?.cancel()
275
+ if (redirects === 5 || !response.headers.get('location')) throw fail('SOURCE_REDIRECT_LIMIT')
276
+ url = httpsUrl(new URL(response.headers.get('location'), url).href)
277
+ continue
278
+ }
279
+ if (!response.ok || !response.body) {
280
+ await response.body?.cancel()
281
+ throw fail('SOURCE_DOWNLOAD_FAILED')
282
+ }
283
+ const declared = response.headers.get('content-length')
284
+ if (declared && Number(declared) > options.maxBytes) {
285
+ await response.body.cancel()
286
+ throw fail('SOURCE_LIMIT')
287
+ }
288
+ const chunks = []
289
+ let total = 0
290
+ for await (const chunk of response.body) {
291
+ total += chunk.length
292
+ if (total > options.maxBytes) {
293
+ await response.body.cancel().catch(() => {})
294
+ throw fail('SOURCE_LIMIT')
295
+ }
296
+ chunks.push(Buffer.from(chunk))
297
+ }
298
+ const bytes = Buffer.concat(chunks, total)
299
+ if (source.integrity) {
300
+ const tokens = source.integrity.trim().split(/\s+/)
301
+ if (!tokens.length || tokens.some(token => !/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(token)))
302
+ throw fail('SOURCE_INTEGRITY_INVALID')
303
+ if (
304
+ !tokens.some(token => {
305
+ const [algorithm, expected] = token.split('-')
306
+ return createHash(algorithm).update(bytes).digest('base64') === expected
307
+ })
308
+ )
309
+ throw fail('SOURCE_INTEGRITY_MISMATCH')
310
+ }
311
+ await writeFile(file, bytes, { flag: 'wx', mode: 0o600 })
312
+ return {
313
+ kind: 'url',
314
+ url: publicUrl(source.url),
315
+ resolvedUrl: publicUrl(url.href),
316
+ ...(source.integrity ? { integrity: source.integrity } : {}),
317
+ }
318
+ }
319
+ throw fail('SOURCE_REDIRECT_LIMIT')
320
+ }
321
+ async function gitArchive(source, root, options) {
322
+ const url = httpsUrl(source.url).href
323
+ if (typeof source.commit !== 'string' || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i.test(source.commit))
324
+ throw fail('SOURCE_GIT_COMMIT_REQUIRED')
325
+ const artifactPath = source.artifactPath === undefined ? undefined : safePath(source.artifactPath)
326
+ const gitRoot = join(root, 'git')
327
+ const config = [
328
+ '-c',
329
+ 'core.hooksPath=' + join(root, 'no-hooks'),
330
+ '-c',
331
+ 'protocol.allow=never',
332
+ '-c',
333
+ 'protocol.https.allow=always',
334
+ '-c',
335
+ 'credential.helper=',
336
+ '-c',
337
+ 'http.followRedirects=false',
338
+ ]
339
+ const env = {
340
+ PATH: process.env.PATH ?? '',
341
+ SystemRoot: process.env.SystemRoot,
342
+ HOME: root,
343
+ GIT_CONFIG_NOSYSTEM: '1',
344
+ GIT_CONFIG_GLOBAL: join(root, 'no-config'),
345
+ GIT_TERMINAL_PROMPT: '0',
346
+ }
347
+ const budget = new AbortController()
348
+ const signal = AbortSignal.any([options.signal, budget.signal])
349
+ let scanning = false
350
+ async function checkBudget() {
351
+ let size = 0,
352
+ count = 0
353
+ async function walk(directory) {
354
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
355
+ const file = join(directory, entry.name)
356
+ let info
357
+ try {
358
+ info = await lstat(file)
359
+ } catch (error) {
360
+ if (error.code === 'ENOENT') continue
361
+ throw error
362
+ }
363
+ if (++count > options.maxFiles || (size += info.size) > options.maxBytes) throw fail('SOURCE_LIMIT')
364
+ if (info.isDirectory()) await walk(file)
365
+ }
366
+ }
367
+ await walk(root)
368
+ }
369
+ const timer = setInterval(() => {
370
+ if (scanning) return
371
+ scanning = true
372
+ void checkBudget()
373
+ .catch(error => budget.abort(error))
374
+ .finally(() => {
375
+ scanning = false
376
+ })
377
+ }, 100)
378
+ timer.unref()
379
+ const run = args =>
380
+ exec('git', [...config, ...args], {
381
+ env,
382
+ signal,
383
+ timeout: options.timeoutMs,
384
+ killSignal: 'SIGKILL',
385
+ maxBuffer: 1024 * 1024,
386
+ windowsHide: true,
387
+ })
388
+ try {
389
+ await run(['init', '--bare', gitRoot])
390
+ await run(['--git-dir=' + gitRoot, 'fetch', '--no-tags', '--depth=1', '--', url, source.commit])
391
+ await checkBudget()
392
+ const actual = (await run(['--git-dir=' + gitRoot, 'rev-parse', 'FETCH_HEAD^{commit}'])).stdout.trim()
393
+ if (actual.toLowerCase() !== source.commit.toLowerCase()) throw fail('SOURCE_GIT_COMMIT_MISMATCH')
394
+ const file = join(root, 'git.tar')
395
+ await run([
396
+ '--git-dir=' + gitRoot,
397
+ 'archive',
398
+ '--format=tar',
399
+ '--output=' + file,
400
+ artifactPath ? actual + ':' + artifactPath : actual,
401
+ ])
402
+ await checkBudget()
403
+ return {
404
+ file,
405
+ provenance: { kind: 'git', url: publicUrl(url), commit: actual, ...(artifactPath ? { artifactPath } : {}) },
406
+ }
407
+ } catch (error) {
408
+ if (budget.signal.aborted) throw budget.signal.reason
409
+ if (options.signal.aborted) throw options.signal.reason
410
+ if (typeof error.code === 'string' && error.code.startsWith('SOURCE_')) throw error
411
+ throw fail('SOURCE_GIT_FAILED')
412
+ } finally {
413
+ clearInterval(timer)
414
+ }
415
+ }
416
+
417
+ /** Only trusted host configuration supplies descriptors. HTTP callers select registered source IDs. */
418
+ export async function acquireSource(source, input) {
419
+ if (
420
+ !source ||
421
+ typeof source !== 'object' ||
422
+ !input ||
423
+ typeof input.destination !== 'string' ||
424
+ !isAbsolute(input.destination)
425
+ )
426
+ throw fail('SOURCE_INVALID')
427
+ const timeoutMs = input.timeoutMs ?? 120000
428
+ const options = {
429
+ maxBytes: input.maxBytes ?? 256 * 1024 * 1024,
430
+ maxFiles: input.maxFiles ?? 50000,
431
+ timeoutMs,
432
+ signal: AbortSignal.any([...(input.signal ? [input.signal] : []), AbortSignal.timeout(timeoutMs)]),
433
+ }
434
+ if (
435
+ !Number.isSafeInteger(options.maxBytes) ||
436
+ options.maxBytes < 1 ||
437
+ !Number.isSafeInteger(options.maxFiles) ||
438
+ options.maxFiles < 1
439
+ )
440
+ throw fail('SOURCE_LIMIT_INVALID')
441
+ options.signal.throwIfAborted()
442
+ await mkdir(input.destination, { mode: 0o700 })
443
+ try {
444
+ const scratch = join(input.destination, '.source')
445
+ await mkdir(scratch)
446
+ let files, provenance
447
+ if (source.kind === 'directory') {
448
+ if (typeof source.directory !== 'string' || !isAbsolute(source.directory)) throw fail('SOURCE_PATH_INVALID')
449
+ files = await directoryFiles(source.directory, options)
450
+ provenance = { kind: 'directory' }
451
+ } else {
452
+ let file
453
+ if (source.kind === 'archive') {
454
+ if (typeof source.file !== 'string' || !isAbsolute(source.file) || !(await lstat(source.file)).isFile())
455
+ throw fail('SOURCE_ARCHIVE_INVALID')
456
+ file = source.file
457
+ provenance = { kind: 'archive' }
458
+ } else if (source.kind === 'url') {
459
+ file = join(scratch, 'download')
460
+ provenance = await download(source, file, options)
461
+ } else if (source.kind === 'git') {
462
+ const result = await gitArchive(source, scratch, options)
463
+ file = result.file
464
+ provenance = result.provenance
465
+ } else throw fail('SOURCE_KIND_UNSUPPORTED')
466
+ if ((await lstat(file)).size > options.maxBytes) throw fail('SOURCE_LIMIT')
467
+ const handle = await open(file, 'r')
468
+ const magic = Buffer.alloc(4)
469
+ try {
470
+ await handle.read(magic, 0, 4, 0)
471
+ } finally {
472
+ await handle.close()
473
+ }
474
+ files = magic.readUInt32LE(0) === 0x04034b50 ? await zipFiles(file, options) : await tarFiles(file, options)
475
+ }
476
+ const packageFiles = files.filter(file => file.name === 'package.json' || file.name.endsWith('/package.json'))
477
+ const rootManifest = packageFiles.find(file => file.name === 'package.json')
478
+ const shortest =
479
+ rootManifest ?? [...packageFiles].sort((a, b) => a.name.split('/').length - b.name.split('/').length)[0]
480
+ if (!shortest) throw fail('SOURCE_PACKAGE_MISSING')
481
+ const prefix = shortest.name.slice(0, -'package.json'.length)
482
+ if (!rootManifest && files.some(file => !file.name.startsWith(prefix))) throw fail('SOURCE_PACKAGE_AMBIGUOUS')
483
+ const manifest = JSON.parse(shortest.bytes.toString('utf8'))
484
+ if (typeof manifest.name !== 'string' || typeof manifest.version !== 'string') throw fail('SOURCE_PACKAGE_INVALID')
485
+ const directory = join(input.destination, 'package')
486
+ await mkdir(directory)
487
+ for (const file of files) {
488
+ options.signal.throwIfAborted()
489
+ const name = safePath(file.name.slice(prefix.length))
490
+ const output = join(directory, name)
491
+ if (relative(directory, output).startsWith('..')) throw fail('SOURCE_PATH_INVALID')
492
+ await mkdir(dirname(output), { recursive: true })
493
+ await writeFile(output, file.bytes, { flag: 'wx', mode: 0o600 })
494
+ }
495
+ await rm(scratch, { recursive: true, force: true })
496
+ return { directory, provenance: { ...provenance, name: manifest.name, version: manifest.version } }
497
+ } catch (error) {
498
+ await rm(input.destination, { recursive: true, force: true })
499
+ if (typeof error.code === 'string' && error.code.startsWith('SOURCE_')) throw error
500
+ if (options.signal.aborted) throw options.signal.reason
501
+ throw fail('SOURCE_ACQUISITION_FAILED')
502
+ }
503
+ }
@@ -0,0 +1,153 @@
1
+ import { z } from 'zod'
2
+ import { EnvironmentDocumentV2Schema } from './debug-environments.mjs'
3
+ export { referenceTopics } from './author-reference.mjs'
4
+
5
+ export const version = z.string().regex(/^[a-f0-9]{64}$/)
6
+ export const identifier = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,79}$/)
7
+ export const record = z.record(z.unknown())
8
+ const diagnosticSchema = z
9
+ .object({
10
+ code: z.string(),
11
+ message: z.string(),
12
+ severity: z.string().optional(),
13
+ file: z.string().optional(),
14
+ line: z.number().optional(),
15
+ column: z.number().optional(),
16
+ })
17
+ .passthrough()
18
+ const saved = z.object({ file: z.string(), version })
19
+ const jobState = z.enum(['queued', 'running', 'succeeded', 'failed', 'cancelled', 'interrupted'])
20
+ export const jobKind = z.enum(['check', 'test', 'demo', 'preview', 'pack'])
21
+ export { jobState }
22
+ const job = z
23
+ .object({
24
+ jobId: z.string(),
25
+ kind: jobKind,
26
+ state: jobState,
27
+ stale: z.boolean(),
28
+ sourceRevision: version,
29
+ createdAt: z.number(),
30
+ phase: z.string().optional(),
31
+ outputCursor: z.number().int().optional(),
32
+ diagnosticCount: z.number().int().optional(),
33
+ diagnosticsTruncated: z.boolean().optional(),
34
+ diagnostics: z.array(diagnosticSchema).optional(),
35
+ result: z
36
+ .object({
37
+ preview: z
38
+ .object({ endpoint: z.string(), clientPath: z.string(), url: z.string().optional() })
39
+ .passthrough()
40
+ .optional(),
41
+ candidate: record.optional(),
42
+ })
43
+ .passthrough()
44
+ .optional(),
45
+ })
46
+ .passthrough()
47
+ const page = item =>
48
+ z
49
+ .object({
50
+ total: z.number().int(),
51
+ offset: z.number().int(),
52
+ nextOffset: z.number().int().nullable(),
53
+ items: z.array(item),
54
+ })
55
+ .passthrough()
56
+ const team = z.object({ schemaVersion: z.literal(1), id: identifier, name: z.string(), team: z.array(record), version })
57
+ const legacyEnvironment = z.object({
58
+ schemaVersion: z.literal(1),
59
+ id: identifier,
60
+ name: z.string(),
61
+ packages: z.record(z.string()),
62
+ sources: z.array(z.string()),
63
+ version: version.nullable(),
64
+ })
65
+ const environment = z.discriminatedUnion('schemaVersion', [
66
+ legacyEnvironment,
67
+ EnvironmentDocumentV2Schema.extend({ version: version.nullable() }),
68
+ ])
69
+
70
+ // Dynamic content and battle payloads keep their domain fields; the envelopes and
71
+ // control fields are explicit so clients can handle pagination, conflicts and jobs.
72
+ export const outputSchemas = {
73
+ describe: z.object({
74
+ protocolVersion: z.number(),
75
+ root: z.string(),
76
+ name: z.string(),
77
+ project: record,
78
+ sourceRevision: version,
79
+ capabilities: record,
80
+ diagnostics: z.array(diagnosticSchema),
81
+ }),
82
+ context: z.object({ connected: z.boolean(), reason: z.string().optional(), state: record.optional() }).passthrough(),
83
+ query: page(
84
+ z
85
+ .object({
86
+ kind: z.string(),
87
+ scope: z.enum(['project', 'dependencies']),
88
+ readOnly: z.boolean(),
89
+ namespace: z.string(),
90
+ packageName: z.string().optional(),
91
+ id: z.string().optional(),
92
+ qualifiedId: z.string().optional(),
93
+ file: z.string().optional(),
94
+ version: version.optional(),
95
+ index: z.number().int().nullable().optional(),
96
+ name: z.string().optional(),
97
+ record: record.optional(),
98
+ })
99
+ .passthrough(),
100
+ ).extend({ diagnostics: z.array(diagnosticSchema).optional() }),
101
+ read: saved.extend({ text: z.string() }),
102
+ write: saved,
103
+ save: z.object({
104
+ complete: z.boolean(),
105
+ results: z.array(
106
+ z.object({
107
+ file: z.string(),
108
+ saved: z.boolean(),
109
+ version: version.optional(),
110
+ diagnostic: diagnosticSchema.optional(),
111
+ }),
112
+ ),
113
+ }),
114
+ start: job,
115
+ 'job-query': job,
116
+ 'cancel-query': job,
117
+ 'jobs-query': page(job),
118
+ 'job-output': z.object({
119
+ jobId: z.string(),
120
+ text: z.string(),
121
+ cursor: z.number().int(),
122
+ nextCursor: z.number().int(),
123
+ endCursor: z.number().int(),
124
+ truncated: z.boolean(),
125
+ hasMore: z.boolean(),
126
+ unit: z.literal('utf16'),
127
+ }),
128
+ 'team-list': z.object({ items: z.array(team) }),
129
+ 'team-save': team,
130
+ 'team-remove': z.object({ id: identifier, removed: z.literal(true) }),
131
+ 'environment-list': z.object({ items: z.array(environment) }),
132
+ 'environment-save': environment,
133
+ reference: z.object({ topic: z.string(), title: z.string() }).passthrough(),
134
+ 'asset-inspect': z.object({ metadata: record }),
135
+ battle: z
136
+ .object({
137
+ sessionId: z.string(),
138
+ revision: z.number().int(),
139
+ state: record.nullable().optional(),
140
+ stateCurrent: z.boolean().optional(),
141
+ failure: diagnosticSchema.optional(),
142
+ selections: z.array(record).optional(),
143
+ seed: z.string().optional(),
144
+ teamIds: z.array(identifier).optional(),
145
+ playerId: z.string().optional(),
146
+ cursor: z.number().int().optional(),
147
+ events: z.array(z.object({ cursor: z.number().int(), revision: z.number().int(), message: record })).optional(),
148
+ nextCursor: z.number().int().optional(),
149
+ hasMore: z.boolean().optional(),
150
+ closed: z.boolean().optional(),
151
+ })
152
+ .passthrough(),
153
+ }