castle-web-cli 0.4.164 → 0.4.165

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 (127) hide show
  1. package/dist/agent-prompts.d.ts +3 -0
  2. package/dist/agent-prompts.js +14 -6
  3. package/dist/agent.js +14 -1
  4. package/dist/castle-host/host.js +276 -0
  5. package/dist/devSessionChild.js +66 -1
  6. package/dist/devSessionServer.js +21 -2
  7. package/dist/devSessionStorage.d.ts +9 -0
  8. package/dist/devSessionStorage.js +139 -0
  9. package/dist/forks.js +1 -1
  10. package/dist/ide.d.ts +0 -2
  11. package/dist/ide.js +1 -7
  12. package/dist/imports.js +5 -0
  13. package/dist/init.js +1 -1
  14. package/dist/platformDoc.js +14 -2
  15. package/dist/rawData.d.ts +2 -0
  16. package/dist/rawData.js +10 -0
  17. package/dist/serve.js +98 -0
  18. package/dist/shell/assets/{index-QtCau5vM.js → index-CG9TrvCm.js} +1 -1
  19. package/dist/shell/index.html +1 -1
  20. package/kits/base/CLAUDE.md +1 -1
  21. package/kits/base/castle.json +1 -1
  22. package/kits/base/node_modules/.package-lock.json +28 -0
  23. package/kits/base/node_modules/castle-web-fonts/README.md +114 -0
  24. package/kits/base/node_modules/castle-web-fonts/dist/catalog.d.ts +18 -0
  25. package/kits/base/node_modules/castle-web-fonts/dist/catalog.js +142 -0
  26. package/kits/base/node_modules/castle-web-fonts/dist/face.d.ts +1 -0
  27. package/kits/base/node_modules/castle-web-fonts/dist/face.js +52 -0
  28. package/kits/base/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +3 -0
  29. package/kits/base/node_modules/castle-web-fonts/dist/faces/Bore.js +10 -0
  30. package/kits/base/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +3 -0
  31. package/kits/base/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +10 -0
  32. package/kits/base/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +3 -0
  33. package/kits/base/node_modules/castle-web-fonts/dist/faces/DMSans.js +10 -0
  34. package/kits/base/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +3 -0
  35. package/kits/base/node_modules/castle-web-fonts/dist/faces/Glacier.js +10 -0
  36. package/kits/base/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +3 -0
  37. package/kits/base/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +10 -0
  38. package/kits/base/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +3 -0
  39. package/kits/base/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +10 -0
  40. package/kits/base/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +3 -0
  41. package/kits/base/node_modules/castle-web-fonts/dist/faces/Synco.js +10 -0
  42. package/kits/base/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +3 -0
  43. package/kits/base/node_modules/castle-web-fonts/dist/faces/Tektur.js +10 -0
  44. package/kits/base/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +3 -0
  45. package/kits/base/node_modules/castle-web-fonts/dist/faces/YatraOne.js +10 -0
  46. package/kits/base/node_modules/castle-web-fonts/dist/index.d.ts +16 -0
  47. package/kits/base/node_modules/castle-web-fonts/dist/index.js +15 -0
  48. package/kits/base/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +393 -0
  49. package/kits/base/node_modules/castle-web-fonts/licenses/FONTS.md +64 -0
  50. package/kits/base/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +95 -0
  51. package/kits/base/node_modules/castle-web-fonts/package.json +47 -0
  52. package/kits/base/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  53. package/kits/base/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  54. package/kits/base/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  55. package/kits/base/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  56. package/kits/base/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  57. package/kits/base/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  58. package/kits/base/node_modules/castle-web-fonts/woff2/SOURCE.txt +2 -0
  59. package/kits/base/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  60. package/kits/base/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  61. package/kits/base/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  62. package/kits/base/package-lock.json +1 -1
  63. package/kits/base/sdk/README.md +181 -36
  64. package/kits/base/sdk/castle.d.ts +2 -0
  65. package/kits/base/sdk/castle.js +1 -0
  66. package/kits/base/sdk/chunk.d.ts +1 -0
  67. package/kits/base/sdk/chunk.js +15 -0
  68. package/kits/base/sdk/commands.d.ts +86 -0
  69. package/kits/base/sdk/runtime.js +21 -12
  70. package/kits/base/sdk/server/platformHandle.d.ts +10 -0
  71. package/kits/base/sdk/server/storage.d.ts +46 -0
  72. package/kits/base/sdk/server/storage.js +218 -0
  73. package/kits/base/sdk/server/wrapper.d.ts +14 -1
  74. package/kits/base/sdk/server/wrapper.js +4 -1
  75. package/kits/base/sdk/storage.d.ts +15 -0
  76. package/kits/base/sdk/storage.js +29 -86
  77. package/kits/base/sdk/storageJson.d.ts +5 -0
  78. package/kits/base/sdk/storageJson.js +69 -0
  79. package/kits/base/sdk/store.d.ts +67 -0
  80. package/kits/base/sdk/store.js +313 -0
  81. package/kits/base/sdk/unloadFlush.d.ts +3 -0
  82. package/kits/base/sdk/unloadFlush.js +30 -0
  83. package/kits/blank/node_modules/.package-lock.json +13 -0
  84. package/kits/blank/node_modules/castle-web-fonts/README.md +114 -0
  85. package/kits/blank/node_modules/castle-web-fonts/dist/catalog.d.ts +18 -0
  86. package/kits/blank/node_modules/castle-web-fonts/dist/catalog.js +142 -0
  87. package/kits/blank/node_modules/castle-web-fonts/dist/face.d.ts +1 -0
  88. package/kits/blank/node_modules/castle-web-fonts/dist/face.js +52 -0
  89. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +3 -0
  90. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.js +10 -0
  91. package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +3 -0
  92. package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +10 -0
  93. package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +3 -0
  94. package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.js +10 -0
  95. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +3 -0
  96. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.js +10 -0
  97. package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +3 -0
  98. package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +10 -0
  99. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +3 -0
  100. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +10 -0
  101. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +3 -0
  102. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.js +10 -0
  103. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +3 -0
  104. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.js +10 -0
  105. package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +3 -0
  106. package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.js +10 -0
  107. package/kits/blank/node_modules/castle-web-fonts/dist/index.d.ts +16 -0
  108. package/kits/blank/node_modules/castle-web-fonts/dist/index.js +15 -0
  109. package/kits/blank/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +393 -0
  110. package/kits/blank/node_modules/castle-web-fonts/licenses/FONTS.md +64 -0
  111. package/kits/blank/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +95 -0
  112. package/kits/blank/node_modules/castle-web-fonts/package.json +47 -0
  113. package/kits/blank/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  114. package/kits/blank/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  115. package/kits/blank/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  116. package/kits/blank/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  117. package/kits/blank/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  118. package/kits/blank/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  119. package/kits/blank/node_modules/castle-web-fonts/woff2/SOURCE.txt +2 -0
  120. package/kits/blank/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  121. package/kits/blank/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  122. package/kits/blank/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  123. package/kits/physics-2d/castle.json +1 -1
  124. package/kits/physics-2d/editors/SceneEditor.jsx +2 -1
  125. package/kits/physics-2d/engine/blueprint.js +29 -28
  126. package/kits/physics-2d/package-lock.json +1 -6
  127. package/package.json +1 -1
@@ -0,0 +1,139 @@
1
+ import { graphql } from './api.js';
2
+ const SCOPE_ARGS = `
3
+ $deckId: ID!
4
+ $scope: CauldronStorageScope!
5
+ $subject: ID
6
+ `;
7
+ const OPERATIONS = {
8
+ get: {
9
+ field: 'cauldronStorageGet',
10
+ query: `query CastleDevStorageGet(${SCOPE_ARGS} $keys: [String!]!) {
11
+ cauldronStorageGet(deckId: $deckId, scope: $scope, subject: $subject, keys: $keys) {
12
+ key
13
+ value
14
+ }
15
+ }`,
16
+ },
17
+ list: {
18
+ field: 'cauldronStorageList',
19
+ query: `query CastleDevStorageList(${SCOPE_ARGS} $prefix: String, $limit: Int, $cursor: String) {
20
+ cauldronStorageList(
21
+ deckId: $deckId
22
+ scope: $scope
23
+ subject: $subject
24
+ prefix: $prefix
25
+ limit: $limit
26
+ cursor: $cursor
27
+ ) {
28
+ entries {
29
+ key
30
+ value
31
+ }
32
+ cursor
33
+ }
34
+ }`,
35
+ },
36
+ set: {
37
+ field: 'cauldronStorageSet',
38
+ query: `mutation CastleDevStorageSet(${SCOPE_ARGS} $entries: [CauldronStorageEntryInput!]!) {
39
+ cauldronStorageSet(
40
+ deckId: $deckId
41
+ scope: $scope
42
+ subject: $subject
43
+ entries: $entries
44
+ asServer: true
45
+ ) {
46
+ rowCount
47
+ byteCount
48
+ }
49
+ }`,
50
+ },
51
+ delete: {
52
+ field: 'cauldronStorageDelete',
53
+ query: `mutation CastleDevStorageDelete(${SCOPE_ARGS} $keys: [String!]!) {
54
+ cauldronStorageDelete(
55
+ deckId: $deckId
56
+ scope: $scope
57
+ subject: $subject
58
+ keys: $keys
59
+ asServer: true
60
+ ) {
61
+ rowCount
62
+ byteCount
63
+ }
64
+ }`,
65
+ },
66
+ increment: {
67
+ field: 'cauldronStorageIncrement',
68
+ query: `mutation CastleDevStorageIncrement(${SCOPE_ARGS} $key: String!, $delta: Float!) {
69
+ cauldronStorageIncrement(
70
+ deckId: $deckId
71
+ scope: $scope
72
+ subject: $subject
73
+ key: $key
74
+ delta: $delta
75
+ asServer: true
76
+ )
77
+ }`,
78
+ },
79
+ boardSubmit: {
80
+ field: 'cauldronStorageBoardSubmit',
81
+ query: `mutation CastleDevStorageBoardSubmit($deckId: ID!, $board: String!, $subject: ID, $score: Float!) {
82
+ cauldronStorageBoardSubmit(
83
+ deckId: $deckId
84
+ board: $board
85
+ subject: $subject
86
+ score: $score
87
+ asServer: true
88
+ ) {
89
+ subject
90
+ score
91
+ updatedAt
92
+ }
93
+ }`,
94
+ },
95
+ boardTop: {
96
+ field: 'cauldronStorageBoardTop',
97
+ query: `query CastleDevStorageBoardTop($deckId: ID!, $board: String!, $limit: Int) {
98
+ cauldronStorageBoardTop(deckId: $deckId, board: $board, limit: $limit) {
99
+ subject
100
+ score
101
+ updatedAt
102
+ }
103
+ }`,
104
+ },
105
+ boardGet: {
106
+ field: 'cauldronStorageBoardGet',
107
+ query: `query CastleDevStorageBoardGet($deckId: ID!, $board: String!, $subject: ID) {
108
+ cauldronStorageBoardGet(deckId: $deckId, board: $board, subject: $subject) {
109
+ subject
110
+ score
111
+ updatedAt
112
+ }
113
+ }`,
114
+ },
115
+ };
116
+ export async function runDevStorageOperation(deckId, op, args) {
117
+ const operation = OPERATIONS[op];
118
+ if (!operation) {
119
+ return failure('CAULDRON_STORAGE_INVALID_ARGUMENT', `unknown storage operation ${op}`);
120
+ }
121
+ if (!deckId || deckId === 'dev') {
122
+ return failure('CAULDRON_STORAGE_UNAVAILABLE', 'Storage needs a published deck. Run `castle-web save-deck` first, then restart serve.');
123
+ }
124
+ try {
125
+ const response = await graphql(operation.query, { ...args, deckId });
126
+ const error = response.errors?.[0];
127
+ if (error) {
128
+ const code = error.extensions?.code;
129
+ return failure(typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE', error.message ?? 'storage request failed');
130
+ }
131
+ return { ok: true, value: response.data?.[operation.field] ?? null };
132
+ }
133
+ catch (error) {
134
+ return failure('CAULDRON_STORAGE_UNAVAILABLE', error instanceof Error ? error.message : 'storage request failed');
135
+ }
136
+ }
137
+ function failure(code, message) {
138
+ return { ok: false, error: { code, message } };
139
+ }
package/dist/forks.js CHANGED
@@ -150,7 +150,7 @@ export function listOwnForks(deckDir) {
150
150
  return out.sort();
151
151
  }
152
152
  function writeForkRecord(deckDir, alias, inner, record) {
153
- const existing = (readCastleJson(deckDir) ?? {});
153
+ const existing = readCastleJson(deckDir) ?? {};
154
154
  const pins = { ...(existing.imports ?? {}) };
155
155
  const pin = pins[alias];
156
156
  if (!pin)
package/dist/ide.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import * as http from 'http';
2
2
  import { Duplex } from 'stream';
3
- import { type RawData } from 'ws';
4
3
  import { COVER_FILE } from './localPaths.js';
5
4
  export declare const IDE_ASSET_PREFIX = "/__castle/ide/";
6
5
  export declare const PTY_WS_PATH = "/__castle/pty";
@@ -10,7 +9,6 @@ export declare const FAVICON_LINK_TAGS: string;
10
9
  export declare const FILES_API_PREFIX = "/__castle/files/";
11
10
  export declare const COVER_API_PATH = "/__castle/cover";
12
11
  export { COVER_FILE };
13
- export declare function rawDataToString(data: RawData): string;
14
12
  export interface IdeServer {
15
13
  /** Serve the IDE page + its static assets. Returns true if it handled the request. */
16
14
  handleHttpRequest(req: http.IncomingMessage, res: http.ServerResponse, reqPath: string): boolean;
package/dist/ide.js CHANGED
@@ -16,6 +16,7 @@ import { isSameOriginUpgrade } from './wsOrigin.js';
16
16
  import headlessPkg from '@xterm/headless';
17
17
  import { SerializeAddon } from '@xterm/addon-serialize';
18
18
  import { WebSocketServer } from 'ws';
19
+ import { rawDataToString } from './rawData.js';
19
20
  import { IMPORTS_DIR, importStatuses, updateImport } from './imports.js';
20
21
  import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
21
22
  import { ensureVisibleGlob, ensureVisiblePath } from './castleJson.js';
@@ -966,13 +967,6 @@ function clampSize(value, fallback) {
966
967
  return fallback;
967
968
  return Math.max(2, Math.min(1000, Math.floor(n)));
968
969
  }
969
- export function rawDataToString(data) {
970
- if (Array.isArray(data))
971
- return Buffer.concat(data).toString('utf8');
972
- if (Buffer.isBuffer(data))
973
- return data.toString('utf8');
974
- return Buffer.from(new Uint8Array(data)).toString('utf8');
975
- }
976
970
  function send(socket, body) {
977
971
  if (socket.readyState === socket.OPEN)
978
972
  socket.send(JSON.stringify(body));
package/dist/imports.js CHANGED
@@ -389,6 +389,11 @@ function backupImport(deckDir, alias) {
389
389
  }
390
390
  fs.mkdirSync(path.dirname(dest), { recursive: true });
391
391
  fs.cpSync(src, dest, { recursive: true, verbatimSymlinks: true });
392
+ // The copy comes out locked, because the import it was taken from is. Unlock
393
+ // it: the pin below is written INTO it, and a read-only directory refuses
394
+ // that -- which failed the whole update, backup included, rather than the one
395
+ // write.
396
+ unlockImportTree(dest);
392
397
  const pin = (readCastleJson(deckDir)?.imports ?? {})[alias];
393
398
  if (pin) {
394
399
  fs.writeFileSync(path.join(dest, '.castle-import-pin.json'), JSON.stringify(pin, null, 2), 'utf-8');
package/dist/init.js CHANGED
@@ -55,7 +55,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
55
55
  // Registry version of castle-web-sdk to inject when scaffolding from a
56
56
  // globally-installed castle-web (not from inside the workspace). Bumped
57
57
  // alongside cli/sdk version bumps.
58
- const PUBLISHED_SDK_VERSION = '0.4.25';
58
+ const PUBLISHED_SDK_VERSION = '0.4.26';
59
59
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
60
60
  // face can ship without a cli release, and a caret range means an existing
61
61
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -200,10 +200,11 @@ const COMMON_SECTIONS = `## Imports are read-only
200
200
  onMessage(session, player, data) {}, // data is what the client sent, already parsed
201
201
  onTick(session, dtSeconds) {}, // only when castle.json sets server.tickRate > 0
202
202
  onReplaced(session) {}, // you published a new version; this session keeps the old one
203
+ async onShutdown(session) {}, // the session is ending; awaited, so a save here lands
203
204
  };
204
205
  \`\`\`
205
206
 
206
- \`session\` gives you \`send(playerId, data)\`, \`broadcast(data, { except })\`, \`disconnect(playerId, reason)\`, \`players\`, \`sessionId\`, \`deckId\`, and \`mode\`.
207
+ \`session\` gives you \`send(playerId, data)\`, \`broadcast(data, { except })\`, \`disconnect(playerId, reason)\`, \`players\`, \`sessionId\`, \`deckId\`, \`mode\`, and \`storage\`.
207
208
  - **Player identity comes from Castle, not from the client.** The \`player\` passed to your callbacks is authenticated by the platform, so a client cannot claim to be someone else by putting a name in a message. Trust \`player.userId\`; never trust identity inside \`data\`.
208
209
  - **The server is authoritative — put the rules there.** Deck code runs on the player's phone and can be modified, so validate every move on the server and send back state for clients to render. \`playerId\` identifies a connection (stable across a reconnect) while \`userId\` identifies the account, and one account can be in a session twice from two tabs.
209
210
  - **The client joins with \`Multiplayer.join\`:**
@@ -219,7 +220,18 @@ const COMMON_SECTIONS = `## Imports are read-only
219
220
 
220
221
  \`named\` puts everyone passing the same \`key\` in one session, which is how you build room codes and invite links. \`public\` drops a player into a shared session for the deck; \`party\` uses the Castle party they are already in.
221
222
  - **Always handle \`conn.isSolo\`.** When a player cannot join — signed out, blocked, private deck, or no capacity free — the SDK returns a working single-player connection instead of throwing. Keep the deck playable on its own rather than gating the whole game behind other people showing up.
222
- - **What the server may and may not do.** Roughly 128MB of memory, no filesystem that survives, and **no network access at all**: no \`fetch\`, no database, no third-party API. Keep state in memory and send it to clients. A session ends once its last player leaves and nothing persists between sessions, so use \`sharedDeckStorage\` for anything that must outlive one.
223
+ - **What the server may and may not do.** Roughly 128MB of memory, no filesystem that survives, and **no network access at all**: no \`fetch\`, no database, no third-party API. Keep state in memory and send it to clients. A session ends once its last player leaves and its memory goes with it.
224
+ - **\`session.storage\` is what outlives a session**, and it is the same store the deck's clients see through \`Store\`:
225
+
226
+ \`\`\`js
227
+ const { wins = 0 } = await session.storage.deck.get(['wins']);
228
+ await session.storage.deck.set({ wins: wins + 1 });
229
+ await session.storage.user(player.userId).set({ lastSeen: Date.now() });
230
+ await session.storage.board('high').submit(player.userId, score);
231
+ \`\`\`
232
+
233
+ Publishing a server takes ownership of \`deck\` scope: from then on clients read that data but no longer write it, which is what lets you keep authoritative state players cannot forge. A server can write any player's public bucket and submit any player's score, so name the player — there is no \`storage.me\`. It can never read \`private\` storage, not even for its own players.
234
+ - **Save as things change, not only at the end.** \`onShutdown\` is awaited and a save made there does land, but it only runs on a clean stop: an out-of-memory kill or a host failing sends no shutdown at all. Treat it as the last chance rather than the plan.
223
235
  - **Limits worth designing around.** Client→server messages are capped at 16 KB and about 30 per second; server→client messages are capped at 64 KB. These limits apply to both JSON and binary frames and are measured on the frame, so a binary frame's one-byte protocol tag leaves you one byte under the cap for payload. Sending 20–30 updates per second means sending deltas rather than whole-world snapshots, and every player's phone pays for whatever you broadcast.
224
236
  - **Binary messages are opt-in per payload.** Pass any typed array, \`DataView\`, or \`ArrayBuffer\` to client \`send\`, server \`send\`, or server \`broadcast\` to send its raw bytes. \`onMessage\` always receives those bytes as a \`Uint8Array\`, while every other payload continues to use JSON. Reconstruct another view type such as \`Float32Array\` on receipt; multi-byte values use the sender platform's byte order.
225
237
  - **Test multiplayer locally with no setup.** \`castle-web serve\` runs your server file alongside the deck; open the play URL in two tabs and they share a session. Editing anything under \`server/\` restarts it and clients reconnect, so you exercise your reconnect path constantly. Server \`console.log\` goes to the serve's logs, not the browser console.
@@ -0,0 +1,2 @@
1
+ import type { RawData } from 'ws';
2
+ export declare function rawDataToString(data: RawData): string;
@@ -0,0 +1,10 @@
1
+ // A `ws` text frame arrives as a Buffer, a Buffer[] or an ArrayBuffer, and only
2
+ // the first two stringify to their contents -- an ArrayBuffer would decode as
3
+ // "[object ArrayBuffer]". Every text protocol in here goes through this.
4
+ export function rawDataToString(data) {
5
+ if (Array.isArray(data))
6
+ return Buffer.concat(data).toString('utf8');
7
+ if (Buffer.isBuffer(data))
8
+ return data.toString('utf8');
9
+ return Buffer.from(new Uint8Array(data)).toString('utf8');
10
+ }
package/dist/serve.js CHANGED
@@ -527,6 +527,7 @@ const BRIDGED_CONTENT_MESSAGES = new Set([
527
527
  'log',
528
528
  'screenshot_response',
529
529
  'write_file',
530
+ 'rename_file',
530
531
  'castle_command',
531
532
  ]);
532
533
  const LEGACY_CONTENT_MESSAGES = new Set([...BRIDGED_CONTENT_MESSAGES, 'ping']);
@@ -631,6 +632,9 @@ export async function serve(dir, options = {}) {
631
632
  // dedup above normally returns before here, but an explicit --port/--host
632
633
  // asks for a second serve, and a second serve is not a reason to replace
633
634
  // files under the first one's session.
635
+ //
636
+ // Also skipped when CASTLE_NO_AUTO_UPDATE is set (local kit development:
637
+ // keep hand-synced imports/ instead of pulling published kits).
634
638
  if (!existingServe(projectDir)) {
635
639
  // A failure to check must never keep the deck from opening.
636
640
  await autoUpdateImports(projectDir).catch((e) => {
@@ -1245,6 +1249,23 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1245
1249
  ...response,
1246
1250
  }));
1247
1251
  }
1252
+ if (msg.type === 'rename_file') {
1253
+ if ((bridgeRole ?? legacyRole) === 'play') {
1254
+ ws.send(JSON.stringify({
1255
+ type: 'rename_file_response',
1256
+ requestId: msg.requestId,
1257
+ ok: false,
1258
+ error: 'Play frames cannot rename deck files.',
1259
+ }));
1260
+ return;
1261
+ }
1262
+ const response = renameProjectFile(projectDir, msg.from, msg.to);
1263
+ ws.send(JSON.stringify({
1264
+ type: 'rename_file_response',
1265
+ requestId: msg.requestId,
1266
+ ...response,
1267
+ }));
1268
+ }
1248
1269
  // SDK command from a locally-served deck. The dev server is the host:
1249
1270
  // it runs the command via the SDK host executor with the CLI's login
1250
1271
  // token, then replies to just this socket. See castle-web-sdk's
@@ -1352,3 +1373,80 @@ function writeProjectFile(projectDir, requestedPath, contents) {
1352
1373
  return { ok: false, error: `Could not write ${requestedPath}: ${message}` };
1353
1374
  }
1354
1375
  }
1376
+ // Resolve a deck-relative path for a mutating op (write/rename). Same guards as
1377
+ // `writeProjectFile`: no traversal, no protected dirs, imports only via an own
1378
+ // fork. Returns the absolute target plus the deck-relative POSIX path clients
1379
+ // keep using.
1380
+ function resolveMutableProjectPath(projectDir, requestedPath) {
1381
+ if (typeof requestedPath !== 'string' || requestedPath.trim() === '') {
1382
+ return { ok: false, error: 'Missing file path.' };
1383
+ }
1384
+ const normalized = path.normalize(requestedPath.replace(/\\/g, '/'));
1385
+ if (normalized === '.') {
1386
+ return { ok: false, error: 'Missing file path.' };
1387
+ }
1388
+ if (path.isAbsolute(normalized) ||
1389
+ normalized === '..' ||
1390
+ normalized.startsWith(`..${path.sep}`)) {
1391
+ return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
1392
+ }
1393
+ const parts = normalized.split(path.sep);
1394
+ if (parts.includes('.git') || parts.includes('.castle') || parts.includes('node_modules')) {
1395
+ return { ok: false, error: `Refusing to write protected deck path: ${requestedPath}` };
1396
+ }
1397
+ const filepath = path.resolve(projectDir, normalized);
1398
+ const relative = path.relative(projectDir, filepath);
1399
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
1400
+ return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
1401
+ }
1402
+ const relPosix = relative.split(path.sep).join('/');
1403
+ if (relPosix === IMPORTS_DIR || relPosix.startsWith(`${IMPORTS_DIR}/`)) {
1404
+ const fork = ownForkFile(projectDir, relPosix);
1405
+ if (!fork) {
1406
+ return {
1407
+ ok: false,
1408
+ error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
1409
+ };
1410
+ }
1411
+ return { ok: true, abs: fork, rel: relPosix };
1412
+ }
1413
+ if (relPosix === FORKS_DIR || relPosix.startsWith(`${FORKS_DIR}/`)) {
1414
+ return { ok: false, error: `Protected deck path: ${requestedPath}` };
1415
+ }
1416
+ return { ok: true, abs: filepath, rel: relPosix };
1417
+ }
1418
+ function isSameProjectFile(a, b) {
1419
+ try {
1420
+ const sa = fs.statSync(a);
1421
+ const sb = fs.statSync(b);
1422
+ return sa.ino === sb.ino && sa.dev === sb.dev;
1423
+ }
1424
+ catch {
1425
+ return false;
1426
+ }
1427
+ }
1428
+ // Bridge counterpart of the HTTP files/rename handler. Same collision and
1429
+ // import/fork rules; returns a LocalResponse-shaped result for the SDK.
1430
+ function renameProjectFile(projectDir, fromPath, toPath) {
1431
+ const from = resolveMutableProjectPath(projectDir, fromPath);
1432
+ if (!from.ok)
1433
+ return from;
1434
+ const to = resolveMutableProjectPath(projectDir, toPath);
1435
+ if (!to.ok)
1436
+ return to;
1437
+ if (!fs.existsSync(from.abs)) {
1438
+ return { ok: false, error: `Not found: ${from.rel}` };
1439
+ }
1440
+ if (from.abs !== to.abs && fs.existsSync(to.abs) && !isSameProjectFile(from.abs, to.abs)) {
1441
+ return { ok: false, error: `Already exists: ${to.rel}` };
1442
+ }
1443
+ try {
1444
+ fs.mkdirSync(path.dirname(to.abs), { recursive: true });
1445
+ fs.renameSync(from.abs, to.abs);
1446
+ return { ok: true, path: to.rel };
1447
+ }
1448
+ catch (error) {
1449
+ const message = error instanceof Error ? error.message : String(error);
1450
+ return { ok: false, error: `Could not rename ${from.rel}: ${message}` };
1451
+ }
1452
+ }