@air-jam/devtools 0.0.0-stage → 1.0.0-beta.1

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 (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/chunk-2O67AXCU.js +470 -0
  4. package/dist/chunk-2O67AXCU.js.map +1 -0
  5. package/dist/chunk-AO3ZDXF6.js +142 -0
  6. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  7. package/dist/chunk-ART5TEYT.js +472 -0
  8. package/dist/chunk-ART5TEYT.js.map +1 -0
  9. package/dist/chunk-ASC2CK2R.js +77 -0
  10. package/dist/chunk-ASC2CK2R.js.map +1 -0
  11. package/dist/chunk-E3UZZGAV.js +50 -0
  12. package/dist/chunk-E3UZZGAV.js.map +1 -0
  13. package/dist/chunk-EJTE7UKX.js +64 -0
  14. package/dist/chunk-EJTE7UKX.js.map +1 -0
  15. package/dist/chunk-ESFKNN75.js +110 -0
  16. package/dist/chunk-ESFKNN75.js.map +1 -0
  17. package/dist/chunk-EU7A6PXW.js +1339 -0
  18. package/dist/chunk-EU7A6PXW.js.map +1 -0
  19. package/dist/chunk-FN7E6EA7.js +549 -0
  20. package/dist/chunk-FN7E6EA7.js.map +1 -0
  21. package/dist/chunk-GDFAWHGA.js +190 -0
  22. package/dist/chunk-GDFAWHGA.js.map +1 -0
  23. package/dist/chunk-HZUGBH4Y.js +347 -0
  24. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  25. package/dist/chunk-ITKAOEGX.js +93 -0
  26. package/dist/chunk-ITKAOEGX.js.map +1 -0
  27. package/dist/chunk-JBCUTWRI.js +897 -0
  28. package/dist/chunk-JBCUTWRI.js.map +1 -0
  29. package/dist/chunk-JSI5S4WP.js +1174 -0
  30. package/dist/chunk-JSI5S4WP.js.map +1 -0
  31. package/dist/chunk-L4D675BG.js +97 -0
  32. package/dist/chunk-L4D675BG.js.map +1 -0
  33. package/dist/chunk-M6CJ7GQC.js +133 -0
  34. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  35. package/dist/chunk-MEIMOSZC.js +749 -0
  36. package/dist/chunk-MEIMOSZC.js.map +1 -0
  37. package/dist/chunk-O3XG3FNL.js +1014 -0
  38. package/dist/chunk-O3XG3FNL.js.map +1 -0
  39. package/dist/chunk-OM6SCJ7H.js +18 -0
  40. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  41. package/dist/chunk-PKD4WVX5.js +63 -0
  42. package/dist/chunk-PKD4WVX5.js.map +1 -0
  43. package/dist/chunk-PMBLXGFM.js +3384 -0
  44. package/dist/chunk-PMBLXGFM.js.map +1 -0
  45. package/dist/chunk-PMNE5GIN.js +279 -0
  46. package/dist/chunk-PMNE5GIN.js.map +1 -0
  47. package/dist/chunk-QAWI64VR.js +148 -0
  48. package/dist/chunk-QAWI64VR.js.map +1 -0
  49. package/dist/chunk-QGADSPHZ.js +449 -0
  50. package/dist/chunk-QGADSPHZ.js.map +1 -0
  51. package/dist/chunk-SPYN66UV.js +338 -0
  52. package/dist/chunk-SPYN66UV.js.map +1 -0
  53. package/dist/context.d.ts +19 -0
  54. package/dist/context.js +10 -0
  55. package/dist/context.js.map +1 -0
  56. package/dist/controller.d.ts +67 -0
  57. package/dist/controller.js +40 -0
  58. package/dist/controller.js.map +1 -0
  59. package/dist/dependencies.d.ts +44 -0
  60. package/dist/dependencies.js +10 -0
  61. package/dist/dependencies.js.map +1 -0
  62. package/dist/dev.d.ts +21 -0
  63. package/dist/dev.js +19 -0
  64. package/dist/dev.js.map +1 -0
  65. package/dist/game-builds.d.ts +200 -0
  66. package/dist/game-builds.js +16 -0
  67. package/dist/game-builds.js.map +1 -0
  68. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  69. package/dist/game-runs.d.ts +1452 -0
  70. package/dist/game-runs.js +76 -0
  71. package/dist/game-runs.js.map +1 -0
  72. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  73. package/dist/game-session-broker.d.ts +4 -0
  74. package/dist/game-session-broker.js +40 -0
  75. package/dist/game-session-broker.js.map +1 -0
  76. package/dist/game-session.d.ts +3934 -0
  77. package/dist/game-session.js +195 -0
  78. package/dist/game-session.js.map +1 -0
  79. package/dist/game-settings.d.ts +16 -0
  80. package/dist/game-settings.js +237 -0
  81. package/dist/game-settings.js.map +1 -0
  82. package/dist/games.d.ts +28 -0
  83. package/dist/games.js +16 -0
  84. package/dist/games.js.map +1 -0
  85. package/dist/harness/visual.d.ts +204 -0
  86. package/dist/harness/visual.js +46 -0
  87. package/dist/harness/visual.js.map +1 -0
  88. package/dist/logs.d.ts +15 -0
  89. package/dist/logs.js +57 -0
  90. package/dist/logs.js.map +1 -0
  91. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  92. package/dist/mcp-config.d.ts +63 -0
  93. package/dist/mcp-config.js +191 -0
  94. package/dist/mcp-config.js.map +1 -0
  95. package/dist/platform-auth.d.ts +9 -0
  96. package/dist/platform-auth.js +45 -0
  97. package/dist/platform-auth.js.map +1 -0
  98. package/dist/platform-game-analytics.d.ts +51 -0
  99. package/dist/platform-game-analytics.js +49 -0
  100. package/dist/platform-game-analytics.js.map +1 -0
  101. package/dist/platform-game-app-id.d.ts +46 -0
  102. package/dist/platform-game-app-id.js +93 -0
  103. package/dist/platform-game-app-id.js.map +1 -0
  104. package/dist/platform-game-media.d.ts +347 -0
  105. package/dist/platform-game-media.js +168 -0
  106. package/dist/platform-game-media.js.map +1 -0
  107. package/dist/platform-games.d.ts +87 -0
  108. package/dist/platform-games.js +183 -0
  109. package/dist/platform-games.js.map +1 -0
  110. package/dist/quality.d.ts +16 -0
  111. package/dist/quality.js +62 -0
  112. package/dist/quality.js.map +1 -0
  113. package/dist/release.d.ts +1304 -0
  114. package/dist/release.js +34 -0
  115. package/dist/release.js.map +1 -0
  116. package/dist/rooms-check.d.ts +90 -0
  117. package/dist/rooms-check.js +717 -0
  118. package/dist/rooms-check.js.map +1 -0
  119. package/dist/source-tree-contract.d.ts +16 -0
  120. package/dist/source-tree-contract.js +13 -0
  121. package/dist/source-tree-contract.js.map +1 -0
  122. package/dist/testing.d.ts +464 -0
  123. package/dist/testing.js +27 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/tooling/describe-game.d.ts +2 -0
  126. package/dist/tooling/describe-game.js +54 -0
  127. package/dist/tooling/describe-game.js.map +1 -0
  128. package/dist/tooling/game-session-broker.d.ts +2 -0
  129. package/dist/tooling/game-session-broker.js +28 -0
  130. package/dist/tooling/game-session-broker.js.map +1 -0
  131. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  132. package/dist/tooling/hold-runtime-host.js +931 -0
  133. package/dist/tooling/hold-runtime-host.js.map +1 -0
  134. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  135. package/dist/tooling/list-visual-scenarios.js +25 -0
  136. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  137. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  138. package/dist/tooling/managed-dev-supervisor.js +51 -0
  139. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  140. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  141. package/dist/tooling/process-scope-guard.d.ts +2 -0
  142. package/dist/tooling/process-scope-guard.js +388 -0
  143. package/dist/tooling/process-scope-guard.js.map +1 -0
  144. package/dist/tooling/process-scope-windows.ps1 +148 -0
  145. package/dist/tooling/rooms-check-device.d.ts +2 -0
  146. package/dist/tooling/rooms-check-device.js +498 -0
  147. package/dist/tooling/rooms-check-device.js.map +1 -0
  148. package/dist/tooling/run-headless-room.d.ts +2 -0
  149. package/dist/tooling/run-headless-room.js +287 -0
  150. package/dist/tooling/run-headless-room.js.map +1 -0
  151. package/dist/tooling/run-test-profile.d.ts +2 -0
  152. package/dist/tooling/run-test-profile.js +181 -0
  153. package/dist/tooling/run-test-profile.js.map +1 -0
  154. package/dist/tooling/run-visual-capture.d.ts +2 -0
  155. package/dist/tooling/run-visual-capture.js +203 -0
  156. package/dist/tooling/run-visual-capture.js.map +1 -0
  157. package/dist/tooling/seal-game-build.d.ts +2 -0
  158. package/dist/tooling/seal-game-build.js +120 -0
  159. package/dist/tooling/seal-game-build.js.map +1 -0
  160. package/dist/types-CdYrgrG_.d.ts +1036 -0
  161. package/dist/types-DyRD-ym1.d.ts +141 -0
  162. package/dist/visual.d.ts +21 -0
  163. package/dist/visual.js +219 -0
  164. package/dist/visual.js.map +1 -0
  165. package/package.json +150 -3
  166. package/src/bounded-response.ts +28 -0
  167. package/src/built-game-runtime.ts +152 -0
  168. package/src/commands.ts +40 -0
  169. package/src/context.ts +218 -0
  170. package/src/controller-protocol.ts +22 -0
  171. package/src/controller.ts +1526 -0
  172. package/src/current-room-host.ts +166 -0
  173. package/src/decision-provider.ts +102 -0
  174. package/src/dependencies.ts +176 -0
  175. package/src/dependency-install-contract.ts +12 -0
  176. package/src/dev.ts +995 -0
  177. package/src/fs-utils.ts +93 -0
  178. package/src/game-action-observation.ts +106 -0
  179. package/src/game-build-protocol.ts +72 -0
  180. package/src/game-build.ts +483 -0
  181. package/src/game-run-owner.ts +2358 -0
  182. package/src/game-run-protocol.ts +448 -0
  183. package/src/game-run-record.ts +92 -0
  184. package/src/game-run-replay.ts +95 -0
  185. package/src/game-run-watch.ts +155 -0
  186. package/src/game-session-broker.ts +793 -0
  187. package/src/game-session-operations.ts +61 -0
  188. package/src/game-session-protocol.ts +180 -0
  189. package/src/game-session-runtime.ts +861 -0
  190. package/src/game-session.ts +206 -0
  191. package/src/game-settings.ts +295 -0
  192. package/src/games.ts +262 -0
  193. package/src/harness/visual/browser.ts +100 -0
  194. package/src/harness/visual/controller-observation.ts +181 -0
  195. package/src/harness/visual/prefab-contract.ts +29 -0
  196. package/src/harness/visual/prefab-runner.ts +178 -0
  197. package/src/harness/visual/runner.ts +549 -0
  198. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  199. package/src/harness/visual/scenario-contract.ts +8 -0
  200. package/src/harness/visual/scenario-helpers.ts +67 -0
  201. package/src/harness/visual/screencast.ts +155 -0
  202. package/src/harness/visual/session.ts +400 -0
  203. package/src/harness/visual/types.ts +184 -0
  204. package/src/harness/visual.ts +7 -0
  205. package/src/headless-room-protocol.ts +112 -0
  206. package/src/headless-room.ts +222 -0
  207. package/src/helper-channel.ts +229 -0
  208. package/src/helper-scripts.ts +69 -0
  209. package/src/installed-dependencies.ts +74 -0
  210. package/src/logs.ts +67 -0
  211. package/src/managed-process-scope.ts +481 -0
  212. package/src/mcp-config.ts +262 -0
  213. package/src/node-process-environment.ts +10 -0
  214. package/src/platform-auth.ts +594 -0
  215. package/src/platform-game-analytics.ts +50 -0
  216. package/src/platform-game-app-id.ts +99 -0
  217. package/src/platform-game-media.ts +209 -0
  218. package/src/platform-games.ts +217 -0
  219. package/src/policy-artifact-contract.ts +52 -0
  220. package/src/policy-artifacts.ts +134 -0
  221. package/src/process-scope-admission.ts +50 -0
  222. package/src/process-scope-protocol.ts +66 -0
  223. package/src/process-scope.ts +327 -0
  224. package/src/quality.ts +82 -0
  225. package/src/release.ts +1683 -0
  226. package/src/rooms-check-fleet.ts +194 -0
  227. package/src/rooms-check-link.ts +138 -0
  228. package/src/rooms-check-protocol.ts +244 -0
  229. package/src/rooms-check.ts +797 -0
  230. package/src/runtime-owner-protocol.ts +218 -0
  231. package/src/source-tree-contract.ts +70 -0
  232. package/src/source-tree.ts +84 -0
  233. package/src/test-profile-process.ts +153 -0
  234. package/src/test-profile-protocol.ts +116 -0
  235. package/src/testing.ts +430 -0
  236. package/src/tooling/declaration-hook.ts +52 -0
  237. package/src/tooling/describe-game.ts +49 -0
  238. package/src/tooling/game-session-broker.ts +7 -0
  239. package/src/tooling/hold-runtime-host.ts +441 -0
  240. package/src/tooling/list-visual-scenarios.ts +21 -0
  241. package/src/tooling/load-game.ts +79 -0
  242. package/src/tooling/managed-dev-supervisor.ts +71 -0
  243. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  244. package/src/tooling/process-scope-guard.ts +213 -0
  245. package/src/tooling/process-scope-windows.ps1 +148 -0
  246. package/src/tooling/rooms-check-device.ts +493 -0
  247. package/src/tooling/run-headless-room.ts +326 -0
  248. package/src/tooling/run-test-profile.ts +190 -0
  249. package/src/tooling/run-visual-capture.ts +231 -0
  250. package/src/tooling/runtime-owner-actions.ts +65 -0
  251. package/src/tooling/seal-game-build.ts +118 -0
  252. package/src/tooling/visual-pack.ts +11 -0
  253. package/src/types.ts +928 -0
  254. package/src/visual.ts +296 -0
  255. package/src/windows-process-scopes.ts +189 -0
  256. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,594 @@
1
+ import {
2
+ type PlatformMachineErrorCode,
3
+ platformMachineApiErrorSchema,
4
+ platformMachineDevicePollResultSchema,
5
+ platformMachineDeviceStartResultSchema,
6
+ platformMachineLogoutResultSchema,
7
+ platformMachineMeResultSchema,
8
+ platformMachineProfileInputSchema,
9
+ platformMachineRevokeSessionInputSchema,
10
+ platformMachineSessionSchema,
11
+ platformMachineSessionsResultSchema,
12
+ platformMachineUserSchema,
13
+ } from "@air-jam/sdk/platform-machine";
14
+ import { randomUUID } from "node:crypto";
15
+ import {
16
+ chmod,
17
+ mkdir,
18
+ readFile,
19
+ rename,
20
+ rm,
21
+ writeFile,
22
+ } from "node:fs/promises";
23
+ import { isIP } from "node:net";
24
+ import os from "node:os";
25
+ import path from "node:path";
26
+ import lockfile from "proper-lockfile";
27
+ import { z } from "zod";
28
+ import type {
29
+ AirJamPlatformAuthStatus,
30
+ AirJamPlatformMachineSessionStore,
31
+ GetPlatformMachineProfileOptions,
32
+ LoginPlatformWithDeviceFlowOptions,
33
+ LogoutPlatformMachineSessionOptions,
34
+ PollPlatformDeviceAuthorizationOptions,
35
+ StartPlatformDeviceAuthorizationOptions,
36
+ } from "./types.js";
37
+
38
+ export type {
39
+ AirJamPlatformAuthStatus,
40
+ AirJamPlatformMachineSessionStore,
41
+ GetPlatformMachineProfileOptions,
42
+ LoginPlatformWithDeviceFlowOptions,
43
+ LogoutPlatformMachineSessionOptions,
44
+ PollPlatformDeviceAuthorizationOptions,
45
+ StartPlatformDeviceAuthorizationOptions,
46
+ } from "./types.js";
47
+
48
+ const LOCAL_PLATFORM_FALLBACK = "http://localhost:3000";
49
+
50
+ export const resolveAirJamStateDirectory = (): string => {
51
+ const configured = process.env.AIRJAM_STATE_DIR?.trim();
52
+ if (!configured) return path.join(os.homedir(), ".airjam");
53
+ if (!path.isAbsolute(configured)) {
54
+ throw new Error("AIRJAM_STATE_DIR must be an absolute path.");
55
+ }
56
+ return path.normalize(configured);
57
+ };
58
+
59
+ const resolvePlatformAuthDirectory = () =>
60
+ path.join(resolveAirJamStateDirectory(), "auth");
61
+
62
+ const resolvePlatformAuthFile = () =>
63
+ path.join(resolvePlatformAuthDirectory(), "platform-session.json");
64
+
65
+ const storedPlatformSessionFields = z.object({
66
+ platformBaseUrl: z.string().url(),
67
+ clientName: z.string().nullable(),
68
+ storedAt: z.string().min(1),
69
+ user: platformMachineUserSchema,
70
+ });
71
+
72
+ export const storedPlatformSessionSchema = storedPlatformSessionFields.extend({
73
+ version: z.literal(2),
74
+ session: platformMachineSessionSchema,
75
+ });
76
+
77
+ // Read the former credential only to exchange it through the refresh endpoint.
78
+ const legacyStoredPlatformSessionSchema = storedPlatformSessionFields.extend({
79
+ version: z.literal(1),
80
+ session: platformMachineSessionSchema.omit({
81
+ refreshToken: true,
82
+ refreshExpiresAt: true,
83
+ }),
84
+ });
85
+
86
+ const readableStoredPlatformSessionSchema = z.discriminatedUnion("version", [
87
+ storedPlatformSessionSchema,
88
+ legacyStoredPlatformSessionSchema,
89
+ ]);
90
+
91
+ const withPlatformSessionLock = async <T>(
92
+ operation: () => Promise<T>,
93
+ ): Promise<T> => {
94
+ await mkdir(resolvePlatformAuthDirectory(), { recursive: true, mode: 0o700 });
95
+ const release = await lockfile.lock(resolvePlatformAuthFile(), {
96
+ realpath: false,
97
+ retries: { retries: 10, minTimeout: 50, maxTimeout: 1000 },
98
+ });
99
+ try {
100
+ return await operation();
101
+ } finally {
102
+ await release();
103
+ }
104
+ };
105
+
106
+ export class AirJamPlatformApiError extends Error {
107
+ readonly code: PlatformMachineErrorCode;
108
+ readonly status: number;
109
+ readonly details: Record<string, unknown> | undefined;
110
+ readonly retryAfterSeconds: number | null;
111
+
112
+ constructor({
113
+ code,
114
+ message,
115
+ status,
116
+ details,
117
+ retryAfterSeconds = null,
118
+ }: {
119
+ code: PlatformMachineErrorCode;
120
+ message: string;
121
+ status: number;
122
+ details?: Record<string, unknown>;
123
+ retryAfterSeconds?: number | null;
124
+ }) {
125
+ super(message);
126
+ this.name = "AirJamPlatformApiError";
127
+ this.code = code;
128
+ this.status = status;
129
+ this.details = details;
130
+ this.retryAfterSeconds = retryAfterSeconds;
131
+ }
132
+ }
133
+
134
+ export class AirJamStoredPlatformSessionError extends Error {
135
+ readonly storagePath: string;
136
+
137
+ constructor(storagePath: string, cause: unknown) {
138
+ super(`The stored Air Jam platform session is unreadable: ${storagePath}`, {
139
+ cause,
140
+ });
141
+ this.name = "AirJamStoredPlatformSessionError";
142
+ this.storagePath = storagePath;
143
+ }
144
+ }
145
+
146
+ const parsePlatformUrl = (rawUrl: string): URL => {
147
+ const trimmed = rawUrl.trim();
148
+ let url: URL;
149
+ try {
150
+ if (!trimmed) throw new Error("Empty URL");
151
+ const hasScheme = /^[a-z][a-z\d+.-]*:/iu.test(trimmed);
152
+ const hasHostPort = /^[^/?#]+:\d+(?:[/?#]|$)/u.test(trimmed);
153
+ if (
154
+ hasScheme &&
155
+ !hasHostPort &&
156
+ !/^[a-z][a-z\d+.-]*:\/\//iu.test(trimmed)
157
+ ) {
158
+ throw new Error("Invalid URL scheme");
159
+ }
160
+ url = new URL(hasScheme && !hasHostPort ? trimmed : `https://${trimmed}`);
161
+ } catch {
162
+ throw new Error("Invalid Air Jam platform URL.");
163
+ }
164
+
165
+ const loopback =
166
+ url.hostname === "localhost" ||
167
+ url.hostname === "[::1]" ||
168
+ (isIP(url.hostname) === 4 && url.hostname.startsWith("127."));
169
+ if (
170
+ (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) ||
171
+ url.username ||
172
+ url.password
173
+ ) {
174
+ throw new Error(
175
+ "Air Jam platform URLs require HTTPS, except HTTP on loopback, and must not contain credentials.",
176
+ );
177
+ }
178
+ return url;
179
+ };
180
+
181
+ export const resolvePlatformBaseUrl = (
182
+ value: string | undefined = process.env.AIRJAM_PLATFORM_URL,
183
+ ): string => {
184
+ const candidate =
185
+ value ??
186
+ process.env.AIR_JAM_PLATFORM_URL ??
187
+ process.env.NEXT_PUBLIC_AIR_JAM_PUBLIC_HOST ??
188
+ process.env.NEXT_PUBLIC_APP_URL ??
189
+ LOCAL_PLATFORM_FALLBACK;
190
+
191
+ return parsePlatformUrl(candidate).toString().replace(/\/$/, "");
192
+ };
193
+
194
+ const sleep = async (durationMs: number) =>
195
+ new Promise((resolve) => setTimeout(resolve, durationMs));
196
+
197
+ export const requestPlatformMachineApi = async <T>({
198
+ baseUrl,
199
+ pathname,
200
+ method = "GET",
201
+ body,
202
+ token,
203
+ schema,
204
+ }: {
205
+ baseUrl: string;
206
+ pathname: string;
207
+ method?: "GET" | "POST" | "PATCH";
208
+ body?: unknown;
209
+ token?: string;
210
+ schema: { parse: (value: unknown) => T };
211
+ }): Promise<T> => {
212
+ const platformUrl = parsePlatformUrl(baseUrl);
213
+ const requestUrl = new URL(pathname, platformUrl);
214
+ if (
215
+ requestUrl.origin !== platformUrl.origin ||
216
+ requestUrl.username ||
217
+ requestUrl.password
218
+ ) {
219
+ throw new Error(
220
+ "Platform agent API requests must stay on the platform origin.",
221
+ );
222
+ }
223
+ const response = await fetch(requestUrl, {
224
+ method,
225
+ // Redirects can replay device codes or credentials, even on the same origin.
226
+ redirect: "error",
227
+ headers: {
228
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
229
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
230
+ },
231
+ body: body === undefined ? undefined : JSON.stringify(body),
232
+ });
233
+
234
+ const payload = (await response.json().catch(() => null)) as unknown;
235
+
236
+ if (!response.ok) {
237
+ const parsedError = platformMachineApiErrorSchema.safeParse(payload);
238
+ if (parsedError.success) {
239
+ throw new AirJamPlatformApiError({
240
+ code: parsedError.data.error,
241
+ message:
242
+ parsedError.data.error === "invalid_token"
243
+ ? `${parsedError.data.message} Run airjam auth login to sign in again.`
244
+ : parsedError.data.message,
245
+ status: response.status,
246
+ details: parsedError.data.details,
247
+ retryAfterSeconds: parsedError.data.retryAfterSeconds,
248
+ });
249
+ }
250
+
251
+ throw new AirJamPlatformApiError({
252
+ code: "invalid_request",
253
+ message: `Platform agent API request failed: ${response.status}`,
254
+ status: response.status,
255
+ });
256
+ }
257
+
258
+ return schema.parse(payload);
259
+ };
260
+
261
+ export const readStoredPlatformMachineSession = async () => {
262
+ const storagePath = resolvePlatformAuthFile();
263
+ let source: string;
264
+ try {
265
+ source = await readFile(storagePath, "utf8");
266
+ } catch (error) {
267
+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
268
+ return null;
269
+ }
270
+ throw error;
271
+ }
272
+
273
+ try {
274
+ return readableStoredPlatformSessionSchema.parse(
275
+ JSON.parse(source) as unknown,
276
+ );
277
+ } catch (error) {
278
+ throw new AirJamStoredPlatformSessionError(storagePath, error);
279
+ }
280
+ };
281
+
282
+ export const writeStoredPlatformMachineSession = async (
283
+ value: AirJamPlatformMachineSessionStore,
284
+ ): Promise<void> => {
285
+ const authDirectory = resolvePlatformAuthDirectory();
286
+ const storagePath = resolvePlatformAuthFile();
287
+ const temporaryPath = `${storagePath}.tmp-${process.pid}-${randomUUID()}`;
288
+ await mkdir(authDirectory, { recursive: true, mode: 0o700 });
289
+ await chmod(authDirectory, 0o700);
290
+ try {
291
+ await writeFile(
292
+ temporaryPath,
293
+ `${JSON.stringify(storedPlatformSessionSchema.parse(value), null, 2)}\n`,
294
+ { encoding: "utf8", flag: "wx", mode: 0o600 },
295
+ );
296
+ await rename(temporaryPath, storagePath);
297
+ await chmod(storagePath, 0o600);
298
+ } finally {
299
+ await rm(temporaryPath, { force: true });
300
+ }
301
+ };
302
+
303
+ export const clearStoredPlatformMachineSession = async (): Promise<void> => {
304
+ await rm(resolvePlatformAuthFile(), { force: true });
305
+ };
306
+
307
+ export const startPlatformDeviceAuthorization = async ({
308
+ platformUrl,
309
+ clientName,
310
+ }: StartPlatformDeviceAuthorizationOptions = {}) =>
311
+ requestPlatformMachineApi({
312
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
313
+ pathname: "/api/cli/auth/device/start",
314
+ method: "POST",
315
+ body: {
316
+ ...(clientName?.trim() ? { clientName: clientName.trim() } : {}),
317
+ },
318
+ schema: platformMachineDeviceStartResultSchema,
319
+ });
320
+
321
+ export const pollPlatformDeviceAuthorization = async ({
322
+ platformUrl,
323
+ deviceCode,
324
+ }: PollPlatformDeviceAuthorizationOptions) =>
325
+ requestPlatformMachineApi({
326
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
327
+ pathname: "/api/cli/auth/device/poll",
328
+ method: "POST",
329
+ body: {
330
+ deviceCode,
331
+ },
332
+ schema: platformMachineDevicePollResultSchema,
333
+ });
334
+
335
+ export const loginPlatformWithDeviceFlow = async ({
336
+ platformUrl,
337
+ clientName,
338
+ onPrompt,
339
+ }: LoginPlatformWithDeviceFlowOptions = {}) => {
340
+ const baseUrl = resolvePlatformBaseUrl(platformUrl);
341
+ const authorization = await startPlatformDeviceAuthorization({
342
+ platformUrl: baseUrl,
343
+ clientName,
344
+ });
345
+
346
+ await onPrompt?.(authorization);
347
+
348
+ const expiresAtMs = Date.parse(authorization.expiresAt);
349
+ let intervalSeconds = authorization.intervalSeconds;
350
+ while (Date.now() < expiresAtMs) {
351
+ await sleep(intervalSeconds * 1000);
352
+ if (Date.now() >= expiresAtMs) break;
353
+
354
+ try {
355
+ const authenticated = await pollPlatformDeviceAuthorization({
356
+ platformUrl: baseUrl,
357
+ deviceCode: authorization.deviceCode,
358
+ });
359
+
360
+ if (
361
+ parsePlatformUrl(authenticated.platformBaseUrl).origin !==
362
+ parsePlatformUrl(baseUrl).origin
363
+ ) {
364
+ throw new Error(
365
+ "The login response does not match the requested platform origin.",
366
+ );
367
+ }
368
+ const storedSession: AirJamPlatformMachineSessionStore = {
369
+ version: 2,
370
+ platformBaseUrl: baseUrl,
371
+ clientName: clientName?.trim() || null,
372
+ storedAt: new Date().toISOString(),
373
+ user: authenticated.user,
374
+ session: authenticated.session,
375
+ };
376
+
377
+ await withPlatformSessionLock(() =>
378
+ writeStoredPlatformMachineSession(storedSession),
379
+ );
380
+
381
+ return {
382
+ authorization,
383
+ authenticated,
384
+ storedSession,
385
+ };
386
+ } catch (error) {
387
+ if (error instanceof AirJamPlatformApiError) {
388
+ if (error.code === "slow_down") {
389
+ intervalSeconds += 5;
390
+ continue;
391
+ }
392
+ if (error.code === "authorization_pending") continue;
393
+ }
394
+
395
+ throw error;
396
+ }
397
+ }
398
+
399
+ throw new AirJamPlatformApiError({
400
+ code: "expired_token",
401
+ message: "The Air Jam CLI login expired before it was approved.",
402
+ status: 410,
403
+ });
404
+ };
405
+
406
+ const resolvePlatformMachineAuthUnlocked = async ({
407
+ platformUrl,
408
+ token,
409
+ }: {
410
+ platformUrl?: string;
411
+ token?: string;
412
+ }) => {
413
+ if (token?.trim()) {
414
+ return {
415
+ baseUrl: resolvePlatformBaseUrl(platformUrl),
416
+ token: token.trim(),
417
+ };
418
+ }
419
+
420
+ let stored = await readStoredPlatformMachineSession();
421
+ if (!stored) {
422
+ throw new Error(
423
+ "No stored Air Jam platform session was found. Run airjam auth login to sign in.",
424
+ );
425
+ }
426
+ const baseUrl = resolvePlatformBaseUrl(platformUrl ?? stored.platformBaseUrl);
427
+ if (
428
+ parsePlatformUrl(baseUrl).origin !==
429
+ parsePlatformUrl(stored.platformBaseUrl).origin
430
+ ) {
431
+ throw new Error(
432
+ "The stored Air Jam session belongs to a different platform origin. Log in to that platform or supply an explicit token.",
433
+ );
434
+ }
435
+ if (
436
+ stored.version === 1 ||
437
+ Date.parse(stored.session.expiresAt) <= Date.now() + 30_000
438
+ ) {
439
+ const authenticated = await requestPlatformMachineApi({
440
+ baseUrl,
441
+ pathname: "/api/cli/auth/refresh",
442
+ method: "POST",
443
+ body: {
444
+ refreshToken:
445
+ stored.version === 1
446
+ ? stored.session.token
447
+ : stored.session.refreshToken,
448
+ },
449
+ schema: platformMachineDevicePollResultSchema,
450
+ });
451
+ if (
452
+ parsePlatformUrl(authenticated.platformBaseUrl).origin !==
453
+ parsePlatformUrl(baseUrl).origin
454
+ ) {
455
+ throw new Error(
456
+ "The refresh response does not match the requested platform origin.",
457
+ );
458
+ }
459
+ stored = {
460
+ ...stored,
461
+ version: 2,
462
+ user: authenticated.user,
463
+ session: authenticated.session,
464
+ storedAt: new Date().toISOString(),
465
+ };
466
+ await writeStoredPlatformMachineSession(stored);
467
+ }
468
+ return { baseUrl, token: stored.session.token };
469
+ };
470
+
471
+ export const resolvePlatformMachineAuth = async (options: {
472
+ platformUrl?: string;
473
+ token?: string;
474
+ }) =>
475
+ options.token?.trim()
476
+ ? resolvePlatformMachineAuthUnlocked(options)
477
+ : withPlatformSessionLock(() =>
478
+ resolvePlatformMachineAuthUnlocked(options),
479
+ );
480
+
481
+ export const listPlatformMachineSessions = async (
482
+ options: GetPlatformMachineProfileOptions = {},
483
+ ) => {
484
+ const resolved = await resolvePlatformMachineAuth(options);
485
+ return requestPlatformMachineApi({
486
+ baseUrl: resolved.baseUrl,
487
+ pathname: "/api/cli/auth/sessions",
488
+ token: resolved.token,
489
+ schema: platformMachineSessionsResultSchema,
490
+ });
491
+ };
492
+
493
+ export const revokePlatformMachineSession = async (
494
+ options: GetPlatformMachineProfileOptions & { id: string },
495
+ ) => {
496
+ const resolved = await resolvePlatformMachineAuth(options);
497
+ return requestPlatformMachineApi({
498
+ baseUrl: resolved.baseUrl,
499
+ pathname: "/api/cli/auth/sessions/revoke",
500
+ method: "POST",
501
+ token: resolved.token,
502
+ body: platformMachineRevokeSessionInputSchema.parse(options),
503
+ schema: platformMachineLogoutResultSchema,
504
+ });
505
+ };
506
+
507
+ export const getPlatformMachineProfile = async ({
508
+ platformUrl,
509
+ token,
510
+ }: GetPlatformMachineProfileOptions = {}) => {
511
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
512
+ return requestPlatformMachineApi({
513
+ baseUrl: resolved.baseUrl,
514
+ pathname: "/api/cli/auth/me",
515
+ token: resolved.token,
516
+ schema: platformMachineMeResultSchema,
517
+ });
518
+ };
519
+
520
+ export const updatePlatformMachineProfile = async ({
521
+ platformUrl,
522
+ token,
523
+ displayName,
524
+ }: GetPlatformMachineProfileOptions & { displayName: string }) => {
525
+ const input = platformMachineProfileInputSchema.parse({ displayName });
526
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
527
+ return requestPlatformMachineApi({
528
+ baseUrl: resolved.baseUrl,
529
+ pathname: "/api/cli/auth/profile",
530
+ method: "POST",
531
+ token: resolved.token,
532
+ body: input,
533
+ schema: platformMachineUserSchema,
534
+ });
535
+ };
536
+
537
+ export const logoutPlatformMachineSession = async ({
538
+ platformUrl,
539
+ token,
540
+ }: LogoutPlatformMachineSessionOptions = {}) => {
541
+ return withPlatformSessionLock(async () => {
542
+ const resolved = await resolvePlatformMachineAuthUnlocked({
543
+ platformUrl,
544
+ token,
545
+ });
546
+ const result = await requestPlatformMachineApi({
547
+ baseUrl: resolved.baseUrl,
548
+ pathname: "/api/cli/auth/logout",
549
+ method: "POST",
550
+ token: resolved.token,
551
+ schema: platformMachineLogoutResultSchema,
552
+ });
553
+ if (!token) await clearStoredPlatformMachineSession();
554
+ return result;
555
+ });
556
+ };
557
+
558
+ export const getPlatformMachineAuthStatus =
559
+ async (): Promise<AirJamPlatformAuthStatus> => {
560
+ const stored = await readStoredPlatformMachineSession();
561
+
562
+ if (!stored) {
563
+ return {
564
+ authenticated: false,
565
+ storagePath: resolvePlatformAuthFile(),
566
+ platformBaseUrl: null,
567
+ clientName: null,
568
+ storedAt: null,
569
+ user: null,
570
+ session: null,
571
+ };
572
+ }
573
+
574
+ return {
575
+ authenticated: true,
576
+ storagePath: resolvePlatformAuthFile(),
577
+ platformBaseUrl: stored.platformBaseUrl,
578
+ clientName: stored.clientName,
579
+ storedAt: stored.storedAt,
580
+ user: stored.user,
581
+ session: {
582
+ id: stored.session.id,
583
+ expiresAt: stored.session.expiresAt,
584
+ refreshExpiresAt:
585
+ stored.version === 1
586
+ ? stored.session.expiresAt
587
+ : stored.session.refreshExpiresAt,
588
+ createdAt: stored.session.createdAt,
589
+ userAgent: stored.session.userAgent,
590
+ },
591
+ };
592
+ };
593
+
594
+ export const getPlatformAuthStoragePath = () => resolvePlatformAuthFile();
@@ -0,0 +1,50 @@
1
+ import {
2
+ platformMachineGameAnalyticsOverviewInputSchema,
3
+ platformMachineGameAnalyticsOverviewSchema,
4
+ platformMachineGameAnalyticsSessionsInputSchema,
5
+ platformMachineGameAnalyticsSessionsSchema,
6
+ } from "@air-jam/sdk/platform-machine";
7
+ import {
8
+ requestPlatformMachineApi,
9
+ resolvePlatformMachineAuth,
10
+ } from "./platform-auth.js";
11
+
12
+ type GameAnalyticsOptions = {
13
+ platformUrl?: string;
14
+ token?: string;
15
+ slugOrId: string;
16
+ };
17
+
18
+ export const getPlatformGameAnalyticsOverview = async ({
19
+ platformUrl,
20
+ token,
21
+ slugOrId,
22
+ days,
23
+ }: GameAnalyticsOptions & { days?: number }) => {
24
+ const input = platformMachineGameAnalyticsOverviewInputSchema.parse({ days });
25
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
26
+ return requestPlatformMachineApi({
27
+ baseUrl: resolved.baseUrl,
28
+ pathname: `/api/cli/games/${encodeURIComponent(slugOrId)}/analytics?days=${input.days}`,
29
+ token: resolved.token,
30
+ schema: platformMachineGameAnalyticsOverviewSchema,
31
+ });
32
+ };
33
+
34
+ export const getPlatformGameAnalyticsSessions = async ({
35
+ platformUrl,
36
+ token,
37
+ slugOrId,
38
+ limit,
39
+ }: GameAnalyticsOptions & { limit?: number }) => {
40
+ const input = platformMachineGameAnalyticsSessionsInputSchema.parse({
41
+ limit,
42
+ });
43
+ const resolved = await resolvePlatformMachineAuth({ platformUrl, token });
44
+ return requestPlatformMachineApi({
45
+ baseUrl: resolved.baseUrl,
46
+ pathname: `/api/cli/games/${encodeURIComponent(slugOrId)}/analytics/sessions?limit=${input.limit}`,
47
+ token: resolved.token,
48
+ schema: platformMachineGameAnalyticsSessionsSchema,
49
+ });
50
+ };