@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,12 +1,12 @@
1
1
  # 形象、声音与多语言
2
2
 
3
- 本包采用分离的表现格式 v2。精灵、技能和印记规则保存在 `data/species`、`data/skills`、`data/marks`;表现关联保存在 `data/presentations`;资源身份和位置保存在 `data/resources`。素材仍可与规则放在同一个 npm 包里。
3
+ 本包采用分离的表现格式 v2。精灵、技能和印记规则保存在 `data/species`、`data/skills`、`data/marks`;表现关联保存在 `data/presentations`;资源身份和位置保存在 `data/resources`。这些 YAML 是源项目输入,不进入 npm 发行包;发行包包含编译后的规则、表现清单和被引用的素材。
4
4
 
5
5
  以 `data/presentations/main.yaml` 和 `data/resources/main.yaml` 为例:表现的 `target` 指向本包内容,`icon`、`portrait`、`battle.source`、`sfx` 等字段引用资源 ID。资源记录的 `source` 才填写包根目录相对路径或 HTTP(S) URL。跨包素材写 `{namespace: other-pack, id: shared-icon}`,并声明对应 npm 依赖。
6
6
 
7
7
  资源 ID 应保持稳定。移动素材后更新资源记录的 `source`,对象关联不变;移动定义文件不会改变 ID。不要通过改 ID 修复路径。工作台会保留缺失引用并提示重新定位。
8
8
 
9
- 默认把素材放在 `assets/`;允许其他包内普通目录,但必须加入 `package.json.files`。不允许符号链接或路径穿越。`kind` 为 image、audio、swf;战斗 `renderer` 明确为 image 或 seer2-swf。图片与音频用途不能混用。
9
+ 默认把素材放在 `assets/`;也可使用包内其他普通目录,但必须加入 `package.json.files` 并由表现资源定义引用,发布工具只复制实际引用的素材。不允许符号链接或路径穿越。`kind` 为 image、audio、swf;战斗 `renderer` 明确为 image 或 seer2-swf。图片与音频用途不能混用。
10
10
 
11
11
  名称与 ICU 描述继续放在 `locales/<language>/<namespace>.yaml`,使用相同内容 ID。工作台把规则、资源和多语言组合为对象页面;外部 AI 应分别编辑对应源记录。
12
12
 
@@ -18,4 +18,4 @@
18
18
 
19
19
  `npm run build` 生成 `dist/content.json` 和 `dist/presentation.json`。前者只有规则,后者包含表现关联、资源索引与语言。不要编辑生成物。HTTP 地址不会在构建或安装时下载;包内素材会记录哈希和大小。旧的内嵌 presentation、assets.json 映射不再支持。
20
20
 
21
- 修改后运行 `npm test` 和 `npm run pack`。发布前确保 SDK 与表现格式 v2 匹配。
21
+ 修改后运行 `npm test` 和 `npm run pack`。发布前确保 SDK 与表现格式 v2 匹配。安装后的内容包只读;不要直接编辑已安装目录,应回到源项目修改并发布新版本。
@@ -4,12 +4,8 @@
4
4
  "type": "module",
5
5
  "private": true,
6
6
  "files": [
7
- "data",
8
7
  "dist",
9
- "src",
10
- "assets",
11
- "locales",
12
- "docs"
8
+ "assets"
13
9
  ],
14
10
  "scripts": {
15
11
  "rename": "arcadia-content rename",
@@ -23,9 +19,9 @@
23
19
  "mcp": "arcadia-content-mcp ."
24
20
  },
25
21
  "devDependencies": {
26
- "@types/node": "25.6.0",
22
+ "@types/node": "26.6.6",
27
23
  "typescript": "6.0.3",
28
- "@arcadia-eternity/content-sdk": "4.3.3"
24
+ "@arcadia-eternity/content-sdk": "4.4.0"
29
25
  },
30
26
  "arcadia": {
31
27
  "formatVersion": 1,
@@ -27,8 +27,13 @@ before(
27
27
  } finally {
28
28
  globalThis.fetch = fetch
29
29
  }
30
- assert.ok(example.files.some(file => file.startsWith('data/species/')))
31
- assert.ok(!example.files.includes('content.json'))
30
+ assert.ok(example.files.includes('dist/content.json'))
31
+ assert.ok(example.files.includes('dist/presentation.json'))
32
+ assert.ok(example.files.includes('dist/arcadia-effects.json'))
33
+ assert.equal(
34
+ example.files.some(file => /^(?:data|locales|src|docs)\//.test(file)),
35
+ false,
36
+ )
32
37
  },
33
38
  { timeout: 60000 },
34
39
  )
@@ -36,17 +41,15 @@ after(async () => {
36
41
  await example?.dispose()
37
42
  })
38
43
 
39
- test('the installed package includes local artwork, remote declarations and both languages', () => {
44
+ test('the installed package includes compiled content, local artwork, remote declarations and both languages', () => {
40
45
  for (const file of [
46
+ 'dist/content.json',
41
47
  'dist/presentation.json',
42
- 'docs/presentation.md',
48
+ 'dist/arcadia-effects.json',
43
49
  'assets/pets/frostling-icon.png',
44
50
  'assets/pets/frostling-portrait.png',
45
51
  'assets/pets/frostling-battle.png',
46
52
  'assets/marks/slow.png',
47
- ...['zh-CN', 'en'].flatMap(language =>
48
- ['species', 'skill', 'mark'].map(kind => `locales/${language}/${kind}.yaml`),
49
- ),
50
53
  ])
51
54
  assert.ok(example.files.includes(file), `Missing packaged file: ${file}`)
52
55
  const presentation = example.environment.presentation.find(
@@ -0,0 +1,58 @@
1
+ import { prepareBattleEnvironment } from './environment.js';
2
+ import { playersFromTeams } from './project-teams.js';
3
+ import { type SandboxContent } from '@arcadia-eternity/battle/sandbox/effects';
4
+ import type { Battle } from '@arcadia-eternity/battle/engine';
5
+ export { prepareBattleEnvironment } from './environment.js';
6
+ import { UseSkillContext } from '@arcadia-eternity/battle/engine';
7
+ export { AttackTargetOpinion, EffectContext, EffectTrigger, RemoveMarkContext, parameterAddress, setGlobalLogger, } from '@arcadia-eternity/battle/engine';
8
+ /** Existing package scenarios use the default environment with declared dependencies only. */
9
+ export declare function prepareContentPack(root?: string, options?: NonNullable<Parameters<typeof prepareBattleEnvironment>[1]>): Promise<{
10
+ environment: Readonly<import("@arcadia-eternity/pack-loader/node").PreparedNpmEnvironment>;
11
+ environmentDocument: import("./debug-environments.js").EnvironmentDocumentV2;
12
+ candidate: import("./environment.js").ContentCandidate;
13
+ environmentLock: {
14
+ file: string;
15
+ version: string;
16
+ } | undefined;
17
+ sourceRevisions: Record<string, string>;
18
+ loadTeams(ids: string[]): ReturnType<typeof playersFromTeams>;
19
+ teams: import("./project-teams.js").ProjectTeam[];
20
+ teamVersions: Record<string, string | null>;
21
+ manifest: import("./workspace.js").PackageManifest & {
22
+ arcadia: import("./workspace.js").ManifestArcadia;
23
+ };
24
+ files: string[];
25
+ track(battle: import("./environment.js").BattleLike): void;
26
+ untrack(battle: import("./environment.js").BattleLike): void;
27
+ createBattle: (seed?: string, { ai, players: supplied, runtimeIds, battleOptions, }?: {
28
+ ai?: boolean;
29
+ players?: readonly unknown[];
30
+ runtimeIds?: boolean;
31
+ battleOptions?: Record<string, unknown>;
32
+ }) => Promise<Battle>;
33
+ restoreBattle: (snapshot: unknown) => Promise<Battle>;
34
+ contentFor: (battle: Battle) => SandboxContent['content'];
35
+ createBattleSession: (seed?: string, { ai, players: supplied, runtimeIds, battleOptions, }?: {
36
+ ai?: boolean;
37
+ players?: readonly unknown[];
38
+ runtimeIds?: boolean;
39
+ battleOptions?: Record<string, unknown>;
40
+ }) => Promise<import("@arcadia-eternity/battle/sandbox/node").WorkerBattleSystem>;
41
+ defaultPlayers: () => {
42
+ id: string;
43
+ name: string;
44
+ team: {
45
+ id: string;
46
+ }[];
47
+ }[];
48
+ dispose(): Promise<void>;
49
+ }>;
50
+ export declare function attack(battle: Battle): UseSkillContext;
51
+ export declare function cancelled(error: unknown): void;
52
+ export declare function nextTurn(battle: Battle): Promise<void>;
53
+ export declare function runBattle(battle: Battle, onTurn?: (battle: Battle) => void): Promise<{
54
+ winner: string | undefined;
55
+ turns: number;
56
+ hp: number[];
57
+ damage: number[];
58
+ }>;
@@ -0,0 +1,205 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import assert from 'node:assert/strict';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { join, resolve } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+ import { prepareBattleEnvironment } from './environment.js';
14
+ import { assertEnvironmentTeam, validateEnvironmentRules } from './environment-rules.js';
15
+ import { prepareSandboxContent } from '@arcadia-eternity/battle/sandbox/effects';
16
+ import { createNodeBattleWorkerManager } from '@arcadia-eternity/battle/sandbox/node';
17
+ import { isRecord } from './types.js';
18
+ export { prepareBattleEnvironment } from './environment.js';
19
+ import { AttackTargetOpinion, BattleMessageType, TurnContext, UseSkillContext } from '@arcadia-eternity/battle/engine';
20
+ export { AttackTargetOpinion, EffectContext, EffectTrigger, RemoveMarkContext, parameterAddress, setGlobalLogger, } from '@arcadia-eternity/battle/engine';
21
+ /** Existing package scenarios use the default environment with declared dependencies only. */
22
+ export async function prepareContentPack(root = process.cwd(), options = {}) {
23
+ root = resolve(root);
24
+ const { default: config } = await import(__rewriteRelativeImportExtension(pathToFileURL(join(root, 'arcadia.config.mjs')).href));
25
+ if (!isRecord(config) ||
26
+ !Array.isArray(config.teams) ||
27
+ config.teams.length !== 2 ||
28
+ config.teams.some((id) => typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(id)) ||
29
+ Object.keys(config).some(key => key !== 'teams'))
30
+ throw new Error('arcadia.config.mjs must export exactly two project team IDs in teams');
31
+ const teams = config.teams;
32
+ const prepared = await prepareBattleEnvironment(root, options);
33
+ const { environment } = prepared;
34
+ const environmentRules = validateEnvironmentRules(prepared.environmentDocument.rules);
35
+ // Four automation sessions, one human preview, and room for their validated replacements.
36
+ const workers = createNodeBattleWorkerManager({ maxBattles: 7 });
37
+ function defaultPlayers() {
38
+ return prepared.loadTeams(teams);
39
+ }
40
+ function runtimePlayers(supplied, runtimeIds = false) {
41
+ const players = (supplied ?? defaultPlayers()).map(player => ({
42
+ ...player,
43
+ id: (runtimeIds ? undefined : player.id) ?? randomBytes(16).toString('base64url').slice(0, 21),
44
+ team: player.team.map(pet => ({
45
+ ...pet,
46
+ id: runtimeIds ? randomBytes(16).toString('base64url').slice(0, 21) : pet.id,
47
+ })),
48
+ }));
49
+ for (const player of players)
50
+ assertEnvironmentTeam(environmentRules, player.team);
51
+ return players;
52
+ }
53
+ const referenceContent = new WeakMap();
54
+ function ownBattle(battle, effects) {
55
+ referenceContent.set(battle, effects.content);
56
+ const cleanup = battle.cleanup.bind(battle);
57
+ // Keep the runtime method non-enumerable, like the prototype method: only
58
+ // domain fields belong in snapshots, never this resource-owner callback.
59
+ Object.defineProperty(battle, 'cleanup', {
60
+ configurable: true,
61
+ value: async () => {
62
+ try {
63
+ await cleanup();
64
+ }
65
+ finally {
66
+ effects.dispose();
67
+ }
68
+ },
69
+ });
70
+ prepared.track(battle);
71
+ return battle;
72
+ }
73
+ /** Explicit trusted introspection entry. Every reference battle owns fresh VMs,
74
+ * just like the Worker entry; preparing an environment never evaluates effects.
75
+ */
76
+ async function createBattle(seed = 'content-pack-template', { ai = false, players: supplied, runtimeIds = false, battleOptions = {}, } = {}) {
77
+ const input = runtimePlayers(supplied, runtimeIds);
78
+ const effects = await prepareSandboxContent(environment.sandbox);
79
+ try {
80
+ const players = effects.content.parsePlayers(input, {
81
+ aiPlayerIds: ai && input[1] ? [input[1].id] : [],
82
+ });
83
+ if (players.length !== 2)
84
+ throw new Error('The demo requires exactly two players');
85
+ const ids = players.flatMap(player => [player.id, ...player.team.map(pet => pet.id)]);
86
+ if (new Set(ids).size !== ids.length)
87
+ throw new Error('玩家和精灵的编号不能重复');
88
+ return ownBattle(effects.content.createBattle(players[0], players[1], {
89
+ ...battleOptions,
90
+ rngSeed: seed,
91
+ timerConfig: battleOptions.timerConfig ?? { enabled: false },
92
+ }), effects);
93
+ }
94
+ catch (error) {
95
+ effects.dispose();
96
+ throw error;
97
+ }
98
+ }
99
+ async function restoreBattle(snapshot) {
100
+ const effects = await prepareSandboxContent(environment.sandbox);
101
+ try {
102
+ return ownBattle(effects.content.restore(snapshot), effects);
103
+ }
104
+ catch (error) {
105
+ effects.dispose();
106
+ throw error;
107
+ }
108
+ }
109
+ function contentFor(battle) {
110
+ const content = referenceContent.get(battle);
111
+ if (!content)
112
+ throw new Error('Battle does not belong to this reference helper');
113
+ return content;
114
+ }
115
+ async function createBattleSession(seed = 'content-pack-template', { ai = false, players: supplied, runtimeIds = false, battleOptions = {}, } = {}) {
116
+ const players = runtimePlayers(supplied, runtimeIds);
117
+ const system = await workers.create({
118
+ environment: environment.sandbox,
119
+ players,
120
+ aiPlayerIds: ai ? [players[1]?.id] : [],
121
+ options: { ...battleOptions, rngSeed: seed, timerConfig: battleOptions.timerConfig ?? { enabled: false } },
122
+ hostOptions: { teamSelection: battleOptions.teamSelection },
123
+ });
124
+ return system;
125
+ }
126
+ return {
127
+ ...prepared,
128
+ createBattle,
129
+ restoreBattle,
130
+ contentFor,
131
+ createBattleSession,
132
+ defaultPlayers,
133
+ async dispose() {
134
+ try {
135
+ await workers.dispose();
136
+ }
137
+ finally {
138
+ await prepared.dispose();
139
+ }
140
+ },
141
+ };
142
+ }
143
+ export function attack(battle) {
144
+ const player = battle.playerA;
145
+ const context = new UseSkillContext(new TurnContext(battle), player, player.activePet, AttackTargetOpinion.opponent, player.activePet.skills[0]);
146
+ context.updateActualTarget();
147
+ return context;
148
+ }
149
+ export function cancelled(error) {
150
+ if (!(error instanceof Error) || error.message !== 'Battle cancelled')
151
+ throw error;
152
+ }
153
+ export function nextTurn(battle) {
154
+ return new Promise((resolve, reject) => {
155
+ const timeout = setTimeout(() => {
156
+ unsubscribe();
157
+ reject(new Error('Battle did not reach its next input boundary'));
158
+ }, 10000);
159
+ const listener = (message) => {
160
+ if (message.type !== BattleMessageType.TurnAction)
161
+ return;
162
+ clearTimeout(timeout);
163
+ unsubscribe();
164
+ resolve();
165
+ };
166
+ const unsubscribe = () => battle.unregisterListener(listener);
167
+ battle.registerListener(listener);
168
+ });
169
+ }
170
+ export async function runBattle(battle, onTurn = () => { }) {
171
+ const damage = [], failures = [];
172
+ battle.registerListener((message) => {
173
+ if (message.type === BattleMessageType.Damage)
174
+ damage.push(message.data.damage);
175
+ if (message.type === BattleMessageType.Error || String(message.type) === BattleMessageType.EffectApplyFail)
176
+ failures.push(message);
177
+ if (message.type === BattleMessageType.TurnEnd)
178
+ onTurn(battle);
179
+ if (message.type !== BattleMessageType.TurnAction)
180
+ return;
181
+ for (const player of [battle.playerA, battle.playerB]) {
182
+ const selection = battle.currentTurn >= 40
183
+ ? { type: 'surrender', player: player.id }
184
+ : {
185
+ type: 'use-skill',
186
+ player: player.id,
187
+ skill: player.activePet.skills[0].id,
188
+ target: AttackTargetOpinion.opponent,
189
+ };
190
+ if (!battle.setSelection(selection))
191
+ throw new Error('Example selection rejected');
192
+ if (selection.type === 'surrender')
193
+ break;
194
+ }
195
+ });
196
+ await battle.startBattle();
197
+ assert.deepEqual(failures, [], 'the demonstration must not hide effect execution failures');
198
+ assert.ok(battle.currentTurn < 40, 'the demonstration should finish by defeating the opposing pet');
199
+ return {
200
+ winner: battle.victor?.name,
201
+ turns: battle.currentTurn,
202
+ hp: [battle.playerA, battle.playerB].map(player => player.activePet.currentHp),
203
+ damage,
204
+ };
205
+ }
@@ -0,0 +1,5 @@
1
+ /** Shared runtime-narrowing helpers for data that crosses disk, npm, and process boundaries. */
2
+ export type UnknownRecord = Record<string, unknown>;
3
+ export declare function isRecord(value: unknown): value is UnknownRecord;
4
+ export declare function errorCode(error: unknown): string | undefined;
5
+ export declare function errorMessage(error: unknown): string;
package/dist/types.js ADDED
@@ -0,0 +1,14 @@
1
+ /** Shared runtime-narrowing helpers for data that crosses disk, npm, and process boundaries. */
2
+ export function isRecord(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ export function errorCode(error) {
6
+ return isRecord(error) && typeof error.code === 'string' ? error.code : undefined;
7
+ }
8
+ export function errorMessage(error) {
9
+ if (error instanceof Error)
10
+ return error.message;
11
+ if (isRecord(error) && typeof error.message === 'string')
12
+ return error.message;
13
+ return JSON.stringify(error) ?? 'Unknown error';
14
+ }
@@ -0,0 +1,10 @@
1
+ export interface WorkbenchContext {
2
+ connected: boolean;
3
+ reason?: string;
4
+ protocol?: string;
5
+ root?: string;
6
+ updatedAt?: number;
7
+ [key: string]: unknown;
8
+ }
9
+ /** Ephemeral desktop state is context, never an edit authorization or a disk revision. */
10
+ export declare function readWorkbenchContext(file: string | undefined, root: string, now?: number): Promise<WorkbenchContext>;
@@ -0,0 +1,27 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { errorCode, isRecord } from './types.js';
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)
6
+ return { connected: false, reason: 'not-configured' };
7
+ try {
8
+ if ((await stat(file)).size > 4 * 1024 * 1024)
9
+ throw new Error('Workbench context exceeds 4 MiB');
10
+ const context = JSON.parse(await readFile(file, 'utf8'));
11
+ if (!isRecord(context))
12
+ return { connected: false, reason: 'project-mismatch' };
13
+ if (context.protocol !== 'arcadia-workbench-context/v1' || context.root !== root)
14
+ return { connected: false, reason: 'project-mismatch' };
15
+ if (typeof context.updatedAt !== 'number' ||
16
+ !Number.isFinite(context.updatedAt) ||
17
+ now - context.updatedAt > 90000 ||
18
+ context.updatedAt > now + 5000)
19
+ return { connected: false, reason: 'expired' };
20
+ return { connected: true, ...context };
21
+ }
22
+ catch (error) {
23
+ if (errorCode(error) === 'ENOENT')
24
+ return { connected: false, reason: 'workbench-closed' };
25
+ throw error;
26
+ }
27
+ }
@@ -0,0 +1 @@
1
+ export declare function workspaceCli(args: string[]): Promise<void>;
@@ -0,0 +1,66 @@
1
+ import { openAuthorSession } from './author-api.js';
2
+ import { diagnostic } from './workspace.js';
3
+ import { isRecord } from './types.js';
4
+ export async function workspaceCli(args) {
5
+ const [directory, operation = 'describe', ...flags] = args;
6
+ let execute = false, environmentId;
7
+ for (let index = 0; index < flags.length; index++) {
8
+ if (flags[index] === '--execute')
9
+ execute = true;
10
+ else if (flags[index] === '--environment' && operation === 'preview' && flags[index + 1])
11
+ environmentId = flags[++index];
12
+ else
13
+ throw new Error('Unknown workspace option; use --execute or preview --environment <id>');
14
+ }
15
+ if (!directory)
16
+ throw new Error('Usage: arcadia-content workspace <directory> <operation> [--execute] [--environment <id>]. JSON input on stdin for query/read/write/save.');
17
+ const session = await openAuthorSession(directory, { watch: false, execute });
18
+ const cancel = () => session.close();
19
+ process.once('SIGTERM', cancel);
20
+ process.once('SIGINT', cancel);
21
+ try {
22
+ let result;
23
+ if (['check', 'test', 'demo', 'preview', 'pack'].includes(operation)) {
24
+ let job = await session.jobs.start({ kind: operation, ...(environmentId ? { environmentId } : {}) });
25
+ while (['queued', 'running'].includes(job.state)) {
26
+ await new Promise(resolve => setTimeout(resolve, 100));
27
+ job = session.jobs.get(job.jobId);
28
+ }
29
+ result = job;
30
+ if (job.state !== 'succeeded' || job.stale)
31
+ 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')
39
+ process.exitCode = 1;
40
+ return;
41
+ }
42
+ }
43
+ else {
44
+ let input = '';
45
+ if (operation !== 'describe')
46
+ for await (const chunk of process.stdin) {
47
+ input += chunk;
48
+ if (Buffer.byteLength(input) > 3 * 1024 * 1024)
49
+ throw new Error('JSON input exceeds 3 MiB');
50
+ }
51
+ result = await session.call(operation, input ? JSON.parse(input) : {});
52
+ if (operation === 'save' && isRecord(result) && !result.complete)
53
+ process.exitCode = 1;
54
+ }
55
+ console.log(JSON.stringify({ result }));
56
+ }
57
+ catch (error) {
58
+ console.log(JSON.stringify({ error: diagnostic(error) }));
59
+ process.exitCode = 1;
60
+ }
61
+ finally {
62
+ process.removeListener('SIGTERM', cancel);
63
+ process.removeListener('SIGINT', cancel);
64
+ await session.close();
65
+ }
66
+ }
@@ -0,0 +1,19 @@
1
+ import type { Stats } from 'node:fs';
2
+ export declare function contentError(code: string, message?: string): Error & {
3
+ code: string;
4
+ };
5
+ /** Capture data bytes only. Symlink targets must remain inside the installed project. */
6
+ export declare function materialFiles(root: string, { signal, maxBytes, maxFiles, onRead, }?: {
7
+ signal?: AbortSignal;
8
+ maxBytes?: number;
9
+ maxFiles?: number;
10
+ onRead?: (path: string, stats: Stats) => void;
11
+ }): Promise<Array<{
12
+ path: string;
13
+ bytes: Buffer;
14
+ }>>;
15
+ export declare function writeMaterials(root: string, files: unknown, { signal, maxBytes, maxFiles, }?: {
16
+ signal?: AbortSignal;
17
+ maxBytes?: number;
18
+ maxFiles?: number;
19
+ }): Promise<void>;