@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.
- package/README.md +3 -3
- package/bin/arcadia-content-mcp.mjs +2 -0
- package/bin/arcadia-content.mjs +2 -0
- package/dist/asset-inspect.d.ts +30 -0
- package/dist/asset-inspect.js +84 -0
- package/dist/author-api.d.ts +48 -0
- package/dist/author-api.js +128 -0
- package/dist/author-reference.d.ts +61 -0
- package/dist/author-reference.js +130 -0
- package/dist/build-content.d.ts +2 -0
- package/dist/build-content.js +29 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +81 -0
- package/dist/content-query.d.ts +30 -0
- package/dist/content-query.js +326 -0
- package/dist/content-workspace.d.ts +204 -0
- package/dist/content-workspace.js +981 -0
- package/dist/debug-environments.d.ts +96 -0
- package/dist/debug-environments.js +135 -0
- package/dist/demo.d.ts +1 -0
- package/dist/demo.js +18 -0
- package/dist/effect-build.d.ts +3 -0
- package/dist/effect-build.js +44 -0
- package/dist/environment-rules.d.ts +7 -0
- package/dist/environment-rules.js +94 -0
- package/dist/environment.d.ts +48 -0
- package/dist/environment.js +184 -0
- package/dist/job-journal.d.ts +19 -0
- package/dist/job-journal.js +110 -0
- package/dist/jobs.d.ts +103 -0
- package/dist/jobs.js +626 -0
- package/dist/lib/content.d.ts +24 -0
- package/dist/lib/content.js +106 -0
- package/dist/lib/presentation.d.ts +26 -0
- package/dist/lib/presentation.js +252 -0
- package/dist/lib/yaml-sharing.d.ts +16 -0
- package/dist/lib/yaml-sharing.js +130 -0
- package/dist/managed-projects.d.ts +37 -0
- package/dist/managed-projects.js +305 -0
- package/dist/managed-sources.d.ts +28 -0
- package/dist/managed-sources.js +541 -0
- package/dist/mcp-contracts.d.ts +420 -0
- package/dist/mcp-contracts.js +146 -0
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +228 -0
- package/dist/module-path.d.ts +1 -0
- package/dist/module-path.js +8 -0
- package/dist/pack-project.d.ts +10 -0
- package/dist/pack-project.js +178 -0
- package/dist/preview-control.d.ts +17 -0
- package/dist/preview-control.js +273 -0
- package/dist/preview.d.ts +24 -0
- package/dist/preview.js +332 -0
- package/dist/project-teams.d.ts +51 -0
- package/dist/project-teams.js +106 -0
- package/dist/project.d.ts +18 -0
- package/dist/project.js +146 -0
- package/dist/rename.d.ts +2 -0
- package/dist/rename.js +128 -0
- package/dist/setup.d.ts +2 -0
- package/dist/setup.js +117 -0
- package/dist/source-lock.d.ts +9 -0
- package/dist/source-lock.js +117 -0
- package/dist/template/README.md +2 -0
- package/dist/template/docs/presentation.md +3 -3
- package/dist/template/package.json +3 -7
- package/dist/template/test/pack.test.mjs +10 -7
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +205 -0
- package/dist/types.d.ts +5 -0
- package/dist/types.js +14 -0
- package/dist/workbench-context.d.ts +10 -0
- package/dist/workbench-context.js +27 -0
- package/dist/workspace-cli.d.ts +1 -0
- package/dist/workspace-cli.js +66 -0
- package/dist/workspace-materials.d.ts +19 -0
- package/dist/workspace-materials.js +165 -0
- package/dist/workspace.d.ts +190 -0
- package/dist/workspace.js +726 -0
- package/package.json +34 -27
- package/dist/asset-inspect.mjs +0 -67
- package/dist/author-api.mjs +0 -112
- package/dist/author-reference.mjs +0 -121
- package/dist/build-content.mjs +0 -30
- package/dist/cli.mjs +0 -76
- package/dist/content-query.mjs +0 -283
- package/dist/content-workspace.d.mts +0 -161
- package/dist/content-workspace.mjs +0 -936
- package/dist/debug-environments.mjs +0 -154
- package/dist/demo.mjs +0 -22
- package/dist/effect-build.d.mts +0 -2
- package/dist/effect-build.mjs +0 -46
- package/dist/environment-rules.d.mts +0 -5
- package/dist/environment-rules.mjs +0 -92
- package/dist/environment.mjs +0 -183
- package/dist/job-journal.mjs +0 -94
- package/dist/jobs.mjs +0 -579
- package/dist/lib/content.mjs +0 -95
- package/dist/lib/presentation.mjs +0 -240
- package/dist/lib/yaml-sharing.mjs +0 -101
- package/dist/managed-projects.d.mts +0 -35
- package/dist/managed-projects.mjs +0 -303
- package/dist/managed-sources.d.mts +0 -19
- package/dist/managed-sources.mjs +0 -503
- package/dist/mcp-contracts.mjs +0 -153
- package/dist/mcp.mjs +0 -369
- package/dist/pack-project.mjs +0 -157
- package/dist/preview-control.mjs +0 -260
- package/dist/preview.mjs +0 -313
- package/dist/project-teams.mjs +0 -98
- package/dist/project.mjs +0 -140
- package/dist/rename.mjs +0 -112
- package/dist/setup.mjs +0 -134
- package/dist/source-lock.mjs +0 -103
- package/dist/testing.mjs +0 -204
- package/dist/workbench-context.mjs +0 -18
- package/dist/workspace-cli.mjs +0 -60
- package/dist/workspace-materials.mjs +0 -153
- package/dist/workspace.mjs +0 -684
- /package/dist/{index.d.mts → index.d.ts} +0 -0
- /package/dist/{index.mjs → index.js} +0 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import YAML from 'yaml';
|
|
2
|
+
import { PetSchema, parseWithErrors } from '@arcadia-eternity/schema';
|
|
3
|
+
import { WorkspaceError } from './workspace.js';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { errorMessage } from './types.js';
|
|
6
|
+
const validId = /^[a-z0-9][a-z0-9_-]{0,79}$/;
|
|
7
|
+
const petKeys = Object.keys(PetSchema.properties).filter(key => key !== 'id');
|
|
8
|
+
function invalid(message) {
|
|
9
|
+
throw new WorkspaceError('TEAM_INVALID', message);
|
|
10
|
+
}
|
|
11
|
+
/** Team envelope and portable pet fields are shared with author reference discovery. */
|
|
12
|
+
export const teamEnvelopeSchema = z
|
|
13
|
+
.object({
|
|
14
|
+
schemaVersion: z.literal(1),
|
|
15
|
+
id: z.string().regex(validId),
|
|
16
|
+
name: z
|
|
17
|
+
.string()
|
|
18
|
+
.min(1)
|
|
19
|
+
.max(80)
|
|
20
|
+
.refine(value => !!value.trim())
|
|
21
|
+
.overwrite(value => value.trim()),
|
|
22
|
+
team: z.array(z.unknown()).max(6),
|
|
23
|
+
})
|
|
24
|
+
.strict();
|
|
25
|
+
export const portablePetSchema = {
|
|
26
|
+
...PetSchema,
|
|
27
|
+
properties: Object.fromEntries(petKeys.map(key => [key, PetSchema.properties[key]])),
|
|
28
|
+
required: PetSchema.required.filter(key => key !== 'id'),
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
};
|
|
31
|
+
const portablePetInputSchema = z.record(z.string(), z.unknown()).transform((value, context) => {
|
|
32
|
+
try {
|
|
33
|
+
if (Object.keys(value).some(key => !petKeys.includes(key)))
|
|
34
|
+
throw new Error('精灵配置包含运行时编号或未知字段');
|
|
35
|
+
const parsed = parseWithErrors(PetSchema, { ...value, id: '0'.repeat(21) });
|
|
36
|
+
return Object.fromEntries(petKeys
|
|
37
|
+
.filter(key => parsed[key] !== undefined)
|
|
38
|
+
.map(key => [key, parsed[key]]));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
context.addIssue({ code: z.ZodIssueCode.custom, message: errorMessage(error) });
|
|
42
|
+
return z.NEVER;
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
export const TeamDocumentSchema = teamEnvelopeSchema.extend({ team: z.array(portablePetInputSchema).max(6) });
|
|
46
|
+
export function teamDocument(value) {
|
|
47
|
+
const parsed = TeamDocumentSchema.safeParse(value);
|
|
48
|
+
if (!parsed.success)
|
|
49
|
+
invalid(`测试队伍配置无效:${parsed.error.issues[0].message}`);
|
|
50
|
+
return parsed.data;
|
|
51
|
+
}
|
|
52
|
+
/** Copy saved team documents into independent players with deterministic, battle-local identities. */
|
|
53
|
+
export function playersFromTeams(teamLibrary, ids) {
|
|
54
|
+
if (!Array.isArray(ids) || ids.length !== 2)
|
|
55
|
+
throw new Error('测试必须显式指定两个项目队伍标识');
|
|
56
|
+
return ids.map((id, side) => {
|
|
57
|
+
const entry = teamLibrary.find(team => team.id === id);
|
|
58
|
+
if (!entry)
|
|
59
|
+
throw new Error(`TEAM_MISSING: ${id}`);
|
|
60
|
+
return {
|
|
61
|
+
id: String(side).repeat(21),
|
|
62
|
+
name: entry.name,
|
|
63
|
+
team: entry.team.map((pet, index) => ({ ...structuredClone(pet), id: `p${side}${index}`.padEnd(21, '0') })),
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export class ProjectTeams {
|
|
68
|
+
workspace;
|
|
69
|
+
constructor(workspace) {
|
|
70
|
+
this.workspace = workspace;
|
|
71
|
+
}
|
|
72
|
+
file(id) {
|
|
73
|
+
if (typeof id !== 'string' || !validId.test(id))
|
|
74
|
+
invalid('测试队伍标识无效');
|
|
75
|
+
return `debug/teams/${id}.yaml`;
|
|
76
|
+
}
|
|
77
|
+
async list() {
|
|
78
|
+
const teams = [];
|
|
79
|
+
for (const { file } of await this.workspace.files()) {
|
|
80
|
+
if (!/^debug\/teams\/[^/]+\.yaml$/.test(file))
|
|
81
|
+
continue;
|
|
82
|
+
const source = await this.workspace.read(file);
|
|
83
|
+
const document = teamDocument(YAML.parse(source.text));
|
|
84
|
+
if (file !== this.file(document.id))
|
|
85
|
+
invalid(`文件名与队伍标识不同:${file}`);
|
|
86
|
+
teams.push({ ...document, version: source.version });
|
|
87
|
+
}
|
|
88
|
+
return teams;
|
|
89
|
+
}
|
|
90
|
+
async save({ document, expectedVersion, }) {
|
|
91
|
+
const parsed = teamDocument(document);
|
|
92
|
+
if (expectedVersion !== null && typeof expectedVersion !== 'string')
|
|
93
|
+
invalid('保存需要已读取的文件版本');
|
|
94
|
+
const saved = await this.workspace.write({
|
|
95
|
+
file: this.file(parsed.id),
|
|
96
|
+
expectedVersion,
|
|
97
|
+
text: YAML.stringify(parsed),
|
|
98
|
+
});
|
|
99
|
+
return { ...parsed, version: saved.version };
|
|
100
|
+
}
|
|
101
|
+
async remove({ id, expectedVersion }) {
|
|
102
|
+
if (typeof expectedVersion !== 'string')
|
|
103
|
+
invalid('删除需要已读取的文件版本');
|
|
104
|
+
await this.workspace.remove({ file: this.file(id), expectedVersion });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare function authorConnection(root: string, execute?: boolean, env?: NodeJS.ProcessEnv, readOnly?: boolean, contextFile?: string, published?: boolean): {
|
|
2
|
+
mcpServers: {
|
|
3
|
+
arcadia: {
|
|
4
|
+
command: string;
|
|
5
|
+
args: string[];
|
|
6
|
+
env: {
|
|
7
|
+
ELECTRON_RUN_AS_NODE: string;
|
|
8
|
+
ARCADIA_NPM_CLI?: string | undefined;
|
|
9
|
+
ARCADIA_PREVIEW_CLIENT_URL?: string | undefined;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
/** Connect bundled tools only when absent. Never replace a project's existing dependencies. */
|
|
15
|
+
export declare function connectDevelopmentSdk(root: string): Promise<{
|
|
16
|
+
linked: string[];
|
|
17
|
+
}>;
|
|
18
|
+
export declare function createSourceProject(directory: string, identity: string): Promise<string>;
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { cp, lstat, mkdir, readFile, realpath, readdir, symlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { WorkspaceError } from './workspace.js';
|
|
6
|
+
import { siblingModulePath } from './module-path.js';
|
|
7
|
+
import { errorCode } from './types.js';
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
const moduleRoot = fileURLToPath(new URL('../', import.meta.url));
|
|
10
|
+
export function authorConnection(root, execute = false, env = process.env, readOnly = false, contextFile, published = false) {
|
|
11
|
+
return {
|
|
12
|
+
mcpServers: {
|
|
13
|
+
arcadia: {
|
|
14
|
+
command: process.execPath,
|
|
15
|
+
args: [
|
|
16
|
+
siblingModulePath('mcp'),
|
|
17
|
+
root,
|
|
18
|
+
...(readOnly ? ['--read-only'] : execute ? ['--execute'] : []),
|
|
19
|
+
...(contextFile ? ['--context-file', contextFile] : []),
|
|
20
|
+
...(published ? ['--published'] : []),
|
|
21
|
+
],
|
|
22
|
+
env: {
|
|
23
|
+
ELECTRON_RUN_AS_NODE: '1',
|
|
24
|
+
...(env.ARCADIA_NPM_CLI ? { ARCADIA_NPM_CLI: env.ARCADIA_NPM_CLI } : {}),
|
|
25
|
+
...(env.ARCADIA_PREVIEW_CLIENT_URL ? { ARCADIA_PREVIEW_CLIENT_URL: env.ARCADIA_PREVIEW_CLIENT_URL } : {}),
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
async function packageRoot(names, entry) {
|
|
32
|
+
if (!Array.isArray(names))
|
|
33
|
+
names = [names];
|
|
34
|
+
let path = dirname(require.resolve(entry));
|
|
35
|
+
for (;;) {
|
|
36
|
+
try {
|
|
37
|
+
if (names.includes(JSON.parse(await readFile(join(path, 'package.json'), 'utf8')).name))
|
|
38
|
+
return realpath(path);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
/* Walk to owning package. */
|
|
42
|
+
}
|
|
43
|
+
const parent = dirname(path);
|
|
44
|
+
if (parent === path)
|
|
45
|
+
throw new Error(`Cannot find SDK package ${names.join(' or ')}`);
|
|
46
|
+
path = parent;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Connect bundled tools only when absent. Never replace a project's existing dependencies. */
|
|
50
|
+
export async function connectDevelopmentSdk(root) {
|
|
51
|
+
root = await realpath(root);
|
|
52
|
+
// Existing dependency directories must not redirect writes outside this project.
|
|
53
|
+
async function directory(parts) {
|
|
54
|
+
let current = root;
|
|
55
|
+
for (const part of parts) {
|
|
56
|
+
current = join(current, part);
|
|
57
|
+
try {
|
|
58
|
+
await mkdir(current);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (errorCode(error) !== 'EEXIST')
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
const info = await lstat(current);
|
|
65
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
66
|
+
throw new WorkspaceError('PATH_INVALID', 'SDK 目录必须是项目内普通目录', current);
|
|
67
|
+
}
|
|
68
|
+
return current;
|
|
69
|
+
}
|
|
70
|
+
// Validate all parents before adding any links.
|
|
71
|
+
await directory(['node_modules']);
|
|
72
|
+
await directory(['node_modules', '@arcadia-eternity']);
|
|
73
|
+
await directory(['node_modules', '.bin']);
|
|
74
|
+
const packages = {
|
|
75
|
+
'@arcadia-eternity/battle': await packageRoot('@arcadia-eternity/battle', '@arcadia-eternity/battle/engine'),
|
|
76
|
+
'@arcadia-eternity/pack-loader': await packageRoot('@arcadia-eternity/pack-loader', '@arcadia-eternity/pack-loader/node'),
|
|
77
|
+
'@arcadia-eternity/content-sdk': moduleRoot,
|
|
78
|
+
typescript: await packageRoot(['typescript', 'typescript-native-bridge'], 'typescript'),
|
|
79
|
+
};
|
|
80
|
+
const linked = [];
|
|
81
|
+
for (const [name, source] of Object.entries(packages)) {
|
|
82
|
+
const target = join(root, 'node_modules', name);
|
|
83
|
+
await directory(['node_modules', ...name.split('/').slice(0, -1)]);
|
|
84
|
+
try {
|
|
85
|
+
await lstat(target);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (errorCode(error) !== 'ENOENT')
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir');
|
|
93
|
+
linked.push(name);
|
|
94
|
+
}
|
|
95
|
+
// npm scripts use the shared CLI, while the desktop invokes its absolute entry directly.
|
|
96
|
+
const bin = join(root, 'node_modules/.bin');
|
|
97
|
+
await directory(['node_modules', '.bin']);
|
|
98
|
+
for (const [name, entry] of [
|
|
99
|
+
['arcadia-content', 'cli'],
|
|
100
|
+
['arcadia-content-mcp', 'mcp'],
|
|
101
|
+
]) {
|
|
102
|
+
const script = siblingModulePath(entry);
|
|
103
|
+
if (process.platform === 'win32')
|
|
104
|
+
await writeFile(join(bin, name + '.cmd'), `@echo off\r\nnode "${script}" %*\r\n`, { flag: 'wx' }).catch(e => {
|
|
105
|
+
if (errorCode(e) !== 'EEXIST')
|
|
106
|
+
throw e;
|
|
107
|
+
});
|
|
108
|
+
else
|
|
109
|
+
await symlink(script, join(bin, name)).catch(e => {
|
|
110
|
+
if (errorCode(e) !== 'EEXIST')
|
|
111
|
+
throw e;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
return { linked };
|
|
115
|
+
}
|
|
116
|
+
export async function createSourceProject(directory, identity) {
|
|
117
|
+
if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(identity))
|
|
118
|
+
throw new WorkspaceError('PROJECT_INVALID', '项目 ID 无效');
|
|
119
|
+
await mkdir(directory); // No overwrite or merge with existing directories.
|
|
120
|
+
let template = fileURLToPath(new URL('./template/', import.meta.url));
|
|
121
|
+
try {
|
|
122
|
+
await lstat(template);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
template = fileURLToPath(new URL('../template/', import.meta.url));
|
|
126
|
+
}
|
|
127
|
+
for (const entry of await readdir(template))
|
|
128
|
+
await cp(join(template, entry), join(directory, entry), { recursive: true, force: false, errorOnExist: true });
|
|
129
|
+
async function renameText(root) {
|
|
130
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
131
|
+
const file = join(root, entry.name);
|
|
132
|
+
if (entry.isDirectory())
|
|
133
|
+
await renameText(file);
|
|
134
|
+
else if (/\.(json|ya?ml|mjs|ts|md)$/.test(entry.name)) {
|
|
135
|
+
const text = await readFile(file, 'utf8');
|
|
136
|
+
await writeFile(file, text.replaceAll('example-content-pack', identity).replaceAll('example-pack', identity));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
await renameText(directory);
|
|
141
|
+
const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
|
|
142
|
+
manifest.name = `@arcadia-local/${identity}`;
|
|
143
|
+
await writeFile(join(directory, 'package.json'), JSON.stringify(manifest, null, 2) + '\n');
|
|
144
|
+
await connectDevelopmentSdk(directory);
|
|
145
|
+
return directory;
|
|
146
|
+
}
|
package/dist/rename.d.ts
ADDED
package/dist/rename.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import YAML from 'yaml';
|
|
5
|
+
import { AuthorWorkspace } from './workspace.js';
|
|
6
|
+
import { teamDocument } from './project-teams.js';
|
|
7
|
+
import { readContentSources } from './lib/content.js';
|
|
8
|
+
import { isRecord } from './types.js';
|
|
9
|
+
const args = process.argv.slice(2);
|
|
10
|
+
if (args.includes('--help')) {
|
|
11
|
+
console.log('arcadia-content rename --name @your-scope/my-pack --project-id my-pack --namespace my-pack');
|
|
12
|
+
process.exit(0);
|
|
13
|
+
}
|
|
14
|
+
const options = {};
|
|
15
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
16
|
+
const option = args[i];
|
|
17
|
+
if (!['--name', '--project-id', '--namespace'].includes(option) ||
|
|
18
|
+
options[option] ||
|
|
19
|
+
!args[i + 1] ||
|
|
20
|
+
args[i + 1].startsWith('--'))
|
|
21
|
+
throw new Error(`Unknown, duplicate or incomplete option: ${args[i]}`);
|
|
22
|
+
options[option] = args[i + 1];
|
|
23
|
+
}
|
|
24
|
+
const name = options['--name'] ?? '';
|
|
25
|
+
const projectId = options['--project-id'] ?? '';
|
|
26
|
+
const newNamespace = options['--namespace'] ?? '';
|
|
27
|
+
if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/.test(name) || name.length > 214)
|
|
28
|
+
throw new Error('Provide a lowercase npm package name.');
|
|
29
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/.test(projectId) || ['base', 'constructor', 'prototype'].includes(projectId))
|
|
30
|
+
throw new Error('Provide a non-reserved project ID (1–80 letters, digits, dots, underscores or hyphens).');
|
|
31
|
+
if (!/^[a-z0-9][a-z0-9_.-]{0,79}$/.test(newNamespace) || newNamespace === 'base')
|
|
32
|
+
throw new Error('Provide a non-reserved lowercase namespace (1–80 characters).');
|
|
33
|
+
const root = resolve('.');
|
|
34
|
+
const packagePath = resolve('package.json');
|
|
35
|
+
const manifest = JSON.parse(await readFile(packagePath, 'utf8'));
|
|
36
|
+
const oldId = manifest.arcadia.projectId;
|
|
37
|
+
const oldNamespace = manifest.arcadia.namespace;
|
|
38
|
+
const sources = await readContentSources(root);
|
|
39
|
+
const workspace = await AuthorWorkspace.open(root, { watch: false });
|
|
40
|
+
for (const { file } of await workspace.files()) {
|
|
41
|
+
if (!/^debug\/teams\/[^/]+\.yaml$/.test(file))
|
|
42
|
+
continue;
|
|
43
|
+
const source = await workspace.read(file);
|
|
44
|
+
const document = YAML.parseDocument(source.text);
|
|
45
|
+
if (document.errors.length)
|
|
46
|
+
throw document.errors[0];
|
|
47
|
+
teamDocument(document.toJS());
|
|
48
|
+
sources.push({ kind: 'project-team', file, document, version: source.version, relative: file });
|
|
49
|
+
}
|
|
50
|
+
function rewrite(value) {
|
|
51
|
+
if (Array.isArray(value))
|
|
52
|
+
return value.map(rewrite);
|
|
53
|
+
if (!value || typeof value !== 'object')
|
|
54
|
+
return value;
|
|
55
|
+
const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]));
|
|
56
|
+
const reference = result.$ref;
|
|
57
|
+
if (isRecord(reference) && reference.projectId === oldId)
|
|
58
|
+
reference.projectId = projectId;
|
|
59
|
+
if (result.namespace === oldNamespace &&
|
|
60
|
+
typeof result.id === 'string' &&
|
|
61
|
+
Object.keys(result).every(key => ['namespace', 'id'].includes(key)))
|
|
62
|
+
result.namespace = newNamespace;
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
manifest.name = name;
|
|
66
|
+
manifest.arcadia.projectId = projectId;
|
|
67
|
+
manifest.arcadia.namespace = newNamespace;
|
|
68
|
+
const changes = sources.map(source => {
|
|
69
|
+
if (!source.document)
|
|
70
|
+
return { file: source.file, text: JSON.stringify(rewrite(source.value), null, 2) + '\n' };
|
|
71
|
+
const document = source.document;
|
|
72
|
+
// Detach alias uses before editing: an anchor may also supply an unrelated content ID.
|
|
73
|
+
const aliases = new Map();
|
|
74
|
+
YAML.visit(document, {
|
|
75
|
+
Alias(_key, alias) {
|
|
76
|
+
const replacement = document.createNode(alias.toJS(document), {
|
|
77
|
+
aliasDuplicateObjects: false,
|
|
78
|
+
});
|
|
79
|
+
replacement.comment = alias.comment;
|
|
80
|
+
replacement.commentBefore = alias.commentBefore;
|
|
81
|
+
aliases.set(alias, replacement);
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
YAML.visit(document, {
|
|
85
|
+
Alias: (_key, alias) => {
|
|
86
|
+
const replacement = aliases.get(alias);
|
|
87
|
+
if (replacement)
|
|
88
|
+
return replacement;
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
YAML.visit(document, {
|
|
92
|
+
Map(_key, node) {
|
|
93
|
+
if (source.kind === 'project-team') {
|
|
94
|
+
const update = (value) => {
|
|
95
|
+
if (YAML.isScalar(value) && typeof value.value === 'string' && value.value.startsWith(`${oldNamespace}:`))
|
|
96
|
+
value.value = newNamespace + value.value.slice((oldNamespace ?? '').length);
|
|
97
|
+
};
|
|
98
|
+
for (const key of ['species', 'ability', 'emblem'])
|
|
99
|
+
update(node.get(key, true));
|
|
100
|
+
const skills = node.get('skills', true);
|
|
101
|
+
if (YAML.isSeq(skills))
|
|
102
|
+
skills.items.forEach(update);
|
|
103
|
+
}
|
|
104
|
+
const namespaceNode = node.get('namespace', true);
|
|
105
|
+
if (YAML.isScalar(namespaceNode) &&
|
|
106
|
+
namespaceNode.value === oldNamespace &&
|
|
107
|
+
node.has('id') &&
|
|
108
|
+
node.items.length === 2)
|
|
109
|
+
namespaceNode.value = newNamespace;
|
|
110
|
+
const reference = node.get('$ref', true);
|
|
111
|
+
if (!YAML.isMap(reference))
|
|
112
|
+
return;
|
|
113
|
+
const project = reference.get('projectId', true);
|
|
114
|
+
if (YAML.isScalar(project) && project.value === oldId)
|
|
115
|
+
project.value = projectId;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
return { file: source.file, text: String(document), version: source.version, relative: source.relative };
|
|
119
|
+
});
|
|
120
|
+
await writeFile(packagePath, JSON.stringify(manifest, null, 2) + '\n');
|
|
121
|
+
for (const change of changes) {
|
|
122
|
+
if (change.relative && change.version)
|
|
123
|
+
await workspace.write({ file: change.relative, expectedVersion: change.version, text: change.text });
|
|
124
|
+
else
|
|
125
|
+
await writeFile(change.file, change.text);
|
|
126
|
+
}
|
|
127
|
+
await workspace.close();
|
|
128
|
+
console.log(`Renamed to ${manifest.name}. Update repository metadata before publishing. Keep projectId and namespace stable after sharing.`);
|
package/dist/setup.d.ts
ADDED
package/dist/setup.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn, execFileSync } from 'node:child_process';
|
|
3
|
+
import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { basename, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { errorMessage } from './types.js';
|
|
7
|
+
export async function setup(args = process.argv.slice(2), root = process.cwd()) {
|
|
8
|
+
root = resolve(root);
|
|
9
|
+
const options = { offline: false };
|
|
10
|
+
for (let i = 0; i < args.length; i++) {
|
|
11
|
+
const arg = args[i];
|
|
12
|
+
if (arg === '--help') {
|
|
13
|
+
console.log('arcadia-content setup [--sdk-dir /path/to/sdk] [--offline]');
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (arg === '--offline' && !options.offline)
|
|
17
|
+
options.offline = true;
|
|
18
|
+
else if (arg === '--sdk-dir' && !options.sdkDir && args[i + 1] && !args[i + 1].startsWith('--'))
|
|
19
|
+
options.sdkDir = resolve(args[++i]);
|
|
20
|
+
else
|
|
21
|
+
throw new Error(`Unknown, duplicate or incomplete option: ${arg}`);
|
|
22
|
+
}
|
|
23
|
+
const pin = JSON.parse(await readFile(join(root, 'arcadia-sdk.json'), 'utf8'));
|
|
24
|
+
if (!/^[a-f0-9]{40}$/.test(pin.revision) || !/^\d+\.\d+\.\d+$/.test(pin.pnpmVersion) || pin.sdkApi !== 2)
|
|
25
|
+
throw new Error('Invalid SDK pin in arcadia-sdk.json');
|
|
26
|
+
if (process.platform === 'win32' || Number(process.versions.node.split('.')[0]) !== 24)
|
|
27
|
+
throw new Error('This development SDK currently supports Node.js 24 on Linux or macOS.');
|
|
28
|
+
const env = {
|
|
29
|
+
...process.env,
|
|
30
|
+
pnpm_config_verify_deps_before_run: 'false',
|
|
31
|
+
ELECTRON_SKIP_BINARY_DOWNLOAD: '1',
|
|
32
|
+
};
|
|
33
|
+
function run(command, args, cwd = root) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
const child = spawn(command, args, { cwd, env, stdio: 'inherit' });
|
|
36
|
+
child.on('error', reject);
|
|
37
|
+
child.on('exit', code => (code === 0 ? resolve() : reject(new Error(`${command} exited with ${code}`))));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
41
|
+
const state = join(root, '.arcadia');
|
|
42
|
+
await mkdir(state, { recursive: true });
|
|
43
|
+
const sdkDirectory = options.sdkDir ?? join(state, `sdk-${pin.revision}`);
|
|
44
|
+
try {
|
|
45
|
+
if (!options.sdkDir && !(await exists(join(sdkDirectory, 'arcadia-author-sdk.json')))) {
|
|
46
|
+
if (options.offline)
|
|
47
|
+
throw new Error('Prepare an SDK first, or supply --sdk-dir for offline setup.');
|
|
48
|
+
const source = join(state, `source-${pin.revision}`);
|
|
49
|
+
if (!(await exists(source))) {
|
|
50
|
+
await mkdir(source);
|
|
51
|
+
await run('git', ['init', '--quiet', '--initial-branch=main'], source);
|
|
52
|
+
await run('git', ['remote', 'add', 'origin', pin.repository], source);
|
|
53
|
+
}
|
|
54
|
+
await run('git', ['fetch', '--depth=1', 'origin', pin.revision], source);
|
|
55
|
+
await run('git', ['checkout', '--detach', pin.revision], source);
|
|
56
|
+
const head = execFileSync('git', ['rev-parse', 'HEAD'], {
|
|
57
|
+
cwd: source,
|
|
58
|
+
encoding: 'utf8',
|
|
59
|
+
}).trim();
|
|
60
|
+
const changes = execFileSync('git', ['status', '--porcelain'], {
|
|
61
|
+
cwd: source,
|
|
62
|
+
encoding: 'utf8',
|
|
63
|
+
}).trim();
|
|
64
|
+
if (head !== pin.revision || changes)
|
|
65
|
+
throw new Error('The cached SDK source must match the pinned revision without local changes.');
|
|
66
|
+
const pnpm = (args) => run('npx', ['--yes', `--package=pnpm@${pin.pnpmVersion}`, 'pnpm', ...args], source);
|
|
67
|
+
await pnpm(['install', '--frozen-lockfile', '--ignore-scripts']);
|
|
68
|
+
await pnpm(['--filter', './packages/content-dev...', '--filter', '@arcadia-eternity/protocol...', 'run', 'build']);
|
|
69
|
+
await run(process.execPath, ['scripts/stage-author-sdk.mjs', sdkDirectory], source);
|
|
70
|
+
}
|
|
71
|
+
const index = JSON.parse(await readFile(join(sdkDirectory, 'arcadia-author-sdk.json'), 'utf8'));
|
|
72
|
+
if (index.format !== 'arcadia.author-sdk-local' ||
|
|
73
|
+
index.version !== 1 ||
|
|
74
|
+
index.sdkApi !== pin.sdkApi ||
|
|
75
|
+
index.build?.formatVersion !== 1 ||
|
|
76
|
+
![index.build.coreBuildId, index.build.registryBuildId].every(id => /^[a-f0-9]{64}$/.test(id)))
|
|
77
|
+
throw new Error('SDK manifest format, API or build identity does not match this template.');
|
|
78
|
+
const required = new Set(['battle', 'const', 'interface', 'pack-loader', 'protocol', 'schema', 'content-sdk'].map(name => `@arcadia-eternity/${name}`));
|
|
79
|
+
const archives = [];
|
|
80
|
+
for (const pkg of index.packages) {
|
|
81
|
+
if (!required.delete(pkg.name) || basename(pkg.filename) !== pkg.filename || !pkg.filename.endsWith('.tgz'))
|
|
82
|
+
throw new Error(`Unexpected or duplicated SDK archive: ${pkg.name}`);
|
|
83
|
+
const file = join(sdkDirectory, pkg.filename);
|
|
84
|
+
archives.push(file);
|
|
85
|
+
}
|
|
86
|
+
if (required.size)
|
|
87
|
+
throw new Error(`Missing SDK packages: ${[...required].join(', ')}`);
|
|
88
|
+
await run('npm', [
|
|
89
|
+
'install',
|
|
90
|
+
'--ignore-scripts',
|
|
91
|
+
'--no-save',
|
|
92
|
+
'--no-package-lock',
|
|
93
|
+
'--no-audit',
|
|
94
|
+
'--no-fund',
|
|
95
|
+
...(options.offline ? ['--offline'] : []),
|
|
96
|
+
...archives,
|
|
97
|
+
]);
|
|
98
|
+
await writeFile(join(state, 'sdk-installed.json'), JSON.stringify({
|
|
99
|
+
sdkApi: index.sdkApi,
|
|
100
|
+
source: options.sdkDir ? 'provided-sdk' : pin.repository,
|
|
101
|
+
revision: options.sdkDir ? null : pin.revision,
|
|
102
|
+
build: index.build,
|
|
103
|
+
}, null, 2) + '\n');
|
|
104
|
+
console.log('SDK installed. Run npm test, npm run demo, or npm run pack.');
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
throw new Error(`SDK setup failed: ${errorMessage(error)}`, { cause: error });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (process.argv[1] &&
|
|
111
|
+
!import.meta.url.startsWith('data:') &&
|
|
112
|
+
resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
113
|
+
setup().catch(error => {
|
|
114
|
+
console.error(errorMessage(error));
|
|
115
|
+
process.exitCode = 1;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Serialize each source write across cooperating local author processes in this project.
|
|
2
|
+
* One project lock also covers filename aliases on case-insensitive filesystems.
|
|
3
|
+
* Each file still commits separately; ordinary external editors still use CAS checks.
|
|
4
|
+
* Lamport's bakery ordering avoids stealing a live owner's lock after a timeout.
|
|
5
|
+
* Claims live outside source revisions. PID reuse can delay recovery, never bypass a live owner.
|
|
6
|
+
*/
|
|
7
|
+
export declare function withSourceLock<T>(root: string, file: string, action: () => Promise<T>, { timeoutMs }?: {
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
}): Promise<T>;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, readFile, readdir, realpath, unlink } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import writeFileAtomic from 'write-file-atomic';
|
|
6
|
+
import { errorCode } from './types.js';
|
|
7
|
+
const claimName = /^([1-9][0-9]*)-([a-f0-9-]{36})\.json$/;
|
|
8
|
+
const busy = (file) => Object.assign(new Error('其他作者操作正在保存此项目,请稍后重试'), { code: 'SOURCE_BUSY', file });
|
|
9
|
+
const invalid = (file) => Object.assign(new Error('作者保存协调目录必须是普通目录'), { code: 'PATH_INVALID', file });
|
|
10
|
+
async function directory(root, file) {
|
|
11
|
+
if ((await realpath(root)) !== root)
|
|
12
|
+
throw invalid(file);
|
|
13
|
+
let path = root;
|
|
14
|
+
for (const part of ['.arcadia', 'author-locks']) {
|
|
15
|
+
path = join(path, part);
|
|
16
|
+
try {
|
|
17
|
+
await mkdir(path, { mode: 0o700 });
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (errorCode(error) !== 'EEXIST')
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
const info = await lstat(path);
|
|
24
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
25
|
+
throw invalid(file);
|
|
26
|
+
}
|
|
27
|
+
return path;
|
|
28
|
+
}
|
|
29
|
+
async function claims(path, file) {
|
|
30
|
+
const names = (await readdir(path)).filter(name => claimName.test(name));
|
|
31
|
+
if (names.length > 1024)
|
|
32
|
+
throw busy(file);
|
|
33
|
+
const result = [];
|
|
34
|
+
for (const name of names) {
|
|
35
|
+
const match = claimName.exec(name);
|
|
36
|
+
const pid = Number(match?.[1]);
|
|
37
|
+
if (!Number.isSafeInteger(pid))
|
|
38
|
+
throw busy(file);
|
|
39
|
+
const claim = join(path, name);
|
|
40
|
+
try {
|
|
41
|
+
// Each attempt has a fresh UUID. Removing a dead process's claim cannot
|
|
42
|
+
// remove a replacement owner's claim, unlike reclaiming one shared lock.
|
|
43
|
+
try {
|
|
44
|
+
process.kill(pid, 0);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (errorCode(error) === 'ESRCH') {
|
|
48
|
+
await unlink(claim);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (errorCode(error) !== 'EPERM')
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
const info = await lstat(claim);
|
|
55
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 1024)
|
|
56
|
+
throw invalid(file);
|
|
57
|
+
let ticket = null;
|
|
58
|
+
try {
|
|
59
|
+
const value = JSON.parse(await readFile(claim, 'utf8'));
|
|
60
|
+
if (typeof value.ticket === 'string' && /^[1-9][0-9]{0,99}$/.test(value.ticket))
|
|
61
|
+
ticket = BigInt(value.ticket);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
// An initial exclusive write may be visible before its bytes arrive.
|
|
65
|
+
// Treat an incomplete live claim as choosing, never as unlocked.
|
|
66
|
+
if (!(error instanceof SyntaxError))
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
result.push({ name, ticket });
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (errorCode(error) !== 'ENOENT')
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
/** Serialize each source write across cooperating local author processes in this project.
|
|
79
|
+
* One project lock also covers filename aliases on case-insensitive filesystems.
|
|
80
|
+
* Each file still commits separately; ordinary external editors still use CAS checks.
|
|
81
|
+
* Lamport's bakery ordering avoids stealing a live owner's lock after a timeout.
|
|
82
|
+
* Claims live outside source revisions. PID reuse can delay recovery, never bypass a live owner.
|
|
83
|
+
*/
|
|
84
|
+
export async function withSourceLock(root, file, action, { timeoutMs = 5000 } = {}) {
|
|
85
|
+
const path = await directory(root, file);
|
|
86
|
+
const name = `${process.pid}-${randomUUID()}.json`;
|
|
87
|
+
const claim = join(path, name);
|
|
88
|
+
const deadline = Date.now() + timeoutMs;
|
|
89
|
+
const handle = await open(claim, 'wx', 0o600);
|
|
90
|
+
try {
|
|
91
|
+
try {
|
|
92
|
+
await handle.writeFile(JSON.stringify({ ticket: null }));
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await handle.close();
|
|
96
|
+
}
|
|
97
|
+
const current = await claims(path, file);
|
|
98
|
+
const ticket = current.reduce((highest, entry) => (entry.ticket !== null && entry.ticket > highest ? entry.ticket : highest), 0n) + 1n;
|
|
99
|
+
await writeFileAtomic(claim, JSON.stringify({ ticket: ticket.toString() }), { mode: 0o600 });
|
|
100
|
+
for (;;) {
|
|
101
|
+
const contenders = await claims(path, file);
|
|
102
|
+
const blocked = contenders.some(entry => entry.name !== name &&
|
|
103
|
+
(entry.ticket === null || entry.ticket < ticket || (entry.ticket === ticket && entry.name < name)));
|
|
104
|
+
if (!blocked)
|
|
105
|
+
return await action();
|
|
106
|
+
if (Date.now() >= deadline)
|
|
107
|
+
throw busy(file);
|
|
108
|
+
await delay(20);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
await unlink(claim).catch(error => {
|
|
113
|
+
if (errorCode(error) !== 'ENOENT')
|
|
114
|
+
throw error;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
package/dist/template/README.md
CHANGED
|
@@ -12,6 +12,8 @@ SDK 构建模板携带 `skills/arcadia-content-authoring/SKILL.md` 和 `skills/s
|
|
|
12
12
|
|
|
13
13
|
表现关联位于 `data/presentations/main.yaml`,资源定义位于 `data/resources/main.yaml`。规则只描述游戏内容,表现通过对象 ID 关联,图片与声音使用稳定资源 ID。移动素材时只更新资源定义的 `source`。见 [表现说明](docs/presentation.md)。
|
|
14
14
|
|
|
15
|
+
`data/`、`locales/` 和 `src/` 只用于源项目创作。`npm run pack` 发布的归档只包含 `dist/`、被表现清单引用的素材及包元数据;安装后的包为只读,修改内容需要回到本项目重新构建并发布新版本。
|
|
16
|
+
|
|
15
17
|
## 依赖内容包
|
|
16
18
|
|
|
17
19
|
复用其他包的技能、印记或资源时,将其声明为 `package.json` 的运行依赖(`dependencies`),并使用已安装版本支持的引用格式。`npm test` 使用标准助手,通过 npm 安装候选及其依赖,再由共享加载器组装环境;不需要另写依赖加载器。官方 base 同样必须是运行依赖,且使用包含静态适配产物的构建版本。不要把开发目录中的 `file:../sdk/*.tgz` 当成可分发的依赖地址。
|