@wildshard/engine 0.1.15 → 0.1.17

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 (207) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/index.html +157 -11
  3. package/lint/engine-sides.json +16 -0
  4. package/lint/host-register.json +496 -0
  5. package/lint/ratchet.json +2 -2
  6. package/lint/shard-imports.d.mts +1 -0
  7. package/lint/shard-imports.mjs +56 -8
  8. package/lint/wildshard-plugin.js +22 -4
  9. package/package.json +16 -5
  10. package/scripts/app-build/buildIdentity.d.mts +3 -1
  11. package/scripts/app-build/buildIdentity.mjs +25 -5
  12. package/scripts/app-build/builtAt.d.mts +4 -0
  13. package/scripts/app-build/builtAt.mjs +21 -0
  14. package/scripts/app-build/serviceWorker.ts +16 -2
  15. package/scripts/app-build/versionFiles.ts +2 -1
  16. package/scripts/app-build-pipeline.mjs +4 -1
  17. package/scripts/audio-download-proof.mjs +843 -0
  18. package/scripts/build-app.mjs +4 -0
  19. package/scripts/build-mirror.d.mts +2 -0
  20. package/scripts/build-mirror.mjs +5 -4
  21. package/scripts/built-product.mjs +3 -3
  22. package/scripts/cell-mem/metrics-preload.mjs +65 -0
  23. package/scripts/cell-mem-bench.mjs +130 -0
  24. package/scripts/check-chunks.mjs +2 -1
  25. package/scripts/devserver-client.d.mts +5 -0
  26. package/scripts/devserver-client.mjs +68 -0
  27. package/scripts/engine-ci-budget.ts +7 -1
  28. package/scripts/format-lock.mjs +20 -11
  29. package/scripts/generate-title-launch.mjs +3 -2
  30. package/scripts/grid-crossing-walk-proof.mjs +16 -8
  31. package/scripts/heavy-lane.py +25 -1
  32. package/scripts/host-ruler/register-migrate.mjs +242 -0
  33. package/scripts/host-ruler/register.d.mts +36 -0
  34. package/scripts/host-ruler/register.mjs +116 -0
  35. package/scripts/host-ruler/roots.d.mts +29 -0
  36. package/scripts/host-ruler/roots.mjs +333 -0
  37. package/scripts/host-ruler/server-roots.d.mts +23 -0
  38. package/scripts/host-ruler/server-roots.mjs +272 -0
  39. package/scripts/main-watch.d.mts +1 -1
  40. package/scripts/main-watch.mjs +10 -6
  41. package/scripts/map-hash.mjs +3 -6
  42. package/scripts/mmo-bots.mjs +2 -2
  43. package/scripts/offline-proof-rules.d.mts +1 -0
  44. package/scripts/offline-proof-rules.mjs +22 -1
  45. package/scripts/online-rig.mjs +4 -4
  46. package/scripts/page-release/flow.d.mts +1 -0
  47. package/scripts/page-release/flow.mjs +6 -2
  48. package/scripts/page-release.mjs +5 -1
  49. package/scripts/physics-route.json +0 -71
  50. package/scripts/pins-catalogue.ts +103 -0
  51. package/scripts/pins-reuse.mjs +3 -1
  52. package/scripts/pins.ts +22 -14
  53. package/scripts/preview-grid.ts +203 -0
  54. package/scripts/road-preload-proof.mjs +167 -0
  55. package/scripts/server-release/publish.mjs +2 -2
  56. package/scripts/server-release/served-slug.d.mts +2 -0
  57. package/scripts/server-release/served-slug.mjs +10 -0
  58. package/scripts/server-release/sign.d.mts +1 -0
  59. package/scripts/server-release/sign.mjs +3 -7
  60. package/scripts/shard-components.mjs +0 -2
  61. package/scripts/shard-outputs.d.mts +8 -0
  62. package/scripts/shard-outputs.mjs +45 -11
  63. package/scripts/side-parity.d.mts +2 -1
  64. package/scripts/side-parity.mjs +25 -4
  65. package/scripts/test-amber.d.mts +1 -0
  66. package/scripts/test-amber.mjs +10 -0
  67. package/scripts/test-products.json +3 -3
  68. package/scripts/tracked-public.d.mts +1 -0
  69. package/scripts/tracked-public.mjs +17 -0
  70. package/src/cli/engine.mjs +8 -0
  71. package/src/client/app/bootRoute.ts +4 -1
  72. package/src/client/app/dropModal.ts +15 -2
  73. package/src/client/app/entry.ts +67 -11
  74. package/src/client/app/slugPath.ts +5 -0
  75. package/src/client/engine/audio/Audio.ts +20 -2
  76. package/src/client/engine/boot/bakedTextures.ts +3 -2
  77. package/src/client/engine/boot/bootTrace.ts +6 -1
  78. package/src/client/engine/boot/bytes.ts +4 -3
  79. package/src/client/engine/boot/clearDownloads.ts +1 -1
  80. package/src/client/engine/boot/contentRead.ts +4 -0
  81. package/src/client/engine/boot/dropNotice.ts +20 -6
  82. package/src/client/engine/boot/gpuFiles.ts +25 -2
  83. package/src/client/engine/boot/lastEnd.ts +8 -2
  84. package/src/client/engine/boot/shardPrefetch.ts +7 -1
  85. package/src/client/engine/boot/sw.ts +19 -0
  86. package/src/client/engine/core/Game.ts +11 -3
  87. package/src/client/engine/core/GpuRecovery.ts +7 -0
  88. package/src/client/engine/core/Volumetrics.ts +5 -0
  89. package/src/client/engine/core/assets.ts +27 -20
  90. package/src/client/engine/core/bootstrap.ts +1 -2
  91. package/src/client/engine/core/ktx2.ts +84 -11
  92. package/src/client/engine/explore/Compare.ts +2 -2
  93. package/src/client/engine/explore/TouchFly.ts +3 -5
  94. package/src/client/engine/input/dom.ts +12 -0
  95. package/src/client/engine/net/predictor.ts +6 -2
  96. package/src/client/engine/player/Player.ts +10 -2
  97. package/src/client/engine/player/TouchControls.ts +12 -4
  98. package/src/client/engine/pwa/sw.js +47 -8
  99. package/src/client/engine/render/drawCheck.ts +96 -0
  100. package/src/client/engine/saves/staleBuildNote.ts +46 -0
  101. package/src/client/engine/telemetry/browserErrors.ts +157 -20
  102. package/src/client/engine/telemetry/screenOutbox.ts +61 -0
  103. package/src/client/engine/telemetry/staleBuildReport.ts +12 -0
  104. package/src/client/engine/ui/DeathFade.ts +99 -11
  105. package/src/client/engine/ui/ErrorModal.ts +13 -6
  106. package/src/client/engine/ui/Feedback.ts +2 -1
  107. package/src/client/engine/ui/Loading.ts +10 -6
  108. package/src/client/engine/ui/Map.ts +2 -1
  109. package/src/client/engine/ui/WeaponStrip.ts +2 -1
  110. package/src/client/engine/ui/backGuard.ts +104 -0
  111. package/src/client/engine/ui/hudAdapters.ts +30 -4
  112. package/src/client/engine/ui/loading.css +17 -0
  113. package/src/client/engine/ui/namePrompt.ts +6 -5
  114. package/src/client/engine/ui/styles/combat.css +12 -0
  115. package/src/client/engine/ui/styles/namePrompt.css +4 -2
  116. package/src/client/game/boot/audio.generated.ts +0 -294
  117. package/src/client/game/boot/bytes.generated.ts +0 -11
  118. package/src/client/game/boot/versions.generated.ts +0 -11
  119. package/src/client/game/compendium/keepsakes.ts +16 -6
  120. package/src/client/game/grapple/tool.ts +10 -7
  121. package/src/client/game/grid/cellLoading.ts +23 -12
  122. package/src/client/game/grid/cellScreens.ts +39 -74
  123. package/src/client/game/grid/liveSession.ts +40 -7
  124. package/src/client/game/grid/nearPlaceholderPlan.ts +8 -0
  125. package/src/client/game/grid/nearPlaceholderView.ts +9 -3
  126. package/src/client/game/grid/oneWayIn.ts +92 -27
  127. package/src/client/game/grid/pageEntry.ts +19 -0
  128. package/src/client/game/grid/pageShell.ts +1 -1
  129. package/src/client/game/grid/plotAudio.ts +114 -0
  130. package/src/client/game/grid/products.ts +55 -5
  131. package/src/client/game/grid/roadLookPlatform.ts +2 -2
  132. package/src/client/game/grid/session.ts +38 -22
  133. package/src/client/game/grid/spawnGround.ts +68 -0
  134. package/src/client/game/grid/voidLook.ts +29 -23
  135. package/src/client/game/loot/runtime.ts +3 -1
  136. package/src/client/game/mainMenu.ts +14 -6
  137. package/src/client/game/riding/hud.ts +6 -4
  138. package/src/client/game/session/finish.ts +17 -3
  139. package/src/client/game/session/play.ts +8 -2
  140. package/src/client/game/session/session.ts +4 -1
  141. package/src/client/game/shardfile/clientWorker.ts +41 -12
  142. package/src/client/game/shardfile/serverRoute.ts +10 -22
  143. package/src/client/game/slugPage.css +11 -0
  144. package/src/client/game/slugPage.ts +84 -0
  145. package/src/client/game/systems/viewmodel/heldView.ts +6 -3
  146. package/src/client/game/titleDeck.ts +55 -32
  147. package/src/client/host/online/doctor.ts +7 -6
  148. package/src/client/host/online/linkScreens.ts +16 -0
  149. package/src/client/host/online/release.ts +51 -5
  150. package/src/client/host/online/shell.ts +48 -27
  151. package/src/client/host/standalone/shell.ts +7 -3
  152. package/src/cook/game/audioReport.ts +57 -0
  153. package/src/cook/game/entryTotals.ts +26 -6
  154. package/src/cook/game/installedRuntimeReads.ts +3 -0
  155. package/src/server/engine/sim/respawn.ts +6 -1
  156. package/src/server/engine/sim.ts +3 -0
  157. package/src/server/game/grid/simulation.ts +35 -0
  158. package/src/server/game/loot/harvest.ts +2 -0
  159. package/src/server/game/loot/keepsakeProgression.ts +40 -0
  160. package/src/server/game/loot/playerOwned.ts +5 -1
  161. package/src/server/game/plugin/simulation.ts +4 -0
  162. package/src/server/game/population/nativeBake.ts +2 -1
  163. package/src/server/game/quest/chapterRecords.ts +2 -0
  164. package/src/server/game/quest/serverChapters.ts +4 -0
  165. package/src/server/game/quest/serverDoors.ts +11 -5
  166. package/src/server/game/roomRespawn.ts +4 -0
  167. package/src/server/game/shardfile/installedSides.ts +18 -0
  168. package/src/server/game/shardfile/nativeAssemblyHosts.ts +19 -10
  169. package/src/server/game/shardfile/nativeAssemblyInput.ts +1 -4
  170. package/src/server/host/bake/headlessWorker.ts +5 -1
  171. package/src/server/host/dedicated/cellHost.ts +98 -29
  172. package/src/server/host/dedicated/cellProtocol.ts +11 -1
  173. package/src/server/host/dedicated/cellWorker.ts +9 -3
  174. package/src/server/host/dedicated/crossing.ts +6 -2
  175. package/src/server/host/dedicated/dedicatedRoom.ts +21 -8
  176. package/src/server/host/dedicated/gridCells.ts +52 -9
  177. package/src/server/host/dedicated/main.ts +31 -12
  178. package/src/server/host/dedicated/placementFile.ts +72 -0
  179. package/src/server/host/dedicated/releaseFile.ts +17 -10
  180. package/src/server/host/dedicated/roadRoom.ts +21 -5
  181. package/src/server/host/dedicated/workerTable.ts +13 -1
  182. package/src/server/host/dedicated/world.ts +81 -9
  183. package/src/server/host/headlessRuntime.ts +10 -5
  184. package/src/server/host/installers.ts +62 -0
  185. package/src/server/host/openWorld.ts +59 -0
  186. package/src/server/host/ropeDecks.ts +2 -0
  187. package/src/server/host/standalone/cellWorld.ts +25 -19
  188. package/src/server/host/standalone/fallFloor.ts +2 -2
  189. package/src/server/host/standalone/gridServer.ts +7 -4
  190. package/src/server/host/standalone/roadWorld.ts +41 -4
  191. package/src/shared/engine/audio/bootAudio.ts +33 -0
  192. package/src/shared/engine/level/spec.ts +3 -3
  193. package/src/shared/engine/net/acts.ts +3 -0
  194. package/src/shared/engine/physics/query.ts +27 -0
  195. package/src/shared/engine/physics/terrain.ts +19 -28
  196. package/src/shared/engine/saves/saves.lock.json +15 -0
  197. package/src/shared/engine/sim/actRoutes.ts +2 -0
  198. package/src/shared/game/compendium/keepsakeProgression.ts +24 -0
  199. package/src/shared/game/grid/catalogue.ts +12 -5
  200. package/src/shared/game/grid/catalogueSlot.ts +11 -0
  201. package/src/shared/game/grid/farProxy.ts +6 -5
  202. package/src/shared/game/grid/pageMode.ts +1 -1
  203. package/src/shared/game/grid/roadLayout.ts +26 -3
  204. package/src/shared/game/grid/singleplayer.json +0 -13
  205. package/src/shared/game/grid/voidFloor.ts +122 -0
  206. package/src/shared/game/strings.ts +15 -0
  207. package/src/shared/host/standalone/netInput.ts +2 -1
@@ -1,7 +1,7 @@
1
1
  import { mountUi } from '../ui/ownership';
2
2
  import { mountBoostLook } from '../ui/hoverBoost';
3
3
  import { app } from '../app/runtime';
4
- import { listenDom } from '../input/dom';
4
+ import { capturePointer, listenDom, listenPage } from '../input/dom';
5
5
  import type { Action, TouchStack, TouchVerbSpec } from '../input/InputService';
6
6
  import { engineString } from '../../../shared/engine/strings';
7
7
  /**
@@ -123,6 +123,8 @@ export class TouchControls {
123
123
  private readonly scope = (app.levelScope ?? app.engineScope).child('touch');
124
124
  readonly active: boolean;
125
125
  private stickPointer = -1; private lookPointer = -1; private attackPointer = -1;
126
+ /** fingers the stick, look or attack hold whose capture the browser refused (capturePointer): released from the window too */
127
+ private readonly uncaptured = new Set<number>();
126
128
  private stickBase = { x: 0, y: 0 };
127
129
  private lookLast = { x: 0, y: 0 };
128
130
  private attackLast = { x: 0, y: 0 }; private attackPath = 0; private attackT0 = 0; // the ATTACK touch: last spot, px travelled, start time
@@ -299,7 +301,7 @@ export class TouchControls {
299
301
  this.flick.begin(e.clientX, e.clientY, this.lookT0);
300
302
  lookpad.classList.toggle('active', inBar);
301
303
  } else return;
302
- root.setPointerCapture(e.pointerId);
304
+ if (!capturePointer(root, e.pointerId)) this.uncaptured.add(e.pointerId);
303
305
  e.preventDefault();
304
306
  });
305
307
  listenDom(this.scope, root, 'pointermove', (e) => {
@@ -348,6 +350,12 @@ export class TouchControls {
348
350
  };
349
351
  listenDom(this.scope, root, 'pointerup', release);
350
352
  listenDom(this.scope, root, 'pointercancel', release);
353
+ // WILDSHARD-GAME-2M (QA 2026-11-13 row 6): Android Chrome can refuse a capture (the touch already handed to the browser).
354
+ // That finger's lift can then land outside the layer, and the stick, look or attack stayed held: the next touch on it
355
+ // was ignored ("couldn't control anything"). An uncaptured finger is released from the window as well.
356
+ for (const type of ['pointerup', 'pointercancel'] as const) {
357
+ listenPage(this.scope, type, (e) => { if (this.uncaptured.delete(e.pointerId)) release(e); }, { capture: true });
358
+ }
351
359
 
352
360
  // ── ATTACK / FIRE: fires on touch-down; the disc then captures the touch (its move / up events bubble to the layer's
353
361
  // handlers above), so a drag from it turns the camera while the finger is held and a still hold (melee) becomes the
@@ -359,7 +367,7 @@ export class TouchControls {
359
367
  if (this.attackPointer >= 0) return; // one finger on the disc at a time
360
368
  this.attackPointer = e.pointerId;
361
369
  this.attackLast = { x: e.clientX, y: e.clientY }; this.attackPath = 0; this.attackT0 = performance.now();
362
- attack.setPointerCapture(e.pointerId);
370
+ if (!capturePointer(attack, e.pointerId)) this.uncaptured.add(e.pointerId);
363
371
  attack.classList.add('down');
364
372
  if (!this.weapons.enabled) return;
365
373
  this.weapons.tryFire(); // the bow: only the dry click on an empty quiver — its draw is the hold
@@ -458,7 +466,7 @@ export class TouchControls {
458
466
  const own = button; root.append(own); this.verbs.set(slot, own);
459
467
  const pointers = new Set<number>();
460
468
  listenDom(this.scope, own, 'pointerdown', (event) => {
461
- event.preventDefault(); event.stopPropagation(); pointers.add(event.pointerId); own.setPointerCapture(event.pointerId);
469
+ event.preventDefault(); event.stopPropagation(); pointers.add(event.pointerId); capturePointer(own, event.pointerId);
462
470
  const current = this.verbActions[slot]; if (current === undefined || pointers.size !== 1) return;
463
471
  const live = this.verbSpecs[slot];
464
472
  if (live?.hold === true) { this.heldVerbs.set(slot, current); app.input.setHeld(current, true); } else app.input.press(current);
@@ -8,7 +8,13 @@ const ASSETS = '__ASSET_CACHE__';
8
8
  const BOOKS = 'ws-builds-v1';
9
9
  const SHELL_PREFIX = 'ws-shell-v3-';
10
10
  const SHELL = `${SHELL_PREFIX}${BUILD}`;
11
+ /** OFFLINE OF5 (J298): a world build (its document stamped with `__WS_WORLD__`; play, staging) never runs the in-page solo
12
+ * server, so it never precaches the solo server's code or its server book. Read at run time: a deploy stamps the document. */
13
+ const WORLD = /\bglobalThis\.__WS_WORLD__=/u.test(DOCUMENT);
14
+ const SOLO_ONLY = /\/standalone\/(?:serverWorker|serverRuntime)-[^/]+\.js$|\/assets\/spawn\/server-[^/]+\.json$/u;
11
15
  const FILES = JSON.parse('__FILES__');
16
+ /** What this build precaches and records as its generation: its files, less the solo server's on a world build. */
17
+ const PRECACHE_FILES = FILES.filter(path => !WORLD || !SOLO_ONLY.test(path));
12
18
  const SHELL_FILES = JSON.parse('__SHELL_FILES__');
13
19
  const NAMED = new Set(FILES);
14
20
  const MATCH = { ignoreVary: true };
@@ -16,8 +22,11 @@ const abs = path => new URL(path, self.registration.scope).href;
16
22
  const bookKey = build => abs(`/__ws_build__/${encodeURIComponent(build)}`);
17
23
  const CONTENT = /-[a-f0-9]{8,64}\.[a-z0-9]+$|\/[a-f0-9]{64}\.[a-z0-9]+$/;
18
24
  const HASH = /\/([a-f0-9]{64})\.[a-z0-9]+$/;
25
+ /** OF5: a spawn manifest's code list (`code/<sha16>.json`) is named by its own bytes too, so it is kept across builds: an
26
+ * update's first offline launch still reads the route's code list. */
27
+ const OWN_NAMED = /^\/assets\/spawn\/code\/[a-f0-9]{16}\.json$/;
19
28
  /** @param {URL} url */
20
- const immutable = url => NAMED.has(url.pathname) || url.pathname.startsWith('/b/') || CONTENT.test(url.pathname)
29
+ const immutable = url => NAMED.has(url.pathname) || url.pathname.startsWith('/b/') || CONTENT.test(url.pathname) || OWN_NAMED.test(url.pathname)
21
30
  || /^[a-f0-9]{8,64}$/.test(url.searchParams.get('v') ?? '');
22
31
  const isHtml = response => /\btext\/html\b/i.test(response.headers.get('content-type') ?? '');
23
32
  /* PAGE-SIZE PZ10 (J276): content on the content base (`https://packs.wildshard.io/content/<set>/`, baked from the boot
@@ -26,6 +35,8 @@ const isHtml = response => /\btext\/html\b/i.test(response.headers.get('content-
26
35
  * kept: an opaque body cannot be checked and is padded against quota, and a range never stands for the whole file. */
27
36
  /** @type {{ base: string, files: string[] }} one parsed value: the bundler would fold a literal base into its origin */
28
37
  const { base: CONTENT_BASE, files: CONTENT_FILES } = JSON.parse('__CONTENT__');
38
+ /** OF5: the server book on the content base is solo-only too (a URL there, its path under the base's folder). */
39
+ const CONTENT_PRECACHE = CONTENT_FILES.filter(href => !WORLD || !SOLO_ONLY.test(new URL(href).pathname));
29
40
  const CONTENT_CACHE = 'ws-content-v1';
30
41
  const CONTENT_URL = CONTENT_BASE === '' ? undefined : new URL(CONTENT_BASE);
31
42
  /** A base on the page's own origin (contentBase.ts allows one) owns its folder only; the rest of the origin is the page's. */
@@ -203,15 +214,35 @@ function precacheGeneration() {
203
214
  precaching ??= (async () => {
204
215
  try {
205
216
  const [assets, books] = await Promise.all([store(ASSETS), caches.open(BOOKS)]);
206
- await precacheQueue(assets, FILES);
217
+ await precacheQueue(assets, PRECACHE_FILES);
207
218
  // PZ10: this build's books on the content base; a build is a generation (and adoptable) only once they are held
208
- if (CONTENT_FILES.length > 0) await precacheQueue(await store(CONTENT_CACHE), CONTENT_FILES, true);
209
- await books.put(bookKey(BUILD), Response.json({ files: FILES.map(abs) }));
219
+ if (CONTENT_PRECACHE.length > 0) await precacheQueue(await store(CONTENT_CACHE), CONTENT_PRECACHE, true);
220
+ await books.put(bookKey(BUILD), Response.json({ files: PRECACHE_FILES.map(abs) }));
210
221
  } catch (error) { precaching = undefined; throw error; }
211
222
  })();
212
223
  return precaching;
213
224
  }
214
225
 
226
+ /** OFFLINE OF7 (PZ15): the build's network-first reads (`/programs/`, `/shardfiles/`) are kept in its shell, which activate
227
+ * deletes. Copy them into this build's shell first, so the first offline launch after an update still has them; a copy this
228
+ * shell holds wins, and the newest older shell wins over older ones. Online they are still read from the network first.
229
+ * Chosen over content-naming those files (OF7's other fix): this changes no URL, no cook and no reader. */
230
+ /** OF5: the deck's draft cards (`/drafts/`, named by their source art, not their bytes) are read the same way. */
231
+ const NETWORK_FIRST = /^\/(?:programs|shardfiles|drafts)\//;
232
+ async function carryNetworkFirst() {
233
+ const shell = await store(SHELL);
234
+ for (const name of (await caches.keys()).reverse()) {
235
+ if (name === SHELL || !name.startsWith(SHELL_PREFIX)) continue;
236
+ const old = await caches.open(name);
237
+ // in parallel within one shell (its keys are distinct): activate holds the first launch after an update
238
+ await Promise.all((await old.keys()).map(async request => {
239
+ if (!NETWORK_FIRST.test(new URL(request.url).pathname) || await shell.match(request, MATCH) !== undefined) return;
240
+ const response = await old.match(request, MATCH);
241
+ if (response !== undefined && !isHtml(response)) await shell.put(request, response);
242
+ }));
243
+ }
244
+ }
245
+
215
246
  workerScope.listen(self, 'activate', event => {
216
247
  event.waitUntil((async () => {
217
248
  const books = await caches.open(BOOKS), current = bookKey(BUILD);
@@ -228,6 +259,7 @@ workerScope.listen(self, 'activate', event => {
228
259
  if (record !== undefined) for (const file of (await record.json()).files) if (!kept.has(file)) await assets.delete(file);
229
260
  await books.delete(key);
230
261
  }
262
+ await carryNetworkFirst().catch(() => undefined);
231
263
  for (const name of await caches.keys()) {
232
264
  if (name === SHELL) continue;
233
265
  if (name.startsWith('ws-shell-') || name.startsWith('ws-static-') || name === 'ws-immutable') await caches.delete(name);
@@ -372,7 +404,7 @@ workerScope.listen(self, 'fetch', event => {
372
404
  }
373
405
  if (/^\/(?:assets|basis|fonts)\//.test(url.pathname) || url.pathname === '/manifest.webmanifest') {
374
406
  event.respondWith(cached(request, SHELL, event));
375
- } else if (/^\/(?:programs|shardfiles)\//.test(url.pathname)) event.respondWith(networkFirst(request, SHELL, event));
407
+ } else if (NETWORK_FIRST.test(url.pathname)) event.respondWith(networkFirst(request, SHELL, event));
376
408
  });
377
409
 
378
410
  workerScope.listen(self, 'message', event => {
@@ -384,11 +416,18 @@ workerScope.listen(self, 'message', event => {
384
416
  // Adoption waits on this reply: a build is offered as the next document's worker only once its code is held.
385
417
  // A page asks once it reaches control, so it no longer counts as loading, and the precache resumes.
386
418
  const port = event.ports?.[0], client = event.source?.id;
387
- if (typeof client === 'string') controlled.add(client);
388
- resumePrecache();
419
+ // OF5a: a title asks too (`update`), so a build update seen only on the title holds its code before the first offline
420
+ // launch. Only on a device that holds another build's generation: a first visit's title still reads nothing (S2, DL1),
421
+ // and a title that is turned down neither counts as a page past loading nor resumes another page's pause.
422
+ const update = event.data?.update === true;
423
+ const settle = () => { if (typeof client === 'string') controlled.add(client); resumePrecache(); };
424
+ if (!update) settle();
389
425
  event.waitUntil((async () => {
390
426
  let ok = true;
391
- try { await precacheGeneration(); } catch { ok = false; }
427
+ try {
428
+ if (update && (await (await caches.open(BOOKS)).keys()).every(key => key.url === bookKey(BUILD))) ok = false;
429
+ else { if (update) settle(); await precacheGeneration(); }
430
+ } catch { ok = false; }
392
431
  port?.postMessage({ type, ok, build: BUILD });
393
432
  })());
394
433
  return;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * QA-FEEDBACK-2026-11-13 row 6 (Jake's friend, Android Chrome, staging v0.1.16): the game joined and played, the HUD and
3
+ * the minimap drew, but the world was the page's own background, and nothing reached Sentry. The world draws through
4
+ * the composer's half-float targets (RGBA16F); WebGL2 can only draw into those where the GPU offers
5
+ * EXT_color_buffer_float or EXT_color_buffer_half_float. Without either the targets are incomplete framebuffers: every
6
+ * draw into them is dropped without a throw, and the screen pass copies their empty (transparent) texels to the canvas.
7
+ *
8
+ * So the engine's HDR targets take `hdrTargetType`: half float where the GPU can draw into it, else 8-bit (the same
9
+ * passes, less headroom for bloom), and `DrawCheck` makes a world that still draws nothing loud: twice after the first
10
+ * frames, in the same task as the draw (the drawing buffer is not preserved), it reads the composer's input framebuffer
11
+ * status and a 3×3 grid of the canvas. An incomplete target, or a canvas that stayed fully transparent at both checks,
12
+ * is reported once as a fault (Sentry, and the error card) naming the GPU and what it lacks.
13
+ */
14
+ import * as THREE from 'three';
15
+ import type { Renderer } from './renderer';
16
+
17
+ /** whether this renderer's GPU can draw into half-float colour targets (asking also enables the extension) */
18
+ export function halfFloatTargets(renderer: Pick<Renderer, 'extensions'>): boolean {
19
+ return renderer.extensions.has('EXT_color_buffer_float') || renderer.extensions.has('EXT_color_buffer_half_float');
20
+ }
21
+
22
+ /** the type of the engine's HDR targets (the composer; volumetrics through fitHdrTarget): half float where it can be drawn into, else
23
+ * 8-bit. Not yet: keyedSky's environment equirect (game layer) and staticCapture, which stay half float (a darker world, not a black one). */
24
+ export function hdrTargetType(renderer: Pick<Renderer, 'extensions'>): THREE.TextureDataType {
25
+ return halfFloatTargets(renderer) ? THREE.HalfFloatType : THREE.UnsignedByteType;
26
+ }
27
+
28
+ /** A half-float target made before the renderer was known, retyped to 8-bit (and reallocated) where the GPU cannot draw into half float. */
29
+ export function fitHdrTarget(renderer: Pick<Renderer, 'extensions'>, target: THREE.WebGLRenderTarget): void {
30
+ if (target.texture.type !== THREE.HalfFloatType || halfFloatTargets(renderer)) return;
31
+ target.texture.type = THREE.UnsignedByteType; target.dispose();
32
+ }
33
+
34
+ /** what a draw report names about the GPU: its model (no player identifier), and the limits a phone GPU runs short of */
35
+ export function gpuSummary(gl: WebGLRenderingContext | WebGL2RenderingContext): string {
36
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
37
+ const name = String(info === null ? gl.getParameter(gl.RENDERER) : gl.getParameter(info.UNMASKED_RENDERER_WEBGL));
38
+ const has = (ext: string): string => (gl.getSupportedExtensions() ?? []).includes(ext) ? 'yes' : 'no';
39
+ const n = (p: number): string => String(gl.getParameter(p));
40
+ return `GPU ${name} · color_buffer_float ${has('EXT_color_buffer_float')} · color_buffer_half_float ${has('EXT_color_buffer_half_float')}`
41
+ + ` · frag uniforms ${n(gl.MAX_FRAGMENT_UNIFORM_VECTORS)} · varyings ${n(gl.MAX_VARYING_VECTORS)} · textures ${n(gl.MAX_TEXTURE_IMAGE_UNITS)}`
42
+ + ` · max texture ${n(gl.MAX_TEXTURE_SIZE)}`;
43
+ }
44
+
45
+ /** true when every sample of a 3×3 grid of the bound framebuffer is fully transparent (nothing drawn: the page shows through) */
46
+ export function blankFramebuffer(gl: Pick<WebGLRenderingContext, 'readPixels' | 'RGBA' | 'UNSIGNED_BYTE' | 'drawingBufferWidth' | 'drawingBufferHeight'>): boolean {
47
+ const px = new Uint8Array(4), w = gl.drawingBufferWidth, h = gl.drawingBufferHeight;
48
+ for (const fx of [0.2, 0.5, 0.8]) for (const fy of [0.2, 0.5, 0.8]) {
49
+ gl.readPixels(Math.floor(w * fx), Math.floor(h * fy), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
50
+ if (px[3] !== 0) return false;
51
+ }
52
+ return true;
53
+ }
54
+
55
+ /** the frames (counted from the loop's start) a draw check runs on */
56
+ export const DRAW_CHECK_FRAMES: readonly number[] = [60, 300];
57
+
58
+ export interface DrawCheckHost {
59
+ renderer: { getContext: () => WebGLRenderingContext | WebGL2RenderingContext; getRenderTarget: () => THREE.WebGLRenderTarget | null; setRenderTarget: (target: THREE.WebGLRenderTarget | null) => void };
60
+ /** the composer's input buffer (where the world draws), null before the composer exists */
61
+ target: () => THREE.WebGLRenderTarget | null;
62
+ /** `certain`: the target is incomplete (nothing can draw); otherwise the canvas only read transparent twice */
63
+ report: (error: Error, certain: boolean) => void;
64
+ }
65
+
66
+ /** The world's draw check: `afterDraw(frame)` right after each loop draw, in the same task. Reports at most once. */
67
+ export class DrawCheck {
68
+ private blank = 0;
69
+ private done = false;
70
+ private readonly host: DrawCheckHost;
71
+ constructor(host: DrawCheckHost) { this.host = host; }
72
+
73
+ afterDraw(frame: number): void {
74
+ if (this.done || !DRAW_CHECK_FRAMES.includes(frame)) return;
75
+ const { renderer } = this.host, gl = renderer.getContext();
76
+ if (gl.isContextLost()) return; // GpuRecovery owns a lost context
77
+ const prev = renderer.getRenderTarget();
78
+ let why = '', certain = false;
79
+ try {
80
+ const target = this.host.target();
81
+ if (target !== null) {
82
+ renderer.setRenderTarget(target);
83
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
84
+ if (status !== gl.FRAMEBUFFER_COMPLETE) { certain = true; why = `the world's target is incomplete (status 0x${status.toString(16)})`; }
85
+ }
86
+ renderer.setRenderTarget(null);
87
+ if (why === '' && blankFramebuffer(gl) && ++this.blank === DRAW_CHECK_FRAMES.length) why = `the canvas stayed transparent at frames ${DRAW_CHECK_FRAMES.join(' and ')}`;
88
+ } catch { return; } finally { renderer.setRenderTarget(prev); }
89
+ if (why === '' && frame !== DRAW_CHECK_FRAMES.at(-1)) return;
90
+ this.done = true;
91
+ if (why === '') return;
92
+ let gpu = '';
93
+ try { gpu = gpuSummary(gl); } catch { gpu = 'GPU unknown'; }
94
+ this.host.report(new Error(`World drew nothing: ${why} · ${gpu}`), certain);
95
+ }
96
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * STALE-BUILD SB6: index.html's `data-stale-build` script runs before any module, so it has no save service; when it stops a
3
+ * stale build and sends the player to update, it leaves its note in localStorage `ws-stale-build` (build, built-at, the server's
4
+ * build, tries, when). The next build that boots takes the note here, once: read, then removed. Its report then waits in the
5
+ * device's screen outbox (`screen.reports`, telemetry/browserErrors.ts) until Sentry acknowledges it.
6
+ */
7
+ export interface StaleBuildNote {
8
+ readonly build: string;
9
+ /** the stale build's own stamp (ms) */
10
+ readonly at: number;
11
+ /** the build the server named, '' when it named none */
12
+ readonly server: string;
13
+ readonly tries: number;
14
+ /** when the stale screen last wrote the note (ms) */
15
+ readonly seen: number;
16
+ }
17
+ export const STALE_BUILD_NOTE_KEY = 'ws-stale-build';
18
+
19
+ /** a time a Date can hold (ms); anything else is not the inline script's */
20
+ const time = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 8.64e15;
21
+
22
+ /** The note as the inline script wrote it, or null for anything else. */
23
+ export function parseStaleBuildNote(raw: string | null): StaleBuildNote | null {
24
+ if (raw === null) return null;
25
+ let value: unknown;
26
+ try { value = JSON.parse(raw); } catch { return null; }
27
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
28
+ const { build, at, server, tries, seen } = value as Record<string, unknown>;
29
+ if (typeof build !== 'string' || typeof server !== 'string' || typeof tries !== 'number' || !time(at) || !time(seen)) return null;
30
+ return { build: build.slice(0, 200), at, server: server.slice(0, 200), tries, seen };
31
+ }
32
+
33
+ type NoteStore = Pick<Storage, 'getItem' | 'removeItem'>;
34
+ function pageStore(): NoteStore | null {
35
+ try { return typeof localStorage === 'undefined' ? null : localStorage; } catch { return null; }
36
+ }
37
+
38
+ /** Take the note once: it is removed as it is read, and a malformed one is dropped too. Null when there is none. */
39
+ export function takeStaleBuildNote(store: NoteStore | null = pageStore()): StaleBuildNote | null {
40
+ if (store === null) return null;
41
+ let raw: string | null = null;
42
+ try { raw = store.getItem(STALE_BUILD_NOTE_KEY); } catch { return null; }
43
+ if (raw === null) return null;
44
+ try { store.removeItem(STALE_BUILD_NOTE_KEY); } catch { return null; } // a note that can't be removed would report on every boot
45
+ return parseStaleBuildNote(raw);
46
+ }
@@ -1,7 +1,10 @@
1
1
  import { Scope } from '../../../shared/engine/app/scope';
2
2
  import { harnessPins, installedIdentity } from '../../../shared/engine/app/identity';
3
+ import { pageScope } from '../../../shared/engine/app/resources';
4
+ import { jsonSlot, type Json } from '../saves/slots';
3
5
  /** Optional, error-only Sentry channel. The existing /api/errors report remains the primary local inbox. */
4
6
  import type { captureException, ErrorEvent, getClient, httpContextIntegration, init, withScope } from '@sentry/browser';
7
+ import type { StaleBuildNote } from '../saves/staleBuildNote';
5
8
 
6
9
  declare const __BUILD_ID__: string;
7
10
  /** vite.config.ts: package.json's version (scripts/changelog.mjs); absent under Node */
@@ -15,8 +18,28 @@ export interface BrowserErrorTags {
15
18
  readonly fatal: boolean;
16
19
  /** Small, explicit diagnostics supplied by the caller; never browser storage or request headers. */
17
20
  readonly diagnostic?: Record<string, unknown>;
21
+ /** SENTRY-TRIAGE S13: the error screen this report opened. Set only by the call that opens it, so each screen is one event. */
22
+ readonly screen?: ErrorScreen;
18
23
  }
19
24
 
25
+ /**
26
+ * SENTRY-TRIAGE S13 (Jake, 2026-11-13: "Every time an error modal opens, are we writing something to Sentry that we can pull down and
27
+ * audit?"): every screen a player sees that means something went wrong, as its Sentry `screen` tag. Query: `screen:title-drop`.
28
+ * error-modal the fatal modal (src/client/engine/ui/ErrorModal.ts showFatal: a fault, the boot failed, Developer's every error)
29
+ * stuck-step the same modal opened by the stuck-step watchdog (showError with S4's stall, src/client/app/entry.ts)
30
+ * glitch-chip "A glitch was reported" (ErrorModal.ts showChip, once a session)
31
+ * load-failure the shard's load-failure page (src/client/engine/ui/errorScreen.ts showLoadFailure, src/client/game/session/session.ts)
32
+ * title-drop the drop modal, "Unexpectedly back at the title" (src/client/app/dropModal.ts showDropModal)
33
+ * link-lost the online stop card "Couldn't reconnect" (src/client/host/online/linkScreens.ts)
34
+ * link-refused the online stop card "The world turned this connection away" (the same file)
35
+ * stale-build the stale-build screen (index.html data-stale-build, STALE-BUILD SB6), reported by the next build that boots
36
+ * (telemetry/staleBuildReport.ts) since that page stops before Sentry can load
37
+ * Not screens of a fault, so never reported: the player's own reload, back or exit (QA 11-12 row 35), "Playing somewhere else",
38
+ * "The world is full", the reconnect banner (counted in `net` telemetry), title refusal lines and the Connection doctor.
39
+ */
40
+ export const ERROR_SCREENS = ['error-modal', 'stuck-step', 'glitch-chip', 'load-failure', 'title-drop', 'link-lost', 'link-refused', 'stale-build'] as const;
41
+ export type ErrorScreen = typeof ERROR_SCREENS[number];
42
+
20
43
  // A DSN is a public browser endpoint, not an auth token. Only real production pages report.
21
44
  const productionDsn = 'https://ccaf25bcd6baa389433fb9efe0117c9b@o4512161165410304.ingest.us.sentry.io/4512161184088064';
22
45
  const dsn = String(import.meta.env['VITE_SENTRY_DSN'] ?? (import.meta.env.PROD ? productionDsn : '')).trim();
@@ -34,6 +57,9 @@ export function browserErrorDist(build: string): string | undefined {
34
57
  return build !== '' && build.length <= 64 ? build : undefined;
35
58
  }
36
59
  let sdk: Promise<BrowserSdk | null> | null = null;
60
+ /** S13: deliveries waiting on an event that beforeSend refused (noise, a page that stopped reporting): that event is done, not owed */
61
+ const refusedListeners = new Set<(id: string) => void>();
62
+ const refused = (id: string | undefined): null => { for (const listener of refusedListeners) listener(id ?? ''); return null; };
37
63
 
38
64
  /** External error delivery is opt-in by exact app origin and never by a test runner. */
39
65
  export function browserErrorDeliveryAllowed(environment: { readonly origin: string; readonly automated: boolean; readonly harness: boolean },
@@ -68,6 +94,21 @@ export function browserErrorNoise(event: ErrorEvent, page: { readonly environmen
68
94
  return null;
69
95
  }
70
96
 
97
+ /**
98
+ * Known, designed refusals of an old browser: the player was told what to do, so they are warnings, never fatal (SENTRY-TRIAGE,
99
+ * WILDSHARD-GAME-8F). J171 keeps signature code out of the page, so a browser with no WebCrypto Ed25519 can't join the online world.
100
+ */
101
+ const UNSUPPORTED_BROWSER = ['This browser is too old for the online world'] as const;
102
+
103
+ /** The Sentry level an error reports at: `warning` for a designed old-browser refusal, else `fatal` or `error`. Pure, so it is tested. */
104
+ export function browserErrorLevel(error: unknown, fatal: boolean): 'warning' | 'error' | 'fatal' {
105
+ const message = error instanceof Error ? error.message
106
+ : typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string' ? error.message : String(error);
107
+ // includes, not startsWith: a title drop reports it as `<what>: <reason>` (src/client/app/entry.ts showDrop).
108
+ if (UNSUPPORTED_BROWSER.some((phrase) => message.includes(phrase))) return 'warning';
109
+ return fatal ? 'fatal' : 'error';
110
+ }
111
+
71
112
  function productionPage(): boolean {
72
113
  if (typeof location === 'undefined' || typeof navigator === 'undefined') return false;
73
114
  return browserErrorDeliveryAllowed({origin: location.origin, automated: navigator.webdriver, harness: harnessPins() !== undefined},
@@ -96,8 +137,8 @@ function loadSdk(): Promise<BrowserSdk | null> {
96
137
  maxBreadcrumbs: 0,
97
138
  normalizeDepth: 6, // context -> checkpoint array -> checkpoint -> facts
98
139
  beforeSend(event) {
99
- if (!productionPage()) return null;
100
- if (browserErrorNoise(event, { environment, userAgent: navigator.userAgent }) !== null) return null;
140
+ if (!productionPage()) return refused(event.event_id);
141
+ if (browserErrorNoise(event, { environment, userAgent: navigator.userAgent }) !== null) return refused(event.event_id);
101
142
  if (event.request) {
102
143
  event.request.url = `${location.origin}${location.pathname}`;
103
144
  // The user agent names the browser, OS and device; no referrer or other header leaves the page.
@@ -108,22 +149,22 @@ function loadSdk(): Promise<BrowserSdk | null> {
108
149
  },
109
150
  });
110
151
  return sentry;
111
- }).catch(() => null);
152
+ // S13: a failed chunk load (a stale page, the network) must not silence every later report on this page; the next one tries again
153
+ }).catch(() => { sdk = null; return null; });
112
154
  return sdk;
113
155
  }
114
156
 
157
+ function tagsOf(tags: BrowserErrorTags): Record<string, string> {
158
+ return { system: tags.system, build: tags.build, shard: tags.shard, boot_stage: tags.bootStage, ...(tags.screen === undefined ? {} : { screen: tags.screen }) };
159
+ }
160
+
115
161
  async function send(error: unknown, tags: BrowserErrorTags): Promise<void> {
116
162
  const sentry = await loadSdk();
117
163
  if (sentry === null) return;
118
164
  try {
119
165
  sentry.withScope((scope) => {
120
- scope.setTags({
121
- system: tags.system,
122
- build: tags.build,
123
- shard: tags.shard,
124
- boot_stage: tags.bootStage,
125
- });
126
- scope.setLevel(tags.fatal ? 'fatal' : 'error');
166
+ scope.setTags(tagsOf(tags));
167
+ scope.setLevel(browserErrorLevel(error, tags.fatal));
127
168
  if (tags.diagnostic) scope.setContext('boot_diagnostic', tags.diagnostic);
128
169
  sentry.captureException(asError(error));
129
170
  });
@@ -140,34 +181,130 @@ function asError(error: unknown): Error {
140
181
  return new Error(String(error));
141
182
  }
142
183
 
143
- /** Fire and forget: an absent DSN adds no request or SDK initialization to a player's boot. */
184
+ /**
185
+ * Fire and forget: an absent DSN adds no request or SDK initialization to a player's boot. A report that opens an error screen
186
+ * (`tags.screen`) is durable instead (S13): it is written to the device's screen outbox first, in the screen's own turn, and leaves
187
+ * the outbox only once Sentry acknowledges it, so a page that reloads, goes to the title or dies right after still delivers it
188
+ * (the next page sends it with the same event id, so Sentry keeps one).
189
+ */
144
190
  export function captureBrowserError(error: unknown, tags: BrowserErrorTags): void {
145
191
  if (!dsn || !productionPage()) return;
192
+ if (tags.screen !== undefined) { reportScreen(error, tags); return; }
146
193
  void send(error, tags);
147
194
  }
148
195
 
149
- /** Durable diagnostics require a transport acknowledgement, not just captureException's event ID. */
150
- export async function deliverBrowserError(error: Error, tags: BrowserErrorTags): Promise<boolean> {
196
+ /** Durable diagnostics require a transport acknowledgement, not just captureException's event ID. `eventId`: a fixed id (S13). */
197
+ export async function deliverBrowserError(error: Error, tags: BrowserErrorTags, eventId?: string): Promise<boolean> {
151
198
  if (!dsn || !productionPage()) return true;
152
199
  const sentry = await loadSdk();
153
200
  const client = sentry?.getClient();
154
201
  if (!sentry || !client) { sdk = null; return false; }
155
202
  return new Promise((resolve) => {
156
203
  const delivery = new Scope('error.delivery');
157
- let eventId = '';
204
+ let sentId = '';
158
205
  let unsubscribe = (): void => undefined;
159
- delivery.timeout(5000, () => { delivery.dispose(); unsubscribe(); resolve(false); });
160
- const finish = (ok: boolean): void => { delivery.dispose(); unsubscribe(); resolve(ok); };
206
+ let stopRefused = (): void => undefined;
207
+ delivery.timeout(5000, () => { delivery.dispose(); unsubscribe(); stopRefused(); resolve(false); });
208
+ const finish = (ok: boolean): void => { delivery.dispose(); unsubscribe(); stopRefused(); resolve(ok); };
209
+ const onRefused = (id: string): void => { if (id !== '' && (id === sentId || id === eventId)) finish(true); };
210
+ refusedListeners.add(onRefused);
211
+ stopRefused = (): void => { refusedListeners.delete(onRefused); };
161
212
  unsubscribe = client.on('afterSendEvent', (event, response) => {
162
- if (event.event_id === eventId) finish(response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300);
213
+ if (event.event_id === sentId) finish(response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300);
163
214
  });
164
215
  try {
165
216
  sentry.withScope((scope) => {
166
- scope.setTags({ system: tags.system, build: tags.build, shard: tags.shard, boot_stage: tags.bootStage });
167
- scope.setLevel('error');
217
+ scope.setTags(tagsOf(tags));
218
+ scope.setLevel(browserErrorLevel(error, tags.screen !== undefined && tags.fatal));
168
219
  if (tags.diagnostic) scope.setContext('boot_diagnostic', tags.diagnostic);
169
- eventId = sentry.captureException(error);
220
+ sentId = sentry.captureException(error, eventId === undefined ? undefined : { event_id: eventId });
170
221
  });
171
222
  } catch { finish(false); }
172
223
  });
173
224
  }
225
+
226
+ /**
227
+ * STALE-BUILD SB6: the stale-build screen (index.html `data-stale-build`) runs before Sentry can load, so the next build that
228
+ * boots reports it, once, as screen `stale-build` through the screen outbox (durable until Sentry acknowledges it). The build
229
+ * tag is the stale build's, not this page's.
230
+ */
231
+ export function staleBuildReport(note: StaleBuildNote): { error: Error; tags: BrowserErrorTags } {
232
+ const days = Math.floor((note.seen - note.at) / 86_400_000);
233
+ const error = new Error(`A stale build was stopped at the title and sent to update (${String(days)} days old)`);
234
+ return { error, tags: { system: 'stale-build', build: note.build, shard: '', bootStage: 'title', fatal: false, screen: 'stale-build',
235
+ diagnostic: { builtAt: new Date(note.at).toISOString(), seen: new Date(note.seen).toISOString(), server: note.server, tries: note.tries } } };
236
+ }
237
+
238
+ // ── S13: the screen outbox (its reader and sender, src/client/engine/telemetry/screenOutbox.ts, load only when something is owed) ──
239
+ /** one screen report waiting for Sentry's acknowledgement */
240
+ export interface ScreenReport {
241
+ /** the Sentry event id (32 hex), fixed when the screen opens so a resend is the same event */
242
+ readonly id: string;
243
+ readonly at: number;
244
+ readonly message: string;
245
+ readonly stack: string;
246
+ readonly tags: BrowserErrorTags & { readonly screen: ErrorScreen };
247
+ }
248
+ /** where the outbox lives: the device's `screen.reports` slot on a page, a variable in a test */
249
+ export interface ScreenStore { read: () => Json; write: (value: Json) => void }
250
+ export const OUTBOX_MAX = 8;
251
+
252
+ let idCount = 0;
253
+ /** A fresh event id. getRandomValues works on a plain-http page, where crypto.randomUUID throws (QA 11-13 row 5). */
254
+ export function screenEventId(random: (bytes: Uint8Array<ArrayBuffer>) => Uint8Array = (bytes) => crypto.getRandomValues(bytes)): string {
255
+ try { return [...random(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join(''); }
256
+ catch { idCount++; return `${Date.now().toString(16)}${idCount.toString(16)}`.padStart(32, '0').slice(-32); }
257
+ }
258
+
259
+ /** the page's outbox: literal jsonSlot calls (test/saves-lock.test.ts reads the key from them) */
260
+ const pageStore: ScreenStore = {
261
+ read: () => jsonSlot('screen.reports', 'device').peek(),
262
+ write: (value) => { if (!jsonSlot('screen.reports', 'device').write(value)) throw new Error('screen outbox not saved'); },
263
+ };
264
+ const sending = new Set<string>();
265
+ let flushWired = false;
266
+ /** a report as the outbox stores it: JSON, so a diagnostic's undefined fields drop as they would on the wire */
267
+ function stored(report: ScreenReport): Json {
268
+ const text = JSON.stringify(report);
269
+ return JSON.parse(text) as Json;
270
+ }
271
+ async function sendOnce(error: Error, tags: BrowserErrorTags, id: string): Promise<void> {
272
+ sending.add(id);
273
+ try { await deliverBrowserError(error, tags, id); } catch { /* telemetry never throws */ } finally { sending.delete(id); }
274
+ }
275
+
276
+ /** S13: the report of a screen that just opened, on the device before anything awaits, then sent. */
277
+ function reportScreen(error: unknown, tags: BrowserErrorTags): void {
278
+ if (tags.screen === undefined) return;
279
+ const e = asError(error);
280
+ // the diagnostic rides along up to 16 KB of JSON; a larger one is cut to a note, so eight stored reports stay small beside the saves
281
+ const diagnostic = tags.diagnostic === undefined ? undefined : JSON.stringify(tags.diagnostic).length <= 16_384 ? tags.diagnostic : { truncated: true };
282
+ const report: ScreenReport = { id: screenEventId(), at: Date.now(), message: e.message.slice(0, 2000), stack: (e.stack ?? '').slice(0, 6000),
283
+ tags: { ...tags, screen: tags.screen, ...(diagnostic === undefined ? {} : { diagnostic }) } };
284
+ let kept = true;
285
+ try {
286
+ const raw = pageStore.read();
287
+ pageStore.write([...(Array.isArray(raw) ? raw : []), stored(report)].slice(-OUTBOX_MAX));
288
+ } catch { kept = false; }
289
+ // storage refused: this page still sends it, once
290
+ if (kept) flushScreenReports(); else void sendOnce(e, report.tags, report.id);
291
+ }
292
+
293
+ /** S13: whether this build can deliver a screen report at all (a DSN is built in), so a build or test without one arms no flush timer */
294
+ export function screenReportsEnabled(): boolean { return dsn !== ''; }
295
+
296
+ /** Send what this page or an earlier one still owes (every document, off the boot's hot path), and again when the network is back. */
297
+ export function flushScreenReports(): void {
298
+ if (!dsn || !productionPage()) return;
299
+ if (!flushWired && typeof window !== 'undefined') {
300
+ flushWired = true;
301
+ pageScope.listen(window, 'online', () => { flushScreenReports(); });
302
+ }
303
+ // offline: the `online` listener sends it; a chunk import now would only fail
304
+ if (typeof navigator !== 'undefined' && !navigator.onLine) return;
305
+ let raw: Json = null;
306
+ try { raw = pageStore.read(); } catch { return; }
307
+ if (!Array.isArray(raw) || raw.length === 0) return;
308
+ void import('./screenOutbox').then(({ ScreenOutbox, flushScreenOutbox }) => flushScreenOutbox(new ScreenOutbox(pageStore), deliverBrowserError, sending))
309
+ .catch(() => undefined);
310
+ }
@@ -0,0 +1,61 @@
1
+ import type { Json } from '../saves/slots';
2
+ import { ERROR_SCREENS, OUTBOX_MAX, type BrowserErrorTags, type ScreenReport, type ScreenStore } from './browserErrors';
3
+ /**
4
+ * SENTRY-TRIAGE S13: the screen outbox's reader and sender, loaded only when a report is owed (outside the title's gzip ceiling).
5
+ * Every error screen's report waits on the device (browserErrors.ts reportScreen) until Sentry acknowledges it; a resend keeps its
6
+ * event id, so Sentry keeps one event.
7
+ */
8
+
9
+ const OUTBOX_AGE_MS = 7 * 24 * 60 * 60_000;
10
+
11
+ /** The outbox over a store. Pure: no SDK and no page. */
12
+ export class ScreenOutbox {
13
+ private readonly store: ScreenStore;
14
+ private readonly now: () => number;
15
+ constructor(store: ScreenStore, now: () => number = Date.now) { this.store = store; this.now = now; }
16
+ /** the reports still owed, oldest first: at most OUTBOX_MAX, none older than a week, nothing malformed */
17
+ pending(): ScreenReport[] {
18
+ let raw: Json = null;
19
+ try { raw = this.store.read(); } catch { return []; }
20
+ if (!Array.isArray(raw)) return [];
21
+ const now = this.now();
22
+ const owed: ScreenReport[] = [];
23
+ for (const item of raw) {
24
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
25
+ const { id, at, message, stack, tags } = item;
26
+ if (typeof id !== 'string' || typeof at !== 'number' || now - at >= OUTBOX_AGE_MS || typeof message !== 'string' || typeof stack !== 'string') continue;
27
+ if (typeof tags !== 'object' || tags === null || Array.isArray(tags)) continue;
28
+ const screen = ERROR_SCREENS.find((name) => name === tags['screen']);
29
+ if (screen === undefined || typeof tags['system'] !== 'string' || typeof tags['bootStage'] !== 'string') continue;
30
+ // every tag is a string or the fatal flag; the diagnostic is a plain object
31
+ const sound = Object.entries(tags).every(([key, value]) => key === 'diagnostic'
32
+ ? typeof value === 'object' && value !== null && !Array.isArray(value) : typeof value === 'string' || typeof value === 'boolean');
33
+ if (sound) owed.push({ id, at, message, stack, tags: { ...(tags as unknown as BrowserErrorTags), screen } });
34
+ }
35
+ return owed.slice(-OUTBOX_MAX);
36
+ }
37
+ /** keep a report until it is acknowledged; false when storage refused it */
38
+ add(report: ScreenReport): boolean {
39
+ return this.save([...this.pending().filter((p) => p.id !== report.id), report]);
40
+ }
41
+ ack(id: string): void { this.save(this.pending().filter((p) => p.id !== id)); }
42
+ private save(queue: readonly ScreenReport[]): boolean {
43
+ const text = JSON.stringify(queue.slice(-OUTBOX_MAX));
44
+ try { this.store.write(JSON.parse(text) as Json); return true; } catch { return false; }
45
+ }
46
+ }
47
+
48
+ /** Send every owed report; an acknowledged one leaves the outbox. `deliver` resolves true on Sentry's 2xx. */
49
+ export async function flushScreenOutbox(outbox: ScreenOutbox, deliver: (error: Error, tags: BrowserErrorTags, eventId: string) => Promise<boolean>,
50
+ inFlight: Set<string>): Promise<void> {
51
+ for (const report of outbox.pending()) {
52
+ // another flush may have delivered it while this one waited
53
+ if (inFlight.has(report.id) || !outbox.pending().some((p) => p.id === report.id)) continue;
54
+ inFlight.add(report.id);
55
+ try {
56
+ const error = new Error(report.message);
57
+ if (report.stack !== '') error.stack = report.stack;
58
+ if (await deliver(error, report.tags, report.id)) outbox.ack(report.id);
59
+ } catch { /* kept for the next flush */ } finally { inFlight.delete(report.id); }
60
+ }
61
+ }
@@ -0,0 +1,12 @@
1
+ import { takeStaleBuildNote, type StaleBuildNote } from '../saves/staleBuildNote';
2
+ import { captureBrowserError, staleBuildReport } from './browserErrors';
3
+
4
+ /** STALE-BUILD SB6: report an earlier page's stale-build note (browserErrors.ts staleBuildReport), if there is one; the note is gone after this. */
5
+ export function reportStaleBuild(take: () => StaleBuildNote | null = takeStaleBuildNote, capture: typeof captureBrowserError = captureBrowserError): void {
6
+ try {
7
+ const note = take();
8
+ if (note === null) return;
9
+ const { error, tags } = staleBuildReport(note);
10
+ capture(error, tags);
11
+ } catch { /* telemetry never disrupts the boot */ }
12
+ }