castle-web-cli 0.4.156 → 0.4.158

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 +114 -8
  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-BuSYLy-C.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 +79 -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,569 @@
1
+ # Castle Web SDK Reference
2
+
3
+ `castle-web-sdk` lets a deck use services provided by the Castle
4
+ platform — for example, a deck can save per-player data, post and read
5
+ scores on a leaderboard, or get a server-synced time for daily content.
6
+
7
+ Comes with every deck: the SDK is a file of the `base` kit each deck
8
+ imports (`imports/castle.base/sdk/`), and the bare specifier resolves
9
+ there — nothing to install, and no deck `package.json` names it. Import
10
+ what you need from `castle-web-sdk`:
11
+
12
+ ```js
13
+ import { setup, initCard, Storage, Leaderboard } from "castle-web-sdk";
14
+ ```
15
+
16
+ ## Contents
17
+
18
+ - [Storage](#storage)
19
+ - [SharedStorage](#sharedstorage)
20
+ - [Leaderboard](#leaderboard)
21
+ - [Time](#time)
22
+ - [User](#user)
23
+ - [Pass](#pass)
24
+ - [Portal](#portal)
25
+ - [Haptics](#haptics)
26
+ - [Lifecycle](#lifecycle)
27
+ - [Multiplayer](#multiplayer)
28
+ - [Setup](#setup)
29
+ - [Saving files](#writefilepath-contents-promisevoid)
30
+ - [CastleError](#castleerror)
31
+
32
+ ## Multiplayer
33
+
34
+ `Multiplayer.join` connects the deck to its Cauldron server. Pick a public
35
+ session, the current Castle party, or a stable named room:
36
+
37
+ ```js
38
+ import { Multiplayer } from "castle-web-sdk";
39
+
40
+ const connection = await Multiplayer.join({ mode: "public" });
41
+ connection.onRoster(({ players, you }) => {
42
+ console.log(`${you?.username} is one of ${players.length} players`);
43
+ });
44
+ connection.onMessage((message) => receiveServerMessage(message));
45
+ connection.send({ type: "ready" });
46
+ ```
47
+
48
+ Named rooms use `{ mode: "named", key: "room-name" }`; party sessions use
49
+ `{ mode: "party" }`. Only one connection can be live per deck instance. The SDK
50
+ reconnects temporary socket drops automatically. `onStateChange` reports
51
+ `acquiring`, `connecting`, `connected`, `reconnecting`, and `closed`; its optional
52
+ metadata distinguishes a server `bye`, a replaced server version, an explicit
53
+ `leave`, and connection failures.
54
+
55
+ When Castle selects solo fallback, the returned connection has `isSolo === true`,
56
+ a one-player roster, and no server process. Calls to `send` are accepted but do
57
+ nothing. Client frames are limited to 16KB after JSON serialization.
58
+
59
+ Server callbacks are the default export from the deck's server entry. They are
60
+ session-first and receive only platform-trusted player identities:
61
+
62
+ ```js
63
+ export default {
64
+ onPlayerJoin(session, player) {
65
+ session.broadcast({ type: "joined", playerId: player.playerId });
66
+ },
67
+ onMessage(session, player, message) {
68
+ session.broadcast({ from: player.playerId, message });
69
+ },
70
+ };
71
+ ```
72
+
73
+ TypeScript server entries can import callback, session, player, and platform
74
+ handle types from `castle-web-sdk/server`. Server transport has no runtime
75
+ dependency on a WebSocket package.
76
+
77
+ ## Storage
78
+
79
+ `Storage` saves data for the current player. Nobody else can read it.
80
+ Use it for save files, settings, progress.
81
+
82
+ ### `Storage.get<T>(key): Promise<T | null>`
83
+
84
+ Returns the value at `key`, or `null` if not set.
85
+
86
+ ```js
87
+ const level = (await Storage.get("level")) ?? 1;
88
+ ```
89
+
90
+ ### `Storage.set(key, value)`
91
+
92
+ Sets `key` to `value`. `value` must be something that can convert to
93
+ JSON (`null`, booleans, finite numbers, strings, arrays, plain
94
+ objects). The next `get(key)` returns the new value immediately. Writes
95
+ save in the background.
96
+
97
+ ```js
98
+ Storage.set("level", 7);
99
+ Storage.set("settings", { sound: true, music: false });
100
+ ```
101
+
102
+ ### `Storage.remove(key)`
103
+
104
+ Removes `key`.
105
+
106
+ ## SharedStorage
107
+
108
+ `SharedStorage` saves data that other players can read. Values must
109
+ be something that can convert to JSON, same as `Storage`.
110
+
111
+ Scopes:
112
+
113
+ - `'deck'` — one shared bucket for the whole deck. Any player can read
114
+ or write.
115
+ - `'user'` — a per-player public bucket. Any player can read; only the
116
+ owning player can write.
117
+
118
+ ### `SharedStorage.get(scope, key): Promise<T | null>`
119
+
120
+ Reads a shared value. For `'user'`, omit the user id to read the
121
+ current player's bucket, or pass one to read someone else's:
122
+
123
+ ```js
124
+ const worldHighScore = await SharedStorage.get("deck", "highScore");
125
+ const myColor = await SharedStorage.get("user", "color");
126
+ const theirColor = await SharedStorage.get("user", otherUserId, "color");
127
+ ```
128
+
129
+ ### `SharedStorage.set(scope, key, value)`
130
+
131
+ Writes a shared value. `'user'` writes always go to the current
132
+ player's bucket. Writes save in the background.
133
+
134
+ ```js
135
+ SharedStorage.set("deck", "highScore", 9001);
136
+ SharedStorage.set("user", "color", "red");
137
+ ```
138
+
139
+ ### `SharedStorage.remove(scope, key)`
140
+
141
+ Removes a shared value.
142
+
143
+ ## Leaderboard
144
+
145
+ `Leaderboard` ranks players by a numeric score, per deck and per
146
+ variable name. Pick a variable name for each leaderboard the deck has
147
+ (e.g. `'score'`, `'time'`). `show` opens Castle's own leaderboard screen;
148
+ reach for `fetch` only if the deck draws the scores itself.
149
+
150
+ ### `Leaderboard.write(variable, score, options?)`
151
+
152
+ Submits a score. Only the player's best score for that `variable` (and
153
+ scope) is kept. In the editor it does nothing — safe to call from
154
+ gameplay code unconditionally.
155
+
156
+ `options` is `{ scope?: string }`. By default the score goes to the
157
+ deck's global leaderboard for `variable`; pass `scope` to write to a
158
+ separate leaderboard (for example a daily one, or a custom id):
159
+
160
+ ```js
161
+ Leaderboard.write("score", 1200);
162
+
163
+ // A daily leaderboard: scope by the current Castle day so each day gets
164
+ // its own board (see Time.getServerDate).
165
+ const { daysSinceCastleEpoch } = await Time.getServerDate();
166
+ Leaderboard.write("score", 1200, { scope: `daily-${daysSinceCastleEpoch}` });
167
+ ```
168
+
169
+ ### `Leaderboard.show(variable, type, options?): Promise<LeaderboardShowResult>`
170
+
171
+ Opens Castle's own leaderboard screen for `variable` — the same board
172
+ players see on other Castle decks, with FOR YOU and GLOBAL tabs, sharing,
173
+ and profile links. This is the normal way to show a leaderboard: Castle
174
+ draws it and owns the data, so the deck gets no entries back.
175
+
176
+ `type` is `'high'` (highest first) or `'low'` (lowest first). `options` is
177
+ `{ scope?, label? }` — `scope` works as it does in `write`, and `label`
178
+ titles the column of scores (default `'Score'`; e.g. `'Time'`, `'Coins'`).
179
+
180
+ Opening the board also submits the score the player has written this
181
+ session, so their own result is on it right away. The board appears
182
+ immediately, on a loading spinner; the promise resolves once the scores
183
+ are in. The player closes it themselves — there's no `hide`.
184
+
185
+ `LeaderboardShowResult` has a `status`:
186
+
187
+ - `'shown'` — Castle opened the leaderboard.
188
+ - `'unavailable'` — this host has no leaderboard screen, or can't show
189
+ one right now. Nothing was submitted; the score still saves normally.
190
+
191
+ ```js
192
+ Leaderboard.write("score", finalScore);
193
+ gameOverButton.onclick = () => Leaderboard.show("score", "high");
194
+ ```
195
+
196
+ ### `Leaderboard.fetch(variable, type, options?): Promise<LeaderboardData>`
197
+
198
+ Fetches the leaderboard's entries so the deck can draw them itself — use
199
+ this only when Castle's own screen isn't what you want. `type` and
200
+ `options.scope` work as they do in `show`.
201
+
202
+ Like `show`, a fetch reflects **the player's own** score written this
203
+ session right away. Other players' recent scores still appear on their own
204
+ normal timing.
205
+
206
+ The returned `LeaderboardData` has:
207
+
208
+ - `list` — array of entries, each `{ place, value, username, userId? }`.
209
+ - `playerRank` — the current player's place on the board (if they have
210
+ a score).
211
+ - `playerValue` — the current player's score (if they have one).
212
+
213
+ ```js
214
+ const data = await Leaderboard.fetch("score", "high");
215
+ for (const entry of data.list) {
216
+ console.log(`${entry.place}. ${entry.username} — ${entry.value}`);
217
+ }
218
+ if (data.playerRank) {
219
+ console.log(`you are #${data.playerRank} with ${data.playerValue}`);
220
+ }
221
+ ```
222
+
223
+ ## Time
224
+
225
+ ### `Time.getServerTime(): Promise<number>`
226
+
227
+ Returns the current server time as a Unix timestamp in seconds.
228
+
229
+ ```js
230
+ const now = await Time.getServerTime();
231
+ ```
232
+
233
+ ### `Time.getServerDate(timezone?): Promise<CastleDateParts>`
234
+
235
+ Returns the current server time broken into date parts. `timezone` is
236
+ `'Castle'` (default; Castle's server timezone, same for every player)
237
+ or `'player'` (the player's local timezone).
238
+
239
+ The returned `CastleDateParts` has:
240
+
241
+ - `sec`, `min`, `hour` — time of day.
242
+ - `day` (1-31), `month` (1-12), `year` — date.
243
+ - `wday` — day of the week (1-7, Sunday = 1).
244
+ - `yday` — day of the year (1-366).
245
+ - `daysSinceCastleEpoch` — a day number that increments every day.
246
+ Use it for daily content.
247
+
248
+ ```js
249
+ const date = await Time.getServerDate("player");
250
+ const dailyPuzzle = (date.daysSinceCastleEpoch % 30) + 1;
251
+ ```
252
+
253
+ ## User
254
+
255
+ ### `User.getCurrent(): Promise<CastleUser>`
256
+
257
+ Returns the signed-in player. Throws `CastleError`
258
+ (`LOGIN_REQUIRED`) when nobody is signed in.
259
+
260
+ The returned `CastleUser` has `userId`, `username`, `isAnonymous`, and `isActive`.
261
+ Anonymous accounts are real logins with generated `anonymous-user-...` names;
262
+ check `isAnonymous` before accepting writes into anything other players see,
263
+ such as a shared gallery.
264
+
265
+ ```js
266
+ const me = await User.getCurrent();
267
+ greet(me.username);
268
+ ```
269
+
270
+ ## Pass
271
+
272
+ A pass is something a creator sells to players for Castle bricks (the
273
+ in-app currency): buy it once, own it for good. Use one to gate part of a
274
+ deck behind a purchase — bonus levels, a cosmetic, supporting the
275
+ creator. Set up the pass (name, art, price) on Castle; a deck refers to
276
+ it by id.
277
+
278
+ ### `Pass.has(passId): Promise<boolean>`
279
+
280
+ Returns `true` if the current player owns the pass. No UI, nothing
281
+ charged — use it to gate content.
282
+
283
+ ```js
284
+ if (await Pass.has(bonusLevelsPassId)) {
285
+ showBonusLevels();
286
+ }
287
+ ```
288
+
289
+ ### `Pass.offer(passId): Promise<PassOfferResult>`
290
+
291
+ Presents the pass for the player to buy; resolves when they're done.
292
+ Bricks cost real money, so this only works in the Castle mobile app —
293
+ elsewhere (the website, the dev server) it resolves `unavailable`.
294
+ `PassOfferResult` has a `status`:
295
+
296
+ - `'purchased'` — just bought it; grant access.
297
+ - `'alreadyOwned'` — already had it (not charged); grant access.
298
+ - `'cancelled'` — dismissed without buying.
299
+ - `'unavailable'` — can't buy here (e.g. the website).
300
+
301
+ ```js
302
+ const { status } = await Pass.offer(bonusLevelsPassId);
303
+ if (status === "purchased" || status === "alreadyOwned") {
304
+ showBonusLevels();
305
+ }
306
+ ```
307
+
308
+ ## Portal
309
+
310
+ A portal sends the player from this deck to another Castle deck,
311
+ referred to by its deck id.
312
+
313
+ ### `Portal.open(deckId): Promise<PortalOpenResult>`
314
+
315
+ Sends the player to `deckId`: the Castle app swipes the feed to it, the
316
+ website opens its page. There's nowhere to go in the editor or dev server,
317
+ so there it resolves `unavailable`. `PortalOpenResult` has a `status`:
318
+
319
+ - `'navigating'` — the host is moving to the target deck. Treat `open` as
320
+ final: this deck is torn down as it navigates away, so don't rely on code
321
+ running afterward.
322
+ - `'unavailable'` — nowhere to navigate here (the editor or dev server).
323
+
324
+ ```js
325
+ portalButton.onclick = async () => {
326
+ const { status } = await Portal.open(nextDeckId);
327
+ if (status === "unavailable") {
328
+ // No feed to navigate here — fall back to your own affordance.
329
+ }
330
+ };
331
+ ```
332
+
333
+ ### `Portal.prefetch(deckId): Promise<PortalPrefetchResult>`
334
+
335
+ A best-effort hint that the player may soon `open(deckId)`. In the Castle app
336
+ the host warms that deck (fetching it now so a later `open` transitions without
337
+ a cold load); everywhere else it's a no-op. `PortalPrefetchResult`
338
+ has a `status`:
339
+
340
+ - `'prefetching'` — the host accepted the hint (or the deck was already warm).
341
+ - `'rejected'` — the host declined, e.g. this deck has already prefetched its
342
+ limit of upcoming decks. Prefetch a few likely destinations, not everything.
343
+ - `'unavailable'` — the host doesn't prefetch here (the website, editor, or dev
344
+ server).
345
+
346
+ ```js
347
+ link.addEventListener("pointerenter", () => {
348
+ Portal.prefetch(link.dataset.deckId);
349
+ });
350
+ ```
351
+
352
+ ## Haptics
353
+
354
+ `Haptics` plays a short device vibration ("buzz") for tactile feedback —
355
+ a tap confirmation, a success chime, an error shake. The host owns the
356
+ effect: the Castle mobile app plays a native haptic, the website uses the
357
+ browser's vibration API where available, and the dev server or an
358
+ unsupported device does nothing.
359
+
360
+ ### `Haptics.play(style): Promise<HapticsResult>`
361
+
362
+ Plays a haptic in one of seven styles:
363
+
364
+ - `'light'`, `'medium'`, `'heavy'` — impact taps of increasing strength.
365
+ - `'selection'` — a light tick, e.g. moving through options.
366
+ - `'success'`, `'warning'`, `'error'` — notification patterns.
367
+
368
+ Usually you don't await it — fire it and move on:
369
+
370
+ ```js
371
+ button.onclick = () => {
372
+ Haptics.play("light");
373
+ doTheThing();
374
+ };
375
+ ```
376
+
377
+ The returned `HapticsResult` has a `status`, if you want to branch on it:
378
+
379
+ - `'triggered'` — the host played (or accepted) the haptic.
380
+ - `'unavailable'` — this host or device can't play haptics (e.g. the dev
381
+ server, or a browser with no vibration support). Nothing was played.
382
+
383
+ Haptics respect the player's settings — if a player has muted haptics,
384
+ `play` does nothing and resolves `'unavailable'`. Rapid repeated calls may
385
+ be coalesced, so it's safe to call on frequent events.
386
+
387
+ ## Lifecycle
388
+
389
+ `Lifecycle` tells the host when the deck has painted its first frame, so
390
+ the Castle feed can reveal it right away instead of waiting out a fixed
391
+ delay.
392
+
393
+ ### `Lifecycle.ready()`
394
+
395
+ Signal that the deck has painted its first presentable frame. Idempotent
396
+ — only the first call has any effect.
397
+
398
+ Kits already wire this up to fire as soon as the first frame paints; if
399
+ you change how the deck first renders, make sure it still fires there. If
400
+ nothing calls this, the feed reveals the deck on its own after a brief
401
+ timeout.
402
+
403
+ If you call it right after kicking off your initial render, wait for the
404
+ next paint first so the host doesn't reveal a blank frame:
405
+
406
+ ```js
407
+ createRoot(root).render(<App />);
408
+ requestAnimationFrame(() => requestAnimationFrame(() => Lifecycle.ready()));
409
+ ```
410
+
411
+ ## Setup
412
+
413
+ Startup, editor-mode check, and a file-write call for editor UI.
414
+
415
+ ### `setup()`
416
+
417
+ Call this once at the start of the deck, before any other SDK call.
418
+ `setup()` initializes the SDK so the rest of the API is usable and
419
+ mounts a 5:7 Castle card around whatever the deck renders into `#root`
420
+ in play mode. The SDK preserves the card aspect ratio; Castle hosts own
421
+ the card's max size, placement, and surrounding padding.
422
+ While running locally with `castle-web serve`, it also forwards
423
+ `console` output to the CLI and reloads the page when `castle-web
424
+ restart` runs.
425
+
426
+ ```js
427
+ import { setup } from "castle-web-sdk";
428
+
429
+ setup();
430
+ ```
431
+
432
+ ### `initCard(): HTMLDivElement`
433
+
434
+ Use this when the deck draws into a `<canvas>` (or anything else)
435
+ rather than into the React tree at `#root`. Returns a `<div>` with the
436
+ standard Castle 5:7 card aspect ratio. The div resizes itself when the
437
+ window resizes. In Castle-hosted iframes/WebViews it fills the host's
438
+ available card frame.
439
+
440
+ ```js
441
+ import { setup, initCard } from "castle-web-sdk";
442
+
443
+ setup();
444
+ const card = initCard();
445
+
446
+ const canvas = document.createElement("canvas");
447
+ canvas.style.cssText = "width: 100%; height: 100%; display: block;";
448
+ card.appendChild(canvas);
449
+ ```
450
+
451
+ If the deck mounts a React tree into `#root` instead, you don't need
452
+ `initCard()` — `setup()` already wraps `#root`'s children in a card.
453
+
454
+ Host-specific layout flags such as `CastleEmbed.feed` are deprecated.
455
+ New code should let Castle hosts provide the frame and let the SDK infer
456
+ whether it is running standalone or embedded.
457
+
458
+ ### `CARD_RATIO`
459
+
460
+ The card aspect ratio (`5 / 7`). Use this if you need to size something
461
+ to match the card.
462
+
463
+ ### `isEdit(): boolean`
464
+
465
+ `true` when the deck is being edited, `false` when it's being played.
466
+ Use this to show editor UI only in edit mode.
467
+
468
+ ```js
469
+ import { isEdit, setup } from "castle-web-sdk";
470
+
471
+ setup();
472
+ if (isEdit()) {
473
+ mountEditor();
474
+ } else {
475
+ startGame();
476
+ }
477
+ ```
478
+
479
+ ### `writeFile(path, contents): Promise<void>`
480
+
481
+ Writes a file in the deck directory. `path` is relative to the deck
482
+ root, `contents` is a string. Use this from editor UI to save scenes,
483
+ drawings, or generated source.
484
+
485
+ ```js
486
+ import { writeFile } from "castle-web-sdk";
487
+
488
+ writeFile("scenes/main.scene", JSON.stringify(scene, null, 2));
489
+ ```
490
+
491
+ The write is **durable**: the newest contents per path are held until the
492
+ dev server confirms them, retried if it is briefly unreachable, and
493
+ written as soon as it is back — including across a page reload. A dev
494
+ server connection drops more often than it looks (a sleeping laptop or
495
+ phone, a network change, a restarted serve), and an editor that treated
496
+ those moments as failures would show work as saved that never landed.
497
+
498
+ Because of that, the returned promise settles with the FIRST attempt: it
499
+ rejecting means "not yet", not "lost". Don't drive a "saved" indicator
500
+ off it — use `onSaveState` below.
501
+
502
+ Only works while editing locally with `castle-web serve`. Calls from a
503
+ published deck fail.
504
+
505
+ ### `onSaveState(listener): () => void`
506
+
507
+ Subscribe to what is still waiting to reach disk. The listener gets
508
+ `{ pending, error }` — `pending` lists the paths the dev server hasn't
509
+ confirmed, and `error` is why, while writes are failing. Fires on every
510
+ change and once immediately; returns an unsubscribe.
511
+
512
+ ```js
513
+ import { onSaveState } from "castle-web-sdk";
514
+
515
+ onSaveState(({ pending, error }) => {
516
+ banner.hidden = !(error && pending.length);
517
+ });
518
+ ```
519
+
520
+ `hasPendingSave(path)` answers the same question for one file — useful
521
+ for ignoring a file-change event that is only the echo of your own write
522
+ still in flight. `flushSaves()` gives everything queued an immediate
523
+ attempt and resolves once they have all settled, whatever the outcome;
524
+ reach for it just before a reload.
525
+
526
+ ### `writeFileOnce(path, contents): Promise<void>`
527
+
528
+ One attempt, over the connection as it is right now, failing when it
529
+ fails. Almost nothing wants this — a rejection here means the write is
530
+ gone, and the caller owns what happens next. Use it only when a failure
531
+ genuinely means give up, and `writeFile` when a person's work is at
532
+ stake.
533
+
534
+ ### `fileUrl(path): string`
535
+
536
+ A URL that serves a deck file as raw bytes. Point an `<img>`, `<audio>`,
537
+ or `<video>` at it when editor UI has to show a file the browser renders
538
+ natively — `writeFile`'s counterpart reads text, which is nothing an
539
+ image or a sound can be read as.
540
+
541
+ ```js
542
+ import { fileUrl } from "castle-web-sdk";
543
+
544
+ <img src={fileUrl("assets/logo.png")} alt="" />;
545
+ ```
546
+
547
+ Like `writeFile`, this only means anything while editing locally with
548
+ `castle-web serve` — a published deck has no serve to ask, and should
549
+ load its assets through the bundler instead.
550
+
551
+ ## CastleError
552
+
553
+ Every error the SDK throws is a `CastleError`. Check `code` to tell
554
+ the kinds apart.
555
+
556
+ Common codes:
557
+
558
+ - `LOGIN_REQUIRED` — the player needs to be signed in.
559
+ - `MISSING_DECK_ID` — the deck hasn't been saved to Castle yet, so it
560
+ has no id.
561
+ - `CASTLE_STORAGE_SERIALIZE_FAILED` — value isn't plain JSON (e.g. a
562
+ class instance, a function, a non-finite number, or a cycle).
563
+ - `INVALID_LEADERBOARD_VARIABLE`, `INVALID_LEADERBOARD_SCORE`,
564
+ `INVALID_LEADERBOARD_TYPE` — bad argument to a `Leaderboard` call.
565
+ - `UNSUPPORTED_TIMEZONE` — `Time.getServerDate` got a zone other than
566
+ `'Castle'` or `'player'`.
567
+ - `CASTLE_HOST_UNAVAILABLE` — the Castle host (the app or website running
568
+ the deck) didn't handle the request — e.g. it timed out or wasn't
569
+ reachable. Usually transient; retry or surface a gentle error.
@@ -0,0 +1,27 @@
1
+ export { isEdit } from "./context";
2
+ export { CastleError } from "./errors";
3
+ export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
4
+ export { Haptics } from "./haptics";
5
+ export type { CastleHapticsApi, HapticsResult, HapticsStatus, HapticStyle } from "./haptics";
6
+ export { Leaderboard } from "./leaderboard";
7
+ export type { LeaderboardData, LeaderboardEntry, LeaderboardOptions, LeaderboardScope, LeaderboardShowOptions, LeaderboardShowResult, LeaderboardShowStatus, LeaderboardSort, } from "./leaderboard";
8
+ export { Lifecycle } from "./lifecycle";
9
+ export type { CastleLifecycleApi } from "./lifecycle";
10
+ export { Multiplayer } from "./multiplayer";
11
+ export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerStateMetadata, } from "./multiplayer";
12
+ export { MAX_CLIENT_FRAME_BYTES, MAX_PLAYERS_CAP } from "./multiplayerProtocol";
13
+ export type { ClientByeFrame, ClientHelloFrame, ClientMessageFrame, ClientPingFrame, ClientPongFrame, ClientReplacedFrame, ClientRosterFrame, ClientToPlatformFrame, ClientToPlatformMessageFrame, MultiplayerPlayer, PlayerIdentity, PlatformToClientFrame, SessionPlayer, SessionType, } from "./multiplayerProtocol";
14
+ export { Pass } from "./passes";
15
+ export type { CastlePassApi, PassOfferResult, PassOfferStatus, } from "./passes";
16
+ export { Portal } from "./portal";
17
+ export type { CastlePortalApi, PortalOpenResult, PortalOpenStatus, PortalPrefetchResult, PortalPrefetchStatus, } from "./portal";
18
+ export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
19
+ export type { FileChange, FilesChangedEvent } from "./runtime";
20
+ export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
21
+ export type { SaveState } from "./saveQueue";
22
+ export { SharedStorage, Storage } from "./storage";
23
+ export { Time } from "./time";
24
+ export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
25
+ export type { Json } from "./types";
26
+ export { User } from "./user";
27
+ export type { CastleUser, CastleUserApi } from "./user";
@@ -0,0 +1,16 @@
1
+ // Castle Web SDK
2
+ export { isEdit } from "./context";
3
+ export { CastleError } from "./errors";
4
+ export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
5
+ export { Haptics } from "./haptics";
6
+ export { Leaderboard } from "./leaderboard";
7
+ export { Lifecycle } from "./lifecycle";
8
+ export { Multiplayer } from "./multiplayer";
9
+ export { MAX_CLIENT_FRAME_BYTES, MAX_PLAYERS_CAP } from "./multiplayerProtocol";
10
+ export { Pass } from "./passes";
11
+ export { Portal } from "./portal";
12
+ export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
13
+ export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
14
+ export { SharedStorage, Storage } from "./storage";
15
+ export { Time } from "./time";
16
+ export { User } from "./user";