@arcadia-eternity/content-sdk 4.3.3 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +3 -3
  2. package/bin/arcadia-content-mcp.mjs +2 -0
  3. package/bin/arcadia-content.mjs +2 -0
  4. package/dist/asset-inspect.d.ts +30 -0
  5. package/dist/asset-inspect.js +84 -0
  6. package/dist/author-api.d.ts +48 -0
  7. package/dist/author-api.js +128 -0
  8. package/dist/author-reference.d.ts +61 -0
  9. package/dist/author-reference.js +130 -0
  10. package/dist/build-content.d.ts +2 -0
  11. package/dist/build-content.js +29 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/cli.js +81 -0
  14. package/dist/content-query.d.ts +30 -0
  15. package/dist/content-query.js +326 -0
  16. package/dist/content-workspace.d.ts +204 -0
  17. package/dist/content-workspace.js +981 -0
  18. package/dist/debug-environments.d.ts +96 -0
  19. package/dist/debug-environments.js +135 -0
  20. package/dist/demo.d.ts +1 -0
  21. package/dist/demo.js +18 -0
  22. package/dist/effect-build.d.ts +3 -0
  23. package/dist/effect-build.js +44 -0
  24. package/dist/environment-rules.d.ts +7 -0
  25. package/dist/environment-rules.js +94 -0
  26. package/dist/environment.d.ts +48 -0
  27. package/dist/environment.js +184 -0
  28. package/dist/job-journal.d.ts +19 -0
  29. package/dist/job-journal.js +110 -0
  30. package/dist/jobs.d.ts +103 -0
  31. package/dist/jobs.js +626 -0
  32. package/dist/lib/content.d.ts +24 -0
  33. package/dist/lib/content.js +106 -0
  34. package/dist/lib/presentation.d.ts +26 -0
  35. package/dist/lib/presentation.js +252 -0
  36. package/dist/lib/yaml-sharing.d.ts +16 -0
  37. package/dist/lib/yaml-sharing.js +130 -0
  38. package/dist/managed-projects.d.ts +37 -0
  39. package/dist/managed-projects.js +305 -0
  40. package/dist/managed-sources.d.ts +28 -0
  41. package/dist/managed-sources.js +541 -0
  42. package/dist/mcp-contracts.d.ts +420 -0
  43. package/dist/mcp-contracts.js +146 -0
  44. package/dist/mcp.d.ts +2 -0
  45. package/dist/mcp.js +228 -0
  46. package/dist/module-path.d.ts +1 -0
  47. package/dist/module-path.js +8 -0
  48. package/dist/pack-project.d.ts +10 -0
  49. package/dist/pack-project.js +178 -0
  50. package/dist/preview-control.d.ts +17 -0
  51. package/dist/preview-control.js +273 -0
  52. package/dist/preview.d.ts +24 -0
  53. package/dist/preview.js +332 -0
  54. package/dist/project-teams.d.ts +51 -0
  55. package/dist/project-teams.js +106 -0
  56. package/dist/project.d.ts +18 -0
  57. package/dist/project.js +146 -0
  58. package/dist/rename.d.ts +2 -0
  59. package/dist/rename.js +128 -0
  60. package/dist/setup.d.ts +2 -0
  61. package/dist/setup.js +117 -0
  62. package/dist/source-lock.d.ts +9 -0
  63. package/dist/source-lock.js +117 -0
  64. package/dist/template/README.md +2 -0
  65. package/dist/template/docs/presentation.md +3 -3
  66. package/dist/template/package.json +3 -7
  67. package/dist/template/test/pack.test.mjs +10 -7
  68. package/dist/testing.d.ts +58 -0
  69. package/dist/testing.js +205 -0
  70. package/dist/types.d.ts +5 -0
  71. package/dist/types.js +14 -0
  72. package/dist/workbench-context.d.ts +10 -0
  73. package/dist/workbench-context.js +27 -0
  74. package/dist/workspace-cli.d.ts +1 -0
  75. package/dist/workspace-cli.js +66 -0
  76. package/dist/workspace-materials.d.ts +19 -0
  77. package/dist/workspace-materials.js +165 -0
  78. package/dist/workspace.d.ts +190 -0
  79. package/dist/workspace.js +726 -0
  80. package/package.json +34 -27
  81. package/dist/asset-inspect.mjs +0 -67
  82. package/dist/author-api.mjs +0 -112
  83. package/dist/author-reference.mjs +0 -121
  84. package/dist/build-content.mjs +0 -30
  85. package/dist/cli.mjs +0 -76
  86. package/dist/content-query.mjs +0 -283
  87. package/dist/content-workspace.d.mts +0 -161
  88. package/dist/content-workspace.mjs +0 -936
  89. package/dist/debug-environments.mjs +0 -154
  90. package/dist/demo.mjs +0 -22
  91. package/dist/effect-build.d.mts +0 -2
  92. package/dist/effect-build.mjs +0 -46
  93. package/dist/environment-rules.d.mts +0 -5
  94. package/dist/environment-rules.mjs +0 -92
  95. package/dist/environment.mjs +0 -183
  96. package/dist/job-journal.mjs +0 -94
  97. package/dist/jobs.mjs +0 -579
  98. package/dist/lib/content.mjs +0 -95
  99. package/dist/lib/presentation.mjs +0 -240
  100. package/dist/lib/yaml-sharing.mjs +0 -101
  101. package/dist/managed-projects.d.mts +0 -35
  102. package/dist/managed-projects.mjs +0 -303
  103. package/dist/managed-sources.d.mts +0 -19
  104. package/dist/managed-sources.mjs +0 -503
  105. package/dist/mcp-contracts.mjs +0 -153
  106. package/dist/mcp.mjs +0 -369
  107. package/dist/pack-project.mjs +0 -157
  108. package/dist/preview-control.mjs +0 -260
  109. package/dist/preview.mjs +0 -313
  110. package/dist/project-teams.mjs +0 -98
  111. package/dist/project.mjs +0 -140
  112. package/dist/rename.mjs +0 -112
  113. package/dist/setup.mjs +0 -134
  114. package/dist/source-lock.mjs +0 -103
  115. package/dist/testing.mjs +0 -204
  116. package/dist/workbench-context.mjs +0 -18
  117. package/dist/workspace-cli.mjs +0 -60
  118. package/dist/workspace-materials.mjs +0 -153
  119. package/dist/workspace.mjs +0 -684
  120. /package/dist/{index.d.mts → index.d.ts} +0 -0
  121. /package/dist/{index.mjs → index.js} +0 -0
@@ -1,154 +0,0 @@
1
- import { WorkspaceError } from './workspace.mjs'
2
- import { z } from 'zod'
3
- const idPattern = /^[a-z0-9][a-z0-9_-]{0,79}$/
4
- const packagePattern = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/
5
- const fail = message => {
6
- throw new WorkspaceError('ENVIRONMENT_INVALID', message)
7
- }
8
- const sharedFields = {
9
- id: z
10
- .string()
11
- .regex(idPattern)
12
- .refine(value => value !== 'default', 'default 是内置环境'),
13
- name: z
14
- .string()
15
- .min(1)
16
- .max(80)
17
- .refine(value => !!value.trim())
18
- .transform(value => value.trim()),
19
- packages: z.record(
20
- z.string().regex(packagePattern),
21
- z
22
- .string()
23
- .min(1)
24
- .refine(
25
- value => !!value.trim() && !/(?:file:|link:|workspace:|\/|\\)/.test(value),
26
- '额外 npm 包需要可共享的注册表版本约束',
27
- ),
28
- ),
29
- sources: z
30
- .array(z.string().regex(packagePattern))
31
- .max(20)
32
- .refine(value => new Set(value).size === value.length, '源码包标识不能重复'),
33
- }
34
-
35
- const reference = z
36
- .string()
37
- .min(1)
38
- .max(256)
39
- .regex(/^[a-zA-Z0-9_./:-]+$/)
40
- const uniqueList = schema =>
41
- z
42
- .array(schema)
43
- .max(10000)
44
- .refine(value => new Set(value).size === value.length, '引用不能重复')
45
- const contentSelection = z
46
- .object({
47
- species: uniqueList(reference).optional(),
48
- skills: uniqueList(reference).optional(),
49
- marks: uniqueList(reference).optional(),
50
- })
51
- .strict()
52
-
53
- /** Portable rule data. Runtime consumers must explicitly support every declared capability. */
54
- const EnvironmentRulesSchema = z
55
- .object({
56
- schemaVersion: z.literal(1),
57
- tier: z.string().regex(idPattern).optional(),
58
- allow: contentSelection.optional(),
59
- deny: contentSelection.optional(),
60
- team: z
61
- .object({
62
- minSize: z.number().int().min(1).max(100).optional(),
63
- maxSize: z.number().int().min(1).max(100).optional(),
64
- uniqueSpecies: z.boolean().optional(),
65
- })
66
- .strict()
67
- .refine(
68
- value => value.minSize === undefined || value.maxSize === undefined || value.minSize <= value.maxSize,
69
- '队伍最小数量不能大于最大数量',
70
- )
71
- .optional(),
72
- })
73
- .strict()
74
-
75
- const EnvironmentRequirementsSchema = z
76
- .object({
77
- engine: z.string().trim().min(1).max(128).optional(),
78
- sdk: z.string().trim().min(1).max(128).optional(),
79
- capabilities: uniqueList(z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/)).optional(),
80
- })
81
- .strict()
82
-
83
- const EnvironmentDocumentV1Schema = z.object({ schemaVersion: z.literal(1), ...sharedFields }).strict()
84
- export const EnvironmentDocumentV2Schema = z
85
- .object({
86
- schemaVersion: z.literal(2),
87
- ...sharedFields,
88
- disabled: z.object({ packages: sharedFields.packages, sources: sharedFields.sources }).strict().optional(),
89
- rules: EnvironmentRulesSchema,
90
- requires: EnvironmentRequirementsSchema,
91
- })
92
- .strict()
93
-
94
- export const EnvironmentDocumentSchema = z.discriminatedUnion('schemaVersion', [
95
- EnvironmentDocumentV1Schema,
96
- EnvironmentDocumentV2Schema,
97
- ])
98
- export function environmentDocument(input) {
99
- const parsed = EnvironmentDocumentSchema.safeParse(input)
100
- if (!parsed.success) fail(`环境配置无效:${parsed.error.issues[0].message}`)
101
- const value = parsed.data
102
- if (
103
- value.disabled &&
104
- (Object.keys(value.disabled.packages).some(
105
- name => Object.hasOwn(value.packages, name) || value.sources.includes(name),
106
- ) ||
107
- value.disabled.sources.some(
108
- name =>
109
- Object.hasOwn(value.packages, name) ||
110
- value.sources.includes(name) ||
111
- Object.hasOwn(value.disabled.packages, name),
112
- ))
113
- )
114
- fail('启用和停用的资源包不能重复')
115
- return value
116
- }
117
-
118
- /** Read legacy documents into the shared domain model without rewriting source files. */
119
- export function normalizeEnvironmentDocument(value) {
120
- const document = environmentDocument(value)
121
- if (document.schemaVersion === 2) return document
122
- return { ...document, schemaVersion: 2, rules: { schemaVersion: 1 }, requires: {} }
123
- }
124
- export class DebugEnvironments {
125
- constructor(workspace) {
126
- this.workspace = workspace
127
- }
128
- file(id) {
129
- if (typeof id !== 'string' || !idPattern.test(id) || id === 'default') fail('环境标识无效')
130
- return `debug/environments/${id}.json`
131
- }
132
- async list() {
133
- const environments = [
134
- { schemaVersion: 1, id: 'default', name: '当前包与正式依赖', packages: {}, sources: [], version: null },
135
- ]
136
- for (const { file } of await this.workspace.files()) {
137
- if (!/^debug\/environments\/[^/]+\.json$/.test(file) || file.endsWith('.package-lock.json')) continue
138
- const source = await this.workspace.read(file),
139
- value = environmentDocument(JSON.parse(source.text))
140
- if (this.file(value.id) !== file) fail('环境文件名与标识不一致')
141
- environments.push({ ...value, version: source.version })
142
- }
143
- return environments
144
- }
145
- async save({ document, expectedVersion }) {
146
- const value = environmentDocument(document)
147
- const result = await this.workspace.write({
148
- file: this.file(value.id),
149
- expectedVersion,
150
- text: JSON.stringify(value, null, 2) + '\n',
151
- })
152
- return { ...value, version: result.version }
153
- }
154
- }
package/dist/demo.mjs DELETED
@@ -1,22 +0,0 @@
1
- import { prepareContentPack, runBattle } from './testing.mjs'
2
- import { setGlobalLogger } from '@arcadia-eternity/battle/engine'
3
- setGlobalLogger({ debug() {}, info() {}, warn() {}, error() {} })
4
- const example = await prepareContentPack()
5
- try {
6
- console.log(`Package: ${example.manifest.name}`)
7
- console.log(`Namespace: ${example.manifest.arcadia.namespace}`)
8
- console.log(`Environment: ${example.environment.revision}`)
9
- const result = await runBattle(await example.createBattle(), battle => {
10
- const pets = [battle.playerA, battle.playerB].map(
11
- player =>
12
- `${player.name}: HP ${player.activePet.currentHp}, speed ${player.activePet.stat.spe}, marks ${player.activePet.marks.length}`,
13
- )
14
- console.log(`Turn ${battle.currentTurn}: ${pets.join(' | ')}`)
15
- })
16
- console.log(`Winner: ${result.winner}; finished in ${result.turns} turns.`)
17
- console.log(
18
- `ARCADIA_RESULT=${JSON.stringify({ ...result, candidate: example.candidate, environmentRevision: example.environment.revision, packageName: example.manifest.name, files: example.files })}`,
19
- )
20
- } finally {
21
- await example.dispose()
22
- }
@@ -1,2 +0,0 @@
1
- export declare function buildEffects(root: string): Promise<void>
2
- export { effectDiscoveryPlugin } from '@arcadia-eternity/pack-loader/effect-build'
@@ -1,46 +0,0 @@
1
- import { readFile, writeFile, mkdir, rename, realpath, lstat, rm } from 'node:fs/promises'
2
- import { resolve, relative, isAbsolute, dirname, sep } from 'node:path'
3
- import { compileEffectModule } from '@arcadia-eternity/pack-loader/effect-build'
4
-
5
- /** Build closed effect text without evaluating author code. The installed artifact is consumed by environment preparation. */
6
- export async function buildEffects(root) {
7
- root = await realpath(root)
8
- const pkg = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'))
9
- const directory = pkg.arcadia?.effectSources
10
- if (directory === undefined) return
11
- if (
12
- typeof directory !== 'string' ||
13
- !directory ||
14
- typeof pkg.arcadia.effectArtifact !== 'string' ||
15
- pkg.arcadia.effects
16
- )
17
- throw new Error('effectSources requires an effectArtifact destination and no effects entry')
18
- const source = resolve(root, directory),
19
- destination = resolve(root, pkg.arcadia.effectArtifact)
20
- for (const path of [source, destination]) {
21
- const rel = relative(resolve(root), path)
22
- if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) throw new Error('Effect path escapes project')
23
- }
24
- const canonicalSource = await realpath(source)
25
- const sourceLocation = relative(root, canonicalSource)
26
- if (sourceLocation === '..' || sourceLocation.startsWith(`..${sep}`) || isAbsolute(sourceLocation))
27
- throw new Error('Effect source escapes project')
28
- let parent = root
29
- for (const segment of relative(root, dirname(destination)).split(sep).filter(Boolean)) {
30
- parent = resolve(parent, segment)
31
- await mkdir(parent, { recursive: true })
32
- const info = await lstat(parent)
33
- if (!info.isDirectory() || info.isSymbolicLink())
34
- throw new Error('Effect output must use regular project directories')
35
- }
36
- const artifact = await compileEffectModule(source, root, pkg.name)
37
- const temporary = `${destination}.${process.pid}.tmp`
38
- await writeFile(temporary, JSON.stringify(artifact) + '\n', { flag: 'wx' })
39
- try {
40
- await rename(temporary, destination)
41
- } finally {
42
- await rm(temporary, { force: true })
43
- }
44
- }
45
-
46
- export { effectDiscoveryPlugin } from '@arcadia-eternity/pack-loader/effect-build'
@@ -1,5 +0,0 @@
1
- import type { EnvironmentRules } from './content-workspace.mjs'
2
-
3
- export function validateEnvironmentRules(rules?: unknown): EnvironmentRules
4
- export function assertEnvironmentRequirements(requires?: unknown): void
5
- export function assertEnvironmentTeam(rules: unknown, team: unknown): void
@@ -1,92 +0,0 @@
1
- const fail = code => {
2
- throw Object.assign(new Error(code), { code })
3
- }
4
- const record = value => value !== null && typeof value === 'object' && !Array.isArray(value)
5
- const keysAllowed = (value, names) => Object.keys(value).every(name => names.includes(name))
6
- const identifier = value =>
7
- typeof value === 'string' && value.length > 0 && value.length <= 256 && !/\p{Cc}/u.test(value)
8
-
9
- /** Validate the currently implemented rule vocabulary before admitting an environment. */
10
- export function validateEnvironmentRules(input) {
11
- const rules = input === undefined ? { schemaVersion: 1 } : input
12
- if (!record(rules) || !keysAllowed(rules, ['schemaVersion', 'tier', 'allow', 'deny', 'team']))
13
- fail('ENVIRONMENT_RULES_INVALID')
14
- if (rules.schemaVersion !== 1 || (rules.tier !== undefined && rules.tier !== 'standard'))
15
- fail('ENVIRONMENT_RULES_UNSUPPORTED')
16
- for (const group of [rules.allow, rules.deny]) {
17
- if (group === undefined) continue
18
- if (!record(group) || !keysAllowed(group, ['species', 'skills', 'marks'])) fail('ENVIRONMENT_RULES_INVALID')
19
- for (const values of Object.values(group)) {
20
- if (
21
- !Array.isArray(values) ||
22
- values.length > 10000 ||
23
- values.some(value => !identifier(value)) ||
24
- new Set(values).size !== values.length
25
- )
26
- fail('ENVIRONMENT_RULES_INVALID')
27
- }
28
- }
29
- if (
30
- rules.team !== undefined &&
31
- (!record(rules.team) || !keysAllowed(rules.team, ['minSize', 'maxSize', 'uniqueSpecies']))
32
- )
33
- fail('ENVIRONMENT_RULES_INVALID')
34
- const { minSize = 1, maxSize = 6, uniqueSpecies } = rules.team ?? {}
35
- if (
36
- !Number.isInteger(minSize) ||
37
- !Number.isInteger(maxSize) ||
38
- minSize < 1 ||
39
- maxSize > 6 ||
40
- minSize > maxSize ||
41
- (uniqueSpecies !== undefined && typeof uniqueSpecies !== 'boolean')
42
- )
43
- fail('ENVIRONMENT_RULES_INVALID')
44
- return structuredClone(rules)
45
- }
46
-
47
- /** Version requirements fail closed until a host implements capability negotiation. */
48
- export function assertEnvironmentRequirements(input) {
49
- const requires = input === undefined ? {} : input
50
- if (!record(requires) || !keysAllowed(requires, ['engine', 'sdk', 'capabilities']))
51
- fail('ENVIRONMENT_REQUIREMENT_INVALID')
52
- for (const key of ['engine', 'sdk'])
53
- if (requires[key] !== undefined && (typeof requires[key] !== 'string' || !requires[key].trim()))
54
- fail('ENVIRONMENT_REQUIREMENT_INVALID')
55
- if (
56
- requires.capabilities !== undefined &&
57
- (!Array.isArray(requires.capabilities) || requires.capabilities.some(value => !identifier(value)))
58
- )
59
- fail('ENVIRONMENT_REQUIREMENT_INVALID')
60
- if (requires.capabilities?.length) fail('ENVIRONMENT_CAPABILITY_UNSUPPORTED')
61
- if (requires.engine !== undefined || requires.sdk !== undefined) fail('ENVIRONMENT_REQUIREMENT_UNSUPPORTED')
62
- }
63
-
64
- /** Admission checks apply to normalized team definitions, before creating any battle. */
65
- export function assertEnvironmentTeam(input, team) {
66
- const rules = validateEnvironmentRules(input)
67
- const { minSize = 1, maxSize = 6, uniqueSpecies = false } = rules.team ?? {}
68
- if (!Array.isArray(team) || team.length < minSize || team.length > maxSize) fail('ENVIRONMENT_TEAM_REJECTED')
69
- for (const pet of team) {
70
- if (
71
- !record(pet) ||
72
- !identifier(pet.species) ||
73
- !Array.isArray(pet.skills) ||
74
- pet.skills.some(skill => !identifier(skill))
75
- )
76
- fail('ENVIRONMENT_TEAM_REJECTED')
77
- if ([pet.ability, pet.emblem].some(mark => mark !== undefined && mark !== '' && !identifier(mark)))
78
- fail('ENVIRONMENT_TEAM_REJECTED')
79
- const selected = {
80
- species: [pet.species],
81
- skills: pet.skills,
82
- marks: [pet.ability, pet.emblem].filter(value => !!value),
83
- }
84
- for (const kind of ['species', 'skills', 'marks']) {
85
- const allow = rules.allow?.[kind],
86
- deny = rules.deny?.[kind]
87
- if (selected[kind].some(id => (allow !== undefined && !allow.includes(id)) || deny?.includes(id)))
88
- fail('ENVIRONMENT_TEAM_REJECTED')
89
- }
90
- }
91
- if (uniqueSpecies && new Set(team.map(pet => pet.species)).size !== team.length) fail('ENVIRONMENT_TEAM_REJECTED')
92
- }
@@ -1,183 +0,0 @@
1
- import assert from 'node:assert/strict'
2
- import { execFile } from 'node:child_process'
3
- import { mkdir, mkdtemp, readFile, rm, writeFile, cp, symlink } from 'node:fs/promises'
4
- import { tmpdir } from 'node:os'
5
- import { join, resolve, dirname } from 'node:path'
6
- import { promisify } from 'node:util'
7
- import { emptyNpmContentHost, prepareNpmProject, resolveNpmInvocation } from '@arcadia-eternity/pack-loader/node'
8
- import { AuthorWorkspace } from './workspace.mjs'
9
- import { ProjectTeams, playersFromTeams } from './project-teams.mjs'
10
- import { createHash } from 'node:crypto'
11
- import { fileURLToPath } from 'node:url'
12
- import { DebugEnvironments, normalizeEnvironmentDocument } from './debug-environments.mjs'
13
- import { assertEnvironmentRequirements, validateEnvironmentRules } from './environment-rules.mjs'
14
- const exec = promisify(execFile)
15
- async function npm(args, options) {
16
- const invocation = await resolveNpmInvocation(args)
17
- return exec(invocation.file, invocation.args, options)
18
- }
19
- /** Pack and install exactly what a consuming server receives. Approval is limited to this local demo. */
20
- export async function prepareBattleEnvironment(
21
- root = process.cwd(),
22
- { offline = true, cache, environmentId = 'default', sources = {}, lockRoot } = {},
23
- ) {
24
- root = resolve(root)
25
- const temporary = await mkdtemp(join(tmpdir(), 'arcadia-pack-template-'))
26
- const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
27
- const cacheArgs = cache ? ['--cache', resolve(cache)] : []
28
- const battles = new Set()
29
- const sourceRevisions = {}
30
- let environment, workspace, lockWorkspace
31
- async function dispose() {
32
- for (const battle of battles) await battle.cleanup()
33
- await environment?.dispose()
34
- await workspace?.close()
35
- await lockWorkspace?.close()
36
- await rm(temporary, { recursive: true, force: true })
37
- }
38
- try {
39
- workspace = await AuthorWorkspace.open(root, { watch: false })
40
- const selected = (await new DebugEnvironments(workspace).list()).find(entry => entry.id === environmentId)
41
- if (!selected) throw new Error(`ENVIRONMENT_MISSING: ${environmentId}`)
42
- const { version: _version, ...selectedDocument } = selected
43
- const environmentDocument =
44
- environmentId === 'default'
45
- ? { ...selectedDocument, schemaVersion: 2, rules: { schemaVersion: 1 }, requires: {} }
46
- : normalizeEnvironmentDocument(selectedDocument)
47
- assertEnvironmentRequirements(environmentDocument.requires)
48
- validateEnvironmentRules(environmentDocument.rules)
49
- const lockFile = environmentId === 'default' ? undefined : `debug/environments/${environmentId}.package-lock.json`
50
- let oldLock
51
- if (lockFile) {
52
- try {
53
- oldLock = await workspace.read(lockFile)
54
- } catch (error) {
55
- if (error.code !== 'ENOENT') throw error
56
- }
57
- }
58
- const result = await npm(['pack', '--json', '--ignore-scripts', '--pack-destination', temporary, ...cacheArgs], {
59
- cwd: root,
60
- })
61
- const packed = JSON.parse(result.stdout)[0]
62
- const files = packed.files.map(file => file.path)
63
- assert.ok(files.includes(manifest.arcadia.content))
64
- if (manifest.arcadia.effects) assert.ok(files.includes(manifest.arcadia.effects))
65
- assert.ok(
66
- !files.some(file => /^(?:\.arcadia|\.github|node_modules|test|scripts|debug)\//.test(file)),
67
- 'the package must contain content, not a developer workspace',
68
- )
69
- const installation = join(temporary, 'server-project')
70
- await mkdir(join(installation, 'candidates'), { recursive: true })
71
- const dependencies = { ...selected.packages }
72
- async function addCandidate(directory, metadata, packedInfo) {
73
- if (Object.hasOwn(dependencies, metadata.name)) throw new Error(`ENVIRONMENT_DUPLICATE: ${metadata.name}`)
74
- const filename = `candidates/${packedInfo.shasum}.tgz`
75
- await cp(join(directory, packedInfo.filename), join(installation, filename))
76
- dependencies[metadata.name] = `file:${filename}`
77
- }
78
- await addCandidate(temporary, manifest, packed)
79
- for (const name of selected.sources) {
80
- const source = sources[name]
81
- if (typeof source !== 'string') throw new Error(`ENVIRONMENT_SOURCE_MISSING: ${name},请设置本机源码映射`)
82
- const sourceWorkspace = await AuthorWorkspace.open(resolve(source), { watch: false })
83
- try {
84
- const before = await sourceWorkspace.revision({ contentOnly: true })
85
- sourceRevisions[name] = before
86
- const captured = join(temporary, `source-${Object.keys(dependencies).length}`)
87
- await mkdir(captured)
88
- for (const entry of await sourceWorkspace.files()) {
89
- if (entry.error) throw new Error(entry.error)
90
- await mkdir(dirname(join(captured, entry.file)), { recursive: true })
91
- await cp(await sourceWorkspace.path(entry.file), join(captured, entry.file))
92
- }
93
- if (before !== (await sourceWorkspace.revision({ contentOnly: true })))
94
- throw new Error('ENVIRONMENT_SOURCE_CHANGED')
95
- await symlink(
96
- join(sourceWorkspace.root, 'node_modules'),
97
- join(captured, 'node_modules'),
98
- process.platform === 'win32' ? 'junction' : 'dir',
99
- )
100
- const metadata = JSON.parse(await readFile(join(captured, 'package.json'), 'utf8'))
101
- if (metadata.name !== name) throw new Error(`ENVIRONMENT_SOURCE_IDENTITY: ${name}`)
102
- await exec(process.execPath, [fileURLToPath(new URL('./cli.mjs', import.meta.url)), 'build'], { cwd: captured })
103
- const info = JSON.parse(
104
- (await npm(['pack', '--json', '--ignore-scripts', ...cacheArgs], { cwd: captured })).stdout,
105
- )[0]
106
- if (info.files.some(file => /^(?:debug|test|scripts|node_modules|\.arcadia|\.github)\//.test(file.path)))
107
- throw new Error('ENVIRONMENT_PACKAGE_FILES')
108
- await addCandidate(captured, metadata, info)
109
- } finally {
110
- await sourceWorkspace.close()
111
- }
112
- }
113
- if (oldLock) await writeFile(join(installation, 'package-lock.json'), oldLock.text)
114
- await writeFile(
115
- join(installation, 'package.json'),
116
- JSON.stringify({
117
- name: 'arcadia-template-demo-server',
118
- version: '1.0.0',
119
- private: true,
120
- dependencies,
121
- }),
122
- )
123
- await npm(
124
- [
125
- 'install',
126
- ...(offline ? ['--offline'] : []),
127
- '--ignore-scripts',
128
- '--omit=dev',
129
- '--no-audit',
130
- '--no-fund',
131
- ...cacheArgs,
132
- ],
133
- { cwd: installation },
134
- )
135
- environment = await prepareNpmProject(installation, emptyNpmContentHost, {
136
- policy: { profile: 'local-development' },
137
- })
138
- let environmentLock
139
- if (lockFile) {
140
- const text = await readFile(join(installation, 'package-lock.json'), 'utf8')
141
- if (lockRoot) {
142
- lockWorkspace = await AuthorWorkspace.open(resolve(lockRoot), { watch: false })
143
- const saved = await lockWorkspace.write({ file: lockFile, expectedVersion: oldLock?.version ?? null, text })
144
- environmentLock = { file: lockFile, version: saved.version }
145
- } else environmentLock = { file: lockFile, version: createHash('sha256').update(text).digest('hex') }
146
- }
147
- const teamLibrary = await new ProjectTeams(workspace).list()
148
- function loadTeams(ids) {
149
- return playersFromTeams(teamLibrary, ids)
150
- }
151
- const candidate = {
152
- packageName: manifest.name,
153
- version: manifest.version,
154
- integrity: packed.integrity,
155
- shasum: packed.shasum,
156
- sdkApi: manifest.arcadia.sdkApi,
157
- build: environment.build,
158
- environmentRevision: environment.revision,
159
- environmentId,
160
- environmentConfigVersion: selected.version,
161
- }
162
- if (process.env.ARCADIA_AUTHOR_RESULT === '1')
163
- console.log(`ARCADIA_RESULT=${JSON.stringify({ candidate, environmentLock, sourceRevisions })}`)
164
- return {
165
- environment,
166
- environmentDocument,
167
- candidate,
168
- environmentLock,
169
- sourceRevisions,
170
- loadTeams,
171
- teams: teamLibrary,
172
- teamVersions: Object.fromEntries(teamLibrary.map(team => [team.id, team.version])),
173
- manifest,
174
- files,
175
- dispose,
176
- track: battle => battles.add(battle),
177
- untrack: battle => battles.delete(battle),
178
- }
179
- } catch (error) {
180
- await dispose()
181
- throw error
182
- }
183
- }
@@ -1,94 +0,0 @@
1
- import { mkdir, readdir, readFile, rm, lstat } from 'node:fs/promises'
2
- import { join } from 'node:path'
3
- import writeFileAtomic from 'write-file-atomic'
4
-
5
- const idPattern = /^[a-f0-9-]{36}$/
6
- /** Local task receipts and cancellation requests are never part of a content package. */
7
- export class JobJournal {
8
- #last = new Map()
9
- constructor(root) {
10
- this.directory = join(root, '.arcadia', 'author-jobs')
11
- }
12
- file(id, suffix = 'json') {
13
- if (!idPattern.test(id)) throw new Error('TASK_INVALID')
14
- return join(this.directory, `${id}.${suffix}`)
15
- }
16
- async save(job, live) {
17
- const text = JSON.stringify({ pid: process.pid, live, job })
18
- if (this.#last.get(job.jobId) === text) return
19
- await mkdir(this.directory, { recursive: true })
20
- await writeFileAtomic(this.file(job.jobId), text, { mode: 0o600 })
21
- this.#last.set(job.jobId, text)
22
- }
23
- async read() {
24
- let names
25
- try {
26
- names = await readdir(this.directory)
27
- } catch (error) {
28
- if (error.code === 'ENOENT') return []
29
- throw error
30
- }
31
- const records = []
32
- for (const name of names.filter(name => idPattern.test(name.slice(0, -5)) && name.endsWith('.json'))) {
33
- const file = join(this.directory, name)
34
- let info
35
- try {
36
- info = await lstat(file)
37
- } catch (error) {
38
- if (error.code === 'ENOENT') continue
39
- throw error
40
- }
41
- if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) continue
42
- let receipt
43
- try {
44
- receipt = JSON.parse(await readFile(file, 'utf8'))
45
- } catch (error) {
46
- if (error instanceof SyntaxError || error.code === 'ENOENT') continue
47
- throw error
48
- }
49
- if (
50
- !receipt.job ||
51
- `${receipt.job.jobId}.json` !== name ||
52
- !Number.isInteger(receipt.pid) ||
53
- receipt.pid <= 0 ||
54
- !Array.isArray(receipt.job.diagnostics)
55
- )
56
- continue
57
- if (receipt.live || ['queued', 'running'].includes(receipt.job.state)) {
58
- try {
59
- process.kill(receipt.pid, 0)
60
- } catch (error) {
61
- if (error.code === 'ESRCH') {
62
- receipt.live = false
63
- receipt.job.state = 'interrupted'
64
- receipt.job.diagnostics.push({
65
- code: 'TASK_INTERRUPTED',
66
- message: '任务宿主已退出;请重新运行。源项目和已安装版本保留。',
67
- })
68
- }
69
- }
70
- }
71
- records.push(receipt)
72
- }
73
- const ordered = records.sort((a, b) => (a.job.createdAt ?? 0) - (b.job.createdAt ?? 0))
74
- const active = receipt => receipt.live || ['queued', 'running'].includes(receipt.job.state)
75
- const history = new Set(ordered.filter(receipt => !active(receipt)).slice(-30))
76
- return ordered.filter(receipt => active(receipt) || history.has(receipt))
77
- }
78
- async requestCancel(id) {
79
- await writeFileAtomic(this.file(id, 'cancel'), '', { mode: 0o600 })
80
- }
81
- async cancelled(id) {
82
- try {
83
- await lstat(this.file(id, 'cancel'))
84
- return true
85
- } catch (error) {
86
- if (error.code === 'ENOENT') return false
87
- throw error
88
- }
89
- }
90
- async remove(id) {
91
- await Promise.all(['json', 'cancel'].map(suffix => rm(this.file(id, suffix), { force: true })))
92
- this.#last.delete(id)
93
- }
94
- }