@air-jam/devtools 0.9.3 → 1.0.0-beta.2

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 (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/chunk-M6CJ7GQC.js +133 -0
  33. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  34. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  35. package/dist/chunk-MEIMOSZC.js.map +1 -0
  36. package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
  37. package/dist/chunk-O3XG3FNL.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +769 -67
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +287 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +72 -41
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +255 -38
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +326 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
@@ -0,0 +1,295 @@
1
+ import { airJamSettingSchema, defineAirJamSettings } from "@air-jam/sdk/core";
2
+ import { randomUUID } from "node:crypto";
3
+ import { realpathSync } from "node:fs";
4
+ import {
5
+ readFile,
6
+ realpath,
7
+ rename,
8
+ rm,
9
+ stat,
10
+ writeFile,
11
+ } from "node:fs/promises";
12
+ import { createRequire } from "node:module";
13
+ import path from "node:path";
14
+ import type * as TS from "typescript";
15
+ import { inspectGame } from "./games.js";
16
+
17
+ export type SettingValue = number | boolean | string;
18
+ export type KeptGameSettings = {
19
+ file: string;
20
+ kept: { key: string; from: SettingValue; to: SettingValue }[];
21
+ };
22
+
23
+ function refuse(code: string, message: string): never {
24
+ throw Object.assign(new Error(`${code}: ${message}`), { code });
25
+ }
26
+
27
+ /** Changes only literal defaults in the declaration selected by the game's config. */
28
+ export async function keepGameSettings({
29
+ cwd = process.cwd(),
30
+ values,
31
+ }: {
32
+ cwd?: string;
33
+ values: Record<string, SettingValue>;
34
+ }): Promise<KeptGameSettings> {
35
+ cwd = await realpath(cwd);
36
+ let ts: typeof TS;
37
+ try {
38
+ ts = createRequire(path.join(cwd, "package.json"))(
39
+ "typescript",
40
+ ) as typeof TS;
41
+ } catch {
42
+ refuse(
43
+ "AJ_SETTINGS_TYPESCRIPT_MISSING",
44
+ "Install typescript in this game's dependencies before keeping settings.",
45
+ );
46
+ }
47
+ const fail: (message: string) => never = (message) =>
48
+ refuse("AJ_SETTINGS_DECLARATION", message);
49
+ // Bind only game source. SDK/package declarations and ambient libraries are
50
+ // irrelevant to resolving which local variable the game actually imports.
51
+ const sourceRoot = path.join(cwd, "src");
52
+ const localFile = (file: string) => {
53
+ try {
54
+ const resolved = realpathSync(file);
55
+ const relative = path.relative(cwd, resolved);
56
+ return relative !== ".." &&
57
+ !relative.startsWith(`..${path.sep}`) &&
58
+ !path.isAbsolute(relative) &&
59
+ !relative.split(path.sep).includes("node_modules")
60
+ ? resolved
61
+ : undefined;
62
+ } catch {
63
+ return undefined;
64
+ }
65
+ };
66
+ const options: TS.CompilerOptions = {
67
+ noLib: true,
68
+ types: [],
69
+ skipLibCheck: true,
70
+ target: ts.ScriptTarget.Latest,
71
+ module: ts.ModuleKind.ESNext,
72
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
73
+ allowImportingTsExtensions: true,
74
+ };
75
+ const host = ts.createCompilerHost(options);
76
+ host.getCurrentDirectory = () => cwd;
77
+ host.fileExists = (file) => localFile(file) !== undefined;
78
+ host.readFile = (file) => {
79
+ const local = localFile(file);
80
+ return local ? ts.sys.readFile(local) : undefined;
81
+ };
82
+ host.getSourceFile = (file, languageVersion) => {
83
+ const local = localFile(file);
84
+ const text = local ? host.readFile(local) : undefined;
85
+ return local && text !== undefined
86
+ ? ts.createSourceFile(local, text, languageVersion, true)
87
+ : undefined;
88
+ };
89
+ host.resolveModuleNames = (names, containingFile) =>
90
+ names.map((name) =>
91
+ name.startsWith(".")
92
+ ? ts.resolveModuleName(name, containingFile, options, host)
93
+ .resolvedModule
94
+ : undefined,
95
+ );
96
+ const configPath = path.join(sourceRoot, "airjam.config.ts");
97
+ const program = ts.createProgram([configPath], options, host);
98
+ const config = program.getSourceFile(configPath);
99
+ if (!config) fail("The game's src/airjam.config.ts could not be read.");
100
+ if (program.getSyntacticDiagnostics().length)
101
+ fail("Fix the game's source syntax before keeping settings.");
102
+ const checker = program.getTypeChecker();
103
+ const resolveVariable = (initial: TS.Symbol | undefined) => {
104
+ let symbol = initial;
105
+ const aliases = new Set<TS.Symbol>();
106
+ while (symbol && symbol.flags & ts.SymbolFlags.Alias) {
107
+ if (aliases.has(symbol))
108
+ fail("The settings binding has a circular alias.");
109
+ aliases.add(symbol);
110
+ symbol = checker.getAliasedSymbol(symbol);
111
+ }
112
+ const declarations = symbol?.getDeclarations();
113
+ if (
114
+ declarations?.length !== 1 ||
115
+ !ts.isVariableDeclaration(declarations[0])
116
+ )
117
+ fail("Expected one unambiguous source variable declaration.");
118
+ const variable = declarations[0];
119
+ if (
120
+ !ts.isIdentifier(variable.name) ||
121
+ !ts.isVariableDeclarationList(variable.parent) ||
122
+ !(variable.parent.flags & ts.NodeFlags.Const) ||
123
+ !variable.initializer
124
+ )
125
+ fail("Settings must use one directly initialized const binding.");
126
+ return {
127
+ source: variable.getSourceFile(),
128
+ initializer: variable.initializer,
129
+ };
130
+ };
131
+ const name = (node: TS.PropertyName) => {
132
+ if (ts.isIdentifier(node) || ts.isStringLiteral(node)) return node.text;
133
+ return fail(
134
+ "Computed properties cannot be kept; use explicit property names.",
135
+ );
136
+ };
137
+ const properties = (node: TS.Expression | undefined) => {
138
+ if (!node || !ts.isObjectLiteralExpression(node))
139
+ return fail("Use one explicit object literal for the declaration.");
140
+ const result = new Map<string, TS.PropertyAssignment>();
141
+ for (const property of node.properties) {
142
+ if (!ts.isPropertyAssignment(property))
143
+ fail(
144
+ "Spread and shorthand properties cannot be kept; use explicit properties.",
145
+ );
146
+ const key = name(property.name);
147
+ if (result.has(key))
148
+ fail(`Duplicate property ${key} makes the declaration ambiguous.`);
149
+ result.set(key, property);
150
+ }
151
+ return result;
152
+ };
153
+ const isCall = (node: TS.Node, called: string): node is TS.CallExpression =>
154
+ ts.isCallExpression(node) &&
155
+ ts.isIdentifier(node.expression) &&
156
+ node.expression.text === called;
157
+ const games: TS.CallExpression[] = [];
158
+ const visit = (node: TS.Node) => {
159
+ if (isCall(node, "defineAirJamGame")) games.push(node);
160
+ ts.forEachChild(node, visit);
161
+ };
162
+ visit(config);
163
+ if (games.length !== 1)
164
+ fail("Expected exactly one defineAirJamGame declaration.");
165
+ const module = checker.getSymbolAtLocation(config);
166
+ const exportedGame =
167
+ module &&
168
+ checker.getExportsOfModule(module).find((entry) => entry.name === "airjam");
169
+ if (resolveVariable(exportedGame).initializer !== games[0])
170
+ fail(
171
+ "The defineAirJamGame declaration must be the game's exported airjam value.",
172
+ );
173
+ // A checker may still pick a symbol from invalid duplicate exports. Never
174
+ // treat that recovery choice as an authoritative source-edit target.
175
+ if (
176
+ program
177
+ .getSemanticDiagnostics()
178
+ .some(({ code }) => [2300, 2308, 2323, 2451, 2484, 2588].includes(code))
179
+ )
180
+ fail(
181
+ "Duplicate or ambiguous bindings must be resolved before keeping settings.",
182
+ );
183
+ const selected = properties(games[0].arguments[0]).get(
184
+ "settings",
185
+ )?.initializer;
186
+ if (!selected) fail("This game has no settings declaration.");
187
+ let source = config;
188
+ let declaration = selected;
189
+ if (ts.isIdentifier(selected)) {
190
+ const binding = resolveVariable(checker.getSymbolAtLocation(selected));
191
+ source = binding.source;
192
+ declaration = binding.initializer;
193
+ }
194
+ if (
195
+ !isCall(declaration, "defineAirJamSettings") ||
196
+ declaration.arguments.length !== 1
197
+ )
198
+ fail("Settings must be bound directly to defineAirJamSettings({...}).");
199
+ const settings = properties(declaration.arguments[0]);
200
+ const edits: { start: number; end: number; text: string }[] = [];
201
+ const kept: KeptGameSettings["kept"] = [];
202
+ for (const [key, to] of Object.entries(values)) {
203
+ const entry = settings.get(key);
204
+ if (!entry)
205
+ refuse("AJ_SETTING_UNKNOWN", `${key} is not declared by this game.`);
206
+ const call = entry.initializer;
207
+ if (
208
+ !ts.isCallExpression(call) ||
209
+ !ts.isPropertyAccessExpression(call.expression) ||
210
+ !ts.isIdentifier(call.expression.expression) ||
211
+ call.expression.expression.text !== "setting" ||
212
+ !["number", "boolean", "choice"].includes(call.expression.name.text) ||
213
+ call.arguments.length !== 1
214
+ )
215
+ fail(
216
+ `${key} must use setting.number, setting.boolean or setting.choice directly.`,
217
+ );
218
+ const literal = properties(call.arguments[0]).get("default")?.initializer;
219
+ if (!literal) fail(`${key} needs an explicit default literal.`);
220
+ let from: SettingValue;
221
+ if (ts.isNumericLiteral(literal)) from = Number(literal.text);
222
+ else if (
223
+ ts.isPrefixUnaryExpression(literal) &&
224
+ literal.operator === ts.SyntaxKind.MinusToken &&
225
+ ts.isNumericLiteral(literal.operand)
226
+ )
227
+ from = -Number(literal.operand.text);
228
+ else if (ts.isStringLiteral(literal)) from = literal.text;
229
+ else if (
230
+ literal.kind === ts.SyntaxKind.TrueKeyword ||
231
+ literal.kind === ts.SyntaxKind.FalseKeyword
232
+ )
233
+ from = literal.kind === ts.SyntaxKind.TrueKeyword;
234
+ else
235
+ fail(
236
+ `${key} needs a number, boolean or string default literal; shared or computed defaults cannot be kept.`,
237
+ );
238
+ kept.push({ key, from, to });
239
+ if (from !== to) {
240
+ let text = JSON.stringify(to);
241
+ if (
242
+ typeof to === "string" &&
243
+ source.text[literal.getStart(source)] === "'"
244
+ )
245
+ text = `'${to.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\r/g, "\\r").replace(/\n/g, "\\n")}'`;
246
+ edits.push({ start: literal.getStart(source), end: literal.end, text });
247
+ }
248
+ }
249
+ // Use the same evaluated descriptors as inspection and the SDK's authoritative validation.
250
+ const inspected = await inspectGame({ cwd });
251
+ const descriptors = Object.fromEntries(
252
+ Object.entries(inspected.declaration.settings ?? {}).map(([key, value]) => [
253
+ key,
254
+ airJamSettingSchema.parse(value),
255
+ ]),
256
+ );
257
+ for (const [key, value] of Object.entries(values)) {
258
+ if (!Object.hasOwn(descriptors, key))
259
+ refuse("AJ_SETTING_UNKNOWN", `${key} is not declared by this game.`);
260
+ try {
261
+ defineAirJamSettings({
262
+ [key]: { ...descriptors[key], default: value },
263
+ } as Parameters<typeof defineAirJamSettings>[0]);
264
+ } catch {
265
+ refuse(
266
+ "AJ_SETTING_INVALID",
267
+ `${key} must match its declared type, range and step or options.`,
268
+ );
269
+ }
270
+ }
271
+ if (edits.length) {
272
+ let output = source.text;
273
+ for (const edit of edits.sort((a, b) => b.start - a.start))
274
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
275
+ if ((await readFile(source.fileName, "utf8")) !== source.text)
276
+ refuse(
277
+ "AJ_SETTINGS_STALE",
278
+ "The game changed while keeping settings; read again.",
279
+ );
280
+ const temporary = `${source.fileName}.${randomUUID()}.tmp`;
281
+ try {
282
+ await writeFile(temporary, output, {
283
+ flag: "wx",
284
+ mode: (await stat(source.fileName)).mode,
285
+ });
286
+ await rename(temporary, source.fileName);
287
+ } finally {
288
+ await rm(temporary, { force: true });
289
+ }
290
+ }
291
+ return {
292
+ file: path.relative(cwd, source.fileName).split(path.sep).join("/"),
293
+ kept,
294
+ };
295
+ }
package/src/games.ts CHANGED
@@ -1,13 +1,18 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { airJamGameDescriptionSchema } from "@air-jam/sdk/core";
2
2
  import path from "node:path";
3
+ import { z } from "zod";
4
+ import { runCommandResult } from "./commands.js";
3
5
  import { detectProjectContext } from "./context.js";
4
6
  import {
5
7
  listDirectories,
6
8
  pathExists,
7
9
  readJsonFile,
8
10
  readPackageJson,
9
- resolveCandidatePath,
10
11
  } from "./fs-utils.js";
12
+ import {
13
+ resolveDevtoolsHelperArgs,
14
+ resolveDevtoolsHelperScript,
15
+ } from "./helper-scripts.js";
11
16
  import type {
12
17
  AirJamGameInspection,
13
18
  AirJamGameSummary,
@@ -27,101 +32,85 @@ export type {
27
32
 
28
33
  const REPO_GAME_MANIFEST = "airjam-template.json";
29
34
 
30
- const toStringOrNull = (value: unknown): string | null =>
31
- typeof value === "string" ? value : null;
32
-
33
35
  const toBooleanOrNull = (value: unknown): boolean | null =>
34
36
  typeof value === "boolean" ? value : null;
35
37
 
36
- const inferGameIdFromRoot = (
37
- rootDir: string,
38
- packageName: string | null,
39
- ): string => packageName ?? path.basename(rootDir);
38
+ export const AIRJAM_CONFIG_PATH = "src/airjam.config.ts";
40
39
 
41
- const getConfigPath = async (rootDir: string): Promise<string | null> =>
42
- resolveCandidatePath(rootDir, [
43
- "src/airjam.config.ts",
44
- "src/airjam.config.tsx",
45
- "src/airjam.config.js",
46
- "src/airjam.config.mjs",
47
- "airjam.config.ts",
48
- "airjam.config.tsx",
49
- "airjam.config.js",
50
- "airjam.config.mjs",
51
- ]);
40
+ const describeGames = (configPaths: string[], cwd: string) => {
41
+ if (!configPaths.length) return [];
42
+ const result = runCommandResult({
43
+ command: process.execPath,
44
+ args: [
45
+ ...resolveDevtoolsHelperArgs(
46
+ resolveDevtoolsHelperScript("describe-game.ts"),
47
+ ),
48
+ ...configPaths.flatMap((config) => ["--config", config]),
49
+ ],
50
+ cwd,
51
+ });
52
+ if (!result.ok)
53
+ throw new Error(
54
+ `Air Jam declaration inspection failed.\n${result.stderr || result.stdout}`,
55
+ );
56
+ return z.array(airJamGameDescriptionSchema).parse(JSON.parse(result.stdout));
57
+ };
52
58
 
53
- const readRepoGameSummary = async (
59
+ const readGameSummary = async (
54
60
  rootDir: string,
55
- ): Promise<AirJamGameSummary | null> => {
61
+ declaration: AirJamGameSummary["declaration"],
62
+ ): Promise<AirJamGameSummary> => {
56
63
  const manifestPath = path.join(rootDir, REPO_GAME_MANIFEST);
57
- if (!(await pathExists(manifestPath))) {
58
- return null;
59
- }
60
-
61
- const manifest = await readJsonFile<JsonObject>(manifestPath);
64
+ const hasManifest = await pathExists(manifestPath);
65
+ const manifest = hasManifest
66
+ ? await readJsonFile<JsonObject>(manifestPath)
67
+ : null;
62
68
  const packageJson = await readPackageJson(rootDir);
63
- const packageName = packageJson?.value.name ?? null;
64
- const configPath = await getConfigPath(rootDir);
65
-
66
69
  return {
67
- id:
68
- toStringOrNull(manifest.id) ?? inferGameIdFromRoot(rootDir, packageName),
69
- name:
70
- toStringOrNull(manifest.name) ?? packageName ?? path.basename(rootDir),
71
70
  rootDir,
72
- packageName,
73
- description: toStringOrNull(manifest.description),
74
- category: toStringOrNull(manifest.category),
75
- scaffold: toBooleanOrNull(manifest.scaffold),
76
- manifestPath,
77
- configPath,
71
+ manifestPath: hasManifest ? manifestPath : null,
72
+ id: declaration.metadata.slug,
73
+ name: declaration.metadata.name,
74
+ packageName: packageJson?.value.name ?? null,
75
+ description: declaration.metadata.tagline,
76
+ category: declaration.metadata.category,
77
+ scaffold: toBooleanOrNull(manifest?.scaffold),
78
+ configPath: path.join(rootDir, AIRJAM_CONFIG_PATH),
79
+ declaration,
78
80
  };
79
81
  };
80
82
 
81
- const readStandaloneGameSummary = async (
82
- context: AirJamProjectContext,
83
- ): Promise<AirJamGameSummary> => {
84
- const packageName = context.packageJson?.name ?? null;
85
- const configPath = await getConfigPath(context.rootDir);
86
-
87
- return {
88
- id: inferGameIdFromRoot(context.rootDir, packageName),
89
- name: packageName ?? path.basename(context.rootDir),
90
- rootDir: context.rootDir,
91
- packageName,
92
- description: toStringOrNull(context.packageJson?.description),
93
- category: null,
94
- scaffold: null,
95
- manifestPath: null,
96
- configPath,
97
- };
83
+ const gameRoots = async (context: AirJamProjectContext) => {
84
+ if (context.mode === "standalone-game") return [context.rootDir];
85
+ if (context.mode !== "monorepo") return [];
86
+ const directories = await listDirectories(
87
+ path.join(context.rootDir, "games"),
88
+ );
89
+ const candidates = await Promise.all(
90
+ directories.map(async (rootDir) =>
91
+ (await pathExists(path.join(rootDir, REPO_GAME_MANIFEST)))
92
+ ? rootDir
93
+ : null,
94
+ ),
95
+ );
96
+ return candidates.filter((rootDir) => rootDir !== null);
98
97
  };
99
98
 
100
99
  export const listGames = async ({
101
100
  cwd = process.cwd(),
102
- }: {
103
- cwd?: string;
104
- } = {}): Promise<AirJamGameSummary[]> => {
101
+ }: { cwd?: string } = {}): Promise<AirJamGameSummary[]> => {
105
102
  const context = await detectProjectContext({ cwd });
106
-
107
- if (context.mode === "monorepo") {
108
- const gameDirs = await listDirectories(path.join(context.rootDir, "games"));
109
- const summaries = await Promise.all(gameDirs.map(readRepoGameSummary));
110
- return summaries
111
- .filter((game): game is AirJamGameSummary => Boolean(game))
112
- .sort((left, right) => left.name.localeCompare(right.name));
113
- }
114
-
115
- if (context.mode === "standalone-game") {
116
- return [await readStandaloneGameSummary(context)];
117
- }
118
-
119
- return [];
120
- };
121
-
122
- const inferControllerPath = (configSource: string): string | null => {
123
- const match = /controllerPath:\s*["'`]([^"'`]+)["'`]/.exec(configSource);
124
- return match?.[1] ?? null;
103
+ const roots = await gameRoots(context);
104
+ const descriptions = describeGames(
105
+ roots.map((rootDir) => path.join(rootDir, AIRJAM_CONFIG_PATH)),
106
+ context.rootDir,
107
+ );
108
+ const games = await Promise.all(
109
+ roots.map((rootDir, index) =>
110
+ readGameSummary(rootDir, descriptions[index]),
111
+ ),
112
+ );
113
+ return games.sort((left, right) => left.name.localeCompare(right.name));
125
114
  };
126
115
 
127
116
  const inferQualityGates = (
@@ -163,31 +152,38 @@ export const inspectGame = async ({
163
152
  gameId?: string;
164
153
  } = {}): Promise<AirJamGameInspection> => {
165
154
  const context = await detectProjectContext({ cwd });
166
- const games = await listGames({ cwd });
167
- const game = gameId
168
- ? games.find((candidate) => candidate.id === gameId)
169
- : games[0];
170
-
171
- if (!game) {
155
+ const roots = await gameRoots(context);
156
+ const rootDir =
157
+ context.mode === "standalone-game"
158
+ ? roots[0]
159
+ : gameId
160
+ ? roots.find((candidate) => path.basename(candidate) === gameId)
161
+ : roots.find(
162
+ (candidate) =>
163
+ path.resolve(cwd).startsWith(`${candidate}${path.sep}`) ||
164
+ path.resolve(cwd) === candidate,
165
+ );
166
+ if (!rootDir)
172
167
  throw new Error(
173
168
  gameId
174
169
  ? `Unable to find Air Jam game "${gameId}".`
175
- : "Unable to find an Air Jam game in this project.",
170
+ : "Choose a gameId when inspecting a workspace.",
176
171
  );
177
- }
172
+ const [declaration] = describeGames(
173
+ [path.join(rootDir, AIRJAM_CONFIG_PATH)],
174
+ context.rootDir,
175
+ );
176
+ const game = await readGameSummary(rootDir, declaration);
177
+ if (gameId && game.id !== gameId)
178
+ throw new Error(`Game directory "${gameId}" declares slug "${game.id}".`);
178
179
 
179
180
  const packageJson = await readPackageJson(game.rootDir);
180
181
  const scripts = packageJson?.value.scripts ?? {};
181
- const configSource = game.configPath
182
- ? await readFile(game.configPath, "utf8").catch(() => "")
183
- : "";
184
182
 
185
183
  return {
186
184
  ...game,
187
185
  packageJsonPath: packageJson?.path ?? null,
188
186
  scripts,
189
- metadataExportLikely: /\bgameMetadata\b/.test(configSource),
190
- controllerPathLikely: inferControllerPath(configSource),
191
187
  qualityGates: inferQualityGates(
192
188
  context.mode === "monorepo"
193
189
  ? (context.packageJson?.scripts ?? {})
@@ -0,0 +1,100 @@
1
+ import {
2
+ AIR_JAM_RUNTIME_TOPOLOGY_WINDOW_KEY,
3
+ type ResolvedAirJamRuntimeTopology,
4
+ } from "@air-jam/sdk/runtime-topology";
5
+ import {
6
+ chromium,
7
+ type Browser,
8
+ type BrowserContext,
9
+ type LaunchOptions,
10
+ } from "playwright-core";
11
+
12
+ import {
13
+ admitProcessScopeMember,
14
+ processScopeToken,
15
+ } from "../../process-scope-admission.js";
16
+ import { processScopeMarker } from "../../process-scope.js";
17
+
18
+ /** Production assets receive their owner-provided topology before the app loads, only in their own origin. */
19
+ export async function installHarnessRuntimeTopology(
20
+ context: BrowserContext,
21
+ topology: ResolvedAirJamRuntimeTopology,
22
+ ) {
23
+ await context.addInitScript(
24
+ ({ key, topology }) => {
25
+ if (window.location.origin === topology.appOrigin)
26
+ (window as unknown as Record<string, unknown>)[key] = topology;
27
+ },
28
+ { key: AIR_JAM_RUNTIME_TOPOLOGY_WINDOW_KEY, topology },
29
+ );
30
+ }
31
+
32
+ const launchHarnessBrowserOptions = () => {
33
+ return {
34
+ headless: true,
35
+ args: [
36
+ // Without a GPU, compositing through SwiftShader took about three
37
+ // quarters of a one-CPU project and ran games at a quarter speed;
38
+ // software compositing reaches 60 fps there, and WebGL keeps SwiftShader.
39
+ "--disable-gpu-compositing",
40
+ "--enable-webgl",
41
+ "--ignore-gpu-blocklist",
42
+ "--use-angle=swiftshader",
43
+ ],
44
+ };
45
+ };
46
+ const launchConfiguredBrowser = async <Result>(
47
+ launch: (options: LaunchOptions) => Promise<Result>,
48
+ ): Promise<Result> => {
49
+ const options = launchHarnessBrowserOptions();
50
+
51
+ if (process.env.AIRJAM_BROWSER_EXECUTABLE_PATH) {
52
+ return launch({
53
+ ...options,
54
+ executablePath: process.env.AIRJAM_BROWSER_EXECUTABLE_PATH,
55
+ });
56
+ }
57
+
58
+ try {
59
+ return await launch(options);
60
+ } catch (bundledBrowserError) {
61
+ try {
62
+ return await launch({ ...options, channel: "chrome" });
63
+ } catch (systemBrowserError) {
64
+ throw new Error(
65
+ [
66
+ "Air Jam could not launch a browser runtime for semantic sessions.",
67
+ "Install Playwright Chromium or set AIRJAM_BROWSER_EXECUTABLE_PATH to a Chromium-compatible browser.",
68
+ `Bundled browser: ${bundledBrowserError instanceof Error ? bundledBrowserError.message : String(bundledBrowserError)}`,
69
+ `System Chrome: ${systemBrowserError instanceof Error ? systemBrowserError.message : String(systemBrowserError)}`,
70
+ ].join("\n\n"),
71
+ );
72
+ }
73
+ }
74
+ };
75
+
76
+ export const launchHarnessBrowser = (): Promise<Browser> =>
77
+ launchConfiguredBrowser((options) => chromium.launch(options));
78
+
79
+ export async function launchScopedHarnessBrowser() {
80
+ const marker = processScopeMarker(processScopeToken());
81
+ const server = await launchConfiguredBrowser((options) =>
82
+ chromium.launchServer({
83
+ ...options,
84
+ args: [...(options.args ?? []), marker],
85
+ }),
86
+ );
87
+ try {
88
+ const processId = server.process().pid;
89
+ if (!processId)
90
+ throw new Error(
91
+ "process_scope_unavailable: Browser process identity unavailable.",
92
+ );
93
+ await admitProcessScopeMember(processId);
94
+ const browser = await chromium.connect(server.wsEndpoint());
95
+ return { browser, close: () => server.close() };
96
+ } catch (error) {
97
+ await server.close();
98
+ throw error;
99
+ }
100
+ }