castle-web-cli 0.4.157 → 0.4.159

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 (243) hide show
  1. package/dist/agent-failures.d.ts +1 -0
  2. package/dist/agent-failures.js +6 -4
  3. package/dist/agent-prompts.js +4 -0
  4. package/dist/agent.d.ts +11 -0
  5. package/dist/agent.js +175 -15
  6. package/dist/bundle.js +8 -2
  7. package/dist/castle-host/host.js +4 -2
  8. package/dist/castleJson.js +6 -1
  9. package/dist/check.d.ts +1 -0
  10. package/dist/check.js +25 -0
  11. package/dist/devSessionServer.js +31 -7
  12. package/dist/imports.js +1 -19
  13. package/dist/index.js +15 -1
  14. package/dist/init.d.ts +2 -2
  15. package/dist/init.js +78 -42
  16. package/dist/mcpPlaytest.d.ts +1 -0
  17. package/dist/mcpPlaytest.js +182 -0
  18. package/dist/metering.d.ts +24 -0
  19. package/dist/metering.js +87 -0
  20. package/dist/sdkResolve.d.ts +3 -0
  21. package/dist/sdkResolve.js +55 -0
  22. package/dist/serve.js +50 -4
  23. package/dist/serverBundle.js +8 -3
  24. package/dist/shell/assets/{index-DsDkYFvP.js → index-DMSoTyXh.js} +64 -64
  25. package/dist/shell/assets/{index-DwezawBs.css → index-DfZmu3XC.css} +1 -1
  26. package/dist/shell/index.html +2 -2
  27. package/dist/vitePlugins.d.ts +1 -0
  28. package/dist/vitePlugins.js +20 -0
  29. package/kits/base/CLAUDE.md +196 -0
  30. package/kits/{blank → base}/castle.json +5 -2
  31. package/kits/base/editorHost.js +172 -0
  32. package/kits/{blank → base}/node_modules/.package-lock.json +3 -2
  33. package/kits/{blank → base}/package-lock.json +7 -4
  34. package/kits/{blank → base}/package.json +4 -2
  35. package/kits/base/sdk/README.md +569 -0
  36. package/kits/base/sdk/castle.d.ts +27 -0
  37. package/kits/base/sdk/castle.js +16 -0
  38. package/kits/base/sdk/commands.d.ts +181 -0
  39. package/kits/base/sdk/commands.js +16 -0
  40. package/kits/base/sdk/context.d.ts +17 -0
  41. package/kits/base/sdk/context.js +15 -0
  42. package/kits/base/sdk/errors.d.ts +22 -0
  43. package/kits/base/sdk/errors.js +16 -0
  44. package/kits/base/sdk/files.d.ts +15 -0
  45. package/kits/base/sdk/files.js +52 -0
  46. package/kits/base/sdk/haptics.d.ts +6 -0
  47. package/kits/base/sdk/haptics.js +36 -0
  48. package/kits/base/sdk/leaderboard.d.ts +26 -0
  49. package/kits/base/sdk/leaderboard.js +296 -0
  50. package/kits/base/sdk/lifecycle.d.ts +4 -0
  51. package/kits/base/sdk/lifecycle.js +13 -0
  52. package/kits/base/sdk/multiplayer.d.ts +43 -0
  53. package/kits/base/sdk/multiplayer.js +464 -0
  54. package/kits/base/sdk/multiplayerProtocol.d.ts +51 -0
  55. package/kits/base/sdk/multiplayerProtocol.js +5 -0
  56. package/kits/base/sdk/passes.d.ts +7 -0
  57. package/kits/base/sdk/passes.js +84 -0
  58. package/kits/base/sdk/portal.d.ts +7 -0
  59. package/kits/base/sdk/portal.js +35 -0
  60. package/kits/base/sdk/runtime.d.ts +62 -0
  61. package/kits/base/sdk/runtime.js +970 -0
  62. package/kits/base/sdk/saveQueue.d.ts +27 -0
  63. package/kits/base/sdk/saveQueue.js +205 -0
  64. package/kits/base/sdk/server/platformHandle.d.ts +25 -0
  65. package/kits/base/sdk/server/platformHandle.js +1 -0
  66. package/kits/base/sdk/server/wrapper.d.ts +28 -0
  67. package/kits/base/sdk/server/wrapper.js +109 -0
  68. package/kits/base/sdk/storage.d.ts +16 -0
  69. package/kits/base/sdk/storage.js +323 -0
  70. package/kits/base/sdk/time.d.ts +17 -0
  71. package/kits/base/sdk/time.js +120 -0
  72. package/kits/base/sdk/transport.d.ts +17 -0
  73. package/kits/base/sdk/transport.js +141 -0
  74. package/kits/base/sdk/types.d.ts +3 -0
  75. package/kits/base/sdk/types.js +1 -0
  76. package/kits/base/sdk/user.d.ts +10 -0
  77. package/kits/base/sdk/user.js +45 -0
  78. package/kits/multiplayer-2d/.prettierrc +5 -0
  79. package/kits/multiplayer-2d/CLAUDE.md +129 -0
  80. package/kits/multiplayer-2d/behaviors/Box.jsx +92 -0
  81. package/kits/multiplayer-2d/behaviors/Player.jsx +86 -0
  82. package/kits/multiplayer-2d/blueprints/crate.scene +13 -0
  83. package/kits/multiplayer-2d/blueprints/other-player.scene +13 -0
  84. package/kits/multiplayer-2d/blueprints/player.scene +15 -0
  85. package/kits/multiplayer-2d/blueprints/wall.scene +12 -0
  86. package/kits/multiplayer-2d/castle.json +39 -0
  87. package/kits/multiplayer-2d/code/client/avatars.js +93 -0
  88. package/kits/multiplayer-2d/code/client/poses.js +168 -0
  89. package/kits/multiplayer-2d/code/server/index.js +26 -0
  90. package/kits/multiplayer-2d/code/server/limits.js +99 -0
  91. package/kits/multiplayer-2d/code/server/ownership.js +177 -0
  92. package/kits/multiplayer-2d/code/server/players.js +127 -0
  93. package/kits/multiplayer-2d/code/server/sceneBodies.js +98 -0
  94. package/kits/multiplayer-2d/code/server/world.js +337 -0
  95. package/kits/multiplayer-2d/code/systems/multiplayer.js +424 -0
  96. package/kits/multiplayer-2d/eslint.config.js +21 -0
  97. package/kits/multiplayer-2d/fonts.generated.js +9 -0
  98. package/kits/multiplayer-2d/index.html +25 -0
  99. package/kits/multiplayer-2d/main.jsx +10 -0
  100. package/kits/multiplayer-2d/package-lock.json +351 -0
  101. package/kits/multiplayer-2d/package.json +30 -0
  102. package/kits/multiplayer-2d/scenes/main.scene +20 -0
  103. package/kits/multiplayer-2d/test/two-client-test.mjs +341 -0
  104. package/kits/multiplayer-2d/theme.style +4 -0
  105. package/kits/multiplayer-3d/.prettierrc +5 -0
  106. package/kits/multiplayer-3d/CLAUDE.md +215 -0
  107. package/kits/multiplayer-3d/blueprints/ball.scene +21 -0
  108. package/kits/multiplayer-3d/blueprints/other-player.scene +21 -0
  109. package/kits/multiplayer-3d/castle.json +43 -0
  110. package/kits/multiplayer-3d/code/client/avatars.js +136 -0
  111. package/kits/multiplayer-3d/code/client/nameTags.js +101 -0
  112. package/kits/multiplayer-3d/code/client/poses.js +220 -0
  113. package/kits/multiplayer-3d/code/server/index.js +23 -0
  114. package/kits/multiplayer-3d/code/server/limits.js +107 -0
  115. package/kits/multiplayer-3d/code/server/ownership.js +157 -0
  116. package/kits/multiplayer-3d/code/server/players.js +114 -0
  117. package/kits/multiplayer-3d/code/server/sceneBodies.js +88 -0
  118. package/kits/multiplayer-3d/code/server/world.js +306 -0
  119. package/kits/multiplayer-3d/code/systems/multiplayer.js +427 -0
  120. package/kits/multiplayer-3d/eslint.config.js +20 -0
  121. package/kits/multiplayer-3d/fonts.generated.js +9 -0
  122. package/kits/multiplayer-3d/index.html +22 -0
  123. package/kits/multiplayer-3d/main.jsx +9 -0
  124. package/kits/multiplayer-3d/package-lock.json +368 -0
  125. package/kits/multiplayer-3d/package.json +32 -0
  126. package/kits/multiplayer-3d/scenes/main.scene +409 -0
  127. package/kits/multiplayer-3d/theme.style +3 -0
  128. package/kits/physics-2d/CLAUDE.md +6 -0
  129. package/kits/physics-2d/castle.json +7 -1
  130. package/kits/physics-2d/editors/behaviorRegistry.js +5 -0
  131. package/kits/physics-2d/editors/editorRegistry.jsx +3 -1
  132. package/kits/physics-2d/engine/files.js +9 -5
  133. package/kits/physics-2d/engine/systemRegistry.js +2 -0
  134. package/kits/physics-2d/engine/ui.module.css +11 -0
  135. package/kits/physics-2d/package-lock.json +8 -2
  136. package/kits/physics-2d/package.json +2 -2
  137. package/kits/physics-3d/CLAUDE.md +4 -4
  138. package/kits/physics-3d/behaviors/Shape.jsx +1 -1
  139. package/kits/physics-3d/blueprints/crate.scene +1 -1
  140. package/kits/physics-3d/blueprints/door.scene +4 -4
  141. package/kits/physics-3d/blueprints/pillar.scene +1 -1
  142. package/kits/physics-3d/blueprints/platform.scene +1 -1
  143. package/kits/physics-3d/blueprints/statue.scene +1 -1
  144. package/kits/physics-3d/blueprints/wall.scene +1 -1
  145. package/kits/physics-3d/castle.json +8 -11
  146. package/kits/physics-3d/docs/pxmodel-format.md +1 -1
  147. package/kits/physics-3d/engine3d/materials.js +3 -3
  148. package/kits/physics-3d/engine3d/modelFiles.js +4 -2
  149. package/kits/physics-3d/engine3d/world3d.js +1 -1
  150. package/kits/physics-3d/fonts.generated.js +9 -0
  151. package/kits/physics-3d/main.jsx +1 -1
  152. package/kits/physics-3d/package-lock.json +85 -2
  153. package/kits/physics-3d/package.json +6 -2
  154. package/kits/physics-3d/scenes/main.scene +1 -1
  155. package/kits/physics-3d/scenes/model-lab.scene +1 -1
  156. package/kits/real-time/.prettierrc +5 -0
  157. package/kits/real-time/CLAUDE.md +60 -0
  158. package/kits/real-time/castle.json +19 -0
  159. package/kits/real-time/code/client/clock.js +68 -0
  160. package/kits/real-time/code/client/connection.js +134 -0
  161. package/kits/real-time/code/client/gameHooks.js +50 -0
  162. package/kits/real-time/code/client/interpolate.js +82 -0
  163. package/kits/real-time/code/client/messages.js +55 -0
  164. package/kits/real-time/code/client/ownership.js +94 -0
  165. package/kits/real-time/code/client/smooth.js +54 -0
  166. package/kits/real-time/code/server/blockDelta.js +48 -0
  167. package/kits/real-time/code/server/gameHooks.js +47 -0
  168. package/kits/real-time/code/server/limits.js +35 -0
  169. package/kits/real-time/code/server/session.js +251 -0
  170. package/kits/real-time/eslint.config.js +22 -0
  171. package/kits/real-time/index.html +45 -0
  172. package/kits/real-time/package.json +14 -0
  173. package/kits/{tabletop → turn-based}/CLAUDE.md +42 -49
  174. package/kits/turn-based/blueprints/board.scene +15 -0
  175. package/kits/turn-based/blueprints/square.scene +25 -0
  176. package/kits/turn-based/castle.json +37 -0
  177. package/kits/turn-based/code/behaviors/Board.jsx +169 -0
  178. package/kits/turn-based/code/behaviors/Square.jsx +26 -0
  179. package/kits/turn-based/code/server/index.js +152 -0
  180. package/kits/turn-based/drawings/square.sprite +25 -0
  181. package/kits/turn-based/eslint.config.js +12 -0
  182. package/kits/turn-based/fonts.generated.js +9 -0
  183. package/kits/{tabletop → turn-based}/index.html +5 -3
  184. package/kits/{tabletop → turn-based}/main.jsx +2 -2
  185. package/kits/{tabletop → turn-based}/package-lock.json +17 -4
  186. package/kits/{tabletop → turn-based}/package.json +5 -2
  187. package/kits/turn-based/room.js +289 -0
  188. package/kits/turn-based/scenes/main.scene +227 -0
  189. package/kits/{tabletop → turn-based}/testing.js +131 -99
  190. package/kits/turn-based/theme.style +3 -0
  191. package/package.json +1 -1
  192. package/kits/blank/CLAUDE.md +0 -198
  193. package/kits/tabletop/castle.json +0 -34
  194. package/kits/tabletop/room.js +0 -269
  195. /package/kits/{blank → base}/index.html +0 -0
  196. /package/kits/{blank → base}/node_modules/castle-web-fonts/README.md +0 -0
  197. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.d.ts +0 -0
  198. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.js +0 -0
  199. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.d.ts +0 -0
  200. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.js +0 -0
  201. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +0 -0
  202. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.js +0 -0
  203. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +0 -0
  204. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +0 -0
  205. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +0 -0
  206. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.js +0 -0
  207. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +0 -0
  208. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.js +0 -0
  209. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +0 -0
  210. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +0 -0
  211. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +0 -0
  212. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +0 -0
  213. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +0 -0
  214. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.js +0 -0
  215. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +0 -0
  216. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.js +0 -0
  217. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +0 -0
  218. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.js +0 -0
  219. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.d.ts +0 -0
  220. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.js +0 -0
  221. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +0 -0
  222. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/FONTS.md +0 -0
  223. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +0 -0
  224. /package/kits/{blank → base}/node_modules/castle-web-fonts/package.json +0 -0
  225. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  226. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  227. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  228. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  229. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  230. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  231. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/SOURCE.txt +0 -0
  232. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  233. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  234. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  235. /package/kits/physics-3d/drawings/{crate.pxart → crate.sprite} +0 -0
  236. /package/kits/physics-3d/drawings/{door-edge.pxart → door-edge.sprite} +0 -0
  237. /package/kits/physics-3d/drawings/{door.pxart → door.sprite} +0 -0
  238. /package/kits/physics-3d/drawings/{face.pxart → face.sprite} +0 -0
  239. /package/kits/physics-3d/drawings/{floor.pxart → floor.sprite} +0 -0
  240. /package/kits/physics-3d/drawings/{platform.pxart → platform.sprite} +0 -0
  241. /package/kits/physics-3d/drawings/{statue.pxart → statue.sprite} +0 -0
  242. /package/kits/physics-3d/drawings/{wall.pxart → wall.sprite} +0 -0
  243. /package/kits/{tabletop → turn-based}/.prettierrc +0 -0
@@ -0,0 +1,970 @@
1
+ import { CASTLE_SDK_PROTOCOL, } from "./commands";
2
+ import { getCastleEmbed, isEdit } from "./context";
3
+ export const CARD_RATIO = 5 / 7;
4
+ // Host -> deck capture request, and the deck's answer. Kept in sync with the
5
+ // editor shell (cli/src/shell/coverApi.ts).
6
+ const HOST_CAPTURE_REQUEST = "castle-capture-cover";
7
+ const HOST_CAPTURE_RESULT = "castle-capture-cover-result";
8
+ let ws = null;
9
+ let logBuffer = [];
10
+ let nextRequestId = 1;
11
+ const pendingRequests = new Map();
12
+ // Local-dev command channel: the `castle-web serve` dev server is the host, so
13
+ // SDK commands ride the same websocket runtime.ts already uses for
14
+ // logs/screenshots/restart. Correlated by requestId, separate from the
15
+ // screenshot/write_file request map above.
16
+ const COMMAND_TIMEOUT_MS = 15000;
17
+ const SOCKET_WAIT_TIMEOUT_MS = 10000;
18
+ const pendingCommands = new Map();
19
+ const origLog = console.log;
20
+ const origWarn = console.warn;
21
+ const origError = console.error;
22
+ // Indirected dynamic import so deck bundlers don't statically rewrite it.
23
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
24
+ const dynamicImport = new Function("u", "return import(u)");
25
+ export function setup() {
26
+ interceptConsole();
27
+ connectLocal();
28
+ initLocalWake();
29
+ initHostCapture();
30
+ initPlaySelection();
31
+ initPlayCard();
32
+ logPanelLoad();
33
+ }
34
+ // Every panel boot leaves a line, so a reload from ANY cause shows up -- a load
35
+ // with no preceding reason line is one we do not yet explain.
36
+ function panelTag() {
37
+ try {
38
+ const q = new URLSearchParams(location.search);
39
+ return q.get("panel") || q.get("file") || "deck";
40
+ }
41
+ catch {
42
+ return "deck";
43
+ }
44
+ }
45
+ function logPanelLoad() {
46
+ setTimeout(() => console.log(`[reload] ${panelTag()} LOADED`), 0);
47
+ }
48
+ /**
49
+ * One attempt at writing a file, over the socket as it is right now. Fails when
50
+ * the socket does. This is the primitive `writeFile` is built on -- reach for it
51
+ * only when a failure genuinely means "give up", which is rare enough that the
52
+ * queue itself is the only caller in this repo.
53
+ */
54
+ export function writeFileOnce(path, contents) {
55
+ return sendLocalRequest({
56
+ type: "write_file",
57
+ path,
58
+ contents,
59
+ });
60
+ }
61
+ // A same-origin URL that serves a deck file as raw bytes. Editor UI that shows
62
+ // a file the browser renders natively -- an image in an `<img>`, a sound in an
63
+ // `<audio>` -- points at this instead of reading the file, which only speaks
64
+ // text. Only meaningful while editing locally with `castle-web serve`; a
65
+ // published deck has no serve to ask.
66
+ export function fileUrl(path) {
67
+ return `/__castle/files/raw?path=${encodeURIComponent(path)}`;
68
+ }
69
+ // Move a deck file. `writeFile`'s counterpart for the case where the file's
70
+ // NAME is the thing changing -- an editor renaming a blueprint has to move the
71
+ // file, not write a copy and leave the old one behind. Rejects when the
72
+ // destination exists or the source is gone (the serve's own guards), so a
73
+ // caller can surface the collision instead of silently clobbering.
74
+ export async function renameFile(from, to) {
75
+ await fileOp("rename", { from, to });
76
+ }
77
+ // Delete a deck file. Editor UI only, same as `writeFile` -- a published deck
78
+ // has no serve to ask.
79
+ export async function deleteFile(path) {
80
+ await fileOp("delete", { path });
81
+ }
82
+ async function fileOp(action, body) {
83
+ const res = await fetch(`/__castle/files/${action}`, {
84
+ method: "POST",
85
+ headers: { "content-type": "application/json" },
86
+ body: JSON.stringify(body),
87
+ });
88
+ if (res.ok)
89
+ return;
90
+ const detail = await res.text().catch(() => "");
91
+ throw new Error(`castle: ${action} failed (${res.status}) ${detail}`.trim());
92
+ }
93
+ // Ask the editor shell to open (or focus) an editor for `path`. This is how a
94
+ // kit editor hands the creator off to another file -- the creation modal
95
+ // dropping them into the pixel editor for the sprite it just made. A no-op
96
+ // anywhere there's no shell listening (a published deck, a bare serve), which
97
+ // is why it neither returns nor throws: the handoff is a courtesy, and the
98
+ // file was already written before we asked.
99
+ export function openFile(path) {
100
+ if (typeof window === "undefined" || window.parent === window)
101
+ return;
102
+ window.parent.postMessage({ type: "castle-open-file", path }, "*");
103
+ }
104
+ export function initCard() {
105
+ const style = document.createElement("style");
106
+ style.textContent = `
107
+ * { margin: 0; padding: 0; box-sizing: border-box; }
108
+ html, body { width: 100%; height: 100%; background: #000; overflow: hidden; }
109
+ body { display: flex; align-items: center; justify-content: center; }
110
+ #castle-card {
111
+ position: relative;
112
+ border-radius: 4% / calc(4% * (5 / 7));
113
+ overflow: hidden;
114
+ background: #121213;
115
+ }
116
+ `;
117
+ document.head.appendChild(style);
118
+ const card = document.createElement("div");
119
+ card.id = "castle-card";
120
+ document.body.appendChild(card);
121
+ function resize() {
122
+ const { w, h } = computeCardSize();
123
+ card.style.width = w + "px";
124
+ card.style.height = h + "px";
125
+ }
126
+ resize();
127
+ window.addEventListener("resize", resize);
128
+ return card;
129
+ }
130
+ // A deck being PLAYED is a game, not a document: dragging across it should move
131
+ // a paddle, not blue-highlight the score, and a long press on a phone should not
132
+ // raise the copy/define callout over the card.
133
+ //
134
+ // It belongs here rather than in a host. Selection is decided inside the deck's
135
+ // own document, so neither the website's iframe nor the app's WebView can reach
136
+ // it from outside -- and doing it once in the SDK covers the play panel,
137
+ // castle.xyz and the feed together.
138
+ //
139
+ // Play mode only: in edit mode the same document hosts kit editors and deck UI,
140
+ // where selecting text is the point. Form fields keep selection either way, so a
141
+ // deck that asks for a name still works.
142
+ function initPlaySelection() {
143
+ if (isEdit())
144
+ return;
145
+ const style = document.createElement("style");
146
+ style.textContent = `
147
+ html, body {
148
+ -webkit-user-select: none;
149
+ user-select: none;
150
+ -webkit-touch-callout: none;
151
+ }
152
+ input, textarea, [contenteditable=""], [contenteditable="true"] {
153
+ -webkit-user-select: text;
154
+ user-select: text;
155
+ }
156
+ `;
157
+ document.head.appendChild(style);
158
+ }
159
+ // Constrains whatever the deck renders into #root to a 5:7 card in play mode.
160
+ // Hosts own max size and padding; the SDK only preserves the card aspect ratio.
161
+ function initPlayCard() {
162
+ if (isEdit())
163
+ return;
164
+ const style = document.createElement("style");
165
+ style.textContent = `
166
+ html, body { background: #000; }
167
+ #root > * {
168
+ position: fixed !important;
169
+ inset: auto !important;
170
+ left: 50% !important;
171
+ top: 50% !important;
172
+ transform: translate(-50%, -50%) !important;
173
+ width: var(--castle-card-w, 100vw) !important;
174
+ height: var(--castle-card-h, 100vh) !important;
175
+ border-radius: 4% / calc(4% * (5 / 7)) !important;
176
+ overflow: hidden !important;
177
+ }
178
+ `;
179
+ document.head.appendChild(style);
180
+ // Mark whatever this turns into a card, the way `initCard` marks the one it
181
+ // creates. Anything looking for "the card" -- a capture cropping to it, in
182
+ // page or headless -- otherwise finds nothing here and has to guess at the
183
+ // viewport, which is not the same rectangle: standalone chrome insets the
184
+ // card, so a viewport shot carries a border the card does not have.
185
+ //
186
+ // Runs on a timer as well as now because `setup()` is called before a deck
187
+ // renders, so #root is usually still empty at this point; a deck that mounts
188
+ // later still gets its card marked.
189
+ function markCard() {
190
+ const el = document.querySelector("#root > *");
191
+ if (el)
192
+ el.dataset.castleCard = "";
193
+ }
194
+ markCard();
195
+ requestAnimationFrame(markCard);
196
+ new MutationObserver(markCard).observe(document.documentElement, {
197
+ childList: true,
198
+ subtree: true,
199
+ });
200
+ function resize() {
201
+ const { w, h } = computeCardSize();
202
+ document.documentElement.style.setProperty("--castle-card-w", w + "px");
203
+ document.documentElement.style.setProperty("--castle-card-h", h + "px");
204
+ }
205
+ resize();
206
+ window.addEventListener("resize", resize);
207
+ }
208
+ function computeCardSize() {
209
+ const pad = shouldUseStandaloneChrome() ? 20 : 0;
210
+ const aw = Math.max(1, window.innerWidth - pad * 2);
211
+ const ah = Math.max(1, window.innerHeight - pad * 2);
212
+ let w;
213
+ let h;
214
+ if (aw / ah < CARD_RATIO) {
215
+ w = aw;
216
+ h = w / CARD_RATIO;
217
+ }
218
+ else {
219
+ h = ah;
220
+ w = h * CARD_RATIO;
221
+ }
222
+ return { w, h };
223
+ }
224
+ function shouldUseStandaloneChrome() {
225
+ if (window.parent !== window)
226
+ return false;
227
+ const embed = getCastleEmbed();
228
+ return embed?.host === "dev";
229
+ }
230
+ function sendMsg(msg) {
231
+ if (ws && ws.readyState === WebSocket.OPEN) {
232
+ ws.send(JSON.stringify(msg));
233
+ }
234
+ else {
235
+ logBuffer.push(msg);
236
+ }
237
+ }
238
+ function sendLocalRequest(msg) {
239
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
240
+ return Promise.reject(new Error("Castle local CLI is not connected."));
241
+ }
242
+ const requestId = `req_${nextRequestId++}`;
243
+ const request = { ...msg, requestId };
244
+ return new Promise((resolve, reject) => {
245
+ const timeout = setTimeout(() => {
246
+ pendingRequests.delete(requestId);
247
+ reject(new Error(`Timed out waiting for ${msg.type}.`));
248
+ }, 10000);
249
+ pendingRequests.set(requestId, { resolve, reject, timeout });
250
+ ws.send(JSON.stringify(request));
251
+ });
252
+ }
253
+ // Send an SDK command to the dev server and resolve with the raw response
254
+ // envelope (ok/data/error). transport.ts interprets it — error reconstruction
255
+ // stays uniform across all three channels there. Waits for the socket to open
256
+ // so a command issued during startup isn't dropped.
257
+ export function sendLocalCommand(command, params) {
258
+ const requestId = `cmd_${nextRequestId++}`;
259
+ return new Promise((resolve, reject) => {
260
+ const timeout = setTimeout(() => {
261
+ pendingCommands.delete(requestId);
262
+ reject(new Error(`Timed out waiting for command ${command}.`));
263
+ }, COMMAND_TIMEOUT_MS);
264
+ pendingCommands.set(requestId, (env) => {
265
+ clearTimeout(timeout);
266
+ pendingCommands.delete(requestId);
267
+ resolve(env);
268
+ });
269
+ waitForSocket()
270
+ .then((socket) => {
271
+ socket.send(JSON.stringify({
272
+ type: "castle_command",
273
+ castleSdk: CASTLE_SDK_PROTOCOL,
274
+ requestId,
275
+ command,
276
+ params,
277
+ }));
278
+ })
279
+ .catch((error) => {
280
+ clearTimeout(timeout);
281
+ pendingCommands.delete(requestId);
282
+ reject(error instanceof Error ? error : new Error(String(error)));
283
+ });
284
+ });
285
+ }
286
+ function waitForSocket() {
287
+ if (ws && ws.readyState === WebSocket.OPEN)
288
+ return Promise.resolve(ws);
289
+ return new Promise((resolve, reject) => {
290
+ const start = Date.now();
291
+ const poll = setInterval(() => {
292
+ if (ws && ws.readyState === WebSocket.OPEN) {
293
+ clearInterval(poll);
294
+ resolve(ws);
295
+ }
296
+ else if (Date.now() - start > SOCKET_WAIT_TIMEOUT_MS) {
297
+ clearInterval(poll);
298
+ reject(new Error("Castle dev server is not connected."));
299
+ }
300
+ }, 100);
301
+ });
302
+ }
303
+ function resolveLocalCommand(msg) {
304
+ const pending = pendingCommands.get(msg.requestId);
305
+ if (pending)
306
+ pending(msg);
307
+ }
308
+ function resolveLocalRequest(msg) {
309
+ if (!msg.requestId)
310
+ return false;
311
+ const pending = pendingRequests.get(msg.requestId);
312
+ if (!pending)
313
+ return false;
314
+ clearTimeout(pending.timeout);
315
+ pendingRequests.delete(msg.requestId);
316
+ if (msg.ok) {
317
+ pending.resolve(msg);
318
+ }
319
+ else {
320
+ pending.reject(new Error(msg.error || "Castle local request failed."));
321
+ }
322
+ return true;
323
+ }
324
+ function interceptConsole() {
325
+ console.log = (...args) => {
326
+ origLog(...args);
327
+ sendMsg({ type: "log", level: "log", msg: formatConsoleArgs(args) });
328
+ };
329
+ console.warn = (...args) => {
330
+ origWarn(...args);
331
+ sendMsg({ type: "log", level: "warn", msg: formatConsoleArgs(args) });
332
+ };
333
+ console.error = (...args) => {
334
+ origError(...args);
335
+ sendMsg({ type: "log", level: "error", msg: formatConsoleArgs(args) });
336
+ };
337
+ }
338
+ function formatConsoleArgs(args) {
339
+ return args
340
+ .map((arg) => {
341
+ if (typeof arg === "string")
342
+ return arg;
343
+ if (arg instanceof Error)
344
+ return arg.stack || arg.message;
345
+ try {
346
+ const json = JSON.stringify(arg);
347
+ return json ?? String(arg);
348
+ }
349
+ catch {
350
+ return String(arg);
351
+ }
352
+ })
353
+ .join(" ");
354
+ }
355
+ // Compositing a card needs html2canvas, and where it comes from decides whether
356
+ // a capture can fail for reasons that have nothing to do with the deck.
357
+ //
358
+ // The serve lends it from its own origin (`castle-web serve`, so: the editor,
359
+ // the dev server, a cloud sandbox) -- same origin, no third party, and it works
360
+ // with no internet at all. Every caller that captures runs against a serve, so
361
+ // this is the path in practice.
362
+ //
363
+ // The CDN is the fallback for a deck with no serve behind it, which today means
364
+ // a published deck -- where nothing captures. Keeping it costs nothing and means
365
+ // a capture from somewhere unforeseen still degrades to "slow" rather than
366
+ // "canvas-only". Loaded once and reused: html2canvas is ~194KB.
367
+ let html2canvasPromise = null;
368
+ function loadHtml2Canvas() {
369
+ if (!html2canvasPromise) {
370
+ const local = new URL("/__castle/vendor/html2canvas.js", location.origin)
371
+ .href;
372
+ html2canvasPromise = dynamicImport(local)
373
+ .catch(() => dynamicImport("https://esm.sh/html2canvas"))
374
+ .catch((err) => {
375
+ // Don't cache a failure -- a later capture may have a serve, or a network.
376
+ html2canvasPromise = null;
377
+ throw err;
378
+ });
379
+ }
380
+ return html2canvasPromise;
381
+ }
382
+ async function captureWithHtml2Canvas(target) {
383
+ try {
384
+ const mod = await loadHtml2Canvas();
385
+ const c = await mod.default(target, {
386
+ backgroundColor: null,
387
+ scale: devicePixelRatio,
388
+ useCORS: true,
389
+ });
390
+ return c.toDataURL("image/png");
391
+ }
392
+ catch {
393
+ return null;
394
+ }
395
+ }
396
+ function cropCanvasToCard(card, canvas) {
397
+ const cardRect = card.getBoundingClientRect();
398
+ const c = document.createElement("canvas");
399
+ c.width = cardRect.width * devicePixelRatio;
400
+ c.height = cardRect.height * devicePixelRatio;
401
+ const ctx = c.getContext("2d");
402
+ const canvasRect = canvas.getBoundingClientRect();
403
+ const dx = (canvasRect.left - cardRect.left) * devicePixelRatio;
404
+ const dy = (canvasRect.top - cardRect.top) * devicePixelRatio;
405
+ ctx.drawImage(canvas, dx, dy, canvasRect.width * devicePixelRatio, canvasRect.height * devicePixelRatio);
406
+ return c.toDataURL("image/png");
407
+ }
408
+ // Does the card show anything the canvas didn't draw? A deck is free to put raw
409
+ // DOM in the card -- a HUD, a title, a button -- and that DOM is part of what the
410
+ // player sees, so a canvas-only capture would be a cover that doesn't match the
411
+ // deck. Walks the card for any rendered node outside the canvas: an element with
412
+ // a non-empty box, or visible text.
413
+ function hasContentBesidesCanvas(card, canvas) {
414
+ const isRenderedBox = (el) => {
415
+ const style = getComputedStyle(el);
416
+ if (style.display === "none" ||
417
+ style.visibility === "hidden" ||
418
+ style.opacity === "0") {
419
+ return false;
420
+ }
421
+ const rect = el.getBoundingClientRect();
422
+ return rect.width > 0 && rect.height > 0;
423
+ };
424
+ for (const el of Array.from(card.querySelectorAll("*"))) {
425
+ if (el === canvas || canvas.contains(el))
426
+ continue;
427
+ if (isRenderedBox(el))
428
+ return true;
429
+ }
430
+ // Text put straight in the card (or in a zero-box wrapper) renders without any
431
+ // element of its own to measure.
432
+ const walker = document.createTreeWalker(card, NodeFilter.SHOW_TEXT);
433
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
434
+ if ((n.textContent || "").trim())
435
+ return true;
436
+ }
437
+ return false;
438
+ }
439
+ async function captureScreenshot() {
440
+ const card = document.querySelector("#castle-card, [data-castle-card]");
441
+ if (card) {
442
+ const cardCanvas = card.querySelector("canvas");
443
+ // Cropping the canvas is exact and needs no network, but it only tells the
444
+ // truth when the canvas IS the card. Otherwise composite the whole card --
445
+ // html2canvas draws canvases into its output, so nothing is lost by it.
446
+ if (cardCanvas && !hasContentBesidesCanvas(card, cardCanvas)) {
447
+ return cropCanvasToCard(card, cardCanvas);
448
+ }
449
+ const composited = await captureWithHtml2Canvas(card);
450
+ if (composited)
451
+ return composited;
452
+ // html2canvas is fetched at capture time, so it can fail closed (offline, a
453
+ // host CSP). A canvas-only cover beats no cover.
454
+ if (cardCanvas)
455
+ return cropCanvasToCard(card, cardCanvas);
456
+ }
457
+ if (document.body?.dataset.castleScreenshotTarget === "viewport") {
458
+ const viewportCapture = await captureWithHtml2Canvas(document.body);
459
+ if (viewportCapture)
460
+ return viewportCapture;
461
+ }
462
+ const canvas = document.querySelector("canvas");
463
+ if (canvas)
464
+ return canvas.toDataURL("image/png");
465
+ return captureWithHtml2Canvas(card || document.body);
466
+ }
467
+ // A framing host (the editor shell, for a deck's cover image) asks the deck for
468
+ // a capture instead of reaching into the frame for its canvas: the canvas is
469
+ // only part of what a deck renders, and only the deck can composite the rest.
470
+ // Answers the window that asked, falling back to the parent frame.
471
+ function initHostCapture() {
472
+ if (typeof window === "undefined" || window.parent === window)
473
+ return;
474
+ // A host re-asks while it waits, in case its first request landed before this
475
+ // handler existed. Same id means same request, so the repeat is dropped rather
476
+ // than starting a second capture alongside the one already running.
477
+ const inFlight = new Set();
478
+ window.addEventListener("message", (event) => {
479
+ if (!isTrustedShellMessage(event))
480
+ return;
481
+ const data = event.data;
482
+ if (!data || data.type !== HOST_CAPTURE_REQUEST)
483
+ return;
484
+ const requestId = typeof data.requestId === "string" ? data.requestId : undefined;
485
+ if (requestId) {
486
+ if (inFlight.has(requestId))
487
+ return;
488
+ inFlight.add(requestId);
489
+ }
490
+ const reply = (dataUrl) => {
491
+ if (requestId)
492
+ inFlight.delete(requestId);
493
+ const target = event.source ?? window.parent;
494
+ target.postMessage({ type: HOST_CAPTURE_RESULT, requestId, dataUrl, ok: !!dataUrl }, event.origin);
495
+ };
496
+ void captureScreenshot().then(reply, () => reply(null));
497
+ });
498
+ }
499
+ function isTrustedShellMessage(event) {
500
+ const expectedOrigin = window
501
+ .__castleShellOrigin;
502
+ return (event.source === window.parent &&
503
+ (expectedOrigin ? event.origin === expectedOrigin : event.origin !== "null"));
504
+ }
505
+ // ─── local dev-server socket ───────────────────────────────────────────────────
506
+ // Reconnect policy mirrors the shell's terminal client: back off while the tab
507
+ // is visible, stay quiet while it is hidden or offline, and force a FRESH socket
508
+ // on wake. That last part is the one that matters -- a phone coming back from
509
+ // sleep holds a socket that still reports OPEN while its connection died with
510
+ // the radio, and nothing ever closes it. Sends into that socket vanish, which is
511
+ // what used to eat an edit made in the first seconds after unlocking.
512
+ const RECONNECT_DELAYS_MS = [250, 500, 1000, 2000, 4000, 8000, 12000, 15000];
513
+ // A heartbeat, for the same reason the shell has one: a write failing is good
514
+ // evidence the socket died, but a deck iframe that is only LISTENING -- for
515
+ // files_changed, for restart -- has nothing to fail, and would sit on a dead
516
+ // socket showing stale files. 25s also keeps the connection from being closed as
517
+ // idle by the proxy in front of a cloud sandbox (60s).
518
+ const PING_INTERVAL_MS = 25_000;
519
+ const PONG_TIMEOUT_MS = 8_000;
520
+ let pingTimer = null;
521
+ let pongTimer = null;
522
+ let reconnectTimer = null;
523
+ let reconnectAttempt = 0;
524
+ let socketToken = 0;
525
+ // The current socket whatever its readyState -- `ws` is only ever the open,
526
+ // usable one, so it can't answer "is a connection already on its way?".
527
+ let socketRef = null;
528
+ // Whether this page has ever reached a dev serve. A published deck has none
529
+ // (`/__castle/ws-port` 404s) and must never retry; a deck being edited does, so
530
+ // a failure there is a serve briefly away and IS worth retrying -- before, one
531
+ // blip during a sandbox restart stopped reconnection until a page reload.
532
+ let localServeSeen = false;
533
+ let needsWakeReconnect = false;
534
+ const intentionallyClosed = new WeakSet();
535
+ const connectionListeners = new Set();
536
+ let bridgeListening = false;
537
+ /**
538
+ * Notified `true` on every fresh dev-server socket and `false` when one is lost.
539
+ * What lets a queued write know the moment retrying is worth it again.
540
+ */
541
+ export function onLocalConnection(listener) {
542
+ connectionListeners.add(listener);
543
+ return () => connectionListeners.delete(listener);
544
+ }
545
+ function setConnected(connected) {
546
+ for (const listener of connectionListeners) {
547
+ try {
548
+ listener(connected);
549
+ }
550
+ catch {
551
+ // one subscriber's failure is not the socket's problem
552
+ }
553
+ }
554
+ }
555
+ // Connecting from a hidden tab is wasted work (browsers freeze it anyway) and
556
+ // connecting while the OS says there is no network just burns the backoff.
557
+ function canConnectLocal() {
558
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
559
+ return false;
560
+ }
561
+ return !(typeof navigator !== "undefined" && navigator.onLine === false);
562
+ }
563
+ function clearReconnectTimer() {
564
+ if (reconnectTimer === null)
565
+ return;
566
+ clearTimeout(reconnectTimer);
567
+ reconnectTimer = null;
568
+ }
569
+ // No give-up: nothing else would ever restart this socket, and every file write
570
+ // an editor makes rides it. The delays flatten out at 15s, which costs nothing
571
+ // while a sandbox is away and picks straight back up when it returns.
572
+ function scheduleReconnect() {
573
+ if (reconnectTimer !== null || !canConnectLocal())
574
+ return;
575
+ const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)];
576
+ reconnectAttempt += 1;
577
+ reconnectTimer = setTimeout(() => {
578
+ reconnectTimer = null;
579
+ connectLocal();
580
+ }, delay);
581
+ }
582
+ function connectLocal() {
583
+ clearReconnectTimer();
584
+ if (!canConnectLocal())
585
+ return;
586
+ if (typeof window !== "undefined" && window.parent !== window) {
587
+ connectBridge();
588
+ return;
589
+ }
590
+ fetch("/__castle/ws-port")
591
+ .then((r) => r.json())
592
+ .then(({ port, path }) => {
593
+ if (!port && !path) {
594
+ if (localServeSeen)
595
+ scheduleReconnect();
596
+ return;
597
+ }
598
+ localServeSeen = true;
599
+ openLocalSocket(path ? localWsUrl(path) : `ws://localhost:${port}`);
600
+ })
601
+ .catch(() => {
602
+ if (localServeSeen)
603
+ scheduleReconnect();
604
+ });
605
+ }
606
+ function connectBridge() {
607
+ if (bridgeListening || ws?.readyState === WebSocket.OPEN)
608
+ return;
609
+ bridgeListening = true;
610
+ const onInit = (event) => {
611
+ const data = event.data;
612
+ if (!data ||
613
+ data.type !== "castle-bridge-init" ||
614
+ !isTrustedShellMessage(event) ||
615
+ event.ports.length !== 1) {
616
+ return;
617
+ }
618
+ const port = event.ports[0];
619
+ const socket = {
620
+ readyState: WebSocket.OPEN,
621
+ send: (value) => {
622
+ try {
623
+ port.postMessage(JSON.parse(value));
624
+ }
625
+ catch {
626
+ /* malformed local payload */
627
+ }
628
+ },
629
+ };
630
+ port.onmessage = (messageEvent) => {
631
+ const value = messageEvent.data;
632
+ if (!value || typeof value !== "object")
633
+ return;
634
+ handleLocalMessage(value);
635
+ };
636
+ port.start();
637
+ localServeSeen = true;
638
+ ws = socket;
639
+ for (const msg of logBuffer)
640
+ socket.send(JSON.stringify(msg));
641
+ logBuffer = [];
642
+ bridgeListening = false;
643
+ window.removeEventListener("message", onInit);
644
+ setConnected(true);
645
+ };
646
+ window.addEventListener("message", onInit);
647
+ }
648
+ function stopHeartbeat() {
649
+ if (pingTimer !== null) {
650
+ clearInterval(pingTimer);
651
+ pingTimer = null;
652
+ }
653
+ if (pongTimer !== null) {
654
+ clearTimeout(pongTimer);
655
+ pongTimer = null;
656
+ }
657
+ }
658
+ // Any inbound frame answers the liveness question; a pong is just the one we
659
+ // asked for.
660
+ function noteAlive() {
661
+ if (pongTimer === null)
662
+ return;
663
+ clearTimeout(pongTimer);
664
+ pongTimer = null;
665
+ }
666
+ function startHeartbeat() {
667
+ stopHeartbeat();
668
+ pingTimer = setInterval(() => {
669
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
670
+ return;
671
+ }
672
+ if (!ws || ws.readyState !== WebSocket.OPEN)
673
+ return;
674
+ if (pongTimer !== null)
675
+ return;
676
+ try {
677
+ ws.send(JSON.stringify({ type: "ping" }));
678
+ }
679
+ catch {
680
+ wakeLocal(true);
681
+ return;
682
+ }
683
+ pongTimer = setTimeout(() => {
684
+ pongTimer = null;
685
+ wakeLocal(true);
686
+ }, PONG_TIMEOUT_MS);
687
+ }, PING_INTERVAL_MS);
688
+ }
689
+ function openLocalSocket(url) {
690
+ const socket = new WebSocket(url);
691
+ const token = ++socketToken;
692
+ socketRef = socket;
693
+ socket.onopen = () => {
694
+ if (socketToken !== token)
695
+ return;
696
+ ws = socket;
697
+ reconnectAttempt = 0;
698
+ for (const msg of logBuffer)
699
+ socket.send(JSON.stringify(msg));
700
+ logBuffer = [];
701
+ startHeartbeat();
702
+ setConnected(true);
703
+ };
704
+ socket.onmessage = (evt) => {
705
+ if (socketToken !== token)
706
+ return;
707
+ noteAlive();
708
+ try {
709
+ const msg = JSON.parse(evt.data);
710
+ if (msg.type === "pong")
711
+ return; // liveness only
712
+ handleLocalMessage(msg);
713
+ }
714
+ catch {
715
+ // ignore malformed messages
716
+ }
717
+ };
718
+ socket.onclose = () => {
719
+ // Requests belong to the socket that carried them, so they are settled by
720
+ // the socket losing the connection -- not by whichever one closes last.
721
+ if (ws === socket) {
722
+ stopHeartbeat();
723
+ ws = null;
724
+ for (const [requestId, pending] of pendingRequests) {
725
+ clearTimeout(pending.timeout);
726
+ pending.reject(new Error("Castle local CLI disconnected."));
727
+ pendingRequests.delete(requestId);
728
+ }
729
+ setConnected(false);
730
+ }
731
+ if (socketToken !== token)
732
+ return; // a newer socket has already taken over
733
+ socketRef = null;
734
+ if (!intentionallyClosed.has(socket))
735
+ scheduleReconnect();
736
+ };
737
+ socket.onerror = () => socket.close();
738
+ }
739
+ /**
740
+ * Replace a socket that claims to be OPEN but isn't carrying anything. Called
741
+ * when a request over it failed: that is the zombie's signature, and the only
742
+ * evidence available -- the connection died without a close, so `readyState`
743
+ * says OPEN and will go on saying it forever.
744
+ *
745
+ * This is what makes recovery independent of wake events. A network that drops
746
+ * while the tab is in front of you fires no visibilitychange, no pageshow and
747
+ * no focus, so without this a retry loop would keep posting into the same dead
748
+ * socket until the page was reloaded. Returns true if it acted.
749
+ */
750
+ export function reconnectIfSocketIsDead() {
751
+ if (!localServeSeen || !socketRef)
752
+ return false;
753
+ if (socketRef.readyState !== WebSocket.OPEN)
754
+ return false;
755
+ wakeLocal(true);
756
+ return true;
757
+ }
758
+ // Back from hidden/frozen/offline. `force` replaces even a socket that claims to
759
+ // be OPEN, because after a sleep that claim is exactly what can't be trusted;
760
+ // an in-flight write is safe to drop with it now that saves are queued and
761
+ // retried rather than sent once (see saveQueue.ts).
762
+ function wakeLocal(force) {
763
+ if (!localServeSeen || !canConnectLocal())
764
+ return;
765
+ reconnectAttempt = 0;
766
+ const current = socketRef;
767
+ if (current && current.readyState === WebSocket.CONNECTING)
768
+ return;
769
+ if (current && current.readyState === WebSocket.OPEN && !force)
770
+ return;
771
+ if (current && !intentionallyClosed.has(current)) {
772
+ intentionallyClosed.add(current);
773
+ try {
774
+ current.close(1000, "reconnect");
775
+ }
776
+ catch {
777
+ // already gone
778
+ }
779
+ }
780
+ connectLocal();
781
+ }
782
+ // Deliberately does NOT close the socket on the way out (the shell's terminal
783
+ // does): a pagehide is often a tab switch, and closing would settle writes that
784
+ // were about to land. The `persisted` pageshow below covers the bfcache case.
785
+ function initLocalWake() {
786
+ if (typeof document === "undefined" || typeof window === "undefined")
787
+ return;
788
+ const sleep = () => {
789
+ needsWakeReconnect = true;
790
+ clearReconnectTimer();
791
+ };
792
+ const wake = (extraForce = false) => {
793
+ const force = needsWakeReconnect || extraForce;
794
+ needsWakeReconnect = false;
795
+ wakeLocal(force);
796
+ };
797
+ document.addEventListener("visibilitychange", () => {
798
+ if (document.visibilityState === "hidden")
799
+ sleep();
800
+ else
801
+ wake();
802
+ });
803
+ window.addEventListener("pagehide", sleep);
804
+ window.addEventListener("offline", sleep);
805
+ window.addEventListener("pageshow", (event) => wake(event.persisted));
806
+ window.addEventListener("focus", () => wake());
807
+ window.addEventListener("online", () => wake(true));
808
+ }
809
+ function handleLocalMessage(msg) {
810
+ if (msg.type === "screenshot_request") {
811
+ void captureScreenshot()
812
+ .then((data) => {
813
+ if (data) {
814
+ sendMsg({
815
+ type: "screenshot_response",
816
+ requestId: msg.requestId,
817
+ data,
818
+ });
819
+ return;
820
+ }
821
+ sendMsg({
822
+ type: "screenshot_response",
823
+ requestId: msg.requestId,
824
+ ok: false,
825
+ error: "Could not capture screenshot.",
826
+ });
827
+ })
828
+ .catch((error) => {
829
+ sendMsg({
830
+ type: "screenshot_response",
831
+ requestId: msg.requestId,
832
+ ok: false,
833
+ error: error instanceof Error ? error.message : "Could not capture screenshot.",
834
+ });
835
+ });
836
+ }
837
+ else if (msg.type === "restart") {
838
+ scheduleReload(RESTART_DEBOUNCE_MS, "restart message");
839
+ }
840
+ else if (msg.type === "files_changed") {
841
+ dispatchFilesChanged(msg);
842
+ }
843
+ else if (msg.type === "write_file_response") {
844
+ resolveLocalRequest(msg);
845
+ }
846
+ else if (msg.type === "castle_command_response") {
847
+ resolveLocalCommand(msg);
848
+ }
849
+ }
850
+ // Files-changed listeners, registered by consumers (the kit engine, editors).
851
+ // The SDK only delivers the event; deciding what to re-read or reload is the
852
+ // consumer's job.
853
+ const filesChangedListeners = new Set();
854
+ export function onFilesChanged(listener) {
855
+ filesChangedListeners.add(listener);
856
+ return () => filesChangedListeners.delete(listener);
857
+ }
858
+ function dispatchFilesChanged(msg) {
859
+ const rawChanges = Array.isArray(msg.changes) ? msg.changes : [];
860
+ const changes = [];
861
+ for (const raw of rawChanges) {
862
+ if (typeof raw?.path !== "string")
863
+ continue;
864
+ const event = raw.event;
865
+ if (event !== "add" && event !== "change" && event !== "delete")
866
+ continue;
867
+ changes.push({
868
+ path: raw.path,
869
+ event,
870
+ affected: Array.isArray(raw.affected)
871
+ ? raw.affected.filter((p) => typeof p === "string")
872
+ : [],
873
+ });
874
+ }
875
+ if (changes.length === 0)
876
+ return;
877
+ const affected = Array.isArray(msg.affected)
878
+ ? msg.affected.filter((p) => typeof p === "string")
879
+ : [];
880
+ const event = { changes, affected };
881
+ for (const listener of filesChangedListeners) {
882
+ try {
883
+ listener(event);
884
+ }
885
+ catch {
886
+ // one consumer's failure shouldn't starve the others
887
+ }
888
+ }
889
+ }
890
+ // Restart (from `castle-web restart` / task agents) is debounced so a burst
891
+ // of reload requests -- several tasks finishing close together -- produces
892
+ // one reload. Before reloading, registered hooks run (the kit editor flushes
893
+ // its debounced unsaved edits there, save-state hooks stash their state) so
894
+ // in-flight work isn't lost.
895
+ const RESTART_DEBOUNCE_MS = 1500;
896
+ // Consumer-requested reloads (a code file changed) coalesce on a short window:
897
+ // the serve already batched the fs events, so this only folds multiple
898
+ // consumers requesting at once.
899
+ const REQUEST_RELOAD_DEBOUNCE_MS = 250;
900
+ let restartTimer = null;
901
+ const beforeRestartHooks = new Set();
902
+ export function onBeforeRestart(hook) {
903
+ beforeRestartHooks.add(hook);
904
+ return () => beforeRestartHooks.delete(hook);
905
+ }
906
+ // Save-state hooks: consumers register a saver keyed by a stable string; right
907
+ // before a reload every saver runs and its value is stashed in sessionStorage.
908
+ // After the reload the consumer calls takeReloadState(key) to pick it back up.
909
+ // Simple stash — enough for editor selection / lightweight runtime state.
910
+ const RELOAD_STATE_PREFIX = "castle-reload-state:";
911
+ const reloadStateSavers = new Map();
912
+ export function onSaveReloadState(key, save) {
913
+ reloadStateSavers.set(key, save);
914
+ return () => {
915
+ if (reloadStateSavers.get(key) === save)
916
+ reloadStateSavers.delete(key);
917
+ };
918
+ }
919
+ export function takeReloadState(key) {
920
+ try {
921
+ const raw = sessionStorage.getItem(RELOAD_STATE_PREFIX + key);
922
+ if (raw === null)
923
+ return null;
924
+ sessionStorage.removeItem(RELOAD_STATE_PREFIX + key);
925
+ return JSON.parse(raw);
926
+ }
927
+ catch {
928
+ return null;
929
+ }
930
+ }
931
+ function stashReloadState() {
932
+ for (const [key, save] of reloadStateSavers) {
933
+ try {
934
+ const value = save();
935
+ if (value === undefined)
936
+ continue;
937
+ sessionStorage.setItem(RELOAD_STATE_PREFIX + key, JSON.stringify(value));
938
+ }
939
+ catch {
940
+ // a failed saver shouldn't block the reload
941
+ }
942
+ }
943
+ }
944
+ // Reload this page after honoring the save hooks. Consumers call this when a
945
+ // files-changed event tells them code they run on has changed.
946
+ export function requestReload() {
947
+ scheduleReload(REQUEST_RELOAD_DEBOUNCE_MS, "requestReload");
948
+ }
949
+ function scheduleReload(delayMs, reason = "unknown") {
950
+ console.log(`[reload] ${panelTag()} scheduling reload (${reason})`);
951
+ if (restartTimer !== null)
952
+ clearTimeout(restartTimer);
953
+ restartTimer = setTimeout(() => {
954
+ void (async () => {
955
+ try {
956
+ await Promise.all([...beforeRestartHooks].map(async (hook) => hook()));
957
+ }
958
+ catch {
959
+ // a failed flush shouldn't block the reload
960
+ }
961
+ stashReloadState();
962
+ location.reload();
963
+ })();
964
+ }, delayMs);
965
+ }
966
+ function localWsUrl(path) {
967
+ const url = new URL(path, location.href);
968
+ url.protocol = location.protocol === "https:" ? "wss:" : "ws:";
969
+ return url.href;
970
+ }