@arcadia-eternity/content-sdk 4.3.4 → 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
package/dist/testing.mjs DELETED
@@ -1,204 +0,0 @@
1
- import assert from 'node:assert/strict'
2
- import { randomBytes } from 'node:crypto'
3
- import { join, resolve } from 'node:path'
4
- import { pathToFileURL } from 'node:url'
5
- import { prepareBattleEnvironment } from './environment.mjs'
6
- import { assertEnvironmentTeam, validateEnvironmentRules } from './environment-rules.mjs'
7
- import { prepareSandboxContent } from '@arcadia-eternity/battle/sandbox/effects'
8
- import { createNodeBattleWorkerManager } from '@arcadia-eternity/battle/sandbox/node'
9
- export { prepareBattleEnvironment } from './environment.mjs'
10
- import { AttackTargetOpinion, BattleMessageType, TurnContext, UseSkillContext } from '@arcadia-eternity/battle/engine'
11
- export {
12
- AttackTargetOpinion,
13
- EffectContext,
14
- EffectTrigger,
15
- RemoveMarkContext,
16
- parameterAddress,
17
- setGlobalLogger,
18
- } from '@arcadia-eternity/battle/engine'
19
- /** Existing package scenarios use the default environment with declared dependencies only. */
20
- export async function prepareContentPack(root = process.cwd(), options = {}) {
21
- root = resolve(root)
22
- const { default: config } = await import(pathToFileURL(join(root, 'arcadia.config.mjs')).href)
23
- if (
24
- !Array.isArray(config?.teams) ||
25
- config.teams.length !== 2 ||
26
- config.teams.some(id => typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(id)) ||
27
- Object.keys(config).some(key => key !== 'teams')
28
- )
29
- throw new Error('arcadia.config.mjs must export exactly two project team IDs in teams')
30
- const prepared = await prepareBattleEnvironment(root, options)
31
- const { environment } = prepared
32
- const environmentRules = validateEnvironmentRules(prepared.environmentDocument.rules)
33
- // Four automation sessions, one human preview, and room for their validated replacements.
34
- const workers = createNodeBattleWorkerManager({ maxBattles: 7 })
35
- function defaultPlayers() {
36
- return prepared.loadTeams(config.teams)
37
- }
38
- function runtimePlayers(supplied, runtimeIds = false) {
39
- const players = (supplied ?? defaultPlayers()).map(player => ({
40
- ...player,
41
- id: (runtimeIds ? undefined : player.id) ?? randomBytes(16).toString('base64url').slice(0, 21),
42
- team: player.team.map(pet => ({
43
- ...pet,
44
- id: runtimeIds ? randomBytes(16).toString('base64url').slice(0, 21) : pet.id,
45
- })),
46
- }))
47
- for (const player of players) assertEnvironmentTeam(environmentRules, player.team)
48
- return players
49
- }
50
- const referenceContent = new WeakMap()
51
- function ownBattle(battle, effects) {
52
- referenceContent.set(battle, effects.content)
53
- const cleanup = battle.cleanup.bind(battle)
54
- // Keep the runtime method non-enumerable, like the prototype method: only
55
- // domain fields belong in snapshots, never this resource-owner callback.
56
- Object.defineProperty(battle, 'cleanup', {
57
- configurable: true,
58
- value: async () => {
59
- try {
60
- await cleanup()
61
- } finally {
62
- effects.dispose()
63
- }
64
- },
65
- })
66
- prepared.track(battle)
67
- return battle
68
- }
69
- /** Explicit trusted introspection entry. Every reference battle owns fresh VMs,
70
- * just like the Worker entry; preparing an environment never evaluates effects.
71
- */
72
- async function createBattle(
73
- seed = 'content-pack-template',
74
- { ai = false, players: supplied, runtimeIds = false, battleOptions = {} } = {},
75
- ) {
76
- const input = runtimePlayers(supplied, runtimeIds)
77
- const effects = await prepareSandboxContent(environment.sandbox)
78
- try {
79
- const players = effects.content.parsePlayers(input, { aiPlayerIds: ai ? [input[1]?.id] : [] })
80
- if (players.length !== 2) throw new Error('The demo requires exactly two players')
81
- const ids = players.flatMap(player => [player.id, ...player.team.map(pet => pet.id)])
82
- if (new Set(ids).size !== ids.length) throw new Error('玩家和精灵的编号不能重复')
83
- return ownBattle(
84
- effects.content.createBattle(players[0], players[1], {
85
- ...battleOptions,
86
- rngSeed: seed,
87
- timerConfig: battleOptions.timerConfig ?? { enabled: false },
88
- }),
89
- effects,
90
- )
91
- } catch (error) {
92
- effects.dispose()
93
- throw error
94
- }
95
- }
96
- async function restoreBattle(snapshot) {
97
- const effects = await prepareSandboxContent(environment.sandbox)
98
- try {
99
- return ownBattle(effects.content.restore(snapshot), effects)
100
- } catch (error) {
101
- effects.dispose()
102
- throw error
103
- }
104
- }
105
- function contentFor(battle) {
106
- const content = referenceContent.get(battle)
107
- if (!content) throw new Error('Battle does not belong to this reference helper')
108
- return content
109
- }
110
- async function createBattleSession(
111
- seed = 'content-pack-template',
112
- { ai = false, players: supplied, runtimeIds = false, battleOptions = {} } = {},
113
- ) {
114
- const players = runtimePlayers(supplied, runtimeIds)
115
- const system = await workers.create({
116
- environment: environment.sandbox,
117
- players,
118
- aiPlayerIds: ai ? [players[1]?.id] : [],
119
- options: { ...battleOptions, rngSeed: seed, timerConfig: battleOptions.timerConfig ?? { enabled: false } },
120
- hostOptions: { teamSelection: battleOptions.teamSelection },
121
- })
122
- return system
123
- }
124
- return {
125
- ...prepared,
126
- createBattle,
127
- restoreBattle,
128
- contentFor,
129
- createBattleSession,
130
- defaultPlayers,
131
- async dispose() {
132
- try {
133
- await workers.dispose()
134
- } finally {
135
- await prepared.dispose()
136
- }
137
- },
138
- }
139
- }
140
-
141
- export function attack(battle) {
142
- const player = battle.playerA
143
- const context = new UseSkillContext(
144
- new TurnContext(battle),
145
- player,
146
- player.activePet,
147
- AttackTargetOpinion.opponent,
148
- player.activePet.skills[0],
149
- )
150
- context.updateActualTarget()
151
- return context
152
- }
153
- export function cancelled(error) {
154
- if (!(error instanceof Error) || error.message !== 'Battle cancelled') throw error
155
- }
156
- export function nextTurn(battle) {
157
- return new Promise((resolve, reject) => {
158
- const timeout = setTimeout(() => {
159
- unsubscribe()
160
- reject(new Error('Battle did not reach its next input boundary'))
161
- }, 10000)
162
- const listener = message => {
163
- if (message.type !== BattleMessageType.TurnAction) return
164
- clearTimeout(timeout)
165
- unsubscribe()
166
- resolve()
167
- }
168
- const unsubscribe = () => battle.unregisterListener(listener)
169
- battle.registerListener(listener)
170
- })
171
- }
172
- export async function runBattle(battle, onTurn = () => {}) {
173
- const damage = [],
174
- failures = []
175
- battle.registerListener(message => {
176
- if (message.type === BattleMessageType.Damage) damage.push(message.data.damage)
177
- if (message.type === BattleMessageType.Error || message.type === BattleMessageType.EffectApplyFail)
178
- failures.push(message)
179
- if (message.type === BattleMessageType.TurnEnd) onTurn(battle)
180
- if (message.type !== BattleMessageType.TurnAction) return
181
- for (const player of [battle.playerA, battle.playerB]) {
182
- const selection =
183
- battle.currentTurn >= 40
184
- ? { type: 'surrender', player: player.id }
185
- : {
186
- type: 'use-skill',
187
- player: player.id,
188
- skill: player.activePet.skills[0].id,
189
- target: AttackTargetOpinion.opponent,
190
- }
191
- if (!battle.setSelection(selection)) throw new Error('Example selection rejected')
192
- if (selection.type === 'surrender') break
193
- }
194
- })
195
- await battle.startBattle()
196
- assert.deepEqual(failures, [], 'the demonstration must not hide effect execution failures')
197
- assert.ok(battle.currentTurn < 40, 'the demonstration should finish by defeating the opposing pet')
198
- return {
199
- winner: battle.victor?.name,
200
- turns: battle.currentTurn,
201
- hp: [battle.playerA, battle.playerB].map(player => player.activePet.currentHp),
202
- damage,
203
- }
204
- }
@@ -1,18 +0,0 @@
1
- import { readFile, stat } from 'node:fs/promises'
2
-
3
- /** Ephemeral desktop state is context, never an edit authorization or a disk revision. */
4
- export async function readWorkbenchContext(file, root, now = Date.now()) {
5
- if (!file) return { connected: false, reason: 'not-configured' }
6
- try {
7
- if ((await stat(file)).size > 4 * 1024 * 1024) throw new Error('Workbench context exceeds 4 MiB')
8
- const context = JSON.parse(await readFile(file, 'utf8'))
9
- if (context.protocol !== 'arcadia-workbench-context/v1' || context.root !== root)
10
- return { connected: false, reason: 'project-mismatch' }
11
- if (!Number.isFinite(context.updatedAt) || now - context.updatedAt > 90000 || context.updatedAt > now + 5000)
12
- return { connected: false, reason: 'expired' }
13
- return { connected: true, ...context }
14
- } catch (error) {
15
- if (error.code === 'ENOENT') return { connected: false, reason: 'workbench-closed' }
16
- throw error
17
- }
18
- }
@@ -1,60 +0,0 @@
1
- import { openAuthorSession } from './author-api.mjs'
2
- import { diagnostic } from './workspace.mjs'
3
-
4
- export async function workspaceCli(args) {
5
- const [directory, operation = 'describe', ...flags] = args
6
- let execute = false,
7
- environmentId
8
- for (let index = 0; index < flags.length; index++) {
9
- if (flags[index] === '--execute') execute = true
10
- else if (flags[index] === '--environment' && operation === 'preview' && flags[index + 1])
11
- environmentId = flags[++index]
12
- else throw new Error('Unknown workspace option; use --execute or preview --environment <id>')
13
- }
14
- if (!directory)
15
- throw new Error(
16
- 'Usage: arcadia-content workspace <directory> <operation> [--execute] [--environment <id>]. JSON input on stdin for query/read/write/save.',
17
- )
18
- const session = await openAuthorSession(directory, { watch: false, execute })
19
- const cancel = () => session.close()
20
- process.once('SIGTERM', cancel)
21
- process.once('SIGINT', cancel)
22
- try {
23
- let result
24
- if (['check', 'test', 'demo', 'preview', 'pack'].includes(operation)) {
25
- let job = await session.jobs.start({ kind: operation, ...(environmentId ? { environmentId } : {}) })
26
- while (['queued', 'running'].includes(job.state)) {
27
- await new Promise(resolve => setTimeout(resolve, 100))
28
- job = session.jobs.get(job.jobId)
29
- }
30
- result = job
31
- if (job.state !== 'succeeded' || job.stale) process.exitCode = 1
32
- if (operation === 'preview' && job.state === 'succeeded' && !job.stale) {
33
- console.log(JSON.stringify({ result: job }))
34
- while (!session.jobs.closed && session.jobs.get(job.jobId).state === 'succeeded')
35
- await new Promise(resolve => setTimeout(resolve, 100))
36
- const final = session.jobs.get(job.jobId)
37
- console.log(JSON.stringify({ result: final }))
38
- if (final.state === 'failed') process.exitCode = 1
39
- return
40
- }
41
- } else {
42
- let input = ''
43
- if (operation !== 'describe')
44
- for await (const chunk of process.stdin) {
45
- input += chunk
46
- if (Buffer.byteLength(input) > 3 * 1024 * 1024) throw new Error('JSON input exceeds 3 MiB')
47
- }
48
- result = await session.call(operation, input ? JSON.parse(input) : {})
49
- if (operation === 'save' && !result.complete) process.exitCode = 1
50
- }
51
- console.log(JSON.stringify({ result }))
52
- } catch (error) {
53
- console.log(JSON.stringify({ error: diagnostic(error) }))
54
- process.exitCode = 1
55
- } finally {
56
- process.removeListener('SIGTERM', cancel)
57
- process.removeListener('SIGINT', cancel)
58
- await session.close()
59
- }
60
- }
@@ -1,153 +0,0 @@
1
- import { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises'
2
- import { dirname, isAbsolute, join, relative } from 'node:path'
3
-
4
- export function contentError(code, message = code) {
5
- return Object.assign(new Error(message), { code })
6
- }
7
- const materialRoots = new Set(['package.json', 'package-lock.json', 'node_modules', 'candidates'])
8
- const forbidden = new Set(['.git', '.env', '.npmrc', '.arcadia', '.bin'])
9
- function checkedMaterialPath(value) {
10
- if (typeof value !== 'string' || !value || value.includes('\\') || value.includes('\0') || isAbsolute(value))
11
- throw contentError('MATERIAL_PATH_INVALID')
12
- const parts = value.split('/')
13
- if (
14
- parts.some(
15
- part =>
16
- !part ||
17
- part === '.' ||
18
- part === '..' ||
19
- forbidden.has(part) ||
20
- /[<>:"|?*]/.test(part) ||
21
- [...part].some(character => character.codePointAt(0) < 32) ||
22
- /[. ]$/.test(part) ||
23
- /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part),
24
- ) ||
25
- !materialRoots.has(parts[0])
26
- )
27
- throw contentError('MATERIAL_PATH_INVALID')
28
- return value
29
- }
30
-
31
- /** Capture data bytes only. Symlink targets must remain inside the installed project. */
32
- export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, onRead } = {}) {
33
- root = await realpath(root)
34
- const result = []
35
- const captured = []
36
- let total = 0
37
- async function walk(path, name, ancestors = new Set()) {
38
- signal?.throwIfAborted()
39
- const actual = await realpath(path)
40
- const rel = relative(root, actual)
41
- if (isAbsolute(rel) || rel === '..' || rel.startsWith('../')) throw contentError('MATERIAL_PATH_ESCAPE')
42
- checkedMaterialPath(rel.split('\\').join('/'))
43
- const info = await lstat(actual)
44
- captured.push({ path, actual, size: info.size, mtimeMs: info.mtimeMs, ino: info.ino })
45
- if (info.isDirectory()) {
46
- if (ancestors.has(actual)) throw contentError('MATERIAL_PATH_CYCLE')
47
- const next = new Set(ancestors).add(actual)
48
- for (const child of (await readdir(actual)).sort()) {
49
- if (forbidden.has(child)) continue
50
- await walk(join(actual, child), name ? `${name}/${child}` : child, next)
51
- }
52
- const after = await lstat(actual)
53
- if (info.ino !== after.ino || info.mtimeMs !== after.mtimeMs || info.ctimeMs !== after.ctimeMs)
54
- throw contentError('MATERIAL_SOURCE_CHANGED')
55
- onRead?.(actual, after)
56
- return
57
- }
58
- if (!info.isFile()) throw contentError('MATERIAL_FILE_INVALID')
59
- checkedMaterialPath(name)
60
- total += info.size
61
- if (total > maxBytes || result.length >= maxFiles) throw contentError('MATERIAL_LIMIT')
62
- const bytes = await readFile(actual)
63
- const after = await lstat(actual)
64
- if (
65
- info.size !== bytes.length ||
66
- info.mtimeMs !== after.mtimeMs ||
67
- info.ctimeMs !== after.ctimeMs ||
68
- info.ino !== after.ino
69
- )
70
- throw contentError('MATERIAL_SOURCE_CHANGED')
71
- onRead?.(actual, after)
72
- result.push({ path: name, bytes })
73
- }
74
- for (const name of materialRoots) {
75
- try {
76
- await lstat(join(root, name))
77
- } catch (error) {
78
- if (error.code === 'ENOENT' && name !== 'package.json' && name !== 'package-lock.json') continue
79
- throw error
80
- }
81
- try {
82
- await walk(join(root, name), name)
83
- } catch (error) {
84
- if (error.code === 'ENOENT') throw contentError('MATERIAL_SOURCE_CHANGED')
85
- throw error
86
- }
87
- }
88
- // Verify the whole captured tree after the last read. This detects membership
89
- // changes and retargeted links without a separate content-hash protocol.
90
- for (const entry of captured) {
91
- signal?.throwIfAborted()
92
- try {
93
- if ((await realpath(entry.path)) !== entry.actual) throw contentError('MATERIAL_SOURCE_CHANGED')
94
- const info = await lstat(entry.actual)
95
- if (entry.size !== info.size || entry.mtimeMs !== info.mtimeMs || entry.ino !== info.ino)
96
- throw contentError('MATERIAL_SOURCE_CHANGED')
97
- } catch (error) {
98
- if (error.code === 'ENOENT') throw contentError('MATERIAL_SOURCE_CHANGED')
99
- throw error
100
- }
101
- }
102
- return result
103
- }
104
-
105
- export async function writeMaterials(root, files, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000 } = {}) {
106
- if (!Array.isArray(files) || files.length > maxFiles) throw contentError('MATERIAL_LIMIT')
107
- const seen = new Set()
108
- let total = 0
109
- for (const file of files) {
110
- signal?.throwIfAborted()
111
- const path = checkedMaterialPath(file.path)
112
- // Case aliases are rejected even on case-sensitive machines for portable archives.
113
- const alias = path.toLowerCase()
114
- if (seen.has(alias)) throw contentError('MATERIAL_PATH_DUPLICATE')
115
- seen.add(alias)
116
- if (
117
- !Buffer.isBuffer(file.bytes) &&
118
- (typeof file.data !== 'string' ||
119
- !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data))
120
- )
121
- throw contentError('MATERIAL_ENCODING_INVALID')
122
- const bytes = Buffer.isBuffer(file.bytes) ? file.bytes : Buffer.from(file.data, 'base64')
123
- total += bytes.length
124
- if (total > maxBytes) throw contentError('MATERIAL_LIMIT')
125
- await mkdir(dirname(join(root, path)), { recursive: true })
126
- await writeFile(join(root, path), bytes, { flag: 'wx', mode: 0o600 })
127
- }
128
- if (!seen.has('package.json') || !seen.has('package-lock.json')) throw contentError('MATERIAL_LOCK_REQUIRED')
129
- // npm may omit this directory for a valid empty dependency graph. Static npm
130
- // inspection still expects it, including after a file-only archive round trip.
131
- await mkdir(join(root, 'node_modules'), { recursive: true })
132
- const lock = JSON.parse(await readFile(join(root, 'package-lock.json'), 'utf8'))
133
- if (![2, 3].includes(lock.lockfileVersion) || !lock.packages || typeof lock.packages !== 'object')
134
- throw contentError('MATERIAL_LOCK_INVALID')
135
- for (const pkg of Object.values(lock.packages)) {
136
- if (!pkg || typeof pkg !== 'object') throw contentError('MATERIAL_LOCK_INVALID')
137
- if (pkg.link === true) throw contentError('MATERIAL_LOCK_NOT_PORTABLE')
138
- if (typeof pkg.resolved === 'string' && /^https?:/.test(pkg.resolved)) {
139
- const url = new URL(pkg.resolved)
140
- if (
141
- url.username ||
142
- url.password ||
143
- [...url.searchParams.keys()].some(key => /token|secret|password|credential|authorization/i.test(key))
144
- )
145
- throw contentError('MATERIAL_LOCK_CREDENTIALS')
146
- }
147
- if (typeof pkg.resolved === 'string' && pkg.resolved.startsWith('file:')) {
148
- const path = pkg.resolved.slice(5)
149
- if (!path.startsWith('candidates/')) throw contentError('MATERIAL_LOCK_NOT_PORTABLE')
150
- checkedMaterialPath(path)
151
- }
152
- }
153
- }