dreamboard 0.1.21 → 0.1.22

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 (186) hide show
  1. package/dist/{chunk-EYYWGWTO.js → chunk-2RCUHMGL.js} +343 -1911
  2. package/dist/chunk-2RCUHMGL.js.map +1 -0
  3. package/dist/{chunk-MOVHYB6E.js → chunk-AQ5UUNJS.js} +1018 -692
  4. package/dist/chunk-AQ5UUNJS.js.map +1 -0
  5. package/dist/{chunk-BMYC6772.js → chunk-H3O43F5P.js} +9765 -3068
  6. package/dist/chunk-H3O43F5P.js.map +1 -0
  7. package/dist/dev-host/dev-api-proxy-plugin.ts +330 -0
  8. package/dist/dev-host/dev-diagnostics.ts +62 -0
  9. package/dist/dev-host/dev-fallback-stylesheet.ts +50 -0
  10. package/dist/dev-host/dev-host-controller.ts +686 -0
  11. package/dist/dev-host/dev-host-player-query.ts +17 -0
  12. package/dist/dev-host/dev-host-session-transport.ts +52 -0
  13. package/dist/dev-host/dev-host-storage.ts +56 -0
  14. package/dist/dev-host/dev-log-relay-plugin.ts +469 -0
  15. package/dist/dev-host/dev-runtime-config.ts +14 -0
  16. package/dist/dev-host/dev-runtime-platform.ts +419 -0
  17. package/dist/dev-host/dev-virtual-modules-plugin.ts +63 -0
  18. package/dist/dev-host/host-main.css +182 -0
  19. package/dist/dev-host/host-main.tsx +754 -0
  20. package/dist/dev-host/index.html +56 -0
  21. package/dist/dev-host/plugin-main.ts +55 -0
  22. package/dist/dev-host/plugin.html +24 -0
  23. package/dist/dev-host/start-dev-server.ts +138 -0
  24. package/dist/dev-host/virtual-modules.d.ts +27 -0
  25. package/dist/dist-FEPN3BDN.js +16543 -0
  26. package/dist/dist-FEPN3BDN.js.map +1 -0
  27. package/dist/{dist-WJRJNFLI.js → dist-FRURQI7Q.js} +4 -2
  28. package/dist/index.js +3 -3
  29. package/dist/internal.js +159 -124
  30. package/dist/internal.js.map +1 -1
  31. package/dist/runtime-packages/tailwind-config/shared-styles.css +146 -0
  32. package/dist/runtime-packages/ui/src/components/.gitkeep +0 -0
  33. package/dist/runtime-packages/ui/src/components/accordion.tsx +66 -0
  34. package/dist/runtime-packages/ui/src/components/ai-elements/actions.tsx +65 -0
  35. package/dist/runtime-packages/ui/src/components/ai-elements/artifact.tsx +147 -0
  36. package/dist/runtime-packages/ui/src/components/ai-elements/branch.tsx +215 -0
  37. package/dist/runtime-packages/ui/src/components/ai-elements/canvas.tsx +22 -0
  38. package/dist/runtime-packages/ui/src/components/ai-elements/chain-of-thought.tsx +228 -0
  39. package/dist/runtime-packages/ui/src/components/ai-elements/code-block.tsx +179 -0
  40. package/dist/runtime-packages/ui/src/components/ai-elements/confirmation.tsx +158 -0
  41. package/dist/runtime-packages/ui/src/components/ai-elements/connection.tsx +28 -0
  42. package/dist/runtime-packages/ui/src/components/ai-elements/context.tsx +408 -0
  43. package/dist/runtime-packages/ui/src/components/ai-elements/controls.tsx +18 -0
  44. package/dist/runtime-packages/ui/src/components/ai-elements/conversation.tsx +97 -0
  45. package/dist/runtime-packages/ui/src/components/ai-elements/edge.tsx +140 -0
  46. package/dist/runtime-packages/ui/src/components/ai-elements/image.tsx +24 -0
  47. package/dist/runtime-packages/ui/src/components/ai-elements/inline-citation.tsx +287 -0
  48. package/dist/runtime-packages/ui/src/components/ai-elements/loader.tsx +96 -0
  49. package/dist/runtime-packages/ui/src/components/ai-elements/message.tsx +463 -0
  50. package/dist/runtime-packages/ui/src/components/ai-elements/node.tsx +71 -0
  51. package/dist/runtime-packages/ui/src/components/ai-elements/open-in-chat.tsx +365 -0
  52. package/dist/runtime-packages/ui/src/components/ai-elements/panel.tsx +15 -0
  53. package/dist/runtime-packages/ui/src/components/ai-elements/plan.tsx +142 -0
  54. package/dist/runtime-packages/ui/src/components/ai-elements/prompt-input.tsx +1380 -0
  55. package/dist/runtime-packages/ui/src/components/ai-elements/queue.tsx +274 -0
  56. package/dist/runtime-packages/ui/src/components/ai-elements/reasoning.tsx +182 -0
  57. package/dist/runtime-packages/ui/src/components/ai-elements/response.tsx +22 -0
  58. package/dist/runtime-packages/ui/src/components/ai-elements/shimmer.tsx +64 -0
  59. package/dist/runtime-packages/ui/src/components/ai-elements/sources.tsx +77 -0
  60. package/dist/runtime-packages/ui/src/components/ai-elements/suggestion.tsx +53 -0
  61. package/dist/runtime-packages/ui/src/components/ai-elements/task.tsx +87 -0
  62. package/dist/runtime-packages/ui/src/components/ai-elements/tool.tsx +165 -0
  63. package/dist/runtime-packages/ui/src/components/ai-elements/toolbar.tsx +16 -0
  64. package/dist/runtime-packages/ui/src/components/ai-elements/web-preview.tsx +263 -0
  65. package/dist/runtime-packages/ui/src/components/alert-dialog.tsx +157 -0
  66. package/dist/runtime-packages/ui/src/components/alert.tsx +66 -0
  67. package/dist/runtime-packages/ui/src/components/avatar.tsx +53 -0
  68. package/dist/runtime-packages/ui/src/components/badge.tsx +46 -0
  69. package/dist/runtime-packages/ui/src/components/button-group.tsx +83 -0
  70. package/dist/runtime-packages/ui/src/components/button.tsx +65 -0
  71. package/dist/runtime-packages/ui/src/components/card.tsx +92 -0
  72. package/dist/runtime-packages/ui/src/components/carousel.tsx +241 -0
  73. package/dist/runtime-packages/ui/src/components/collapsible.tsx +33 -0
  74. package/dist/runtime-packages/ui/src/components/command.tsx +184 -0
  75. package/dist/runtime-packages/ui/src/components/context-menu.tsx +252 -0
  76. package/dist/runtime-packages/ui/src/components/counter.tsx +11 -0
  77. package/dist/runtime-packages/ui/src/components/dialog.tsx +146 -0
  78. package/dist/runtime-packages/ui/src/components/drawer.tsx +132 -0
  79. package/dist/runtime-packages/ui/src/components/dropdown-menu.tsx +257 -0
  80. package/dist/runtime-packages/ui/src/components/form.tsx +168 -0
  81. package/dist/runtime-packages/ui/src/components/header.tsx +13 -0
  82. package/dist/runtime-packages/ui/src/components/hover-card.tsx +44 -0
  83. package/dist/runtime-packages/ui/src/components/input-group.tsx +178 -0
  84. package/dist/runtime-packages/ui/src/components/input.tsx +21 -0
  85. package/dist/runtime-packages/ui/src/components/item.tsx +193 -0
  86. package/dist/runtime-packages/ui/src/components/label.tsx +24 -0
  87. package/dist/runtime-packages/ui/src/components/navigation-menu.tsx +168 -0
  88. package/dist/runtime-packages/ui/src/components/popover.tsx +55 -0
  89. package/dist/runtime-packages/ui/src/components/progress.tsx +31 -0
  90. package/dist/runtime-packages/ui/src/components/radio-group.tsx +45 -0
  91. package/dist/runtime-packages/ui/src/components/resizable.tsx +56 -0
  92. package/dist/runtime-packages/ui/src/components/scroll-area.tsx +58 -0
  93. package/dist/runtime-packages/ui/src/components/select.tsx +187 -0
  94. package/dist/runtime-packages/ui/src/components/separator.tsx +28 -0
  95. package/dist/runtime-packages/ui/src/components/skeleton.tsx +13 -0
  96. package/dist/runtime-packages/ui/src/components/sonner.tsx +25 -0
  97. package/dist/runtime-packages/ui/src/components/spinner.tsx +16 -0
  98. package/dist/runtime-packages/ui/src/components/switch.tsx +31 -0
  99. package/dist/runtime-packages/ui/src/components/table.tsx +137 -0
  100. package/dist/runtime-packages/ui/src/components/tabs.tsx +74 -0
  101. package/dist/runtime-packages/ui/src/components/textarea.tsx +23 -0
  102. package/dist/runtime-packages/ui/src/components/theme-provider.tsx +73 -0
  103. package/dist/runtime-packages/ui/src/components/tooltip.tsx +61 -0
  104. package/dist/runtime-packages/ui/src/components/ui/file-upload.tsx +195 -0
  105. package/dist/runtime-packages/ui/src/hooks/.gitkeep +0 -0
  106. package/dist/runtime-packages/ui/src/index.ts +68 -0
  107. package/dist/runtime-packages/ui/src/lib/utils.ts +6 -0
  108. package/dist/runtime-packages/ui-host-runtime/src/actor-principal.ts +68 -0
  109. package/dist/runtime-packages/ui-host-runtime/src/components/host-controls.tsx +359 -0
  110. package/dist/runtime-packages/ui-host-runtime/src/components/host-feedback-toaster.tsx +274 -0
  111. package/dist/runtime-packages/ui-host-runtime/src/components/host-feedback.tsx +214 -0
  112. package/dist/runtime-packages/ui-host-runtime/src/components/host-session-metadata.tsx +135 -0
  113. package/dist/runtime-packages/ui-host-runtime/src/components/index.ts +5 -0
  114. package/dist/runtime-packages/ui-host-runtime/src/components/perf-overlay.tsx +194 -0
  115. package/dist/runtime-packages/ui-host-runtime/src/host-controls.tsx +1 -0
  116. package/dist/runtime-packages/ui-host-runtime/src/host-feedback.tsx +1 -0
  117. package/dist/runtime-packages/ui-host-runtime/src/host-session-transport.ts +162 -0
  118. package/dist/runtime-packages/ui-host-runtime/src/index.ts +2 -0
  119. package/dist/runtime-packages/ui-host-runtime/src/logger.ts +11 -0
  120. package/dist/runtime-packages/ui-host-runtime/src/perf.ts +253 -0
  121. package/dist/runtime-packages/ui-host-runtime/src/plugin-bridge.ts +195 -0
  122. package/dist/runtime-packages/ui-host-runtime/src/plugin-health-check.ts +138 -0
  123. package/dist/runtime-packages/ui-host-runtime/src/plugin-messages.ts +159 -0
  124. package/dist/runtime-packages/ui-host-runtime/src/plugin-session-gateway.ts +524 -0
  125. package/dist/runtime-packages/ui-host-runtime/src/runtime/index.ts +12 -0
  126. package/dist/runtime-packages/ui-host-runtime/src/screenshot/projection-to-snapshot.ts +122 -0
  127. package/dist/runtime-packages/ui-host-runtime/src/screenshot/static-store-api.ts +26 -0
  128. package/dist/runtime-packages/ui-host-runtime/src/session-ingress-controller.ts +477 -0
  129. package/dist/runtime-packages/ui-host-runtime/src/session-ingress.ts +209 -0
  130. package/dist/runtime-packages/ui-host-runtime/src/session-live-runtime.ts +112 -0
  131. package/dist/runtime-packages/ui-host-runtime/src/session-model.ts +318 -0
  132. package/dist/runtime-packages/ui-host-runtime/src/session-projection.ts +211 -0
  133. package/dist/runtime-packages/ui-host-runtime/src/session-state-reducer.ts +814 -0
  134. package/dist/runtime-packages/ui-host-runtime/src/sse-manager.ts +334 -0
  135. package/dist/runtime-packages/ui-host-runtime/src/unified-session-store.ts +180 -0
  136. package/dist/scaffold/assets/static/app/tsconfig.framework.json +3 -1
  137. package/dist/scaffold/assets/static/ui/tsconfig.framework.json +7 -19
  138. package/package.json +52 -17
  139. package/skills/dreamboard/SKILL.md +41 -75
  140. package/LICENSE +0 -89
  141. package/NOTICE +0 -1
  142. package/dist/chunk-BMYC6772.js.map +0 -1
  143. package/dist/chunk-EYYWGWTO.js.map +0 -1
  144. package/dist/chunk-MOVHYB6E.js.map +0 -1
  145. package/dist/scaffold/assets/static/ui/App.tsx +0 -22
  146. package/dist/src-CUL7EGGG.js +0 -634
  147. package/dist/src-CUL7EGGG.js.map +0 -1
  148. package/skills/dreamboard/references/authoring-lifecycle.md +0 -102
  149. package/skills/dreamboard/references/board-surfaces.md +0 -36
  150. package/skills/dreamboard/references/board-topology.md +0 -443
  151. package/skills/dreamboard/references/boards-and-topology.md +0 -100
  152. package/skills/dreamboard/references/card-actions.md +0 -107
  153. package/skills/dreamboard/references/cli.md +0 -120
  154. package/skills/dreamboard/references/core-concepts.md +0 -514
  155. package/skills/dreamboard/references/custom-renderers.md +0 -26
  156. package/skills/dreamboard/references/derived-values.md +0 -55
  157. package/skills/dreamboard/references/effects.md +0 -111
  158. package/skills/dreamboard/references/game-contract.md +0 -89
  159. package/skills/dreamboard/references/game-definition.md +0 -89
  160. package/skills/dreamboard/references/game-shell.md +0 -80
  161. package/skills/dreamboard/references/hand-surfaces.md +0 -33
  162. package/skills/dreamboard/references/index.md +0 -112
  163. package/skills/dreamboard/references/inputs-and-targets.md +0 -160
  164. package/skills/dreamboard/references/interactions.md +0 -158
  165. package/skills/dreamboard/references/manifest-fields.md +0 -137
  166. package/skills/dreamboard/references/manifest.md +0 -81
  167. package/skills/dreamboard/references/package-surfaces.md +0 -69
  168. package/skills/dreamboard/references/phases.md +0 -145
  169. package/skills/dreamboard/references/prompts-and-choices.md +0 -55
  170. package/skills/dreamboard/references/quickstart.md +0 -71
  171. package/skills/dreamboard/references/rule-authoring.md +0 -144
  172. package/skills/dreamboard/references/setup-bootstrap.md +0 -78
  173. package/skills/dreamboard/references/stages-and-zones.md +0 -59
  174. package/skills/dreamboard/references/static-views.md +0 -67
  175. package/skills/dreamboard/references/table-queries-and-ops.md +0 -103
  176. package/skills/dreamboard/references/testing-bases.md +0 -147
  177. package/skills/dreamboard/references/testing-generated-contracts.md +0 -142
  178. package/skills/dreamboard/references/testing-runtime-assertions.md +0 -124
  179. package/skills/dreamboard/references/testing-scenarios.md +0 -148
  180. package/skills/dreamboard/references/testing-ui-tests.md +0 -174
  181. package/skills/dreamboard/references/testing.md +0 -161
  182. package/skills/dreamboard/references/ui-architecture.md +0 -137
  183. package/skills/dreamboard/references/ui-components.md +0 -34
  184. package/skills/dreamboard/references/views.md +0 -72
  185. package/skills/dreamboard/references/workspace-layout.md +0 -136
  186. /package/dist/{dist-WJRJNFLI.js.map → dist-FRURQI7Q.js.map} +0 -0
@@ -0,0 +1,686 @@
1
+ import { validatePlayerAction } from "@dreamboard/api-client";
2
+ import {
3
+ PluginSessionGateway,
4
+ type GameSessionStoreApi,
5
+ type HostSessionTransport,
6
+ type LoggerLike,
7
+ type SessionContext,
8
+ type UnifiedSessionStore,
9
+ unifiedSessionSelectors,
10
+ } from "@dreamboard/ui-host-runtime/runtime";
11
+ import { formatConsoleArgs } from "./dev-diagnostics.js";
12
+ import type { ActiveSession, DevHostStorage } from "./dev-host-storage.js";
13
+
14
+ const AUTO_RECOVERY_SSE_FAILURE_THRESHOLD = 2;
15
+ const MAX_AUTO_RECOVERY_ATTEMPTS = 1;
16
+ type DevHostSessionSnapshot = Awaited<
17
+ ReturnType<NonNullable<HostSessionTransport["createDevSessionSnapshot"]>>
18
+ >;
19
+
20
+ type SessionStoreApi = {
21
+ getState: () => UnifiedSessionStore;
22
+ subscribe: (
23
+ listener: (
24
+ state: UnifiedSessionStore,
25
+ previousState: UnifiedSessionStore,
26
+ ) => void,
27
+ ) => () => void;
28
+ };
29
+
30
+ function hasRenderableSnapshot(store: SessionStoreApi): boolean {
31
+ const state = store.getState();
32
+ return (
33
+ unifiedSessionSelectors.bootstrapStatus(state) === "renderable" &&
34
+ state.getPluginSnapshot().view !== null
35
+ );
36
+ }
37
+
38
+ function createSubmissionError(
39
+ errorCode: string | undefined,
40
+ message: string | undefined,
41
+ fallbackMessage: string,
42
+ ): Error & { errorCode?: string } {
43
+ const error = new Error(message ?? fallbackMessage) as Error & {
44
+ errorCode?: string;
45
+ };
46
+ error.name = "SubmissionError";
47
+ error.errorCode = errorCode;
48
+ return error;
49
+ }
50
+
51
+ export interface DevHostControllerConfig {
52
+ autoStartGame: boolean;
53
+ compiledResultId: string;
54
+ createDevSessionSnapshot?: NonNullable<
55
+ HostSessionTransport["createDevSessionSnapshot"]
56
+ >;
57
+ debug: boolean;
58
+ fallbackSession: ActiveSession;
59
+ gameId: string;
60
+ initialPlayerId?: string | null;
61
+ playerCount: number;
62
+ setupProfileId: string | null;
63
+ slug: string;
64
+ userId: string | null;
65
+ }
66
+
67
+ /**
68
+ * Structured surface for reducer/runtime failures that bubble up from the
69
+ * backend. These are shown in the dev host overlay so authors see the same
70
+ * file/line/stack information they'd get from a `dreamboard dev` backend log.
71
+ */
72
+ export interface DevHostRuntimeError {
73
+ title: string;
74
+ summary: string;
75
+ violations: Array<{
76
+ message: string;
77
+ field?: string;
78
+ code?: string;
79
+ }>;
80
+ correlationId?: string;
81
+ }
82
+
83
+ export interface DevHostControllerSnapshot {
84
+ session: ActiveSession;
85
+ seedValue: string;
86
+ isCreatingSession: boolean;
87
+ iframeSrc: string;
88
+ pluginReady: boolean;
89
+ runtimeError: DevHostRuntimeError | null;
90
+ }
91
+
92
+ export class DevHostController {
93
+ private readonly listeners = new Set<() => void>();
94
+ private readonly defaultSession: ActiveSession;
95
+ private readonly unsubscribeStore: () => void;
96
+
97
+ private currentSession: ActiveSession;
98
+ private seedValue: string;
99
+ private isCreatingSession = false;
100
+ private pluginReady = false;
101
+ private iframeLoaded = false;
102
+ private iframe: HTMLIFrameElement | null = null;
103
+ private gateway: PluginSessionGateway | null = null;
104
+ private gatewayStoreAttached = false;
105
+ private pluginFrameReloadCounter = 0;
106
+ private autoRecoveryAttempts = 0;
107
+ private sessionSnapshotSseFailureCount = 0;
108
+ private recoveryInFlight = false;
109
+ private runtimeError: DevHostRuntimeError | null = null;
110
+ private playerSwitchRequestId = 0;
111
+
112
+ constructor(
113
+ private readonly store: SessionStoreApi,
114
+ private readonly storage: DevHostStorage,
115
+ private readonly config: DevHostControllerConfig,
116
+ private readonly logger: LoggerLike,
117
+ ) {
118
+ this.defaultSession = structuredClone(config.fallbackSession);
119
+ this.currentSession = structuredClone(this.defaultSession);
120
+ this.seedValue = String(this.currentSession.seed ?? 1337);
121
+ this.unsubscribeStore = this.store.subscribe((state) => {
122
+ if (unifiedSessionSelectors.bootstrapStatus(state) !== "loading") {
123
+ this.sessionSnapshotSseFailureCount = 0;
124
+ }
125
+ if (
126
+ this.pluginReady &&
127
+ !this.gatewayStoreAttached &&
128
+ hasRenderableSnapshot(this.store)
129
+ ) {
130
+ this.attachStore();
131
+ }
132
+ });
133
+ }
134
+
135
+ subscribe(listener: () => void): () => void {
136
+ this.listeners.add(listener);
137
+ return () => {
138
+ this.listeners.delete(listener);
139
+ };
140
+ }
141
+
142
+ getSnapshot(): DevHostControllerSnapshot {
143
+ return {
144
+ session: this.currentSession,
145
+ seedValue: this.seedValue,
146
+ isCreatingSession: this.isCreatingSession,
147
+ iframeSrc: `/plugin.html?session=${encodeURIComponent(this.currentSession.sessionId)}&reload=${this.pluginFrameReloadCounter}`,
148
+ pluginReady: this.pluginReady,
149
+ runtimeError: this.runtimeError,
150
+ };
151
+ }
152
+
153
+ dismissRuntimeError(): void {
154
+ if (this.runtimeError === null) {
155
+ return;
156
+ }
157
+ this.runtimeError = null;
158
+ this.notify();
159
+ }
160
+
161
+ /**
162
+ * Public entry point for surfacing runtime errors originating outside
163
+ * the controller (e.g. the api-client interceptor that detects a
164
+ * `session_invalid` envelope from the dev proxy and wants to route
165
+ * the failure through the existing overlay).
166
+ */
167
+ reportRuntimeError(error: DevHostRuntimeError): void {
168
+ this.setRuntimeError(error);
169
+ }
170
+
171
+ async initialize(): Promise<void> {
172
+ this.sessionSnapshotSseFailureCount = 0;
173
+ this.notify();
174
+
175
+ try {
176
+ const preferredPlayerId = this.resolvePreferredPlayerId();
177
+ await this.loadStoreSnapshot(preferredPlayerId, "dev-bootstrap");
178
+ this.syncCurrentSessionFromStore();
179
+ this.persistCurrentPlayerFromStore();
180
+ } catch (initialError) {
181
+ const preferredPlayerId = this.resolvePreferredPlayerId();
182
+ let error = initialError;
183
+ if (preferredPlayerId) {
184
+ this.logger.warn(
185
+ "[DevHost] Failed to bootstrap the requested player selection; retrying with the default player:",
186
+ error instanceof Error ? error.message : String(error),
187
+ );
188
+ this.storage.persistPreferredPlayerId(null);
189
+ try {
190
+ await this.loadStoreSnapshot(null, "dev-bootstrap");
191
+ this.syncCurrentSessionFromStore();
192
+ this.persistCurrentPlayerFromStore();
193
+ this.notify();
194
+ return;
195
+ } catch (retryError) {
196
+ error = retryError;
197
+ }
198
+ }
199
+ this.logger.error(
200
+ "[DevHost] Failed to bootstrap the backend session:",
201
+ error instanceof Error ? error.message : String(error),
202
+ );
203
+ }
204
+ this.notify();
205
+ }
206
+
207
+ setSeedValue(value: string): void {
208
+ this.seedValue = value;
209
+ this.notify();
210
+ }
211
+
212
+ async createNewSession(): Promise<void> {
213
+ const nextSeed = Number.parseInt(this.seedValue.trim(), 10);
214
+ if (!Number.isSafeInteger(nextSeed)) {
215
+ this.logger.error("[DevHost] Seed must be a safe integer.");
216
+ return;
217
+ }
218
+
219
+ this.isCreatingSession = true;
220
+ this.notify();
221
+
222
+ try {
223
+ this.clearRuntimeError();
224
+ if (this.gateway) {
225
+ this.gateway.disconnect();
226
+ this.gateway = null;
227
+ }
228
+ this.gatewayStoreAttached = false;
229
+ this.pluginReady = false;
230
+ this.reloadPluginFrame();
231
+ this.store.getState().reset();
232
+ const snapshot = await this.createBackendDevSessionSnapshot(nextSeed);
233
+ this.adoptCreatedSession(snapshot, nextSeed);
234
+ await this.loadStoreSnapshot(null, "dev-new");
235
+ this.syncCurrentSessionFromStore(nextSeed);
236
+ this.persistCurrentPlayerFromStore();
237
+ } catch (error) {
238
+ this.logger.error("[DevHost] Failed to create a new session:", error);
239
+ } finally {
240
+ this.isCreatingSession = false;
241
+ this.notify();
242
+ }
243
+ }
244
+
245
+ async startGameFromSidebar(): Promise<void> {
246
+ try {
247
+ this.clearRuntimeError();
248
+ await this.store.getState().startSession({
249
+ sessionId: this.currentSession.sessionId,
250
+ userId: this.config.userId,
251
+ source: "dev-bootstrap",
252
+ });
253
+ this.syncCurrentSessionFromStore();
254
+ this.persistCurrentPlayerFromStore();
255
+ this.notify();
256
+ } catch (error) {
257
+ this.setRuntimeError(
258
+ convertProblemDetailsToRuntimeError(
259
+ error,
260
+ "Failed to start the backend session.",
261
+ ),
262
+ );
263
+ this.logger.error(
264
+ "[DevHost] Failed to start the backend session:",
265
+ error instanceof Error ? error.message : String(error),
266
+ );
267
+ }
268
+ }
269
+
270
+ switchPlayer(playerId: string): void {
271
+ void this.switchPlayerFromBootstrap(playerId);
272
+ }
273
+
274
+ async restoreHistoryEntry(entryId: string): Promise<void> {
275
+ await this.store.getState().restoreHistory({
276
+ sessionId: this.currentSession.sessionId,
277
+ entryId,
278
+ });
279
+ }
280
+
281
+ setIframe(element: HTMLIFrameElement | null): void {
282
+ this.iframe = element;
283
+ }
284
+
285
+ onIframeLoad(): void {
286
+ this.iframeLoaded = true;
287
+ this.connectGateway();
288
+ }
289
+
290
+ matchesPluginWindow(source: MessageEvent["source"]): boolean {
291
+ return Boolean(this.iframe && source === this.iframe.contentWindow);
292
+ }
293
+
294
+ handleSseTransportError(args: unknown[]): void {
295
+ if (
296
+ unifiedSessionSelectors.bootstrapStatus(this.store.getState()) !==
297
+ "loading" ||
298
+ this.recoveryInFlight
299
+ ) {
300
+ return;
301
+ }
302
+
303
+ const errorMessage = args
304
+ .map((value) => (value instanceof Error ? value.message : String(value)))
305
+ .join(" ");
306
+ if (!errorMessage.includes("SSE failed: 400")) {
307
+ return;
308
+ }
309
+
310
+ this.sessionSnapshotSseFailureCount += 1;
311
+ if (
312
+ this.sessionSnapshotSseFailureCount < AUTO_RECOVERY_SSE_FAILURE_THRESHOLD
313
+ ) {
314
+ return;
315
+ }
316
+
317
+ void this.recoverFromUnhealthySession(
318
+ "The current session stream is unhealthy, creating a fresh session...",
319
+ );
320
+ }
321
+
322
+ dispose(): void {
323
+ this.unsubscribeStore();
324
+ if (this.gateway) {
325
+ this.gateway.disconnect();
326
+ this.gateway = null;
327
+ }
328
+ this.gatewayStoreAttached = false;
329
+ this.store.getState().closeStreams();
330
+ }
331
+
332
+ private notify(): void {
333
+ this.listeners.forEach((listener) => listener());
334
+ }
335
+
336
+ private setRuntimeError(error: DevHostRuntimeError): void {
337
+ this.runtimeError = error;
338
+ this.notify();
339
+ }
340
+
341
+ private clearRuntimeError(): void {
342
+ if (this.runtimeError === null) {
343
+ return;
344
+ }
345
+ this.runtimeError = null;
346
+ this.notify();
347
+ }
348
+
349
+ private connectGateway(): void {
350
+ if (!this.iframeLoaded || !this.iframe) {
351
+ return;
352
+ }
353
+
354
+ if (!unifiedSessionSelectors.sessionId(this.store.getState())) {
355
+ return;
356
+ }
357
+
358
+ const session = this.store.getState().getPluginSnapshot().session;
359
+
360
+ if (this.gateway) {
361
+ this.gateway.disconnect();
362
+ this.gateway = null;
363
+ }
364
+ this.gatewayStoreAttached = false;
365
+
366
+ this.pluginReady = false;
367
+
368
+ this.gateway = new PluginSessionGateway({
369
+ iframe: this.iframe,
370
+ sessionId: this.currentSession.sessionId,
371
+ controllablePlayerIds: session.controllablePlayerIds,
372
+ controllingPlayerId: session.controllingPlayerId ?? "",
373
+ userId: this.config.userId,
374
+ onReady: () => {
375
+ this.pluginReady = true;
376
+ if (hasRenderableSnapshot(this.store)) {
377
+ this.attachStore();
378
+ }
379
+ this.notify();
380
+ },
381
+ onError: (error) => {
382
+ this.pluginReady = false;
383
+ this.logger.error(
384
+ "[DevHost] Plugin iframe failed:",
385
+ error instanceof Error ? error.message : error,
386
+ );
387
+ this.notify();
388
+ },
389
+ onInteraction: async (
390
+ playerId: string,
391
+ interactionId: string,
392
+ params: unknown,
393
+ meta,
394
+ ) => {
395
+ try {
396
+ await this.store.getState().submitInteraction({
397
+ sessionId: this.currentSession.sessionId,
398
+ playerId,
399
+ interactionId,
400
+ params,
401
+ clientActionId: meta?.clientActionId,
402
+ });
403
+ } catch (error) {
404
+ if (error instanceof Error && error.name === "SubmissionError") {
405
+ throw error;
406
+ }
407
+ throw createSubmissionError(
408
+ "api-error",
409
+ undefined,
410
+ "Failed to submit interaction",
411
+ );
412
+ }
413
+ },
414
+ onValidateInteraction: async (
415
+ playerId: string,
416
+ interactionId: string,
417
+ params: unknown,
418
+ ) => {
419
+ const gameplay = this.store.getState().getRenderableGameplay();
420
+ if (!gameplay) {
421
+ return {
422
+ valid: false,
423
+ errorCode: "runtime-unavailable",
424
+ message: "No renderable gameplay snapshot is available.",
425
+ };
426
+ }
427
+ const expectedVersion = gameplay.version;
428
+ const actionSetVersion = gameplay.actionSetVersion;
429
+ const { data, error } = await validatePlayerAction({
430
+ path: {
431
+ sessionId: this.currentSession.sessionId,
432
+ playerId,
433
+ interactionId,
434
+ },
435
+ body: {
436
+ expectedVersion,
437
+ actionSetVersion,
438
+ inputs:
439
+ params && typeof params === "object" && !Array.isArray(params)
440
+ ? (params as never)
441
+ : {},
442
+ },
443
+ });
444
+
445
+ if (error) {
446
+ return {
447
+ valid: false,
448
+ errorCode: "api-error",
449
+ message: "Failed to validate interaction",
450
+ };
451
+ }
452
+
453
+ return {
454
+ valid: data?.valid ?? true,
455
+ errorCode: data?.errorCode ?? undefined,
456
+ message: data?.message ?? undefined,
457
+ };
458
+ },
459
+ onSwitchPlayer: (playerId: string) => {
460
+ this.switchPlayer(playerId);
461
+ },
462
+ onRestoreHistory: async (entryId: string) => {
463
+ await this.restoreHistoryEntry(entryId);
464
+ },
465
+ logger: this.logger,
466
+ });
467
+
468
+ this.gateway.connect();
469
+ }
470
+
471
+ private attachStore(): void {
472
+ if (!this.gateway || this.gatewayStoreAttached) {
473
+ return;
474
+ }
475
+
476
+ const storeApi: GameSessionStoreApi = {
477
+ getStateSnapshot: this.store.getState().getPluginSnapshot,
478
+ subscribe: (listener: () => void) =>
479
+ this.store.subscribe((_state, _previousState) => {
480
+ listener();
481
+ }),
482
+ onStateAck: this.store.getState().onStateAck,
483
+ markNotificationRead: this.store.getState().markNotificationRead,
484
+ };
485
+
486
+ this.gateway.attachStore(storeApi);
487
+ this.gatewayStoreAttached = true;
488
+ }
489
+
490
+ private reloadPluginFrame(): void {
491
+ this.pluginFrameReloadCounter += 1;
492
+ this.iframeLoaded = false;
493
+ this.pluginReady = false;
494
+ this.gatewayStoreAttached = false;
495
+ }
496
+
497
+ private async recoverFromUnhealthySession(reason: string): Promise<void> {
498
+ if (
499
+ this.recoveryInFlight ||
500
+ this.autoRecoveryAttempts >= MAX_AUTO_RECOVERY_ATTEMPTS ||
501
+ unifiedSessionSelectors.bootstrapStatus(this.store.getState()) !==
502
+ "loading"
503
+ ) {
504
+ return;
505
+ }
506
+
507
+ this.recoveryInFlight = true;
508
+ this.autoRecoveryAttempts += 1;
509
+
510
+ try {
511
+ this.logger.warn("[DevHost] " + reason);
512
+ const seed = this.currentSession.seed ?? 1337;
513
+ const snapshot = await this.createBackendDevSessionSnapshot(seed);
514
+ this.adoptCreatedSession(snapshot, seed);
515
+ await this.loadStoreSnapshot(null, "dev-new");
516
+ this.syncCurrentSessionFromStore(seed);
517
+ this.persistCurrentPlayerFromStore();
518
+ } catch (error) {
519
+ this.logger.error(
520
+ "[DevHost] Automatic recovery failed:",
521
+ formatConsoleArgs([error]),
522
+ );
523
+ } finally {
524
+ this.recoveryInFlight = false;
525
+ }
526
+ }
527
+
528
+ private async loadStoreSnapshot(
529
+ playerId: string | null | undefined,
530
+ source: string,
531
+ expectedPerspectivePlayerId?: string | null,
532
+ ): Promise<void> {
533
+ await this.store.getState().loadSessionSnapshot({
534
+ sessionId: this.currentSession.sessionId,
535
+ userId: this.config.userId,
536
+ requestedPlayerId: playerId,
537
+ expectedPerspectivePlayerId,
538
+ source,
539
+ });
540
+ }
541
+
542
+ private async createBackendDevSessionSnapshot(
543
+ seed: number,
544
+ ): Promise<DevHostSessionSnapshot> {
545
+ if (!this.config.createDevSessionSnapshot) {
546
+ throw new Error("Dev host session transport is not configured.");
547
+ }
548
+ return this.config.createDevSessionSnapshot({ seed });
549
+ }
550
+
551
+ private adoptCreatedSession(
552
+ snapshot: DevHostSessionSnapshot,
553
+ seed: number | null,
554
+ ): void {
555
+ this.currentSession = {
556
+ sessionId: snapshot.context.sessionId,
557
+ shortCode: snapshot.context.shortCode,
558
+ gameId: this.config.gameId,
559
+ seed,
560
+ };
561
+ }
562
+
563
+ private resolvePreferredPlayerId(): string | null {
564
+ return (
565
+ this.config.initialPlayerId?.trim() ||
566
+ this.storage.loadPreferredPlayerId()
567
+ );
568
+ }
569
+
570
+ private syncCurrentSessionFromStore(seedOverride?: number | null): void {
571
+ const context = unifiedSessionSelectors.sessionContext(
572
+ this.store.getState(),
573
+ ) as SessionContext | null;
574
+ if (!context) {
575
+ return;
576
+ }
577
+ this.currentSession = {
578
+ sessionId: context.identity.sessionId,
579
+ shortCode: context.identity.shortCode,
580
+ gameId: context.identity.gameId,
581
+ seed: seedOverride ?? this.currentSession.seed ?? null,
582
+ };
583
+ this.seedValue = String(this.currentSession.seed ?? 1337);
584
+ if (this.iframeLoaded) {
585
+ this.connectGateway();
586
+ }
587
+ }
588
+
589
+ private persistCurrentPlayerFromStore(): void {
590
+ const currentPlayerId = unifiedSessionSelectors.currentPlayerId(
591
+ this.store.getState(),
592
+ );
593
+ if (currentPlayerId) {
594
+ this.storage.persistPreferredPlayerId(currentPlayerId);
595
+ }
596
+ }
597
+
598
+ private async switchPlayerFromBootstrap(playerId: string): Promise<void> {
599
+ const requestId = ++this.playerSwitchRequestId;
600
+ try {
601
+ await this.loadStoreSnapshot(playerId, "player-switch", playerId);
602
+ if (requestId !== this.playerSwitchRequestId) {
603
+ return;
604
+ }
605
+ this.assertSwitchStoreMatchesPlayer(playerId);
606
+ this.clearRuntimeError();
607
+ this.syncCurrentSessionFromStore();
608
+ this.persistCurrentPlayerFromStore();
609
+ this.notify();
610
+ } catch (error) {
611
+ if (requestId !== this.playerSwitchRequestId) {
612
+ return;
613
+ }
614
+ this.logger.error(
615
+ "[DevHost] Failed to switch player:",
616
+ error instanceof Error ? error.message : String(error),
617
+ );
618
+ this.setRuntimeError(
619
+ convertProblemDetailsToRuntimeError(
620
+ error,
621
+ `Failed to switch to ${playerId}.`,
622
+ ),
623
+ );
624
+ }
625
+ }
626
+
627
+ private assertSwitchStoreMatchesPlayer(playerId: string): void {
628
+ const currentPlayerId = unifiedSessionSelectors.currentPlayerId(
629
+ this.store.getState(),
630
+ );
631
+ if (!currentPlayerId) {
632
+ return;
633
+ }
634
+ if (currentPlayerId !== playerId) {
635
+ throw new Error(
636
+ `Switch snapshot resolved ${currentPlayerId} instead of ${playerId}.`,
637
+ );
638
+ }
639
+ }
640
+ }
641
+
642
+ type ApiErrorPayload = {
643
+ title?: string;
644
+ detail?: string;
645
+ status?: number;
646
+ requestId?: string;
647
+ violations?: Array<{
648
+ message?: string;
649
+ field?: string;
650
+ code?: string;
651
+ }>;
652
+ };
653
+
654
+ /**
655
+ * Convert a backend `ProblemDetails` (or an opaque error object) into the
656
+ * structured shape the dev host overlay renders. We surface every violation
657
+ * intentionally — when a reducer `initialize` throws, the JS stack lives in
658
+ * the second violation entry, so collapsing them into a single string would
659
+ * lose the file and line information we just went to the trouble of
660
+ * preserving in `JsExecutor.jsRejectionToException`.
661
+ */
662
+ function convertProblemDetailsToRuntimeError(
663
+ error: unknown,
664
+ fallbackMessage: string,
665
+ ): DevHostRuntimeError {
666
+ const payload = (error ?? {}) as ApiErrorPayload;
667
+ const violations = (payload.violations ?? [])
668
+ .filter((violation) => typeof violation?.message === "string")
669
+ .map((violation) => ({
670
+ message: violation.message as string,
671
+ field: typeof violation.field === "string" ? violation.field : undefined,
672
+ code: typeof violation.code === "string" ? violation.code : undefined,
673
+ }));
674
+
675
+ const title = payload.title?.trim() || "Game failed to start";
676
+ const summary =
677
+ payload.detail?.trim() ||
678
+ (error instanceof Error ? error.message : fallbackMessage);
679
+
680
+ return {
681
+ title,
682
+ summary,
683
+ violations,
684
+ correlationId: payload.requestId,
685
+ };
686
+ }
@@ -0,0 +1,17 @@
1
+ export function normalizeDevHostPlayerQueryParam(
2
+ value: string | null | undefined,
3
+ ): string | null {
4
+ const trimmed = value?.trim();
5
+ if (!trimmed) {
6
+ return null;
7
+ }
8
+ return trimmed.startsWith("player-") ? trimmed : `player-${trimmed}`;
9
+ }
10
+
11
+ export function resolveInitialDevHostPlayerId(
12
+ search: string | URLSearchParams,
13
+ ): string | null {
14
+ const params =
15
+ typeof search === "string" ? new URLSearchParams(search) : search;
16
+ return normalizeDevHostPlayerQueryParam(params.get("player"));
17
+ }