@dreamboard-games/cli 0.1.30-alpha.3 → 0.1.30-alpha.31

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 (173) hide show
  1. package/README.md +27 -108
  2. package/dist/agent-verifier/agent-workspace-verifier.mjs +1988 -57
  3. package/dist/agent-verifier/agent-workspace-verifier.mjs.map +1 -1
  4. package/dist/agent-verifier/{chunk-XQXDOBYB.mjs → chunk-4I2WWAPK.mjs} +27 -10
  5. package/dist/agent-verifier/chunk-4I2WWAPK.mjs.map +1 -0
  6. package/dist/agent-verifier/{chunk-O4YCPU7C.mjs → chunk-BWBN2TDJ.mjs} +539 -641
  7. package/dist/agent-verifier/chunk-BWBN2TDJ.mjs.map +1 -0
  8. package/dist/agent-verifier/{chunk-TAEQKBJB.mjs → chunk-GWRZRWCF.mjs} +1 -1
  9. package/dist/agent-verifier/chunk-GWRZRWCF.mjs.map +1 -0
  10. package/dist/agent-verifier/chunk-H6XDQJ3N.mjs +11 -0
  11. package/dist/agent-verifier/chunk-HUBV22JQ.mjs +89 -0
  12. package/dist/agent-verifier/chunk-HUBV22JQ.mjs.map +1 -0
  13. package/dist/agent-verifier/{chunk-VS573ERH.mjs → chunk-JZTH3EMV.mjs} +2 -2
  14. package/dist/agent-verifier/{chunk-XGWCY624.mjs → chunk-KDAQ4CZY.mjs} +34 -27
  15. package/dist/agent-verifier/chunk-KDAQ4CZY.mjs.map +1 -0
  16. package/dist/agent-verifier/{chunk-IAYRNVUC.mjs → chunk-LMW66VBH.mjs} +2 -13
  17. package/dist/agent-verifier/{chunk-IAYRNVUC.mjs.map → chunk-LMW66VBH.mjs.map} +1 -1
  18. package/dist/agent-verifier/{chunk-776W3UGV.mjs → chunk-M6YNQZCC.mjs} +4 -13
  19. package/dist/agent-verifier/chunk-M6YNQZCC.mjs.map +1 -0
  20. package/dist/agent-verifier/{chunk-H76MT5UR.mjs → chunk-M7UVBANQ.mjs} +2 -1
  21. package/dist/agent-verifier/chunk-M7UVBANQ.mjs.map +1 -0
  22. package/dist/agent-verifier/{chunk-SH5JKYOB.mjs → chunk-MIRGCMUC.mjs} +112 -26
  23. package/dist/agent-verifier/chunk-MIRGCMUC.mjs.map +1 -0
  24. package/dist/agent-verifier/{chunk-NAK77WXW.mjs → chunk-MYMVXTZT.mjs} +4 -5
  25. package/dist/agent-verifier/chunk-MYMVXTZT.mjs.map +1 -0
  26. package/dist/agent-verifier/{chunk-7WWGFAAU.mjs → chunk-NBRUEJUK.mjs} +215 -223
  27. package/dist/agent-verifier/chunk-NBRUEJUK.mjs.map +1 -0
  28. package/dist/agent-verifier/chunk-OJFZVGEL.mjs +492 -0
  29. package/dist/agent-verifier/chunk-OJFZVGEL.mjs.map +1 -0
  30. package/dist/agent-verifier/{chunk-LUZ7KE6H.mjs → chunk-QD4SQNUP.mjs} +4 -8
  31. package/dist/agent-verifier/{chunk-LUZ7KE6H.mjs.map → chunk-QD4SQNUP.mjs.map} +1 -1
  32. package/dist/agent-verifier/chunk-TTB7AIHZ.mjs +214 -0
  33. package/dist/agent-verifier/chunk-TTB7AIHZ.mjs.map +1 -0
  34. package/dist/agent-verifier/{chunk-F2DIOJJZ.mjs → chunk-XCQQIPCO.mjs} +5 -46
  35. package/dist/agent-verifier/chunk-XCQQIPCO.mjs.map +1 -0
  36. package/dist/agent-verifier/{global-config-Y2NTSK4R.mjs → global-config-2NUESNEQ.mjs} +6 -6
  37. package/dist/agent-verifier/{keychain-backend-SPQWGKZN.mjs → keychain-backend-FF4I6ODB.mjs} +12 -7
  38. package/dist/agent-verifier/keychain-backend-FF4I6ODB.mjs.map +1 -0
  39. package/dist/agent-verifier/{local-files-JFOQQZDL.mjs → local-files-OF4QFISU.mjs} +10 -10
  40. package/dist/agent-verifier/{chunk-UIOLGH4A.mjs → local-typecheck-DHVLM37Z.mjs} +4 -4
  41. package/dist/agent-verifier/local-typecheck-DHVLM37Z.mjs.map +1 -0
  42. package/dist/agent-verifier/{materialize-workspace-ZAVGQQSF.mjs → materialize-workspace-MAGKDMK5.mjs} +23 -22
  43. package/dist/agent-verifier/materialize-workspace-MAGKDMK5.mjs.map +1 -0
  44. package/dist/agent-verifier/{project-state-K576C2TE.mjs → project-state-XKUSCFSV.mjs} +2 -2
  45. package/dist/agent-verifier/{prompt-MJRJMOGQ.mjs → prompt-VKHMCQT6.mjs} +2 -2
  46. package/dist/agent-verifier/{chunk-A64ZZUZV.mjs → reducer-bundle-preflight-GLUJKTWU.mjs} +76 -25
  47. package/dist/agent-verifier/reducer-bundle-preflight-GLUJKTWU.mjs.map +1 -0
  48. package/dist/agent-verifier/{chunk-JGT4P4UD.mjs → reducer-contract-preflight-WVQQPW5F.mjs} +7 -6
  49. package/dist/agent-verifier/reducer-contract-preflight-WVQQPW5F.mjs.map +1 -0
  50. package/dist/agent-verifier/{chunk-E7SSWJXJ.mjs → reducer-native-test-harness-UFMSNNDY.mjs} +463 -686
  51. package/dist/agent-verifier/reducer-native-test-harness-UFMSNNDY.mjs.map +1 -0
  52. package/dist/agent-verifier/static-scaffold-CLRRWXON.mjs +24 -0
  53. package/dist/agent-verifier/workspace-codegen-SPPVHURX.mjs +10 -0
  54. package/dist/agent-verifier/{workspace-dependencies-NOOQBK6I.mjs → workspace-dependencies-5HEEKZFP.mjs} +6 -4
  55. package/dist/authoring-compatibility-internal.js +12 -0
  56. package/dist/chunk-2H7UOFLK.js +11 -0
  57. package/dist/chunk-6NYVJYN4.js +313 -0
  58. package/dist/chunk-6NYVJYN4.js.map +1 -0
  59. package/dist/chunk-EQNBQVIW.js +204 -0
  60. package/dist/chunk-EQNBQVIW.js.map +1 -0
  61. package/dist/chunk-X244CUU4.js +3815 -0
  62. package/dist/chunk-X244CUU4.js.map +1 -0
  63. package/dist/{chunk-TAQKH67O.js → chunk-YNJVKC2T.js} +2587 -7278
  64. package/dist/chunk-YNJVKC2T.js.map +1 -0
  65. package/dist/{global-config-S4ZIPECE.js → global-config-RBMW7IVA.js} +4 -3
  66. package/dist/index.js +3099 -6187
  67. package/dist/index.js.map +1 -1
  68. package/dist/internal.js +36 -10
  69. package/dist/internal.js.map +1 -1
  70. package/dist/{keychain-backend-HDF4TZDL.js → keychain-backend-FSNTNTZE.js} +12 -7
  71. package/dist/keychain-backend-FSNTNTZE.js.map +1 -0
  72. package/dist/{prompt-NDV3AE5L.js → prompt-GMZABCJC.js} +2 -2
  73. package/package.json +9 -19
  74. package/release/authoring-release-set.json +38 -0
  75. package/skills/dreamboard/SKILL.md +30 -28
  76. package/skills/dreamboard/references/building-your-first-game.md +15 -15
  77. package/skills/dreamboard/references/cli.md +46 -47
  78. package/skills/dreamboard/references/manifest-authoring.md +11 -3
  79. package/skills/dreamboard/references/quickstart.md +16 -13
  80. package/skills/dreamboard/references/testing.md +6 -13
  81. package/dist/agent-verifier/chunk-3UKQVWLV.mjs +0 -1744
  82. package/dist/agent-verifier/chunk-3UKQVWLV.mjs.map +0 -1
  83. package/dist/agent-verifier/chunk-776W3UGV.mjs.map +0 -1
  84. package/dist/agent-verifier/chunk-7WWGFAAU.mjs.map +0 -1
  85. package/dist/agent-verifier/chunk-A64ZZUZV.mjs.map +0 -1
  86. package/dist/agent-verifier/chunk-E7SSWJXJ.mjs.map +0 -1
  87. package/dist/agent-verifier/chunk-F2DIOJJZ.mjs.map +0 -1
  88. package/dist/agent-verifier/chunk-G42BGGG2.mjs +0 -70
  89. package/dist/agent-verifier/chunk-G42BGGG2.mjs.map +0 -1
  90. package/dist/agent-verifier/chunk-H76MT5UR.mjs.map +0 -1
  91. package/dist/agent-verifier/chunk-HGMUAL33.mjs +0 -39
  92. package/dist/agent-verifier/chunk-HGMUAL33.mjs.map +0 -1
  93. package/dist/agent-verifier/chunk-JGT4P4UD.mjs.map +0 -1
  94. package/dist/agent-verifier/chunk-NAK77WXW.mjs.map +0 -1
  95. package/dist/agent-verifier/chunk-O4YCPU7C.mjs.map +0 -1
  96. package/dist/agent-verifier/chunk-S34FRJHS.mjs +0 -222
  97. package/dist/agent-verifier/chunk-S34FRJHS.mjs.map +0 -1
  98. package/dist/agent-verifier/chunk-SH5JKYOB.mjs.map +0 -1
  99. package/dist/agent-verifier/chunk-SKI2ESE5.mjs +0 -44
  100. package/dist/agent-verifier/chunk-TAEQKBJB.mjs.map +0 -1
  101. package/dist/agent-verifier/chunk-UIOLGH4A.mjs.map +0 -1
  102. package/dist/agent-verifier/chunk-UIZNWRM6.mjs +0 -2432
  103. package/dist/agent-verifier/chunk-UIZNWRM6.mjs.map +0 -1
  104. package/dist/agent-verifier/chunk-W3N3QJ4V.mjs +0 -624
  105. package/dist/agent-verifier/chunk-W3N3QJ4V.mjs.map +0 -1
  106. package/dist/agent-verifier/chunk-XGWCY624.mjs.map +0 -1
  107. package/dist/agent-verifier/chunk-XQXDOBYB.mjs.map +0 -1
  108. package/dist/agent-verifier/compile-TEQVA46V.mjs +0 -312
  109. package/dist/agent-verifier/compile-TEQVA46V.mjs.map +0 -1
  110. package/dist/agent-verifier/keychain-backend-SPQWGKZN.mjs.map +0 -1
  111. package/dist/agent-verifier/local-typecheck-XVGWI75X.mjs +0 -10
  112. package/dist/agent-verifier/materialize-workspace-ZAVGQQSF.mjs.map +0 -1
  113. package/dist/agent-verifier/reducer-bundle-preflight-LXNJUBKL.mjs +0 -20
  114. package/dist/agent-verifier/reducer-contract-preflight-TUMQ43JV.mjs +0 -11
  115. package/dist/agent-verifier/reducer-native-test-harness-CHX5MBL5.mjs +0 -50
  116. package/dist/agent-verifier/static-scaffold-R7SVDRQI.mjs +0 -27
  117. package/dist/agent-verifier/sync-THAI546U.mjs +0 -588
  118. package/dist/agent-verifier/sync-THAI546U.mjs.map +0 -1
  119. package/dist/agent-verifier/test-AFAQFKOB.mjs +0 -353
  120. package/dist/agent-verifier/test-AFAQFKOB.mjs.map +0 -1
  121. package/dist/agent-verifier/workspace-codegen-2ZMQRIKJ.mjs +0 -10
  122. package/dist/agent-verifier/workspace-dependencies-NOOQBK6I.mjs.map +0 -1
  123. package/dist/chunk-N7XPNNUI.js +0 -432
  124. package/dist/chunk-N7XPNNUI.js.map +0 -1
  125. package/dist/chunk-SEGVTWSK.js +0 -44
  126. package/dist/chunk-SEGVTWSK.js.map +0 -1
  127. package/dist/chunk-TAQKH67O.js.map +0 -1
  128. package/dist/dev-host/components/drawer.tsx +0 -132
  129. package/dist/dev-host/components/input.tsx +0 -21
  130. package/dist/dev-host/dev-api-proxy-plugin.ts +0 -328
  131. package/dist/dev-host/dev-author-dom-warnings.ts +0 -100
  132. package/dist/dev-host/dev-diagnostics.ts +0 -62
  133. package/dist/dev-host/dev-fallback-stylesheet.ts +0 -53
  134. package/dist/dev-host/dev-hmr-guard-plugin.ts +0 -47
  135. package/dist/dev-host/dev-host-controller.ts +0 -674
  136. package/dist/dev-host/dev-host-player-query.ts +0 -17
  137. package/dist/dev-host/dev-host-session-transport.ts +0 -52
  138. package/dist/dev-host/dev-host-storage.ts +0 -56
  139. package/dist/dev-host/dev-log-relay-plugin.ts +0 -510
  140. package/dist/dev-host/dev-runtime-config.ts +0 -14
  141. package/dist/dev-host/dev-runtime-platform.ts +0 -335
  142. package/dist/dev-host/dev-virtual-modules-plugin.ts +0 -64
  143. package/dist/dev-host/host-main.css +0 -224
  144. package/dist/dev-host/host-main.tsx +0 -948
  145. package/dist/dev-host/index.html +0 -56
  146. package/dist/dev-host/lib/utils.ts +0 -6
  147. package/dist/dev-host/plugin-main.ts +0 -61
  148. package/dist/dev-host/plugin.html +0 -24
  149. package/dist/dev-host/shared-styles.css +0 -144
  150. package/dist/dev-host/start-dev-server.ts +0 -140
  151. package/dist/dev-host/virtual-modules.d.ts +0 -27
  152. package/dist/global-config-S4ZIPECE.js.map +0 -1
  153. package/dist/keychain-backend-HDF4TZDL.js.map +0 -1
  154. package/skills/dreamboard/scripts/events-extract.mjs +0 -218
  155. /package/dist/agent-verifier/{chunk-SKI2ESE5.mjs.map → chunk-H6XDQJ3N.mjs.map} +0 -0
  156. /package/dist/agent-verifier/{chunk-VS573ERH.mjs.map → chunk-JZTH3EMV.mjs.map} +0 -0
  157. /package/dist/agent-verifier/{global-config-Y2NTSK4R.mjs.map → global-config-2NUESNEQ.mjs.map} +0 -0
  158. /package/dist/agent-verifier/{local-files-JFOQQZDL.mjs.map → local-files-OF4QFISU.mjs.map} +0 -0
  159. /package/dist/agent-verifier/{local-typecheck-XVGWI75X.mjs.map → project-state-XKUSCFSV.mjs.map} +0 -0
  160. /package/dist/agent-verifier/{prompt-MJRJMOGQ.mjs.map → prompt-VKHMCQT6.mjs.map} +0 -0
  161. /package/dist/agent-verifier/{project-state-K576C2TE.mjs.map → static-scaffold-CLRRWXON.mjs.map} +0 -0
  162. /package/dist/agent-verifier/{reducer-bundle-preflight-LXNJUBKL.mjs.map → workspace-codegen-SPPVHURX.mjs.map} +0 -0
  163. /package/dist/agent-verifier/{reducer-contract-preflight-TUMQ43JV.mjs.map → workspace-dependencies-5HEEKZFP.mjs.map} +0 -0
  164. /package/dist/{agent-verifier/reducer-native-test-harness-CHX5MBL5.mjs.map → authoring-compatibility-internal.js.map} +0 -0
  165. /package/dist/{agent-verifier/static-scaffold-R7SVDRQI.mjs.map → chunk-2H7UOFLK.js.map} +0 -0
  166. /package/dist/{agent-verifier/workspace-codegen-2ZMQRIKJ.mjs.map → global-config-RBMW7IVA.js.map} +0 -0
  167. /package/dist/{prompt-NDV3AE5L.js.map → prompt-GMZABCJC.js.map} +0 -0
  168. /package/{dist/scaffold → scaffold}/assets/static/app/tsconfig.framework.json +0 -0
  169. /package/{dist/scaffold → scaffold}/assets/static/app/tsconfig.json +0 -0
  170. /package/{dist/scaffold → scaffold}/assets/static/ui/index.tsx +0 -0
  171. /package/{dist/scaffold → scaffold}/assets/static/ui/style.css +0 -0
  172. /package/{dist/scaffold → scaffold}/assets/static/ui/tsconfig.framework.json +0 -0
  173. /package/{dist/scaffold → scaffold}/assets/static/ui/tsconfig.json +0 -0
@@ -0,0 +1,3815 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CLIENT_PROBLEM_TYPES,
4
+ REDUCER_TESTING_TYPES_WRAPPER_CONTENT,
5
+ SERVER_PROBLEM_TYPES,
6
+ buildReducerTestingContractContent,
7
+ client,
8
+ createGameplayCapability,
9
+ createProjectSessionFromReducerSnapshot,
10
+ createRepoLocalPackageResolutionPlugin,
11
+ external_exports,
12
+ findProjectRoot,
13
+ getJob,
14
+ getProjectCompiledResult,
15
+ getSessionSnapshot,
16
+ hashContent,
17
+ listProjectCompiledResults,
18
+ loadManifest,
19
+ loadProjectConfig,
20
+ readWorkspaceTextFileIfExists,
21
+ resolveCliRepoRoot,
22
+ resolveWorkspacePath,
23
+ workspacePathExists,
24
+ writeWorkspaceJsonFile,
25
+ writeWorkspaceTextFile,
26
+ zProblemDetails
27
+ } from "./chunk-YNJVKC2T.js";
28
+ import {
29
+ getStoredSession,
30
+ loadGlobalConfig,
31
+ withCredentialLock
32
+ } from "./chunk-6NYVJYN4.js";
33
+ import {
34
+ DEFAULT_API_BASE_URL,
35
+ DEFAULT_WEB_BASE_URL,
36
+ ENVIRONMENT_CONFIGS,
37
+ PROJECT_DIR_NAME,
38
+ ensureDir,
39
+ exists
40
+ } from "./chunk-EQNBQVIW.js";
41
+
42
+ // src/build-target.ts
43
+ var injectedBuildChannel = true ? "published" : void 0;
44
+ var BUILD_CHANNEL = injectedBuildChannel === "published" ? "published" : "development";
45
+ var IS_PUBLISHED_BUILD = BUILD_CHANNEL === "published";
46
+ var PUBLISHED_ENVIRONMENT = "prod";
47
+
48
+ // src/auth/refresh-error.ts
49
+ function classifyRefreshError(error) {
50
+ const message = error.message?.toLowerCase() ?? "";
51
+ if (error.status === 400 || error.status === 401 || message.includes("invalid_grant") || message.includes("refresh token") || message.includes("expired") || message.includes("revoked")) {
52
+ return { kind: "permanent_invalid", reason: error.message };
53
+ }
54
+ if (error.status === 408 || error.status === 429 || typeof error.status === "number" && error.status >= 500 || message.includes("timeout") || message.includes("network") || message.includes("fetch failed")) {
55
+ return { kind: "transient", reason: error.message };
56
+ }
57
+ return { kind: "unknown", reason: error.message };
58
+ }
59
+
60
+ // src/auth/clerk-oauth.ts
61
+ import crypto from "crypto";
62
+ function createPkcePair() {
63
+ const verifier = base64Url(crypto.randomBytes(32));
64
+ const challenge = base64Url(
65
+ crypto.createHash("sha256").update(verifier).digest()
66
+ );
67
+ return { verifier, challenge };
68
+ }
69
+ function buildClerkAuthorizationUrl(input) {
70
+ const { issuer, clientId, scope } = assertConfigured(input.config);
71
+ const url = new URL("/oauth/authorize", issuer);
72
+ url.searchParams.set("response_type", "code");
73
+ url.searchParams.set("client_id", clientId);
74
+ url.searchParams.set("redirect_uri", input.redirectUri);
75
+ url.searchParams.set("state", input.state);
76
+ url.searchParams.set("code_challenge", input.codeChallenge);
77
+ url.searchParams.set("code_challenge_method", "S256");
78
+ url.searchParams.set("scope", scope ?? "openid profile email offline_access");
79
+ return url;
80
+ }
81
+ async function exchangeClerkOAuthCode(input) {
82
+ const { clientId, tokenUrl } = assertConfigured(input.config);
83
+ const body = new URLSearchParams({
84
+ grant_type: "authorization_code",
85
+ client_id: clientId,
86
+ code: input.code,
87
+ redirect_uri: input.redirectUri,
88
+ code_verifier: input.codeVerifier
89
+ });
90
+ return requestClerkToken(tokenUrl, body);
91
+ }
92
+ async function refreshClerkOAuthToken(input) {
93
+ const { clientId, tokenUrl } = assertConfigured(input.config);
94
+ const body = new URLSearchParams({
95
+ grant_type: "refresh_token",
96
+ client_id: clientId,
97
+ refresh_token: input.refreshToken
98
+ });
99
+ return requestClerkToken(tokenUrl, body);
100
+ }
101
+ function assertConfigured(config) {
102
+ const issuer = config.issuer?.trim().replace(/\/$/, "");
103
+ const clientId = config.clientId?.trim();
104
+ if (!issuer || !clientId) {
105
+ throw new Error(
106
+ [
107
+ "Clerk OAuth CLI is not configured for this environment.",
108
+ "The CLI expects first-party environments to be configured in its built-in registry.",
109
+ "If this environment has no registered public Clerk OAuth client, create one and release a CLI with its client id.",
110
+ "For emergency overrides, set the environment-specific DREAMBOARD_<ENV>_CLERK_OAUTH_* variables or DREAMBOARD_CLERK_OAUTH_*.",
111
+ "For local harness auth, use `pnpm auth:local` or the auto-bootstrapped local harness flows instead."
112
+ ].join(" ")
113
+ );
114
+ }
115
+ return {
116
+ issuer,
117
+ clientId,
118
+ tokenUrl: config.tokenUrl?.trim() || new URL("/oauth/token", issuer).toString(),
119
+ scope: config.scope?.trim() || void 0
120
+ };
121
+ }
122
+ async function requestClerkToken(tokenUrl, body) {
123
+ const response = await fetch(tokenUrl, {
124
+ method: "POST",
125
+ headers: {
126
+ "Content-Type": "application/x-www-form-urlencoded",
127
+ Accept: "application/json"
128
+ },
129
+ body
130
+ });
131
+ if (!response.ok) {
132
+ const detail = await response.text();
133
+ throw new Error(
134
+ `Clerk OAuth token request failed (${response.status}): ${detail}`
135
+ );
136
+ }
137
+ const payload = await response.json();
138
+ if (typeof payload.access_token !== "string") {
139
+ throw new Error("Clerk OAuth token response did not include access_token.");
140
+ }
141
+ if (typeof payload.refresh_token !== "string") {
142
+ throw new Error(
143
+ "Clerk OAuth token response did not include refresh_token."
144
+ );
145
+ }
146
+ const expiresAt = typeof payload.expires_in === "number" ? new Date(Date.now() + payload.expires_in * 1e3).toISOString() : void 0;
147
+ return {
148
+ accessToken: payload.access_token,
149
+ refreshToken: payload.refresh_token,
150
+ expiresAt,
151
+ tokenUrl
152
+ };
153
+ }
154
+ function base64Url(bytes) {
155
+ return bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
156
+ }
157
+
158
+ // src/auth/token-exchange.ts
159
+ async function exchangeDreamboardUserToken(input) {
160
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch.bind(globalThis);
161
+ const response = await fetchImpl(
162
+ new URL("/api/auth/token-exchange", input.apiBaseUrl),
163
+ {
164
+ method: "POST",
165
+ headers: {
166
+ Authorization: `Bearer ${input.clerkAccessToken}`,
167
+ "Content-Type": "application/json",
168
+ Accept: "application/json"
169
+ },
170
+ body: JSON.stringify({ audience: input.audience })
171
+ }
172
+ );
173
+ if (!response.ok) {
174
+ throw new Error(
175
+ `Dreamboard token exchange failed (${response.status}). Run \`dreamboard auth login\` to authenticate again.`
176
+ );
177
+ }
178
+ const payload = await response.json();
179
+ if (typeof payload.accessToken !== "string" || payload.accessToken === "") {
180
+ throw new Error("Dreamboard token exchange response omitted accessToken.");
181
+ }
182
+ if (payload.tokenType !== "Bearer") {
183
+ throw new Error(
184
+ "Dreamboard token exchange response had invalid tokenType."
185
+ );
186
+ }
187
+ if (payload.audience !== input.audience) {
188
+ throw new Error("Dreamboard token exchange response had wrong audience.");
189
+ }
190
+ const expiresIn = typeof payload.expiresIn === "number" && Number.isFinite(payload.expiresIn) ? payload.expiresIn : void 0;
191
+ return {
192
+ accessToken: payload.accessToken,
193
+ tokenType: "Bearer",
194
+ audience: input.audience,
195
+ expiresIn,
196
+ expiresAt: expiresIn === void 0 ? void 0 : new Date(Date.now() + expiresIn * 1e3).toISOString()
197
+ };
198
+ }
199
+
200
+ // src/auth/user-session-manager.ts
201
+ var DEFAULT_TOKEN_MIN_VALIDITY_MS = 60 * 1e3;
202
+ function createUserSessionManager(config) {
203
+ return {
204
+ async establishRefreshableSession(session) {
205
+ return withCredentialLock(async (ops) => {
206
+ const credentials = credentialsFromRefreshableSession(session);
207
+ await ops.writeFull(credentials);
208
+ const exchanged = await exchangeDreamboardUserToken({
209
+ apiBaseUrl: config.apiBaseUrl,
210
+ clerkAccessToken: credentials.accessToken,
211
+ audience: "dreamboard-api"
212
+ });
213
+ const apiToken = toAccessToken(exchanged);
214
+ await ops.writeFull(withApiToken(credentials, apiToken));
215
+ return apiToken;
216
+ });
217
+ },
218
+ async establishAccessOnlySession(accessToken) {
219
+ await withCredentialLock((ops) => ops.writeAccessOnly(accessToken));
220
+ },
221
+ async resolveApiToken(options) {
222
+ const localOrInjected = resolveNonStoredToken(config, "dreamboard-api");
223
+ if (localOrInjected) return localOrInjected;
224
+ if (!usesStoredSession(config)) return null;
225
+ const minValidityMs = options?.minValiditySeconds === void 0 ? DEFAULT_TOKEN_MIN_VALIDITY_MS : Math.max(0, options.minValiditySeconds * 1e3);
226
+ return withCredentialLock(async (ops) => {
227
+ const stored = await ops.read();
228
+ return resolveStoredApiToken(ops, config, stored, minValidityMs);
229
+ });
230
+ },
231
+ async resolveGitToken() {
232
+ const localOrInjected = resolveNonStoredToken(config, "dreamboard-git");
233
+ if (localOrInjected) return localOrInjected;
234
+ if (!usesStoredSession(config)) {
235
+ throw missingSessionError();
236
+ }
237
+ return withCredentialLock(async (ops) => {
238
+ const stored = await ops.read();
239
+ const clerk = await resolveFreshClerkSession(ops, config, stored);
240
+ return toAccessToken(
241
+ await exchangeDreamboardUserToken({
242
+ apiBaseUrl: config.apiBaseUrl,
243
+ clerkAccessToken: clerk.accessToken,
244
+ audience: "dreamboard-git"
245
+ })
246
+ );
247
+ });
248
+ },
249
+ async inspectSession() {
250
+ const localOrInjected = resolveNonStoredToken(config, "dreamboard-api");
251
+ if (localOrInjected) {
252
+ return inspectAccessOnlyToken(localOrInjected);
253
+ }
254
+ if (!usesStoredSession(config)) {
255
+ return { kind: "none" };
256
+ }
257
+ return withCredentialLock(async (ops) => {
258
+ const stored = await ops.read();
259
+ if (!stored) return { kind: "none" };
260
+ const cached = freshStoredApiToken(
261
+ stored,
262
+ DEFAULT_TOKEN_MIN_VALIDITY_MS
263
+ );
264
+ if (cached) {
265
+ return activeStatus("refreshable", cached, false);
266
+ }
267
+ try {
268
+ const token = await resolveStoredApiToken(
269
+ ops,
270
+ config,
271
+ stored,
272
+ DEFAULT_TOKEN_MIN_VALIDITY_MS
273
+ );
274
+ return activeStatus("refreshable", token, true);
275
+ } catch (error) {
276
+ return failedRefreshableStatus(error);
277
+ }
278
+ });
279
+ },
280
+ async logout() {
281
+ await withCredentialLock((ops) => ops.clear("logout_command"));
282
+ }
283
+ };
284
+ }
285
+ async function resolveStoredApiToken(ops, config, stored, minValidityMs) {
286
+ const cached = freshStoredApiToken(stored, minValidityMs);
287
+ if (cached) return cached;
288
+ const clerk = await resolveFreshClerkSession(ops, config, stored);
289
+ const exchanged = await exchangeDreamboardUserToken({
290
+ apiBaseUrl: config.apiBaseUrl,
291
+ clerkAccessToken: clerk.accessToken,
292
+ audience: "dreamboard-api"
293
+ });
294
+ const apiToken = toAccessToken(exchanged);
295
+ await ops.writeFull(withApiToken(clerk, apiToken));
296
+ return apiToken;
297
+ }
298
+ async function resolveFreshClerkSession(ops, config, stored) {
299
+ if (!stored) {
300
+ throw missingSessionError();
301
+ }
302
+ if (!stored.refreshToken) {
303
+ throw new Error(
304
+ "Stored Dreamboard session is missing its refresh token. Run `dreamboard auth login` to authenticate again."
305
+ );
306
+ }
307
+ if (stored.accessToken && isFresh(
308
+ stored.tokenExpiresAt,
309
+ stored.accessToken,
310
+ DEFAULT_TOKEN_MIN_VALIDITY_MS
311
+ )) {
312
+ return credentialsFromStored(config, stored);
313
+ }
314
+ const payload = await refreshClerkOAuthToken({
315
+ config: {
316
+ issuer: stored.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
317
+ clientId: stored.clerkOAuthClientId ?? config.clerkOAuthClientId,
318
+ tokenUrl: stored.clerkOAuthTokenUrl ?? config.clerkOAuthTokenUrl
319
+ },
320
+ refreshToken: stored.refreshToken
321
+ });
322
+ const refreshed = {
323
+ accessToken: payload.accessToken,
324
+ refreshToken: payload.refreshToken,
325
+ tokenExpiresAt: payload.expiresAt,
326
+ dreamboardApiToken: stored.dreamboardApiToken,
327
+ dreamboardApiExpiresAt: stored.dreamboardApiExpiresAt,
328
+ clerkOAuthIssuer: stored.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
329
+ clerkOAuthClientId: stored.clerkOAuthClientId ?? config.clerkOAuthClientId,
330
+ clerkOAuthTokenUrl: payload.tokenUrl,
331
+ environment: stored.environment ?? config.environment
332
+ };
333
+ await ops.writeFull(refreshed);
334
+ return refreshed;
335
+ }
336
+ function credentialsFromStored(config, stored) {
337
+ if (!stored.accessToken || !stored.refreshToken) {
338
+ throw missingSessionError();
339
+ }
340
+ return {
341
+ accessToken: stored.accessToken,
342
+ refreshToken: stored.refreshToken,
343
+ tokenExpiresAt: stored.tokenExpiresAt,
344
+ dreamboardApiToken: stored.dreamboardApiToken,
345
+ dreamboardApiExpiresAt: stored.dreamboardApiExpiresAt,
346
+ clerkOAuthIssuer: stored.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
347
+ clerkOAuthClientId: stored.clerkOAuthClientId ?? config.clerkOAuthClientId,
348
+ clerkOAuthTokenUrl: stored.clerkOAuthTokenUrl ?? config.clerkOAuthTokenUrl,
349
+ environment: stored.environment ?? config.environment
350
+ };
351
+ }
352
+ function credentialsFromRefreshableSession(session) {
353
+ return {
354
+ accessToken: session.clerkAccessToken,
355
+ refreshToken: session.refreshToken,
356
+ tokenExpiresAt: session.clerkAccessExpiresAt,
357
+ clerkOAuthIssuer: session.clerkOAuthIssuer,
358
+ clerkOAuthClientId: session.clerkOAuthClientId,
359
+ clerkOAuthTokenUrl: session.clerkOAuthTokenUrl,
360
+ environment: session.environment
361
+ };
362
+ }
363
+ function withApiToken(credentials, token) {
364
+ return {
365
+ ...credentials,
366
+ dreamboardApiToken: token.token,
367
+ dreamboardApiExpiresAt: token.expiresAt
368
+ };
369
+ }
370
+ function toAccessToken(token) {
371
+ return {
372
+ token: token.accessToken,
373
+ expiresAt: token.expiresAt,
374
+ audience: token.audience
375
+ };
376
+ }
377
+ function resolveNonStoredToken(config, audience) {
378
+ if (usesStoredSession(config)) return null;
379
+ if (!config.authToken) return null;
380
+ return {
381
+ token: config.authToken,
382
+ expiresAt: config.tokenExpiresAt,
383
+ audience
384
+ };
385
+ }
386
+ function freshStoredApiToken(stored, minValidityMs) {
387
+ if (!stored?.dreamboardApiToken) return null;
388
+ if (isFresh(
389
+ stored.dreamboardApiExpiresAt,
390
+ stored.dreamboardApiToken,
391
+ minValidityMs
392
+ )) {
393
+ return {
394
+ token: stored.dreamboardApiToken,
395
+ expiresAt: stored.dreamboardApiExpiresAt,
396
+ audience: "dreamboard-api"
397
+ };
398
+ }
399
+ return null;
400
+ }
401
+ function inspectAccessOnlyToken(token) {
402
+ const expiry = resolveExpiry(token.expiresAt, token.token);
403
+ if (expiry && expiry.getTime() <= Date.now()) {
404
+ return {
405
+ kind: "invalid",
406
+ sessionKind: "access-only",
407
+ message: "Stored Dreamboard access token is expired. Run `dreamboard auth login` to authenticate again."
408
+ };
409
+ }
410
+ return activeStatus("access-only", token, false);
411
+ }
412
+ function failedRefreshableStatus(error) {
413
+ const message = error instanceof Error ? error.message : String(error);
414
+ const errorStatus = typeof error === "object" && error !== null && "status" in error ? error.status : void 0;
415
+ const classification = classifyRefreshError({
416
+ message,
417
+ status: typeof errorStatus === "number" ? errorStatus : void 0
418
+ });
419
+ if (classification.kind === "permanent_invalid") {
420
+ return {
421
+ kind: "invalid",
422
+ sessionKind: "refreshable",
423
+ message
424
+ };
425
+ }
426
+ return {
427
+ kind: "degraded",
428
+ sessionKind: "refreshable",
429
+ message
430
+ };
431
+ }
432
+ function activeStatus(sessionKind, apiToken, repaired) {
433
+ return {
434
+ kind: "active",
435
+ sessionKind,
436
+ apiToken,
437
+ repaired
438
+ };
439
+ }
440
+ function missingSessionError() {
441
+ return new Error(
442
+ "Missing Dreamboard session. Run `dreamboard auth login` to authenticate."
443
+ );
444
+ }
445
+ function isFresh(expiresAt, token, minValidityMs) {
446
+ const expiry = resolveExpiry(expiresAt, token);
447
+ return expiry !== null && Number.isFinite(expiry.getTime()) && expiry.getTime() > Date.now() + minValidityMs;
448
+ }
449
+ function resolveExpiry(expiresAt, token) {
450
+ if (expiresAt) {
451
+ const parsed = new Date(expiresAt);
452
+ return Number.isFinite(parsed.getTime()) ? parsed : null;
453
+ }
454
+ return getJwtExpiry(token);
455
+ }
456
+ function getJwtExpiry(accessToken) {
457
+ if (!accessToken) return null;
458
+ const parts = accessToken.split(".");
459
+ if (parts.length !== 3) return null;
460
+ try {
461
+ const payload = JSON.parse(
462
+ Buffer.from(parts[1], "base64url").toString("utf8")
463
+ );
464
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) {
465
+ return null;
466
+ }
467
+ return new Date(payload.exp * 1e3);
468
+ } catch {
469
+ return null;
470
+ }
471
+ }
472
+ function usesStoredSession(config) {
473
+ return config.refreshTokenSource === "global";
474
+ }
475
+
476
+ // src/config/local-harness-auth.ts
477
+ import { createHmac, randomUUID } from "crypto";
478
+ var DEFAULT_SUBJECT = "harness-smoke-local@dreamboard.local";
479
+ var DEFAULT_ISSUER = "dreamboard-local-harness";
480
+ var DEFAULT_SECRET = "dreamboard-local-harness-token-secret";
481
+ var LOCAL_AWS_ISSUER = "dreamboard-local-aws-harness";
482
+ var LOCAL_AWS_SECRET = "dreamboard-local-aws-harness-token-secret";
483
+ var DEFAULT_TTL_SECONDS = 8 * 60 * 60;
484
+ var mintedTokens = /* @__PURE__ */ new Map();
485
+ function resolveLocalHarnessAccessToken(config) {
486
+ if (IS_PUBLISHED_BUILD || config.environment !== "local") {
487
+ return void 0;
488
+ }
489
+ const profile = inferLocalHarnessProfile(config);
490
+ if (config.authToken && (profile !== "local-aws" || isExplicitTokenSource(config.authTokenSource))) {
491
+ return void 0;
492
+ }
493
+ const cacheKey = [
494
+ profile,
495
+ process.env.LOCAL_HARNESS_TOKEN_ISSUER ?? "",
496
+ process.env.LOCAL_HARNESS_TOKEN_SECRET ?? "",
497
+ process.env.LOCAL_HARNESS_SUBJECT ?? "",
498
+ process.env.HARNESS_USER_EMAIL ?? "",
499
+ process.env.LOCAL_HARNESS_EMAIL ?? "",
500
+ process.env.LOCAL_HARNESS_TOKEN_TTL_SECONDS ?? ""
501
+ ].join("\0");
502
+ const cached = mintedTokens.get(cacheKey);
503
+ if (cached) return cached;
504
+ const token = mintLocalHarnessToken(profile);
505
+ mintedTokens.set(cacheKey, token);
506
+ return token;
507
+ }
508
+ function isExplicitTokenSource(source) {
509
+ return source === "flag" || source === "env" || source === "agent-env";
510
+ }
511
+ function inferLocalHarnessProfile(config) {
512
+ return isLocalAwsUrl(config.apiBaseUrl) || isLocalAwsUrl(config.webBaseUrl) ? "local-aws" : "local";
513
+ }
514
+ function mintLocalHarnessToken(profile) {
515
+ const subject = envValue(process.env.LOCAL_HARNESS_SUBJECT) ?? envValue(process.env.HARNESS_USER_EMAIL) ?? DEFAULT_SUBJECT;
516
+ const email = envValue(process.env.LOCAL_HARNESS_EMAIL) ?? (subject.includes("@") ? subject : void 0);
517
+ const issuer = envValue(process.env.LOCAL_HARNESS_TOKEN_ISSUER) ?? (profile === "local-aws" ? LOCAL_AWS_ISSUER : DEFAULT_ISSUER);
518
+ const secret = envValue(process.env.LOCAL_HARNESS_TOKEN_SECRET) ?? (profile === "local-aws" ? LOCAL_AWS_SECRET : DEFAULT_SECRET);
519
+ const ttlSeconds = Number(
520
+ envValue(process.env.LOCAL_HARNESS_TOKEN_TTL_SECONDS) ?? String(DEFAULT_TTL_SECONDS)
521
+ );
522
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
523
+ throw new Error(
524
+ "LOCAL_HARNESS_TOKEN_TTL_SECONDS must be a positive number."
525
+ );
526
+ }
527
+ const now = Math.floor(Date.now() / 1e3);
528
+ const payload = {
529
+ typ: "local_harness_access",
530
+ dreamboard_provider: "local-harness",
531
+ dreamboard_provider_subject: subject,
532
+ ...email ? { email } : {},
533
+ iss: issuer,
534
+ sub: subject,
535
+ iat: now,
536
+ exp: now + Math.floor(ttlSeconds),
537
+ jti: randomUUID()
538
+ };
539
+ const headerPart = base64UrlJson({ alg: "HS256", typ: "JWT" });
540
+ const payloadPart = base64UrlJson(payload);
541
+ const signature = createHmac("sha256", secret).update(`${headerPart}.${payloadPart}`).digest("base64url");
542
+ return `${headerPart}.${payloadPart}.${signature}`;
543
+ }
544
+ function base64UrlJson(value) {
545
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
546
+ }
547
+ function envValue(raw) {
548
+ return typeof raw === "string" && raw.trim().length > 0 ? raw.trim() : void 0;
549
+ }
550
+ function isLocalAwsUrl(rawUrl) {
551
+ if (!rawUrl) return false;
552
+ try {
553
+ const url = new URL(rawUrl);
554
+ return (url.hostname === "localhost" || url.hostname === "127.0.0.1") && (url.port === "18080" || url.port === "8088");
555
+ } catch {
556
+ return false;
557
+ }
558
+ }
559
+
560
+ // src/config/resolve.ts
561
+ var TRANSIENT_READ_RETRY_DELAYS_MS = [100, 300];
562
+ function resolveConfig(globalConfig, flags, project, credentials) {
563
+ if (IS_PUBLISHED_BUILD) {
564
+ assertPublicRuntimeFlags(flags);
565
+ }
566
+ const envEnvironment = IS_PUBLISHED_BUILD ? void 0 : environmentFromProcess();
567
+ const projectEnvironment = IS_PUBLISHED_BUILD ? void 0 : project?.environment;
568
+ const environment = IS_PUBLISHED_BUILD ? PUBLISHED_ENVIRONMENT : flags.env || envEnvironment || projectEnvironment || globalConfig.environment || "staging";
569
+ const envConfig = ENVIRONMENT_CONFIGS[environment];
570
+ const publishedEnvConfig = ENVIRONMENT_CONFIGS[PUBLISHED_ENVIRONMENT];
571
+ const hasExplicitEnvironmentOverride = !IS_PUBLISHED_BUILD && Boolean(flags.env || envEnvironment || projectEnvironment);
572
+ const resolvedApiBaseUrl = IS_PUBLISHED_BUILD ? publishedEnvConfig?.apiBaseUrl ?? DEFAULT_API_BASE_URL : hasExplicitEnvironmentOverride ? projectLocalBaseUrl(project?.apiBaseUrl, environment) || envConfig?.apiBaseUrl || DEFAULT_API_BASE_URL : project?.apiBaseUrl || envConfig?.apiBaseUrl || DEFAULT_API_BASE_URL;
573
+ const apiBaseUrl = valueOrUndefined(process.env.DREAMBOARD_API_BASE_URL) ?? resolvedApiBaseUrl;
574
+ const resolvedWebBaseUrl = IS_PUBLISHED_BUILD ? publishedEnvConfig?.webBaseUrl ?? DEFAULT_WEB_BASE_URL : hasExplicitEnvironmentOverride ? projectLocalBaseUrl(project?.webBaseUrl, environment) || envConfig?.webBaseUrl || DEFAULT_WEB_BASE_URL : project?.webBaseUrl || envConfig?.webBaseUrl || DEFAULT_WEB_BASE_URL;
575
+ const webBaseUrl = valueOrUndefined(process.env.DREAMBOARD_WEB_BASE_URL) ?? resolvedWebBaseUrl;
576
+ const snapshot = buildCredentialSnapshot(flags, credentials, environment);
577
+ const oauthConfig = resolveEnvironmentOAuthConfig(environment, envConfig);
578
+ return {
579
+ environment,
580
+ apiBaseUrl,
581
+ webBaseUrl,
582
+ authToken: snapshot.dreamboardApiToken ?? (snapshot.refreshToken ? void 0 : snapshot.accessToken),
583
+ refreshToken: snapshot.refreshToken,
584
+ tokenExpiresAt: snapshot.dreamboardApiExpiresAt ?? (snapshot.refreshToken ? void 0 : snapshot.tokenExpiresAt),
585
+ clerkAccessToken: snapshot.accessToken,
586
+ clerkAccessExpiresAt: snapshot.tokenExpiresAt,
587
+ dreamboardApiToken: snapshot.dreamboardApiToken,
588
+ dreamboardApiExpiresAt: snapshot.dreamboardApiExpiresAt,
589
+ clerkOAuthIssuer: snapshot.clerkOAuthIssuer ?? oauthConfig.issuer,
590
+ clerkOAuthClientId: snapshot.clerkOAuthClientId ?? oauthConfig.clientId,
591
+ clerkOAuthTokenUrl: snapshot.clerkOAuthTokenUrl ?? oauthConfig.tokenUrl,
592
+ clerkOAuthScope: oauthConfig.scope,
593
+ authTokenSource: snapshot.authTokenSource,
594
+ refreshTokenSource: snapshot.refreshTokenSource
595
+ };
596
+ }
597
+ function resolveEnvironmentOAuthConfig(environment, envConfig) {
598
+ const prefix = environment.toUpperCase();
599
+ return {
600
+ issuer: valueOrUndefined(
601
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_ISSUER`]
602
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_ISSUER) ?? envConfig?.clerkOAuthIssuer,
603
+ clientId: valueOrUndefined(
604
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_CLIENT_ID`]
605
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_CLIENT_ID) ?? envConfig?.clerkOAuthClientId,
606
+ tokenUrl: valueOrUndefined(
607
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_TOKEN_URL`]
608
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_TOKEN_URL) ?? envConfig?.clerkOAuthTokenUrl,
609
+ scope: valueOrUndefined(process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_SCOPE`]) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_SCOPE) ?? envConfig?.clerkOAuthScope
610
+ };
611
+ }
612
+ function buildCredentialSnapshot(flags, storedCredentials, environment) {
613
+ const flagToken = valueOrUndefined(flags.token);
614
+ const agentEnvToken = valueOrUndefined(process.env.DREAMBOARD_AGENT_TOKEN);
615
+ const envToken = valueOrUndefined(process.env.DREAMBOARD_TOKEN);
616
+ const environmentScopedStoredCredentials = storedCredentials?.environment && environment && storedCredentials.environment !== environment ? null : storedCredentials ?? null;
617
+ if (IS_PUBLISHED_BUILD) {
618
+ const stored = environmentScopedStoredCredentials;
619
+ if (agentEnvToken) {
620
+ return {
621
+ accessToken: agentEnvToken,
622
+ refreshToken: void 0,
623
+ tokenExpiresAt: void 0,
624
+ authTokenSource: "agent-env",
625
+ refreshTokenSource: "none"
626
+ };
627
+ }
628
+ return {
629
+ accessToken: stored?.accessToken,
630
+ refreshToken: stored?.refreshToken,
631
+ tokenExpiresAt: stored?.tokenExpiresAt,
632
+ dreamboardApiToken: stored?.dreamboardApiToken,
633
+ dreamboardApiExpiresAt: stored?.dreamboardApiExpiresAt,
634
+ clerkOAuthIssuer: stored?.clerkOAuthIssuer,
635
+ clerkOAuthClientId: stored?.clerkOAuthClientId,
636
+ clerkOAuthTokenUrl: stored?.clerkOAuthTokenUrl,
637
+ environment: stored?.environment,
638
+ authTokenSource: stored?.dreamboardApiToken || stored?.accessToken && !stored.refreshToken ? "global" : "none",
639
+ refreshTokenSource: stored?.refreshToken ? "global" : "none"
640
+ };
641
+ }
642
+ const accessToken = flagToken || agentEnvToken || envToken || environmentScopedStoredCredentials?.accessToken;
643
+ const refreshToken = environmentScopedStoredCredentials?.refreshToken;
644
+ const authTokenSource = flagToken ? "flag" : agentEnvToken ? "agent-env" : envToken ? "env" : environmentScopedStoredCredentials?.accessToken ? "global" : "none";
645
+ const refreshTokenSource = environmentScopedStoredCredentials?.refreshToken ? "global" : "none";
646
+ return {
647
+ accessToken,
648
+ refreshToken,
649
+ tokenExpiresAt: environmentScopedStoredCredentials?.tokenExpiresAt,
650
+ dreamboardApiToken: environmentScopedStoredCredentials?.dreamboardApiToken,
651
+ dreamboardApiExpiresAt: environmentScopedStoredCredentials?.dreamboardApiExpiresAt,
652
+ clerkOAuthIssuer: environmentScopedStoredCredentials?.clerkOAuthIssuer,
653
+ clerkOAuthClientId: environmentScopedStoredCredentials?.clerkOAuthClientId,
654
+ clerkOAuthTokenUrl: environmentScopedStoredCredentials?.clerkOAuthTokenUrl,
655
+ environment: environmentScopedStoredCredentials?.environment,
656
+ authTokenSource,
657
+ refreshTokenSource
658
+ };
659
+ }
660
+ function environmentFromProcess() {
661
+ const value = valueOrUndefined(process.env.DREAMBOARD_ENV);
662
+ if (!value) return void 0;
663
+ if (value === "local" || value === "staging" || value === "prod") {
664
+ return value;
665
+ }
666
+ throw new Error(
667
+ `Invalid DREAMBOARD_ENV '${value}'. Valid options: local, staging, prod`
668
+ );
669
+ }
670
+ function projectLocalBaseUrl(rawUrl, environment) {
671
+ if (environment !== "local" || !rawUrl) return void 0;
672
+ try {
673
+ const url = new URL(rawUrl);
674
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" ? rawUrl : void 0;
675
+ } catch {
676
+ return void 0;
677
+ }
678
+ }
679
+ function assertPublicRuntimeFlags(flags) {
680
+ const argv = process.argv.slice(2);
681
+ if (flags.env || argv.includes("--env")) {
682
+ throw new Error(
683
+ "The published Dreamboard CLI is production-only and does not accept `--env`."
684
+ );
685
+ }
686
+ if (valueOrUndefined(flags.token) || argv.includes("--token")) {
687
+ throw new Error(
688
+ "Direct JWT injection is not supported in the published Dreamboard CLI. Use `dreamboard auth login` so the CLI can store and refresh your session."
689
+ );
690
+ }
691
+ if (process.env.DREAMBOARD_TOKEN) {
692
+ throw new Error(
693
+ "The published Dreamboard CLI ignores direct token environment variables. Use `dreamboard auth login` so the CLI can manage refreshable credentials."
694
+ );
695
+ }
696
+ }
697
+ async function configureClient(config) {
698
+ const localHarnessToken = resolveLocalHarnessAccessToken(config);
699
+ const resolvedToken = localHarnessToken ? { token: localHarnessToken } : await createUserSessionManager(config).resolveApiToken();
700
+ const effectiveAccessToken = resolvedToken?.token;
701
+ client.setConfig({
702
+ baseUrl: config.apiBaseUrl,
703
+ fetch: createRetryingReadFetch(globalThis.fetch.bind(globalThis)),
704
+ headers: effectiveAccessToken ? { Authorization: `Bearer ${effectiveAccessToken}` } : {}
705
+ });
706
+ }
707
+ function createRetryingReadFetch(fetchImpl) {
708
+ return (async (input, init) => {
709
+ const method = resolveFetchMethod(input, init);
710
+ if (method !== "GET" && method !== "HEAD") {
711
+ return fetchImpl(input, init);
712
+ }
713
+ let lastError;
714
+ for (let attempt = 0; attempt <= TRANSIENT_READ_RETRY_DELAYS_MS.length; attempt += 1) {
715
+ try {
716
+ return await fetchImpl(input, init);
717
+ } catch (error) {
718
+ lastError = error;
719
+ if (attempt >= TRANSIENT_READ_RETRY_DELAYS_MS.length || !isTransientFetchError(error)) {
720
+ throw error;
721
+ }
722
+ await sleep(TRANSIENT_READ_RETRY_DELAYS_MS[attempt]);
723
+ }
724
+ }
725
+ throw lastError;
726
+ });
727
+ }
728
+ function resolveFetchMethod(input, init) {
729
+ const method = init?.method ?? (typeof Request !== "undefined" && input instanceof Request ? input.method : void 0);
730
+ return (method ?? "GET").toUpperCase();
731
+ }
732
+ function isTransientFetchError(error) {
733
+ const message = error instanceof Error ? error.message : typeof error === "object" && error !== null && "message" in error ? String(error.message) : String(error);
734
+ const normalized = message.toLowerCase();
735
+ return normalized.includes("fetch failed") || normalized.includes("network") || normalized.includes("timeout") || normalized.includes("econnreset") || normalized.includes("econnrefused") || normalized.includes("socket");
736
+ }
737
+ function sleep(ms) {
738
+ return new Promise((resolve) => setTimeout(resolve, ms));
739
+ }
740
+ function requireAuth(config) {
741
+ if (!config.authToken && !config.refreshToken && !resolveLocalHarnessAccessToken(config)) {
742
+ throw new Error(
743
+ "Missing Dreamboard session. Run `dreamboard auth login` to authenticate."
744
+ );
745
+ }
746
+ }
747
+ function valueOrUndefined(value) {
748
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
749
+ }
750
+ function getAuthTokenExpiry(accessToken) {
751
+ if (!accessToken) return null;
752
+ const parts = accessToken.split(".");
753
+ if (parts.length !== 3) return null;
754
+ try {
755
+ const payload = JSON.parse(
756
+ Buffer.from(parts[1], "base64url").toString("utf8")
757
+ );
758
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) {
759
+ return null;
760
+ }
761
+ return new Date(payload.exp * 1e3);
762
+ } catch {
763
+ return null;
764
+ }
765
+ }
766
+ async function loadProjectContextCredentials(requireAuth2, loadCredentials = getStoredSession) {
767
+ return requireAuth2 ? loadCredentials() : void 0;
768
+ }
769
+ async function resolveProjectContext(flags, opts) {
770
+ const projectRoot = await findProjectRoot(process.cwd());
771
+ if (!projectRoot) {
772
+ throw new Error(
773
+ "Not inside a dreamboard project (missing .dreamboard/project.json)."
774
+ );
775
+ }
776
+ const projectConfig = await loadProjectConfig(projectRoot);
777
+ const requireAuthForContext = opts?.requireAuth !== false;
778
+ const [globalConfig, credentials] = await Promise.all([
779
+ loadGlobalConfig(),
780
+ loadProjectContextCredentials(requireAuthForContext)
781
+ ]);
782
+ const config = resolveConfig(globalConfig, flags, projectConfig, credentials);
783
+ if (requireAuthForContext) {
784
+ requireAuth(config);
785
+ await configureClient(config);
786
+ }
787
+ return { projectRoot, projectConfig, config };
788
+ }
789
+
790
+ // src/flags.ts
791
+ var configFlagsSchema = external_exports.object({
792
+ env: external_exports.enum(["local", "staging", "prod"]).optional(),
793
+ token: external_exports.string().optional()
794
+ });
795
+ var ruleInputFlagsSchema = external_exports.object({
796
+ "rule-file": external_exports.string().optional(),
797
+ rule: external_exports.string().optional()
798
+ });
799
+ var playerCountFlagsSchema = external_exports.object({
800
+ players: external_exports.string().optional(),
801
+ "player-count": external_exports.string().optional()
802
+ });
803
+ var newCommandArgsSchema = configFlagsSchema.extend({
804
+ slug: external_exports.string().min(1),
805
+ description: external_exports.string().min(1),
806
+ force: external_exports.boolean().default(false),
807
+ "wait-timeout-ms": external_exports.string().optional(),
808
+ "repository-poll-interval-ms": external_exports.string().optional()
809
+ });
810
+ var cloneCommandArgsSchema = configFlagsSchema.extend({
811
+ slug: external_exports.string().min(1),
812
+ "wait-timeout-ms": external_exports.string().optional(),
813
+ "repository-poll-interval-ms": external_exports.string().optional()
814
+ });
815
+ var queryCommandArgsSchema = configFlagsSchema.extend({
816
+ title: external_exports.string().min(1)
817
+ });
818
+ var pullCommandArgsSchema = configFlagsSchema.extend({
819
+ force: external_exports.boolean().default(false)
820
+ });
821
+ var syncCommandArgsSchema = configFlagsSchema.extend({
822
+ force: external_exports.boolean().default(false),
823
+ yes: external_exports.boolean().default(false)
824
+ });
825
+ var compileCommandArgsSchema = configFlagsSchema.extend({
826
+ debug: external_exports.boolean().default(false),
827
+ "skip-local-check": external_exports.boolean().default(false)
828
+ });
829
+ var statusCommandArgsSchema = configFlagsSchema.extend({
830
+ json: external_exports.boolean().default(false)
831
+ });
832
+ var commitScopedCommandArgsSchema = configFlagsSchema.extend({
833
+ commit: external_exports.string().min(1),
834
+ json: external_exports.boolean().default(false)
835
+ });
836
+ var buildCommandArgsSchema = commitScopedCommandArgsSchema.extend({
837
+ profile: external_exports.enum(["preview", "release"]).optional().default("preview")
838
+ });
839
+ var releasePublishCommandArgsSchema = commitScopedCommandArgsSchema.extend({
840
+ yes: external_exports.boolean().default(false)
841
+ });
842
+ var devCommandArgsSchema = configFlagsSchema.extend({
843
+ seed: external_exports.string().optional(),
844
+ "setup-profile": external_exports.string().optional(),
845
+ players: external_exports.string().optional(),
846
+ "player-count": external_exports.string().optional(),
847
+ debug: external_exports.boolean().default(false),
848
+ resume: external_exports.string().optional(),
849
+ "from-scenario": external_exports.string().optional(),
850
+ "new-session": external_exports.boolean().default(false),
851
+ open: external_exports.boolean().default(false),
852
+ port: external_exports.string().optional(),
853
+ host: external_exports.union([external_exports.string(), external_exports.boolean()]).optional(),
854
+ "allowed-host": external_exports.string().optional()
855
+ });
856
+ var joinCommandArgsSchema = configFlagsSchema.extend({
857
+ session: external_exports.string().min(1).optional(),
858
+ player: external_exports.string().min(1),
859
+ "raw-events": external_exports.boolean().default(false)
860
+ });
861
+ var configCommandArgsSchema = configFlagsSchema.extend({
862
+ action: external_exports.string().optional().default("show"),
863
+ scope: external_exports.enum(["global", "workspace"]).optional().default("global")
864
+ });
865
+ var authCommandArgsSchema = external_exports.object({
866
+ action: external_exports.enum(["set", "login", "logout", "env", "status", "git-credential"]),
867
+ tokenValue: external_exports.string().optional(),
868
+ token: external_exports.string().optional(),
869
+ jwt: external_exports.boolean().optional(),
870
+ env: external_exports.enum(["local", "staging", "prod"]).optional()
871
+ });
872
+ function parseArgs(commandName, schema, args) {
873
+ const parsed = schema.safeParse(args);
874
+ if (parsed.success) {
875
+ return parsed.data;
876
+ }
877
+ const details = parsed.error.issues.map((issue) => {
878
+ const field = issue.path.length > 0 ? issue.path.join(".") : "args";
879
+ return `${field}: ${issue.message}`;
880
+ }).join("; ");
881
+ throw new Error(`Invalid arguments for '${commandName}': ${details}`);
882
+ }
883
+ function parseConfigFlags(args) {
884
+ return parseArgs("config-flags", configFlagsSchema, args);
885
+ }
886
+ function parsePlayerCountFlags(args) {
887
+ return parseArgs("player-count", playerCountFlagsSchema, args);
888
+ }
889
+ function parseNewCommandArgs(args) {
890
+ return parseArgs("new", newCommandArgsSchema, args);
891
+ }
892
+ function parseCloneCommandArgs(args) {
893
+ return parseArgs("clone", cloneCommandArgsSchema, args);
894
+ }
895
+ function parseCommitScopedCommandArgs(commandName, args) {
896
+ return parseArgs(commandName, commitScopedCommandArgsSchema, args);
897
+ }
898
+ function parseBuildCommandArgs(args) {
899
+ return parseArgs("build", buildCommandArgsSchema, args);
900
+ }
901
+ function parseReleasePublishCommandArgs(args) {
902
+ return parseArgs("release publish", releasePublishCommandArgsSchema, args);
903
+ }
904
+ function parseDevCommandArgs(args) {
905
+ return parseArgs("dev", devCommandArgsSchema, args);
906
+ }
907
+ function parseAuthCommandArgs(args) {
908
+ return parseArgs("auth", authCommandArgsSchema, args);
909
+ }
910
+
911
+ // src/command-args.ts
912
+ var CONFIG_FLAG_ARGS = {
913
+ env: {
914
+ type: "string",
915
+ description: "Environment: local | staging | prod"
916
+ },
917
+ token: {
918
+ type: "string",
919
+ description: "Auth token (Dreamboard bearer JWT)"
920
+ }
921
+ };
922
+
923
+ // src/utils/problem-types.ts
924
+ var CLI_PROBLEM_TYPES = {
925
+ ...SERVER_PROBLEM_TYPES,
926
+ ...CLIENT_PROBLEM_TYPES
927
+ };
928
+
929
+ // src/utils/errors.ts
930
+ var STALE_CONTRACT_ARTIFACT_CODE = "STALE_CONTRACT_ARTIFACT";
931
+ var STALE_CONTRACT_ARTIFACT_EXIT_CODE = 42;
932
+ function isProblemViolationArray(value) {
933
+ return Array.isArray(value) && value.every(
934
+ (entry) => typeof entry === "object" && entry !== null && typeof entry.message === "string"
935
+ );
936
+ }
937
+ function isProblemDetails(value) {
938
+ return zProblemDetails.safeParse(value).success;
939
+ }
940
+ function coerceViolations(value) {
941
+ if (isProblemViolationArray(value)) {
942
+ return value;
943
+ }
944
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
945
+ return value.map((message) => ({ message }));
946
+ }
947
+ return void 0;
948
+ }
949
+ function getRequestId(response) {
950
+ return response?.headers?.get?.("X-Correlation-ID") ?? response?.headers?.get?.("x-correlation-id") ?? void 0;
951
+ }
952
+ function toApiProblem(error, response, fallback) {
953
+ if (isProblemDetails(error)) {
954
+ return {
955
+ ...error,
956
+ status: error.status || response?.status || 0,
957
+ requestId: error.requestId ?? getRequestId(response)
958
+ };
959
+ }
960
+ if (error instanceof Error) {
961
+ return {
962
+ type: CLI_PROBLEM_TYPES.TRANSPORT_ERROR,
963
+ title: response?.statusText || "API error",
964
+ status: response?.status ?? 0,
965
+ detail: error.message || fallback,
966
+ requestId: getRequestId(response)
967
+ };
968
+ }
969
+ if (error && typeof error === "object") {
970
+ const obj = error;
971
+ const detail2 = typeof obj.detail === "string" ? obj.detail : typeof obj.message === "string" ? obj.message : void 0;
972
+ const title = typeof obj.title === "string" ? obj.title : response?.statusText || "API error";
973
+ const violations = coerceViolations(obj.violations) ?? coerceViolations(obj.errors);
974
+ if (detail2) {
975
+ return {
976
+ type: typeof obj.type === "string" ? obj.type : CLI_PROBLEM_TYPES.UNKNOWN_API_ERROR,
977
+ title,
978
+ status: typeof obj.status === "number" ? obj.status : response?.status ?? 0,
979
+ detail: detail2,
980
+ requestId: typeof obj.requestId === "string" ? obj.requestId : getRequestId(response),
981
+ retryable: typeof obj.retryable === "boolean" ? obj.retryable : void 0,
982
+ context: typeof obj.context === "object" && obj.context !== null ? obj.context : void 0,
983
+ violations,
984
+ timestamp: typeof obj.timestamp === "string" ? obj.timestamp : void 0,
985
+ instance: typeof obj.instance === "string" ? obj.instance : void 0
986
+ };
987
+ }
988
+ }
989
+ const detail = typeof error === "string" ? error.trim() || fallback : fallback;
990
+ return {
991
+ type: CLI_PROBLEM_TYPES.UNKNOWN_API_ERROR,
992
+ title: response?.statusText || "API error",
993
+ status: response?.status ?? 0,
994
+ detail,
995
+ requestId: getRequestId(response)
996
+ };
997
+ }
998
+ function formatProblem(problem) {
999
+ const base = problem.detail || problem.title;
1000
+ const violations = problem.violations && problem.violations.length > 0 ? ` (${problem.violations.map((entry) => entry.message).join("; ")})` : "";
1001
+ const statusSuffix = problem.status && problem.status > 0 ? ` (HTTP ${problem.status})` : "";
1002
+ return `${base}${violations}${statusSuffix}`;
1003
+ }
1004
+ var DreamboardApiError = class extends Error {
1005
+ problem;
1006
+ status;
1007
+ requestId;
1008
+ retryable;
1009
+ constructor(problem, cause) {
1010
+ super(formatProblem(problem), { cause });
1011
+ this.name = "DreamboardApiError";
1012
+ this.problem = problem;
1013
+ this.status = problem.status;
1014
+ this.requestId = problem.requestId;
1015
+ this.retryable = problem.retryable;
1016
+ }
1017
+ };
1018
+ function toDreamboardApiError(error, response, fallback) {
1019
+ return new DreamboardApiError(toApiProblem(error, response, fallback), error);
1020
+ }
1021
+ function isDreamboardApiError(error) {
1022
+ return error instanceof DreamboardApiError;
1023
+ }
1024
+ function getObjectStringProperty(value, property) {
1025
+ return value && typeof value === "object" && typeof value[property] === "string" ? value[property] : void 0;
1026
+ }
1027
+ function isStaleContractArtifactMessage(message) {
1028
+ return message.includes(STALE_CONTRACT_ARTIFACT_CODE) || message.includes("StaleContractArtifactError") || message.toLowerCase().includes("stale contract artifact");
1029
+ }
1030
+ function isStaleContractArtifactError(error) {
1031
+ if (getObjectStringProperty(error, "code") === STALE_CONTRACT_ARTIFACT_CODE) {
1032
+ return true;
1033
+ }
1034
+ if (getObjectStringProperty(error, "name") === "StaleContractArtifactError") {
1035
+ return true;
1036
+ }
1037
+ const message = getObjectStringProperty(error, "message");
1038
+ return message ? isStaleContractArtifactMessage(message) : false;
1039
+ }
1040
+ function getCliErrorExitCode(error) {
1041
+ return isStaleContractArtifactError(error) ? STALE_CONTRACT_ARTIFACT_EXIT_CODE : 1;
1042
+ }
1043
+ function isGameNotFoundProblem(problem) {
1044
+ return problem.status === 404 && (problem.detail?.startsWith("Game not found: ") === true || problem.instance?.includes("/source-blobs/upload-sessions") === true);
1045
+ }
1046
+ function getProblemResolution(problem) {
1047
+ if (isGameNotFoundProblem(problem)) {
1048
+ return [
1049
+ "Verify the project binding with `dreamboard project status --commit <rev>` after pushing the exact commit.",
1050
+ "If you meant to use an existing remote project, check that your selected account and environment point at the backend that has that project."
1051
+ ].join(" ");
1052
+ }
1053
+ switch (problem.type) {
1054
+ case CLI_PROBLEM_TYPES.UNAUTHORIZED:
1055
+ return "Run `dreamboard auth login` to authenticate again.";
1056
+ case CLI_PROBLEM_TYPES.FORBIDDEN:
1057
+ return "Check that the signed-in account has access to this game, or run `dreamboard auth login` with the correct account.";
1058
+ case CLI_PROBLEM_TYPES.TOO_MANY_REQUESTS:
1059
+ return "Wait a moment, then retry the command.";
1060
+ case CLI_PROBLEM_TYPES.TRANSPORT_ERROR:
1061
+ return "Check that the selected Dreamboard server is reachable and try again later.";
1062
+ case CLI_PROBLEM_TYPES.VALIDATION_FAILED:
1063
+ return "Fix the validation issue above, then retry the command.";
1064
+ case CLI_PROBLEM_TYPES.ACTIVE_JOB_CONFLICT:
1065
+ return "Wait for the active job to finish, then retry the command.";
1066
+ case CLI_PROBLEM_TYPES.GAME_SLUG_CONFLICT:
1067
+ return "Choose a different game slug, or use the existing workspace for that slug.";
1068
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_NOT_FOUND:
1069
+ return "Push the exact Git commit, then run `dreamboard project status --commit <rev> --wait` before retrying.";
1070
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_DRIFT:
1071
+ case CLI_PROBLEM_TYPES.AUTHORING_STATE_DRIFT:
1072
+ case CLI_PROBLEM_TYPES.STATE_CONFLICT:
1073
+ return "Resolve the Git/source conflict in your worktree, push the intended exact commit, and retry the command against that commit.";
1074
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_BASE_MISSING:
1075
+ case CLI_PROBLEM_TYPES.AUTHORING_STATE_BASE_MISSING:
1076
+ return "Clone the project repository into a clean workspace or push the intended exact commit before retrying.";
1077
+ case CLI_PROBLEM_TYPES.INTERNAL_ERROR:
1078
+ return "Retry the command. If it still fails, include the request id when asking for help.";
1079
+ default:
1080
+ return void 0;
1081
+ }
1082
+ }
1083
+ function getProblemDetails(problem) {
1084
+ return [
1085
+ `Problem: ${problem.type}`,
1086
+ problem.instance ? `Endpoint: ${problem.instance}` : void 0,
1087
+ problem.requestId ? `Request ID: ${problem.requestId}` : void 0,
1088
+ problem.timestamp ? `Timestamp: ${problem.timestamp}` : void 0
1089
+ ].filter((detail) => Boolean(detail));
1090
+ }
1091
+ function presentCliError(error) {
1092
+ if (isDreamboardApiError(error)) {
1093
+ return {
1094
+ message: formatProblem(error.problem),
1095
+ resolution: getProblemResolution(error.problem),
1096
+ details: getProblemDetails(error.problem)
1097
+ };
1098
+ }
1099
+ if (error instanceof Error) {
1100
+ return {
1101
+ message: error.message,
1102
+ details: []
1103
+ };
1104
+ }
1105
+ if (typeof error === "object" && error !== null) {
1106
+ let serialized;
1107
+ try {
1108
+ serialized = JSON.stringify(error);
1109
+ } catch {
1110
+ serialized = String(error);
1111
+ }
1112
+ return {
1113
+ message: serialized,
1114
+ details: []
1115
+ };
1116
+ }
1117
+ return {
1118
+ message: String(error),
1119
+ details: []
1120
+ };
1121
+ }
1122
+ function formatCliError(error) {
1123
+ const presentation = presentCliError(error);
1124
+ return [
1125
+ presentation.message,
1126
+ presentation.resolution ? `Resolution: ${presentation.resolution}` : void 0,
1127
+ ...presentation.details
1128
+ ].filter((line) => Boolean(line)).join("\n");
1129
+ }
1130
+
1131
+ // src/utils/strings.ts
1132
+ import path from "path";
1133
+ function normalizeSlug(input) {
1134
+ const lowered = input.trim().toLowerCase();
1135
+ const replaced = lowered.replace(/[^a-z0-9]+/g, "-");
1136
+ return replaced.replace(/^-+/, "").replace(/-+$/, "");
1137
+ }
1138
+ function titleFromSlug(slug) {
1139
+ return slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
1140
+ }
1141
+ function parsePositiveInt(value, label) {
1142
+ const parsed = Number.parseInt(value, 10);
1143
+ if (!Number.isFinite(parsed) || parsed <= 0) {
1144
+ throw new Error(`${label} must be a positive integer.`);
1145
+ }
1146
+ return parsed;
1147
+ }
1148
+ function sleep2(ms) {
1149
+ return new Promise((resolve) => setTimeout(resolve, ms));
1150
+ }
1151
+
1152
+ // src/services/api/compiled-results-api.ts
1153
+ var COMPILE_JOB_POLL_INTERVAL_MS = 1e3;
1154
+ var DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS = 10 * 60 * 1e3;
1155
+ function firstNonEmpty(...values) {
1156
+ for (const value of values) {
1157
+ if (typeof value === "string" && value.trim().length > 0) {
1158
+ return value.trim();
1159
+ }
1160
+ }
1161
+ return null;
1162
+ }
1163
+ function formatTerminalCompileJobMessage(job) {
1164
+ const detail = firstNonEmpty(job.errorMessage, job.message);
1165
+ const phase = firstNonEmpty(job.phase);
1166
+ const prefix = `Compile ${job.status.toLowerCase()}${phase ? ` [${phase}]` : ""}`;
1167
+ return detail ? `${prefix}: ${detail}` : `${prefix}: job ${job.jobId} ended before a compiled result was created.`;
1168
+ }
1169
+ function compareCreatedAtDesc(left, right) {
1170
+ const leftTime = Date.parse(left.createdAt);
1171
+ const rightTime = Date.parse(right.createdAt);
1172
+ if (Number.isFinite(leftTime) && Number.isFinite(rightTime)) {
1173
+ return rightTime - leftTime;
1174
+ }
1175
+ if (Number.isFinite(rightTime)) {
1176
+ return 1;
1177
+ }
1178
+ if (Number.isFinite(leftTime)) {
1179
+ return -1;
1180
+ }
1181
+ return 0;
1182
+ }
1183
+ async function findFallbackCompiledResultForJob(options) {
1184
+ const { gameId, projectId, job } = options;
1185
+ if (!projectId) {
1186
+ return null;
1187
+ }
1188
+ const results = await listProjectCompiledResults({
1189
+ path: { projectId },
1190
+ query: { limit: 100 }
1191
+ });
1192
+ if (results.error || !results.data) {
1193
+ return null;
1194
+ }
1195
+ if (results.data.results.length === 0) {
1196
+ return null;
1197
+ }
1198
+ const jobCreatedAtMs = Date.parse(job.createdAt);
1199
+ const resultsCreatedAfterJob = Number.isFinite(jobCreatedAtMs) ? results.data.results.filter((result) => {
1200
+ const resultCreatedAtMs = Date.parse(result.createdAt);
1201
+ return !Number.isFinite(resultCreatedAtMs) || resultCreatedAtMs >= jobCreatedAtMs;
1202
+ }) : results.data.results;
1203
+ const candidateResults = resultsCreatedAfterJob.length > 0 ? resultsCreatedAfterJob : results.data.results;
1204
+ return [...candidateResults].sort(compareCreatedAtDesc)[0] ?? null;
1205
+ }
1206
+ async function findCompiledResultsForAuthoringState(options) {
1207
+ void options;
1208
+ return [];
1209
+ }
1210
+ async function getCompiledResultSdk(gameId, compiledResultId) {
1211
+ void gameId;
1212
+ void compiledResultId;
1213
+ throw new Error("Game-scoped compiled result lookup is no longer supported.");
1214
+ }
1215
+ async function getProjectCompiledResultSdk(projectId, compiledResultId) {
1216
+ const { data, error, response } = await getProjectCompiledResult({
1217
+ path: { projectId, compiledResultId }
1218
+ });
1219
+ if (error || !data) {
1220
+ throw toDreamboardApiError(
1221
+ error,
1222
+ response,
1223
+ "Failed to fetch compiled result"
1224
+ );
1225
+ }
1226
+ return data;
1227
+ }
1228
+ async function waitForCompiledResultJobSdk(options) {
1229
+ const { gameId, projectId, jobId, onProgress } = options;
1230
+ let previousTransitionKey = null;
1231
+ const startedAt = Date.now();
1232
+ const timeoutMs = readCompileJobWaitTimeoutMs();
1233
+ while (Date.now() - startedAt < timeoutMs) {
1234
+ const {
1235
+ data: job,
1236
+ error,
1237
+ response
1238
+ } = await getJob({
1239
+ path: { jobId }
1240
+ });
1241
+ if (error || !job) {
1242
+ if (isTransientJobPollError(error, response)) {
1243
+ await sleep2(COMPILE_JOB_POLL_INTERVAL_MS);
1244
+ continue;
1245
+ }
1246
+ throw toDreamboardApiError(error, response, "Failed to get job");
1247
+ }
1248
+ const transitionKey = `${job.status}:${job.phase ?? ""}`;
1249
+ if (transitionKey !== previousTransitionKey) {
1250
+ previousTransitionKey = transitionKey;
1251
+ onProgress?.(job);
1252
+ }
1253
+ if (job.status === "COMPLETED" || job.status === "FAILED") {
1254
+ const compiledResultId = job.createdCompiledResultId ?? job.createdAppScriptId;
1255
+ if (compiledResultId) {
1256
+ if (projectId) {
1257
+ const compiledResult2 = await getProjectCompiledResultSdk(
1258
+ projectId,
1259
+ compiledResultId
1260
+ );
1261
+ return { job, compiledResult: compiledResult2 };
1262
+ }
1263
+ const compiledResult = await getCompiledResultSdk(
1264
+ gameId,
1265
+ compiledResultId
1266
+ );
1267
+ return { job, compiledResult };
1268
+ }
1269
+ const fallbackCompiledResult = await findFallbackCompiledResultForJob({
1270
+ gameId,
1271
+ projectId,
1272
+ job
1273
+ });
1274
+ if (fallbackCompiledResult) {
1275
+ return { job, compiledResult: fallbackCompiledResult };
1276
+ }
1277
+ throw new Error(formatTerminalCompileJobMessage(job));
1278
+ }
1279
+ if (job.status === "CANCELLED" || job.status === "INTERRUPTED") {
1280
+ throw new Error(formatTerminalCompileJobMessage(job));
1281
+ }
1282
+ await sleep2(COMPILE_JOB_POLL_INTERVAL_MS);
1283
+ }
1284
+ throw new Error(`Compile job ${jobId} did not complete in time.`);
1285
+ }
1286
+ function readCompileJobWaitTimeoutMs() {
1287
+ const raw = process.env.DREAMBOARD_COMPILE_WAIT_TIMEOUT_MS;
1288
+ if (!raw) return DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS;
1289
+ const parsed = Number(raw);
1290
+ if (!Number.isFinite(parsed) || parsed <= 0) {
1291
+ return DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS;
1292
+ }
1293
+ return parsed;
1294
+ }
1295
+ function isTransientJobPollError(error, response) {
1296
+ if (response) return false;
1297
+ if (!error) return false;
1298
+ if (error instanceof Error) {
1299
+ return isTransientJobPollMessage(error.message);
1300
+ }
1301
+ if (typeof error === "object" && error !== null && "message" in error) {
1302
+ return isTransientJobPollMessage(String(error.message));
1303
+ }
1304
+ return isTransientJobPollMessage(String(error));
1305
+ }
1306
+ function isTransientJobPollMessage(message) {
1307
+ const normalized = message.toLowerCase();
1308
+ return normalized.includes("fetch failed") || normalized.includes("network") || normalized.includes("timeout") || normalized.includes("econnreset") || normalized.includes("econnrefused") || normalized.includes("socket");
1309
+ }
1310
+
1311
+ // src/services/testing/reducer-native-test-harness.ts
1312
+ import path3 from "path";
1313
+ import { randomUUID as randomUUID3 } from "crypto";
1314
+ import { createRequire } from "module";
1315
+ import { pathToFileURL as pathToFileURL2 } from "url";
1316
+ import {
1317
+ existsSync,
1318
+ mkdirSync,
1319
+ readFileSync,
1320
+ rmSync,
1321
+ writeFileSync
1322
+ } from "fs";
1323
+ import { readdir } from "fs/promises";
1324
+ import { isDeepStrictEqual } from "util";
1325
+
1326
+ // src/utils/ts-module-loader.ts
1327
+ import { mkdtemp, rm, writeFile } from "fs/promises";
1328
+ import { tmpdir } from "os";
1329
+ import path2 from "path";
1330
+ import { pathToFileURL } from "url";
1331
+ import { build } from "esbuild";
1332
+ var ESBUILD_EXTERNALS = [
1333
+ "playwright",
1334
+ "playwright-core",
1335
+ "chromium-bidi",
1336
+ "electron"
1337
+ ];
1338
+ function resolveSourceCheckoutBuildContext() {
1339
+ try {
1340
+ const repoRoot = resolveCliRepoRoot(import.meta.url);
1341
+ return {
1342
+ nodePaths: [
1343
+ path2.join(repoRoot, "apps", "dreamboard-cli", "node_modules"),
1344
+ path2.join(repoRoot, "node_modules")
1345
+ ],
1346
+ plugins: [createRepoLocalPackageResolutionPlugin({ repoRoot })]
1347
+ };
1348
+ } catch {
1349
+ return {
1350
+ nodePaths: [path2.join(process.cwd(), "node_modules")],
1351
+ plugins: []
1352
+ };
1353
+ }
1354
+ }
1355
+ async function bundleTypeScriptModuleText(entryPath, options = {}) {
1356
+ const sourceCheckoutContext = resolveSourceCheckoutBuildContext();
1357
+ const result = await build({
1358
+ entryPoints: [entryPath],
1359
+ bundle: true,
1360
+ format: "esm",
1361
+ platform: "node",
1362
+ target: "node24",
1363
+ sourcemap: "inline",
1364
+ external: [...ESBUILD_EXTERNALS, ...options.external ?? []],
1365
+ nodePaths: sourceCheckoutContext.nodePaths,
1366
+ plugins: sourceCheckoutContext.plugins,
1367
+ write: false
1368
+ });
1369
+ const output = result.outputFiles?.[0];
1370
+ if (!output) {
1371
+ throw new Error(`Failed to bundle TypeScript module '${entryPath}'.`);
1372
+ }
1373
+ return output.text;
1374
+ }
1375
+ async function importTypeScriptModule(entryPath) {
1376
+ const tempDir = await mkdtemp(path2.join(tmpdir(), "dreamboard-ts-module-"));
1377
+ const outfile = path2.join(
1378
+ tempDir,
1379
+ `${path2.basename(entryPath).replace(/\.[^.]+$/u, "")}.mjs`
1380
+ );
1381
+ try {
1382
+ const bundledText = await bundleTypeScriptModuleText(entryPath);
1383
+ await writeFile(outfile, bundledText);
1384
+ return await import(pathToFileURL(outfile).href);
1385
+ } finally {
1386
+ await rm(tempDir, { recursive: true, force: true });
1387
+ }
1388
+ }
1389
+
1390
+ // src/services/gameplay-authority-submit.ts
1391
+ import { randomUUID as randomUUID2 } from "crypto";
1392
+
1393
+ // ../../node_modules/.pnpm/@dreamboard-games+gameplay-authority-protocol@0.1.0-alpha.0/node_modules/@dreamboard-games/gameplay-authority-protocol/dist/frames.js
1394
+ var GAMEPLAY_AUTHORITY_AUDIENCE = "dreamboard-gameplay-authority";
1395
+ var GAMEPLAY_TUNNEL_AUDIENCE = "dreamboard-gameplay-authority-tunnel";
1396
+ var GameplayPermissionSchema = external_exports.enum([
1397
+ "observe",
1398
+ "submit",
1399
+ "restore-history"
1400
+ ]);
1401
+ var GameplayConnectionContextSchema = external_exports.object({
1402
+ sessionId: external_exports.string().uuid(),
1403
+ playerId: external_exports.string().min(1),
1404
+ permissions: external_exports.array(GameplayPermissionSchema)
1405
+ });
1406
+ var GameplayActorKindSchema = external_exports.enum(["user", "demo", "perf"]);
1407
+ var JsonPatchOperationSchema = external_exports.object({
1408
+ op: external_exports.string().min(1),
1409
+ path: external_exports.string()
1410
+ }).catchall(external_exports.unknown());
1411
+ var ProjectedDeltaSchema = external_exports.object({
1412
+ kind: external_exports.literal("delta"),
1413
+ generation: external_exports.number().int().nonnegative(),
1414
+ baseVersion: external_exports.number().int().nonnegative(),
1415
+ version: external_exports.number().int().nonnegative(),
1416
+ patch: external_exports.array(JsonPatchOperationSchema)
1417
+ });
1418
+ var ProjectedSnapshotSchema = external_exports.object({
1419
+ kind: external_exports.literal("snapshot"),
1420
+ generation: external_exports.number().int().nonnegative(),
1421
+ version: external_exports.number().int().nonnegative(),
1422
+ view: external_exports.unknown()
1423
+ });
1424
+ var BaseGameplayCapabilityClaimsSchema = external_exports.object({
1425
+ typ: external_exports.literal("gameplay-capability"),
1426
+ aud: external_exports.literal(GAMEPLAY_AUTHORITY_AUDIENCE),
1427
+ iss: external_exports.string().min(1),
1428
+ exp: external_exports.number().int().positive(),
1429
+ iat: external_exports.number().int().positive().optional(),
1430
+ jti: external_exports.string().min(1).optional(),
1431
+ sessionId: external_exports.string().uuid(),
1432
+ playerId: external_exports.string().min(1),
1433
+ permissions: external_exports.array(GameplayPermissionSchema)
1434
+ });
1435
+ var UserGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1436
+ actorKind: external_exports.literal("user")
1437
+ });
1438
+ var DemoGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1439
+ actorKind: external_exports.literal("demo")
1440
+ });
1441
+ var PerfGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1442
+ actorKind: external_exports.literal("perf"),
1443
+ perfRunId: external_exports.string().uuid(),
1444
+ laneId: external_exports.string().min(1)
1445
+ });
1446
+ var GameplayCapabilityClaimsSchema = external_exports.discriminatedUnion("actorKind", [
1447
+ UserGameplayCapabilityClaimsSchema,
1448
+ DemoGameplayCapabilityClaimsSchema,
1449
+ PerfGameplayCapabilityClaimsSchema
1450
+ ]);
1451
+ var GameplayTunnelClaimsSchema = external_exports.object({
1452
+ aud: external_exports.literal(GAMEPLAY_TUNNEL_AUDIENCE),
1453
+ iss: external_exports.string().min(1),
1454
+ exp: external_exports.number().int().positive(),
1455
+ iat: external_exports.number().int().positive().optional(),
1456
+ jti: external_exports.string().min(1).optional(),
1457
+ targetInstanceId: external_exports.string().min(1),
1458
+ sessionId: external_exports.string().uuid(),
1459
+ playerId: external_exports.string().min(1),
1460
+ // Permissions are cryptographically bound into the tunnel token so the owner
1461
+ // task trusts the signed claim set rather than the unauthenticated
1462
+ // `tunnel.bind` frame. An ingress task cannot grant a player capabilities the
1463
+ // issued token did not attest.
1464
+ permissions: external_exports.array(GameplayPermissionSchema)
1465
+ });
1466
+ var AuthConnectFrameSchema = external_exports.object({
1467
+ type: external_exports.literal("auth.connect"),
1468
+ capabilityToken: external_exports.string().min(1)
1469
+ });
1470
+ var AuthRefreshFrameSchema = external_exports.object({
1471
+ type: external_exports.literal("auth.refresh"),
1472
+ capabilityToken: external_exports.string().min(1)
1473
+ });
1474
+ var SessionResumeFrameSchema = external_exports.object({
1475
+ type: external_exports.literal("session.resume"),
1476
+ lastSeenGeneration: external_exports.number().int().nonnegative().nullable(),
1477
+ lastSeenVersion: external_exports.number().int().nonnegative().nullable(),
1478
+ unacknowledgedClientActionIds: external_exports.array(external_exports.string().min(1)).max(32)
1479
+ });
1480
+ var CommandSubmitFrameSchema = external_exports.object({
1481
+ type: external_exports.literal("command.submit"),
1482
+ clientActionId: external_exports.string().min(1).max(128),
1483
+ expectedVersion: external_exports.number().int().nonnegative(),
1484
+ actionSetVersion: external_exports.string().min(1),
1485
+ interactionId: external_exports.string().min(1),
1486
+ inputs: external_exports.record(external_exports.string(), external_exports.unknown())
1487
+ });
1488
+ var HistoryRestoreFrameSchema = external_exports.object({
1489
+ type: external_exports.literal("history.restore"),
1490
+ restoreId: external_exports.string().min(1).max(128),
1491
+ targetGeneration: external_exports.number().int().nonnegative(),
1492
+ targetVersion: external_exports.number().int().nonnegative()
1493
+ });
1494
+ var ClientGameplayFrameSchema = external_exports.discriminatedUnion("type", [
1495
+ AuthConnectFrameSchema,
1496
+ AuthRefreshFrameSchema,
1497
+ SessionResumeFrameSchema,
1498
+ CommandSubmitFrameSchema,
1499
+ HistoryRestoreFrameSchema
1500
+ ]);
1501
+ var TunnelBindFrameSchema = external_exports.object({
1502
+ type: external_exports.literal("tunnel.bind"),
1503
+ context: GameplayConnectionContextSchema
1504
+ });
1505
+ var TunnelClientFrameSchema = external_exports.discriminatedUnion("type", [
1506
+ TunnelBindFrameSchema,
1507
+ SessionResumeFrameSchema,
1508
+ CommandSubmitFrameSchema,
1509
+ HistoryRestoreFrameSchema
1510
+ ]);
1511
+ var CommandAcceptedFrameSchema = external_exports.object({
1512
+ type: external_exports.literal("command.accepted"),
1513
+ clientActionId: external_exports.string().min(1),
1514
+ generation: external_exports.number().int().nonnegative(),
1515
+ version: external_exports.number().int().nonnegative(),
1516
+ stateHash: external_exports.string().min(1),
1517
+ update: ProjectedSnapshotSchema
1518
+ });
1519
+ var CommandRejectedFrameSchema = external_exports.object({
1520
+ type: external_exports.literal("command.rejected"),
1521
+ clientActionId: external_exports.string().min(1).optional(),
1522
+ errorCode: external_exports.string().min(1),
1523
+ message: external_exports.string().min(1),
1524
+ currentGeneration: external_exports.number().int().nonnegative().optional(),
1525
+ currentVersion: external_exports.number().int().nonnegative().optional()
1526
+ });
1527
+ var HistoryRestoredFrameSchema = external_exports.object({
1528
+ type: external_exports.literal("history.restored"),
1529
+ restoreId: external_exports.string().min(1),
1530
+ generation: external_exports.number().int().nonnegative(),
1531
+ version: external_exports.number().int().nonnegative(),
1532
+ stateHash: external_exports.string().min(1),
1533
+ update: ProjectedSnapshotSchema
1534
+ });
1535
+ var HistoryRestoreRejectedFrameSchema = external_exports.object({
1536
+ type: external_exports.literal("history.restoreRejected"),
1537
+ restoreId: external_exports.string().min(1).optional(),
1538
+ errorCode: external_exports.string().min(1),
1539
+ message: external_exports.string().min(1),
1540
+ currentGeneration: external_exports.number().int().nonnegative().optional(),
1541
+ currentVersion: external_exports.number().int().nonnegative().optional()
1542
+ });
1543
+ var AuthAcceptedFrameSchema = external_exports.object({
1544
+ type: external_exports.literal("auth.accepted"),
1545
+ expiresAt: external_exports.string().datetime()
1546
+ });
1547
+ var AuthorityRecoveringFrameSchema = external_exports.object({
1548
+ type: external_exports.literal("authority.recovering"),
1549
+ retryAfterMs: external_exports.number().int().positive(),
1550
+ message: external_exports.string().min(1)
1551
+ });
1552
+ var SessionSnapshotFrameSchema = external_exports.object({
1553
+ type: external_exports.literal("session.snapshot"),
1554
+ generation: external_exports.number().int().nonnegative(),
1555
+ version: external_exports.number().int().nonnegative(),
1556
+ stateHash: external_exports.string().min(1),
1557
+ update: ProjectedSnapshotSchema
1558
+ });
1559
+ var SessionDeltaFrameSchema = external_exports.object({
1560
+ type: external_exports.literal("session.delta"),
1561
+ clientActionId: external_exports.string().min(1).optional(),
1562
+ update: ProjectedDeltaSchema
1563
+ });
1564
+ var ServerGameplayFrameSchema = external_exports.discriminatedUnion("type", [
1565
+ AuthAcceptedFrameSchema,
1566
+ AuthorityRecoveringFrameSchema,
1567
+ SessionSnapshotFrameSchema,
1568
+ SessionDeltaFrameSchema,
1569
+ CommandAcceptedFrameSchema,
1570
+ CommandRejectedFrameSchema,
1571
+ HistoryRestoredFrameSchema,
1572
+ HistoryRestoreRejectedFrameSchema
1573
+ ]);
1574
+ var TunnelBoundFrameSchema = external_exports.object({
1575
+ type: external_exports.literal("tunnel.bound"),
1576
+ sessionId: external_exports.string().uuid(),
1577
+ playerId: external_exports.string().min(1)
1578
+ });
1579
+ var TunnelServerFrameSchema = external_exports.discriminatedUnion("type", [
1580
+ TunnelBoundFrameSchema,
1581
+ AuthorityRecoveringFrameSchema,
1582
+ SessionSnapshotFrameSchema,
1583
+ SessionDeltaFrameSchema,
1584
+ CommandAcceptedFrameSchema,
1585
+ CommandRejectedFrameSchema,
1586
+ HistoryRestoredFrameSchema,
1587
+ HistoryRestoreRejectedFrameSchema
1588
+ ]);
1589
+
1590
+ // ../../node_modules/.pnpm/@dreamboard-games+gameplay-authority-client@0.1.0-alpha.1/node_modules/@dreamboard-games/gameplay-authority-client/dist/index.js
1591
+ var DEFAULT_OPEN_TIMEOUT_MS = 5e3;
1592
+ var DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
1593
+ var GameplayAuthorityRecoveringError = class extends Error {
1594
+ retryAfterMs;
1595
+ constructor(message, retryAfterMs) {
1596
+ super(message);
1597
+ this.name = "GameplayAuthorityRecoveringError";
1598
+ this.retryAfterMs = retryAfterMs;
1599
+ }
1600
+ };
1601
+ async function connectGameplayAuthority(input) {
1602
+ const webSocketFactory = input.webSocketFactory ?? browserWebSocketFactory();
1603
+ const openTimeoutMs = input.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS;
1604
+ const requestTimeoutMs = input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1605
+ const socket = new webSocketFactory(input.websocketUrl, input.webSocketInit);
1606
+ try {
1607
+ await waitUntilOpen(socket, openTimeoutMs);
1608
+ socket.send(JSON.stringify({
1609
+ type: "auth.connect",
1610
+ capabilityToken: input.capabilityToken
1611
+ }));
1612
+ await waitForServerFrame(socket, (frame) => frame.type === "auth.accepted", requestTimeoutMs);
1613
+ return new WebSocketGameplayAuthorityClient(socket, requestTimeoutMs);
1614
+ } catch (error) {
1615
+ socket.close();
1616
+ throw error;
1617
+ }
1618
+ }
1619
+ var WebSocketGameplayAuthorityClient = class {
1620
+ socket;
1621
+ requestTimeoutMs;
1622
+ constructor(socket, requestTimeoutMs) {
1623
+ this.socket = socket;
1624
+ this.requestTimeoutMs = requestTimeoutMs;
1625
+ }
1626
+ resume(input = {}) {
1627
+ this.socket.send(JSON.stringify({
1628
+ type: "session.resume",
1629
+ lastSeenGeneration: input.lastSeenGeneration ?? null,
1630
+ lastSeenVersion: input.lastSeenVersion ?? null,
1631
+ unacknowledgedClientActionIds: input.unacknowledgedClientActionIds ?? []
1632
+ }));
1633
+ }
1634
+ async submitCommand(input) {
1635
+ this.socket.send(JSON.stringify({
1636
+ type: "command.submit",
1637
+ clientActionId: input.clientActionId,
1638
+ expectedVersion: input.expectedVersion,
1639
+ actionSetVersion: input.actionSetVersion,
1640
+ interactionId: input.interactionId,
1641
+ inputs: input.inputs
1642
+ }));
1643
+ const frame = await waitForServerFrame(this.socket, (candidate) => candidate.type === "authority.recovering" || candidate.type === "command.accepted" && candidate.clientActionId === input.clientActionId || candidate.type === "command.rejected" && (candidate.clientActionId === void 0 || candidate.clientActionId === input.clientActionId), this.requestTimeoutMs);
1644
+ throwIfRecovering(frame);
1645
+ if (frame.type !== "command.accepted" && frame.type !== "command.rejected") {
1646
+ throw new Error("Unexpected gameplay authority command frame.");
1647
+ }
1648
+ return frame;
1649
+ }
1650
+ async restoreHistory(input) {
1651
+ this.socket.send(JSON.stringify({
1652
+ type: "history.restore",
1653
+ restoreId: input.restoreId,
1654
+ targetGeneration: input.targetGeneration,
1655
+ targetVersion: input.targetVersion
1656
+ }));
1657
+ const frame = await waitForServerFrame(this.socket, (candidate) => candidate.type === "authority.recovering" || candidate.type === "history.restored" && candidate.restoreId === input.restoreId || candidate.type === "history.restoreRejected" && (candidate.restoreId === void 0 || candidate.restoreId === input.restoreId), this.requestTimeoutMs);
1658
+ throwIfRecovering(frame);
1659
+ if (frame.type !== "history.restored" && frame.type !== "history.restoreRejected") {
1660
+ throw new Error("Unexpected gameplay authority history frame.");
1661
+ }
1662
+ return frame;
1663
+ }
1664
+ frames(signal) {
1665
+ return readServerFrames(this.socket, signal);
1666
+ }
1667
+ close() {
1668
+ this.socket.close();
1669
+ }
1670
+ };
1671
+ function throwIfRecovering(frame) {
1672
+ if (frame.type === "authority.recovering") {
1673
+ throw new GameplayAuthorityRecoveringError(frame.message, frame.retryAfterMs);
1674
+ }
1675
+ }
1676
+ function browserWebSocketFactory() {
1677
+ return BrowserGameplayAuthorityWebSocket;
1678
+ }
1679
+ var BrowserGameplayAuthorityWebSocket = class {
1680
+ socket;
1681
+ listeners = /* @__PURE__ */ new Map();
1682
+ constructor(url, init) {
1683
+ if (init?.headers && Object.keys(init.headers).length > 0) {
1684
+ throw new Error("Browser WebSocket does not support custom headers; provide a webSocketFactory for header-aware runtimes.");
1685
+ }
1686
+ this.socket = new WebSocket(url);
1687
+ }
1688
+ send(data) {
1689
+ this.socket.send(data);
1690
+ }
1691
+ close() {
1692
+ this.socket.close();
1693
+ }
1694
+ on(event, listener) {
1695
+ const wrapped = (observed) => {
1696
+ if (event === "message" && "data" in observed) {
1697
+ listener(observed.data);
1698
+ return;
1699
+ }
1700
+ listener(observed);
1701
+ };
1702
+ const listeners = this.listeners.get(event) ?? /* @__PURE__ */ new Map();
1703
+ listeners.set(listener, wrapped);
1704
+ this.listeners.set(event, listeners);
1705
+ this.socket.addEventListener(event, wrapped);
1706
+ }
1707
+ off(event, listener) {
1708
+ const listeners = this.listeners.get(event);
1709
+ const wrapped = listeners?.get(listener);
1710
+ if (!listeners || !wrapped) {
1711
+ return;
1712
+ }
1713
+ this.socket.removeEventListener(event, wrapped);
1714
+ listeners.delete(listener);
1715
+ }
1716
+ };
1717
+ async function waitUntilOpen(socket, timeoutMs) {
1718
+ await waitForEvent(socket, "open", timeoutMs);
1719
+ }
1720
+ async function waitForEvent(socket, event, timeoutMs) {
1721
+ return new Promise((resolve, reject) => {
1722
+ const cleanup = installSocketListeners(socket, {
1723
+ timeoutMs,
1724
+ onEvent(observed) {
1725
+ if (observed === event) {
1726
+ cleanup();
1727
+ resolve();
1728
+ }
1729
+ },
1730
+ onError(error) {
1731
+ cleanup();
1732
+ reject(error instanceof Error ? error : new Error("gameplay socket error"));
1733
+ },
1734
+ onClose() {
1735
+ cleanup();
1736
+ reject(new Error("gameplay socket closed"));
1737
+ },
1738
+ onTimeout() {
1739
+ cleanup();
1740
+ reject(new Error("gameplay socket timed out"));
1741
+ }
1742
+ });
1743
+ });
1744
+ }
1745
+ async function waitForServerFrame(socket, predicate, timeoutMs) {
1746
+ return new Promise((resolve, reject) => {
1747
+ const cleanup = installSocketListeners(socket, {
1748
+ timeoutMs,
1749
+ onMessage(data) {
1750
+ let frame;
1751
+ try {
1752
+ frame = ServerGameplayFrameSchema.parse(JSON.parse(messageToString(data)));
1753
+ } catch (error) {
1754
+ cleanup();
1755
+ reject(error instanceof Error ? error : new Error("invalid gameplay authority frame"));
1756
+ return;
1757
+ }
1758
+ if (predicate(frame)) {
1759
+ cleanup();
1760
+ resolve(frame);
1761
+ }
1762
+ },
1763
+ onError(error) {
1764
+ cleanup();
1765
+ reject(error instanceof Error ? error : new Error("gameplay socket error"));
1766
+ },
1767
+ onClose() {
1768
+ cleanup();
1769
+ reject(new Error("gameplay socket closed"));
1770
+ },
1771
+ onTimeout() {
1772
+ cleanup();
1773
+ reject(new Error("gameplay socket timed out"));
1774
+ }
1775
+ });
1776
+ });
1777
+ }
1778
+ function installSocketListeners(socket, handlers) {
1779
+ const timer = setTimeout(handlers.onTimeout, handlers.timeoutMs);
1780
+ const onOpen = () => handlers.onEvent?.("open");
1781
+ const onMessage = (data) => handlers.onMessage?.(data);
1782
+ const onError = (error) => handlers.onError(error);
1783
+ const onClose = () => handlers.onClose();
1784
+ socket.on("open", onOpen);
1785
+ socket.on("message", onMessage);
1786
+ socket.on("error", onError);
1787
+ socket.on("close", onClose);
1788
+ return () => {
1789
+ clearTimeout(timer);
1790
+ socket.off?.("open", onOpen);
1791
+ socket.off?.("message", onMessage);
1792
+ socket.off?.("error", onError);
1793
+ socket.off?.("close", onClose);
1794
+ };
1795
+ }
1796
+ function readServerFrames(socket, signal) {
1797
+ const queue = [];
1798
+ let wake = null;
1799
+ let closed = false;
1800
+ let error = null;
1801
+ const wakeReader = () => {
1802
+ wake?.();
1803
+ wake = null;
1804
+ };
1805
+ const onMessage = (data) => {
1806
+ try {
1807
+ queue.push(ServerGameplayFrameSchema.parse(JSON.parse(messageToString(data))));
1808
+ } catch (candidate) {
1809
+ error = candidate instanceof Error ? candidate : new Error("invalid gameplay authority frame");
1810
+ }
1811
+ wakeReader();
1812
+ };
1813
+ const onError = (candidate) => {
1814
+ error = candidate instanceof Error ? candidate : new Error("gameplay socket error");
1815
+ wakeReader();
1816
+ };
1817
+ const onClose = () => {
1818
+ closed = true;
1819
+ wakeReader();
1820
+ };
1821
+ const onAbort = () => {
1822
+ closed = true;
1823
+ wakeReader();
1824
+ };
1825
+ socket.on("message", onMessage);
1826
+ socket.on("error", onError);
1827
+ socket.on("close", onClose);
1828
+ signal?.addEventListener("abort", onAbort, { once: true });
1829
+ const cleanup = () => {
1830
+ socket.off?.("message", onMessage);
1831
+ socket.off?.("error", onError);
1832
+ socket.off?.("close", onClose);
1833
+ signal?.removeEventListener("abort", onAbort);
1834
+ };
1835
+ const iterator = {
1836
+ async next() {
1837
+ while (!closed && !signal?.aborted) {
1838
+ const next = queue.shift();
1839
+ if (next) {
1840
+ return { done: false, value: next };
1841
+ }
1842
+ if (error) {
1843
+ cleanup();
1844
+ throw error;
1845
+ }
1846
+ await new Promise((resolve) => {
1847
+ wake = resolve;
1848
+ });
1849
+ }
1850
+ cleanup();
1851
+ if (error) {
1852
+ throw error;
1853
+ }
1854
+ return { done: true, value: void 0 };
1855
+ },
1856
+ async return(value) {
1857
+ closed = true;
1858
+ wakeReader();
1859
+ cleanup();
1860
+ return { done: true, value };
1861
+ },
1862
+ async throw(candidate) {
1863
+ closed = true;
1864
+ wakeReader();
1865
+ cleanup();
1866
+ throw candidate;
1867
+ },
1868
+ [Symbol.asyncIterator]() {
1869
+ return this;
1870
+ },
1871
+ async [Symbol.asyncDispose]() {
1872
+ await this.return(void 0);
1873
+ }
1874
+ };
1875
+ return iterator;
1876
+ }
1877
+ function messageToString(data) {
1878
+ if (typeof data === "string") {
1879
+ return data;
1880
+ }
1881
+ if (data instanceof ArrayBuffer) {
1882
+ return new TextDecoder().decode(data);
1883
+ }
1884
+ if (ArrayBuffer.isView(data)) {
1885
+ return new TextDecoder().decode(data);
1886
+ }
1887
+ return String(data);
1888
+ }
1889
+
1890
+ // src/services/gameplay-authority-submit.ts
1891
+ var CLIENT_ACTION_ID_HEADER = "X-Dreamboard-Client-Action-Id";
1892
+ var DEFAULT_TIMEOUT_MS = 1e4;
1893
+ async function submitGameplayAuthorityAction(options) {
1894
+ try {
1895
+ const requestCapability = options.capabilityRequester ?? createGameplayCapability;
1896
+ const connectAuthority = options.connectAuthority ?? connectGameplayAuthority;
1897
+ const capability = await requestCapability({
1898
+ path: {
1899
+ sessionId: options.path.sessionId,
1900
+ playerId: options.path.playerId
1901
+ }
1902
+ });
1903
+ if (capability.error || !capability.data) {
1904
+ return { error: capability.error ?? new Error("Missing capability.") };
1905
+ }
1906
+ const clientActionId = options.headers?.[CLIENT_ACTION_ID_HEADER] ?? options.clientActionIdFactory?.() ?? randomUUID2();
1907
+ const client2 = await connectAuthority({
1908
+ websocketUrl: capability.data.websocketUrl,
1909
+ capabilityToken: capability.data.token,
1910
+ openTimeoutMs: DEFAULT_TIMEOUT_MS,
1911
+ requestTimeoutMs: DEFAULT_TIMEOUT_MS
1912
+ });
1913
+ try {
1914
+ const frame = await client2.submitCommand({
1915
+ clientActionId,
1916
+ expectedVersion: options.body.expectedVersion,
1917
+ actionSetVersion: options.body.actionSetVersion,
1918
+ interactionId: options.path.interactionId,
1919
+ inputs: options.body.inputs ?? {}
1920
+ });
1921
+ if (frame.type === "command.rejected") {
1922
+ return {
1923
+ data: {
1924
+ success: false,
1925
+ accepted: false,
1926
+ version: typeof frame.currentVersion === "number" ? frame.currentVersion : options.body.expectedVersion,
1927
+ actionSetVersion: options.body.actionSetVersion,
1928
+ errorCode: typeof frame.errorCode === "string" ? frame.errorCode : void 0,
1929
+ message: typeof frame.message === "string" ? frame.message : void 0,
1930
+ clientActionId
1931
+ }
1932
+ };
1933
+ }
1934
+ const acceptedVersion = typeof frame.version === "number" ? frame.version : void 0;
1935
+ if (acceptedVersion === void 0) {
1936
+ return {
1937
+ error: new Error("Accepted frame did not include a numeric version.")
1938
+ };
1939
+ }
1940
+ const update = frame.update && typeof frame.update === "object" ? frame.update : {};
1941
+ const view = update.view && typeof update.view === "object" ? update.view : {};
1942
+ const projectedActionSetVersion = typeof view.actionSetVersion === "string" ? view.actionSetVersion : void 0;
1943
+ return {
1944
+ data: {
1945
+ success: true,
1946
+ accepted: true,
1947
+ durabilityStatus: "COMMITTED",
1948
+ version: acceptedVersion,
1949
+ actionSetVersion: projectedActionSetVersion ?? options.body.actionSetVersion,
1950
+ clientActionId
1951
+ }
1952
+ };
1953
+ } catch (error) {
1954
+ if (error instanceof GameplayAuthorityRecoveringError) {
1955
+ return {
1956
+ error: new Error(error.message || "Session authority is recovering.")
1957
+ };
1958
+ }
1959
+ throw error;
1960
+ } finally {
1961
+ client2.close();
1962
+ }
1963
+ } catch (error) {
1964
+ return { error };
1965
+ }
1966
+ }
1967
+
1968
+ // src/services/workflows/resolve-setup-profile.ts
1969
+ function resolveSetupProfileSelection(options) {
1970
+ const setupProfiles = options.manifest.setupProfiles ?? [];
1971
+ const requestedSetupProfileId = options.requestedSetupProfileId?.trim() || void 0;
1972
+ if (requestedSetupProfileId) {
1973
+ const requestedProfile = setupProfiles.find(
1974
+ (profile) => profile.id === requestedSetupProfileId
1975
+ );
1976
+ if (!requestedProfile) {
1977
+ const knownProfiles = setupProfiles.map((profile) => profile.id).join(", ");
1978
+ throw new Error(
1979
+ setupProfiles.length === 0 ? `Unknown setup profile '${requestedSetupProfileId}'. The manifest defines no setup profiles.` : `Unknown setup profile '${requestedSetupProfileId}'. Expected one of: ${knownProfiles}.`
1980
+ );
1981
+ }
1982
+ return {
1983
+ id: requestedProfile.id,
1984
+ name: requestedProfile.name,
1985
+ source: "explicit"
1986
+ };
1987
+ }
1988
+ if (setupProfiles.length === 0) {
1989
+ return {
1990
+ id: null,
1991
+ name: null,
1992
+ source: "none"
1993
+ };
1994
+ }
1995
+ if (setupProfiles.length === 1) {
1996
+ return {
1997
+ id: setupProfiles[0]?.id ?? null,
1998
+ name: setupProfiles[0]?.name ?? null,
1999
+ source: "implicit-single"
2000
+ };
2001
+ }
2002
+ return {
2003
+ id: setupProfiles[0]?.id ?? null,
2004
+ name: setupProfiles[0]?.name ?? null,
2005
+ source: "implicit-first"
2006
+ };
2007
+ }
2008
+ async function resolveSetupProfileSelectionForSession(options) {
2009
+ const manifest = await loadManifest(options.projectRoot);
2010
+ return resolveSetupProfileSelection({
2011
+ manifest,
2012
+ requestedSetupProfileId: options.requestedSetupProfileId
2013
+ });
2014
+ }
2015
+
2016
+ // src/utils/session-game-source.ts
2017
+ function projectIdFromSessionGameSource(source) {
2018
+ if (source.kind === "USER_COMPILED") {
2019
+ return source.projectId;
2020
+ }
2021
+ return `demo:${source.slug}:${source.revisionId}`;
2022
+ }
2023
+
2024
+ // src/services/testing/reducer-native-test-harness.ts
2025
+ globalThis.__DREAMBOARD_AUTHORING_WARNINGS__ = true;
2026
+ var GENERATED_TESTING_TYPES_PREFIX = "// Generated by dreamboard";
2027
+ var TESTING_TYPES_STUB = "export function defineScenario(scenario) { return scenario; }\n";
2028
+ var BASE_SUFFIX = ".base.ts";
2029
+ var SCENARIO_SUFFIX = ".scenario.ts";
2030
+ var SDK_UI_RUNTIME_EXTERNALS = [
2031
+ "@radix-ui/react-accordion",
2032
+ "@radix-ui/react-dialog",
2033
+ "@radix-ui/react-label",
2034
+ "@radix-ui/react-select",
2035
+ "@radix-ui/react-slot",
2036
+ "@radix-ui/react-tooltip",
2037
+ "@use-gesture/react",
2038
+ "clsx",
2039
+ "framer-motion",
2040
+ "lucide-react",
2041
+ "react",
2042
+ "react-dom",
2043
+ "vaul"
2044
+ ];
2045
+ function formatScenarioErrorForDisplay(options) {
2046
+ const message = options.error.message || "Scenario failed.";
2047
+ const scenarioFrame = findScenarioStackFrame({
2048
+ stack: options.error.stack,
2049
+ projectRoot: options.projectRoot,
2050
+ scenarioFilePath: options.scenarioFilePath
2051
+ });
2052
+ return scenarioFrame ? `${message}
2053
+ ${scenarioFrame}` : message;
2054
+ }
2055
+ function findScenarioStackFrame(options) {
2056
+ if (!options.stack) {
2057
+ return null;
2058
+ }
2059
+ const absolutePath = path3.resolve(options.scenarioFilePath);
2060
+ const relativePath = path3.relative(options.projectRoot, absolutePath);
2061
+ const normalizedRelativePath = relativePath.split(path3.sep).join("/");
2062
+ const escapedAbsolutePath = escapeRegExp(absolutePath);
2063
+ const escapedRelativePath = escapeRegExp(normalizedRelativePath);
2064
+ const absoluteFrame = new RegExp(`${escapedAbsolutePath}:(\\d+):(\\d+)`);
2065
+ const relativeFrame = new RegExp(`${escapedRelativePath}:(\\d+):(\\d+)`);
2066
+ for (const line of options.stack.split("\n")) {
2067
+ const normalizedLine = line.split(path3.sep).join("/");
2068
+ const match = normalizedLine.match(absoluteFrame) ?? normalizedLine.match(relativeFrame);
2069
+ if (match?.[1] && match?.[2]) {
2070
+ return `at ${normalizedRelativePath}:${match[1]}:${match[2]}`;
2071
+ }
2072
+ }
2073
+ return null;
2074
+ }
2075
+ function escapeRegExp(value) {
2076
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2077
+ }
2078
+ var projectReducerNativeModules = /* @__PURE__ */ new Map();
2079
+ function resolveProjectSdkModule(projectRoot, specifier) {
2080
+ const requireFromProject = createRequire(
2081
+ path3.join(projectRoot, "package.json")
2082
+ );
2083
+ return requireFromProject.resolve(specifier);
2084
+ }
2085
+ async function importProjectSdkModule(projectRoot, specifier) {
2086
+ const modulePath = resolveProjectSdkModule(projectRoot, specifier);
2087
+ return await import(pathToFileURL2(modulePath).href);
2088
+ }
2089
+ async function loadProjectReducerNativeModules(projectRoot) {
2090
+ const cacheKey = path3.resolve(projectRoot);
2091
+ const cached = projectReducerNativeModules.get(cacheKey);
2092
+ if (cached) {
2093
+ return cached;
2094
+ }
2095
+ const promise = Promise.all([
2096
+ importProjectSdkModule(cacheKey, "@dreamboard-games/sdk/reducer"),
2097
+ importProjectSdkModule(cacheKey, "@dreamboard-games/sdk/reducer-contract"),
2098
+ importProjectSdkModule(
2099
+ cacheKey,
2100
+ "@dreamboard-games/sdk/testing"
2101
+ )
2102
+ ]).then(([reducerModule, reducerContractModule, testingModule]) => {
2103
+ if (typeof reducerModule.createReducerBundle !== "function" || typeof reducerModule.contractFingerprint !== "function" || typeof reducerContractModule.materializeManifestTable !== "function" || typeof testingModule.createExpectApi !== "function") {
2104
+ throw new Error(
2105
+ "Installed @dreamboard-games/sdk does not expose the reducer-native test helpers required by this CLI."
2106
+ );
2107
+ }
2108
+ return {
2109
+ createReducerBundle: reducerModule.createReducerBundle,
2110
+ contractFingerprint: reducerModule.contractFingerprint,
2111
+ materializeManifestTable: reducerContractModule.materializeManifestTable,
2112
+ createExpectApi: testingModule.createExpectApi
2113
+ };
2114
+ });
2115
+ projectReducerNativeModules.set(cacheKey, promise);
2116
+ return promise;
2117
+ }
2118
+ function createSubmissionError(errorCode, message, fallbackMessage) {
2119
+ const error = new Error(message ?? fallbackMessage);
2120
+ error.name = "SubmissionError";
2121
+ error.errorCode = errorCode;
2122
+ return error;
2123
+ }
2124
+ function deepEqual(left, right) {
2125
+ return isDeepStrictEqual(left, right);
2126
+ }
2127
+ function shouldRefreshReducerTestingTypes(existingContent) {
2128
+ if (existingContent === null || existingContent.trim().length === 0 || existingContent === TESTING_TYPES_STUB || existingContent.startsWith(GENERATED_TESTING_TYPES_PREFIX)) {
2129
+ return true;
2130
+ }
2131
+ return false;
2132
+ }
2133
+ async function discoverFiles(root, suffix) {
2134
+ if (!await exists(root)) {
2135
+ return [];
2136
+ }
2137
+ const entries = await readdir(root, { withFileTypes: true });
2138
+ const files = [];
2139
+ for (const entry of entries) {
2140
+ const entryPath = path3.join(root, entry.name);
2141
+ if (entry.isDirectory()) {
2142
+ files.push(...await discoverFiles(entryPath, suffix));
2143
+ continue;
2144
+ }
2145
+ if (entry.isFile() && entry.name.endsWith(suffix)) {
2146
+ files.push(entryPath);
2147
+ }
2148
+ }
2149
+ files.sort();
2150
+ return files;
2151
+ }
2152
+ function isFunction(value) {
2153
+ return typeof value === "function";
2154
+ }
2155
+ function parseTypedBaseDefinition(value) {
2156
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || !("setup" in value) || !isFunction(value.setup)) {
2157
+ throw new Error("Invalid reducer-native base definition.");
2158
+ }
2159
+ const parentBaseId = "extends" in value && typeof value.extends === "string" ? value.extends : void 0;
2160
+ const seed = "seed" in value && typeof value.seed === "number" ? value.seed : void 0;
2161
+ const players = "players" in value && typeof value.players === "number" ? value.players : void 0;
2162
+ if ((seed === void 0 || players === void 0) && !parentBaseId) {
2163
+ throw new Error(
2164
+ "Invalid reducer-native base definition. Base definitions without --extends must declare numeric seed and players."
2165
+ );
2166
+ }
2167
+ const setupProfileId = "setupProfileId" in value && typeof value.setupProfileId === "string" ? value.setupProfileId : void 0;
2168
+ return {
2169
+ ...value,
2170
+ seed,
2171
+ players,
2172
+ setupProfileId,
2173
+ extends: parentBaseId
2174
+ };
2175
+ }
2176
+ function parseTypedScenarioDefinition(value) {
2177
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || !("from" in value) || typeof value.from !== "string" || !("when" in value) || !isFunction(value.when) || !("then" in value) || !isFunction(value.then)) {
2178
+ throw new Error("Invalid reducer-native scenario definition.");
2179
+ }
2180
+ const phase = "phase" in value && typeof value.phase === "string" ? value.phase : void 0;
2181
+ const stage = "stage" in value && typeof value.stage === "string" ? value.stage : void 0;
2182
+ return {
2183
+ ...value,
2184
+ phase,
2185
+ stage
2186
+ };
2187
+ }
2188
+ async function isReducerNativeTestingWorkspace(projectRoot) {
2189
+ return await exists(path3.join(projectRoot, "app", "game.ts")) && await exists(
2190
+ path3.join(projectRoot, "shared", "generated", "ui-contract.ts")
2191
+ );
2192
+ }
2193
+ async function ensureReducerNativeTestingFiles(projectRoot) {
2194
+ const testingTypesPath = "test/testing-types.ts";
2195
+ const testingContractPath = "test/generated/testing-contract.ts";
2196
+ const baseStatesPath = "test/generated/base-states.generated.ts";
2197
+ const baseStatesDtsPath = "test/generated/base-states.generated.d.ts";
2198
+ const scenarioManifestPath = "test/generated/scenario-manifest.generated.ts";
2199
+ await ensureDir(resolveWorkspacePath(projectRoot, "test"));
2200
+ await ensureDir(resolveWorkspacePath(projectRoot, "test/generated"));
2201
+ const existingTestingTypes = await readWorkspaceTextFileIfExists(
2202
+ projectRoot,
2203
+ testingTypesPath
2204
+ );
2205
+ if (shouldRefreshReducerTestingTypes(existingTestingTypes)) {
2206
+ await writeWorkspaceTextFile(
2207
+ projectRoot,
2208
+ testingTypesPath,
2209
+ REDUCER_TESTING_TYPES_WRAPPER_CONTENT
2210
+ );
2211
+ }
2212
+ const rejectionCodes = await collectKnownRejectionCodes(projectRoot);
2213
+ await writeWorkspaceTextFile(
2214
+ projectRoot,
2215
+ testingContractPath,
2216
+ buildReducerTestingContractContent({ rejectionCodes })
2217
+ );
2218
+ const header = "// Generated by dreamboard test. Do not edit by hand.\n";
2219
+ if (!await workspacePathExists(projectRoot, baseStatesPath)) {
2220
+ await writeWorkspaceTextFile(
2221
+ projectRoot,
2222
+ baseStatesPath,
2223
+ `${header}export const BASE_STATES = {} as const;
2224
+ export const BASE_STATES_CONTRACT_FINGERPRINT = undefined;
2225
+ `
2226
+ );
2227
+ } else {
2228
+ const existingBaseStates = await readWorkspaceTextFileIfExists(
2229
+ projectRoot,
2230
+ baseStatesPath
2231
+ );
2232
+ if (existingBaseStates && !existingBaseStates.includes("BASE_STATES_CONTRACT_FINGERPRINT")) {
2233
+ await writeWorkspaceTextFile(
2234
+ projectRoot,
2235
+ baseStatesPath,
2236
+ `${existingBaseStates.trimEnd()}
2237
+ export const BASE_STATES_CONTRACT_FINGERPRINT = undefined;
2238
+ `
2239
+ );
2240
+ }
2241
+ }
2242
+ if (!await workspacePathExists(projectRoot, baseStatesDtsPath)) {
2243
+ await writeWorkspaceTextFile(
2244
+ projectRoot,
2245
+ baseStatesDtsPath,
2246
+ `${header}export declare const BASE_STATES: Record<string, unknown>;
2247
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
2248
+ `
2249
+ );
2250
+ } else {
2251
+ const existingBaseStatesDts = await readWorkspaceTextFileIfExists(
2252
+ projectRoot,
2253
+ baseStatesDtsPath
2254
+ );
2255
+ if (existingBaseStatesDts && !existingBaseStatesDts.includes("BASE_STATES_CONTRACT_FINGERPRINT")) {
2256
+ await writeWorkspaceTextFile(
2257
+ projectRoot,
2258
+ baseStatesDtsPath,
2259
+ `${existingBaseStatesDts.trimEnd()}
2260
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
2261
+ `
2262
+ );
2263
+ }
2264
+ }
2265
+ if (!await workspacePathExists(projectRoot, scenarioManifestPath)) {
2266
+ await writeWorkspaceTextFile(
2267
+ projectRoot,
2268
+ scenarioManifestPath,
2269
+ `${header}export const SCENARIO_MANIFEST = [] as const;
2270
+ `
2271
+ );
2272
+ }
2273
+ }
2274
+ var DEFAULT_REJECTION_CODES = [
2275
+ "NOT_YOUR_TURN",
2276
+ "action-unavailable",
2277
+ "invalid-action-params",
2278
+ "prompt-not-owned"
2279
+ ];
2280
+ async function collectKnownRejectionCodes(projectRoot) {
2281
+ const knownCodes = new Set(DEFAULT_REJECTION_CODES);
2282
+ const gamePath = path3.join(projectRoot, "app", "game.ts");
2283
+ if (!await exists(gamePath)) {
2284
+ return Array.from(knownCodes).sort(
2285
+ (left, right) => left.localeCompare(right)
2286
+ );
2287
+ }
2288
+ try {
2289
+ const module = await importTypeScriptModule(gamePath);
2290
+ const phases = module.default?.phases ?? {};
2291
+ for (const phase of Object.values(phases)) {
2292
+ const interactions = phase.interactions ?? {};
2293
+ for (const interaction of Object.values(interactions)) {
2294
+ for (const errorCode of interaction.errorCodes ?? []) {
2295
+ if (typeof errorCode === "string" && errorCode.length > 0) {
2296
+ knownCodes.add(errorCode);
2297
+ }
2298
+ }
2299
+ }
2300
+ }
2301
+ } catch {
2302
+ }
2303
+ return Array.from(knownCodes).sort(
2304
+ (left, right) => left.localeCompare(right)
2305
+ );
2306
+ }
2307
+ async function loadTypedBases(projectRoot) {
2308
+ const baseFiles = await discoverFiles(
2309
+ resolveWorkspacePath(projectRoot, "test/bases"),
2310
+ BASE_SUFFIX
2311
+ );
2312
+ const loaded = [];
2313
+ for (const filePath of baseFiles) {
2314
+ const externals = reducerNativeTestHelperExternals(projectRoot, filePath);
2315
+ const [module, bundledText] = await Promise.all([
2316
+ importTypeScriptModule(filePath),
2317
+ bundleTypeScriptModuleText(filePath, { external: externals })
2318
+ ]);
2319
+ loaded.push({
2320
+ filePath,
2321
+ definition: parseTypedBaseDefinition(module.default),
2322
+ bundleHash: hashContent(bundledText)
2323
+ });
2324
+ }
2325
+ return loaded;
2326
+ }
2327
+ async function loadTypedScenarios(projectRoot, options) {
2328
+ const scenarioFiles = options.scenarioPath ? [resolveWorkspacePath(projectRoot, options.scenarioPath)] : await discoverFiles(
2329
+ resolveWorkspacePath(projectRoot, "test/scenarios"),
2330
+ SCENARIO_SUFFIX
2331
+ );
2332
+ const loaded = [];
2333
+ for (const filePath of scenarioFiles) {
2334
+ const externals = reducerNativeTestHelperExternals(projectRoot, filePath);
2335
+ const [module, bundledText] = await Promise.all([
2336
+ importTypeScriptModule(filePath),
2337
+ bundleTypeScriptModuleText(filePath, { external: externals })
2338
+ ]);
2339
+ loaded.push({
2340
+ filePath,
2341
+ definition: parseTypedScenarioDefinition(module.default),
2342
+ bundleHash: hashContent(bundledText)
2343
+ });
2344
+ }
2345
+ return loaded;
2346
+ }
2347
+ function reducerNativeTestHelperExternals(projectRoot, filePath) {
2348
+ const testingTypesPath = path3.join(projectRoot, "test", "testing-types");
2349
+ const relative = path3.relative(path3.dirname(filePath), testingTypesPath).replaceAll("\\", "/");
2350
+ const specifier = relative.startsWith(".") ? relative : `./${relative}`;
2351
+ return [specifier, `${specifier}.ts`, ...SDK_UI_RUNTIME_EXTERNALS];
2352
+ }
2353
+ var JS_MAX_SAFE_INTEGER = 9007199254740991n;
2354
+ var JS_MIN_SAFE_INTEGER = -JS_MAX_SAFE_INTEGER;
2355
+ var JS_MAX_SAFE_INTEGER_EXCLUSIVE = JS_MAX_SAFE_INTEGER + 1n;
2356
+ var KotlinSeededRandom = class {
2357
+ x;
2358
+ y;
2359
+ z;
2360
+ w;
2361
+ v;
2362
+ addend;
2363
+ constructor(seed) {
2364
+ const seedBig = BigInt.asIntN(64, BigInt(Math.trunc(seed)));
2365
+ const seed1 = Number(BigInt.asIntN(32, seedBig));
2366
+ const seed2 = Number(BigInt.asIntN(32, seedBig >> 32n));
2367
+ this.x = seed1 | 0;
2368
+ this.y = seed2 | 0;
2369
+ this.z = 0;
2370
+ this.w = 0;
2371
+ this.v = ~seed1;
2372
+ this.addend = seed1 << 10 ^ seed2 >>> 4 | 0;
2373
+ if ((this.x | this.y | this.z | this.w | this.v) === 0) {
2374
+ throw new Error(
2375
+ "Kotlin random seed must initialize at least one state word."
2376
+ );
2377
+ }
2378
+ for (let index = 0; index < 64; index += 1) {
2379
+ this.nextInt();
2380
+ }
2381
+ }
2382
+ nextInt() {
2383
+ let next = this.x | 0;
2384
+ next ^= next >>> 2;
2385
+ this.x = this.y;
2386
+ this.y = this.z;
2387
+ this.z = this.w;
2388
+ const currentV = this.v | 0;
2389
+ this.w = currentV;
2390
+ next = next ^ next << 1 ^ currentV ^ currentV << 4 | 0;
2391
+ this.v = next;
2392
+ this.addend = this.addend + 362437 | 0;
2393
+ return next + this.addend | 0;
2394
+ }
2395
+ nextBits(bitCount) {
2396
+ if (bitCount <= 0) {
2397
+ return 0;
2398
+ }
2399
+ return this.nextInt() >>> 32 - bitCount;
2400
+ }
2401
+ nextIntBound(bound) {
2402
+ if (bound <= 0) {
2403
+ throw new Error("bound must be positive");
2404
+ }
2405
+ if ((bound & -bound) === bound) {
2406
+ const bitCount = 31 - Math.clz32(bound);
2407
+ return this.nextBits(bitCount);
2408
+ }
2409
+ let value;
2410
+ while (true) {
2411
+ const bits = this.nextInt() >>> 1;
2412
+ value = bits % bound;
2413
+ if (bits - value + (bound - 1) >= 0) {
2414
+ return value;
2415
+ }
2416
+ }
2417
+ }
2418
+ nextLong() {
2419
+ return Number(this.nextLongBigInt());
2420
+ }
2421
+ nextLongBigInt() {
2422
+ const high = BigInt(this.nextInt());
2423
+ const low = BigInt(this.nextInt());
2424
+ return BigInt.asIntN(64, (high << 32n) + low);
2425
+ }
2426
+ nextReducerRuntimeSeed() {
2427
+ return Number(
2428
+ this.nextLongRange(JS_MIN_SAFE_INTEGER, JS_MAX_SAFE_INTEGER_EXCLUSIVE)
2429
+ );
2430
+ }
2431
+ nextLongRange(from, until) {
2432
+ if (until <= from) {
2433
+ throw new Error("until must be greater than from");
2434
+ }
2435
+ const bound = until - from;
2436
+ const mask = bound - 1n;
2437
+ if ((bound & mask) === 0n) {
2438
+ return from + (BigInt.asUintN(64, this.nextLongBigInt()) & mask);
2439
+ }
2440
+ while (true) {
2441
+ const bits = BigInt.asUintN(64, this.nextLongBigInt()) >> 1n;
2442
+ const value = bits % bound;
2443
+ if (BigInt.asIntN(64, bits + mask - value) >= 0n) {
2444
+ return from + value;
2445
+ }
2446
+ }
2447
+ }
2448
+ };
2449
+ function shuffleWithKotlinRandom(values, random) {
2450
+ const next = [...values];
2451
+ for (let index = next.length - 1; index > 0; index -= 1) {
2452
+ const swapIndex = random.nextIntBound(index + 1);
2453
+ const current = next[index];
2454
+ next[index] = next[swapIndex];
2455
+ next[swapIndex] = current;
2456
+ }
2457
+ return next;
2458
+ }
2459
+ function resolveEffectiveBaseSetup(options) {
2460
+ const inheritedSetupProfileId = options.base.setupProfileId ?? (options.base.extends && options.basesById ? resolveEffectiveBaseSetup({
2461
+ manifest: options.manifest,
2462
+ base: options.basesById.get(options.base.extends)?.definition ?? (() => {
2463
+ throw new Error(
2464
+ `Base '${options.base.id}' extends unknown parent '${options.base.extends}'.`
2465
+ );
2466
+ })(),
2467
+ basesById: options.basesById
2468
+ }).setupProfileId : void 0);
2469
+ const selection = resolveSetupProfileSelection({
2470
+ manifest: options.manifest,
2471
+ requestedSetupProfileId: inheritedSetupProfileId ?? void 0
2472
+ });
2473
+ return {
2474
+ setupProfileId: selection.id
2475
+ };
2476
+ }
2477
+ function resolveBaseDefinition(base, basesById) {
2478
+ const inherited = base.definition.extends !== void 0 ? resolveBaseDefinition(
2479
+ basesById.get(base.definition.extends) ?? (() => {
2480
+ throw new Error(
2481
+ `Base '${base.definition.id}' extends unknown parent '${base.definition.extends}'.`
2482
+ );
2483
+ })(),
2484
+ basesById
2485
+ ) : null;
2486
+ const seed = base.definition.seed ?? inherited?.seed;
2487
+ const players = base.definition.players ?? inherited?.players;
2488
+ if (seed === void 0 || players === void 0) {
2489
+ throw new Error(
2490
+ `Base '${base.definition.id}' must resolve numeric seed and players.`
2491
+ );
2492
+ }
2493
+ return {
2494
+ ...base.definition,
2495
+ seed,
2496
+ players,
2497
+ setupProfileId: base.definition.setupProfileId ?? inherited?.setupProfileId ?? void 0
2498
+ };
2499
+ }
2500
+ function summarizeTableValidationError(manifest, error) {
2501
+ const issues = error.message.split("; ").map((issue) => issue.trim()).filter((issue) => issue.length > 0);
2502
+ if (issues.length === 0 || !issues.every((issue) => issue.startsWith("table"))) {
2503
+ return error.message;
2504
+ }
2505
+ const boardBaseIdByRuntimeId = new Map(
2506
+ (manifest.boards ?? []).flatMap(
2507
+ (board) => board.scope === "perPlayer" ? Array.from(
2508
+ { length: manifest.players.maxPlayers },
2509
+ (_, index) => [`${board.id}:player-${index + 1}`, board.id]
2510
+ ) : [[board.id, board.id]]
2511
+ )
2512
+ );
2513
+ const representativeIssues = issues.slice(0, 3).map((issue) => {
2514
+ const [, runtimeBoardId = ""] = issue.match(/^table\.boards\.byId\.([^.]+)\./) ?? [];
2515
+ const boardBaseId = boardBaseIdByRuntimeId.get(runtimeBoardId);
2516
+ if (!boardBaseId) {
2517
+ return `- ${issue.replace(/^table\./, "")}`;
2518
+ }
2519
+ const boardSpecificPath = issue.replace(/^table\.boards\.byId\.[^.]+\./, "").replace(/^table\./, "");
2520
+ return `- board '${boardBaseId}' (${runtimeBoardId}): ${boardSpecificPath}`;
2521
+ });
2522
+ return [
2523
+ `Reducer-native table validation failed with ${issues.length} issue${issues.length === 1 ? "" : "s"}.`,
2524
+ "Likely root cause: the generated test table shape does not match the authored manifest topology.",
2525
+ ...representativeIssues,
2526
+ "Pass --debug for the full validation dump."
2527
+ ].join("\n");
2528
+ }
2529
+ var ShadowReducerRuntime = class {
2530
+ constructor(modules, manifest, gameModuleDefault, createInitialTable, seed, players, setupProfileId, debug = false) {
2531
+ this.modules = modules;
2532
+ this.manifest = manifest;
2533
+ this.gameModuleDefault = gameModuleDefault;
2534
+ this.createInitialTable = createInitialTable;
2535
+ this.seed = seed;
2536
+ this.players = players;
2537
+ this.setupProfileId = setupProfileId;
2538
+ this.debug = debug;
2539
+ if (typeof gameModuleDefault !== "object" || gameModuleDefault === null || !("contract" in gameModuleDefault)) {
2540
+ throw new Error(
2541
+ "app/game.ts must export a reducer-native game definition."
2542
+ );
2543
+ }
2544
+ this.bundle = this.modules.createReducerBundle(gameModuleDefault);
2545
+ this.runtime = this.bundle.createInProcessRuntime();
2546
+ this.playerIds = Array.from(
2547
+ { length: players },
2548
+ (_, index) => `player-${index + 1}`
2549
+ );
2550
+ }
2551
+ bundle;
2552
+ runtime;
2553
+ playerIds;
2554
+ historyRecords = [];
2555
+ version = 0;
2556
+ started = false;
2557
+ async start() {
2558
+ if (this.started) {
2559
+ return;
2560
+ }
2561
+ const random = new KotlinSeededRandom(this.seed);
2562
+ const shuffleItems = (values) => shuffleWithKotlinRandom(values, random);
2563
+ const table = JSON.parse(
2564
+ JSON.stringify(
2565
+ this.createInitialTable?.({
2566
+ playerIds: this.playerIds,
2567
+ shuffleItems
2568
+ }) ?? this.modules.materializeManifestTable({
2569
+ manifest: this.manifest,
2570
+ playerIds: this.playerIds,
2571
+ shuffleItems
2572
+ })
2573
+ )
2574
+ );
2575
+ const rngSeed = random.nextReducerRuntimeSeed();
2576
+ try {
2577
+ await this.runtime.initialize({
2578
+ table,
2579
+ playerIds: this.playerIds,
2580
+ rngSeed,
2581
+ setup: this.setupProfileId ? {
2582
+ profileId: this.setupProfileId
2583
+ } : null
2584
+ });
2585
+ } catch (error) {
2586
+ if (!this.debug && error instanceof Error) {
2587
+ throw new Error(summarizeTableValidationError(this.manifest, error));
2588
+ }
2589
+ throw error;
2590
+ }
2591
+ this.version = 0;
2592
+ this.started = true;
2593
+ }
2594
+ phase() {
2595
+ return (this.runtime.unsafeState()?.domain?.flow?.currentPhase ?? null) || "";
2596
+ }
2597
+ playerOrder() {
2598
+ return this.playerIds;
2599
+ }
2600
+ rawState() {
2601
+ return this.runtime.snapshot();
2602
+ }
2603
+ currentVersion() {
2604
+ return this.version;
2605
+ }
2606
+ hydrate(snapshot, version = 0) {
2607
+ this.runtime.hydrate({ state: structuredClone(snapshot) });
2608
+ this.version = version;
2609
+ this.started = true;
2610
+ }
2611
+ patchState(mutator) {
2612
+ const next = structuredClone(this.rawState());
2613
+ mutator(next);
2614
+ this.hydrate(next, this.version + 1);
2615
+ }
2616
+ projectAllSeats() {
2617
+ const projection = this.runtime.projectSeatsDynamic({
2618
+ playerIds: this.playerIds
2619
+ });
2620
+ const interactionsByRef = projection.interactionsByRef && typeof projection.interactionsByRef === "object" && !Array.isArray(projection.interactionsByRef) ? projection.interactionsByRef : {};
2621
+ const seats = Object.fromEntries(
2622
+ Object.entries(projection.seats ?? {}).map(([playerId, seat]) => {
2623
+ const availableInteractionRefs = Array.isArray(
2624
+ seat.availableInteractionRefs
2625
+ ) ? seat.availableInteractionRefs.filter(
2626
+ (ref) => typeof ref === "string"
2627
+ ) : [];
2628
+ const availableInteractions = seat.availableInteractions ?? availableInteractionRefs.map((ref) => interactionsByRef[ref]).filter(
2629
+ (descriptor) => !!descriptor && typeof descriptor === "object"
2630
+ );
2631
+ return [
2632
+ playerId,
2633
+ {
2634
+ view: seat.view,
2635
+ availableInteractions,
2636
+ zones: seat.zones
2637
+ }
2638
+ ];
2639
+ })
2640
+ );
2641
+ return {
2642
+ currentStage: projection.currentStage ?? null,
2643
+ stageSeats: projection.stageSeats ?? [],
2644
+ seats
2645
+ };
2646
+ }
2647
+ currentStage() {
2648
+ return this.projectAllSeats().currentStage;
2649
+ }
2650
+ view(playerId) {
2651
+ return this.runtime.projectSeatViewDynamic({
2652
+ playerId
2653
+ }) ?? null;
2654
+ }
2655
+ availableInteractionsForPlayer(playerId) {
2656
+ const projection = this.projectAllSeats();
2657
+ const seat = projection.seats[playerId];
2658
+ const descriptors = seat?.availableInteractions ?? [];
2659
+ return descriptors.filter(
2660
+ (descriptor) => !!descriptor && typeof descriptor.interactionId === "string"
2661
+ ).map((descriptor) => descriptor.interactionId);
2662
+ }
2663
+ /**
2664
+ * Phase-kind interaction descriptors (action + prompt) available to
2665
+ * `playerId` in the current phase. Surfaces the same projection the UI
2666
+ * SDK consumes, so scenarios can assert addressee authorization and
2667
+ * availability without reaching into game-specific state. Returned as
2668
+ * loose records — the typed `InteractionDescriptor` shape is narrowed
2669
+ * downstream in the workspace-generated `testing-contract.ts`.
2670
+ */
2671
+ interactionsForPlayer(playerId) {
2672
+ return this.projectAllSeats().seats[playerId]?.availableInteractions ?? [];
2673
+ }
2674
+ explain(playerId, interactionId) {
2675
+ const runtime = this.runtime;
2676
+ if (typeof runtime.explainInteraction !== "function") {
2677
+ throw new Error(
2678
+ "The installed @dreamboard-games/sdk does not expose interaction explanations. Update the workspace SDK pin."
2679
+ );
2680
+ }
2681
+ return runtime.explainInteraction({ playerId, interactionId });
2682
+ }
2683
+ clearHistory() {
2684
+ this.historyRecords.length = 0;
2685
+ }
2686
+ async applyInput(input) {
2687
+ const parsedInput = toReducerInput(input);
2688
+ const result = await this.runtime.dispatch({ input: parsedInput });
2689
+ if (result.kind === "reject") {
2690
+ const record = {
2691
+ input,
2692
+ accepted: false,
2693
+ errorCode: result.errorCode,
2694
+ message: result.message
2695
+ };
2696
+ this.historyRecords.push(record);
2697
+ throw createSubmissionError(
2698
+ result.errorCode,
2699
+ result.message,
2700
+ "Reducer input rejected."
2701
+ );
2702
+ }
2703
+ this.version += 1;
2704
+ this.historyRecords.push({ input, accepted: true });
2705
+ }
2706
+ async submitInteraction(playerId, interactionId, params) {
2707
+ await this.applyInput({
2708
+ kind: "interaction",
2709
+ playerId,
2710
+ interactionId,
2711
+ params
2712
+ });
2713
+ }
2714
+ };
2715
+ function toReducerInput(input) {
2716
+ return {
2717
+ kind: "interaction",
2718
+ playerId: input.playerId,
2719
+ interactionId: input.interactionId,
2720
+ params: input.params
2721
+ };
2722
+ }
2723
+ function sanitizeSnapshotSegment(value) {
2724
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "-");
2725
+ }
2726
+ function createScenarioSnapshotMatcher(options) {
2727
+ return (filename, actual) => {
2728
+ const suffix = filename ? `.${sanitizeSnapshotSegment(filename)}` : "";
2729
+ const snapshotPath = resolveWorkspacePath(
2730
+ options.projectRoot,
2731
+ `test/generated/snapshots/${sanitizeSnapshotSegment(options.scenarioId)}${suffix}.snapshot.json`
2732
+ );
2733
+ const wrappedValue = {
2734
+ value: actual
2735
+ };
2736
+ const serialized = `${JSON.stringify(wrappedValue, null, 2)}
2737
+ `;
2738
+ mkdirSync(path3.dirname(snapshotPath), { recursive: true });
2739
+ if (!existsSync(snapshotPath) || options.updateSnapshots) {
2740
+ writeFileSync(snapshotPath, serialized, "utf8");
2741
+ return;
2742
+ }
2743
+ const previous = JSON.parse(readFileSync(snapshotPath, "utf8"));
2744
+ if (!deepEqual(previous.value, actual)) {
2745
+ throw new Error(
2746
+ `Snapshot mismatch for scenario '${options.scenarioId}'. Re-run with --update-snapshots to refresh ${path3.relative(options.projectRoot, snapshotPath)}.`
2747
+ );
2748
+ }
2749
+ };
2750
+ }
2751
+ async function createScenarioContext(options) {
2752
+ const api = {
2753
+ start: async () => {
2754
+ await options.shadow.start();
2755
+ },
2756
+ patchState: async (mutator) => {
2757
+ await api.start();
2758
+ if (options.live || options.actionPlan) {
2759
+ throw new Error(
2760
+ "game.patchState is only supported for reducer snapshot scenarios. Use it to materialize a state before --from-scenario or reducer tests, not inside live replay."
2761
+ );
2762
+ }
2763
+ options.shadow.patchState(mutator);
2764
+ },
2765
+ submit: async (playerId, interactionId, params) => {
2766
+ await api.start();
2767
+ const interactionParams = params ?? {};
2768
+ const normalizedInputs = interactionParams && typeof interactionParams === "object" && !Array.isArray(interactionParams) ? interactionParams : {};
2769
+ const previousVersion = options.live ? options.live.version : options.actionPlan ? options.shadow.currentVersion() : 0;
2770
+ if (options.live) {
2771
+ if (!options.live.actionSetVersion) {
2772
+ options.live.actionSetVersion = await fetchLiveActionSetVersion(
2773
+ options.live.sessionId,
2774
+ playerId
2775
+ );
2776
+ }
2777
+ const submittedActionSetVersion = options.live.actionSetVersion;
2778
+ const submitStartedAt = performance.now();
2779
+ const clientActionId = randomUUID3();
2780
+ const { data, error, response } = await submitGameplayAuthorityAction({
2781
+ path: {
2782
+ sessionId: options.live.sessionId,
2783
+ playerId,
2784
+ interactionId
2785
+ },
2786
+ body: {
2787
+ expectedVersion: previousVersion,
2788
+ actionSetVersion: options.live.actionSetVersion,
2789
+ inputs: normalizedInputs
2790
+ },
2791
+ headers: { "X-Dreamboard-Client-Action-Id": clientActionId }
2792
+ });
2793
+ const durationMs = performance.now() - submitStartedAt;
2794
+ options.live.diagnostics?.push({
2795
+ index: options.live.submitIndex ?? 0,
2796
+ playerId,
2797
+ interactionId,
2798
+ inputs: normalizedInputs,
2799
+ expectedVersion: previousVersion,
2800
+ actionSetVersion: submittedActionSetVersion,
2801
+ responseStatus: response?.status,
2802
+ responseBody: options.live.captureResponseBody === false ? void 0 : JSON.stringify(error ?? data ?? null),
2803
+ accepted: data?.accepted ?? void 0,
2804
+ errorCode: data?.accepted === false ? data.errorCode ?? void 0 : error && typeof error === "object" && "detail" in error ? String(error.detail) : void 0,
2805
+ backendTiming: response?.headers?.get("server-timing") ?? response?.headers?.get("x-dreamboard-timing") ?? void 0,
2806
+ durationMs
2807
+ });
2808
+ options.live.submitIndex = (options.live.submitIndex ?? 0) + 1;
2809
+ if (error) {
2810
+ throw createSubmissionError(
2811
+ "api-error",
2812
+ void 0,
2813
+ "Failed to submit interaction"
2814
+ );
2815
+ }
2816
+ if (data?.accepted === false) {
2817
+ const shadowError = await tryShadowSubmit(
2818
+ options.shadow,
2819
+ playerId,
2820
+ interactionId,
2821
+ interactionParams
2822
+ );
2823
+ if (!shadowError || shadowError.errorCode !== data.errorCode) {
2824
+ throw new Error(
2825
+ "Live session rejection diverged from reducer shadow state."
2826
+ );
2827
+ }
2828
+ throw createSubmissionError(
2829
+ data.errorCode ?? void 0,
2830
+ data.message ?? void 0,
2831
+ "Interaction rejected"
2832
+ );
2833
+ }
2834
+ options.live.version = typeof data?.version === "number" ? data.version : previousVersion + 1;
2835
+ options.live.actionSetVersion = data?.actionSetVersion ?? options.live.actionSetVersion;
2836
+ }
2837
+ await options.shadow.submitInteraction(
2838
+ playerId,
2839
+ interactionId,
2840
+ interactionParams
2841
+ );
2842
+ if (options.actionPlan) {
2843
+ options.actionPlan.diagnostics.push({
2844
+ index: options.actionPlan.submitIndex ?? 0,
2845
+ playerId,
2846
+ interactionId,
2847
+ inputs: normalizedInputs,
2848
+ expectedVersion: previousVersion,
2849
+ actionSetVersion: "",
2850
+ accepted: true,
2851
+ durationMs: 0
2852
+ });
2853
+ options.actionPlan.submitIndex = (options.actionPlan.submitIndex ?? 0) + 1;
2854
+ }
2855
+ }
2856
+ };
2857
+ return {
2858
+ game: api,
2859
+ players: () => options.shadow.playerOrder(),
2860
+ seat: (index) => {
2861
+ const order = options.shadow.playerOrder();
2862
+ if (!Number.isInteger(index) || index < 0 || index >= order.length) {
2863
+ throw new Error(
2864
+ `seat(${index}) is out of range; scenario has ${order.length} player(s).`
2865
+ );
2866
+ }
2867
+ return order[index];
2868
+ },
2869
+ state: () => options.shadow.phase(),
2870
+ view: (playerId) => options.shadow.view(playerId),
2871
+ interactions: (playerId) => options.shadow.interactionsForPlayer(playerId),
2872
+ explain: (playerId, interactionId) => options.shadow.explain(playerId, interactionId),
2873
+ expect: options.expect
2874
+ };
2875
+ }
2876
+ async function tryShadowSubmit(shadow, playerId, interactionId, params) {
2877
+ try {
2878
+ await shadow.submitInteraction(playerId, interactionId, params);
2879
+ throw new Error("Expected shadow interaction to reject.");
2880
+ } catch (error) {
2881
+ if (error instanceof Error && error.name === "SubmissionError") {
2882
+ return error;
2883
+ }
2884
+ throw error;
2885
+ }
2886
+ }
2887
+ async function createSessionFromScenario(options) {
2888
+ const startedAt = Date.now();
2889
+ const materialized = await materializeScenarioReducerState(options);
2890
+ const reducerHarnessMs = Date.now() - startedAt;
2891
+ const hydrateStartedAt = Date.now();
2892
+ const {
2893
+ data: snapshot,
2894
+ error,
2895
+ response
2896
+ } = await createProjectSessionFromReducerSnapshot({
2897
+ path: { projectId: options.projectId },
2898
+ body: {
2899
+ compiledResultId: options.compiledResultId,
2900
+ seed: materialized.seed,
2901
+ playerCount: materialized.playerCount,
2902
+ setupProfileId: materialized.setupProfileId ?? void 0,
2903
+ baseId: materialized.baseId,
2904
+ scenarioId: materialized.scenarioId,
2905
+ reducerState: materialized.reducerState,
2906
+ reducerStateVersion: materialized.reducerStateVersion,
2907
+ fingerprintMetadata: materialized.fingerprintMetadata
2908
+ }
2909
+ });
2910
+ const backendHydrateMs = Date.now() - hydrateStartedAt;
2911
+ if (error || !snapshot) {
2912
+ throw toDreamboardApiError(
2913
+ error,
2914
+ response,
2915
+ `Failed to materialize scenario '${options.scenarioId}' from reducer snapshot`
2916
+ );
2917
+ }
2918
+ return {
2919
+ sessionId: snapshot.context.sessionId,
2920
+ shortCode: snapshot.context.shortCode,
2921
+ gameId: projectIdFromSessionGameSource(snapshot.context.gameSource),
2922
+ seed: materialized.seed,
2923
+ playerCount: materialized.playerCount,
2924
+ setupProfileId: materialized.setupProfileId,
2925
+ scenarioId: materialized.scenarioId,
2926
+ phase: materialized.phase,
2927
+ stage: materialized.stage,
2928
+ materialization: {
2929
+ mode: "snapshot",
2930
+ totalMs: Date.now() - startedAt,
2931
+ reducerHarnessMs,
2932
+ backendHydrateMs
2933
+ }
2934
+ };
2935
+ }
2936
+ var MATERIALIZED_SCENARIO_CACHE_VERSION = 1;
2937
+ function materializedScenarioCachePath(options) {
2938
+ return [
2939
+ PROJECT_DIR_NAME,
2940
+ "dev",
2941
+ "scenario-cache",
2942
+ `${sanitizeSnapshotSegment(options.baseId)}.${sanitizeSnapshotSegment(
2943
+ options.scenarioId
2944
+ )}.${options.fingerprintHash}.json`
2945
+ ].join("/");
2946
+ }
2947
+ function materializedScenarioCacheFilePath(options) {
2948
+ return resolveWorkspacePath(
2949
+ options.projectRoot,
2950
+ materializedScenarioCachePath(options)
2951
+ );
2952
+ }
2953
+ async function readMaterializedScenarioCache(options) {
2954
+ const text = await readWorkspaceTextFileIfExists(
2955
+ options.projectRoot,
2956
+ materializedScenarioCachePath(options)
2957
+ );
2958
+ if (!text) return null;
2959
+ try {
2960
+ const payload = JSON.parse(
2961
+ text
2962
+ );
2963
+ if (payload.cacheVersion !== MATERIALIZED_SCENARIO_CACHE_VERSION || payload.fingerprintHash !== options.fingerprintHash || !payload.materialized) {
2964
+ return null;
2965
+ }
2966
+ return payload.materialized;
2967
+ } catch {
2968
+ return null;
2969
+ }
2970
+ }
2971
+ async function writeMaterializedScenarioCache(options) {
2972
+ const cachePath = materializedScenarioCacheFilePath(options);
2973
+ await ensureDir(path3.dirname(cachePath));
2974
+ await writeWorkspaceJsonFile(
2975
+ options.projectRoot,
2976
+ materializedScenarioCachePath(options),
2977
+ {
2978
+ cacheVersion: MATERIALIZED_SCENARIO_CACHE_VERSION,
2979
+ fingerprintHash: options.fingerprintHash,
2980
+ materialized: options.materialized
2981
+ }
2982
+ );
2983
+ }
2984
+ async function materializeScenarioReducerState(options) {
2985
+ await ensureReducerNativeTestingFiles(options.projectRoot);
2986
+ let preloadedGeneratedBaseStates;
2987
+ if (options.trustGeneratedFingerprint === true) {
2988
+ const [generatedBaseStates2, scenarioManifest] = await Promise.all([
2989
+ loadGeneratedBaseStates(options.projectRoot),
2990
+ loadGeneratedScenarioManifest(options.projectRoot)
2991
+ ]);
2992
+ preloadedGeneratedBaseStates = generatedBaseStates2;
2993
+ const scenarioEntry = scenarioManifest.find(
2994
+ (entry) => entry.id === options.scenarioId
2995
+ );
2996
+ const generatedBase2 = scenarioEntry ? generatedBaseStates2?.[baseStateKey(scenarioEntry.base)] : null;
2997
+ if (generatedBase2 && generatedBase2.fingerprint.compiledResultId === options.compiledResultId && generatedBase2.fingerprint.gameId === options.gameId) {
2998
+ const cached2 = await readMaterializedScenarioCache({
2999
+ projectRoot: options.projectRoot,
3000
+ baseId: scenarioEntry.base,
3001
+ scenarioId: options.scenarioId,
3002
+ fingerprintHash: fingerprintHash(generatedBase2.fingerprint)
3003
+ });
3004
+ if (cached2) {
3005
+ return cached2;
3006
+ }
3007
+ }
3008
+ }
3009
+ const [bases, scenarios, generatedBaseStates, manifest] = await Promise.all([
3010
+ loadTypedBases(options.projectRoot),
3011
+ loadTypedScenarios(options.projectRoot, {}),
3012
+ preloadedGeneratedBaseStates === void 0 ? loadGeneratedBaseStates(options.projectRoot) : Promise.resolve(preloadedGeneratedBaseStates),
3013
+ loadManifest(options.projectRoot)
3014
+ ]);
3015
+ const matchingScenarios = scenarios.filter(
3016
+ (scenario2) => scenario2.definition.id === options.scenarioId
3017
+ );
3018
+ if (matchingScenarios.length === 0) {
3019
+ throw new Error(
3020
+ `Unknown scenario '${options.scenarioId}'. Available scenarios: ${scenarios.map((scenario2) => scenario2.definition.id).sort().join(", ")}`
3021
+ );
3022
+ }
3023
+ if (matchingScenarios.length > 1) {
3024
+ throw new Error(
3025
+ `Scenario id '${options.scenarioId}' is defined more than once. Keep one scenario per file and one unique id per workspace.`
3026
+ );
3027
+ }
3028
+ const scenario = matchingScenarios[0];
3029
+ const basesById = new Map(bases.map((base2) => [base2.definition.id, base2]));
3030
+ validateTypedScenarioBases([scenario], basesById);
3031
+ const base = basesById.get(scenario.definition.from);
3032
+ if (!base) {
3033
+ throw new Error(
3034
+ `Missing typed base '${scenario.definition.from}' for scenario '${scenario.definition.id}'.`
3035
+ );
3036
+ }
3037
+ const generatedBase = generatedBaseStates?.[baseStateKey(base.definition.id)];
3038
+ if (!generatedBase) {
3039
+ throw new Error(
3040
+ `Missing generated base artifact for '${base.definition.id}'. Run 'dreamboard test' before using --from-scenario.`
3041
+ );
3042
+ }
3043
+ if (typeof generatedBase.version !== "number") {
3044
+ throw new Error(
3045
+ `Generated base artifact for '${base.definition.id}' is stale. Run 'dreamboard test' before using --from-scenario.`
3046
+ );
3047
+ }
3048
+ const canTrustGeneratedFingerprint = options.trustGeneratedFingerprint === true && generatedBase.fingerprint.compiledResultId === options.compiledResultId && generatedBase.fingerprint.gameId === options.gameId;
3049
+ const current = canTrustGeneratedFingerprint ? generatedBase.fingerprint : await currentFingerprint({
3050
+ projectRoot: options.projectRoot,
3051
+ base,
3052
+ basesById,
3053
+ compiledResultId: options.compiledResultId,
3054
+ gameId: options.gameId
3055
+ });
3056
+ if (!canTrustGeneratedFingerprint) {
3057
+ validateGeneratedFingerprint({
3058
+ generated: generatedBase.fingerprint,
3059
+ current
3060
+ });
3061
+ }
3062
+ const currentHash = fingerprintHash(current);
3063
+ const cached = await readMaterializedScenarioCache({
3064
+ projectRoot: options.projectRoot,
3065
+ baseId: base.definition.id,
3066
+ scenarioId: scenario.definition.id,
3067
+ fingerprintHash: currentHash
3068
+ });
3069
+ if (cached) {
3070
+ return cached;
3071
+ }
3072
+ const [gameModule, manifestContractModule, modules] = await Promise.all([
3073
+ importTypeScriptModule(
3074
+ path3.join(options.projectRoot, "app", "game.ts")
3075
+ ),
3076
+ importTypeScriptModule(
3077
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
3078
+ ),
3079
+ loadProjectReducerNativeModules(options.projectRoot)
3080
+ ]);
3081
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
3082
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3083
+ const effectiveSetup = resolveEffectiveBaseSetup({
3084
+ manifest,
3085
+ base: base.definition,
3086
+ basesById
3087
+ });
3088
+ const shadow = new ShadowReducerRuntime(
3089
+ modules,
3090
+ manifest,
3091
+ gameModule.default,
3092
+ createInitialTable,
3093
+ resolvedBase.seed,
3094
+ resolvedBase.players,
3095
+ effectiveSetup.setupProfileId,
3096
+ options.debug ?? false
3097
+ );
3098
+ shadow.hydrate(generatedBase.snapshot, generatedBase.version);
3099
+ const context = await createScenarioContext({
3100
+ shadow,
3101
+ expect: modules.createExpectApi()
3102
+ });
3103
+ shadow.clearHistory();
3104
+ await scenario.definition.when(context);
3105
+ if (scenario.definition.phase && shadow.phase() !== scenario.definition.phase) {
3106
+ throw new Error(
3107
+ `Scenario '${scenario.definition.id}' expected phase '${scenario.definition.phase}' but reached '${shadow.phase()}'.`
3108
+ );
3109
+ }
3110
+ if (scenario.definition.stage && shadow.currentStage() !== scenario.definition.stage) {
3111
+ throw new Error(
3112
+ `Scenario '${scenario.definition.id}' expected stage '${scenario.definition.stage}' but reached '${shadow.currentStage() ?? "null"}'.`
3113
+ );
3114
+ }
3115
+ const materialized = {
3116
+ baseId: base.definition.id,
3117
+ scenarioId: scenario.definition.id,
3118
+ seed: resolvedBase.seed,
3119
+ playerCount: resolvedBase.players,
3120
+ setupProfileId: effectiveSetup.setupProfileId,
3121
+ reducerState: shadow.rawState(),
3122
+ reducerStateVersion: shadow.currentVersion(),
3123
+ fingerprintMetadata: {
3124
+ baseFingerprintHash: fingerprintHash(generatedBase.fingerprint),
3125
+ currentFingerprintHash: fingerprintHash(current),
3126
+ baseBundleHash: generatedBase.fingerprint.baseBundleHash,
3127
+ manifestHash: generatedBase.fingerprint.manifestHash,
3128
+ appBundleHash: generatedBase.fingerprint.appBundleHash,
3129
+ uiContractHash: generatedBase.fingerprint.uiContractHash,
3130
+ baseId: base.definition.id,
3131
+ scenarioId: scenario.definition.id
3132
+ },
3133
+ phase: shadow.phase(),
3134
+ stage: shadow.currentStage()
3135
+ };
3136
+ await writeMaterializedScenarioCache({
3137
+ projectRoot: options.projectRoot,
3138
+ baseId: base.definition.id,
3139
+ scenarioId: scenario.definition.id,
3140
+ fingerprintHash: currentHash,
3141
+ materialized
3142
+ });
3143
+ return materialized;
3144
+ }
3145
+ async function fetchLiveActionSetVersion(sessionId, playerId) {
3146
+ const { data, error, response } = await getSessionSnapshot({
3147
+ path: { sessionId },
3148
+ query: { playerId }
3149
+ });
3150
+ if (error || !data || data.type !== "gameplay") {
3151
+ throw toDreamboardApiError(
3152
+ error ?? { detail: "Gameplay snapshot was unavailable." },
3153
+ response,
3154
+ "Failed to read live gameplay action set version"
3155
+ );
3156
+ }
3157
+ return data.gameplay.actionSetVersion;
3158
+ }
3159
+ function baseStateKey(baseId) {
3160
+ return baseId;
3161
+ }
3162
+ function fingerprintHash(fingerprint) {
3163
+ return hashContent(JSON.stringify(fingerprint));
3164
+ }
3165
+ function sortBasesForArtifacts(bases, basesById) {
3166
+ const ordered = [];
3167
+ const visiting = /* @__PURE__ */ new Set();
3168
+ const visited = /* @__PURE__ */ new Set();
3169
+ const visit = (base) => {
3170
+ if (visited.has(base.definition.id)) {
3171
+ return;
3172
+ }
3173
+ if (visiting.has(base.definition.id)) {
3174
+ throw new Error(
3175
+ `Cyclic reducer-native base inheritance detected at '${base.definition.id}'.`
3176
+ );
3177
+ }
3178
+ visiting.add(base.definition.id);
3179
+ if (base.definition.extends) {
3180
+ const parent = basesById.get(base.definition.extends);
3181
+ if (!parent) {
3182
+ throw new Error(
3183
+ `Base '${base.definition.id}' extends unknown parent '${base.definition.extends}'.`
3184
+ );
3185
+ }
3186
+ visit(parent);
3187
+ }
3188
+ visiting.delete(base.definition.id);
3189
+ visited.add(base.definition.id);
3190
+ ordered.push(base);
3191
+ };
3192
+ for (const base of bases) {
3193
+ visit(base);
3194
+ }
3195
+ return ordered;
3196
+ }
3197
+ function writeProjectionSnapshots(options) {
3198
+ const projectionDir = resolveWorkspacePath(
3199
+ options.projectRoot,
3200
+ `test/generated/bases/${sanitizeSnapshotSegment(options.baseId)}`
3201
+ );
3202
+ rmSync(projectionDir, { recursive: true, force: true });
3203
+ mkdirSync(projectionDir, { recursive: true });
3204
+ const projection = options.shadow.projectAllSeats();
3205
+ for (const [playerId, seatProjection] of Object.entries(projection.seats)) {
3206
+ const outputPath = resolveWorkspacePath(
3207
+ options.projectRoot,
3208
+ `test/generated/bases/${sanitizeSnapshotSegment(options.baseId)}/${sanitizeSnapshotSegment(playerId)}.projection.json`
3209
+ );
3210
+ writeFileSync(
3211
+ outputPath,
3212
+ `${JSON.stringify(
3213
+ {
3214
+ currentStage: projection.currentStage,
3215
+ stageSeats: projection.stageSeats,
3216
+ ...seatProjection
3217
+ },
3218
+ null,
3219
+ 2
3220
+ )}
3221
+ `,
3222
+ "utf8"
3223
+ );
3224
+ }
3225
+ }
3226
+ function validateTypedScenarioBases(scenarios, basesById) {
3227
+ const available = new Set(basesById.keys());
3228
+ const invalid = scenarios.filter((scenario) => !available.has(scenario.definition.from)).map(
3229
+ (scenario) => path3.relative(process.cwd(), scenario.filePath) + ` -> '${scenario.definition.from}'`
3230
+ );
3231
+ if (invalid.length > 0) {
3232
+ throw new Error(
3233
+ `Unknown scenario base(s): ${invalid.join(", ")}. Available bases: ${Array.from(available).sort().join(", ")}`
3234
+ );
3235
+ }
3236
+ }
3237
+ async function writeReducerNativeGeneratedFiles(options) {
3238
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3239
+ const manifest = await loadManifest(options.projectRoot);
3240
+ const manifestHash = hashContent(JSON.stringify(manifest));
3241
+ const appBundleHash = hashContent(
3242
+ await bundleTypeScriptModuleText(
3243
+ path3.join(options.projectRoot, "app", "game.ts")
3244
+ )
3245
+ );
3246
+ const uiContractHash = hashContent(
3247
+ await bundleTypeScriptModuleText(
3248
+ path3.join(options.projectRoot, "shared", "generated", "ui-contract.ts"),
3249
+ { external: SDK_UI_RUNTIME_EXTERNALS }
3250
+ )
3251
+ );
3252
+ const generatedDir = resolveWorkspacePath(
3253
+ options.projectRoot,
3254
+ "test/generated"
3255
+ );
3256
+ await ensureDir(generatedDir);
3257
+ const baseStates = {};
3258
+ const [gameModule, manifestContractModule, modules] = await Promise.all([
3259
+ importTypeScriptModule(
3260
+ path3.join(options.projectRoot, "app", "game.ts")
3261
+ ),
3262
+ importTypeScriptModule(
3263
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
3264
+ ),
3265
+ loadProjectReducerNativeModules(options.projectRoot)
3266
+ ]);
3267
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
3268
+ const contractFingerprintValue = modules.contractFingerprint(
3269
+ gameModule.default
3270
+ ).value;
3271
+ const basesById = new Map(
3272
+ options.bases.map((base) => [base.definition.id, base])
3273
+ );
3274
+ for (const base of sortBasesForArtifacts(options.bases, basesById)) {
3275
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3276
+ const effectiveSetup = resolveEffectiveBaseSetup({
3277
+ manifest,
3278
+ base: base.definition,
3279
+ basesById
3280
+ });
3281
+ const shadow = new ShadowReducerRuntime(
3282
+ modules,
3283
+ manifest,
3284
+ gameModule.default,
3285
+ createInitialTable,
3286
+ resolvedBase.seed,
3287
+ resolvedBase.players,
3288
+ effectiveSetup.setupProfileId,
3289
+ options.debug ?? false
3290
+ );
3291
+ let parentFingerprintHash = null;
3292
+ if (base.definition.extends) {
3293
+ const parentArtifact = baseStates[baseStateKey(base.definition.extends)];
3294
+ if (!parentArtifact) {
3295
+ throw new Error(
3296
+ `Base '${base.definition.id}' extends '${base.definition.extends}', but the parent artifact does not exist yet.`
3297
+ );
3298
+ }
3299
+ if (parentArtifact.fingerprint.seed !== resolvedBase.seed) {
3300
+ throw new Error(
3301
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes seed from ${parentArtifact.fingerprint.seed} to ${resolvedBase.seed}.`
3302
+ );
3303
+ }
3304
+ if (parentArtifact.fingerprint.players !== resolvedBase.players) {
3305
+ throw new Error(
3306
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes players from ${parentArtifact.fingerprint.players} to ${resolvedBase.players}.`
3307
+ );
3308
+ }
3309
+ if ((parentArtifact.fingerprint.setupProfileId ?? null) !== (effectiveSetup.setupProfileId ?? null)) {
3310
+ throw new Error(
3311
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes setup profile from ${parentArtifact.fingerprint.setupProfileId ?? "none"} to ${effectiveSetup.setupProfileId ?? "none"}.`
3312
+ );
3313
+ }
3314
+ parentFingerprintHash = fingerprintHash(parentArtifact.fingerprint);
3315
+ shadow.hydrate(parentArtifact.snapshot, parentArtifact.version);
3316
+ }
3317
+ const context = await createScenarioContext({
3318
+ shadow,
3319
+ expect: modules.createExpectApi()
3320
+ });
3321
+ await context.game.start();
3322
+ try {
3323
+ await base.definition.setup({
3324
+ game: context.game,
3325
+ players: context.players,
3326
+ seat: context.seat
3327
+ });
3328
+ } catch (error) {
3329
+ const message = error instanceof Error ? error.message : String(error);
3330
+ throw new Error(
3331
+ `Base '${base.definition.id}' setup failed with setupProfileId '${effectiveSetup.setupProfileId ?? "none"}': ${message}`,
3332
+ { cause: error instanceof Error ? error : void 0 }
3333
+ );
3334
+ }
3335
+ baseStates[baseStateKey(base.definition.id)] = {
3336
+ key: baseStateKey(base.definition.id),
3337
+ base: base.definition.id,
3338
+ snapshot: shadow.rawState(),
3339
+ version: shadow.currentVersion(),
3340
+ fingerprint: {
3341
+ base: base.definition.id,
3342
+ seed: resolvedBase.seed,
3343
+ players: resolvedBase.players,
3344
+ baseBundleHash: base.bundleHash,
3345
+ manifestHash,
3346
+ appBundleHash,
3347
+ uiContractHash,
3348
+ setupProfileId: effectiveSetup.setupProfileId,
3349
+ compiledResultId: options.compiledResultId,
3350
+ gameId: options.gameId,
3351
+ parentBaseId: base.definition.extends ?? null,
3352
+ parentFingerprintHash,
3353
+ contractFingerprint: contractFingerprintValue
3354
+ }
3355
+ };
3356
+ writeProjectionSnapshots({
3357
+ projectRoot: options.projectRoot,
3358
+ baseId: base.definition.id,
3359
+ shadow
3360
+ });
3361
+ }
3362
+ const header = "// Generated by dreamboard test. Do not edit by hand.\n";
3363
+ await writeWorkspaceTextFile(
3364
+ options.projectRoot,
3365
+ "test/generated/base-states.generated.ts",
3366
+ `${header}export const BASE_STATES = ${JSON.stringify(baseStates, null, 2)} as const;
3367
+ export const BASE_STATES_CONTRACT_FINGERPRINT = ${JSON.stringify(contractFingerprintValue)};
3368
+ `
3369
+ );
3370
+ await writeWorkspaceTextFile(
3371
+ options.projectRoot,
3372
+ "test/generated/base-states.generated.d.ts",
3373
+ `${header}export declare const BASE_STATES: Record<string, unknown>;
3374
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
3375
+ `
3376
+ );
3377
+ await writeWorkspaceTextFile(
3378
+ options.projectRoot,
3379
+ "test/generated/scenario-manifest.generated.ts",
3380
+ `${header}export const SCENARIO_MANIFEST = ${JSON.stringify(
3381
+ options.scenarios.map((scenario) => ({
3382
+ id: scenario.definition.id,
3383
+ filePath: path3.relative(generatedDir, scenario.filePath),
3384
+ base: scenario.definition.from
3385
+ })),
3386
+ null,
3387
+ 2
3388
+ )} as const;
3389
+ `
3390
+ );
3391
+ await writeWorkspaceJsonFile(
3392
+ options.projectRoot,
3393
+ "test/generated/.generation-meta.json",
3394
+ {
3395
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3396
+ contractFingerprint: contractFingerprintValue,
3397
+ scenarioCount: options.scenarios.length,
3398
+ baseStateCount: options.bases.length
3399
+ }
3400
+ );
3401
+ }
3402
+ async function loadGeneratedBaseStates(projectRoot) {
3403
+ const filePath = path3.join(
3404
+ projectRoot,
3405
+ "test",
3406
+ "generated",
3407
+ "base-states.generated.ts"
3408
+ );
3409
+ if (!await exists(filePath)) {
3410
+ return null;
3411
+ }
3412
+ const module = await importTypeScriptModule(filePath);
3413
+ return module.BASE_STATES ?? null;
3414
+ }
3415
+ async function loadGeneratedScenarioManifest(projectRoot) {
3416
+ const filePath = path3.join(
3417
+ projectRoot,
3418
+ "test",
3419
+ "generated",
3420
+ "scenario-manifest.generated.ts"
3421
+ );
3422
+ if (!await exists(filePath)) {
3423
+ return [];
3424
+ }
3425
+ const module = await importTypeScriptModule(filePath);
3426
+ const entries = module.SCENARIO_MANIFEST;
3427
+ if (!Array.isArray(entries)) {
3428
+ return [];
3429
+ }
3430
+ return entries.flatMap((entry) => {
3431
+ if (entry && typeof entry === "object" && "id" in entry && "base" in entry && typeof entry.id === "string" && typeof entry.base === "string") {
3432
+ return [{ id: entry.id, base: entry.base }];
3433
+ }
3434
+ return [];
3435
+ });
3436
+ }
3437
+ function validateGeneratedFingerprint(options) {
3438
+ const mismatches = [];
3439
+ if (options.generated.contractFingerprint && options.current.contractFingerprint && options.generated.contractFingerprint !== options.current.contractFingerprint) {
3440
+ const error = new Error(
3441
+ `Base states were generated for contract ${options.generated.contractFingerprint} but the current contract is ${options.current.contractFingerprint}. Remedy: run \`dreamboard test\`, then re-run the tests.`
3442
+ );
3443
+ error.code = STALE_CONTRACT_ARTIFACT_CODE;
3444
+ throw error;
3445
+ }
3446
+ if (options.generated.baseBundleHash !== options.current.baseBundleHash) {
3447
+ mismatches.push("base module changed");
3448
+ }
3449
+ if (options.generated.manifestHash !== options.current.manifestHash) {
3450
+ mismatches.push("manifest changed");
3451
+ }
3452
+ if (options.generated.appBundleHash !== options.current.appBundleHash) {
3453
+ mismatches.push("game reducer bundle changed");
3454
+ }
3455
+ if (options.generated.uiContractHash !== options.current.uiContractHash) {
3456
+ mismatches.push("ui contract changed");
3457
+ }
3458
+ if (options.generated.seed !== options.current.seed || options.generated.players !== options.current.players) {
3459
+ mismatches.push("base seed/player count changed");
3460
+ }
3461
+ if ((options.generated.setupProfileId ?? null) !== (options.current.setupProfileId ?? null)) {
3462
+ mismatches.push("base setup profile changed");
3463
+ }
3464
+ if ((options.generated.parentBaseId ?? null) !== (options.current.parentBaseId ?? null)) {
3465
+ mismatches.push("base parent changed");
3466
+ }
3467
+ if ((options.generated.parentFingerprintHash ?? null) !== (options.current.parentFingerprintHash ?? null)) {
3468
+ mismatches.push("parent base artifact changed");
3469
+ }
3470
+ if (mismatches.length > 0) {
3471
+ throw new Error(
3472
+ `${mismatches.join("; ")}. Run 'dreamboard test' to refresh reducer-native base artifacts.`
3473
+ );
3474
+ }
3475
+ }
3476
+ async function currentFingerprint(options) {
3477
+ const manifest = await loadManifest(options.projectRoot);
3478
+ const [gameModule, modules] = await Promise.all([
3479
+ importTypeScriptModule(
3480
+ path3.join(options.projectRoot, "app", "game.ts")
3481
+ ),
3482
+ loadProjectReducerNativeModules(options.projectRoot)
3483
+ ]);
3484
+ const contractFingerprintValue = modules.contractFingerprint(
3485
+ gameModule.default
3486
+ ).value;
3487
+ const resolvedBase = resolveBaseDefinition(
3488
+ options.base,
3489
+ options.basesById ?? /* @__PURE__ */ new Map([[options.base.definition.id, options.base]])
3490
+ );
3491
+ const effectiveSetup = resolveEffectiveBaseSetup({
3492
+ manifest,
3493
+ base: options.base.definition,
3494
+ basesById: options.basesById
3495
+ });
3496
+ let parentFingerprintHash = null;
3497
+ if (options.base.definition.extends) {
3498
+ const parentBase = options.basesById?.get(options.base.definition.extends);
3499
+ if (!parentBase) {
3500
+ throw new Error(
3501
+ `Base '${options.base.definition.id}' extends unknown parent '${options.base.definition.extends}'.`
3502
+ );
3503
+ }
3504
+ parentFingerprintHash = fingerprintHash(
3505
+ await currentFingerprint({
3506
+ projectRoot: options.projectRoot,
3507
+ base: parentBase,
3508
+ basesById: options.basesById,
3509
+ compiledResultId: options.compiledResultId,
3510
+ gameId: options.gameId
3511
+ })
3512
+ );
3513
+ }
3514
+ return {
3515
+ base: options.base.definition.id,
3516
+ seed: resolvedBase.seed,
3517
+ players: resolvedBase.players,
3518
+ baseBundleHash: options.base.bundleHash,
3519
+ manifestHash: hashContent(JSON.stringify(manifest)),
3520
+ appBundleHash: hashContent(
3521
+ await bundleTypeScriptModuleText(
3522
+ path3.join(options.projectRoot, "app", "game.ts")
3523
+ )
3524
+ ),
3525
+ uiContractHash: hashContent(
3526
+ await bundleTypeScriptModuleText(
3527
+ path3.join(options.projectRoot, "shared", "generated", "ui-contract.ts"),
3528
+ { external: SDK_UI_RUNTIME_EXTERNALS }
3529
+ )
3530
+ ),
3531
+ setupProfileId: effectiveSetup.setupProfileId,
3532
+ compiledResultId: options.compiledResultId,
3533
+ gameId: options.gameId,
3534
+ parentBaseId: options.base.definition.extends ?? null,
3535
+ parentFingerprintHash,
3536
+ contractFingerprint: contractFingerprintValue
3537
+ };
3538
+ }
3539
+ async function generateReducerNativeArtifacts(options) {
3540
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3541
+ const [bases, scenarios] = await Promise.all([
3542
+ loadTypedBases(options.projectRoot),
3543
+ loadTypedScenarios(options.projectRoot, {
3544
+ scenarioPath: options.scenarioPath
3545
+ })
3546
+ ]);
3547
+ const basesById = new Map(bases.map((base) => [base.definition.id, base]));
3548
+ validateTypedScenarioBases(scenarios, basesById);
3549
+ await writeReducerNativeGeneratedFiles({
3550
+ projectRoot: options.projectRoot,
3551
+ bases,
3552
+ scenarios,
3553
+ compiledResultId: options.compiledResultId,
3554
+ gameId: options.gameId,
3555
+ debug: options.debug
3556
+ });
3557
+ return { bases, scenarios };
3558
+ }
3559
+ async function runReducerNativeScenarios(options) {
3560
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3561
+ const [
3562
+ bases,
3563
+ scenarios,
3564
+ initialGeneratedBaseStates,
3565
+ manifest,
3566
+ gameModule,
3567
+ manifestContractModule,
3568
+ modules
3569
+ ] = await Promise.all([
3570
+ loadTypedBases(options.projectRoot),
3571
+ loadTypedScenarios(options.projectRoot, {
3572
+ scenarioPath: options.scenarioPath
3573
+ }),
3574
+ loadGeneratedBaseStates(options.projectRoot),
3575
+ loadManifest(options.projectRoot),
3576
+ importTypeScriptModule(
3577
+ path3.join(options.projectRoot, "app", "game.ts")
3578
+ ),
3579
+ importTypeScriptModule(
3580
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
3581
+ ),
3582
+ loadProjectReducerNativeModules(options.projectRoot)
3583
+ ]);
3584
+ let generatedBaseStates = initialGeneratedBaseStates;
3585
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
3586
+ const basesById = new Map(bases.map((base) => [base.definition.id, base]));
3587
+ validateTypedScenarioBases(scenarios, basesById);
3588
+ if (options.updateSnapshots) {
3589
+ await writeReducerNativeGeneratedFiles({
3590
+ projectRoot: options.projectRoot,
3591
+ bases,
3592
+ scenarios,
3593
+ compiledResultId: options.compiledResultId,
3594
+ gameId: options.gameId,
3595
+ debug: options.debug
3596
+ });
3597
+ generatedBaseStates = await loadGeneratedBaseStates(options.projectRoot);
3598
+ }
3599
+ let passed = 0;
3600
+ let failed = 0;
3601
+ const results = [];
3602
+ for (const scenario of scenarios) {
3603
+ const base = basesById.get(scenario.definition.from);
3604
+ if (!base) {
3605
+ throw new Error(
3606
+ `Missing typed base '${scenario.definition.from}' for scenario '${scenario.definition.id}'.`
3607
+ );
3608
+ }
3609
+ if (generatedBaseStates?.[baseStateKey(base.definition.id)]) {
3610
+ validateGeneratedFingerprint({
3611
+ generated: generatedBaseStates[baseStateKey(base.definition.id)].fingerprint,
3612
+ current: await currentFingerprint({
3613
+ projectRoot: options.projectRoot,
3614
+ base,
3615
+ basesById,
3616
+ compiledResultId: options.compiledResultId,
3617
+ gameId: options.gameId
3618
+ })
3619
+ });
3620
+ }
3621
+ try {
3622
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3623
+ const effectiveSetup = resolveEffectiveBaseSetup({
3624
+ manifest,
3625
+ base: base.definition,
3626
+ basesById
3627
+ });
3628
+ const shadow = new ShadowReducerRuntime(
3629
+ modules,
3630
+ manifest,
3631
+ gameModule.default,
3632
+ createInitialTable,
3633
+ resolvedBase.seed,
3634
+ resolvedBase.players,
3635
+ effectiveSetup.setupProfileId,
3636
+ options.debug ?? false
3637
+ );
3638
+ if (base.definition.extends) {
3639
+ const parentArtifact = generatedBaseStates?.[baseStateKey(base.definition.extends)];
3640
+ if (!parentArtifact) {
3641
+ throw new Error(
3642
+ `Base '${base.definition.id}' extends '${base.definition.extends}', but the parent artifact is missing. Run 'dreamboard test' first.`
3643
+ );
3644
+ }
3645
+ shadow.hydrate(parentArtifact.snapshot, parentArtifact.version);
3646
+ }
3647
+ const context = await createScenarioContext({
3648
+ shadow,
3649
+ expect: modules.createExpectApi({
3650
+ matchSnapshot: createScenarioSnapshotMatcher({
3651
+ projectRoot: options.projectRoot,
3652
+ scenarioId: scenario.definition.id,
3653
+ updateSnapshots: options.updateSnapshots ?? false
3654
+ })
3655
+ })
3656
+ });
3657
+ await context.game.start();
3658
+ await base.definition.setup({
3659
+ game: context.game,
3660
+ players: context.players,
3661
+ seat: context.seat
3662
+ });
3663
+ shadow.clearHistory();
3664
+ await scenario.definition.when(context);
3665
+ if (scenario.definition.phase && shadow.phase() !== scenario.definition.phase) {
3666
+ throw new Error(
3667
+ `Scenario '${scenario.definition.id}' expected phase '${scenario.definition.phase}' but reached '${shadow.phase()}'.`
3668
+ );
3669
+ }
3670
+ if (scenario.definition.stage && shadow.currentStage() !== scenario.definition.stage) {
3671
+ throw new Error(
3672
+ `Scenario '${scenario.definition.id}' expected stage '${scenario.definition.stage}' but reached '${shadow.currentStage() ?? "null"}'.`
3673
+ );
3674
+ }
3675
+ await scenario.definition.then(context);
3676
+ passed += 1;
3677
+ results.push({
3678
+ id: scenario.definition.id,
3679
+ success: true
3680
+ });
3681
+ } catch (error) {
3682
+ failed += 1;
3683
+ results.push({
3684
+ id: scenario.definition.id,
3685
+ success: false,
3686
+ errorCode: isStaleContractArtifactError(error) ? STALE_CONTRACT_ARTIFACT_CODE : void 0,
3687
+ error: error instanceof Error ? formatScenarioErrorForDisplay({
3688
+ error,
3689
+ projectRoot: options.projectRoot,
3690
+ scenarioFilePath: scenario.filePath
3691
+ }) : `Scenario '${scenario.definition.id}' failed.`
3692
+ });
3693
+ } finally {
3694
+ }
3695
+ }
3696
+ return { passed, failed, results };
3697
+ }
3698
+
3699
+ // src/services/project/local-maintainer-registry-shared.ts
3700
+ import crypto2 from "crypto";
3701
+ import path4 from "path";
3702
+ var localRegistryAddress = readLocalRegistryAddress();
3703
+ var LOCAL_REGISTRY_HOST = localRegistryAddress.host;
3704
+ var LOCAL_REGISTRY_PORT = localRegistryAddress.port;
3705
+ var LOCAL_REGISTRY_URL = `http://${LOCAL_REGISTRY_HOST}:${LOCAL_REGISTRY_PORT}`;
3706
+ var LOCAL_SCOPE_NPMRC_CONTENT = `@dreamboard-games:registry=${LOCAL_REGISTRY_URL}
3707
+ `;
3708
+ function readLocalRegistryAddress() {
3709
+ const urlOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_URL?.trim();
3710
+ const hostOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_HOST?.trim();
3711
+ const portOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_PORT?.trim();
3712
+ if (urlOverride) {
3713
+ let parsed;
3714
+ try {
3715
+ parsed = new URL(urlOverride);
3716
+ } catch {
3717
+ throw new Error(
3718
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_URL '${urlOverride}'. Expected an http://host:port URL.`
3719
+ );
3720
+ }
3721
+ if (parsed.protocol !== "http:" || !parsed.hostname || !parsed.port) {
3722
+ throw new Error(
3723
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_URL '${urlOverride}'. Expected an http://host:port URL.`
3724
+ );
3725
+ }
3726
+ return {
3727
+ host: hostOverride || parsed.hostname,
3728
+ port: parseLocalRegistryPort(portOverride || parsed.port)
3729
+ };
3730
+ }
3731
+ return {
3732
+ host: hostOverride || "127.0.0.1",
3733
+ port: portOverride ? parseLocalRegistryPort(portOverride) : 4873
3734
+ };
3735
+ }
3736
+ function parseLocalRegistryPort(raw) {
3737
+ const port = Number.parseInt(raw, 10);
3738
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3739
+ throw new Error(
3740
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_PORT '${raw}'. Expected a TCP port from 1 to 65535.`
3741
+ );
3742
+ }
3743
+ return port;
3744
+ }
3745
+ function shortHash(value) {
3746
+ return crypto2.createHash("sha256").update(value).digest("hex").slice(0, 12);
3747
+ }
3748
+ function isLocalMaintainerRegistryEnabled(apiBaseUrl) {
3749
+ let isLocalLoopbackUrl = false;
3750
+ try {
3751
+ const parsed = new URL(apiBaseUrl);
3752
+ isLocalLoopbackUrl = parsed.protocol === "http:" && (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1");
3753
+ } catch {
3754
+ isLocalLoopbackUrl = false;
3755
+ }
3756
+ return !IS_PUBLISHED_BUILD && (apiBaseUrl === ENVIRONMENT_CONFIGS.local?.apiBaseUrl || isLocalLoopbackUrl) && BUILD_CHANNEL === "development";
3757
+ }
3758
+ function didLocalMaintainerSnapshotChange(previous, next) {
3759
+ if (!next) {
3760
+ return false;
3761
+ }
3762
+ return previous?.snapshotId !== next.snapshotId;
3763
+ }
3764
+
3765
+ export {
3766
+ createPkcePair,
3767
+ buildClerkAuthorizationUrl,
3768
+ exchangeClerkOAuthCode,
3769
+ createUserSessionManager,
3770
+ IS_PUBLISHED_BUILD,
3771
+ PUBLISHED_ENVIRONMENT,
3772
+ resolveLocalHarnessAccessToken,
3773
+ resolveConfig,
3774
+ configureClient,
3775
+ requireAuth,
3776
+ getAuthTokenExpiry,
3777
+ resolveProjectContext,
3778
+ parseConfigFlags,
3779
+ parsePlayerCountFlags,
3780
+ parseNewCommandArgs,
3781
+ parseCloneCommandArgs,
3782
+ parseCommitScopedCommandArgs,
3783
+ parseBuildCommandArgs,
3784
+ parseReleasePublishCommandArgs,
3785
+ parseDevCommandArgs,
3786
+ parseAuthCommandArgs,
3787
+ CONFIG_FLAG_ARGS,
3788
+ STALE_CONTRACT_ARTIFACT_CODE,
3789
+ STALE_CONTRACT_ARTIFACT_EXIT_CODE,
3790
+ toDreamboardApiError,
3791
+ isDreamboardApiError,
3792
+ isStaleContractArtifactMessage,
3793
+ isStaleContractArtifactError,
3794
+ getCliErrorExitCode,
3795
+ presentCliError,
3796
+ formatCliError,
3797
+ normalizeSlug,
3798
+ titleFromSlug,
3799
+ parsePositiveInt,
3800
+ findCompiledResultsForAuthoringState,
3801
+ waitForCompiledResultJobSdk,
3802
+ importTypeScriptModule,
3803
+ resolveSetupProfileSelectionForSession,
3804
+ projectIdFromSessionGameSource,
3805
+ isReducerNativeTestingWorkspace,
3806
+ ensureReducerNativeTestingFiles,
3807
+ createSessionFromScenario,
3808
+ generateReducerNativeArtifacts,
3809
+ runReducerNativeScenarios,
3810
+ LOCAL_REGISTRY_URL,
3811
+ shortHash,
3812
+ isLocalMaintainerRegistryEnabled,
3813
+ didLocalMaintainerSnapshotChange
3814
+ };
3815
+ //# sourceMappingURL=chunk-X244CUU4.js.map