castle-web-cli 0.4.240 → 0.4.242

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 (42) hide show
  1. package/dist/bundle.d.ts +9 -1
  2. package/dist/bundle.js +214 -25
  3. package/dist/init.js +1 -1
  4. package/dist/multiplayerDoc.d.ts +1 -1
  5. package/dist/multiplayerDoc.js +2 -0
  6. package/dist/platformDoc.js +3 -3
  7. package/dist/playPagePolicy.js +7 -6
  8. package/dist/roomLogs.d.ts +1 -0
  9. package/dist/roomLogs.js +30 -6
  10. package/dist/save-deck.js +20 -3
  11. package/kits/base/castle.json +1 -1
  12. package/kits/base/sdk/README.md +7 -0
  13. package/kits/base/sdk/context.d.ts +5 -0
  14. package/kits/base/sdk/debugConsole.d.ts +1 -0
  15. package/kits/base/sdk/debugConsole.js +87 -14
  16. package/kits/base/sdk/runtime.js +5 -4
  17. package/kits/hub-game/code/client/chrome.js +8 -4
  18. package/kits/hub-game/code/client/padCues.js +11 -7
  19. package/kits/hub-game/code/client/padReadability.js +3 -3
  20. package/kits/hub-game/code/client/visibility.js +14 -4
  21. package/kits/hub-game/code/server/hub.js +146 -30
  22. package/kits/hub-game/code/server/players.js +6 -1
  23. package/kits/hub-game/code/server/standing.js +7 -3
  24. package/kits/hub-game/code/systems/hub.js +11 -3
  25. package/kits/hub-game/docs/contract.md +25 -4
  26. package/kits/hub-game/scripts/test-ballot.mjs +1 -1
  27. package/kits/hub-game/scripts/test-hub-trip.mjs +24 -0
  28. package/kits/hub-game/scripts/test-pad-cues.mjs +39 -0
  29. package/kits/hub-game/scripts/test-placeat-server.mjs +259 -6
  30. package/kits/hub-game/scripts/test-rehello.mjs +5 -3
  31. package/kits/hub-game/scripts/test-standing.mjs +135 -2
  32. package/kits/hub-game/scripts/test-stuck.mjs +5 -1
  33. package/kits/hub-game/scripts/test-visibility.mjs +54 -0
  34. package/kits/multiplayer-3d/castle.json +1 -1
  35. package/kits/multiplayer-3d/code/client/resumeGate.js +18 -1
  36. package/kits/multiplayer-3d/code/systems/multiplayer.js +41 -7
  37. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +226 -0
  38. package/kits/physics-3d/castle.json +1 -1
  39. package/kits/physics-3d/package.json +1 -1
  40. package/kits/physics-3d/scripts/test-coaxial-escape.mjs +176 -0
  41. package/kits/physics-3d/systems/physics3d.js +8 -0
  42. package/package.json +1 -1
package/dist/bundle.d.ts CHANGED
@@ -17,19 +17,27 @@ export interface ExternalMediaAsset {
17
17
  bytes: Buffer;
18
18
  /** The file it came from, relative to the deck where known, for messages. */
19
19
  source: string;
20
+ /** URLs of the assets this one names in its own bytes (a .gltf's buffers and textures). */
21
+ deps?: string[];
20
22
  }
21
23
  export declare class ExternalMedia {
22
24
  private readonly baseUrl;
23
25
  private readonly exclude;
24
26
  private readonly byUrl;
27
+ private readonly inlined;
25
28
  /** `exclude`: sha256s that stay inline (Ghost refused to store them). */
26
29
  constructor(baseUrl?: string, exclude?: ReadonlySet<string>);
27
30
  /** The deck build's two plugins: the loader (ahead of Vite's) and the late swap (ahead of InlineAssets). */
28
31
  plugin(): Plugin[];
29
32
  private loadedUrl;
33
+ private loadedGltf;
34
+ private rewriteGltf;
30
35
  private record;
31
36
  private urlFor;
32
- /** Every asset the finished page names (a module the build dropped names none). */
37
+ /**
38
+ * Every asset the finished page names (a module the build dropped names
39
+ * none), and each one those name in turn (a .gltf's buffers and textures).
40
+ */
33
41
  assetsIn(html: string): ExternalMediaAsset[];
34
42
  }
35
43
  export declare class InlineAssets {
package/dist/bundle.js CHANGED
@@ -44,12 +44,13 @@ const INLINE_ASSET_MIN_PAYLOAD = 1024;
44
44
  */
45
45
  const INLINE_ASSET_MAX_CHECKED_CODE = 10 * 1024 * 1024;
46
46
  // ---------------------------------------------------------------------------
47
- // Audio and video served by URL, on save.
47
+ // Audio, video, images and 3D models served by URL, on save.
48
48
  //
49
49
  // Inlining keeps a published deck one file, but a 30 MB .wav inlines to 40 MB
50
50
  // of base64, past Ghost's 50 MB scene cap with little else in the deck, and
51
51
  // rolldown holds that 40 MB string many times over (the 30 MB deck peaked at
52
- // 1.35 GB). So when save-deck asks, each audio or video file of
52
+ // 1.35 GB). So when save-deck asks, each audio, video, image (png, jpg, webp,
53
+ // gif) or 3D model (glb, gltf) file of
53
54
  // EXTERNAL_MEDIA_MIN_BYTES or more that Vite would inline is named by its URL
54
55
  // on Castle's CDN instead (`https://hosted.castle.games/cauldron-assets/
55
56
  // <sha256>.<ext>`, immutable, which save-deck stores before it publishes the
@@ -58,13 +59,24 @@ const INLINE_ASSET_MAX_CHECKED_CODE = 10 * 1024 * 1024;
58
59
  // Where InlineAssets swaps a payload for a stand-in that has to come back, the
59
60
  // URL here is the literal's true final value: the minifier may fold, alias or
60
61
  // compare it as it likes, so there is nothing to check. What changes is the
61
- // value itself. A deck that plays it (`new Audio(url)`, `video.src = url`,
62
- // `fetch(url)` then `decodeAudioData`) never notices; a deck that reads the
63
- // bytes out of the data: URI string itself would break. That is why this is
64
- // media only (the one kind a deck hands to a loader rather than inspects),
65
- // save only (the serve and `check` keep the data: URI), and only for the MIME
66
- // types Ghost stores. A Ghost that refuses a type (video, before it stores
67
- // video) or a file keeps that file inline; the save goes on.
62
+ // value itself. A deck that plays or loads it (`new Audio(url)`,
63
+ // `video.src = url`, `img.src = url`, a texture or glTF loader, `fetch(url)`)
64
+ // never notices; a deck that reads the bytes out of the data: URI string
65
+ // itself would break. That is why this is files a deck hands to a loader
66
+ // rather than inspects (never SVG, which decks also inline as markup), save
67
+ // only (the serve and `check` keep the data: URI), and only for the MIME types
68
+ // Ghost stores. A Ghost that refuses a type (images and models, before it
69
+ // stores them) or a file keeps that file inline; the save goes on.
70
+ //
71
+ // A .gltf names its buffers and textures by URI, usually relative to itself,
72
+ // which resolves against neither a data: URI nor the CDN's hash-named URL. So
73
+ // a .gltf imported with `?url` is rewritten first: each relative reference
74
+ // that is a file in the deck becomes that file's own CDN URL (an image of the
75
+ // minimum or more, uploaded beside it) or a data: URI (a .bin buffer, anything
76
+ // smaller, or a type Ghost does not store), and the rewritten file is what is
77
+ // uploaded, whatever its size, since it now carries the references. Excluded
78
+ // (Ghost refused it), the rewritten file goes inline with every reference a
79
+ // data: URI, which loads where the original never could.
68
80
  //
69
81
  // Two places, one rule. A media file imported plainly or with `?url` -- the
70
82
  // way nearly every deck imports one, globs included -- is loaded here, ahead
@@ -76,6 +88,10 @@ const INLINE_ASSET_MAX_CHECKED_CODE = 10 * 1024 * 1024;
76
88
  // own MIME and bytes give. An `?inline` import asked for a data: URI by name,
77
89
  // and keeps it; so does a file Ghost refused to store (`exclude`).
78
90
  //
91
+ // An <img> drawn into a WebGL texture or read back from a canvas (getImageData)
92
+ // taints it unless it loaded with CORS, which a data: URI never needed; the
93
+ // shim below sets CORS on one given an asset URL the same way as on a video.
94
+ //
79
95
  // A media element loads a cross-origin URL without CORS unless told to, and
80
96
  // Web Audio then hears silence from it (`createMediaElementSource`), where the
81
97
  // data: URI played; a video drawn into a WebGL texture taints it. The CDN
@@ -104,10 +120,17 @@ export const EXTERNAL_MEDIA_TYPES = {
104
120
  // lookup), a .weba audio/webm, though both are the same container.
105
121
  'video/mp4': 'mp4',
106
122
  'video/webm': 'webm',
123
+ 'image/png': 'png',
124
+ 'image/jpeg': 'jpg',
125
+ 'image/webp': 'webp',
126
+ 'image/gif': 'gif',
127
+ 'model/gltf-binary': 'glb',
128
+ 'model/gltf+json': 'gltf',
107
129
  };
108
130
  // The MIME Vite's own lookup gives each media extension (its data: URI
109
131
  // header), for the files loaded here. Every one is in EXTERNAL_MEDIA_TYPES.
110
132
  // No .mov or .m4v: Chromium and Android WebView do not play them reliably.
133
+ // No .svg: a deck may read one as markup.
111
134
  const MEDIA_EXTENSION_TYPES = {
112
135
  wav: 'audio/wav',
113
136
  mp3: 'audio/mpeg',
@@ -120,10 +143,37 @@ const MEDIA_EXTENSION_TYPES = {
120
143
  weba: 'audio/webm',
121
144
  mp4: 'video/mp4',
122
145
  webm: 'video/webm',
146
+ png: 'image/png',
147
+ jpg: 'image/jpeg',
148
+ jpeg: 'image/jpeg',
149
+ webp: 'image/webp',
150
+ gif: 'image/gif',
151
+ glb: 'model/gltf-binary',
152
+ gltf: 'model/gltf+json',
123
153
  };
124
154
  // The media extensions Vite treats as assets without a `?url` (its KNOWN_ASSET_TYPES).
125
- const VITE_MEDIA_ASSETS = new Set(['wav', 'mp3', 'ogg', 'opus', 'm4a', 'aac', 'flac', 'mp4', 'webm']);
126
- const MEDIA_ID = /\.(wav|mp3|ogg|oga|opus|m4a|aac|flac|weba|mp4|webm)(\?url)?$/i;
155
+ // Not glb or gltf: a deck imports those with `?url`.
156
+ const VITE_MEDIA_ASSETS = new Set([
157
+ 'wav', 'mp3', 'ogg', 'opus', 'm4a', 'aac', 'flac', 'mp4', 'webm', 'png', 'jpg', 'jpeg', 'webp', 'gif',
158
+ ]);
159
+ const MEDIA_ID = /\.(wav|mp3|ogg|oga|opus|m4a|aac|flac|weba|mp4|webm|png|jpe?g|webp|gif|glb|gltf)(\?url)?$/i;
160
+ const GLTF_TYPE = 'model/gltf+json';
161
+ // The type a .gltf's referenced file is uploaded or inlined as, by extension. A
162
+ // type outside EXTERNAL_MEDIA_TYPES is always inlined: a KTX2 texture, and a
163
+ // .bin buffer, which Ghost does not store (it has no signature to check, and
164
+ // any bytes served as an octet-stream could run as a script).
165
+ const GLTF_REFERENCE_TYPES = {
166
+ bin: 'application/octet-stream',
167
+ png: 'image/png',
168
+ jpg: 'image/jpeg',
169
+ jpeg: 'image/jpeg',
170
+ webp: 'image/webp',
171
+ gif: 'image/gif',
172
+ ktx2: 'image/ktx2',
173
+ };
174
+ // A URI with a scheme (data:, https:, blob:) or a root-relative or
175
+ // protocol-relative one: not a file beside the .gltf.
176
+ const NOT_RELATIVE_URI = /^(?:[a-z][a-z0-9+.-]*:|\/)/i;
127
177
  /**
128
178
  * Smaller media stays inline. 64 KiB is the knee on the largest live deck:
129
179
  * 78 of its 91 media files move and its page goes from 35.2 MB to 1.4 MB; the
@@ -132,7 +182,35 @@ const MEDIA_ID = /\.(wav|mp3|ogg|oga|opus|m4a|aac|flac|weba|mp4|webm)(\?url)?$/i
132
182
  export const EXTERNAL_MEDIA_MIN_BYTES = 64 * 1024;
133
183
  // Where Ghost serves stored assets. The override is for tests against a fake API.
134
184
  export const EXTERNAL_MEDIA_BASE_URL = process.env.CASTLE_ASSET_BASE_URL || 'https://hosted.castle.games/cauldron-assets/';
135
- // Run before any deck script. CORS matters only where a media element is
185
+ function parseGltf(bytes) {
186
+ try {
187
+ const json = JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
188
+ return json && typeof json === 'object' && !Array.isArray(json) ? json : null;
189
+ }
190
+ catch {
191
+ return null;
192
+ }
193
+ }
194
+ /** Every `uri` a glTF names for its buffers and images, as objects to rewrite in place. */
195
+ function gltfReferences(json) {
196
+ const out = [];
197
+ for (const list of [json.buffers, json.images]) {
198
+ if (!Array.isArray(list))
199
+ continue;
200
+ for (const holder of list) {
201
+ if (holder && typeof holder === 'object' && typeof holder.uri === 'string')
202
+ out.push({ uri: holder.uri, holder });
203
+ }
204
+ }
205
+ return out;
206
+ }
207
+ const isRelativeReference = (uri) => uri !== '' && !NOT_RELATIVE_URI.test(uri);
208
+ // Run before any deck script. An <img> given an asset URL by its `src`
209
+ // property or `setAttribute('src')` is made `anonymous` before it fetches, so
210
+ // a deck can draw it into a WebGL texture or read a canvas it was drawn into;
211
+ // one that named an asset past them (markup) is reloaded in CORS mode where
212
+ // its pixels are first read, and that one upload or draw skipped, as for a
213
+ // video below. CORS matters for audio only where a media element is
136
214
  // routed into Web Audio (createMediaElementSource), so that is where it is
137
215
  // made sure of: any element given to it with no crossOrigin of its own becomes
138
216
  // `anonymous`, whatever it names now or is given later (a detached <source>
@@ -157,13 +235,21 @@ export const EXTERNAL_MEDIA_BASE_URL = process.env.CASTLE_ASSET_BASE_URL || 'htt
157
235
  // the frame fetched without CORS would taint the canvas for good.
158
236
  // Anything unexpected leaves the page as it was.
159
237
  function mediaCorsShim(prefix) {
160
- return `(function(){try{var P=${JSON.stringify(prefix)},M=window.HTMLMediaElement,S=window.HTMLSourceElement;if(!M)return;var H=M.prototype;` +
238
+ return `(function(){try{var P=${JSON.stringify(prefix)},M=window.HTMLMediaElement,S=window.HTMLSourceElement,I=window.HTMLImageElement;if(!M)return;var H=M.prototype;` +
161
239
  // A pending restore per element; anything the deck does to it cancels it.
162
240
  'var R=new WeakMap();function z(e){try{R.delete(e)}catch(x){}}' +
163
- 'function c(e,u){try{if(e instanceof M&&typeof u=="string"&&u.indexOf(P)===0&&e.getAttribute("crossorigin")===null)e.crossOrigin="anonymous"}catch(x){}}' +
241
+ // An <img> made CORS here is put back when it is given another URL (unless
242
+ // the deck has written its crossOrigin since, any value), and one
243
+ // inside a <picture> or with a srcset (which may pick another host) is left alone.
244
+ // O holds the <img> elements whose crossorigin the shim wrote and the deck has
245
+ // not written since (k marks the shim's own writes).
246
+ 'var O=new WeakSet(),k=false;function a(e){k=true;try{e.crossOrigin="anonymous"}finally{k=false}O.add(e)}' +
247
+ 'function c(e,u){try{if(typeof u!="string")return;var im=I&&e instanceof I;if(im&&O.has(e)&&u.indexOf(P)!==0){O.delete(e);e.removeAttribute("crossorigin");return}' +
248
+ 'if(im&&(e.hasAttribute("srcset")||e.parentNode&&e.parentNode.nodeName==="PICTURE"))return;' +
249
+ 'if((e instanceof M||im)&&u.indexOf(P)===0&&e.getAttribute("crossorigin")===null){if(im)a(e);else e.crossOrigin="anonymous"}}catch(x){}}' +
164
250
  'function w(T,k,f){var d=T&&Object.getOwnPropertyDescriptor(T.prototype,k);if(d&&d.set&&d.configurable)Object.defineProperty(T.prototype,k,{configurable:true,enumerable:d.enumerable,get:d.get,set:function(v){try{f(this,v)}catch(x){}d.set.call(this,v)}});return d}' +
165
- 'w(M,"src",function(e,v){z(e);c(e,String(v))});w(S,"src",function(e,v){c(e.parentNode,String(v))});var T=w(M,"currentTime",z);' +
166
- 'var g=Element.prototype.setAttribute;Element.prototype.setAttribute=function(n,v){try{if(String(n).toLowerCase()==="src"){if(this instanceof M)z(this);c(this instanceof M?this:S&&this instanceof S?this.parentNode:null,String(v))}}catch(x){}return g.apply(this,arguments)};' +
251
+ 'w(M,"src",function(e,v){z(e);c(e,String(v))});w(S,"src",function(e,v){c(e.parentNode,String(v))});w(I,"src",function(e,v){c(e,String(v))});w(I,"crossOrigin",function(e){if(!k)O.delete(e)});var T=w(M,"currentTime",z);' +
252
+ 'var g=Element.prototype.setAttribute;Element.prototype.setAttribute=function(n,v){try{if(I&&this instanceof I&&String(n).toLowerCase()==="crossorigin")O.delete(this);if(String(n).toLowerCase()==="src"){if(this instanceof M)z(this);c(this instanceof M||I&&this instanceof I?this:S&&this instanceof S?this.parentNode:null,String(v))}}catch(x){}return g.apply(this,arguments)};' +
167
253
  'var L=H.load;["play","pause","load"].forEach(function(k){var f=H[k];if(f)H[k]=function(){z(this);return f.apply(this,arguments)}});' +
168
254
  'var A=window.Audio;if(A){var W=function Audio(u){var e=new A();if(u!==undefined){c(e,String(u));e.src=u}return e};W.prototype=A.prototype;window.Audio=W}' +
169
255
  'function r(e){if(!(e instanceof M)||e.getAttribute("crossorigin")!==null)return;var u=e.currentSrc||e.src||"";e.crossOrigin="anonymous";' +
@@ -176,12 +262,16 @@ function mediaCorsShim(prefix) {
176
262
  // that names an asset without CORS: reloaded in CORS mode on its first read,
177
263
  // and that one texture upload or draw skipped, so nothing is tainted.
178
264
  'var V=window.HTMLVideoElement;function n(e){if(!V||!(e instanceof V)||e.getAttribute("crossorigin")!==null)return false;if((e.currentSrc||e.src||"").indexOf(P)===0)return true;var s=e.querySelectorAll("source");for(var i=0;i<s.length;i++)if((s[i].src||"").indexOf(P)===0)return true;return false}' +
179
- 'function y(C,k){var K=C&&C.prototype,o=K&&K[k];if(typeof o!="function"||o.__castle)return;var h=function(){for(var i=0;i<arguments.length;i++){var e=arguments[i];if(V&&e instanceof V){try{if(n(e)&&r(e))return}catch(x){}break}}return o.apply(this,arguments)};h.__castle=1;K[k]=h}' +
265
+ // An <img> the same way: setting crossorigin makes it fetch again, in CORS mode.
266
+ // The reload is one promise per image, which every createImageBitmap of it waits on.
267
+ 'var Q=new WeakMap();function j(e){return!!I&&e instanceof I&&e.getAttribute("crossorigin")===null&&!e.hasAttribute("srcset")&&!(e.parentNode&&e.parentNode.nodeName==="PICTURE")&&(e.currentSrc||e.src||"").indexOf(P)===0}' +
268
+ 'function q(e){Q.set(e,new Promise(function(ok){var f=function(){e.removeEventListener("load",f);e.removeEventListener("error",f);Q.delete(e);ok()};e.addEventListener("load",f);e.addEventListener("error",f)}));a(e);return true}' +
269
+ 'function y(C,k){var K=C&&C.prototype,o=K&&K[k];if(typeof o!="function"||o.__castle)return;var h=function(){for(var i=0;i<arguments.length;i++){var e=arguments[i];if(V&&e instanceof V){try{if(n(e)&&r(e))return}catch(x){}break}if(I&&e instanceof I){try{if(j(e)&&q(e))return}catch(x){}break}}return o.apply(this,arguments)};h.__castle=1;K[k]=h}' +
180
270
  '[window.WebGLRenderingContext,window.WebGL2RenderingContext].forEach(function(C){["texImage2D","texSubImage2D","texImage3D","texSubImage3D"].forEach(function(k){y(C,k)})});' +
181
271
  '[window.CanvasRenderingContext2D,window.OffscreenCanvasRenderingContext2D].forEach(function(C){y(C,"drawImage")});' +
182
272
  // createImageBitmap answers a promise, so it waits out the reload (a CORS
183
273
  // frame, and the restored time settled) and then reads, instead of skipping.
184
- 'var B=window.createImageBitmap;if(B&&!B.__castle){window.createImageBitmap=function(e){var a=arguments,s=this;try{if(n(e)&&r(e))return new Promise(function(ok){var E=["loadeddata","seeked","canplay","error"],t,d=function(){if(!(e.readyState>=2&&!e.seeking)&&!e.error&&d!==t)return;E.forEach(function(k){e.removeEventListener(k,d)});clearTimeout(t);ok()};t=setTimeout(function(){t=d;d()},10000);E.forEach(function(k){e.addEventListener(k,d)})}).then(function(){return B.apply(s,a)})}catch(x){}return B.apply(this,arguments)};window.createImageBitmap.__castle=1}' +
274
+ 'var B=window.createImageBitmap;if(B&&!B.__castle){window.createImageBitmap=function(e){var a=arguments,s=this;try{if(j(e))q(e);var w8=Q.get(e);if(w8)return w8.then(function(){return B.apply(s,a)});if(n(e)&&r(e))return new Promise(function(ok){var E=["loadeddata","seeked","canplay","error"],t,d=function(){if(!(e.readyState>=2&&!e.seeking)&&!e.error&&d!==t)return;E.forEach(function(k){e.removeEventListener(k,d)});clearTimeout(t);ok()};t=setTimeout(function(){t=d;d()},10000);E.forEach(function(k){e.addEventListener(k,d)})}).then(function(){return B.apply(s,a)})}catch(x){}return B.apply(this,arguments)};window.createImageBitmap.__castle=1}' +
185
275
  '[window.AudioContext,window.webkitAudioContext].forEach(function(C){var K=C&&C.prototype,o=K&&K.createMediaElementSource;if(!o||o.__castle)return;var h=function(e){try{r(e)}catch(x){}return o.apply(this,arguments)};h.__castle=1;K.createMediaElementSource=h});' +
186
276
  '}catch(x){}})();';
187
277
  }
@@ -189,6 +279,9 @@ export class ExternalMedia {
189
279
  baseUrl;
190
280
  exclude;
191
281
  byUrl = new Map();
282
+ // sha256s of the self-contained .gltf files written inline for a refused
283
+ // one, which the late swap would otherwise take for a new asset.
284
+ inlined = new Set();
192
285
  /** `exclude`: sha256s that stay inline (Ghost refused to store them). */
193
286
  constructor(baseUrl = EXTERNAL_MEDIA_BASE_URL, exclude = new Set()) {
194
287
  this.baseUrl = baseUrl;
@@ -238,7 +331,7 @@ export class ExternalMedia {
238
331
  },
239
332
  transform: {
240
333
  order: 'post',
241
- filter: { code: /"data:(?:audio|video)\// },
334
+ filter: { code: /"data:(?:audio|video|image|model)\// },
242
335
  handler: (code, id) => {
243
336
  // An `?inline` import's module: a data: URI asked for by name.
244
337
  if (/[?&]inline(?:[&=]|$)/.test(id))
@@ -279,17 +372,94 @@ export class ExternalMedia {
279
372
  catch {
280
373
  return null;
281
374
  }
375
+ if (mime === GLTF_TYPE)
376
+ return this.loadedGltf(file, size, root);
282
377
  if (size < EXTERNAL_MEDIA_MIN_BYTES)
283
378
  return null;
284
379
  return this.record(mime, fs.readFileSync(file), relativeSource(root, file));
285
380
  }
286
- record(mime, bytes, source) {
381
+ // A .gltf with no relative references is any other asset. One with them is
382
+ // rewritten (see the top of this section): its references become URLs or
383
+ // data: URIs, and it is named by its URL whatever its size -- or, when Ghost
384
+ // refused the rewritten file, inline with every reference a data: URI.
385
+ loadedGltf(file, size, root) {
386
+ const bytes = fs.readFileSync(file);
387
+ const source = relativeSource(root, file);
388
+ const json = parseGltf(bytes);
389
+ if (!json || !gltfReferences(json).some((ref) => isRelativeReference(ref.uri))) {
390
+ return size < EXTERNAL_MEDIA_MIN_BYTES ? null : this.record(GLTF_TYPE, bytes, source);
391
+ }
392
+ const deps = new Map();
393
+ const rewritten = this.rewriteGltf(file, root, parseGltf(bytes), deps, false);
394
+ const sha256 = createHash('sha256').update(rewritten).digest('hex');
395
+ if (!this.exclude.has(sha256)) {
396
+ for (const dep of deps.values())
397
+ if (!this.byUrl.has(dep.url))
398
+ this.byUrl.set(dep.url, dep);
399
+ return this.record(GLTF_TYPE, rewritten, source, [...deps.keys()]);
400
+ }
401
+ const inline = this.rewriteGltf(file, root, parseGltf(bytes), new Map(), true);
402
+ this.inlined.add(createHash('sha256').update(inline).digest('hex'));
403
+ return `data:${GLTF_TYPE};base64,${inline.toString('base64')}`;
404
+ }
405
+ // Each relative reference that is a file under the deck becomes its asset
406
+ // URL (collected in `deps`) or, when it is small, a type Ghost does not
407
+ // store, excluded, or `inlineAll`, a data: URI. Any other reference is left
408
+ // as it was.
409
+ rewriteGltf(file, root, json, deps, inlineAll) {
410
+ const dir = path.dirname(file);
411
+ // Real paths on both sides: a symlink in the deck must not reach a file outside it.
412
+ let within;
413
+ try {
414
+ within = fs.realpathSync(root) + path.sep;
415
+ }
416
+ catch {
417
+ return Buffer.from(JSON.stringify(json));
418
+ }
419
+ for (const { uri, holder } of gltfReferences(json)) {
420
+ if (!isRelativeReference(uri))
421
+ continue;
422
+ let target;
423
+ try {
424
+ target = path.resolve(dir, decodeURIComponent(uri.split(/[?#]/, 1)[0]));
425
+ }
426
+ catch {
427
+ continue;
428
+ }
429
+ let refBytes;
430
+ try {
431
+ target = fs.realpathSync(target);
432
+ if (!target.startsWith(within) || !fs.statSync(target).isFile())
433
+ continue;
434
+ refBytes = fs.readFileSync(target);
435
+ }
436
+ catch {
437
+ continue;
438
+ }
439
+ const type = GLTF_REFERENCE_TYPES[path.extname(target).slice(1).toLowerCase()] ?? 'application/octet-stream';
440
+ const sha256 = createHash('sha256').update(refBytes).digest('hex');
441
+ if (!inlineAll &&
442
+ EXTERNAL_MEDIA_TYPES[type] &&
443
+ refBytes.byteLength >= EXTERNAL_MEDIA_MIN_BYTES &&
444
+ !this.exclude.has(sha256)) {
445
+ const url = `${this.baseUrl}${sha256}.${EXTERNAL_MEDIA_TYPES[type]}`;
446
+ deps.set(url, { sha256, contentType: type, url, bytes: refBytes, source: relativeSource(root, target) });
447
+ holder.uri = url;
448
+ }
449
+ else {
450
+ holder.uri = `data:${type};base64,${refBytes.toString('base64')}`;
451
+ }
452
+ }
453
+ return Buffer.from(JSON.stringify(json));
454
+ }
455
+ record(mime, bytes, source, deps) {
287
456
  const sha256 = createHash('sha256').update(bytes).digest('hex');
288
- if (this.exclude.has(sha256))
457
+ if (this.exclude.has(sha256) || this.inlined.has(sha256))
289
458
  return null;
290
459
  const url = `${this.baseUrl}${sha256}.${EXTERNAL_MEDIA_TYPES[mime]}`;
291
- if (!this.byUrl.has(url))
292
- this.byUrl.set(url, { sha256, contentType: mime, url, bytes, source });
460
+ if (!this.byUrl.has(url)) {
461
+ this.byUrl.set(url, { sha256, contentType: mime, url, bytes, source, ...(deps?.length ? { deps } : {}) });
462
+ }
293
463
  return url;
294
464
  }
295
465
  urlFor(header, payload, source) {
@@ -302,11 +472,30 @@ export class ExternalMedia {
302
472
  const bytes = Buffer.from(payload, 'base64');
303
473
  if (bytes.byteLength < EXTERNAL_MEDIA_MIN_BYTES)
304
474
  return null;
475
+ // A .gltf met only as a data: URI has no file to resolve references against:
476
+ // one that has any stays as it is.
477
+ if (mime === GLTF_TYPE) {
478
+ const json = parseGltf(bytes);
479
+ if (json && gltfReferences(json).some((ref) => isRelativeReference(ref.uri)))
480
+ return null;
481
+ }
305
482
  return this.record(mime, bytes, source);
306
483
  }
307
- /** Every asset the finished page names (a module the build dropped names none). */
484
+ /**
485
+ * Every asset the finished page names (a module the build dropped names
486
+ * none), and each one those name in turn (a .gltf's buffers and textures).
487
+ */
308
488
  assetsIn(html) {
309
- return [...this.byUrl.values()].filter((asset) => html.includes(asset.url));
489
+ const named = [...this.byUrl.values()].filter((asset) => html.includes(asset.url));
490
+ const out = new Map(named.map((asset) => [asset.url, asset]));
491
+ for (const asset of named) {
492
+ for (const url of asset.deps ?? []) {
493
+ const dep = this.byUrl.get(url);
494
+ if (dep && !out.has(url))
495
+ out.set(url, dep);
496
+ }
497
+ }
498
+ return [...out.values()];
310
499
  }
311
500
  }
312
501
  function relativeSource(root, id) {
package/dist/init.js CHANGED
@@ -64,7 +64,7 @@ const BARE_SCAFFOLDS = [
64
64
  // Registry version of castle-web-sdk to inject when scaffolding from a
65
65
  // globally-installed castle-web (not from inside the workspace). Bumped
66
66
  // alongside cli/sdk version bumps.
67
- const PUBLISHED_SDK_VERSION = '0.4.55';
67
+ const PUBLISHED_SDK_VERSION = '0.4.56';
68
68
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
69
69
  // face can ship without a cli release, and a caret range means an existing
70
70
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -1 +1 @@
1
- export declare const MULTIPLAYER_DOC = "# Multiplayer, in practice\n\nRead this before writing or changing a server entry or client netcode by hand.\nWritten fresh by the Castle CLI at every serve start; the full API reference is\nthe SDK's own, at `imports/castle.base/sdk/README.md`.\n\n## Reach for a kit first\n\n`castle.multiplayer-2d` and `castle.multiplayer-3d` (both on `castle.real-time`)\nalready do everything below: a server-authoritative world, one snapshot per\ntick, pose interpolation, roster handling, reconnects, ownership of loose\nobjects. `castle.turn-based` does the same for games played in turns, with\nseats, spectators and idle clearing. A deck on one of those kits normally\nwrites nothing against the raw session API, and the right move is usually to\nadd a rule to the deck's own game hooks rather than a message of your own.\n\nHand-roll only when the game genuinely does not fit them -- and then keep the\nshape below, because it is the shape the platform's limits ask for.\n\n## The outbound budget\n\nA session may send about `40 + 40 x connected players` frames per second, with\nroughly two seconds of burst, and about 1 MiB/s of bytes. What a frame costs:\n\n| call | frames |\n|---|---|\n| `session.send(playerId, data)` | 1 |\n| `session.broadcast(data)` | 1, whatever the player count |\n| `session.broadcast(data, { except })` | one per recipient -- it is a loop of sends |\n\nFrames over the budget are **dropped silently**. The session keeps running and\na dropped frame is never retried, so the symptom is not an error: it is a\nclient whose world quietly stops matching everyone else's. Only sustained abuse\nat several times the budget ends a session.\n\nThe arithmetic that matters, at `tickRate: 20`:\n\n- 4 players, one `send` per player per tick: 80 frames/s of a 200 budget --\n before a single hit, join, chat or one-off frame.\n- 8 players, same: 160 of 360. A second per-player message per tick makes it\n 320, and at `tickRate: 30` that is 480 -- over, and frames start dropping.\n- Either, with one `broadcast` per tick: 20 frames/s. The budget stops being\n something you have to think about.\n\nPer-player sends also send the same bytes N times toward the byte budget. The\nlocal serve does not drop anything, but it warns when a 1-second window goes\nover -- `[multiplayer] server sent ...` in `.castle/logs.txt` and in the serve's\nown output (`.castle/serve.log` when it was detached).\n\n## The snapshot pattern\n\nAuthoritative state lives on the server. `onTick` builds ONE snapshot of every\nplayer and broadcasts it once.\n\nEvery client reads EVERY entry in that snapshot, **including its own** -- the\ndifference is only what it does with each:\n\n- **Other players' entries** drive what it draws for them (interpolated between\n snapshots), and are how it learns someone left or went silent.\n- **Its own entry** is the server's verdict on itself. Take hp, alive/wrecked,\n kills, score and the match state from it every tick, exactly as if it were\n someone else's. The one field it does NOT overwrite each tick is its own pose:\n the local player moves on its own input so the game stays responsive, and the\n client only snaps to the server's position when the two have drifted far\n apart. Ignoring the rest of its own entry is how a player ends up alive on\n their own screen and dead on everyone else's.\n\n```js\nconst state = { matchNumber: 1, players: {}, parked: new Map() };\n\nexport default {\n onPlayerJoin(session, player) {\n state.players[player.playerId] = { x: 0, y: 0, hp: 100, kills: 0, alive: true };\n },\n onMessage(session, player, data) {\n if (data.t === 'move') applyMove(state.players[player.playerId], data);\n },\n onTick(session) {\n // One frame per tick, for any number of players.\n session.broadcast({ t: 'snap', n: state.matchNumber, players: state.players });\n },\n};\n```\n\n```js\nconnection.onMessage((msg) => {\n if (msg.t !== 'snap') return;\n match.setNumber(msg.n); // a new match number means: reset, the round moved on\n for (const [id, p] of Object.entries(msg.players)) {\n if (id === connection.playerId) {\n // My own entry: the server owns all of it except where I am right now.\n Object.assign(me, { hp: p.hp, kills: p.kills, alive: p.alive });\n if (Math.hypot(p.x - me.x, p.y - me.y) > SNAP_DISTANCE) {\n me.x = p.x; // drifted too far to argue; the server is right\n me.y = p.y;\n }\n continue;\n }\n remote.set(id, { ...p, seenAt: performance.now() });\n }\n});\n```\n\nDo not build a per-player payload (\"everyone except you\") on the server: the\nclient needs its own entry anyway, and one tailored message per player costs N\nframes where the shared snapshot costs 1.\n\n## One-off events must be self-healing\n\nA dropped or missed event frame is gone for good. So an event may carry an\neffect, never the only copy of a result:\n\n- `{ t: 'hit', target, dmg }` -- fine for a flash, a sound, a particle.\n- The hp it produced, whether the player is alive or wrecked, the kill count,\n the match number: all of that belongs in the periodic snapshot, and the\n client reconciles from the snapshot every tick.\n\nWrite the client so that receiving zero events and only snapshots still\nproduces a correct, playable screen. Then a dropped frame costs one missing\nspark instead of a player who is dead everywhere but on their own device.\n\n## Connection loss has to be visible\n\nTwo independent things can go quiet: the socket, and a player.\n\n```js\nconnection.onStateChange((state, meta) => {\n // 'acquiring' | 'connecting' | 'connected' | 'reconnecting' | 'closed'\n // meta?.type: 'connectionLost' | 'replaced' | 'bye' | 'left' | 'error'\n hud.setConnection(state, meta?.type);\n});\n```\n\n- Show `reconnecting` and `closed` in the deck's own UI. A player staring at a\n frozen game with no explanation assumes the game is broken.\n- On `closed` with `replaced`, call `Multiplayer.join` again: the creator\n published a new server. A `public` join from matchmaking lands on the new\n version; a `named` or `party` room, or a friend's public room the player\n followed, keeps the old one until Castle ends it, about ten minutes after the\n save. That ending, like a kick, arrives as `bye` with a `reason` to show\n the player; don't rejoin a `bye` automatically, or a kicked player comes\n straight back.\n- Expire a remote player whose last snapshot is older than a few seconds\n (`performance.now() - p.seenAt > 3000`) and stop drawing them. This must run\n off the client's own clock, not off an event -- if the server or the socket\n goes silent, no message will ever arrive to tell you, and every remote player\n stays frozen mid-stride forever.\n- The SDK reconnects short drops by itself and `send` is safe to call while the\n socket is down (those messages are dropped), so the client's job is to show\n the state and recover, not to manage the socket.\n\n## Reconnects: park match state, never delete it\n\n`playerId` is stable across a platform reconnect, but the server still sees\n`onPlayerLeave` and then `onPlayerJoin`. A server that deletes the player's row\non leave silently drops a reconnecting player out of the match while their\nclient happily thinks it is still playing.\n\n```js\nonPlayerLeave(session, player) {\n const parked = state.players[player.playerId];\n delete state.players[player.playerId];\n if (parked) state.parked.set(player.playerId, { at: Date.now(), parked }); // or by userId\n},\nonPlayerJoin(session, player) {\n const held = state.parked.get(player.playerId);\n state.parked.delete(player.playerId);\n state.players[player.playerId] =\n held && Date.now() - held.at < 60_000 ? held.parked : freshPlayer();\n session.send(player.playerId, { t: 'full', ...fullState() }); // 1 frame, once\n},\n```\n\nPark for about 60 seconds (the platform's own reconnect window), keyed by\n`playerId`, or by `userId` when the match should survive a genuinely new\nconnection from the same account. Sweep expired entries on a tick.\n\nOn the client, after a state change back to `connected`, ask for full state\nonce and rebuild from the answer rather than assuming the world is as you left\nit.\n\n## The server ignores and tells\n\nWhen the server refuses a message because the player is not in the state the\nclient assumed -- not in the match, already dead, not their turn -- do not just\n`return`. The client believes something false and nothing will correct it.\n\n```js\nonMessage(session, player, data) {\n const me = state.players[player.playerId];\n if (!me || !me.alive) {\n session.send(player.playerId, { t: 'full', ...fullState() }); // authoritative answer\n return;\n }\n ...\n}\n```\n\nOne frame, and the client resyncs instead of arguing with itself. Rate-limit\nthat reply (once per player per second is plenty) so a looping client cannot\nspend the whole budget on corrections.\n\n## Client to server\n\nClient frames are capped at 16 KB and about 30 messages per second; **exceeding\nthe rate closes the socket**, which is much harsher than the server side's\nsilent drop.\n\n- Throttle pose/input sends to a fixed rate. 8-15 per second is plenty when the\n client interpolates between samples (the real-time kit reports at 20). Never\n send once per animation frame -- 60/s closes the connection.\n- Send intent (\"I am holding left\", \"I fired\"), not results. The server decides\n what happened.\n- Coalesce: one message per send tick carrying the latest pose beats three\n messages describing how it got there.\n\n## Testing it\n\n- Open **four or more** tabs, not two. Every budget and roster bug scales with\n the player count, and two tabs is exactly the case that never reproduces one.\n- Reload tabs mid-match to exercise leave/rejoin, and leave one tab idle to see\n what a silent player looks like to everyone else.\n- Kill and restart the serve (or edit the server entry, which restarts it) to\n see the disconnected state the deck shows.\n- Watch the serve log for the `[multiplayer]` budget warning and for dropped\n oversize frames while you play.\n- A published room that crashed or stopped: `castle-web logs` prints its end\n reason, exit code and last server log lines (creator only; `--rooms` lists rooms).\n";
1
+ export declare const MULTIPLAYER_DOC = "# Multiplayer, in practice\n\nRead this before writing or changing a server entry or client netcode by hand.\nWritten fresh by the Castle CLI at every serve start; the full API reference is\nthe SDK's own, at `imports/castle.base/sdk/README.md`.\n\n## Reach for a kit first\n\n`castle.multiplayer-2d` and `castle.multiplayer-3d` (both on `castle.real-time`)\nalready do everything below: a server-authoritative world, one snapshot per\ntick, pose interpolation, roster handling, reconnects, ownership of loose\nobjects. `castle.turn-based` does the same for games played in turns, with\nseats, spectators and idle clearing. A deck on one of those kits normally\nwrites nothing against the raw session API, and the right move is usually to\nadd a rule to the deck's own game hooks rather than a message of your own.\n\nHand-roll only when the game genuinely does not fit them -- and then keep the\nshape below, because it is the shape the platform's limits ask for.\n\n## The outbound budget\n\nA session may send about `40 + 40 x connected players` frames per second, with\nroughly two seconds of burst, and about 1 MiB/s of bytes. What a frame costs:\n\n| call | frames |\n|---|---|\n| `session.send(playerId, data)` | 1 |\n| `session.broadcast(data)` | 1, whatever the player count |\n| `session.broadcast(data, { except })` | one per recipient -- it is a loop of sends |\n\nFrames over the budget are **dropped silently**. The session keeps running and\na dropped frame is never retried, so the symptom is not an error: it is a\nclient whose world quietly stops matching everyone else's. Only sustained abuse\nat several times the budget ends a session.\n\nThe arithmetic that matters, at `tickRate: 20`:\n\n- 4 players, one `send` per player per tick: 80 frames/s of a 200 budget --\n before a single hit, join, chat or one-off frame.\n- 8 players, same: 160 of 360. A second per-player message per tick makes it\n 320, and at `tickRate: 30` that is 480 -- over, and frames start dropping.\n- Either, with one `broadcast` per tick: 20 frames/s. The budget stops being\n something you have to think about.\n\nPer-player sends also send the same bytes N times toward the byte budget. The\nlocal serve does not drop anything, but it warns when a 1-second window goes\nover -- `[multiplayer] server sent ...` in `.castle/logs.txt` and in the serve's\nown output (`.castle/serve.log` when it was detached).\n\n## The snapshot pattern\n\nAuthoritative state lives on the server. `onTick` builds ONE snapshot of every\nplayer and broadcasts it once.\n\nEvery client reads EVERY entry in that snapshot, **including its own** -- the\ndifference is only what it does with each:\n\n- **Other players' entries** drive what it draws for them (interpolated between\n snapshots), and are how it learns someone left or went silent.\n- **Its own entry** is the server's verdict on itself. Take hp, alive/wrecked,\n kills, score and the match state from it every tick, exactly as if it were\n someone else's. The one field it does NOT overwrite each tick is its own pose:\n the local player moves on its own input so the game stays responsive, and the\n client only snaps to the server's position when the two have drifted far\n apart. Ignoring the rest of its own entry is how a player ends up alive on\n their own screen and dead on everyone else's.\n\n```js\nconst state = { matchNumber: 1, players: {}, parked: new Map() };\n\nexport default {\n onPlayerJoin(session, player) {\n state.players[player.playerId] = { x: 0, y: 0, hp: 100, kills: 0, alive: true };\n },\n onMessage(session, player, data) {\n if (data.t === 'move') applyMove(state.players[player.playerId], data);\n },\n onTick(session) {\n // One frame per tick, for any number of players.\n session.broadcast({ t: 'snap', n: state.matchNumber, players: state.players });\n },\n};\n```\n\n```js\nconnection.onMessage((msg) => {\n if (msg.t !== 'snap') return;\n match.setNumber(msg.n); // a new match number means: reset, the round moved on\n for (const [id, p] of Object.entries(msg.players)) {\n if (id === connection.playerId) {\n // My own entry: the server owns all of it except where I am right now.\n Object.assign(me, { hp: p.hp, kills: p.kills, alive: p.alive });\n if (Math.hypot(p.x - me.x, p.y - me.y) > SNAP_DISTANCE) {\n me.x = p.x; // drifted too far to argue; the server is right\n me.y = p.y;\n }\n continue;\n }\n remote.set(id, { ...p, seenAt: performance.now() });\n }\n});\n```\n\nDo not build a per-player payload (\"everyone except you\") on the server: the\nclient needs its own entry anyway, and one tailored message per player costs N\nframes where the shared snapshot costs 1.\n\n## One-off events must be self-healing\n\nA dropped or missed event frame is gone for good. So an event may carry an\neffect, never the only copy of a result:\n\n- `{ t: 'hit', target, dmg }` -- fine for a flash, a sound, a particle.\n- The hp it produced, whether the player is alive or wrecked, the kill count,\n the match number: all of that belongs in the periodic snapshot, and the\n client reconciles from the snapshot every tick.\n\nWrite the client so that receiving zero events and only snapshots still\nproduces a correct, playable screen. Then a dropped frame costs one missing\nspark instead of a player who is dead everywhere but on their own device.\n\n## Connection loss has to be visible\n\nTwo independent things can go quiet: the socket, and a player.\n\n```js\nconnection.onStateChange((state, meta) => {\n // 'acquiring' | 'connecting' | 'connected' | 'reconnecting' | 'closed'\n // meta?.type: 'connectionLost' | 'replaced' | 'bye' | 'left' | 'error'\n hud.setConnection(state, meta?.type);\n});\n```\n\n- Show `reconnecting` and `closed` in the deck's own UI. A player staring at a\n frozen game with no explanation assumes the game is broken.\n- On `closed` with `replaced`, call `Multiplayer.join` again: the creator\n published a new server. A `public` join from matchmaking lands on the new\n version; a `named` or `party` room, or a friend's public room the player\n followed, keeps the old one until Castle ends it, about ten minutes after the\n save. That ending, like a kick, arrives as `bye` with a `reason` to show\n the player; don't rejoin a `bye` automatically, or a kicked player comes\n straight back.\n- Expire a remote player whose last snapshot is older than a few seconds\n (`performance.now() - p.seenAt > 3000`) and stop drawing them. This must run\n off the client's own clock, not off an event -- if the server or the socket\n goes silent, no message will ever arrive to tell you, and every remote player\n stays frozen mid-stride forever.\n- The SDK reconnects short drops by itself and `send` is safe to call while the\n socket is down (those messages are dropped), so the client's job is to show\n the state and recover, not to manage the socket.\n\n## Reconnects: park match state, never delete it\n\n`playerId` is stable across a platform reconnect, but the server still sees\n`onPlayerLeave` and then `onPlayerJoin`. A server that deletes the player's row\non leave silently drops a reconnecting player out of the match while their\nclient happily thinks it is still playing.\n\n```js\nonPlayerLeave(session, player) {\n const parked = state.players[player.playerId];\n delete state.players[player.playerId];\n if (parked) state.parked.set(player.playerId, { at: Date.now(), parked }); // or by userId\n},\nonPlayerJoin(session, player) {\n const held = state.parked.get(player.playerId);\n state.parked.delete(player.playerId);\n state.players[player.playerId] =\n held && Date.now() - held.at < 60_000 ? held.parked : freshPlayer();\n session.send(player.playerId, { t: 'full', ...fullState() }); // 1 frame, once\n},\n```\n\nPark for about 60 seconds (the platform's own reconnect window), keyed by\n`playerId`, or by `userId` when the match should survive a genuinely new\nconnection from the same account. Sweep expired entries on a tick.\n\nOn the client, after a state change back to `connected`, ask for full state\nonce and rebuild from the answer rather than assuming the world is as you left\nit.\n\n## The server ignores and tells\n\nWhen the server refuses a message because the player is not in the state the\nclient assumed -- not in the match, already dead, not their turn -- do not just\n`return`. The client believes something false and nothing will correct it.\n\n```js\nonMessage(session, player, data) {\n const me = state.players[player.playerId];\n if (!me || !me.alive) {\n session.send(player.playerId, { t: 'full', ...fullState() }); // authoritative answer\n return;\n }\n ...\n}\n```\n\nOne frame, and the client resyncs instead of arguing with itself. Rate-limit\nthat reply (once per player per second is plenty) so a looping client cannot\nspend the whole budget on corrections.\n\n## Client to server\n\nClient frames are capped at 16 KB and about 30 messages per second; **exceeding\nthe rate closes the socket**, which is much harsher than the server side's\nsilent drop.\n\n- Throttle pose/input sends to a fixed rate. 8-15 per second is plenty when the\n client interpolates between samples (the real-time kit reports at 20). Never\n send once per animation frame -- 60/s closes the connection.\n- Send intent (\"I am holding left\", \"I fired\"), not results. The server decides\n what happened.\n- Coalesce: one message per send tick carrying the latest pose beats three\n messages describing how it got there.\n\n## Testing it\n\n- Open **four or more** tabs, not two. Every budget and roster bug scales with\n the player count, and two tabs is exactly the case that never reproduces one.\n- Reload tabs mid-match to exercise leave/rejoin, and leave one tab idle to see\n what a silent player looks like to everyone else.\n- Kill and restart the serve (or edit the server entry, which restarts it) to\n see the disconnected state the deck shows.\n- Watch the serve log for the `[multiplayer]` budget warning and for dropped\n oversize frames while you play.\n- A published room that crashed or stopped: `castle-web logs` prints its end\n reason, exit code and last server log lines (creator only; `--rooms` lists rooms).\n The room list and the room view also show how many server messages were dropped\n for being over 64 KB.\n";
@@ -234,4 +234,6 @@ silent drop.
234
234
  oversize frames while you play.
235
235
  - A published room that crashed or stopped: \`castle-web logs\` prints its end
236
236
  reason, exit code and last server log lines (creator only; \`--rooms\` lists rooms).
237
+ The room list and the room view also show how many server messages were dropped
238
+ for being over 64 KB.
237
239
  `;
@@ -54,7 +54,7 @@ const MODE_BULLET = "- Unprompted, an editor is an offer, never a build: when th
54
54
  export function everyDeckBullets(deckDir) {
55
55
  return [
56
56
  "- **Castle's Parameters panel is where a creator tunes the deck.** It is one of Castle's own panels, beside Play and Files: it shows the `PARAMS` values of every file that has one as live fields the creator drags while the deck runs, which is how they change the way it plays without putting a cursor in code.",
57
- `- **Supported media formats are exactly**: ${mediaList(deckDir)}. Nothing else — a published deck inlines every asset as a \`data:\` URI, where the browser trusts the declared type instead of sniffing the bytes, so a format that merely works while serving (\`.mov\` is the classic case) can be dead once published. Convert, don't improvise. Audio and video (\`.mp4\`, \`.webm\`) of 64 KB or more are the assets not inlined: a published deck serves them from Castle's CDN by URL, so play them with \`new Audio(url)\`, \`video.src = url\` or \`fetch\` + \`decodeAudioData\`, never by reading the string (an \`?inline\` import keeps the \`data:\` URI).`,
57
+ `- **Supported media formats are exactly**: ${mediaList(deckDir)}. Nothing else — a published deck inlines every asset as a \`data:\` URI, where the browser trusts the declared type instead of sniffing the bytes, so a format that merely works while serving (\`.mov\` is the classic case) can be dead once published. Convert, don't improvise. Audio, video (\`.mp4\`, \`.webm\`), images (\`.png\`, \`.jpg\`, \`.webp\`, \`.gif\`) and 3D models (\`.glb\`, and \`.gltf\` with the \`.bin\` and textures it references, imported with \`?url\`) of 64 KB or more are the assets not inlined: a published deck serves them from Castle's CDN by URL, so hand the URL to a loader (\`new Audio(url)\`, \`video.src = url\`, \`img.src = url\`, a texture or glTF loader, \`fetch\`), never read the string itself (an \`?inline\` import keeps the \`data:\` URI).`,
58
58
  "- To add an npm package, put it in `package.json` `dependencies` and run `castle-web install .` (the install `init` ran; it uses whichever package manager made the lockfile).",
59
59
  "- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
60
60
  '- If the browser console shows `[vite] failed to connect to websocket` (or a "Direct websocket connection fallback" line), ignore it. Vite HMR is deliberately off on this serve, so the line is expected and harmless: it is never why a scene is blank, a game is not running, or multiplayer is not connecting. Do not investigate or "fix" it.',
@@ -79,7 +79,7 @@ export function everyDeckBullets(deckDir) {
79
79
  export const HOST_LIMIT_BULLETS = [
80
80
  "- **Where a deck runs decides what it can do.** The Play panel runs it from this serve; players run the published deck in the Castle app (iOS, Android) or castle.xyz's web player. When something works in one and fails in another, check it against the limits below before another fix: if one covers it, name that limit instead of retrying, and ask where they run it if you do not know. If none does, it is an ordinary deck bug (a runtime `fetch` of a loose file, a control that only answers a mouse) and gets fixed.",
81
81
  "- **Microphone and camera are blocked in the Play panel and on castle.xyz**: neither frame is granted them, so `getUserMedia` rejects with `NotAllowedError` whatever the person allows, and no deck change helps. The Android app's published deck can use them; the iOS app is untested.",
82
- "- **A published deck loads almost nothing from the network.** Its CSP allows images, audio and video only from the deck itself, `data:` or `blob:`, `fetch` only to esm.sh, cdnjs.cloudflare.com and Castle's multiplayer hosts, and no iframes. The Play panel enforces the same CSP, so a URL it blocks fails in Play too, and `.castle/logs.txt` names each URL and directive the page blocked with a `[csp] blocked` line. Bundle the file, or let the player pick one with `<input type=\"file\">`.",
82
+ "- **A published deck loads almost nothing from the network.** Its CSP allows images, audio and video only from the deck itself, `data:`, `blob:` and Castle's own CDN (where save-deck puts the deck's large media, images and models), `fetch` only to esm.sh, cdnjs.cloudflare.com, that CDN and Castle's multiplayer hosts, and no iframes. The Play panel enforces the same CSP, so a URL it blocks fails in Play too, and `.castle/logs.txt` names each URL and directive the page blocked with a `[csp] blocked` line. Bundle the file, or let the player pick one with `<input type=\"file\">`.",
83
83
  "- **On castle.xyz a published deck's frame has no origin of its own, and on a device its console reaches no devtools.** Browser storage throws a `SecurityError` there, and so do history calls that pass a URL. Don't build on browser storage; the SDK's replacements, how `setup()` keeps history calls working, and the on-screen console for debugging on a device are in the SDK reference, `imports/castle.base/sdk/README.md`.",
84
84
  "- **An older Castle app build rejects SDK commands newer than the build**, with a `CastleError` whose `code` is `UNKNOWN_COMMAND`; only an app update fixes that, so the deck should catch it and keep working. Which commands need which app build, and every other limit of a Castle service, is in the SDK reference, `imports/castle.base/sdk/README.md`.",
85
85
  ];
@@ -312,7 +312,7 @@ const COMMON_SECTIONS = `## Imports are read-only
312
312
  - **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. A session may also SEND only about \`40 + 40 × connected players\` frames per second (about two seconds of burst, and about 1 MiB/s of bytes): \`session.send\` costs one frame per call, \`session.broadcast(data)\` costs ONE frame however many players are in the session, and \`session.broadcast(data, { except })\` is a loop of sends, so it costs one frame per recipient. Frames over the budget are dropped silently and never retried — the session keeps running, so the symptom is a client whose world quietly stops matching everyone else's; only sustained abuse at several times the budget ends a session. So send one \`broadcast\` per tick carrying every player's state, rather than a tailored \`send\` per player: every client reads every entry of that snapshot INCLUDING its own — it takes hp, kills and match state from its own entry and only keeps its own position locally predicted.
313
313
  - **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.
314
314
  - **Test multiplayer locally with no setup.** \`castle-web serve\` runs your server file alongside the deck. Open the shell URL it prints in two tabs, then open the Play panel in each; those play surfaces share a session. If you open the content origin from \`.castle/serve.json\` directly, use \`/index.html?edit=0\`. Its bare origin loads the edit surface, where \`Multiplayer.join\` is not answered. Editing the server entry, anything beside it, or a deck-owned hook under \`server/\` or \`code/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.
315
- - **A published deck's server rooms have logs too.** \`castle-web logs\` (in the deck folder, signed in as its creator) shows the newest room's state, end reason, exit code, an out-of-memory kill, and its last server log lines; \`--rooms\` lists recent rooms and \`--room <id>\` picks one. Hosts keep the lines for about 30 minutes after a room ends.
315
+ - **A published deck's server rooms have logs too.** \`castle-web logs\` (in the deck folder, signed in as its creator) shows the newest room's state, end reason, exit code, an out-of-memory kill, and its last server log lines; \`--rooms\` lists recent rooms and \`--room <id>\` picks one. Hosts keep the lines for about 30 minutes after a room ends. The room list and the room view also show how many server messages were dropped for being over 64 KB.
316
316
  - **Publishing moves players onto the new version; you don't build versioned rooms or a rejoin prompt.** \`save-deck\` bundles and publishes the server entry, and every new session runs it. A session already running keeps the code it started with: its server gets \`onReplaced\`, and each client's connection closes with \`replaced\` metadata. A deck that joins again when the connection closes (the multiplayer kits do) gets the new version at once for a \`public\` join from matchmaking, since new players are not placed in a running public session on the old code; a \`named\` or \`party\` join, or a public one that follows a friend into their room, goes back to that room, which keeps the old code until it ends. About ten minutes after the save Castle ends any ordinary session still on the old code (hub places, persistent worlds and destinations keep their own release handling), closing its connections with \`bye\` and a reason that says the game was updated; its \`onShutdown\` still runs, so a save there lands, and the next join gets the new version.
317
317
  `;
318
318
  export function platformGuide(deckDir) {
@@ -12,17 +12,18 @@ const CONTENT_PACK_HOSTS = 'https://hosted.castle.games';
12
12
  // `Access-Control-Allow-Origin: *`, so a fetch from the opaque srcdoc origin can read
13
13
  // them. img-src, media-src and connect-src only: an asset is data, never script.
14
14
  export const CASTLE_ASSET_HOSTS = 'https://castle.imgix.net https://image.castle.xyz https://audio.castle.xyz';
15
- // A published deck's audio and video, which save-deck stores there instead of
16
- // inlining it (bundle.ts ExternalMedia). Path-scoped and media-src only: a fetch
17
- // for decodeAudioData is already covered by CONTENT_PACK_HOSTS in connect-src.
18
- const MEDIA_ASSET_SRC = 'https://hosted.castle.games/cauldron-assets/';
15
+ // A published deck's audio, video and images, which save-deck stores there
16
+ // instead of inlining them (bundle.ts ExternalMedia). Path-scoped, img-src and
17
+ // media-src only: a fetch (decodeAudioData, a glTF or texture loader) is
18
+ // already covered by CONTENT_PACK_HOSTS in connect-src.
19
+ const ASSET_SRC = 'https://hosted.castle.games/cauldron-assets/';
19
20
  const DECK_CSP = [
20
21
  "default-src 'self' data: blob:",
21
22
  `script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' data: blob: ${CDN_HOSTS}`,
22
23
  "style-src 'self' 'unsafe-inline' data: blob: https://fonts.googleapis.com",
23
24
  "font-src 'self' data: blob: https://fonts.gstatic.com",
24
- `img-src 'self' data: blob: ${CASTLE_ASSET_HOSTS}`,
25
- `media-src 'self' data: blob: ${CASTLE_ASSET_HOSTS} ${MEDIA_ASSET_SRC}`,
25
+ `img-src 'self' data: blob: ${CASTLE_ASSET_HOSTS} ${ASSET_SRC}`,
26
+ `media-src 'self' data: blob: ${CASTLE_ASSET_HOSTS} ${ASSET_SRC}`,
26
27
  `connect-src 'self' data: blob: ${CDN_HOSTS} ${PLAY_HOSTS} ${CONTENT_PACK_HOSTS} ${CASTLE_ASSET_HOSTS}`,
27
28
  "frame-src 'none'",
28
29
  "child-src 'self' blob:",
@@ -5,6 +5,7 @@ export interface CauldronRoom {
5
5
  startedAt: string;
6
6
  endedAt: string | null;
7
7
  numPlayers: number;
8
+ oversizeDrops: number | null;
8
9
  }
9
10
  export interface CauldronRoomLogLine {
10
11
  at: string | null;
package/dist/roomLogs.js CHANGED
@@ -13,6 +13,9 @@ import { readCastleJson } from './castleJson.js';
13
13
  import * as config from './config.js';
14
14
  const RECENT_ROOMS_LIMIT = 20;
15
15
  const ROOM_FIELDS = 'sessionId deckId env startedAt endedAt numPlayers';
16
+ // Selected separately: a Ghost older than the field rejects the whole document, so the
17
+ // query is retried once without it (see query below).
18
+ const OVERSIZE_FIELD = 'oversizeDrops';
16
19
  const UNAVAILABLE_REASONS = {
17
20
  host_missing: 'the server host that ran this room is gone (hosts are replaced over time), so its logs went with it',
18
21
  host_stale: 'the server host that ran this room has stopped reporting in, so its logs cannot be read',
@@ -31,8 +34,16 @@ const ERROR_CODES = {
31
34
  };
32
35
  export class RoomLogsError extends Error {
33
36
  }
37
+ // `document` builds the query with or without oversizeDrops. A Ghost that predates the
38
+ // field fails validation naming it; then the query runs once more without it and every
39
+ // room's count is unknown (null).
34
40
  async function query(document, variables, field) {
35
- const response = await graphql(document, variables);
41
+ let response = await graphql(document(OVERSIZE_FIELD), variables);
42
+ let withOversize = true;
43
+ if (response.errors?.some((e) => /Cannot query field "oversizeDrops"/.test(e.message ?? ''))) {
44
+ response = await graphql(document(''), variables);
45
+ withOversize = false;
46
+ }
36
47
  const error = response.errors?.[0];
37
48
  if (error)
38
49
  throw new RoomLogsError(describeError(error));
@@ -40,6 +51,10 @@ async function query(document, variables, field) {
40
51
  if (value === undefined || value === null) {
41
52
  throw new RoomLogsError(`The server returned no ${field}.`);
42
53
  }
54
+ if (!withOversize) {
55
+ for (const room of Array.isArray(value) ? value : [value])
56
+ room.oversizeDrops = null;
57
+ }
43
58
  return value;
44
59
  }
45
60
  function describeError(error) {
@@ -54,16 +69,16 @@ function describeError(error) {
54
69
  return visible(code ? `${message} [${code}]` : message);
55
70
  }
56
71
  export function recentRooms(deckId, env, limit = RECENT_ROOMS_LIMIT) {
57
- return query(`query($deckId: ID!, $env: String, $limit: Int) {
72
+ return query((oversize) => `query($deckId: ID!, $env: String, $limit: Int) {
58
73
  cauldronRecentRooms(deckId: $deckId, env: $env, limit: $limit) {
59
- ${ROOM_FIELDS}
74
+ ${ROOM_FIELDS} ${oversize}
60
75
  }
61
76
  }`, { deckId, env, limit }, 'cauldronRecentRooms');
62
77
  }
63
78
  export function roomLogs(deckId, sessionId, env) {
64
- return query(`query($deckId: ID!, $sessionId: ID!, $env: String) {
79
+ return query((oversize) => `query($deckId: ID!, $sessionId: ID!, $env: String) {
65
80
  cauldronRoomLogs(deckId: $deckId, sessionId: $sessionId, env: $env) {
66
- ${ROOM_FIELDS}
81
+ ${ROOM_FIELDS} ${oversize}
67
82
  state logsAvailable logsUnavailableReason endReason exitCode oomKilled droppedLines
68
83
  lines { at stream text }
69
84
  }
@@ -98,12 +113,16 @@ export function formatRooms(deckId, env, rooms) {
98
113
  shortTime(room.startedAt),
99
114
  room.endedAt ? shortTime(room.endedAt) : 'running',
100
115
  String(room.numPlayers),
116
+ hasOversizeDrops(room) ? `${room.oversizeDrops} message${room.oversizeDrops === 1 ? '' : 's'} dropped (over 64 KB)` : '',
101
117
  ].map((cell) => visible(String(cell))));
102
- const header = ['ROOM', 'STARTED', 'ENDED', 'PLAYERS'];
118
+ const header = ['ROOM', 'STARTED', 'ENDED', 'PLAYERS', ''];
103
119
  const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
104
120
  const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();
105
121
  return [`Recent rooms of deck ${deckId} (${env}), newest first:`, line(header), ...rows.map(line)].join('\n');
106
122
  }
123
+ function hasOversizeDrops(room) {
124
+ return typeof room.oversizeDrops === 'number' && room.oversizeDrops > 0;
125
+ }
107
126
  export function formatRoomLogs(logs) {
108
127
  const out = [
109
128
  `Room ${logs.sessionId} of deck ${logs.deckId} (${logs.env})`,
@@ -118,6 +137,11 @@ export function formatRoomLogs(logs) {
118
137
  out.push(` exit code: ${logs.exitCode}`);
119
138
  if (logs.oomKilled)
120
139
  out.push(' killed: out of memory');
140
+ if (hasOversizeDrops(logs)) {
141
+ const n = logs.oversizeDrops;
142
+ out.push(` ${n} server message${n === 1 ? ' was' : 's were'} dropped for being over 64 KB. ` +
143
+ 'Send smaller messages: split the state, or send only what changed.');
144
+ }
121
145
  if (!logs.logsAvailable) {
122
146
  const reason = logs.logsUnavailableReason ?? '';
123
147
  out.push('', `No log lines: ${UNAVAILABLE_REASONS[reason] ?? `unavailable (${reason || 'no reason given'})`}.`);