castle-web-cli 0.4.241 → 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.
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.
@@ -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
  ];
@@ -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:",
package/dist/save-deck.js CHANGED
@@ -534,11 +534,28 @@ async function storeMediaAsset(deckId, asset, busyRetryMs) {
534
534
  // write. Each newly stored asset is fetched once through the CDN, these waits
535
535
  // apart, before a page naming it is published.
536
536
  export const ASSET_SERVED_RETRY_MS = [1000, 2000];
537
+ // A deck reads an asset cross-origin (fetch, a CORS <img>, Web Audio), so served
538
+ // means served with CORS: asked with an Origin, as the deck's browser asks.
539
+ const ASSET_PROBE_ORIGIN = 'https://castle.xyz';
540
+ const servedWithCors = (res) => (res.status === 200 || res.status === 206) && res.headers.get('access-control-allow-origin') === '*';
537
541
  async function assetServed(url) {
538
542
  try {
539
- const res = await fetch(url, { headers: { Range: 'bytes=0-0' }, signal: AbortSignal.timeout(15_000) });
543
+ const res = await fetch(url, {
544
+ headers: { Range: 'bytes=0-0', Origin: ASSET_PROBE_ORIGIN },
545
+ signal: AbortSignal.timeout(15_000),
546
+ });
540
547
  await res.body?.cancel();
541
- return res.status === 200 || res.status === 206;
548
+ return servedWithCors(res);
549
+ }
550
+ catch {
551
+ return false;
552
+ }
553
+ }
554
+ /** An asset already stored and served with CORS (HEAD); anything else is stored again and probed. */
555
+ async function assetAlreadyServed(url) {
556
+ try {
557
+ const res = await fetch(url, { method: 'HEAD', headers: { Origin: ASSET_PROBE_ORIGIN }, signal: AbortSignal.timeout(15_000) });
558
+ return res.status === 200 && servedWithCors(res);
542
559
  }
543
560
  catch {
544
561
  return false;
@@ -575,7 +592,7 @@ export async function uploadMediaAssets(deckId, assets, { busyRetryMs = CHUNK_BU
575
592
  result.refused.push({ asset, code: ASSET_TOO_LARGE });
576
593
  return;
577
594
  }
578
- if (await alreadyStored(asset.url)) {
595
+ if (await assetAlreadyServed(asset.url)) {
579
596
  result.skipped++;
580
597
  return;
581
598
  }
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-11-15T00:40:25.157Z",
85
+ "publishedVersion": "2026-11-18T02:15:05.726Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -2018,6 +2018,13 @@ window.addEventListener("touchstart", (event) => {
2018
2018
  });
2019
2019
  ```
2020
2020
 
2021
+ To open it without changing the deck, the deck's owner adds `?debug=1`
2022
+ to the deck's address on castle.xyz (`https://castle.xyz/d/<deck id>?debug=1`).
2023
+ The page checks that the signed-in viewer owns the deck, and only then
2024
+ opens the console as the deck starts; anyone else gets the deck as
2025
+ usual. It needs a deck saved with SDK 0.4.56 or later, and it works on
2026
+ the website only. In the Castle app, use `DebugConsole.show()`.
2027
+
2021
2028
  ## Setup
2022
2029
 
2023
2030
  Startup, editor-mode check, and a file-write call for editor UI.
@@ -13,6 +13,11 @@ export interface CastleEmbed {
13
13
  * `experiments.get` command instead (experiments.ts).
14
14
  */
15
15
  experiments?: Record<string, string>;
16
+ /**
17
+ * Opens `DebugConsole` as the deck starts. castle.xyz sets it only for the
18
+ * deck's owner, when they add `?debug=1` to the deck's URL.
19
+ */
20
+ debugConsole?: boolean;
16
21
  }
17
22
  declare global {
18
23
  interface Window {
@@ -10,6 +10,7 @@ export interface DebugConsoleApi {
10
10
  hide(): void;
11
11
  lines(): DebugConsoleLine[];
12
12
  }
13
+ export declare const originalConsole: Record<DebugConsoleLevel, (...args: unknown[]) => void>;
13
14
  export declare function formatConsoleArgs(args: unknown[]): string;
14
15
  export declare function recordConsoleLine(level: DebugConsoleLevel, text: string): void;
15
16
  export declare function noteConsoleHooked(): void;
@@ -6,6 +6,10 @@
6
6
  // `setup()` records every console line and uncaught error from the start, so
7
7
  // `show()` reveals what happened before it was called. A deck that never calls
8
8
  // `setup()` gets recording from its first `show()` on.
9
+ //
10
+ // The host can also open it without any deck code (`openForHost` below): on
11
+ // castle.xyz the deck's owner adds `?debug=1` to the deck's URL.
12
+ import { getCastleEmbed } from "./context";
9
13
  const MAX_LINES = 300;
10
14
  const MAX_LINE_CHARS = 2000;
11
15
  const COLORS = {
@@ -13,27 +17,49 @@ const COLORS = {
13
17
  warn: "#ffd66b",
14
18
  error: "#ff8a80",
15
19
  };
20
+ // The console as it was before anything here or in runtime.ts wrapped it.
21
+ // runtime.ts writes through these, so a line is never recorded twice when the
22
+ // host opened the console before the deck called `setup()`.
23
+ export const originalConsole = {
24
+ log: console.log,
25
+ warn: console.warn,
26
+ error: console.error,
27
+ };
16
28
  const recorded = [];
17
29
  let consoleHooked = false;
18
30
  let errorsHooked = false;
19
31
  let panel = null;
20
32
  let list = null;
21
- export function formatConsoleArgs(args) {
22
- return args
23
- .map((arg) => {
33
+ // Never throws, and always a string: a console call the deck makes must not
34
+ // fail because of what it logged (a cyclic object with no prototype, a revoked
35
+ // proxy, an Error whose stack is not a string).
36
+ const UNPRINTABLE = "[unprintable]";
37
+ function formatConsoleArg(arg) {
38
+ try {
24
39
  if (typeof arg === "string")
25
40
  return arg;
26
- if (arg instanceof Error)
27
- return arg.stack || arg.message;
28
- try {
29
- const json = JSON.stringify(arg);
30
- return json ?? String(arg);
41
+ if (arg instanceof Error) {
42
+ const text = arg.stack || arg.message;
43
+ if (typeof text === "string")
44
+ return text;
31
45
  }
32
- catch {
33
- return String(arg);
34
- }
35
- })
36
- .join(" ");
46
+ const json = JSON.stringify(arg);
47
+ if (typeof json === "string")
48
+ return json;
49
+ }
50
+ catch {
51
+ // fall through to String()
52
+ }
53
+ try {
54
+ const text = String(arg);
55
+ return typeof text === "string" ? text : UNPRINTABLE;
56
+ }
57
+ catch {
58
+ return UNPRINTABLE;
59
+ }
60
+ }
61
+ export function formatConsoleArgs(args) {
62
+ return args.map(formatConsoleArg).join(" ");
37
63
  }
38
64
  // runtime.ts's own console hook calls this, so the line is formatted once for
39
65
  // both the dev serve and this buffer.
@@ -74,6 +100,8 @@ function hookConsole() {
74
100
  return;
75
101
  consoleHooked = true;
76
102
  for (const level of ["log", "warn", "error"]) {
103
+ // The console as it is now, so a wrapper the deck installed before
104
+ // calling show() keeps getting its lines.
77
105
  const original = console[level];
78
106
  console[level] = (...args) => {
79
107
  original(...args);
@@ -131,8 +159,12 @@ function show() {
131
159
  return;
132
160
  hookConsole();
133
161
  captureErrors();
134
- if (panel)
162
+ if (panel?.isConnected)
135
163
  return;
164
+ // A deck that replaces the body (innerHTML, replaceChildren) takes the
165
+ // panel with it; draw a new one.
166
+ panel?.remove();
167
+ panel = null;
136
168
  panel = buildPanel();
137
169
  (document.body ?? document.documentElement).appendChild(panel);
138
170
  for (const line of recorded) {
@@ -143,6 +175,7 @@ function show() {
143
175
  }
144
176
  }
145
177
  function hide() {
178
+ stopKeepingOpen();
146
179
  panel?.remove();
147
180
  panel = null;
148
181
  list = null;
@@ -152,3 +185,43 @@ export const DebugConsole = {
152
185
  hide,
153
186
  lines: () => recorded.slice(),
154
187
  };
188
+ // The host decides who sees the console: castle.xyz sets
189
+ // `CastleEmbed.debugConsole` only when the viewer who added `?debug=1` owns the
190
+ // deck (castle-www DeckPlayer). It is in the document before any deck script,
191
+ // so recording starts with the deck. Nothing here reads the deck's own URL:
192
+ // anyone can add a query string, only the host knows who is watching. A deck
193
+ // that sets the flag itself only shows its own console to its own players.
194
+ //
195
+ // Opened this way, the panel comes back when the deck's own startup clears the
196
+ // body (or replaces it), until the owner presses Hide.
197
+ let keepOpen = null;
198
+ function stopKeepingOpen() {
199
+ keepOpen?.disconnect();
200
+ keepOpen = null;
201
+ }
202
+ function openForHost() {
203
+ if (typeof document === "undefined" || getCastleEmbed()?.debugConsole !== true)
204
+ return;
205
+ hookConsole();
206
+ captureErrors();
207
+ const open = () => {
208
+ show();
209
+ if (keepOpen || typeof MutationObserver === "undefined")
210
+ return;
211
+ keepOpen = new MutationObserver(() => {
212
+ if (panel && !panel.isConnected)
213
+ show();
214
+ });
215
+ keepOpen.observe(document.documentElement, { childList: true, subtree: true });
216
+ };
217
+ // A classic script in the head runs before there is a body to draw into.
218
+ // A module deck runs once the document is parsed, still ahead of its own
219
+ // first pass over the body: the observer puts the panel back after that.
220
+ if (document.readyState === "loading") {
221
+ document.addEventListener("DOMContentLoaded", open, { once: true });
222
+ }
223
+ else {
224
+ open();
225
+ }
226
+ }
227
+ openForHost();
@@ -1,6 +1,6 @@
1
1
  import { CASTLE_SDK_PROTOCOL, } from "./commands";
2
2
  import { getCastleEmbed, isEdit } from "./context";
3
- import { captureErrors, formatConsoleArgs, noteConsoleHooked, recordConsoleLine } from "./debugConsole";
3
+ import { captureErrors, formatConsoleArgs, noteConsoleHooked, originalConsole, recordConsoleLine, } from "./debugConsole";
4
4
  import { cardUnit, fitStage, getDisplay } from "./display";
5
5
  import { appliedNotice, applyTunedParams, } from "./paramsRegistry";
6
6
  export const CARD_RATIO = 5 / 7;
@@ -20,9 +20,10 @@ const pendingRequests = new Map();
20
20
  // screenshot/write_file request map above. transport.ts owns the timeouts.
21
21
  const SOCKET_WAIT_TIMEOUT_MS = 10000;
22
22
  const localCommandListeners = new Map();
23
- const origLog = console.log;
24
- const origWarn = console.warn;
25
- const origError = console.error;
23
+ // Not `console.log` itself: the host may have had debugConsole.ts wrap it already.
24
+ const origLog = originalConsole.log;
25
+ const origWarn = originalConsole.warn;
26
+ const origError = originalConsole.error;
26
27
  // Indirected dynamic import so deck bundlers don't statically rewrite it.
27
28
  // eslint-disable-next-line @typescript-eslint/no-implied-eval
28
29
  const dynamicImport = new Function("u", "return import(u)");
@@ -4,11 +4,16 @@ export function makeVisibility(doc = globalThis.document, now = Date.now) {
4
4
  let target = null;
5
5
  let last = null;
6
6
  let listening = false;
7
+ // v1.219: a connection that is not up forgets what was last sent. A send
8
+ // into a socket that died (an app switch) reads as sent; after the rejoin
9
+ // the state is sent again, so the server never keeps a stale hidden.
10
+ const down = () => Boolean(target.net.closed?.() || (target.net.status && target.net.status().state !== 'connected'));
7
11
  const changed = () => {
8
- if (!target || target.net.closed?.()) {
12
+ if (!target) {
9
13
  return;
10
14
  }
11
- if (target.net.status && target.net.status().state !== 'connected') {
15
+ if (down()) {
16
+ last = null;
12
17
  return;
13
18
  }
14
19
  const visible = doc.visibilityState !== 'hidden';
@@ -19,7 +24,9 @@ export function makeVisibility(doc = globalThis.document, now = Date.now) {
19
24
  last = visible;
20
25
  };
21
26
  return {
22
- sync(net, key, enabled) {
27
+ // `admitted`: the hub's count of this connection's re-admissions; a
28
+ // rejoin between two frames, never seen as down, sends again too.
29
+ sync(net, key, enabled, admitted = 0) {
23
30
  if (!enabled || !net || !doc?.addEventListener) {
24
31
  if (listening) {
25
32
  doc.removeEventListener('visibilitychange', changed);
@@ -30,7 +37,10 @@ export function makeVisibility(doc = globalThis.document, now = Date.now) {
30
37
  return;
31
38
  }
32
39
  if (target?.net !== net || target?.key !== key) {
33
- target = { net, key };
40
+ target = { net, key, admitted };
41
+ last = null;
42
+ } else if (target.admitted !== admitted) {
43
+ target.admitted = admitted;
34
44
  last = null;
35
45
  }
36
46
  if (!listening) {
@@ -424,9 +424,10 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
424
424
  typeof data.visible !== 'boolean' || !Number.isFinite(data.at) || data.at < 0) {
425
425
  return;
426
426
  }
427
- if (entry.visibility && (data.at < entry.visibility.at || data.visible === entry.visibility.visible)) {
427
+ if (entry.visibility && (data.at < entry.visibility.at || (data.visible === entry.visibility.visible && !entry.visibilityRejoined))) {
428
428
  return;
429
429
  }
430
+ delete entry.visibilityRejoined;
430
431
  entry.visibility = { visible: data.visible, at: data.at };
431
432
  entry.visibilityPending = true;
432
433
  notifyVisibility(h, player.playerId);
@@ -1549,7 +1550,9 @@ function hello(h, player, data, synthetic = false) {
1549
1550
  !accountProgressBlocked(h, progressUser);
1550
1551
  const entry = {
1551
1552
  // Who this is, kept for `leave`: by then the session has forgotten them.
1552
- ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending } : {}),
1553
+ // v1.219: a rejoin's first signal is taken even when it repeats the kept
1554
+ // value: the client may have sent its change into the socket that died.
1555
+ ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending, ...(data.again !== true ? { visibilityRejoined: true } : known.visibilityRejoined ? { visibilityRejoined: true } : {}) } : {}),
1553
1556
  userId: progressUser,
1554
1557
  ...((known || poseBack) && claimedPose ? { arrivalPose: { ...claimedPose, userId: poseOwner } } : {}),
1555
1558
  username: usernameOf(h, player.playerId),
@@ -646,7 +646,7 @@ class HubSystem {
646
646
  }
647
647
  if (Hub.hub.place?.visibility === true || this.visibility) {
648
648
  this.visibility ??= makeVisibility();
649
- this.visibility.sync(mp.net, this.sceneKey, Hub.hub.place?.visibility === true && !this.trip);
649
+ this.visibility.sync(mp.net, this.sceneKey, Hub.hub.place?.visibility === true && !this.trip, this.admitEpoch ?? 0);
650
650
  }
651
651
  const held = Hub.hub.held.has(mp.net?.selfId?.());
652
652
  const fallY = activeFallY(Hub.hub.place?.fallY, held, Boolean(this.trip));
@@ -1748,6 +1748,7 @@ class HubSystem {
1748
1748
  // cover, and what the page holds is the place as it was before they left:
1749
1749
  // the way back starts under the trip's cover, with no door beat over it.
1750
1750
  const covered = mp.returning?.() === true;
1751
+ const placeTitle = Hub.hub.place?.title;
1751
1752
  Hub.clear();
1752
1753
  if (inGame && scene.persistent.hubTickets.length) {
1753
1754
  this.toast = { text: 'The game ended', until: performance.now() + TOAST_MS };
@@ -1760,8 +1761,14 @@ class HubSystem {
1760
1761
  } else if (!inGame && !refused && mp.target?.mode === 'hub') {
1761
1762
  console.warn('[hub-door] this place ended under a hub join behind a door: leaving by its way back');
1762
1763
  const title = scene.persistent.hubTickets.at(-1)?.title;
1764
+ // Seen on coming back from away, the place most likely ended because it
1765
+ // stood empty past its reconnect window (an owner's House left alone),
1766
+ // not because a new version was saved: say what the player can know.
1767
+ const ended = covered
1768
+ ? `${placeTitle || 'This place'} closed while you were away.`
1769
+ : 'This place was updated.';
1763
1770
  this.toast = {
1764
- text: title ? `This place was updated. Back to ${title}…` : 'This place was updated. Going back…',
1771
+ text: title ? `${ended} Back to ${title}…` : `${ended} Going back…`,
1765
1772
  until: performance.now() + TOAST_MS,
1766
1773
  };
1767
1774
  this.back(scene, { covered });
@@ -721,7 +721,11 @@ suppressed. The chip fits within 94vw and its personal line ellipsizes.
721
721
  server stopped): a game is left as before ("The game ended", then its way
722
722
  back); any other place reached through a door (the host's trail holds the
723
723
  trip) is left by its way back at once, with a line saying it was updated
724
- ("This place was updated. Back to <the place left>…"), and is entered again
724
+ ("This place was updated. Back to <the place left>…"), or, when the ending
725
+ is seen as the player comes back from away (`multiplayer.returning()`), that
726
+ it closed while they were away (v1.220; "<this place's title> closed while you
727
+ were away. Back to <the place left>…"; an owner's House left empty past its
728
+ reconnect window ends this way, nothing was saved), and is entered again
725
729
  through its door, which acquires the new version and its content. A join
726
730
  cannot be made again from inside such a place: its handoff is spent, and
727
731
  only a door's acquisition names the release to mount. The way back is asked
@@ -3685,7 +3689,10 @@ the deck's arrival hook. The kit calls the optional server hook
3685
3689
  The sender identity comes from the session; a payload cannot name another player.
3686
3690
  Malformed, duplicate-state and older-timestamp messages are ignored. `at` is
3687
3691
  untrusted metadata, never server simulation time or proof of elapsed time.
3688
- A place may pause its own guidance clocks while hidden and restore its UI on
3692
+ After any reconnect (v1.219) the client sends its current state again, and
3693
+ the server delivers a retained rejoin's first signal even when it repeats the
3694
+ kept value, so a change sent into a socket that died unseen is not lost and a
3695
+ place never keeps a stale hidden or visible. A place may pause its own guidance clocks while hidden and restore its UI on
3689
3696
  visible. This does not itself reconnect, arrive, leave or change progression;
3690
3697
  the existing `resume` hook remains independent.
3691
3698
 
@@ -5305,6 +5312,8 @@ a deck written before them remains valid.
5305
5312
 
5306
5313
  | date | change |
5307
5314
  | --- | --- |
5315
+ | 2026-11-18 (v1.220) | §"A place replaced under its players" copy: when the ending is seen as the player comes back from away (`multiplayer.returning()`), the line is "<this place's title> closed while you were away. Back to <the place left>…" ("This place closed while you were away…" with no title) instead of "This place was updated", which was not true for an owner's House left empty past its reconnect window. A player who was present still sees the updated line. Copy only: no key, API or wire change. |
5316
+ | 2026-11-18 (v1.219) | §12 page visibility after a rejoin: a client whose connection is not up forgets the state it last sent and sends its current state once it is connected again (a send into a socket that died unseen, as on an app switch, no longer leaves the server holding a stale hidden); the server takes a rejoin's first `hub-visibility` even when it repeats the kept value, then coalesces as before. An avatar-change hello is not a rejoin. No new key or wire field. |
5308
5317
  | 2026-11-17 (v1.218) | Kit-internal, server only, no deck-facing key or API and no wire change: §5 two bodies never start on one spot. A body admitted with no pose where another body takes the scene spawn or the slot its lone arrival would take starts where that arrival will put it (the arrival slot if free, else the free spot beside it; one helper decides both) before its WORLD goes out, so that WORLD is the one placement its client makes, at once; arriving alone it stays there while the spot is still free, and a group with such a member takes the row's slots in the order its members stand along it. An arrival slot (an arrival, and the arrival a fall or a Stuck? unstick puts a player at) or stored pose (cold `resumePose`, arrival pose, retained visit) that another body takes is likewise stepped off on every place, not only on authored floors (`ground.none: true`); a free slot or pose is used exactly. A body takes a spot when it is nearer than two radii and overlaps it in height (one on a floor above or below does not), and only while its player is on the roster (real-time admits a joiner before it removes the bodies of players who left that tick). A group row's later slots are held where a body would stand in them. The search uses the place's own body size and treats a spot past the ground slab's edge (`ground.half`, 100 m by default) as unsupported unless an authored solid holds it; when every candidate fails the slot is shared, as before. Ground-backed places (the Town) kept the spawn for everyone, so two lone joiners stood on exactly the same point; on each client the two capsules were coaxial, Rapier pushed the local one into the ground under the other's avatar, and it could not walk until one left (Nov 17 Market check, reproduced locally). A stepped-off cold restore still reaches its client as the restore always has. Tests: `test-placeat-server` stepoff, arrivalFree and arrivalTaken (WORLD before hello, reports and corrections on: the client moves once), restoreFree, restoreOccupied; `test-standing` slab edge, floors, a leaver on the same tick and an elevated row, `test-rehello` and `test-stuck` updated; physics-3d `test-coaxial-escape`. |
5309
5318
  | 2026-11-10 | `hub.loadingCover` copy and timing: a return's cover (backgrounded 30 s or more, or a dropped connection, after the first load lifted) is plain black, with no title, words or spinner, while hidden and for its first 2.5 s after the page shows; then it says "Reconnecting…" with the spinner. The first load keeps the deck title. The multiplayer-3d kit's return cover is quiet for the same 2.5 s. Most returns are back sooner (measured 2.1-2.4 s past a 180 s app switch). No wire change. Within `hub.contract: 1`. |
5310
5319
  | 2026-11-10 | Kit-internal, no deck-facing key or API: a connection that comes back under a new player id on the same page (a drop past the place's hold, such as 180 s backgrounded) keeps the camera yaw and the avatar's facing through the new session's `hub-arrived`, instead of turning to the arrival facing (the Town turned every such return to its spawn bearing). A trip's arrival, the first join and an arrival on another connection face as before. Within `hub.contract: 1`. |
@@ -960,10 +960,34 @@ await test('a place behind a door whose server is replaced under a player: left
960
960
  system.lastNet = closedNet();
961
961
  system.watchSession(scene, scene.multiplayer);
962
962
  assert.ok(system.trip, `${place.title}: on its way back`);
963
+ assert.equal(system.toast.text, place.result
964
+ ? 'The game ended'
965
+ : `${place.title} closed while you were away. Back to Town…`);
963
966
  system.stepTrip(scene, scene.multiplayer, null, performance.now());
964
967
  assert.equal(covers[0], 1, `${place.title}: the first cover drawn is fully down`);
965
968
  await flush();
966
969
  }
970
+ // An owner's House torn down while they were away (empty past its reconnect
971
+ // window): the line says it closed, not that it was updated; with no title
972
+ // or no ticket it still reads true.
973
+ for (const [place, tickets, text] of [
974
+ [{ title: 'House' }, undefined, 'House closed while you were away. Back to Town…'],
975
+ [{ title: null }, undefined, 'This place closed while you were away. Back to Town…'],
976
+ [{ title: 'House' }, [], 'House closed while you were away. Going back…'],
977
+ ]) {
978
+ const { system, scene } = setup();
979
+ scene.multiplayer = { ...mpStub(scene), net: null, returning: () => true };
980
+ scene.multiplayer.target = { mode: 'hub', handoff: { sessionId: 'house-1' } };
981
+ scene.persistent.hubDepth = 1;
982
+ scene.persistent.hubTickets = tickets ?? [{ scene: 'scenes/main.scene', title: 'Town', door: 'home', hub: true, join: { mode: 'public' } }];
983
+ HubState.hub.place = place;
984
+ answers.back = handoff();
985
+ system.lastNet = closedNet();
986
+ system.watchSession(scene, scene.multiplayer);
987
+ assert.equal(system.toast.text, text);
988
+ assert.ok(system.trip, 'on its way back');
989
+ await flush();
990
+ }
967
991
  // Not returning: the beat plays, and the cover comes down over it.
968
992
  {
969
993
  const { system, scene } = setup();
@@ -131,4 +131,58 @@ assert.deepEqual(mounted, [false, true]);
131
131
  secondClient.sync(null, null, false);
132
132
  shownDoc.visibilityState = 'hidden'; shownDoc.dispatchEvent(new Event('visibilitychange'));
133
133
  assert.deepEqual(mounted, [false, true], 'disposed listener cannot send to its old net');
134
+ // v1.219: an app switch kept the socket while hidden; the return's visible
135
+ // went into the dead socket, which still read connected. After the rejoin
136
+ // the client sends its state again.
137
+ {
138
+ const got = [];
139
+ const doc2 = new EventTarget(); doc2.visibilityState = 'visible';
140
+ let state = 'connected', dead = false;
141
+ const net2 = { status: () => ({ state }), send: (data) => { if (!dead) got.push(data.visible); } };
142
+ const v = makeVisibility(doc2, () => ++at);
143
+ v.sync(net2, 'main', true);
144
+ doc2.visibilityState = 'hidden'; doc2.dispatchEvent(new Event('visibilitychange'));
145
+ dead = true; // the socket died while away, unseen
146
+ doc2.visibilityState = 'visible'; doc2.dispatchEvent(new Event('visibilitychange'));
147
+ state = 'reconnecting'; v.sync(net2, 'main', true);
148
+ dead = false; state = 'connected'; v.sync(net2, 'main', true);
149
+ v.sync(net2, 'main', true);
150
+ assert.deepEqual(got, [true, false, true], 'the rejoin sends visible again, once');
151
+ v.sync(null, null, false);
152
+ }
153
+ // v1.219: a rejoin between two frames is never seen as down; the hub's
154
+ // re-admission count says it, and the state is sent again.
155
+ {
156
+ const got = [];
157
+ const doc3 = new EventTarget(); doc3.visibilityState = 'visible';
158
+ let dead = false;
159
+ const net3 = { status: () => ({ state: 'connected' }), send: (data) => { if (!dead) got.push(data.visible); } };
160
+ const v = makeVisibility(doc3, () => ++at);
161
+ v.sync(net3, 'main', true, 0);
162
+ doc3.visibilityState = 'hidden'; doc3.dispatchEvent(new Event('visibilitychange'));
163
+ dead = true;
164
+ doc3.visibilityState = 'visible'; doc3.dispatchEvent(new Event('visibilitychange'));
165
+ dead = false;
166
+ v.sync(net3, 'main', true, 0);
167
+ assert.deepEqual(got, [true, false], 'no rejoin seen yet');
168
+ v.sync(net3, 'main', true, 1);
169
+ v.sync(net3, 'main', true, 1);
170
+ assert.deepEqual(got, [true, false, true], 'the re-admission sends visible again, once');
171
+ v.sync(null, null, false);
172
+ }
173
+ // v1.219: the server takes a rejoin's first signal even when it repeats the
174
+ // kept value, then coalesces again.
175
+ {
176
+ const seen = [];
177
+ const s = boot({ visibility: true }, { hooks: { visibility(hub, info) { seen.push(info.visible); } } });
178
+ s.tick();
179
+ s.say('p1', { k: 'hub-visibility', visible: false, at: 5000 }); s.tick();
180
+ s.say('p1', { k: 'hub-hello', avatar: 0, resume: true }); s.tick();
181
+ s.say('p1', { k: 'hub-visibility', visible: false, at: 5001 }); s.tick();
182
+ s.say('p1', { k: 'hub-visibility', visible: false, at: 5002 }); s.tick();
183
+ assert.deepEqual(seen, [false, false], 'the first after the rejoin is taken, the next repeat is not');
184
+ s.say('p1', { k: 'hub-hello', avatar: 1, again: true }); s.tick();
185
+ s.say('p1', { k: 'hub-visibility', visible: false, at: 5003 }); s.tick();
186
+ assert.deepEqual(seen, [false, false], 'an avatar change is no rejoin');
187
+ }
134
188
  console.log('test-visibility: ok');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.241",
3
+ "version": "0.4.242",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"