@wildshard/engine 0.1.15 → 0.1.18

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 (262) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/index.html +157 -11
  3. package/lint/engine-sides.json +23 -0
  4. package/lint/host-callback-syntax.mjs +2 -1
  5. package/lint/host-callbacks.mjs +3 -3
  6. package/lint/host-files.mjs +5 -4
  7. package/lint/host-register.json +496 -0
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +2 -2
  10. package/lint/shard-imports.d.mts +1 -0
  11. package/lint/shard-imports.mjs +60 -13
  12. package/lint/shard-source.d.mts +9 -0
  13. package/lint/shard-source.mjs +91 -0
  14. package/lint/shardfile-boundaries.mjs +10 -8
  15. package/lint/sim-closure.mjs +6 -3
  16. package/lint/wildshard-plugin.d.ts +4 -0
  17. package/lint/wildshard-plugin.js +44 -27
  18. package/package.json +24 -6
  19. package/scripts/app-build/buildIdentity.d.mts +3 -1
  20. package/scripts/app-build/buildIdentity.mjs +25 -5
  21. package/scripts/app-build/builtAt.d.mts +4 -0
  22. package/scripts/app-build/builtAt.mjs +21 -0
  23. package/scripts/app-build/outputProducts.d.mts +3 -0
  24. package/scripts/app-build/outputProducts.mjs +31 -0
  25. package/scripts/app-build/serviceWorker.ts +16 -2
  26. package/scripts/app-build/versionFiles.ts +2 -1
  27. package/scripts/app-build-pipeline.mjs +7 -1
  28. package/scripts/audio-download-proof.mjs +843 -0
  29. package/scripts/build-app.mjs +4 -0
  30. package/scripts/build-mirror.d.mts +2 -0
  31. package/scripts/build-mirror.mjs +5 -4
  32. package/scripts/built-product.mjs +3 -3
  33. package/scripts/cell-mem/metrics-preload.mjs +65 -0
  34. package/scripts/cell-mem-bench.mjs +130 -0
  35. package/scripts/check-chunks.mjs +2 -1
  36. package/scripts/check-devserver.mjs +1 -1
  37. package/scripts/chromium-keychain-check.mjs +4 -2
  38. package/scripts/chromium-keychain.mjs +3 -1
  39. package/scripts/cook.mjs +7 -3
  40. package/scripts/devices.d.mts +4 -0
  41. package/scripts/devices.mjs +39 -0
  42. package/scripts/devserver-client.d.mts +7 -0
  43. package/scripts/devserver-client.mjs +85 -0
  44. package/scripts/doctor-proof.mjs +1 -1
  45. package/scripts/e2e-faults.mjs +159 -0
  46. package/scripts/engine-ci-budget.ts +7 -1
  47. package/scripts/format-lock.mjs +20 -11
  48. package/scripts/generate-title-launch.mjs +3 -2
  49. package/scripts/grid-crossing-walk-proof.mjs +30 -11
  50. package/scripts/heavy-lane.py +25 -1
  51. package/scripts/host-ruler/register-migrate.mjs +242 -0
  52. package/scripts/host-ruler/register.d.mts +36 -0
  53. package/scripts/host-ruler/register.mjs +116 -0
  54. package/scripts/host-ruler/roots.d.mts +29 -0
  55. package/scripts/host-ruler/roots.mjs +333 -0
  56. package/scripts/host-ruler/server-roots.d.mts +23 -0
  57. package/scripts/host-ruler/server-roots.mjs +272 -0
  58. package/scripts/main-watch.d.mts +1 -1
  59. package/scripts/main-watch.mjs +10 -6
  60. package/scripts/map-hash.mjs +3 -6
  61. package/scripts/memory-proof.mjs +158 -0
  62. package/scripts/mmo-bots.mjs +2 -2
  63. package/scripts/offline-proof-rules.d.mts +5 -2
  64. package/scripts/offline-proof-rules.mjs +43 -6
  65. package/scripts/offline-proof.mjs +15 -6
  66. package/scripts/online-rig.mjs +4 -4
  67. package/scripts/page-release/flow.d.mts +1 -0
  68. package/scripts/page-release/flow.mjs +6 -2
  69. package/scripts/page-release.mjs +5 -1
  70. package/scripts/physics-route.json +0 -71
  71. package/scripts/pins-catalogue.ts +103 -0
  72. package/scripts/pins-reuse.mjs +3 -1
  73. package/scripts/pins.ts +22 -14
  74. package/scripts/preview-grid.ts +203 -0
  75. package/scripts/road-preload-proof.mjs +167 -0
  76. package/scripts/server-release/publish.mjs +2 -2
  77. package/scripts/server-release/served-slug.d.mts +2 -0
  78. package/scripts/server-release/served-slug.mjs +10 -0
  79. package/scripts/server-release/sign.d.mts +1 -0
  80. package/scripts/server-release/sign.mjs +3 -7
  81. package/scripts/shard-components.mjs +0 -2
  82. package/scripts/shard-outputs.d.mts +8 -0
  83. package/scripts/shard-outputs.mjs +45 -11
  84. package/scripts/side-parity.d.mts +2 -1
  85. package/scripts/side-parity.mjs +25 -4
  86. package/scripts/test-amber.d.mts +1 -0
  87. package/scripts/test-amber.mjs +10 -0
  88. package/scripts/test-products.json +3 -3
  89. package/scripts/tier-textures-proof.mjs +101 -0
  90. package/scripts/tier-textures.mjs +60 -0
  91. package/scripts/tracked-public.d.mts +1 -0
  92. package/scripts/tracked-public.mjs +17 -0
  93. package/scripts/tsconfig.json +1 -0
  94. package/scripts/vps/wildshard-config +79 -23
  95. package/scripts/worker-client-play.mjs +1 -0
  96. package/scripts/worker-client-proof.mjs +1 -1
  97. package/scripts/worker-client-slug.mjs +44 -0
  98. package/src/cli/engine.mjs +8 -0
  99. package/src/client/app/bootRoute.ts +4 -1
  100. package/src/client/app/dropModal.ts +15 -2
  101. package/src/client/app/entry.ts +96 -13
  102. package/src/client/app/slugPath.ts +5 -0
  103. package/src/client/engine/audio/Audio.ts +20 -2
  104. package/src/client/engine/boot/bakedTextures.ts +3 -2
  105. package/src/client/engine/boot/bootTrace.ts +6 -1
  106. package/src/client/engine/boot/bytes.ts +4 -3
  107. package/src/client/engine/boot/clearDownloads.ts +1 -1
  108. package/src/client/engine/boot/contentRead.ts +4 -0
  109. package/src/client/engine/boot/dropNotice.ts +20 -6
  110. package/src/client/engine/boot/gpuFiles.ts +25 -2
  111. package/src/client/engine/boot/lastEnd.ts +8 -2
  112. package/src/client/engine/boot/parsedPages.ts +127 -58
  113. package/src/client/engine/boot/shardPrefetch.ts +7 -1
  114. package/src/client/engine/boot/sw.ts +19 -0
  115. package/src/client/engine/build.d.ts +2 -0
  116. package/src/client/engine/core/Game.ts +29 -3
  117. package/src/client/engine/core/GpuRecovery.ts +7 -0
  118. package/src/client/engine/core/Volumetrics.ts +5 -0
  119. package/src/client/engine/core/assets.ts +27 -20
  120. package/src/client/engine/core/bootstrap.ts +5 -3
  121. package/src/client/engine/core/ktx2.ts +84 -11
  122. package/src/client/engine/debug/probe.ts +18 -1
  123. package/src/client/engine/explore/Compare.ts +2 -2
  124. package/src/client/engine/explore/TouchFly.ts +3 -5
  125. package/src/client/engine/fx/LightPool.ts +41 -1
  126. package/src/client/engine/input/dom.ts +12 -0
  127. package/src/client/engine/net/predictor.ts +6 -2
  128. package/src/client/engine/player/Player.ts +10 -2
  129. package/src/client/engine/player/TouchControls.ts +12 -4
  130. package/src/client/engine/pwa/sw.js +59 -11
  131. package/src/client/engine/render/drawCheck.ts +96 -0
  132. package/src/client/engine/render/precompile.ts +20 -14
  133. package/src/client/engine/saves/staleBuildNote.ts +46 -0
  134. package/src/client/engine/telemetry/browserErrors.ts +161 -21
  135. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  136. package/src/client/engine/telemetry/screenOutbox.ts +61 -0
  137. package/src/client/engine/telemetry/staleBuildReport.ts +12 -0
  138. package/src/client/engine/ui/DeathFade.ts +99 -11
  139. package/src/client/engine/ui/ErrorModal.ts +13 -6
  140. package/src/client/engine/ui/Feedback.ts +2 -1
  141. package/src/client/engine/ui/Loading.ts +10 -6
  142. package/src/client/engine/ui/Map.ts +2 -1
  143. package/src/client/engine/ui/WeaponStrip.ts +2 -1
  144. package/src/client/engine/ui/backGuard.ts +104 -0
  145. package/src/client/engine/ui/hudAdapters.ts +30 -4
  146. package/src/client/engine/ui/loading.css +17 -0
  147. package/src/client/engine/ui/namePrompt.ts +6 -5
  148. package/src/client/engine/ui/styles/combat.css +12 -0
  149. package/src/client/engine/ui/styles/namePrompt.css +4 -2
  150. package/src/client/game/boot/audio.generated.ts +0 -396
  151. package/src/client/game/boot/bytes.generated.ts +42 -71
  152. package/src/client/game/boot/versions.generated.ts +0 -13
  153. package/src/client/game/compendium/keepsakes.ts +16 -6
  154. package/src/client/game/grapple/tool.ts +10 -7
  155. package/src/client/game/grid/area.ts +38 -0
  156. package/src/client/game/grid/cellLoading.ts +23 -12
  157. package/src/client/game/grid/cellScreens.ts +39 -74
  158. package/src/client/game/grid/live.ts +28 -2
  159. package/src/client/game/grid/liveSession.ts +54 -10
  160. package/src/client/game/grid/menu.ts +4 -0
  161. package/src/client/game/grid/nearPlaceholderPlan.ts +8 -0
  162. package/src/client/game/grid/nearPlaceholderView.ts +9 -3
  163. package/src/client/game/grid/neighbourPanels.ts +10 -1
  164. package/src/client/game/grid/oneWayIn.ts +92 -27
  165. package/src/client/game/grid/pageEntry.ts +19 -0
  166. package/src/client/game/grid/pageShell.ts +1 -1
  167. package/src/client/game/grid/placedCards.ts +55 -0
  168. package/src/client/game/grid/placedCells.ts +131 -0
  169. package/src/client/game/grid/plotAudio.ts +114 -0
  170. package/src/client/game/grid/products.ts +55 -5
  171. package/src/client/game/grid/regionalRuntime.ts +6 -0
  172. package/src/client/game/grid/regionalWorld.ts +15 -2
  173. package/src/client/game/grid/roadCull.ts +44 -14
  174. package/src/client/game/grid/roadLookPlatform.ts +2 -2
  175. package/src/client/game/grid/roadTileBacking.ts +13 -3
  176. package/src/client/game/grid/session.ts +47 -22
  177. package/src/client/game/grid/shardfileFar.ts +9 -3
  178. package/src/client/game/grid/spawnGround.ts +68 -0
  179. package/src/client/game/grid/voidLook.ts +29 -23
  180. package/src/client/game/loot/runtime.ts +3 -1
  181. package/src/client/game/mainMenu.ts +14 -6
  182. package/src/client/game/riding/hud.ts +6 -4
  183. package/src/client/game/session/finish.ts +22 -4
  184. package/src/client/game/session/play.ts +8 -2
  185. package/src/client/game/session/session.ts +4 -1
  186. package/src/client/game/shard/titleList.ts +6 -2
  187. package/src/client/game/shardfile/clientWorker.ts +43 -13
  188. package/src/client/game/shardfile/serverRoute.ts +10 -22
  189. package/src/client/game/slugPage.css +11 -0
  190. package/src/client/game/slugPage.ts +84 -0
  191. package/src/client/game/systems/viewmodel/heldView.ts +6 -3
  192. package/src/client/game/titleDeck.ts +56 -32
  193. package/src/client/host/online/doctor.ts +7 -6
  194. package/src/client/host/online/linkScreens.ts +16 -0
  195. package/src/client/host/online/release.ts +51 -5
  196. package/src/client/host/online/shell.ts +62 -27
  197. package/src/client/host/standalone/shell.ts +7 -3
  198. package/src/cook/game/audioReport.ts +57 -0
  199. package/src/cook/game/entryTotals.ts +26 -6
  200. package/src/cook/game/installedRuntimeReads.ts +3 -0
  201. package/src/cook/game/shardCook.ts +38 -8
  202. package/src/cook/game/tierTextures.ts +276 -0
  203. package/src/e2e/smoke/game.ts +19 -14
  204. package/src/e2e/smoke/page-globals.d.ts +9 -8
  205. package/src/e2e/smoke/template2.spec.ts +8 -7
  206. package/src/server/engine/sim/respawn.ts +6 -1
  207. package/src/server/engine/sim.ts +3 -0
  208. package/src/server/game/grid/simulation.ts +35 -0
  209. package/src/server/game/loot/harvest.ts +2 -0
  210. package/src/server/game/loot/keepsakeProgression.ts +40 -0
  211. package/src/server/game/loot/playerOwned.ts +5 -1
  212. package/src/server/game/plugin/simulation.ts +4 -0
  213. package/src/server/game/population/nativeBake.ts +2 -1
  214. package/src/server/game/quest/chapterRecords.ts +2 -0
  215. package/src/server/game/quest/serverChapters.ts +4 -0
  216. package/src/server/game/quest/serverDoors.ts +11 -5
  217. package/src/server/game/roomRespawn.ts +4 -0
  218. package/src/server/game/shardfile/installedSides.ts +18 -0
  219. package/src/server/game/shardfile/nativeAssemblyHosts.ts +19 -10
  220. package/src/server/game/shardfile/nativeAssemblyInput.ts +1 -4
  221. package/src/server/host/bake/headlessWorker.ts +5 -1
  222. package/src/server/host/dedicated/cellHost.ts +98 -29
  223. package/src/server/host/dedicated/cellProtocol.ts +11 -1
  224. package/src/server/host/dedicated/cellWorker.ts +9 -3
  225. package/src/server/host/dedicated/crossing.ts +6 -2
  226. package/src/server/host/dedicated/dedicatedRoom.ts +21 -8
  227. package/src/server/host/dedicated/gridCells.ts +52 -9
  228. package/src/server/host/dedicated/main.ts +31 -12
  229. package/src/server/host/dedicated/placementFile.ts +56 -0
  230. package/src/server/host/dedicated/releaseFile.ts +17 -10
  231. package/src/server/host/dedicated/roadRoom.ts +21 -5
  232. package/src/server/host/dedicated/socketTransport.ts +2 -1
  233. package/src/server/host/dedicated/workerTable.ts +13 -1
  234. package/src/server/host/dedicated/world.ts +111 -10
  235. package/src/server/host/headlessRuntime.ts +10 -5
  236. package/src/server/host/installers.ts +62 -0
  237. package/src/server/host/openWorld.ts +59 -0
  238. package/src/server/host/ropeDecks.ts +2 -0
  239. package/src/server/host/standalone/cellWorld.ts +25 -19
  240. package/src/server/host/standalone/fallFloor.ts +2 -2
  241. package/src/server/host/standalone/gridServer.ts +7 -4
  242. package/src/server/host/standalone/roadWorld.ts +41 -4
  243. package/src/shared/engine/audio/bootAudio.ts +33 -0
  244. package/src/shared/engine/level/spec.ts +3 -3
  245. package/src/shared/engine/net/acts.ts +3 -0
  246. package/src/shared/engine/net/deviceWord.ts +138 -0
  247. package/src/shared/engine/net/socketFrames.ts +7 -4
  248. package/src/shared/engine/physics/query.ts +27 -0
  249. package/src/shared/engine/physics/terrain.ts +19 -28
  250. package/src/shared/engine/saves/saves.lock.json +15 -0
  251. package/src/shared/engine/sim/actRoutes.ts +2 -0
  252. package/src/shared/game/compendium/keepsakeProgression.ts +24 -0
  253. package/src/shared/game/grid/catalogue.ts +12 -5
  254. package/src/shared/game/grid/catalogueSlot.ts +18 -0
  255. package/src/shared/game/grid/farProxy.ts +6 -5
  256. package/src/shared/game/grid/pageMode.ts +1 -1
  257. package/src/shared/game/grid/placementRows.ts +33 -0
  258. package/src/shared/game/grid/roadLayout.ts +26 -3
  259. package/src/shared/game/grid/singleplayer.json +0 -13
  260. package/src/shared/game/grid/voidFloor.ts +122 -0
  261. package/src/shared/game/strings.ts +15 -0
  262. package/src/shared/host/standalone/netInput.ts +2 -1
@@ -2,6 +2,7 @@ import { isDev } from '@wildshard/engine/core/devMode';
2
2
  import type { GridMode } from '../../../shared/game/grid/catalogue';
3
3
 
4
4
  declare const __DEVSERVER__: boolean;
5
+ declare const __PREPARATION_ONLY__: boolean;
5
6
  /**
6
7
  * The main menu's two entries (SHARD-PLATFORM §3.3, G58, G61, SF21a): **Select a shard** (today's one-shard flow) and
7
8
  * **Infinite Wildshard** (the 5 × 5 grid). What each mode lets the player enter is the §3.3 table:
@@ -19,6 +20,9 @@ export const GRID_GATES_PASSED = false;
19
20
 
20
21
  /** The author's build-time switch (`vite build --mode devserver`, SF8c); a unit test's Node has no define, so false */
21
22
  export const DEVSERVER: boolean = typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__;
23
+ /** SHARD-AUTHORING SA43: a production-renderer build made with `WILDSHARD_PREPARATION_ONLY=1` (never released:
24
+ * check-devserver refuses it), the client `wildshard prepare` serves with the author's draft inline */
25
+ export const PREPARATION_ONLY: boolean = typeof __PREPARATION_ONLY__ === 'boolean' && __PREPARATION_ONLY__;
22
26
 
23
27
  /** what the title is allowed to show and enter right now */
24
28
  export interface MenuMode { readonly developer: boolean; readonly devserver: boolean }
@@ -58,3 +58,11 @@ export function planNearPlaceholders(cells: readonly GridCell[], pitch: number,
58
58
  export function placeholderBlocksTiles(instance:string,entered:string|null,registered:boolean,ownsNear:boolean,absentNear:boolean):boolean {
59
59
  return instance!==entered&&!registered&&(ownsNear||absentNear);
60
60
  }
61
+
62
+ /** DL17 (G872) with D189: the cell the player is in, drawn by its regional runtime, skips its tile-view admission only when
63
+ * that runtime draws its own ground, through the tile registration (`registered`) or its manifest's `cellGround: 'world'`.
64
+ * A runtime whose ground is the cell's ring tiles (Pine) admits them like any neighbour: skipped, its far proxy stayed over
65
+ * the spawn and its ground never drew. */
66
+ export function admitsCellTiles(instance:string,drawn:string|null,registered:boolean,ownGround:boolean):boolean {
67
+ return instance!==drawn||(!registered&&!ownGround);
68
+ }
@@ -73,6 +73,11 @@ export class NearPlaceholders {
73
73
  ...(this.host.limit === undefined ? {} : { limit: this.host.limit }) });
74
74
  this.eye = { x: Math.round(eye.x * 10) / 10, z: Math.round(eye.z * 10) / 10 };
75
75
  const wanted = new Map(plan.cells.map(c => [c.instance, c.distance]));
76
+ // QA 2026-11-13 (Jake, Driftwood from the road): a cell turns live a few metres before its runtime draws it (the entry
77
+ // waits at its wall). An owning near view already drawn stays until the runtime covers the cell (its root hides);
78
+ // dropped at once, its far proxy and props-only tiles drew the props over holes. Never started for the entered cell.
79
+ const held = entered === null ? undefined : this.slots.get(entered);
80
+ if (entered !== null && held?.ready === true && held.owns && this.host.root(entered)?.visible === true) wanted.set(entered, plan.cells.find(c => c.instance === entered)?.distance ?? 0);
76
81
  this.distances.clear();
77
82
  for (const [instance, distance] of wanted) this.distances.set(instance, Math.round(distance));
78
83
  for (const [instance, slot] of this.slots) if (!wanted.has(instance)) this.drop(slot);
@@ -86,9 +91,10 @@ export class NearPlaceholders {
86
91
 
87
92
  /** Mirror the rings' refinement onto a cell's near view (the regions its L1 / L0 tiles now draw). */
88
93
  remask(instance: string): void {
89
- const view = this.slots.get(instance)?.view;
94
+ const slot = this.slots.get(instance), view = slot?.view;
90
95
  if (view !== null && view !== undefined) {
91
- view.mask(this.host.mask(instance));
96
+ // an owning near view draws the whole cell: tiles refined beside it (the entry's arrival ring) never cut holes in it
97
+ view.mask(slot?.owns === true ? new Set<number>() : this.host.mask(instance));
92
98
  if (this.slots.get(instance)?.ready !== true) view.mesh.visible = false;
93
99
  }
94
100
  }
@@ -165,7 +171,7 @@ export class NearPlaceholders {
165
171
  }
166
172
  if (!current()) return;
167
173
  slot.ready = true;
168
- view.mask(this.host.mask(instance));
174
+ view.mask(owns ? new Set<number>() : this.host.mask(instance));
169
175
  this.host.cover(instance, true);
170
176
  };
171
177
  void run();
@@ -12,9 +12,10 @@ import type { Group, Object3D } from 'three';
12
12
  import type { ClientTileViews } from '../shardfile/clientViews';
13
13
  import type { Shardfile } from '@wildshard/format/shardSchema';
14
14
  import type { GridCell } from '../../../shared/game/grid/assembly';
15
+ import type { ProbeAreaTarget } from '@wildshard/engine/debug/probe';
15
16
 
16
17
  /** What the panels read of a cell the live host has admitted: the solids of its world, and a field's row where this page has one. */
17
- export interface PanelRegion { readonly colliders: ReadonlyMap<string, { readonly setActive: (active: boolean) => void }>; readonly field: (name: string) => number | undefined }
18
+ export interface PanelRegion { readonly colliders: ReadonlyMap<string, { readonly active: () => boolean; readonly setActive: (active: boolean) => void }>; readonly field: (name: string) => number | undefined }
18
19
  /** The page scope the panels live and die with (the views' own scope type). */
19
20
  type PageScope = Parameters<ClientTileViews['panels']>[3];
20
21
  export interface NeighbourPanelPorts {
@@ -73,6 +74,14 @@ export class NeighbourPanels {
73
74
  return new Map([...this.cells].map(([id, cell]) => [id, cell.bindings.map((b) => ({ panel: b.row.panel, visible: b.panel.visible }))]));
74
75
  }
75
76
 
77
+ /** A cell's door panels as the probe reads them (T2E-1b): drawn, and solid while every collider stands in its admitted
78
+ * region (a panel with no colliders reads solid, as `shardfile.targets()` does). */
79
+ targets(instance: string): readonly ProbeAreaTarget[] {
80
+ const cell = this.cells.get(instance), region = this.ports.region(instance);
81
+ return cell?.bindings.map(({ row, panel }) => ({ panel: row.panel, visible: panel.visible,
82
+ solid: region !== undefined && row.colliders.every(id => region.colliders.get(id)?.active() === true) })) ?? [];
83
+ }
84
+
76
85
  private sync(cell: CellPanels): void {
77
86
  const region = this.ports.region(cell.instance);
78
87
  for (const { row, panel, fallback } of cell.bindings) {
@@ -1,16 +1,17 @@
1
1
  // GO7 (meta MMO-PLAN MP1G, DG4; MMO-ZONE-SELECT ZS4's goto and ZS5's retirement): one way in. On a build with a world (GO4's gate),
2
2
  // Shard select → a grid shard enters the grid at that shard's cell, so Shard select only changes the spawn cell of the one online
3
3
  // world, and no online page boots a bordered `'shard'` page for a grid shard. J300 (GRID-CROSSING GC20): that holds when the world's
4
- // word is missing, late or never kept; only a world known to host one cell (production before GC16) keeps GO4's one-shard page. A
5
- // shard the grid doesn't place (OFFLINE OF3's) keeps today's one-shard page. J311: a build with no world (preview) does the same with
4
+ // word is missing, late or never kept; only a world known to host one cell (production before GC16) keeps GO4's one-shard page. On a
5
+ // world build, a shard the world doesn't open (the grid doesn't place it, or its kept word leaves it out) is never entered (OFFLINE OF3). J311: a build with no world (preview) does the same with
6
6
  // its in-page server, which hosts the whole grid: a Shard select tap enters the solo grid at the shard's cell (`entry.ts` asks only
7
7
  // for a tap, so a bare `?chunk=` link, a harness or an author's embedded product still opens the shard alone).
8
8
  import { pageScope } from '@wildshard/engine/app/resources';
9
- import { jsonSlot } from '@wildshard/engine/saves/slots';
9
+ import { jsonSlot, type Json } from '@wildshard/engine/saves/slots';
10
10
  import { GridAssembly, type GridCell } from '../../../shared/game/grid/assembly';
11
11
  import { hostsGrid } from '../shardfile/serverRoute';
12
12
  import { pageGridIntents } from './intent';
13
13
  import { DEVSERVER, gridMode } from './menu';
14
+ import { GAME_STRINGS } from '../../../shared/game/strings';
14
15
 
15
16
  /** The grid cell a shard's page enters: the first in catalogue order that runs this shard, or undefined for a shard the grid doesn't place. */
16
17
  export function shardCell(slug: string, assembly: GridAssembly = new GridAssembly(gridMode(DEVSERVER))): GridCell | undefined {
@@ -29,6 +30,22 @@ export interface OneWayIn {
29
30
  readonly kept: boolean;
30
31
  }
31
32
 
33
+ /** OFFLINE OF3: the shards a world's word names (`shards`, opus-route2), or null when it names none (an older door, nonsense). */
34
+ export function wordShards(word: unknown): readonly string[] | null {
35
+ const shards = typeof word === 'object' && word !== null && 'shards' in word ? word.shards : null;
36
+ return Array.isArray(shards) && shards.every(shard => typeof shard === 'string') ? shards : null;
37
+ }
38
+
39
+ /** OFFLINE OF3 (J298): whether a world build may enter `slug`. The catalogue must place it (the world opens only grid cells, so a shard
40
+ * with no cell would be seated in another one), and a word that names shards (`shards`, heard now or kept) must name it. No word
41
+ * and nothing kept leaves the catalogue's answer (J300). This replaces ba88ac9a's "unplaced plays solo". */
42
+ export function inThisWorld(slug: string, shards: readonly string[] | null, assembly?: GridAssembly): boolean {
43
+ return shardCell(slug, assembly) !== undefined && (shards === null || shards.includes(slug));
44
+ }
45
+
46
+ /** OF3: the title's line after a `?chunk=` link to a shard this world doesn't open (here, so the entry's static graph stays small). */
47
+ export function notInWorldLine(name: string): string { return GAME_STRINGS.notInWorld.line(name); }
48
+
32
49
  /** The cell a one-shard page enters instead, or null when it stays a one-shard page. */
33
50
  export function oneWayIn(page: OneWayIn, assembly?: GridAssembly): GridCell | null {
34
51
  if ((page.online && !page.hosted) || page.kept) return null;
@@ -36,7 +53,26 @@ export function oneWayIn(page: OneWayIn, assembly?: GridAssembly): GridCell | nu
36
53
  }
37
54
 
38
55
  /** The online module's gate, as `clientWorker.ts` reads it; a page with no world never asks. */
39
- interface OnlineGate { readonly worldWord: (world: { readonly release: string; readonly key: string }, waitMs?: number) => Promise<unknown> }
56
+ export interface OnlineGate { readonly worldWord: (world: { readonly release: string; readonly key: string }, waitMs?: number, keep?: WordKeep) => Promise<unknown> }
57
+ /** opus-wordkeep: the word the door said, which release and when (`online.js`'s `KeptWord`). */
58
+ interface KeptWord { readonly of: string; readonly at: number; readonly word: unknown }
59
+ interface WordKeep { readonly read: () => KeptWord | null; readonly write: (kept: KeptWord) => void }
60
+ /** opus-wordkeep: the tab's kept word, in the page's own session saves. `online.js` keeps the word a minute (so the title, a `?chunk=`
61
+ * page and the grid page share one socket), but its own store has no storage (OF4's finding for `release.kept`), so the page lends
62
+ * this one. The release is under `of`, not `release`: an older build in the same tab kept only a yes there. */
63
+ export function tabWordKeep(): WordKeep {
64
+ const slot = (): ReturnType<typeof jsonSlot> => jsonSlot('gridGate', 'session');
65
+ return {
66
+ read: () => {
67
+ const kept = slot().read();
68
+ if (typeof kept !== 'object' || kept === null || Array.isArray(kept)) return null;
69
+ const { of, at, word } = kept;
70
+ return typeof of === 'string' && typeof at === 'number' && word !== undefined ? { of, at, word } : null;
71
+ },
72
+ // a word is parsed JSON, so it keeps as it came
73
+ write: kept => { slot().write({ of: kept.of, at: kept.at, word: kept.word as Json }); },
74
+ };
75
+ }
40
76
 
41
77
  /** QA 11-12 row 36 (Jake on bad LTE: Driftwood sat 34 s on "Read audio 7 / 91"): the last answer this device got from its world, grid
42
78
  * or one-shard, kept across sessions. A check that misses its deadline uses it, so a cached player stays on the route they downloaded
@@ -44,25 +80,46 @@ interface OnlineGate { readonly worldWord: (world: { readonly release: string; r
44
80
  export interface RouteMemory {
45
81
  /** the kept answer for this world's release (true: it hosts the grid), or null when this device never heard one */
46
82
  readonly read: (release: string) => boolean | null;
47
- readonly write: (release: string, grid: boolean) => void;
83
+ /** OF3: the shards the kept word named, or null when it named none or nothing is kept */
84
+ readonly shards: (release: string) => readonly string[] | null;
85
+ readonly write: (release: string, grid: boolean, shards?: readonly string[] | null) => void;
48
86
  }
49
87
  /** The device's slot (`localStorage`), keyed by the world's release; the build that heard the answer rides along for diagnostics. */
50
88
  export function deviceRouteMemory(): RouteMemory {
51
89
  const slot = (): ReturnType<typeof jsonSlot> => jsonSlot('gridRoute', 'device');
90
+ const kept = (release: string): Readonly<Record<string, unknown>> | null => {
91
+ try {
92
+ const row = slot().read();
93
+ return typeof row === 'object' && row !== null && !Array.isArray(row) && row['of'] === release ? row : null;
94
+ } catch { return null; }
95
+ };
52
96
  return {
53
- read: release => {
54
- try {
55
- const kept = slot().read();
56
- return typeof kept === 'object' && kept !== null && !Array.isArray(kept) && kept['of'] === release && typeof kept['grid'] === 'boolean' ? kept['grid'] : null;
57
- } catch { return null; }
58
- },
59
- write: (release, grid) => {
97
+ read: release => { const grid = kept(release)?.['grid']; return typeof grid === 'boolean' ? grid : null; },
98
+ shards: release => wordShards(kept(release)),
99
+ write: (release, grid, shards = null) => {
60
100
  const build = (globalThis as { __WS_BUILD_ID__?: string }).__WS_BUILD_ID__ ?? '';
61
- try { slot().write({ of: release, grid, build, at: Date.now() }); } catch { /* a device that keeps nothing falls back to today's page */ }
101
+ try { slot().write({ of: release, grid, ...(shards === null ? {} : { shards: [...shards] }), build, at: Date.now() }); } catch { /* a device that keeps nothing falls back to today's page */ }
62
102
  },
63
103
  };
64
104
  }
65
105
 
106
+ const releaseOf = (world: unknown): string | null =>
107
+ typeof world === 'object' && world !== null && 'release' in world && typeof world.release === 'string' ? world.release : null;
108
+ /** OF3: which shards a build may enter, by the world's kept word (`memory`) and the catalogue. A build with no world (preview,
109
+ * sharddev) opens every card: its in-page server hosts any shard. A word that arrives after the page's deadline is kept for the next
110
+ * launch only: until then the page enters as J300 says (no word takes the grid). */
111
+ export function worldOpens(world: unknown, memory: RouteMemory = deviceRouteMemory()): (slug: string) => boolean {
112
+ if (world === undefined) return () => true;
113
+ const release = releaseOf(world), shards = release === null ? null : memory.shards(release);
114
+ let assembly: GridAssembly | undefined; // one catalogue read for a whole deck of cards
115
+ return slug => { assembly ??= new GridAssembly(gridMode(DEVSERVER)); return inThisWorld(slug, shards, assembly); };
116
+ }
117
+ /** OF3: a page leaving for the title because its shard isn't in this world drops any grid entry it held (a tap's, or the one way in's). */
118
+ export function dropGridEntry(slug: string): void { pageGridIntents().consume(slug); }
119
+
120
+ /** What a world's word says, as this page reads it: whether it hosts the grid, and the shards it opens (OF3). */
121
+ export interface WorldHeard { readonly grid: boolean; readonly shards: readonly string[] | null }
122
+
66
123
  /** One deadline over the whole read, the online module's import included (GO4's 3 s). */
67
124
  const HOSTED_MS = 3000;
68
125
  /** How long the read may go on after the deadline, so a late answer is still kept for the next launch. */
@@ -72,29 +129,34 @@ const KEEP_LATE_MS = 10_000;
72
129
  * a grid shard to a one-shard page for want of a word, so only a world known to open one cell does. A build with no world answers
73
130
  * false. Whether the page then reaches the world is the online shell's business: it never waits here. */
74
131
  export async function worldHosted(world: unknown, waitMs: number = HOSTED_MS, memory: RouteMemory = deviceRouteMemory(),
75
- read: (world: unknown, waitMs: number) => Promise<boolean | null> = readHosted): Promise<boolean> {
76
- const release = typeof world === 'object' && world !== null && 'release' in world && typeof world.release === 'string' ? world.release : null;
132
+ read: (world: unknown, waitMs: number) => Promise<WorldHeard | boolean | null> = readHosted): Promise<boolean> {
133
+ const release = releaseOf(world);
77
134
  if (release === null) return false;
78
135
  const scope = pageScope.child('grid.hosted'), late = new Promise<null>(resolve => { scope.timeout(waitMs, () => { resolve(null); }); });
79
136
  // The read itself may run past the page's deadline (`KEEP_LATE_MS`): a link that always answers late still fills the memory
80
137
  // for the next launch, though this page has already gone on without it.
81
- const reading = read(world, Math.max(waitMs, KEEP_LATE_MS)).catch(() => null);
82
- void reading.then(word => { if (word !== null) memory.write(release, word); return undefined; });
83
- let heard: boolean | null;
138
+ // A bare yes or no (a test's reader) names no shards.
139
+ const reading = read(world, Math.max(waitMs, KEEP_LATE_MS))
140
+ .then((word): WorldHeard | null => word === null ? null : typeof word === 'boolean' ? { grid: word, shards: null } : word, () => null);
141
+ void reading.then(word => { if (word !== null) memory.write(release, word.grid, word.shards); return undefined; });
142
+ let heard: WorldHeard | null;
84
143
  try { heard = await Promise.race([reading, late]); } finally { scope.dispose(); }
85
- if (heard !== null) return heard;
144
+ if (heard !== null) return heard.grid;
86
145
  return memory.read(release) ?? true;
87
146
  }
88
- /** The door's word read as grid or not, or null when no word came (unreachable, stalled, closed before its word). */
89
- async function readHosted(world: unknown, waitMs: number): Promise<boolean | null> {
147
+ /** This build's `online.js`, a bundle of its own. */
148
+ async function onlineGate(): Promise<OnlineGate> {
149
+ const build = (globalThis as { __WS_BUILD_ID__?: string }).__WS_BUILD_ID__ ?? '';
150
+ return await import(/* @vite-ignore */ `/b/${build}/standalone/online.js`) as OnlineGate;
151
+ }
152
+ /** The door's word read as grid or not and the shards it opens, or null when no word came (unreachable, stalled, closed before its word). */
153
+ export async function readHosted(world: unknown, waitMs: number, gate: () => Promise<OnlineGate> = onlineGate): Promise<WorldHeard | null> {
90
154
  if (typeof world !== 'object' || world === null || !('release' in world) || !('key' in world)) return null;
91
155
  const { release, key } = world;
92
156
  if (typeof release !== 'string' || typeof key !== 'string') return null;
93
157
  try {
94
- const build = (globalThis as { __WS_BUILD_ID__?: string }).__WS_BUILD_ID__ ?? '';
95
- const gate = await import(/* @vite-ignore */ `/b/${build}/standalone/online.js`) as OnlineGate;
96
- const word = await gate.worldWord({ release, key }, waitMs);
97
- return word === null ? null : hostsGrid(word);
158
+ const word = await (await gate()).worldWord({ release, key }, waitMs, tabWordKeep());
159
+ return word === null ? null : { grid: hostsGrid(word), shards: wordShards(word) };
98
160
  } catch { return null; }
99
161
  }
100
162
 
@@ -103,12 +165,15 @@ async function readHosted(world: unknown, waitMs: number): Promise<boolean | nul
103
165
  * goto intent turns this same page into a grid page (`bootPageMode` consumes it), so Shard select loads once. Returns the cell's
104
166
  * instance, or null when the page stays a one-shard page.
105
167
  */
106
- export async function enterByShard(page: Omit<OneWayIn, 'hosted'>, world: unknown, hosted: (world: unknown) => Promise<boolean> = worldHosted): Promise<string | null> {
168
+ export async function enterByShard(page: Omit<OneWayIn, 'hosted'>, world: unknown, hosted: (world: unknown) => Promise<boolean> = worldHosted,
169
+ opens: (slug: string) => boolean = slug => worldOpens(world)(slug)): Promise<string | null> {
107
170
  // Only a page that could turn asks the world: a kept page and a shard off the grid never wait on a read, and a solo build has no
108
171
  // world to ask (its in-page server hosts the grid, J311).
109
172
  if (oneWayIn({ ...page, hosted: true }) === null) return null;
110
173
  const cell = oneWayIn({ ...page, hosted: !page.online || await hosted(world) });
111
- if (cell === null) return null;
174
+ // OF3: a world whose word (heard just now, or kept) leaves this shard out never seats it there: no grid entry, and the page's entry
175
+ // (`entry.ts`) lands on the title with "Not in this world yet"
176
+ if (cell === null || (page.online && !opens(page.slug))) return null;
112
177
  pageGridIntents().admit({ instance: cell.instance, slug: cell.slug, goto: true });
113
178
  return cell.instance;
114
179
  }
@@ -94,6 +94,18 @@ export function reenterGrid(instance: string): void {
94
94
  travel({ to: target.slug, mode: 'enter', shown: gridDestination({ slug: target.slug }, target) });
95
95
  }
96
96
 
97
+ /** OFFLINE OF2 (J298): a grid page on a build whose world is known to host one cell (production before GC16) re-enters as that cell's
98
+ * one-shard page, online, never the solo grid. The page that boots is a `?chunk=` page with no grid intent; Shard select's one way in
99
+ * keeps it a one-shard page, since the same word (kept a minute, and in the device's route memory) says the world opens one cell. */
100
+ export function reenterShard(instance: string): void {
101
+ const cell = new GridAssembly(gridMode(DEVSERVER)).cells.find(row => row.instance === instance), target = cell === undefined ? undefined : findTitleManifest(cell.slug);
102
+ if (cell === undefined || target === undefined) {
103
+ recordDrop({ reason: `The world hosts one place, and this build can't open ${cell?.slug ?? instance} on its own, so the game went back to the title.`, code: instance });
104
+ location.replace(new URL(location.pathname, location.origin)); return;
105
+ }
106
+ travel({ to: target.slug, mode: 'enter', shown: gridDestination({ slug: target.slug }, target) });
107
+ }
108
+
97
109
  /** GO5: set once the world's door has placed this device in the grid, so its hint is the server's; a solo grid's hint boots home, as before. */
98
110
  export const SERVER_PLACED: SaveKeyDef<boolean> = { key: 'grid.server-placed', scope: 'device', version: 1, schema: v.boolean(), initial: () => false };
99
111
 
@@ -137,6 +149,13 @@ export function bootPageMode(slug: string): PageMode {
137
149
  if (recovery !== null && [slug].includes(recovery.slug)) intent = { instance: recovery.instance, slug: recovery.slug, at: recovery.at };
138
150
  const mode: PageMode = intent === null ? 'shard' : 'grid';
139
151
  setPageMode(mode);
152
+ // OFFLINE OF5: the title's read-ahead (S2) takes the route this pick booted. A deck tap remembers the one-shard flow before the
153
+ // page knows its route; a world that hosts the grid turns it into a grid entry, and a read-ahead of the one-shard manifest is a
154
+ // file this device never keeps (offline, it fails). Only the last pick's own page corrects it.
155
+ try {
156
+ const choice = titlePrefetchChoice(saves);
157
+ if ([slug].includes(choice.read() ?? '')) choice.remember(slug, mode === 'grid' ? 'grid' : 'client');
158
+ } catch { /* the read-ahead hint is optional: blocked storage keeps the page's flow */ }
140
159
  // GO7: a goto, or a recovery reload (the cell this page stood in, the goto's cell if it reloaded before the door placed it), asks the
141
160
  // world for that cell; a title tap's PLAY takes the seat the world keeps (GO5).
142
161
  const chosen = intent !== null && recovery === null && 'goto' in intent && intent.goto;
@@ -46,7 +46,7 @@ export function gridPageShell(source: ShardManifest): ShardManifest {
46
46
 
47
47
  /** The neutral page cannot read a home terrain/navmesh bake merely because it keeps the picker's identity. */
48
48
  export function gridPageShellLevel(shell: ShardManifest): LevelSpec {
49
- return { ...toLevelSpec(shell), id: 'platform.grid', boundary: { visible: false, walls: false } };
49
+ return { ...toLevelSpec(shell), id: 'platform.grid', boundary: { visible: false } };
50
50
  }
51
51
 
52
52
  /** Select the neutral engine level before its staged boot; catalogue identity and each resident's frame stay separate. */
@@ -0,0 +1,55 @@
1
+ // SHARD-AUTHORING SA46 (meta SHARD-AUTHORING-PLAN): the card of a shard the API placed after this page was built. The placement file
2
+ // (`placedCells.ts`) names its cell, but the build bakes no title row for it: a new author's slug uploaded since. Its row comes from
3
+ // the API's catalogue entry (`GET /api/catalogue/shards/<slug>`, which answers the three game origins with CORS), carded plainly by
4
+ // name (`catalogueTitleRow`): the API hosts no uploaded shard's images. Any failure (offline, a 404, no CORS, junk, a name that is
5
+ // not a name) gives no row, and the cell stays out as before.
6
+ import * as v from 'valibot';
7
+ import { Scope } from '@wildshard/engine/app/scope';
8
+ import { apiOrigin } from '@wildshard/engine/core/apiOrigin';
9
+ import { catalogueTitleRow, type TitleManifest } from '../shard/titleList';
10
+
11
+ /** At most this many entries are asked for in one boot: a file rarely adds more than one new slug at a time. */
12
+ export const CARD_LOOKUPS = 4;
13
+ /** The lookups' own deadline, inside the placement file's 3 s: a slow API never costs the cells the build already cards. */
14
+ export const CARD_DEADLINE_MS = 1500;
15
+ const NAME_CHARS = 80;
16
+ /** An entry is about 1.5 KB; anything past this is not one. */
17
+ const ENTRY_BYTES = 64 * 1024;
18
+ const EntrySchema = v.looseObject({ slug: v.string(), name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(NAME_CHARS)) });
19
+
20
+ export interface CardPorts {
21
+ readonly fetch: typeof fetch;
22
+ /** The API's origin (`VITE_API_ORIGIN`, '' for the page's own). */
23
+ readonly api?: string;
24
+ readonly signal: AbortSignal;
25
+ /** The first new row's `order`: after the build's rows. */
26
+ readonly order: number;
27
+ readonly deadlineMs?: number;
28
+ }
29
+
30
+ /** One slug's catalogue row, or undefined for anything but an entry that names this slug. Never throws. */
31
+ async function catalogueCard(slug: string, order: number, ports: CardPorts): Promise<TitleManifest | undefined> {
32
+ try {
33
+ const url = `${ports.api ?? apiOrigin()}/api/catalogue/shards/${encodeURIComponent(slug)}`;
34
+ // called bare: a browser's `fetch` called as a method of another object throws Illegal invocation
35
+ const read = ports.fetch, response = await read(url, { cache: 'no-store', credentials: 'omit', redirect: 'error', signal: ports.signal });
36
+ if (!response.ok) { await response.body?.cancel(); return undefined; }
37
+ const text = await response.text();
38
+ if (text.length > ENTRY_BYTES) return undefined;
39
+ const entry = v.safeParse(EntrySchema, JSON.parse(text));
40
+ return entry.success && new Set([slug]).has(entry.output.slug) ? catalogueTitleRow(slug, entry.output.name, order) : undefined;
41
+ } catch { return undefined; }
42
+ }
43
+
44
+ /** The plain title rows of `slugs` the API's catalogue names, in their order; slugs it does not know are left out. */
45
+ export async function catalogueCards(slugs: readonly string[], ports: CardPorts): Promise<readonly TitleManifest[]> {
46
+ const asked = [...new Set(slugs)].slice(0, CARD_LOOKUPS);
47
+ const scope = new Scope('grid.placed-cards'), abort = new AbortController(), stop = (): void => { abort.abort(); };
48
+ try {
49
+ scope.timeout(ports.deadlineMs ?? CARD_DEADLINE_MS, stop);
50
+ if (ports.signal.aborted) stop(); else scope.listen(ports.signal, 'abort', stop);
51
+ const own = { ...ports, signal: abort.signal };
52
+ const rows = await Promise.all(asked.map((slug, n) => catalogueCard(slug, ports.order + n, own)));
53
+ return rows.filter(row => row !== undefined);
54
+ } finally { scope.dispose(); }
55
+ }
@@ -0,0 +1,131 @@
1
+ // SHARD-AUTHORING SA33 to SA35, the page half (meta SHARD-AUTHORING-PLAN): a released page (staging, production) learns the cells the API
2
+ // placed after its build, at runtime, from the same signed placement file the MMO reads (`releases/<channel>-placements.json`, SA33a).
3
+ // Its build bakes the pinned grid (`catalogue.json`, C3); the MMO's grid is that plus this file, so without it a placed shard had no
4
+ // Shard Select card and `?chunk=<slug>` landed on the deck. The file is believed only under the API's placement key, as the box and
5
+ // SA35's preview bake believe it. A missing, late, unreadable or refused file keeps the build's grid: boot never waits past
6
+ // `PLACED_DEADLINE_MS` and never fails here. The bucket sends it `no-store`, the read asks `no-store`, and the service worker leaves
7
+ // `/releases/` to the network (sw.js `isContentRead`), so no page keeps an old file.
8
+ import * as v from 'valibot';
9
+ import { Scope } from '@wildshard/engine/app/scope';
10
+ import { GRID_RADIUS } from '@wildshard/format/contentBounds';
11
+ import { PLACEMENT_PUBLIC_KEY, PlacementSchema, SignedPlacementSchema, placementsURL, type PlacementFile } from '../../../shared/game/grid/placementRows';
12
+ import { installCatalogue, installedCatalogue, type CatalogueDocument } from '../../../shared/game/grid/catalogueSlot';
13
+ import { findTitleManifest, installTitleManifests, titleManifests } from '../shard/titleList';
14
+ import { catalogueCards } from './placedCards';
15
+ import { parseGridCatalogue } from '../../../shared/game/grid/catalogue';
16
+
17
+ /** How long a page's boot waits for the file: GO4's 3 s, the world word's own deadline. A slower answer leaves the build's grid. */
18
+ export const PLACED_DEADLINE_MS = 3000;
19
+
20
+ type Cell = PlacementFile['cells'][number];
21
+ const hexBytes = (hex: string): Uint8Array<ArrayBuffer> => Uint8Array.from(hex.match(/../gu) ?? [], pair => Number.parseInt(pair, 16));
22
+
23
+ /** The file's text as what it says: WebCrypto's Ed25519 under `publicKey` (SPKI DER in hex), then the box's own schema. It throws on a
24
+ * bad signature, before a byte of the body is believed, and where a browser has no Ed25519. */
25
+ export async function readSignedPlacement(text: string, publicKey: string = PLACEMENT_PUBLIC_KEY): Promise<PlacementFile> {
26
+ const signed = v.parse(SignedPlacementSchema, JSON.parse(text));
27
+ const key = await crypto.subtle.importKey('spki', hexBytes(publicKey), { name: 'Ed25519' }, false, ['verify']);
28
+ if (!await crypto.subtle.verify({ name: 'Ed25519' }, key, hexBytes(signed.signature), new TextEncoder().encode(signed.body))) throw new Error('A placement file has a bad signature');
29
+ return v.parse(PlacementSchema, JSON.parse(signed.body));
30
+ }
31
+
32
+ /** Where this page reads its placed cells: its world's channel's placement file, or null for a page with no world (preview bakes
33
+ * staging's cells at deploy, SA35; a solo build has none). `__WS_PLACEMENTS__`, a proof's own address, wins when set. */
34
+ export function placementsOf(scope: { readonly __WS_WORLD__?: unknown; readonly __WS_PLACEMENTS__?: unknown }): string | null {
35
+ if (typeof scope.__WS_PLACEMENTS__ === 'string') return scope.__WS_PLACEMENTS__;
36
+ const world = scope.__WS_WORLD__;
37
+ const release = typeof world === 'object' && world !== null && 'release' in world && typeof world.release === 'string' ? world.release : null;
38
+ return release === null ? null : placementsURL(release);
39
+ }
40
+
41
+ /** What adding a file's cells to a catalogue gave: the catalogue to install, the cells it took, and why any was left out. */
42
+ export interface Placed { readonly document: CatalogueDocument; readonly added: readonly Cell[]; readonly left: readonly string[] }
43
+ /**
44
+ * The catalogue with the file's cells after the build's own. A cell is left out as the MMO's `placeCell` (`gridCells.ts`) refuses it, rule
45
+ * for rule: an instance placed elsewhere, off the 7 × 7, a slug that already has a cell (or names a cell), an instance that is a placed
46
+ * shard's slug, a taken spot. A cell the build already places the same way is kept once. A slug this build has no card or product for
47
+ * (`known` false: an upload after the build the API's catalogue does not card, SA46) is left out too. `placed` names the slugs the file
48
+ * added, which Shard Select cards (`titleDeck.ts`).
49
+ */
50
+ export function addPlacedCells(document: CatalogueDocument, file: PlacementFile, known: (slug: string) => boolean = () => true): Placed {
51
+ const added: Cell[] = [], left: string[] = [];
52
+ const shards = new Map<string, string>(), cells = new Map<string, string>(), spots = new Map<string, string>();
53
+ for (const row of document.grid.cells as readonly Cell[]) { shards.set(row.instance, row.slug); cells.set(row.slug, row.instance); spots.set(row.cell.join(','), row.instance); }
54
+ for (const row of file.cells) {
55
+ const [x, z] = row.cell, spot = `${String(x)},${String(z)}`;
56
+ if (shards.has(row.instance) && cells.get(row.slug) === row.instance && spots.get(spot) === row.instance) continue;
57
+ const refused = shards.has(row.instance) ? `${row.instance} is already placed elsewhere`
58
+ : Math.abs(x) > GRID_RADIUS || Math.abs(z) > GRID_RADIUS ? 'off the 7 × 7'
59
+ : cells.has(row.slug) || shards.has(row.slug) ? `${row.slug} already has a cell`
60
+ : cells.has(row.instance) ? `${row.instance} is a placed shard's name`
61
+ : spots.has(spot) ? `${spot} is ${spots.get(spot) ?? ''}'s`
62
+ : known(row.slug) ? '' : `${row.slug} is not in this build`;
63
+ if (refused !== '') { left.push(`${row.instance} (${row.slug}) at (${spot}): ${refused}`); continue; }
64
+ shards.set(row.instance, row.slug); cells.set(row.slug, row.instance); spots.set(spot, row.instance);
65
+ added.push({ instance: row.instance, slug: row.slug, cell: [x, z] });
66
+ }
67
+ if (added.length === 0) return { document, added, left };
68
+ const grid = { ...document.grid, cells: [...document.grid.cells, ...added] };
69
+ // the grid's own admission (radius, unique spots and instances): a grid it refuses is never installed
70
+ parseGridCatalogue(grid);
71
+ return { document: { ...document, grid, placed: [...document.placed ?? [], ...added.map(row => row.slug)] }, added, left };
72
+ }
73
+
74
+ /** What a page's read of its placement file did, for the console and the tests: `carded` names the added slugs whose card came
75
+ * from the API's catalogue (SA46). */
76
+ export type PlacedRead = { readonly added: readonly Cell[]; readonly left: readonly string[]; readonly serial: number; readonly carded: readonly string[] } | { readonly kept: string };
77
+ export interface PlacedPorts {
78
+ readonly fetch?: typeof fetch;
79
+ readonly publicKey?: string;
80
+ readonly deadlineMs?: number;
81
+ /** The page's own deadline: once it fires the boot has gone on, so a late answer installs nothing (the deck and the one way in read
82
+ * the grid once). */
83
+ readonly signal?: AbortSignal;
84
+ /** Whether this build cards a slug (default: it has a title row, `titleList.ts`). A slug it lacks may be carded from the API's
85
+ * catalogue (SA46); whether its product loads is the product's own question. */
86
+ readonly known?: (slug: string) => boolean;
87
+ /** The API origin a slug the build lacks is carded from (SA46, `placedCards.ts`; default `VITE_API_ORIGIN`). */
88
+ readonly api?: string;
89
+ /** The catalogue lookups' own deadline (`placedCards.ts` `CARD_DEADLINE_MS`). */
90
+ readonly cardDeadlineMs?: number;
91
+ }
92
+ /** After every row's `order`, so a carded shard is last in the deck. */
93
+ const nextOrder = (rows: readonly { readonly order?: number }[]): number => rows.reduce((top, row) => Math.max(top, row.order ?? 0), rows.length) + 1;
94
+ /** Read the file at `url` and install the build's catalogue with its cells. Never throws: anything but a believed file keeps the build's
95
+ * grid and says why (a 404 is a channel the API has placed nothing on). */
96
+ export async function learnPlacedCells(url: string, ports: PlacedPorts = {}): Promise<PlacedRead> {
97
+ const scope = new Scope('grid.placed-cells');
98
+ try {
99
+ const document = installedCatalogue();
100
+ if (document === undefined) return { kept: 'no installed catalogue' };
101
+ // one signal for both deadlines, without `AbortSignal.any` (Safari 17.4): Safari 17's Ed25519 reads this file too
102
+ const abort = new AbortController(), stop = (): void => { abort.abort(); };
103
+ scope.timeout(ports.deadlineMs ?? PLACED_DEADLINE_MS, stop);
104
+ if (ports.signal?.aborted === true) stop(); else if (ports.signal !== undefined) scope.listen(ports.signal, 'abort', stop);
105
+ const response = await (ports.fetch ?? fetch)(url, { cache: 'no-store', credentials: 'omit', redirect: 'error', signal: abort.signal });
106
+ if (response.status === 404) return { kept: 'no placement file (404): nothing placed on this channel' };
107
+ if (!response.ok) return { kept: `placement file ${String(response.status)}` };
108
+ const file = await readSignedPlacement(await response.text(), ports.publicKey);
109
+ const channel = /\/releases\/(staging|production)-placements\.json$/u.exec(new URL(url).pathname)?.[1];
110
+ if (channel !== undefined && file.channel !== channel) return { kept: `a ${file.channel} placement file at the ${channel} address` };
111
+ const known = ports.known ?? (slug => findTitleManifest(slug) !== undefined);
112
+ // the page's own deadline, read afresh after each wait: once it fires the boot has gone on
113
+ const wentOn = (): boolean => ports.signal?.aborted === true;
114
+ const placed = addPlacedCells(document, file, known);
115
+ if (wentOn()) return { kept: 'the page went on before the placement file was read' };
116
+ if (placed.added.length > 0) installCatalogue(placed.document);
117
+ // SA46: a cell the box would open whose slug this build has no card for (an upload after the build) is carded from its catalogue
118
+ // entry, after the build's own cells are in, so a slow or absent API costs them nothing; a slug it does not card stays out
119
+ const unknown = addPlacedCells(placed.document, file).added.map(cell => cell.slug);
120
+ const built = { added: placed.added, left: placed.left, serial: file.serial, carded: [] };
121
+ if (unknown.length === 0) return built;
122
+ const cards = await catalogueCards(unknown, { fetch: ports.fetch ?? fetch, signal: abort.signal, order: nextOrder(titleManifests()), ...(ports.api === undefined ? {} : { api: ports.api }),
123
+ ...(ports.cardDeadlineMs === undefined ? {} : { deadlineMs: ports.cardDeadlineMs }) });
124
+ if (cards.length === 0 || wentOn()) return built;
125
+ const carded = new Set(cards.map(row => row.slug)), more = addPlacedCells(placed.document, file, slug => carded.has(slug));
126
+ const opened = new Set(more.added.map(cell => cell.slug)), rows = cards.filter(row => opened.has(row.slug));
127
+ if (more.added.length > 0) installCatalogue(more.document);
128
+ if (rows.length > 0) installTitleManifests([...titleManifests(), ...rows]);
129
+ return { added: [...placed.added, ...more.added], left: more.left, serial: file.serial, carded: rows.map(row => row.slug) };
130
+ } catch (error) { return { kept: error instanceof Error ? error.message : String(error) }; } finally { scope.dispose(); }
131
+ }