@wildshard/engine 0.1.19 → 0.1.21

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 (125) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lint/engine-sides.json +5 -0
  3. package/package.json +5 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/chaos-proxy-core.mjs +14 -1
  7. package/scripts/chaos-proxy-proof.mjs +22 -0
  8. package/scripts/check-devserver.mjs +1 -1
  9. package/scripts/failmode-cases.d.mts +8 -0
  10. package/scripts/failmode-cases.mjs +97 -0
  11. package/scripts/failmode-proof.mjs +532 -0
  12. package/scripts/grid-crossing-nightly.mjs +5 -4
  13. package/scripts/grid-crossing-report.mjs +5 -2
  14. package/scripts/grid-crossing-tour.mjs +36 -12
  15. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  16. package/scripts/hover-speed-probe.mjs +136 -0
  17. package/scripts/land.mjs +2 -1
  18. package/scripts/loading-flow/benchmax.mjs +34 -11
  19. package/scripts/loading-flow/deskbench.mjs +276 -0
  20. package/scripts/loading-flow/stalls.d.mts +17 -3
  21. package/scripts/loading-flow/stalls.mjs +82 -3
  22. package/scripts/net-lag-proof.mjs +3 -2
  23. package/scripts/nightly-model.ts +9 -6
  24. package/scripts/offline-proof.mjs +7 -1
  25. package/scripts/online-rig.mjs +9 -7
  26. package/scripts/parity/boot-smoke.mjs +13 -2
  27. package/scripts/pin-format.ts +5 -2
  28. package/scripts/pins-reuse.d.mts +1 -0
  29. package/scripts/pins-reuse.mjs +22 -0
  30. package/scripts/release-cook.mjs +109 -0
  31. package/scripts/scratch-dir.mjs +95 -0
  32. package/scripts/scratch-sweep.mjs +182 -0
  33. package/scripts/tsconfig.json +2 -12
  34. package/scripts/vps/harden-prometheus.sh +3 -0
  35. package/scripts/vps/rebuild.sh +35 -9
  36. package/scripts/vps/wildshard-apply.mjs +5 -1
  37. package/scripts/vps/wildshard-config +117 -1
  38. package/scripts/worktree-reap.mjs +54 -8
  39. package/scripts/worktree.mjs +19 -5
  40. package/src/client/engine/anim/rigParser.ts +2 -2
  41. package/src/client/engine/boot/contentRead.ts +54 -5
  42. package/src/client/engine/boot/gpuFiles.ts +3 -3
  43. package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
  44. package/src/client/engine/core/Game.ts +63 -19
  45. package/src/client/engine/core/gpuOnly.ts +10 -0
  46. package/src/client/engine/core/renderBudget.ts +134 -0
  47. package/src/client/engine/core/shadowLayer.ts +18 -0
  48. package/src/client/engine/explore/pick.ts +13 -1
  49. package/src/client/engine/net/predictor.ts +12 -4
  50. package/src/client/engine/net/redial.ts +40 -5
  51. package/src/client/engine/player/TouchControls.ts +3 -2
  52. package/src/client/engine/render/dataLook.ts +70 -7
  53. package/src/client/engine/render/families/pbr.ts +2 -0
  54. package/src/client/engine/render/families/registry.ts +11 -2
  55. package/src/client/engine/render/families/sceneSurface.ts +118 -0
  56. package/src/client/engine/render/look.ts +7 -1
  57. package/src/client/engine/render/precompile.ts +4 -2
  58. package/src/client/engine/render/tiers.ts +4 -1
  59. package/src/client/engine/telemetry/browserErrors.ts +3 -1
  60. package/src/client/engine/ui/ErrorModal.ts +1 -1
  61. package/src/client/engine/ui/Loading.ts +14 -2
  62. package/src/client/engine/ui/errorScreen.ts +51 -9
  63. package/src/client/engine/ui/hoverBoost.ts +31 -4
  64. package/src/client/engine/ui/styles/touch.css +6 -0
  65. package/src/client/engine/world/declaredProps.ts +5 -1
  66. package/src/client/engine/world/skyRig.ts +4 -1
  67. package/src/client/engine/world/terrainTileView.ts +64 -23
  68. package/src/client/game/boot/spawnDownload.ts +44 -6
  69. package/src/client/game/devScene/hook.ts +149 -12
  70. package/src/client/game/devScene/liveLook.ts +21 -0
  71. package/src/client/game/grid/live.ts +47 -10
  72. package/src/client/game/grid/liveSession.ts +25 -6
  73. package/src/client/game/grid/pageEntry.ts +12 -1
  74. package/src/client/game/grid/productInputs.ts +22 -11
  75. package/src/client/game/grid/session.ts +15 -4
  76. package/src/client/game/grid/shardfileFar.ts +13 -2
  77. package/src/client/game/session/finish.ts +4 -1
  78. package/src/client/game/shardfile/client.ts +24 -7
  79. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  80. package/src/client/game/shardfile/clientSource.ts +7 -3
  81. package/src/client/game/shardfile/clientViews.ts +36 -8
  82. package/src/client/game/shardfile/clientWorker.ts +4 -4
  83. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  84. package/src/client/game/shardfile/groundMerge.ts +59 -5
  85. package/src/client/game/shardfile/hybrid.ts +2 -0
  86. package/src/client/game/shardfile/look.ts +1 -1
  87. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  88. package/src/client/game/shardfile/tileContent.ts +1 -1
  89. package/src/client/game/shardfile/tileDriver.ts +38 -11
  90. package/src/client/game/shardfile/wirePage.ts +7 -3
  91. package/src/client/game/shardfile/worldScenes.ts +17 -10
  92. package/src/client/host/online/doctor.ts +20 -7
  93. package/src/client/host/online/doctorView.ts +2 -0
  94. package/src/client/host/online/linkScreens.ts +95 -11
  95. package/src/client/host/online/reconnectStrip.ts +3 -2
  96. package/src/client/host/online/release.ts +87 -16
  97. package/src/client/host/online/releaseScreens.ts +108 -0
  98. package/src/client/host/online/shell.ts +24 -5
  99. package/src/client/host/online/voice.ts +45 -1
  100. package/src/client/host/online/voiceUi.ts +24 -6
  101. package/src/client/host/standalone/shell.ts +37 -1
  102. package/src/server/engine/sim/playerSim.ts +1 -1
  103. package/src/server/game/grid/simulation.ts +12 -6
  104. package/src/server/game/quest/eliteDrops.ts +7 -3
  105. package/src/server/game/riding/nativeTaming.ts +13 -2
  106. package/src/server/host/dedicated/cellHost.ts +21 -2
  107. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  108. package/src/server/host/dedicated/cellWorker.ts +1 -1
  109. package/src/server/host/dedicated/dedicatedRoom.ts +38 -8
  110. package/src/server/host/dedicated/roadRoom.ts +3 -0
  111. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  112. package/src/server/host/dedicated/workerTable.ts +31 -24
  113. package/src/server/host/standalone/gridServer.ts +1 -1
  114. package/src/server/host/standalone/serverHost.ts +56 -10
  115. package/src/server/host/standalone/serverProduct.ts +9 -7
  116. package/src/server/host/standalone/serverRuntime.ts +1 -1
  117. package/src/shared/engine/boot/loadingWaits.ts +10 -2
  118. package/src/shared/engine/core/config.ts +3 -0
  119. package/src/shared/engine/core/framePacing.ts +12 -1
  120. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  121. package/src/shared/engine/player/hoverSpeed.ts +3 -3
  122. package/src/shared/engine/strings.ts +12 -1
  123. package/src/shared/game/devColliders.ts +60 -0
  124. package/src/shared/game/devGameplay.ts +41 -0
  125. package/src/shared/game/grid/rules.ts +12 -0
@@ -24,7 +24,7 @@ import { macrotask } from '@wildshard/engine/boot/plan';
24
24
  import { loadingUnits } from '@wildshard/engine/boot/waits';
25
25
  import { diagnosticNow } from '@wildshard/engine/core/clock';
26
26
  import { bootTask, bootWork } from '@wildshard/engine/boot/timing';
27
- import { FENCE_LANES, SPAWN_VIEW_M, spawnViewUsesCamera } from './controlRefinement';
27
+ import { SPAWN_VIEW_M, spawnViewUsesCamera } from './controlRefinement';
28
28
  import { streamingDistance, streamingOrder, type StreamingBounds, type StreamingPoint, type StreamingView } from './streamingView';
29
29
 
30
30
  /** MF5: the live drivers, and whether the loader is settling them (no world frames under the card since FC2). */
@@ -52,6 +52,8 @@ export async function settleTileDrivers(frame?: () => void, stallMs = 20000): Pr
52
52
  await bootTask('app:spawn-view-tiles', async () => { for (const driver of Array.from(liveDrivers)) await driver.settle(stallMs); });
53
53
  } finally { loaderMode = false; }
54
54
  }
55
+ /** Whether the loader is settling the live drivers now (no frame is presented under its card). */
56
+ export function tilesSettling(): boolean { return loaderMode; }
55
57
  /** DL21: while the loader settles, the render tiles inside its fence across the live drivers and how many are complete (the
56
58
  * spawn view's card counts them); null outside the settle. */
57
59
  export function settlingTiles(): { readonly done: number; readonly total: number; readonly stages: number; readonly stagesTotal: number } | null {
@@ -81,8 +83,8 @@ export class TileDriver {
81
83
  private readonly retried = new Set<string>();
82
84
  private centre: CellTile | null = null;
83
85
  private renderRing: ReadonlySet<number> = new Set();
84
- /** the attaches `step` started, while they run (the loader's settle waits on them): one in play, FENCE_LANES under the
85
- * loader */
86
+ /** the attaches `step` started, while they run (the loader's settle waits on them): one in play, every fence tile under
87
+ * the loader */
86
88
  private readonly inflight = new Set<Promise<void>>();
87
89
  private plan: TileRingPlan | null = null;
88
90
  private coarseScope: Scope | null = null;
@@ -189,7 +191,7 @@ export class TileDriver {
189
191
  }
190
192
 
191
193
  /** Once a frame with the player's cell-local position: retire the tiles outside the rings, then start the nearest wanted
192
- * tile not yet attached (colliders first), one at a time in play; under the loader up to FENCE_LANES at once (DL21: the
194
+ * tile not yet attached (colliders first), one at a time in play; under the loader all at once (DL21, NB3: the
193
195
  * fence's slab reads and decodes then overlap, where one tile at a time held its queue at one job). Render owners retire one tile beyond the attach ring;
194
196
  * collider owners retain the exact 3 x 3 physical ring (D2 B). */
195
197
  step(x: number, z: number): void {
@@ -201,7 +203,10 @@ export class TileDriver {
201
203
  if (plan.retained[layer].has(key)) continue;
202
204
  this.attached[layer].delete(key); tile.scope.dispose();
203
205
  }
204
- const lanes = loaderMode ? FENCE_LANES : 1;
206
+ // NB3: under the loader every fence tile starts at once. A tile's attach mostly awaits shared work (its slab banks'
207
+ // reads and their one publication chain, the refinement queue's FENCE_LANES jobs), so a lane cap left the spawn's
208
+ // slab tiles queued behind the collider ring's builds (Nine: render began ~450 ms in at x4)
209
+ const lanes = loaderMode ? Number.POSITIVE_INFINITY : 1;
205
210
  if (this.inflight.size >= lanes) return;
206
211
  const now = diagnosticNow(), cone = loaderMode || this.view === null ? null : this.view(), streamView = spawnViewUsesCamera() ? this.streamingView?.() ?? null : null;
207
212
  for (const key of this.wantedAt.keys()) if (!wanted.render.has(key)) this.wantedAt.delete(key);
@@ -326,17 +331,39 @@ export class TileDriver {
326
331
  // content (the card names the step's wait; this says which content holds it)
327
332
  const timed = loaderMode, started = timed ? diagnosticNow() : 0, contents: Record<string, number> = {};
328
333
  try {
329
- for (const content of this.contents) {
330
- if (tile.done.has(content)) continue;
331
- if (!content.tiles().has(key)) { tile.done.add(content); continue; }
332
- if (layer === 'render' && content.ready?.() === false) continue;
334
+ /** under the loader, one content's stage of this tile (timed); false when the tile retired meanwhile */
335
+ const stage = async (content: TileContent): Promise<boolean> => {
336
+ if (tile.done.has(content)) return true;
337
+ if (!content.tiles().has(key)) { tile.done.add(content); return true; }
338
+ if (layer === 'render' && content.ready?.() === false) return true;
333
339
  // Cached stages may resolve in microtasks; share the live frame's
334
340
  // budget before admitting another stage, including background tiles.
335
- if (frameBudgetSpent(WORK_SLICE_MS)) await (loaderMode ? task() : this.pause()); // MF5: no frames under the card
336
- if (tile.scope.disposed || tile.scope.disposing) return null;
341
+ if (frameBudgetSpent(WORK_SLICE_MS)) await task(); // MF5: no frames under the card
342
+ if (tile.scope.disposed || tile.scope.disposing) return false;
337
343
  const at = timed ? diagnosticNow() : 0;
338
344
  await (layer === 'render' ? content.attach(key, tile.scope) : content.attachColliders?.(key, tile.scope));
339
345
  if (timed) contents[content.id] = Math.round(diagnosticNow() - at);
346
+ if (tile.scope.disposed || tile.scope.disposing) return false;
347
+ tile.done.add(content);
348
+ return true;
349
+ };
350
+ // NINE-DRAGON-BENCHMAX NB3: under the loader a tile's contents attach together, so the slab keys' publications queue
351
+ // at once and publish as one warm (slabLibrary.ts `publish`); one after another, each waited on its own (~50 serialized
352
+ // warms on Nine's spawn view, ~75 ms each on a cold phone). In play they stay in order, one at a time.
353
+ // allSettled: a failed content rethrows only once its siblings have finished, so the settle's retry never starts a
354
+ // second attach of this key while the first is still running on the scope the catch disposes
355
+ if (loaderMode) {
356
+ const settled = await Promise.allSettled(this.contents.map(stage)), failed = settled.find(row => row.status === 'rejected');
357
+ if (failed !== undefined) throw failed.reason;
358
+ if (!settled.every(row => row.status === 'fulfilled' && row.value)) return null;
359
+ }
360
+ else for (const content of this.contents) {
361
+ if (tile.done.has(content)) continue;
362
+ if (!content.tiles().has(key)) { tile.done.add(content); continue; }
363
+ if (layer === 'render' && content.ready?.() === false) continue;
364
+ if (frameBudgetSpent(WORK_SLICE_MS)) await this.pause();
365
+ if (tile.scope.disposed || tile.scope.disposing) return null;
366
+ await (layer === 'render' ? content.attach(key, tile.scope) : content.attachColliders?.(key, tile.scope));
340
367
  if (tile.scope.disposed || tile.scope.disposing) return null;
341
368
  tile.done.add(content);
342
369
  }
@@ -82,6 +82,8 @@ export class WirePage {
82
82
  private readonly quests = new Map<string, QuestProgress>();
83
83
  private readonly heard = new Set<string>();
84
84
  private readonly feeds = new Map<string, QuestViewFeed>();
85
+ /** each feed's declaration, as text: a changed one makes a new feed */
86
+ private readonly feedWords = new Map<string, string>();
85
87
  private readonly waiting = new Set<Live>();
86
88
  private readonly books = new Set<Flags>();
87
89
  /** The rows a sky reads: none, until the wire is up. */
@@ -140,7 +142,7 @@ export class WirePage {
140
142
  for (const use of this.waiting) use(client);
141
143
  this.waiting.clear();
142
144
  }
143
- unbind(): void { this.client = null; this.press = () => undefined; this.act = () => undefined; this.dayRow = undefined; this.stop = () => undefined; this.encounterRows = null; this.heads = () => false; this.seeded = null; this.purchases.clear(); this.books.clear(); this.feeds.clear(); this.movers.clear(); }
145
+ unbind(): void { this.client = null; this.press = () => undefined; this.act = () => undefined; this.dayRow = undefined; this.stop = () => undefined; this.encounterRows = null; this.heads = () => false; this.seeded = null; this.purchases.clear(); this.books.clear(); this.feeds.clear(); this.feedWords.clear(); this.movers.clear(); }
144
146
  /** A setting's weather or a dev's jump: the server's sky takes it. Only a mode outlives its world. */
145
147
  climate(word: ClimateWord): void {
146
148
  if (word.op !== 'force') this.skyWords.set(word.op, word);
@@ -215,8 +217,10 @@ export class WirePage {
215
217
  }
216
218
  /** A quest view for `def`, over this player's rows. */
217
219
  quest(def: QuestDef): QuestView {
218
- const feed = this.feeds.get(def.id) ?? new QuestViewFeed([def], { quests: this.quests, phased: this.heard });
219
- this.feeds.set(def.id, feed);
220
+ // SHARD-SOURCE AP19 (DEVSERVER): a quest whose declaration changed (`wildshard watch`'s soft restart) gets a feed of its new steps
221
+ const words = typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ ? JSON.stringify(def) : '', held = this.feeds.get(def.id);
222
+ const feed = held !== undefined && this.feedWords.get(def.id) === words ? held : new QuestViewFeed([def], { quests: this.quests, phased: this.heard });
223
+ this.feeds.set(def.id, feed); this.feedWords.set(def.id, words);
220
224
  return feed.quest(def.id);
221
225
  }
222
226
  /** The server's payouts: the page's own go, so a kill pays once. */
@@ -420,18 +420,25 @@ async function buildPrepared(ctx: ShardContext, section: WorldScenesSection, res
420
420
  // reconstructing a union during play.
421
421
  const slabs = section.libraries.find(entry => entry.kind === 'slabs' && entry.of === row.id);
422
422
  if (slabs?.kind !== 'slabs') throw new Error(`Fine refinement requires baked slabs: ${row.id}`);
423
- const whole = new SlabLibrary(owner, product, row, slabs, refinementQueue(), coarse.ensure, async (part, scope, anchor) => {
423
+ const whole = new SlabLibrary(owner, product, row, slabs, refinementQueue(), coarse.ensure, async parts => {
424
424
  const game = ctx.game.runtime?.world?.game;
425
425
  if (game === undefined || game === null) return;
426
- const live = (): boolean => !owner.disposed && !owner.disposing && !scope.disposed && !scope.disposing;
427
- // The native warmer draws connected hidden roots. Borrow the
428
- // key's actual world frame, without exposing a partial anchor.
429
- anchor.updateWorldMatrix(true, false);
430
- const stage = new Group(); stage.visible = false; stage.matrixAutoUpdate = false; stage.matrix.copy(game.rootScene.matrixWorld).invert().multiply(anchor.matrixWorld);
431
- stage.add(part); game.rootScene.add(stage);
432
- const forget = scope.capture('disposers', () => { stage.removeFromParent(); });
433
- try { await game.warmSceneRoots([stage], live, undefined, { drawGeometry: true }); }
434
- finally { forget(); part.removeFromParent(); stage.removeFromParent(); }
426
+ const live = (): boolean => !owner.disposed && !owner.disposing && parts.every(({ scope }) => !scope.disposed && !scope.disposing);
427
+ // The native warmer draws connected hidden roots. Borrow each
428
+ // key's actual world frame, without exposing a partial anchor;
429
+ // one hidden root holds the publication's every part (NB3).
430
+ const root = new Group(); root.visible = false; root.matrixAutoUpdate = false;
431
+ root.matrix.copy(game.rootScene.matrixWorld).invert();
432
+ const staged = parts.map(({ part, anchor, scope }) => {
433
+ anchor.updateWorldMatrix(true, false);
434
+ const stage = new Group(); stage.matrixAutoUpdate = false; stage.matrix.copy(anchor.matrixWorld);
435
+ stage.add(part); root.add(stage);
436
+ const forget = scope.capture('disposers', () => { stage.removeFromParent(); });
437
+ return { part, stage, forget };
438
+ });
439
+ game.rootScene.add(root);
440
+ try { await game.warmSceneRoots([root], live, undefined, { drawGeometry: true }); }
441
+ finally { for (const { part, stage, forget } of staged) { forget(); part.removeFromParent(); stage.removeFromParent(); } root.removeFromParent(); }
435
442
  });
436
443
  refining.set(row.id, whole);
437
444
  libraries.set(row.id, { geometry: id => whole.geometry(id) }); return;
@@ -22,7 +22,9 @@ export const DOCTOR_CHECKS = [
22
22
  export type DoctorId = (typeof DOCTOR_CHECKS)[number]['id'];
23
23
  export type DoctorState = 'wait' | 'run' | 'pass' | 'warn' | 'fail' | 'skip';
24
24
  /** One check as the panel shows it. `value` is what was measured; `hint` says what to do when it is not a pass. */
25
- export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number }
25
+ export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number;
26
+ /** The failure-mode catalogue's id this row's warning stands for (meta MMO-FAILURE-MODES-PLAN; FM4b mode 42, `clock-skew`). */
27
+ readonly failmode?: string }
26
28
 
27
29
  /** What the page knows before any check: its own stamps (`stampBuildDocuments`). */
28
30
  export interface DoctorConfig {
@@ -56,14 +58,14 @@ async function limited<T>(scope: Scope, ms: number, work: (signal: AbortSignal)
56
58
  }
57
59
 
58
60
  /** A check's outcome before it is timed. */
59
- interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string }
61
+ interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string; readonly failmode?: string }
60
62
  const pass = (value: string): Outcome => ({ state: 'pass', value });
61
63
  const warn = (value: string, hint: string): Outcome => ({ state: 'warn', value, hint });
62
64
  const fail = (value: string, hint: string): Outcome => ({ state: 'fail', value, hint });
63
65
  const skip = (value: string): Outcome => ({ state: 'skip', value });
64
66
 
65
67
  /** What the earlier checks learned, for the later ones. */
66
- interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
68
+ export interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
67
69
  /** The release's build has no server book or part on the packs origin: the server cannot move to it. */
68
70
  packsMissing?: boolean }
69
71
 
@@ -238,18 +240,29 @@ function checkJoin(config: DoctorConfig, learned: Learned, ms: number): Promise<
238
240
  });
239
241
  }
240
242
 
241
- function checkLatency(learned: Learned): Outcome {
243
+ /**
244
+ * FM4b mode 42 (`clock-skew`): the device's clock measured more than 30 s off the server's health `now` (or the page's `Date`
245
+ * header). The warning shows the measured offset and the automatic-clock fix; it never claims the offset caused a failed secure
246
+ * connection. An unmeasured clock is `clock unknown`, never a warning.
247
+ */
248
+ const clockSkew = (offsetMs: number, server: boolean): Outcome => ({ state: 'warn', value: '', failmode: 'clock-skew',
249
+ hint: `Check automatic date and time: this device's clock is ${(Math.abs(offsetMs) / 1000).toFixed(0)} s ${offsetMs >= 0 ? 'behind' : 'ahead of'} the ${server ? 'server' : 'page\'s host'}. Set date and time to automatic in its settings, then Run again.` });
250
+
251
+ /** The latency row, with the device clock's measured offset. Exported for its test. */
252
+ export function checkLatency(learned: Learned): Outcome {
242
253
  const offsetMs = learned.serverOffset ?? learned.pageOffset ?? null;
243
254
  const clock = offsetMs === null ? 'clock unknown' : `clock ${offsetMs >= 0 ? '+' : '−'}${(Math.abs(offsetMs) / 1000).toFixed(1)} s${learned.serverOffset === undefined ? ' vs page' : ''}`;
244
- const clockOff = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS;
255
+ const skewed = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS ? clockSkew(offsetMs, learned.serverOffset !== undefined) : null;
245
256
  if (learned.rtt.length === 0) {
257
+ // a clock that is off is worth saying even when the socket gave no pings to time
258
+ if (skewed !== null) return { ...skewed, value: `${learned.joined ? 'no pong' : 'needs the socket'} · ${clock}` };
246
259
  if (!learned.joined) return skip(`needs the socket · ${clock}`);
247
260
  return warn(`no pong · ${clock}`, 'The server answered the join but not the pings. Run the check again.');
248
261
  }
249
262
  const sorted = [...learned.rtt].sort((a, b) => a - b), median = sorted[Math.floor(sorted.length / 2)] ?? 0, min = sorted[0] ?? 0;
250
263
  const fmt = (ms: number): string => ms < 10 ? ms.toFixed(1) : String(Math.round(ms));
251
264
  const value = `${fmt(median)} ms (min ${fmt(min)}) · ${clock}`;
252
- if (clockOff) return warn(value, "This phone's clock is off. Set date and time to automatic in the phone's settings.");
265
+ if (skewed !== null) return { ...skewed, value };
253
266
  if (median > SLOW_MS) return warn(value, 'The link is slow. Play still works, but hits may feel late. Try Wi-Fi closer to the router, or mobile data.');
254
267
  return pass(value);
255
268
  }
@@ -302,7 +315,7 @@ export async function runDoctor(config: DoctorConfig, owner: Scope, show: (row:
302
315
  let outcome: Outcome;
303
316
  // A check's own limit is inside it; this one is the guard for a check that forgot.
304
317
  try { outcome = await limited(scope, ms * 2, () => work[id]()); } catch (error) { outcome = fail(errorText(error), 'This check did not finish. Run the checks again.'); }
305
- const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started) };
318
+ const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started), ...outcome.failmode === undefined ? {} : { failmode: outcome.failmode } };
306
319
  if (scope.disposed) break;
307
320
  rows.push(row); show(row);
308
321
  }
@@ -111,6 +111,8 @@ export function openDoctor(config: DoctorConfig, exit: DoctorExit | null, earlie
111
111
  const view = rows.get(row.id);
112
112
  if (view === undefined || scope.disposed) return;
113
113
  view.row.dataset['state'] = row.state; view.glyph.textContent = GLYPH[row.state];
114
+ // FM4b mode 42: a warning that stands for a catalogued failure carries its id (`clock-skew`), as the link's cards do
115
+ if (row.failmode === undefined) delete view.row.dataset['failmode']; else view.row.dataset['failmode'] = row.failmode;
114
116
  view.value.textContent = row.state === 'run' ? 'checking…' : row.value;
115
117
  view.hint.textContent = row.hint; view.ms.textContent = row.state === 'run' ? '' : `${String(row.ms)} ms`;
116
118
  };
@@ -5,8 +5,9 @@
5
5
  // turned the link away) and its **hold card** (the banner's sibling: what was tapped, the dial's live progress, what happens by itself).
6
6
  // The look is the Developer prototypes' (src/client/app/failScreens.ts, FM1b); each root carries the catalogue's `data-failmode` ids.
7
7
  import type { Scope } from '@wildshard/engine/app/scope';
8
- import type { LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
8
+ import type { LinkAway, LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
9
9
  import type { Countdown } from '@wildshard/engine/net/socketFrames';
10
+ import type { TransportStats } from '@wildshard/engine/net/transport';
10
11
  import { diagnosticNow } from '@wildshard/engine/core/clock';
11
12
  import { captureBrowserError } from '@wildshard/engine/telemetry/browserErrors';
12
13
 
@@ -24,6 +25,12 @@ function reportStop(screen: 'link-lost' | 'link-refused', detail: string, report
24
25
  const GIVE_UP_S = 120;
25
26
  /** The Reconnected notice stays this long. */
26
27
  const NOTICE_MS = 2500;
28
+ /** FM4b modes 21 and 22, sampled once a second while live: a pong RTT over this is slow; five in a row spanning this much are unstable. */
29
+ const SLOW_RTT_MS = 250, UNSTABLE_SPAN_MS = 250;
30
+ /** Mode 22: the share of frames the server says it skipped for this client (`lossPct`), not measured TCP loss. */
31
+ const UNSTABLE_LOSS_PCT = 5;
32
+ /** A quality chip shows after this many bad seconds in a row, clears after this many good ones, and shows at most once a minute. */
33
+ const QUALITY_SUSTAIN_S = 5, QUALITY_CLEAR_S = 10, QUALITY_GAP_S = 60;
27
34
  /** After Keep waiting, a blocked tap pulses the banner instead of opening the card again, for this long. */
28
35
  const QUIET_MS = 10_000;
29
36
 
@@ -62,18 +69,25 @@ const CSS = `
62
69
  .ws-link details p{margin:8px 0 0;font-size:10.5px;color:rgba(230,242,248,.55);overflow-wrap:anywhere;-webkit-user-select:text;user-select:text}
63
70
  @keyframes ws-link-fade{from{opacity:0}}@keyframes ws-link-rise{from{opacity:0;transform:translateY(8px)}}
64
71
  .ws-link-notice{animation-name:ws-link-fade}
72
+ .ws-link-page{background:#05101a;animation:ws-link-fade .2s ease-out}.ws-link-page .ws-link-box{animation:none}
73
+ .ws-link-mark{position:fixed;left:50%;bottom:calc(6px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:2147482200;padding:3px 10px;pointer-events:none;background:rgba(13,27,38,.78);border:1px solid rgba(255,181,71,.5);font-size:10px;letter-spacing:.22em;text-transform:uppercase;color:var(--a)}
65
74
  @media (max-width:420px){.ws-link-banner{max-width:calc(100% - 220px);padding-left:12px;padding-right:12px}.ws-link-banner b{letter-spacing:.08em}}
66
75
  @media (min-width:700px){.ws-link-banner{max-width:min(620px,calc(100% - 440px))}.ws-link-box{padding:28px 26px 20px}.ws-link h1{font-size:28px}}
67
76
  @media (prefers-reduced-motion:reduce){.ws-link,.ws-link *{animation:none!important;transition:none!important}}
68
77
  `;
69
78
 
70
- const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = ''): HTMLElementTagNameMap[K] => {
79
+ export const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = ''): HTMLElementTagNameMap[K] => {
71
80
  const node = document.createElement(tag);
72
81
  if (className !== '') node.className = className;
73
82
  if (text !== '') node.textContent = text;
74
83
  return node;
75
84
  };
76
- const ring = (): HTMLElement => { const node = make('span', 'ring'); node.setAttribute('aria-hidden', 'true'); return node; };
85
+ export const ring = (): HTMLElement => { const node = make('span', 'ring'); node.setAttribute('aria-hidden', 'true'); return node; };
86
+
87
+ /** The screens' stylesheet. It lives as long as the document: a second shell (a reload in place) shares it. */
88
+ export function linkStyle(): void {
89
+ if (document.getElementById('ws-link-style') === null) { const style = make('style'); style.id = 'ws-link-style'; style.textContent = CSS; document.head.append(style); }
90
+ }
77
91
 
78
92
  /** What the screens ask of the link and the page. */
79
93
  export interface LinkScreenHooks {
@@ -88,6 +102,8 @@ export interface LinkScreenHooks {
88
102
  readonly doctor?: (from: string) => void;
89
103
  /** Reload this page into the world, taking the seat back (another tab, a turned-away link). */
90
104
  readonly reload: () => void;
105
+ /** FM4b modes 21 and 22: the link's measured pong RTT and the server's reported frame skips (`NetClient.stats`) */
106
+ readonly stats?: () => TransportStats | undefined;
91
107
  /** S13: where a failed link's stop card reports (the browser error tracker; a test observes its own) */
92
108
  readonly report?: typeof captureBrowserError;
93
109
  }
@@ -116,10 +132,12 @@ function bannerFor(state: LinkState, cause: LinkCause, dials: number): { ids: st
116
132
  if (cause === 'silent') return { ids: 'half-open', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'no word from the world' };
117
133
  return { ids: 'drop reset', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'one moment' };
118
134
  }
135
+ /** How long the page was away, in the card's words. */
136
+ const awayFor = (ms: number): string => ms < 90_000 ? `${String(Math.round(ms / 1000))} s` : `${String(Math.round(ms / 60_000))} min`;
119
137
  const blockedIds = (ids: string): string => ids.split(' ').map(id => `${id}-blocked`).join(' ');
120
138
 
121
139
  /** A card's frame: the scrim, the box, a tag and a title. The caller fills the rest. */
122
- function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: string, title: string): { root: HTMLElement; box: HTMLElement } {
140
+ export function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: string, title: string): { root: HTMLElement; box: HTMLElement } {
123
141
  const root = scope.ownNode(make('div', 'ws-link ws-link-scrim')), box = make('div', 'ws-link-box');
124
142
  root.dataset['failmode'] = ids; root.dataset['tone'] = tone; root.setAttribute('role', 'alertdialog'); root.setAttribute('aria-modal', 'true'); root.setAttribute('aria-label', title);
125
143
  box.append(make('p', 'ws-link-tag', tag), make('h1', '', title)); root.append(box);
@@ -136,7 +154,7 @@ function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: str
136
154
  });
137
155
  return { root, box };
138
156
  }
139
- function buttons(scope: Scope, actions: readonly { readonly label: string; readonly primary?: true; readonly busy?: string; readonly act: () => void }[]): HTMLElement {
157
+ export function buttons(scope: Scope, actions: readonly { readonly label: string; readonly primary?: true; readonly busy?: string; readonly act: () => void }[]): HTMLElement {
140
158
  const column = make('div', 'ws-link-col');
141
159
  for (const action of actions) {
142
160
  const button = make('button', action.primary === true ? 'go' : '', action.label);
@@ -158,8 +176,7 @@ function buttons(scope: Scope, actions: readonly { readonly label: string; reado
158
176
  */
159
177
  export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLElement = document.body): LinkScreens {
160
178
  const report = hooks.report ?? captureBrowserError;
161
- // the stylesheet lives as long as the document: a second shell (a reload in place) shares it
162
- if (document.getElementById('ws-link-style') === null) { const style = make('style'); style.id = 'ws-link-style'; style.textContent = CSS; document.head.append(style); }
179
+ linkStyle();
163
180
  // the banner keeps the old strip's id, so the online proofs still find it
164
181
  const banner = scope.ownNode(make('div', 'ws-link ws-link-banner')), head = make('b'), line = make('span');
165
182
  banner.id = 'ws-reconnect-strip'; banner.setAttribute('role', 'status'); banner.hidden = true; banner.append(head, line);
@@ -169,7 +186,7 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
169
186
  parent.append(banner, deploy);
170
187
 
171
188
  let state: LinkState = 'live', reason: string | undefined, wasDown = false, quietUntil = 0, deployLeft = 0, deployTicking = false;
172
- let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop' | 'offline'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
189
+ let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop' | 'offline' | 'away'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
173
190
  const held: { text: string; send: (text: string) => void; drop: () => void }[] = [];
174
191
  const down = (): boolean => state === 'reconnecting' || state === 'resuming';
175
192
 
@@ -180,8 +197,8 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
180
197
  // a card takes the pointer back from the game (desktop pointer lock), so its buttons can be clicked
181
198
  const freePointer = (): void => { if ('exitPointerLock' in document && document.pointerLockElement instanceof Element) document.exitPointerLock(); };
182
199
  const paintBanner = (): void => {
183
- // offline, the card is the screen (FM4b mode 2): no banner under it
184
- const shown = down() && hooks.why() !== 'offline';
200
+ // offline (FM4b mode 2) or back from away (modes 4 and 45), the card is the screen: no banner under it
201
+ const shown = down() && hooks.why() !== 'offline' && hooks.progress().away === undefined;
185
202
  banner.hidden = !shown;
186
203
  // a link that is down takes the top band from the deploy countdown; the countdown comes back with the link
187
204
  deploy.hidden = down() || deployLeft <= 0;
@@ -203,7 +220,7 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
203
220
  /** The hold card: the banner opened up, on a tap it can't carry. It repaints each second from the dial's progress. */
204
221
  const hold = (what: string, chat: boolean): void => {
205
222
  // the offline card already says why nothing goes out; a held chat line still waits for the link
206
- if (open?.kind === 'stop' || open?.kind === 'offline') return;
223
+ if (open?.kind === 'stop' || open?.kind === 'offline' || open?.kind === 'away') return;
207
224
  remember(); open?.scope.dispose(); open = null;
208
225
  const own = scope.child('online.hold'), said = bannerFor(state, hooks.why(), hooks.progress().dials);
209
226
  const title = chat ? 'Your message will send when you\'re back' : state === 'resuming' ? 'Still reconnecting' : hooks.why() === 'restart' ? 'The world is restarting' : 'Not connected yet';
@@ -273,8 +290,72 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
273
290
  root.querySelector('button')?.focus();
274
291
  };
275
292
 
293
+ /**
294
+ * FM4b modes 4 (`background-long`) and 45 (`sleep-wake`): the page was away for over 30 s (out of view, or its clock stopped ticking)
295
+ * and came back to a quiet link. The card says how long the page measured itself away and that the link is being checked; it closes
296
+ * by itself when the link is back. J229: no lost seat or last-save resume is claimed, since the page can't know the world's hold.
297
+ */
298
+ const awayCard = (away: LinkAway): void => {
299
+ if (open?.kind === 'away') { open.paint(); return; }
300
+ remember(); open?.scope.dispose(); open = null;
301
+ const asleep = away.how === 'asleep', own = scope.child('online.away');
302
+ const { root, box } = card(own, asleep ? 'background-long sleep-wake' : 'background-long', 'info', 'Away', 'Welcome back');
303
+ box.append(make('p', 'ws-link-body', `You were away for ${awayFor(away.ms)}, and the link to the world went quiet. We're checking your connection now.`));
304
+ const status = make('ul', 'ws-link-facts'), tries = make('li'), next = make('li');
305
+ status.setAttribute('role', 'status'); status.append(tries, next);
306
+ const paint = (): void => {
307
+ const { dials, nextDialMs } = hooks.progress();
308
+ tries.replaceChildren(ring(), dials > 0 ? `Try ${String(dials + 1)}` : 'Checking your connection');
309
+ next.textContent = nextDialMs !== null ? `Next dial in ${String(Math.ceil(nextDialMs / 1000))} s` : 'Dialling now';
310
+ };
311
+ paint(); own.interval(1000, paint);
312
+ box.append(status, make('p', 'ws-link-auto', 'This closes by itself when you\'re back in. Game taps wait here; we never send one late.'),
313
+ buttons(own, [{ label: 'Try now', primary: true, busy: 'Dialling…', act: () => { hooks.dialNow(); } }, ...doctor(asleep ? 'sleep-wake' : 'background-long')]));
314
+ const details = make('details');
315
+ details.append(make('summary', '', 'Details'), make('p', '', `${asleep ? 'no page clock tick' : 'hidden'} ${awayFor(away.ms)} · link quiet on return · redialling`));
316
+ box.append(details);
317
+ parent.append(root); freePointer();
318
+ open = { scope: own, root, kind: 'away', paint };
319
+ root.querySelector('button')?.focus();
320
+ };
321
+
322
+ /**
323
+ * FM4b modes 21 (`slow`) and 22 (`lossy`): a notice chip in the top band while the link is live and measurably slow or unstable.
324
+ * Only what the page measured: the pong RTT, the spread of the last five, the server's `lossPct`. Never a guessed cause or a made-up
325
+ * percentage. A chip waits while a banner is up (it is the bottom layer) and comes back, if still due, with the link.
326
+ */
327
+ const rtts: number[] = [];
328
+ let slowRun = 0, unstableRun = 0, goodRun = 0, sinceChip = QUALITY_GAP_S, qualityScope: Scope | null = null, qualityKind: 'slow' | 'lossy' | null = null, qualityLine: HTMLElement | null = null;
329
+ const hideQuality = (): void => { qualityScope?.dispose(); qualityScope = null; qualityKind = null; qualityLine = null; };
330
+ const showQuality = (kind: 'slow' | 'lossy', rtt: number): void => {
331
+ if (qualityKind !== kind) {
332
+ hideQuality(); unnotice();
333
+ const own = qualityScope = scope.child('online.quality'), chip = own.ownNode(make('div', 'ws-link ws-link-notice'));
334
+ chip.dataset['failmode'] = kind; chip.dataset['tone'] = 'warn'; chip.setAttribute('role', 'status');
335
+ qualityLine = make('span');
336
+ chip.append(make('b', '', kind === 'slow' ? 'Slow connection' : 'Unstable connection'), qualityLine);
337
+ parent.append(chip);
338
+ qualityKind = kind; sinceChip = 0;
339
+ }
340
+ if (qualityLine !== null) qualityLine.textContent = kind === 'slow' ? `${String(Math.round(rtt))} ms` : 'others may jump';
341
+ };
342
+ const sampleQuality = (): void => {
343
+ sinceChip++;
344
+ const stats = hooks.stats?.();
345
+ if (stats === undefined || state !== 'live') { hideQuality(); slowRun = unstableRun = goodRun = 0; rtts.length = 0; return; }
346
+ const rtt = stats.rttMs;
347
+ if (Number.isFinite(rtt) && rtt > 0) { rtts.push(rtt); if (rtts.length > 5) rtts.shift(); }
348
+ const slow = Number.isFinite(rtt) && rtt > SLOW_RTT_MS;
349
+ const unstable = (rtts.length === 5 && Math.max(...rtts) - Math.min(...rtts) >= UNSTABLE_SPAN_MS) || stats.lossPct >= UNSTABLE_LOSS_PCT;
350
+ slowRun = slow ? slowRun + 1 : 0; unstableRun = unstable ? unstableRun + 1 : 0; goodRun = slow || unstable ? 0 : goodRun + 1;
351
+ const due = slowRun >= QUALITY_SUSTAIN_S ? 'slow' : unstableRun >= QUALITY_SUSTAIN_S ? 'lossy' : null;
352
+ if (qualityKind !== null) { if (goodRun >= QUALITY_CLEAR_S) hideQuality(); else showQuality(due ?? qualityKind, rtt); return; }
353
+ if (due !== null && sinceChip >= QUALITY_GAP_S) showQuality(due, rtt);
354
+ };
355
+ scope.interval(1000, sampleQuality);
276
356
  const link = (next: LinkState, why?: string): void => {
277
357
  state = next; reason = why;
358
+ if (state !== 'live') hideQuality();
278
359
  paintBanner();
279
360
  // down again: the notice goes, and a stop card (lost, after Try again) gives way to the banner
280
361
  if (down()) {
@@ -282,6 +363,9 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
282
363
  if (open?.kind === 'stop') close();
283
364
  if (hooks.why() === 'offline') { offlineCard(); return; }
284
365
  if (open?.kind === 'offline') close();
366
+ const away = hooks.progress().away;
367
+ if (away !== undefined) { awayCard(away); return; }
368
+ if (open?.kind === 'away') close();
285
369
  // a hold card follows its banner: a new cause (silent to restart) or 35 s down redraws it, else it just ticks
286
370
  if (open?.kind === 'hold' && open.key !== `${state}:${hooks.why()}` && open.what !== undefined) hold(open.what, open.chat === true); else open?.paint();
287
371
  return;
@@ -11,8 +11,9 @@ const NEW_BUILD_BUTTON = 'min-height:44px;padding:8px 32px;border:1px solid #8fe
11
11
  export function newBuildPanel(scope: Scope, again: () => Promise<boolean>, reload: () => void, parent: HTMLElement = document.body): void {
12
12
  if (document.getElementById('ws-new-build') !== null) return;
13
13
  const panel = scope.ownNode(document.createElement('div')), words = document.createElement('p'), go = document.createElement('button');
14
- panel.id = 'ws-new-build'; panel.setAttribute('role', 'alertdialog'); panel.style.cssText = NEW_BUILD;
15
- words.textContent = 'A new build is out. Reload to play on.'; words.style.margin = '0';
14
+ // FM5 mode 23 (`version-skew`): the page's build and the world's differ, and the one automatic reload didn't land
15
+ panel.id = 'ws-new-build'; panel.dataset['failmode'] = 'version-skew'; panel.setAttribute('role', 'alertdialog'); panel.style.cssText = NEW_BUILD;
16
+ words.textContent = 'A new version is out. Reload to play on.'; words.style.margin = '0';
16
17
  go.type = 'button'; go.textContent = 'Reload'; go.style.cssText = NEW_BUILD_BUTTON;
17
18
  // RL3: the panel is already full-page; the tap's own turn turns it and its button into RELOADING
18
19
  scope.listen(go, 'click', () => { go.disabled = true; go.setAttribute('aria-busy', 'true'); go.textContent = 'Reloading…'; words.textContent = 'Reloading'; reload(); });
@@ -15,11 +15,32 @@ const importKey = async (publicKey: string): Promise<CryptoKey> => {
15
15
  }
16
16
  };
17
17
 
18
+ /** FM5: why a release read failed, as the page can measure it. A browser never says DNS or TLS, so `network` is all an opaque fetch
19
+ * failure is; `offline` is one the browser itself calls offline; `portal` is an answer that isn't the file (HTML, an unapproved redirect,
20
+ * malformed text), which could be a captive portal or a broken origin. */
21
+ export type ReleaseFault =
22
+ | { readonly kind: 'offline' } | { readonly kind: 'network' } | { readonly kind: 'timeout'; readonly ms: number }
23
+ | { readonly kind: 'status'; readonly status: number; readonly retryAfterMs: number | null }
24
+ | { readonly kind: 'portal'; readonly why: 'html' | 'redirect' | 'malformed' } | { readonly kind: 'unsigned' };
25
+ /** A failed release read and what failed. Its message keeps the technical words for Details; a player's screen never shows it raw. */
26
+ export class ReleaseReadError extends Error {
27
+ readonly fault: ReleaseFault;
28
+ constructor(message: string, fault: ReleaseFault, cause?: unknown) { super(message, cause === undefined ? undefined : { cause }); this.name = 'ReleaseReadError'; this.fault = fault; }
29
+ }
30
+
18
31
  /** The file's text as what it says. It throws on a bad signature, and where a browser has no Ed25519. `publicKey` is SPKI DER in hex. */
19
32
  export async function readSignedRelease(text: string, publicKey: string): Promise<ReleaseFile> {
20
- const signed = v.parse(SignedSchema, JSON.parse(text)), key = await importKey(publicKey);
21
- if (!await crypto.subtle.verify({ name: 'Ed25519' }, key, hexBytes(signed.signature), new TextEncoder().encode(signed.body))) throw new Error('A release file has a bad signature');
22
- return v.parse(ReleaseSchema, JSON.parse(signed.body));
33
+ let signed: v.InferOutput<typeof SignedSchema>;
34
+ try { signed = v.parse(SignedSchema, JSON.parse(text)); } catch (error) { throw new ReleaseReadError('A release file that is not a signed file', { kind: 'portal', why: 'malformed' }, error); }
35
+ const key = await importKey(publicKey);
36
+ if (!await crypto.subtle.verify({ name: 'Ed25519' }, key, hexBytes(signed.signature), new TextEncoder().encode(signed.body))) throw new ReleaseReadError('A release file has a bad signature', { kind: 'unsigned' });
37
+ try { return v.parse(ReleaseSchema, JSON.parse(signed.body)); } catch (error) { throw new ReleaseReadError('A signed release file this page cannot read', { kind: 'portal', why: 'malformed' }, error); }
38
+ }
39
+ /** FM5 mode 12: a `Retry-After` of seconds or an HTTP date, in ms from `now`; anything else (or past 10 min) is no answer. */
40
+ export function retryAfterMs(header: string | null, now: number = Date.now()): number | null {
41
+ if (header === null) return null;
42
+ const text = header.trim(), ms = /^\d{1,6}$/u.test(text) ? Number(text) * 1000 : /[a-z]/iu.test(text) ? Date.parse(text) - now : Number.NaN;
43
+ return Number.isFinite(ms) && ms >= 0 && ms <= 600_000 ? Math.round(ms) : null;
23
44
  }
24
45
  /** FM5 (catalogue mode 11): a release read that has not answered, body and all, in 8 s has failed. */
25
46
  export const RELEASE_DEADLINE_MS = 8000;
@@ -30,19 +51,24 @@ export const KEPT_RELEASE_MS: number = 7 * 24 * 60 * 60 * 1000;
30
51
  export async function fetchSignedRelease(url: string, publicKey: string, deadlineMs: number = RELEASE_DEADLINE_MS, read: typeof fetch = fetch): Promise<ReleaseFile> {
31
52
  return readSignedRelease(await fetchReleaseText(url, deadlineMs, read), publicKey);
32
53
  }
33
- async function fetchReleaseText(url: string, deadlineMs: number, read: typeof fetch): Promise<string> {
54
+ const browserOnline = (): boolean => typeof navigator === 'undefined' || navigator.onLine;
55
+ async function fetchReleaseText(url: string, deadlineMs: number, read: typeof fetch, online: () => boolean = browserOnline): Promise<string> {
34
56
  const abort = new AbortController(), scope = new Scope('online.release-read');
35
57
  scope.timeout(deadlineMs, () => { abort.abort(); });
36
58
  try {
37
59
  const response = await read(url, { cache: 'no-store', signal: abort.signal });
38
- if (!response.ok) throw new Error(`No release file at ${url}: ${String(response.status)}`);
39
- return await response.text();
60
+ if (!response.ok) throw new ReleaseReadError(`No release file at ${url}: ${String(response.status)}`, { kind: 'status', status: response.status, retryAfterMs: retryAfterMs(response.headers.get('retry-after')) });
61
+ // FM5 mode 38: an answer from somewhere else, or a page instead of the file, isn't the world's file; nothing in it is followed
62
+ if (response.redirected && response.url !== '' && new URL(response.url).origin !== new URL(url).origin) throw new ReleaseReadError(`The release read was sent to another address (${String(response.status)})`, { kind: 'portal', why: 'redirect' });
63
+ const text = await response.text();
64
+ if (/html/iu.test(response.headers.get('content-type') ?? '') || /^\s*</u.test(text)) throw new ReleaseReadError(`A page instead of the release file (${response.headers.get('content-type') ?? 'no type'})`, { kind: 'portal', why: 'html' });
65
+ return text;
40
66
  } catch (error) {
41
- if (abort.signal.aborted) throw new Error(`No release file at ${url} in ${String(deadlineMs)} ms`, { cause: error });
42
- throw error;
67
+ if (error instanceof ReleaseReadError) throw error;
68
+ if (abort.signal.aborted) throw new ReleaseReadError(`No release file at ${url} in ${String(deadlineMs)} ms`, { kind: 'timeout', ms: deadlineMs }, error);
69
+ throw new ReleaseReadError(error instanceof Error ? error.message : String(error), online() ? { kind: 'network' } : { kind: 'offline' }, error);
43
70
  } finally { scope.dispose(); }
44
71
  }
45
-
46
72
  /** OF4: the last release file a page read and believed: which release, when, and its text as signed. */
47
73
  export interface KeptRelease { readonly of: string; readonly at: number; readonly text: string }
48
74
  export interface ReleaseKeep { readonly read: () => KeptRelease | null; readonly write: (kept: KeptRelease) => void }
@@ -58,17 +84,62 @@ export async function keptRelease(url: string, publicKey: string, keep: ReleaseK
58
84
 
59
85
  /** What a page dials from: the file, and when that was the kept copy, the fresh read still under way (null if it fails). */
60
86
  export interface ReleaseToDial { readonly file: ReleaseFile; readonly fresh: Promise<ReleaseFile | null> | null }
87
+
88
+ /** FM5: the screen a failed read with no kept copy shows (meta MMO-FAILURE-MODES-PLAN modes 1, 11, 12, 37 to 39). */
89
+ export type ReleaseScreen = 'offline-launch' | 'release-5xx' | 'release-429' | 'release-404' | 'captive-portal' | 'release-unsigned';
90
+ export function releaseScreen(fault: ReleaseFault): ReleaseScreen {
91
+ if (fault.kind === 'offline') return 'offline-launch';
92
+ if (fault.kind === 'portal') return 'captive-portal';
93
+ if (fault.kind === 'unsigned') return 'release-unsigned';
94
+ if (fault.kind === 'status' && fault.status === 429) return 'release-429';
95
+ if (fault.kind === 'status' && fault.status === 404) return 'release-404';
96
+ return 'release-5xx';
97
+ }
98
+ /** Mode 11's ladder: 2, 4, 8, 16 s, then every 30 s. */
99
+ const LADDER_MS: readonly number[] = [2000, 4000, 8000, 16_000], LADDER_END_MS = 30_000;
100
+ /** Mode 12: a 429 with no readable Retry-After waits this long first. Mode 37: a 404 is read again each minute. */
101
+ const BUSY_MS = 20_000, MISSING_MS = 60_000;
102
+ /** FM5's retry policy: how long after the `attempt`th failed read (from 0) the page reads again by itself, or null when only the player
103
+ * (Try again), the network coming back or the page coming into view reads again: offline, a captive portal, a file that fails its
104
+ * signature (no retry loop on a file we can't verify). */
105
+ export function releaseRetryMs(fault: ReleaseFault, attempt: number): number | null {
106
+ const ladder = LADDER_MS[attempt] ?? LADDER_END_MS;
107
+ if (fault.kind === 'offline' || fault.kind === 'portal' || fault.kind === 'unsigned') return null;
108
+ if (fault.kind !== 'status') return ladder;
109
+ // a Retry-After of 0 is no licence to loop: never sooner than the ladder's first step, and never sooner than the first refusal's wait
110
+ if (fault.status === 429) return Math.max(fault.retryAfterMs ?? BUSY_MS, LADDER_MS[0] ?? 2000, fault.retryAfterMs === null ? ladder : 0);
111
+ return fault.status === 404 ? MISSING_MS : ladder;
112
+ }
113
+ /** FM5: what a page shows while it has no release file to dial from. `after` shows the fault and settles when the page should read again
114
+ * (the policy's wait, Try again, the network back); it rejects when the player leaves. `done` closes whatever it showed. */
115
+ export interface ReleaseWait {
116
+ readonly after: (fault: ReleaseFault, attempt: number, retryMs: number | null, detail: string) => Promise<void>;
117
+ readonly done: () => void;
118
+ }
119
+
61
120
  /** OF4: the release file a page dials from. A verified kept copy answers at once, so a load never waits on the read; the fresh read
62
- * replaces it once its own signature holds. With no copy the page waits for the read (8 s at most), and a failed read throws. */
63
- export async function releaseToDial(url: string, publicKey: string, ports: { readonly keep: ReleaseKeep; readonly fetch?: typeof fetch; readonly now?: () => number; readonly deadlineMs?: number }): Promise<ReleaseToDial> {
121
+ * replaces it once its own signature holds. With no copy the page waits for the read (8 s at most each), and a failed read throws, or,
122
+ * given `wait` (FM5), shows why and reads again by its policy until a verified file answers or the player leaves. */
123
+ export async function releaseToDial(url: string, publicKey: string, ports: { readonly keep: ReleaseKeep; readonly fetch?: typeof fetch; readonly now?: () => number; readonly deadlineMs?: number; readonly wait?: ReleaseWait; readonly online?: () => boolean }): Promise<ReleaseToDial> {
64
124
  const now = ports.now ?? Date.now, kept = await keptRelease(url, publicKey, ports.keep, now());
65
- const reading = (async (): Promise<ReleaseFile> => {
66
- const text = await fetchReleaseText(url, ports.deadlineMs ?? RELEASE_DEADLINE_MS, ports.fetch ?? fetch), file = await readSignedRelease(text, publicKey);
125
+ const reading = async (): Promise<ReleaseFile> => {
126
+ const text = await fetchReleaseText(url, ports.deadlineMs ?? RELEASE_DEADLINE_MS, ports.fetch ?? fetch, ports.online), file = await readSignedRelease(text, publicKey);
67
127
  // a release only moves forward (J179, the server's own rule in releaseFile.ts): an older signed file never replaces the kept one
68
128
  if (kept !== null && file.serial < kept.serial) throw new Error(`A release file older than the kept one (${String(file.serial)} < ${String(kept.serial)})`);
69
129
  try { ports.keep.write({ of: url, at: now(), text }); } catch { /* a page that can keep nothing reads again next time */ }
70
130
  return file;
71
- })();
72
- if (kept === null) return { file: await reading, fresh: null };
73
- return { file: kept, fresh: reading.catch(() => null) };
131
+ };
132
+ if (kept !== null) return { file: kept, fresh: reading().catch(() => null) };
133
+ const { wait } = ports;
134
+ if (wait === undefined) return { file: await reading(), fresh: null };
135
+ for (let attempt = 0; ; attempt++) {
136
+ try {
137
+ const file = await reading();
138
+ wait.done();
139
+ return { file, fresh: null };
140
+ } catch (error) {
141
+ if (!(error instanceof ReleaseReadError)) { wait.done(); throw error; }
142
+ await wait.after(error.fault, attempt, releaseRetryMs(error.fault, attempt), error.message);
143
+ }
144
+ }
74
145
  }