@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
package/src/release.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ platformMachineArchiveReleaseResultSchema,
2
3
  platformMachineCreateReleaseDraftResultSchema,
3
4
  platformMachineFinalizeReleaseUploadResultSchema,
4
5
  platformMachineGetReleaseResultSchema,
@@ -39,9 +40,9 @@ import { detectProjectContext } from "./context.js";
39
40
  import {
40
41
  pathExists,
41
42
  readPackageJson,
42
- resolveCandidatePath,
43
43
  resolveCanonicalPath,
44
44
  } from "./fs-utils.js";
45
+ import { AIRJAM_CONFIG_PATH, inspectGame } from "./games.js";
45
46
  import {
46
47
  requestPlatformMachineApi,
47
48
  resolvePlatformMachineAuth,
@@ -51,6 +52,7 @@ import type {
51
52
  AirJamLocalReleaseIssue,
52
53
  AirJamLocalReleaseValidation,
53
54
  AirJamPackageManager,
55
+ ArchivePlatformReleaseOptions,
54
56
  BundleLocalReleaseOptions,
55
57
  BundleLocalReleaseResult,
56
58
  CommandResult,
@@ -72,6 +74,7 @@ export type {
72
74
  AirJamLocalReleaseDoctor,
73
75
  AirJamLocalReleaseIssue,
74
76
  AirJamLocalReleaseValidation,
77
+ ArchivePlatformReleaseOptions,
75
78
  BundleLocalReleaseOptions,
76
79
  BundleLocalReleaseResult,
77
80
  ExportPlatformReleaseGenerationOptions,
@@ -167,31 +170,12 @@ const getDefaultReleaseBundlePath = ({
167
170
  );
168
171
  };
169
172
 
170
- const readConfiguredControllerPath = async (
171
- configPath: string | null,
172
- ): Promise<string | null> => {
173
- if (!configPath || !(await pathExists(configPath))) {
174
- return null;
175
- }
176
-
177
- const source = await readFile(configPath, "utf8");
178
- const match = source.match(/controllerPath\s*:\s*["'`](?<path>[^"'`]+)["'`]/);
179
- return match?.groups?.path?.trim() || null;
180
- };
181
-
182
173
  const getLocalAirJamConfigPath = async (
183
174
  projectDir: string,
184
- ): Promise<string | null> =>
185
- resolveCandidatePath(projectDir, [
186
- "src/airjam.config.ts",
187
- "src/airjam.config.tsx",
188
- "src/airjam.config.js",
189
- "src/airjam.config.mjs",
190
- "airjam.config.ts",
191
- "airjam.config.tsx",
192
- "airjam.config.js",
193
- "airjam.config.mjs",
194
- ]);
175
+ ): Promise<string | null> => {
176
+ const configPath = path.join(projectDir, AIRJAM_CONFIG_PATH);
177
+ return (await pathExists(configPath)) ? configPath : null;
178
+ };
195
179
 
196
180
  const collectDirectoryFiles = async (sourceDir: string): Promise<string[]> => {
197
181
  const entries = await readdir(sourceDir);
@@ -740,11 +724,8 @@ const inspectProjectRelease = async ({
740
724
  }): Promise<AirJamLocalReleaseDoctor> => {
741
725
  const packageJson = await readPackageJson(projectDir);
742
726
  const configPath = await getLocalAirJamConfigPath(projectDir);
743
- const configSource = configPath
744
- ? await readFile(configPath, "utf8").catch(() => "")
745
- : "";
746
- const controllerPath =
747
- (await readConfiguredControllerPath(configPath)) ?? null;
727
+ const game = configPath ? await inspectGame({ cwd: projectDir }) : null;
728
+ const controllerPath = game?.declaration.controllerPath ?? null;
748
729
  const distExists = await pathExists(distDir);
749
730
  const distEntryExists = distExists
750
731
  ? await pathExists(path.join(distDir, HOSTED_RELEASE_ENTRY_PATH))
@@ -783,17 +764,6 @@ const inspectProjectRelease = async ({
783
764
  );
784
765
  }
785
766
 
786
- if (!/\bgameMetadata\b/.test(configSource)) {
787
- issues.push(
788
- createIssue(
789
- "missing-game-metadata",
790
- "warning",
791
- "No gameMetadata export was detected in airjam.config.ts. Hosted release submission can still bundle locally, but dashboard prefill and catalog metadata will be incomplete.",
792
- configPath,
793
- ),
794
- );
795
- }
796
-
797
767
  if (distExists && !distEntryExists) {
798
768
  issues.push(
799
769
  createIssue(
@@ -813,7 +783,7 @@ const inspectProjectRelease = async ({
813
783
  packageManager,
814
784
  configPath,
815
785
  buildScript: packageJson?.value.scripts?.build ?? null,
816
- metadataExportLikely: /\bgameMetadata\b/.test(configSource),
786
+ gameSlug: game?.id ?? null,
817
787
  controllerPath,
818
788
  distDir,
819
789
  distExists,
@@ -1177,7 +1147,7 @@ export const inspectLocalRelease = async ({
1177
1147
  packageManager,
1178
1148
  configPath: null,
1179
1149
  buildScript: null,
1180
- metadataExportLikely: false,
1150
+ gameSlug: null,
1181
1151
  controllerPath: null,
1182
1152
  distDir: resolvedDistDir,
1183
1153
  distExists: await pathExists(resolvedDistDir),
@@ -1387,6 +1357,22 @@ export const publishPlatformRelease = async ({
1387
1357
  });
1388
1358
  };
1389
1359
 
1360
+ export const archivePlatformRelease = async ({
1361
+ platformUrl,
1362
+ token,
1363
+ releaseId,
1364
+ }: ArchivePlatformReleaseOptions) => {
1365
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
1366
+
1367
+ return requestPlatformMachineApi({
1368
+ baseUrl: resolved.baseUrl,
1369
+ pathname: `/api/cli/releases/${encodeURIComponent(releaseId)}/archive`,
1370
+ method: "POST",
1371
+ token: resolved.token,
1372
+ schema: platformMachineArchiveReleaseResultSchema,
1373
+ });
1374
+ };
1375
+
1390
1376
  export const uploadPlatformReleaseGeneration = async ({
1391
1377
  platformUrl,
1392
1378
  token,
@@ -0,0 +1,194 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import {
3
+ resolveDevtoolsHelperArgs,
4
+ resolveDevtoolsHelperScript,
5
+ } from "./helper-scripts.js";
6
+ import {
7
+ deviceEventSchema,
8
+ sharedNow,
9
+ type ConnectionProblem,
10
+ type DeviceCommand,
11
+ type DeviceEvent,
12
+ type DeviceLink,
13
+ } from "./rooms-check-protocol.js";
14
+
15
+ /** A scenario found the room server breaking a rule; its message says which. */
16
+ export class ScenarioFailure extends Error {}
17
+
18
+ export type Status = Extract<DeviceEvent, { type: "status" }>;
19
+
20
+ export const isOpen = (event: DeviceEvent): event is Status =>
21
+ event.type === "status" && event.status.phase === "open";
22
+
23
+ /**
24
+ * Spaces connection opens so that no minute holds more than `perMinute`,
25
+ * across every device process of the check, for a server that limits how
26
+ * often one address may connect.
27
+ */
28
+ export class ConnectionPacer {
29
+ private readonly spacingMs: number;
30
+ private next = Number.NEGATIVE_INFINITY;
31
+
32
+ constructor(
33
+ perMinute: number,
34
+ private readonly now: () => number = sharedNow,
35
+ ) {
36
+ this.spacingMs = Math.floor(60_000 / Math.max(perMinute - 1, 1)) + 1;
37
+ }
38
+
39
+ /** Reserves the next open and returns when it may happen. */
40
+ reserve(): number {
41
+ const slot = Math.max(this.now(), this.next);
42
+ this.next = slot + this.spacingMs;
43
+ return slot;
44
+ }
45
+ }
46
+
47
+ /** One device process the check can freeze, thaw, kill and read. */
48
+ export class Device {
49
+ readonly events: DeviceEvent[] = [];
50
+ private readonly waiters = new Set<() => void>();
51
+ private exited = false;
52
+
53
+ constructor(
54
+ readonly name: string,
55
+ private readonly child: ChildProcess,
56
+ pacer: ConnectionPacer | null,
57
+ ) {
58
+ child.on("message", (message: unknown) => {
59
+ const event = deviceEventSchema.parse(message);
60
+ if (event.type === "dial") {
61
+ const grant = () => {
62
+ if (child.connected) child.send({ type: "dial", id: event.id });
63
+ };
64
+ if (pacer) setTimeout(grant, pacer.reserve() - sharedNow());
65
+ else grant();
66
+ return;
67
+ }
68
+ this.events.push(event);
69
+ for (const waiter of [...this.waiters]) waiter();
70
+ });
71
+ child.on("exit", () => {
72
+ this.exited = true;
73
+ });
74
+ }
75
+
76
+ send(command: DeviceCommand): void {
77
+ this.child.send(command);
78
+ }
79
+
80
+ freeze(): void {
81
+ this.child.kill("SIGSTOP");
82
+ }
83
+
84
+ thaw(): void {
85
+ this.child.kill("SIGCONT");
86
+ }
87
+
88
+ kill(): void {
89
+ if (this.exited) return;
90
+ this.child.kill("SIGCONT");
91
+ this.child.kill("SIGKILL");
92
+ }
93
+
94
+ /**
95
+ * The first event since `since` that `find` accepts, or a failure naming
96
+ * `what`; a device that reports it failed fails whatever waits on it.
97
+ */
98
+ until<Found>(
99
+ find: (event: DeviceEvent) => Found | undefined,
100
+ what: string,
101
+ deadlineMs: number,
102
+ since = 0,
103
+ ): Promise<Found> {
104
+ const search = (): { found: Found } | { failed: string } | undefined => {
105
+ for (const event of this.events)
106
+ if (event.at >= since) {
107
+ if (event.type === "failed") return { failed: event.message };
108
+ const found = find(event);
109
+ if (found !== undefined) return { found };
110
+ }
111
+ return undefined;
112
+ };
113
+ return new Promise((resolve, reject) => {
114
+ const check = () => {
115
+ const outcome = search();
116
+ if (outcome === undefined) return;
117
+ clearTimeout(timer);
118
+ this.waiters.delete(check);
119
+ if ("found" in outcome) resolve(outcome.found);
120
+ else reject(new ScenarioFailure(`${this.name}: ${outcome.failed}`));
121
+ };
122
+ const timer = setTimeout(() => {
123
+ this.waiters.delete(check);
124
+ reject(
125
+ new ScenarioFailure(
126
+ `${this.name}: ${what} did not happen within ${deadlineMs} ms.`,
127
+ ),
128
+ );
129
+ }, deadlineMs);
130
+ this.waiters.add(check);
131
+ check();
132
+ });
133
+ }
134
+
135
+ since<Type extends DeviceEvent["type"]>(
136
+ type: Type,
137
+ from = 0,
138
+ to = Number.POSITIVE_INFINITY,
139
+ ): Array<Extract<DeviceEvent, { type: Type }>> {
140
+ return this.events.filter(
141
+ (event): event is Extract<DeviceEvent, { type: Type }> =>
142
+ event.type === type && event.at >= from && event.at <= to,
143
+ );
144
+ }
145
+ }
146
+
147
+ /** The devices of one scenario; every process ends with it. */
148
+ export class Fleet {
149
+ private readonly devices: Device[] = [];
150
+ private readonly script = resolveDevtoolsHelperScript(
151
+ "rooms-check-device.ts",
152
+ );
153
+
154
+ readonly link: DeviceLink;
155
+ readonly hostCredentialCommand: string | undefined;
156
+
157
+ constructor(
158
+ target: { link: DeviceLink; hostCredentialCommand?: string },
159
+ private readonly pacer: ConnectionPacer | null,
160
+ ) {
161
+ this.link = target.link;
162
+ this.hostCredentialCommand = target.hostCredentialCommand;
163
+ }
164
+
165
+ device(name: string): Device {
166
+ const child = spawn(
167
+ process.execPath,
168
+ resolveDevtoolsHelperArgs(this.script),
169
+ {
170
+ stdio: ["ignore", "ignore", "inherit", "ipc"],
171
+ },
172
+ );
173
+ const device = new Device(name, child, this.pacer);
174
+ this.devices.push(device);
175
+ return device;
176
+ }
177
+
178
+ /** Every connection problem the devices reported, timed from `startedAt`. */
179
+ problems(startedAt: number): ConnectionProblem[] {
180
+ return this.devices
181
+ .flatMap((device) =>
182
+ device.since("problem").map((event) => ({
183
+ device: device.name,
184
+ atMs: Math.round(event.at - startedAt),
185
+ problem: event.problem,
186
+ })),
187
+ )
188
+ .sort((left, right) => left.atMs - right.atMs);
189
+ }
190
+
191
+ close(): void {
192
+ for (const device of this.devices) device.kill();
193
+ }
194
+ }
@@ -0,0 +1,138 @@
1
+ import {
2
+ roomCloseReasonForCode,
3
+ type RoomConnector,
4
+ type RoomWireData,
5
+ } from "@air-jam/sdk/room-protocol";
6
+ import { roomSocketUrls } from "@air-jam/sdk/room-session";
7
+ import WebSocket from "ws";
8
+ import type { LinkProblem } from "./rooms-check-protocol.js";
9
+
10
+ const HANDSHAKE_TIMEOUT_MS = 10_000;
11
+
12
+ interface Stallable {
13
+ stall(): void;
14
+ resume(): void;
15
+ }
16
+
17
+ /**
18
+ * The device's network as the check controls it. A stall holds every byte
19
+ * both ways, as a dead cell does: nothing is read, and what the device sends
20
+ * waits where the device cannot see it, as in the system's socket buffer,
21
+ * then leaves in one burst when the network returns.
22
+ */
23
+ export class CheckNetwork {
24
+ private readonly links = new Set<Stallable>();
25
+ private stalled = false;
26
+
27
+ attach(link: Stallable): () => void {
28
+ this.links.add(link);
29
+ if (this.stalled) link.stall();
30
+ return () => this.links.delete(link);
31
+ }
32
+
33
+ stall(): void {
34
+ this.stalled = true;
35
+ for (const link of this.links) link.stall();
36
+ }
37
+
38
+ resume(): void {
39
+ this.stalled = false;
40
+ for (const link of this.links) link.resume();
41
+ }
42
+ }
43
+
44
+ export interface CheckConnectorOptions {
45
+ /** The rooms origin under check. */
46
+ readonly url: string;
47
+ /** Sent as every connection's Origin header, as the page's origin would be. */
48
+ readonly origin?: string;
49
+ /** Resolves when this connection may open; the check paces opens across every process. */
50
+ readonly dial: () => Promise<void>;
51
+ readonly onDialing?: () => void;
52
+ /** A connection failed to open, or closed without this side asking. */
53
+ readonly onProblem: (problem: LinkProblem) => void;
54
+ readonly network?: CheckNetwork;
55
+ }
56
+
57
+ /**
58
+ * Links as a phone or a screen would, over Node's `ws` so the check can send
59
+ * the page's Origin and learn why a connection failed: the HTTP status of a
60
+ * refused upgrade, the error of one that never answered, or the close code.
61
+ */
62
+ export const createCheckConnector = (
63
+ options: CheckConnectorOptions,
64
+ ): RoomConnector => {
65
+ const urlFor = roomSocketUrls(options.url);
66
+ return (address, handlers) => {
67
+ let socket: WebSocket | null = null;
68
+ let closedHere = false;
69
+ let held: RoomWireData[] | null = null;
70
+ let detach = () => {};
71
+ void options.dial().then(() => {
72
+ if (closedHere) return;
73
+ options.onDialing?.();
74
+ const opening = new WebSocket(urlFor(address), {
75
+ origin: options.origin,
76
+ handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
77
+ });
78
+ socket = opening;
79
+ let opened = false;
80
+ let refusedStatus: number | null = null;
81
+ let error: string | null = null;
82
+ opening.on("unexpected-response", (_request, response) => {
83
+ refusedStatus = response.statusCode ?? 0;
84
+ opening.terminate();
85
+ });
86
+ opening.on("error", (cause: Error & { code?: string }) => {
87
+ error ??= cause.code ?? cause.message;
88
+ });
89
+ opening.on("open", () => {
90
+ opened = true;
91
+ detach =
92
+ options.network?.attach({
93
+ stall: () => {
94
+ held ??= [];
95
+ opening.pause();
96
+ },
97
+ resume: () => {
98
+ opening.resume();
99
+ const burst = held ?? [];
100
+ held = null;
101
+ for (const data of burst) opening.send(data);
102
+ },
103
+ }) ?? detach;
104
+ handlers.open();
105
+ });
106
+ opening.on("message", (data, isBinary) => {
107
+ const bytes = Buffer.isBuffer(data)
108
+ ? data
109
+ : Buffer.concat(Array.isArray(data) ? data : [Buffer.from(data)]);
110
+ handlers.message(isBinary ? new Uint8Array(bytes) : bytes.toString());
111
+ });
112
+ opening.on("close", (code) => {
113
+ detach();
114
+ if (closedHere) return;
115
+ options.onProblem(
116
+ opened
117
+ ? { kind: "closed", code, reason: roomCloseReasonForCode(code) }
118
+ : refusedStatus !== null
119
+ ? { kind: "refused", status: refusedStatus }
120
+ : { kind: "failed", error: error ?? `closed with ${code}` },
121
+ );
122
+ handlers.close(code);
123
+ });
124
+ });
125
+ return {
126
+ send: (data) => {
127
+ if (held) held.push(data);
128
+ else if (socket?.readyState === WebSocket.OPEN) socket.send(data);
129
+ },
130
+ buffered: () => (socket?.bufferedAmount ?? 0) > 0,
131
+ close: () => {
132
+ closedHere = true;
133
+ if (socket?.readyState === WebSocket.OPEN) socket.close(1000);
134
+ else socket?.terminate();
135
+ },
136
+ };
137
+ };
138
+ };