castle-web-cli 0.4.152 → 0.4.153

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 (98) hide show
  1. package/dist/castle-host/host.js +11 -3
  2. package/dist/castleJson.d.ts +1 -0
  3. package/dist/castleJson.js +14 -0
  4. package/dist/ide.js +4 -0
  5. package/dist/imports.js +18 -12
  6. package/dist/init.js +28 -12
  7. package/dist/platformDoc.js +68 -0
  8. package/dist/save-deck.js +14 -9
  9. package/dist/serve.js +24 -6
  10. package/dist/serveSecurity.d.ts +2 -0
  11. package/dist/serveSecurity.js +7 -4
  12. package/dist/shell/assets/{index-Dlhc3eZW.js → index-DsDkYFvP.js} +2 -2
  13. package/dist/shell/index.html +1 -1
  14. package/kits/blank/castle.json +1 -1
  15. package/kits/blank/node_modules/.package-lock.json +13 -0
  16. package/kits/blank/node_modules/castle-web-fonts/README.md +114 -0
  17. package/kits/blank/node_modules/castle-web-fonts/dist/catalog.d.ts +18 -0
  18. package/kits/blank/node_modules/castle-web-fonts/dist/catalog.js +142 -0
  19. package/kits/blank/node_modules/castle-web-fonts/dist/face.d.ts +1 -0
  20. package/kits/blank/node_modules/castle-web-fonts/dist/face.js +52 -0
  21. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +3 -0
  22. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.js +10 -0
  23. package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +3 -0
  24. package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +10 -0
  25. package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +3 -0
  26. package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.js +10 -0
  27. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +3 -0
  28. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.js +10 -0
  29. package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +3 -0
  30. package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +10 -0
  31. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +3 -0
  32. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +10 -0
  33. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +3 -0
  34. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.js +10 -0
  35. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +3 -0
  36. package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.js +10 -0
  37. package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +3 -0
  38. package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.js +10 -0
  39. package/kits/blank/node_modules/castle-web-fonts/dist/index.d.ts +16 -0
  40. package/kits/blank/node_modules/castle-web-fonts/dist/index.js +15 -0
  41. package/kits/blank/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +393 -0
  42. package/kits/blank/node_modules/castle-web-fonts/licenses/FONTS.md +64 -0
  43. package/kits/blank/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +95 -0
  44. package/kits/blank/node_modules/castle-web-fonts/package.json +47 -0
  45. package/kits/blank/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  46. package/kits/blank/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  47. package/kits/blank/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  48. package/kits/blank/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  49. package/kits/blank/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  50. package/kits/blank/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  51. package/kits/blank/node_modules/castle-web-fonts/woff2/SOURCE.txt +2 -0
  52. package/kits/blank/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  53. package/kits/blank/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  54. package/kits/blank/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  55. package/kits/blank/package-lock.json +10 -1
  56. package/kits/blank/package.json +3 -1
  57. package/kits/physics-2d/CLAUDE.md +158 -40
  58. package/kits/physics-2d/castle.json +3 -2
  59. package/kits/physics-2d/editors/SingleEditor.jsx +52 -19
  60. package/kits/physics-2d/editors/StyleEditor.jsx +139 -40
  61. package/kits/physics-2d/editors/deckFont.js +88 -0
  62. package/kits/physics-2d/editors/fontPreview.js +66 -0
  63. package/kits/physics-2d/editors/styleEditor.module.css +30 -3
  64. package/kits/physics-2d/editors/styleTheme.js +13 -2
  65. package/kits/physics-2d/engine/ScenePlayer.jsx +17 -2
  66. package/kits/physics-2d/engine/SceneUI.jsx +8 -0
  67. package/kits/physics-2d/engine/files.js +20 -9
  68. package/kits/physics-2d/engine/fonts.js +79 -0
  69. package/kits/physics-2d/engine/scene.js +6 -0
  70. package/kits/physics-2d/fonts.generated.js +9 -0
  71. package/kits/physics-2d/main.jsx +11 -0
  72. package/kits/physics-2d/package-lock.json +8 -1
  73. package/kits/physics-2d/package.json +1 -0
  74. package/kits/physics-2d/theme.style +2 -1
  75. package/kits/physics-3d/castle.json +1 -1
  76. package/kits/physics-3d/engine3d/PxModelEditor.jsx +3 -4
  77. package/kits/physics-3d/engine3d/Scene3DEditor.jsx +12 -8
  78. package/kits/physics-3d/engine3d/editorChrome.jsx +11 -6
  79. package/kits/physics-3d/engine3d/modelFiles.js +4 -5
  80. package/kits/physics-3d/package-lock.json +8 -1
  81. package/kits/physics-3d/package.json +1 -0
  82. package/kits/tabletop/.prettierrc +8 -0
  83. package/kits/tabletop/CLAUDE.md +309 -0
  84. package/kits/tabletop/castle.json +34 -0
  85. package/kits/tabletop/index.html +20 -0
  86. package/kits/tabletop/main.jsx +8 -0
  87. package/kits/tabletop/package-lock.json +341 -0
  88. package/kits/tabletop/package.json +29 -0
  89. package/kits/tabletop/room.js +269 -0
  90. package/kits/tabletop/testing.js +569 -0
  91. package/package.json +1 -1
  92. package/kits/blank/.castle/agent/children.json +0 -1
  93. package/kits/blank/.castle/agent/messages.json +0 -9
  94. package/kits/blank/.castle/agent/pending-sends.json +0 -1
  95. package/kits/blank/.castle/agent/tasks/index.md +0 -2
  96. package/kits/blank/.castle/docs/platform.md +0 -36
  97. package/kits/blank/node_modules/.vite/deps/_metadata.json +0 -8
  98. package/kits/blank/node_modules/.vite/deps/package.json +0 -3
@@ -128,7 +128,11 @@ function runCommand(ctx, command, params, caps) {
128
128
  async function multiplayerGetSession(ctx, params, caps) {
129
129
  const request = multiplayerSessionRequest(params);
130
130
  const deckId = requireDeckId(ctx, "multiplayer.getSession");
131
- const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode: request.mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
131
+ // Which shared session a play belongs to is the host's call, not the deck's,
132
+ // the way `shared.cpp` reads the party off the engine rather than the scene.
133
+ // A play that arrived through a party stays inside it; otherwise public.
134
+ const mode = request.mode === "public" && ctx.partyId ? "party" : request.mode;
135
+ const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
132
136
  return multiplayerSessionResult(data.getCauldronMultiplayerSession);
133
137
  }
134
138
  function multiplayerSessionRequest(params) {
@@ -303,7 +307,11 @@ async function sharedDeckStorageLoad(ctx, params, gql) {
303
307
  // 'user' read: an explicit userId targets another player's public bucket;
304
308
  // otherwise the current player's. 'deck' scope ignores userId.
305
309
  const userId = scope === "user" ? asOptionalString(params.userId) ?? ctx.userId : null;
306
- const data = await graphql(gql, SHARED_DECK_STORAGE_QUERY, { deckId, sessionId: ctx.sessionId, userId, keys: asKeys(params.keys) }, "sharedDeckStorage.load");
310
+ const data = await graphql(gql, SHARED_DECK_STORAGE_QUERY,
311
+ // No sessionId: a play session is not a shared world. Sending one makes the
312
+ // key per-play, so a deck-scoped read finds nothing in play while the
313
+ // editor, which has no session, looks right.
314
+ { deckId, sessionId: null, userId, keys: asKeys(params.keys) }, "sharedDeckStorage.load");
307
315
  return { blob: data.sharedDeckStorage ?? {} };
308
316
  }
309
317
  async function sharedDeckStorageUpdate(ctx, params, gql) {
@@ -312,7 +320,7 @@ async function sharedDeckStorageUpdate(ctx, params, gql) {
312
320
  // 'user'-scope writes are forced to the current player — the deck cannot
313
321
  // write another player's bucket.
314
322
  const userId = scope === "user" ? requireUserId(ctx, "sharedDeckStorage.update") : null;
315
- await graphql(gql, UPDATE_SHARED_DECK_STORAGE_MUTATION, { deckId, sessionId: ctx.sessionId, userId, updates: asUpdates(params.updates) }, "sharedDeckStorage.update");
323
+ await graphql(gql, UPDATE_SHARED_DECK_STORAGE_MUTATION, { deckId, sessionId: null, userId, updates: asUpdates(params.updates) }, "sharedDeckStorage.update");
316
324
  return { ok: true };
317
325
  }
318
326
  async function leaderboardFetch(ctx, params, caps) {
@@ -1,3 +1,4 @@
1
+ export declare const STARTER_STYLE_FILES: string[];
1
2
  export declare const IMPORTS_DIR = "imports";
2
3
  export interface DeckImport {
3
4
  deckId?: string;
@@ -5,6 +5,20 @@ import picomatch from 'picomatch';
5
5
  // module with no imports of its own, because both the import machinery and the
6
6
  // fork overlay need it and importing it from either of those would close a
7
7
  // cycle.
8
+ // Root-level style files a kit ships as a deck's starting point, seeded into a
9
+ // deck at scaffold (init.ts `writeStarterTheme`) and when an import newly brings
10
+ // them (imports.ts `seedKitTheme`).
11
+ //
12
+ // Naming kit files in cli/ is the standing exception to "nothing here hardcodes
13
+ // a kit's vocabulary": a file the DECK owns but the kit authors has to be copied
14
+ // out by someone, and only the CLI is there at scaffold time. Keep the list
15
+ // short, and to inert data at the deck root.
16
+ //
17
+ // They move TOGETHER, which is why this is a list and not one filename:
18
+ // `theme.style` names the deck's font, `fonts.generated.js` is what carries that
19
+ // face's bytes into the bundle, and a deck given the first without the second
20
+ // renders in the fallback while claiming otherwise.
21
+ export const STARTER_STYLE_FILES = ['theme.style', 'fonts.generated.js'];
8
22
  export const IMPORTS_DIR = 'imports';
9
23
  export const DEFAULT_STARTER_SCENE = 'scenes/main.scene';
10
24
  export const DEFAULT_SERVER_TICK_RATE = 20;
package/dist/ide.js CHANGED
@@ -777,6 +777,10 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
777
777
  try {
778
778
  await updateImport(deckDir, { alias: body.alias });
779
779
  sendJson(res, 200, { ok: true, alias: body.alias });
780
+ // An import is code, and updating it can delete a module the shell
781
+ // still holds, so this needs the same invalidate-then-reload a version
782
+ // restore gets. After the response: the panel shouldn't wait on it.
783
+ setImmediate(() => restart?.());
780
784
  }
781
785
  catch (e) {
782
786
  sendJson(res, 500, { error: e instanceof Error ? e.message : String(e) });
package/dist/imports.js CHANGED
@@ -6,7 +6,7 @@ import { runTar } from './save-deck.js';
6
6
  import { normalizeDeckPackageJson } from './normalize.js';
7
7
  import { getKitsDir } from './localPaths.js';
8
8
  import { writePlatformDocs } from './platformDoc.js';
9
- import { ensureVisibleGlob, IMPORTS_DIR, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
9
+ import { ensureVisibleGlob, IMPORTS_DIR, STARTER_STYLE_FILES, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
10
10
  // Adding another deck as a dependency (`castle-web add-import`; removing one is a
11
11
  // later command). Deliberately NOT `get-deck`: that one
12
12
  // replaces THIS deck's own source from the server (and carries guards for the
@@ -626,19 +626,25 @@ function seedKitTheme(deckDir, alias, log) {
626
626
  const main = tryReadCastleJson(importDir)?.main;
627
627
  if (typeof main !== 'string' || !main.trim())
628
628
  return;
629
- const src = path.join(importDir, 'theme.style');
630
- const dest = path.join(deckDir, 'theme.style');
631
- if (!fs.existsSync(src) || fs.existsSync(dest))
632
- return;
633
- try {
634
- fs.copyFileSync(src, dest);
629
+ const seeded = [];
630
+ for (const name of STARTER_STYLE_FILES) {
631
+ const src = path.join(importDir, name);
632
+ const dest = path.join(deckDir, name);
633
+ if (!fs.existsSync(src) || fs.existsSync(dest))
634
+ continue;
635
+ try {
636
+ fs.copyFileSync(src, dest);
637
+ }
638
+ catch (e) {
639
+ console.warn(`Could not seed ${name} from ${alias}: ${e instanceof Error ? e.message : String(e)}`);
640
+ continue;
641
+ }
642
+ ensureVisibleGlob(deckDir, name, name);
643
+ seeded.push(name);
635
644
  }
636
- catch (e) {
637
- console.warn(`Could not seed theme.style from ${alias}: ${e instanceof Error ? e.message : String(e)}`);
645
+ if (seeded.length === 0)
638
646
  return;
639
- }
640
- ensureVisibleGlob(deckDir, 'theme.style', 'theme.style');
641
- log(`Seeded theme.style from ${alias} (new in this version; the deck's to edit)`);
647
+ log(`Seeded ${seeded.join(' + ')} from ${alias} (new in this version; the deck's to edit)`);
642
648
  }
643
649
  async function applyImportUpdate(deckDir, alias, update, source, log) {
644
650
  await placeImport(deckDir, alias, update.deckId, source, update.via);
package/dist/init.js CHANGED
@@ -2,7 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { CLAUDE_MD_PLATFORM_SECTION } from './platformDoc.js';
4
4
  import { installDeps } from './install.js';
5
- import { deckMainFile, deckStarterScene } from './castleJson.js';
5
+ import { deckMainFile, deckStarterScene, STARTER_STYLE_FILES } from './castleJson.js';
6
6
  import { addImportTo, IMPORTS_DIR, lockImportTree, restoreMissingImports, syncImportDependencies, } from './imports.js';
7
7
  import { discardParentSource, fetchParentSource, unpackParentSource, writeRemixIdentity, } from './remix.js';
8
8
  import { getCliEntryPath, getKitsDir, getSdkPackagePath, toPosixPath, } from './localPaths.js';
@@ -47,6 +47,14 @@ export const BARE_DOCS_KIT = 'blank';
47
47
  // globally-installed castle-web (not from inside the workspace). Bumped
48
48
  // alongside cli/sdk version bumps.
49
49
  const PUBLISHED_SDK_VERSION = '0.4.19';
50
+ // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
51
+ // face can ship without a cli release, and a caret range means an existing
52
+ // deck's next install picks it up. Nothing here has to move when it does.
53
+ // Every deck gets it, used or not -- the platform guide tells the agent to
54
+ // import a Castle face, and an import that fails to resolve makes that a lie.
55
+ // Costs a deck node_modules space and no bundle bytes: a deck inlines only the
56
+ // faces it names (see castle-web-fonts' own scripts/verify.mjs).
57
+ const FONTS_RANGE = '^1.0.0';
50
58
  // The account the first-party kits are (to be) published under, so a kit
51
59
  // imported from the CLI's copy is named the same as one fetched from the server.
52
60
  const KIT_AUTHOR = 'castle';
@@ -132,6 +140,7 @@ function makePackageJson(projectDir) {
132
140
  'save-deck': `${cliCommand} save-deck .`,
133
141
  },
134
142
  dependencies: {
143
+ 'castle-web-fonts': FONTS_RANGE,
135
144
  'castle-web-sdk': sdkRef,
136
145
  },
137
146
  };
@@ -290,18 +299,25 @@ export function writeStarterScene(projectDir, kitDir, alias) {
290
299
  fs.mkdirSync(path.join(projectDir, 'scenes'), { recursive: true });
291
300
  writeJsonFile(path.join(projectDir, 'scenes', 'main.scene'), rewrite(scene));
292
301
  }
293
- // A kit may ship a starter `theme.style` (deck-level styling, e.g. the color
294
- // palette). Like the starter scene, it is deck content: the engine reads it
295
- // from the DECK root, and it is the creator's to edit -- so it gets seeded once
296
- // at scaffold time rather than living read-only in the import. Copied verbatim
297
- // (its values are palette ids/hexes, never kit file paths, so no ref
298
- // rewriting). Exported for the same two scaffold paths as writeStarterScene.
302
+ // A kit may ship starter style files (deck-level styling: the color palette,
303
+ // the deck font). Like the starter scene, they are deck content: the engine
304
+ // reads them from the DECK root, and they are the creator's to edit -- so they
305
+ // get seeded once at scaffold time rather than living read-only in the import.
306
+ // Copied verbatim (their values are palette ids, hexes and font names, never
307
+ // kit file paths, so no ref rewriting). Exported for the same two scaffold paths
308
+ // as writeStarterScene.
309
+ //
310
+ // The set is STARTER_STYLE_FILES (castleJson.ts), which says why these two
311
+ // travel together: a deck given the record without the generated module renders
312
+ // in the fallback while claiming otherwise.
299
313
  export function writeStarterTheme(projectDir, kitDir) {
300
- const src = path.join(kitDir, 'theme.style');
301
- const dest = path.join(projectDir, 'theme.style');
302
- if (!fs.existsSync(src) || fs.existsSync(dest))
303
- return;
304
- fs.copyFileSync(src, dest);
314
+ for (const name of STARTER_STYLE_FILES) {
315
+ const src = path.join(kitDir, name);
316
+ const dest = path.join(projectDir, name);
317
+ if (!fs.existsSync(src) || fs.existsSync(dest))
318
+ continue;
319
+ fs.copyFileSync(src, dest);
320
+ }
305
321
  }
306
322
  function makeBareClaudeMd(alias) {
307
323
  return `# Castle deck (no kit)
@@ -143,6 +143,37 @@ const COMMON_SECTIONS = `## Imports are read-only
143
143
 
144
144
  - **Load static assets (drawings, audio, etc.) through the bundler — never runtime-\`fetch\` a loose file path.** Use a static \`import\`, \`import.meta.glob('./drawings/*.svg', { eager: true, import: 'default' })\`, or inline the asset directly. The dev serve happens to serve loose files over HTTP, so \`fetch('drawings/qb.svg')\` looks like it works locally — but \`save-deck\` bundles the whole deck into a single file, loose files are no longer served, and the fetch silently fails on every platform. Kit decks: use the kit's own drawing/asset-loading APIs instead of a raw \`fetch\`.
145
145
 
146
+ ## Fonts
147
+
148
+ - **A deck that renders text should reach for a Castle font first.** Castle ships the licensed faces from the Classic engine as web fonts, and every deck already has them installed. Import the ones you want by name and the bundler inlines those faces and no others:
149
+
150
+ \`\`\`js
151
+ import { installTektur } from 'castle-web-fonts';
152
+
153
+ installTektur(); // now: font-family: 'Tektur'
154
+ const family = await installTektur(); // resolves to 'Tektur', once it can be drawn with
155
+ \`\`\`
156
+
157
+ Choose the faces that fit what the deck IS -- there is no house default to fall back on, and any of the nine is a better answer than not choosing. Two or three is the common shape: one for body and UI, one display face for titles, sometimes a third for a specific effect.
158
+
159
+ | face | character | good for |
160
+ |---|---|---|
161
+ | \`DMSans\` | clean geometric sans, low contrast | body, UI, HUD |
162
+ | \`Piazzolla\` | sturdy text serif, readable at length | body text, narrative, prose-heavy decks |
163
+ | \`CourierPrime\` | monospace typewriter serif | code, terminals, typewriter effects |
164
+ | \`Tektur\` | condensed squarish techno | sci-fi, arcade, HUD numerals |
165
+ | \`Bore\` | very heavy wide grotesque | impact headlines, scores, big titles |
166
+ | \`Synco\` | light wide geometric, unusual joins | retro-modernist titles |
167
+ | \`Glacier\` | slanted condensed hand-cut italic | informal, energetic display |
168
+ | \`HelicoCentrica\` | blackletter-flavored roman, pointed serifs | medieval, fantasy, ornate |
169
+ | \`YatraOne\` | high-contrast brushy display (also Devanagari) | bold headlines, South Asian text |
170
+
171
+ Each face has one weight and one style, as in Classic; asking for bold or italic gets the browser's synthesized version.
172
+ - **Prefer these over \`system-ui\` or a webfont URL** when nothing says otherwise. A system stack renders as a different typeface on every device, and a font-CDN URL costs a network round trip and breaks offline -- where these are bundled into the deck and paint on the first frame. That is a default, not a rule: when someone names a face they want, or describes a look the nine don't reach, use what they asked for. Install it as a package so the bundler inlines it the same way -- \`@fontsource/<face>\`, and take its \`latin-\` entry point, since the plain one pulls every unicode subset (\`@fontsource/inter/400.css\` inlines 288 KB where \`latin-400.css\` inlines 72). Don't link a font CDN from the page.
173
+ - **Import the named export per face. Never build a lookup keyed by a font name** (\`FONTS[name]()\`, \`installers[theme.font]\`): no bundler can tell which key gets read, so that inlines all nine faces -- 495 KB -- into the deck. Faces run 12-90 KB each; two or three is normal, all nine is not. When the name has to come from data (a theme file, a saved setting), resolve it to a real import in a generated module rather than at runtime.
174
+ - **Drawing text to a canvas means waiting for the face first.** Canvas 2D does not trigger a font load, so \`ctx.font = '20px Piazzolla'\` before the face is ready silently falls back to the default -- and never repaints when the font lands, so it looks right after a warm reload and wrong on a cold first paint. \`await installPiazzolla()\` before the first frame. CSS needs no such care.
175
+ - If the deck is built on a kit that sets a deck font of its own, that is the deck's body/UI face already -- don't install a second face to do the same job. A display face on top of it is still an ordinary import. Its guide says which is which.
176
+
146
177
  ## Touch controls
147
178
 
148
179
  - **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch — direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics — a game with no directional movement should have no movement controls at all.
@@ -152,6 +183,43 @@ const COMMON_SECTIONS = `## Imports are read-only
152
183
  - **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, \`min()\`, \`clamp()\`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports \`CARD_RATIO\` (= 5 / 7) if you need the exact ratio.
153
184
  - **Hand-rolled \`<canvas>\` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times \`devicePixelRatio\` (e.g. \`canvas.width = rect.width * dpr\`), keep the CSS width/height as the layout size, and scale the 2D context (\`ctx.scale(dpr, dpr)\`) so drawing code stays in CSS units — re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.
154
185
  - Exception: deliberate pixel art wants a fixed low-resolution backing store with \`image-rendering: pixelated\` CSS instead — don't DPR-scale that; the crisp chunky look is the point.
186
+
187
+ ## Multiplayer
188
+
189
+ - **A deck becomes multiplayer by having a \`server/index.js\`** — no flag, no dashboard. The file's presence is the opt-in, and deleting it turns multiplayer off on the next \`save-deck\`. Castle runs that file as a real server process, one per session, shared by the players in it. Options live in \`castle.json\` under \`server\`: \`main\` (defaults to \`server/index.js\`), \`maxPlayers\` (max 24), and \`tickRate\` (max 30; 0, the default, means no tick).
190
+ - **The server module default-exports lifecycle callbacks**, each taking the session first:
191
+
192
+ \`\`\`js
193
+ export default {
194
+ onStart(session) {}, // once, before anyone joins
195
+ onPlayerJoin(session, player) {}, // player: { playerId, userId, username, isAnonymous }
196
+ onPlayerLeave(session, player) {},
197
+ onMessage(session, player, data) {}, // data is what the client sent, already parsed
198
+ onTick(session, dtSeconds) {}, // only when castle.json sets server.tickRate > 0
199
+ onReplaced(session) {}, // you published a new version; this session keeps the old one
200
+ };
201
+ \`\`\`
202
+
203
+ \`session\` gives you \`send(playerId, data)\`, \`broadcast(data, { except })\`, \`disconnect(playerId, reason)\`, \`players\`, \`sessionId\`, \`deckId\`, and \`mode\`.
204
+ - **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\`.
205
+ - **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.
206
+ - **The client joins with \`Multiplayer.join\`:**
207
+
208
+ \`\`\`js
209
+ import { Multiplayer } from 'castle-web-sdk';
210
+
211
+ const conn = await Multiplayer.join({ mode: 'named', key: 'lobby-1' });
212
+ conn.onMessage((data) => { /* from your server */ });
213
+ conn.onRoster(({ players, you }) => { /* who is here */ });
214
+ conn.send({ move: 'left' });
215
+ \`\`\`
216
+
217
+ \`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.
218
+ - **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.
219
+ - **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.
220
+ - **Limits worth designing around.** Messages from a client are capped at 16KB and about 30 per second; server broadcasts at 64KB. Sending 20–30 updates per second means sending deltas rather than whole-world snapshots, and every player's phone pays for whatever you broadcast.
221
+ - **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.
222
+ - **Publishing does not disturb games in progress.** \`save-deck\` bundles and publishes \`server/\`, but sessions already running keep the code they started with (they get \`onReplaced\`, so you can prompt players), and the next new session picks up the new version.
155
223
  `;
156
224
  export function platformGuide(deckDir) {
157
225
  return `${COMMON_SECTIONS.trimEnd()}
package/dist/save-deck.js CHANGED
@@ -202,15 +202,15 @@ async function captureAutomaticCover(projectDir) {
202
202
  return outPath;
203
203
  }
204
204
  async function uploadLocalCover(projectDir) {
205
- const captured = await captureAutomaticCover(projectDir);
206
- const coverPath = captured ?? path.join(projectDir, COVER_FILE);
207
- if (captured)
208
- console.log('Captured a cover from the running deck.');
209
- else if (fs.existsSync(coverPath))
210
- console.log('Using the cover captured in the editor.');
211
- if (!fs.existsSync(coverPath))
212
- return null;
213
205
  try {
206
+ const captured = await captureAutomaticCover(projectDir);
207
+ const coverPath = captured ?? path.join(projectDir, COVER_FILE);
208
+ if (captured)
209
+ console.log('Captured a cover from the running deck.');
210
+ else if (fs.existsSync(coverPath))
211
+ console.log('Using the cover captured in the editor.');
212
+ if (!fs.existsSync(coverPath))
213
+ return null;
214
214
  const base64 = fs.readFileSync(coverPath).toString('base64');
215
215
  const file = await api.uploadBase64(base64, COVER_FILE);
216
216
  return file?.fileId ?? null;
@@ -274,6 +274,11 @@ export async function saveDeck(dir, opts = {}) {
274
274
  const isNew = !castleJson;
275
275
  const cardId = castleJson?.cardId ?? nanoid(12);
276
276
  const deckId = castleJson?.deckId ?? nanoid(12);
277
+ // Capturing and uploading the cover depends only on the already-running serve. Start it as
278
+ // soon as the bundle has passed, while the independent scene upload is being authorized and
279
+ // transferred. The promise is deliberately non-throwing: a thumbnail must never make the
280
+ // content upload fail or create an unhandled rejection if that upload exits early.
281
+ const backgroundImageFileIdPromise = uploadLocalCover(projectDir);
277
282
  // Upload scene data to S3
278
283
  const configs = await api.createSceneDataUploadConfig([cardId]);
279
284
  if (!configs?.length) {
@@ -307,7 +312,7 @@ export async function saveDeck(dir, opts = {}) {
307
312
  deckInput.visibility = 'unlisted';
308
313
  if (opts.caption !== undefined)
309
314
  deckInput.caption = opts.caption;
310
- const backgroundImageFileId = await uploadLocalCover(projectDir);
315
+ const backgroundImageFileId = await backgroundImageFileIdPromise;
311
316
  try {
312
317
  const cardInput = {
313
318
  cardId,
package/dist/serve.js CHANGED
@@ -55,7 +55,7 @@ async function findFreePort(startPort) {
55
55
  }
56
56
  throw new Error(`No free port found starting from ${startPort}`);
57
57
  }
58
- function listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved) {
58
+ function listenLocalContentServer(bindHost, upstreamHost, upstreamPort, role, security, reserved) {
59
59
  const upstreamHeaders = (req) => ({
60
60
  ...req.headers,
61
61
  ...security.localContentProxyHeaders(role),
@@ -99,7 +99,7 @@ function listenLocalContentServer(upstreamHost, upstreamPort, role, security, re
99
99
  // of the cloud serve contract and must never occupy a future deck port by
100
100
  // convention. Retry the vanishingly rare case where port 0 selects the
101
101
  // main Vite port before Vite itself has bound it.
102
- server.listen(0, '127.0.0.1', () => {
102
+ server.listen(0, bindHost, () => {
103
103
  server.off('error', reject);
104
104
  const address = server.address();
105
105
  const port = typeof address === 'object' && address ? address.port : 0;
@@ -109,7 +109,7 @@ function listenLocalContentServer(upstreamHost, upstreamPort, role, security, re
109
109
  }
110
110
  if (reserved.has(port)) {
111
111
  server.close(() => {
112
- void listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved).then(resolve, reject);
112
+ void listenLocalContentServer(bindHost, upstreamHost, upstreamPort, role, security, reserved).then(resolve, reject);
113
113
  });
114
114
  return;
115
115
  }
@@ -135,6 +135,15 @@ function proxyViteClientUpgrade(req, socket, head, upstreamHost, upstreamPort, h
135
135
  socket.write(upstreamHead);
136
136
  if (head.length)
137
137
  upstreamSocket.write(head);
138
+ // A piped socket with no error handler takes the whole serve down when a
139
+ // client resets its connection -- a tab closing hard, or a script exiting
140
+ // mid-frame. Tear down the pair instead.
141
+ const drop = () => {
142
+ socket.destroy();
143
+ upstreamSocket.destroy();
144
+ };
145
+ socket.on('error', drop);
146
+ upstreamSocket.on('error', drop);
138
147
  socket.pipe(upstreamSocket).pipe(socket);
139
148
  });
140
149
  upstream.on('response', (response) => {
@@ -172,12 +181,12 @@ function isLegacyContentSocketUpgrade(req) {
172
181
  return false;
173
182
  }
174
183
  }
175
- async function startLocalContentServers(upstreamHost, upstreamPort, security, reserved) {
184
+ async function startLocalContentServers(bindHost, upstreamHost, upstreamPort, security, reserved) {
176
185
  const servers = [];
177
186
  const ports = {};
178
187
  try {
179
188
  for (const role of ['edit', 'play']) {
180
- const listening = await listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved);
189
+ const listening = await listenLocalContentServer(bindHost, upstreamHost, upstreamPort, role, security, reserved);
181
190
  servers.push(listening.server);
182
191
  ports[role] = listening.port;
183
192
  reserved.add(listening.port);
@@ -729,7 +738,16 @@ export async function serve(dir, options = {}) {
729
738
  : options.host === '::'
730
739
  ? '::1'
731
740
  : options.host;
732
- const localContentServers = await startLocalContentServers(upstreamHost, port, security, new Set([port]));
741
+ // Content origins follow --host: a serve bound to a tailnet/LAN address is
742
+ // being viewed from another device, where loopback is that device's own.
743
+ const contentBindHost = !options.host ||
744
+ options.host === 'localhost' ||
745
+ options.host === '0.0.0.0' ||
746
+ options.host === '::'
747
+ ? '127.0.0.1'
748
+ : options.host;
749
+ security.setLocalContentHost(contentBindHost);
750
+ const localContentServers = await startLocalContentServers(contentBindHost, upstreamHost, port, security, new Set([port]));
733
751
  process.on('exit', () => {
734
752
  for (const server of localContentServers)
735
753
  server.close();
@@ -20,8 +20,10 @@ export declare class ServeSecurity {
20
20
  private readonly serveNonce;
21
21
  private readonly tickets;
22
22
  private localContentPorts;
23
+ private localContentHost;
23
24
  constructor(publicPort: number, localContentPorts?: LocalContentPorts);
24
25
  setLocalContentPorts(ports: LocalContentPorts): void;
26
+ setLocalContentHost(host: string): void;
25
27
  authorizeHttp(req: http.IncomingMessage): boolean;
26
28
  rejectHttpAuth(res: http.ServerResponse): void;
27
29
  issueTicket(endpoint: SocketEndpoint): string;
@@ -59,6 +59,7 @@ export class ServeSecurity {
59
59
  serveNonce = base32Lower(randomBytes(8));
60
60
  tickets = new Map();
61
61
  localContentPorts;
62
+ localContentHost = '127.0.0.1';
62
63
  constructor(publicPort, localContentPorts) {
63
64
  this.publicPort = publicPort;
64
65
  this.localContentPorts = localContentPorts ?? null;
@@ -70,6 +71,10 @@ export class ServeSecurity {
70
71
  throw new Error('edit and play content ports must be distinct');
71
72
  this.localContentPorts = ports;
72
73
  }
74
+ // The host a browser should use to reach deck content; see contentBindHost.
75
+ setLocalContentHost(host) {
76
+ this.localContentHost = host;
77
+ }
73
78
  authorizeHttp(req) {
74
79
  const value = req.headers['x-castle-serve-token'];
75
80
  return typeof value === 'string' && safeEqual(value, this.serveToken);
@@ -239,7 +244,7 @@ window.fetch=function(input,init){
239
244
  const port = this.localContentPorts?.[role];
240
245
  if (!port)
241
246
  throw new Error('local content ports are not configured');
242
- return `http://127.0.0.1:${port}`;
247
+ return `http://${this.localContentHost}:${port}`;
243
248
  }
244
249
  /** A short-lived play URL for one shared-browser admission attempt. */
245
250
  browserContentOrigin(role = 'play') {
@@ -247,9 +252,7 @@ window.fetch=function(input,init){
247
252
  if (!sandboxId || !/^[a-z0-9]{14}$/.test(sandboxId))
248
253
  return null;
249
254
  const env = process.env.CASTLE_SANDBOX_ENV === 'staging' ? 'staging' : 'prod';
250
- const domain = env === 'staging'
251
- ? 'sandboxes-staging.castlexyz.com'
252
- : 'sandboxes.castlexyz.com';
255
+ const domain = env === 'staging' ? 'sandboxes-staging.castlexyz.com' : 'sandboxes.castlexyz.com';
253
256
  const expiresAtSeconds = Math.floor(Date.now() / 1000) + BROWSER_GRANT_SECONDS;
254
257
  return `https://${this.mintContentLabel(role, sandboxId, expiresAtSeconds)}.${domain}`;
255
258
  }