@wildshard/engine 0.1.17 → 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 (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +7 -0
  3. package/lint/host-callback-syntax.mjs +2 -1
  4. package/lint/host-callbacks.mjs +3 -3
  5. package/lint/host-files.mjs +5 -4
  6. package/lint/no-base64.mjs +3 -1
  7. package/lint/shard-imports.mjs +6 -7
  8. package/lint/shard-source.d.mts +9 -0
  9. package/lint/shard-source.mjs +91 -0
  10. package/lint/shardfile-boundaries.mjs +10 -8
  11. package/lint/sim-closure.mjs +6 -3
  12. package/lint/wildshard-plugin.d.ts +4 -0
  13. package/lint/wildshard-plugin.js +22 -23
  14. package/package.json +9 -2
  15. package/scripts/app-build/outputProducts.d.mts +3 -0
  16. package/scripts/app-build/outputProducts.mjs +31 -0
  17. package/scripts/app-build-pipeline.mjs +3 -0
  18. package/scripts/check-devserver.mjs +1 -1
  19. package/scripts/chromium-keychain-check.mjs +4 -2
  20. package/scripts/chromium-keychain.mjs +3 -1
  21. package/scripts/cook.mjs +7 -3
  22. package/scripts/devices.d.mts +4 -0
  23. package/scripts/devices.mjs +39 -0
  24. package/scripts/devserver-client.d.mts +4 -2
  25. package/scripts/devserver-client.mjs +25 -8
  26. package/scripts/doctor-proof.mjs +1 -1
  27. package/scripts/e2e-faults.mjs +159 -0
  28. package/scripts/grid-crossing-walk-proof.mjs +14 -3
  29. package/scripts/memory-proof.mjs +158 -0
  30. package/scripts/offline-proof-rules.d.mts +4 -2
  31. package/scripts/offline-proof-rules.mjs +21 -5
  32. package/scripts/offline-proof.mjs +15 -6
  33. package/scripts/tier-textures-proof.mjs +101 -0
  34. package/scripts/tier-textures.mjs +60 -0
  35. package/scripts/tsconfig.json +1 -0
  36. package/scripts/vps/wildshard-config +79 -23
  37. package/scripts/worker-client-play.mjs +1 -0
  38. package/scripts/worker-client-proof.mjs +1 -1
  39. package/scripts/worker-client-slug.mjs +44 -0
  40. package/src/client/app/entry.ts +37 -10
  41. package/src/client/engine/boot/parsedPages.ts +127 -58
  42. package/src/client/engine/build.d.ts +2 -0
  43. package/src/client/engine/core/Game.ts +18 -0
  44. package/src/client/engine/core/bootstrap.ts +4 -1
  45. package/src/client/engine/debug/probe.ts +18 -1
  46. package/src/client/engine/fx/LightPool.ts +41 -1
  47. package/src/client/engine/pwa/sw.js +12 -3
  48. package/src/client/engine/render/precompile.ts +20 -14
  49. package/src/client/engine/telemetry/browserErrors.ts +4 -1
  50. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  51. package/src/client/game/boot/audio.generated.ts +0 -102
  52. package/src/client/game/boot/bytes.generated.ts +42 -60
  53. package/src/client/game/boot/versions.generated.ts +0 -2
  54. package/src/client/game/grid/area.ts +38 -0
  55. package/src/client/game/grid/live.ts +28 -2
  56. package/src/client/game/grid/liveSession.ts +14 -3
  57. package/src/client/game/grid/menu.ts +4 -0
  58. package/src/client/game/grid/neighbourPanels.ts +10 -1
  59. package/src/client/game/grid/placedCards.ts +55 -0
  60. package/src/client/game/grid/placedCells.ts +131 -0
  61. package/src/client/game/grid/regionalRuntime.ts +6 -0
  62. package/src/client/game/grid/regionalWorld.ts +15 -2
  63. package/src/client/game/grid/roadCull.ts +44 -14
  64. package/src/client/game/grid/roadTileBacking.ts +13 -3
  65. package/src/client/game/grid/session.ts +9 -0
  66. package/src/client/game/grid/shardfileFar.ts +9 -3
  67. package/src/client/game/session/finish.ts +5 -1
  68. package/src/client/game/shard/titleList.ts +6 -2
  69. package/src/client/game/shardfile/clientWorker.ts +2 -1
  70. package/src/client/game/titleDeck.ts +4 -3
  71. package/src/client/host/online/shell.ts +14 -0
  72. package/src/cook/game/shardCook.ts +38 -8
  73. package/src/cook/game/tierTextures.ts +276 -0
  74. package/src/e2e/smoke/game.ts +19 -14
  75. package/src/e2e/smoke/page-globals.d.ts +9 -8
  76. package/src/e2e/smoke/template2.spec.ts +8 -7
  77. package/src/server/host/dedicated/placementFile.ts +1 -17
  78. package/src/server/host/dedicated/socketTransport.ts +2 -1
  79. package/src/server/host/dedicated/world.ts +30 -1
  80. package/src/shared/engine/net/deviceWord.ts +138 -0
  81. package/src/shared/engine/net/socketFrames.ts +7 -4
  82. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  83. package/src/shared/game/grid/placementRows.ts +33 -0
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/python3 -I
2
2
  # MMO-SERVER-PLAN MS3.5 (J266): the agents' one way to change a game server's settings, through sudo with no password.
3
3
  # wildshard-config show <channel> print the channel's settings file
4
- # wildshard-config set <channel> <KEY> <value> [--production] write one setting, restart the channel, roll back if it
5
- # does not come up healthy
4
+ # wildshard-config set <channel> <KEY> <value> [<KEY> <value>]... [--production]
5
+ # write the settings, restart the channel once, roll back if
6
+ # it does not come up healthy
6
7
  # wildshard-config split <channel> setup.sh's: move the settings out of <channel>.env, once
7
8
  # Settings live in /etc/wildshard/<channel>.settings (640 root:wildshard-<channel>), which the units read after <channel>.env.
8
- # Secrets stay in the root-only .env, and this never reads one out or writes one: only the keys in SETTINGS below, each
9
+ # Secrets stay in the root-only .env, and this never prints one or writes one (it reads only the placement rows there, for
10
+ # the pair check below): only the keys in SETTINGS below, each
9
11
  # checked by its own rule. A production change needs --production, so no one changes the live world by a slip.
12
+ # The two placement keys (SA33, GC33) go together: the server throws at boot on one without the other, so a `set` that would
13
+ # leave the channel with one is refused before anything is written; set both in one call.
10
14
  # Installed root-owned as /usr/local/sbin/wildshard-config by harden.sh; the sudo allowlist names that path only.
11
15
  import os, re, subprocess, sys, tempfile, time, urllib.request
12
16
 
@@ -14,9 +18,20 @@ CHANNELS = {'production': {'port': 8790, 'cpus': 9, 'host': 0}, 'staging': {'por
14
18
  # The pages that open the game (engine doorTrust DEFAULT_ALLOWED_ORIGINS); each channel's own is at its 'host' index.
15
19
  GAME_HOSTS = ('https://play.wildshard.io', 'https://staging.wildshard.io', 'https://preview.wildshard.io')
16
20
  CELL = r'[a-z0-9][a-z0-9-]{0,63}'
21
+ # SA33a: the API's placement key, public half as SPKI DER hex; equal to engine scripts/preview-grid.ts PLACEMENT_PUBLIC_KEY (the
22
+ # engine's test holds them equal). Pinned, so an agent can point a channel at the API's own signed file and nothing else.
23
+ PLACEMENT_PUBLIC_KEY = '302a300506032b65700321004afd39342aac6a4de6066cb72e9df54cbd3d4eb522e5e6e175a17954ab98f25e'
24
+ PLACEMENT_PAIR = ('PLACEMENT_URL', 'PLACEMENT_PUBLIC_KEY')
25
+
26
+
27
+ def placements(channel):
28
+ """The one signed placement file a channel reads: the API writes only releases/<channel>-placements.json (SA33a)."""
29
+ return f'https://packs.wildshard.io/releases/{channel}-placements.json'
30
+
17
31
  # Each allowed key and its rule. Anything else is refused: secrets (SEAT_SECRET, SENTRY_DSN, DATABASE_URL), the trust roots
18
32
  # (RELEASE_URL, RELEASE_PUBLIC_KEY, BUNDLE_ORIGIN, PACK_ORIGIN, TELEMETRY_URL, ERRORS_URL) and exposure (HOST, PORT,
19
- # TRUST_PROXY) are root's, by hand or by a reviewed script. ALLOWED_ORIGINS may only narrow (MS3.4): a set of the game's three
33
+ # TRUST_PROXY) are root's, by hand or by a reviewed script. The placement pair is a trust root too, so each takes one
34
+ # exact value (the channel's own file, the API's pinned key) or blank, which the server reads as unset (Jake, 2026-11-13). ALLOWED_ORIGINS may only narrow (MS3.4): a set of the game's three
20
35
  # hosts that keeps the channel's own, so an agent can drop a page but never add one or lock its own players out.
21
36
  SETTINGS = {
22
37
  'WORLD_CELLS': lambda value, channel: value == 'grid' or (re.fullmatch(f'{CELL}(,{CELL}){{0,63}}', value) is not None
@@ -26,12 +41,18 @@ SETTINGS = {
26
41
  'RECORD_TAG': lambda value, channel: re.fullmatch(r'[A-Za-z0-9._-]{0,64}', value) is not None,
27
42
  'ALLOWED_ORIGINS': lambda value, channel: (set(value.split(',')) <= set(GAME_HOSTS) and len(set(value.split(','))) == len(value.split(','))
28
43
  and GAME_HOSTS[CHANNELS[channel]['host']] in value.split(',')),
44
+ 'WORLD_CROSSING': lambda value, channel: value in ('off', 'worker'),
45
+ 'PLACEMENT_URL': lambda value, channel: value in ('', placements(channel)),
46
+ 'PLACEMENT_PUBLIC_KEY': lambda value, channel: value in ('', PLACEMENT_PUBLIC_KEY),
29
47
  }
30
48
  RULES = {'WORLD_CELLS': "'grid' or comma-separated cell names (a-z, 0-9, -), none twice",
31
49
  'WORLD_WORKERS': 'a whole number from 1 to the channel\'s pinned CPUs (production 9, staging 4)',
32
50
  'WORLD_SEATS': 'a whole number from 1 to 2000', 'RECORD_TAG': 'up to 64 of A-Z a-z 0-9 . _ -',
33
51
  'ALLOWED_ORIGINS': "comma-separated, none twice, from https://play.wildshard.io, https://staging.wildshard.io and "
34
- "https://preview.wildshard.io, keeping the channel's own (production play, staging staging)"}
52
+ "https://preview.wildshard.io, keeping the channel's own (production play, staging staging)",
53
+ 'WORLD_CROSSING': 'off or worker',
54
+ 'PLACEMENT_URL': "https://packs.wildshard.io/releases/<channel>-placements.json for this channel, or blank",
55
+ 'PLACEMENT_PUBLIC_KEY': f'the API placement key {PLACEMENT_PUBLIC_KEY}, or blank'}
35
56
 
36
57
  # The engine's tests hand it a made-up /etc and no systemctl; never as root, so sudo (which drops the environment anyway) cannot.
37
58
  TEST = os.geteuid() != 0 and os.environ.get('WILDSHARD_CONFIG_TEST_ROOT')
@@ -60,6 +81,31 @@ def key_of(row):
60
81
  return match.group(1) if match else None
61
82
 
62
83
 
84
+ def plain(row):
85
+ """A row's value as systemd reads it: one pair of matching quotes stripped."""
86
+ value = row.split('=', 1)[1].strip()
87
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'':
88
+ value = value[1:-1]
89
+ return value
90
+
91
+
92
+ def effective(rows, keys):
93
+ """What the server reads for these keys: the last assignment wins, as systemd reads it (spaces around the key and =)."""
94
+ seen = {}
95
+ for row in rows:
96
+ match = re.match(r'^\s*([A-Z_][A-Z0-9_]*)\s*=', row)
97
+ if match and match.group(1) in keys:
98
+ seen[match.group(1)] = plain(row[match.end() - 1:])
99
+ return seen
100
+
101
+
102
+ def pair_broken(env_rows, settings_rows):
103
+ """True when the server would start with one placement key and not the other (main.ts throws). The settings file is
104
+ read after the .env, and a blank value is unset. Only these two keys are read from the .env."""
105
+ seen = effective(env_rows + settings_rows, PLACEMENT_PAIR)
106
+ return (seen.get('PLACEMENT_URL', '') == '') != (seen.get('PLACEMENT_PUBLIC_KEY', '') == '')
107
+
108
+
63
109
  def write_rows(path, rows, channel):
64
110
  """Atomic, never through a link, 640 root:wildshard-<channel>."""
65
111
  folder = os.path.dirname(path)
@@ -121,7 +167,7 @@ def main(argv):
121
167
  production = '--production' in argv
122
168
  args = [arg for arg in argv if arg != '--production']
123
169
  if not args or args[0] not in ('show', 'set', 'split'):
124
- stop('usage: wildshard-config show <channel> | set <channel> <KEY> <value> [--production] | split <channel>')
170
+ stop('usage: wildshard-config show <channel> | set <channel> <KEY> <value> [<KEY> <value>]... [--production] | split <channel>')
125
171
  verb = args[0]
126
172
  if len(args) < 2 or args[1] not in CHANNELS:
127
173
  stop('the channel is production or staging')
@@ -148,11 +194,6 @@ def main(argv):
148
194
  stop('usage: wildshard-config split <channel>')
149
195
  env_rows = read_rows(env_path)
150
196
  # systemd strips one pair of matching quotes; a value that still fails its rule stays in the .env, never dropped.
151
- def plain(row):
152
- value = row.split('=', 1)[1].strip()
153
- if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'':
154
- value = value[1:-1]
155
- return value
156
197
  # The last assignment of a key is the one systemd uses; a key moves only if that one passes its rule, and then all of
157
198
  # its rows move, so the precedence never changes (Codex J206).
158
199
  last = {key_of(row): row for row in env_rows if key_of(row) in SETTINGS}
@@ -170,30 +211,45 @@ def main(argv):
170
211
  print(f'doing move {", ".join(sorted(keys))} from {channel}.env to {channel}.settings')
171
212
  return 0
172
213
 
173
- if len(args) != 4:
174
- stop('usage: wildshard-config set <channel> <KEY> <value> [--production]')
175
- key, value = args[2], args[3]
176
- if key not in SETTINGS:
177
- stop(f'{key} is not a setting an agent may change; allowed: {", ".join(SETTINGS)}')
178
- if not SETTINGS[key](value, channel):
179
- stop(f'{key} must be {RULES[key]}')
214
+ if len(args) < 4 or len(args) % 2 != 0:
215
+ stop('usage: wildshard-config set <channel> <KEY> <value> [<KEY> <value>]... [--production]')
216
+ pairs = list(zip(args[2::2], args[3::2]))
217
+ keys = [key for key, _ in pairs]
218
+ if len(set(keys)) != len(keys):
219
+ stop('each key once per set')
220
+ for key, value in pairs:
221
+ if key not in SETTINGS:
222
+ stop(f'{key} is not a setting an agent may change; allowed: {", ".join(SETTINGS)}')
223
+ if not SETTINGS[key](value, channel):
224
+ stop(f'{key} must be {RULES[key]}')
180
225
  if channel == 'production' and not production:
181
226
  stop('a production change needs --production')
182
227
  before = read_rows(settings_path)
183
228
  rows = list(before) or list(HEADER)
184
- rows = [row for row in rows if key_of(row) != key] + [f'{key}={value}']
229
+ rows = [row for row in rows if key_of(row) not in keys] + [f'{key}={value}' for key, value in pairs]
230
+ change = ' '.join(f'{key}={value}' for key, value in pairs)
185
231
  if rows == before:
186
- print(f'ok {channel} {key} is already {value}')
232
+ print(f'ok {channel} already has {change}')
187
233
  return 0
234
+ # Checked against what the server would read, the .env included, so no restart can boot into main.ts's throw.
235
+ env_rows = read_rows(env_path)
236
+ if pair_broken(env_rows, rows):
237
+ if pair_broken(env_rows, before):
238
+ stop(f'{channel} already holds only one of PLACEMENT_URL and PLACEMENT_PUBLIC_KEY (in its .env or .settings), so '
239
+ 'its server cannot start; set both in one call, both set or both blank')
240
+ stop('PLACEMENT_URL and PLACEMENT_PUBLIC_KEY go together: set both in one call, both set or both blank')
241
+ placing = effective(env_rows + rows, PLACEMENT_PAIR + ('WORLD_CELLS',))
242
+ if any(key in PLACEMENT_PAIR for key in keys) and placing.get('PLACEMENT_URL', '') != '' and placing.get('WORLD_CELLS', '').strip() != 'grid':
243
+ print(f'note {channel} WORLD_CELLS is not grid, so the server reads no placement file (main.ts)')
188
244
  was_running = running(channel)
189
245
  write_rows(settings_path, rows, channel)
190
- print(f'doing {channel} {key}={value}')
246
+ print(f'doing {channel} {change}')
191
247
  if not was_running:
192
248
  # A channel still waiting for its first release keeps its health stub; the setting takes effect when it starts.
193
- print(f'skip wildshard-server@{channel} is not running; {key}={value} takes effect when it starts')
249
+ print(f'skip wildshard-server@{channel} is not running; {change} takes effect when it starts')
194
250
  return 0
195
251
  if restart(channel):
196
- print(f'ok {channel} is healthy with {key}={value}')
252
+ print(f'ok {channel} is healthy with {change}')
197
253
  return 0
198
254
  # It did not come back: put the old file back and start the old settings, so a bad value never leaves a channel down.
199
255
  if before:
@@ -116,6 +116,7 @@ export async function play(browser, phone, base, only = '') {
116
116
  if (runs('hurt')) { const { hurt } = await import('./worker-client-hurt.mjs'); await hurt(browser, phone, base, step); }
117
117
  if (runs('windup')) { const { windup } = await import('./worker-client-windup.mjs'); await windup(browser, phone, base, step); }
118
118
  if (runs('grid-entry')) { const { gridEntry } = await import('./worker-client-grid-entry.mjs'); await gridEntry(browser, phone, base, step); }
119
+ if (runs('slug')) { const { slugEntry } = await import('./worker-client-slug.mjs'); await slugEntry(browser, phone, base, step, process.argv.find(value => value.startsWith('--slug='))?.slice(7)); }
119
120
  if (runs('recovery-menu')) { const { recoveryMenu } = await import('./worker-client-grid-entry.mjs'); await recoveryMenu(browser, phone, base, step); }
120
121
  if (runs('death-order')) { const { deathOrder } = await import('./worker-client-death-return.mjs'); await deathOrder(browser, phone, base, step); }
121
122
  if (runs('death')) { const { driftwoodDeath } = await import('./worker-client-death.mjs'); await driftwoodDeath(browser, phone, base, step); }
@@ -4,7 +4,7 @@
4
4
  // Then it reloads on the cache that walk left (Chromium refuses a whole-cache query that size), and with the link cut. --chunk= proves a one-shard page.
5
5
  // --play is the flip's checklist: one playthrough on the row, a line for every step, and it fails on any step that didn't work.
6
6
  // --hook on a chunk with a grapple proves the claw: LOCK and JUMP pressed on the page, and the server's bite and zip carrying the body.
7
- // scripts/browser-lane.sh node scripts/worker-client-proof.mjs --base=http://127.0.0.1:4401/ [--seconds=150] [--crossings=2] [--route=x,z;x,z] [--chunk=slug] [--play [--only=movers|sky-trails|data-shard|driftwood|nalati|riding|nine|shards|grid|fights|roc|rocfall|rooms|elite|sky|sunscar|farreach|isle|pine|lantern|rig|sweep]] [--hook]
7
+ // scripts/browser-lane.sh node scripts/worker-client-proof.mjs --base=http://127.0.0.1:4401/ [--seconds=150] [--crossings=2] [--route=x,z;x,z] [--chunk=slug] [--play [--only=slug [--slug=<slug>]|movers|sky-trails|data-shard|driftwood|nalati|riding|nine|shards|grid|fights|roc|rocfall|rooms|elite|sky|sunscar|farreach|isle|pine|lantern|rig|sweep]] [--hook]
8
8
  import { chromium, webkit, devices } from 'playwright';
9
9
  import { saveFixture } from './debug-settings.mjs';
10
10
  import { floorGridBenchmarkUrl, FLOOR_GRID_ENTER } from './frame-floor-navigation.mjs';
@@ -0,0 +1,44 @@
1
+ // SA37 (meta SHARD-AUTHORING-PLAN): the `/slug/<slug>` link an author shares, on a world build. The page is the shard's one card;
2
+ // its PLAY leaves for `/?chunk=<slug>`, and that page enters the world's grid at the shard's cell, as a Shard select tap does.
3
+ // Passes when the server seats the body in that cell, the page stands inside it and plays, with no page error.
4
+ // scripts/browser-lane.sh node scripts/worker-client-proof.mjs --base=<a world build> --play --only=slug [--slug=driftwood-isle]
5
+ /** @typedef {import('./types/worker-page').WorkerWindow} WorkerWindow */
6
+ import { saveFixture } from './debug-settings.mjs';
7
+ import { entered, settled } from './worker-client-grid-entry.mjs';
8
+
9
+ /** @param {import('playwright').Browser} browser @param {import('playwright').BrowserContextOptions} phone @param {string} base
10
+ * @param {import('./types/worker-page').ProofStep} step @param {string} [slug] */
11
+ export async function slugEntry(browser, phone, base, step, slug = 'driftwood-isle') {
12
+ const context = await browser.newContext(phone), page = await context.newPage(), errors = /** @type {string[]} */ ([]);
13
+ page.on('pageerror', error => { errors.push(error.message.slice(0, 300)); });
14
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
15
+ try {
16
+ await step(`slug: /slug/${slug} shows the shard's one card with PLAY`, async () => {
17
+ await page.goto(new URL(`/slug/${slug}?mute=1&nolock=1`, base).href, { waitUntil: 'load' });
18
+ const play = page.locator('.ws-slug .ws-menu-play');
19
+ await play.waitFor({ timeout: 60_000 });
20
+ const card = await page.evaluate(() => {
21
+ const root = /** @type {HTMLElement | null} */ (document.querySelector('.ws-slug'));
22
+ return { slug: root?.dataset.slug, placed: root?.dataset.placed,
23
+ name: document.querySelector('.ws-slug .ws-menu-card b')?.textContent, play: document.querySelector('.ws-slug .ws-menu-play b')?.textContent, path: location.pathname };
24
+ });
25
+ return { ok: card.slug === slug && card.placed === 'true' && card.play === 'Play', ...card };
26
+ });
27
+ await step(`slug: PLAY enters the world's grid at ${slug}'s cell`, async () => {
28
+ await Promise.all([page.waitForEvent('domcontentloaded', { timeout: 60_000 }).catch(() => undefined), (async () => {
29
+ await page.locator('.ws-slug .ws-menu-play').click();
30
+ // a device's first PLAY asks for the Name once (MP2.4)
31
+ const name = page.locator('#ws-name-box input');
32
+ if (await name.waitFor({ timeout: 5000 }).then(() => true, () => false)) {
33
+ await name.fill('Slug');
34
+ await page.locator('#ws-name-box button[type=submit]').click();
35
+ }
36
+ })()]);
37
+ await entered(page);
38
+ const out = await settled(page, slug);
39
+ const url = new URL(page.url());
40
+ // the grid page keeps `/` once it is in (its address is the grid, not the shard), so the cell is read from the server's seat
41
+ return { ok: out.server === slug && out.current === slug && out.inside === slug && out.ready === true && !url.pathname.startsWith('/slug/') && errors.length === 0, path: url.pathname, server: out.server, inside: out.inside, home: out.home, ready: out.ready, frames: out.frames, closed: out.closed, errors: errors.slice(0, 4) };
42
+ });
43
+ } finally { await context.close(); }
44
+ }
@@ -54,6 +54,8 @@ let crashResume: CrashResume | null = null;
54
54
  let selectedImages: Scope | undefined;
55
55
  const task = (): Promise<void> => new Promise((resolve) => { entryScope.timeout(0, resolve); });
56
56
  const UNLISTED = 'This world is not listed. Choose a world from the list.';
57
+ /** How long the boot waits for the placement file (`placedCells.ts`'s own deadline, GO4's 3 s), its chunk's import included. */
58
+ const PLACED_DEADLINE_MS = 3000;
57
59
  /** The plain home URL paints only the title. No renderer, world, or Three.js is imported until a shard is chosen. */
58
60
  // RL3: the static module graph has arrived and run; index.html's 12 s self-reload stands down (only a hung module
59
61
  // fetch, which never gets here, reloads by itself; anything after this is guardBoot's)
@@ -65,6 +67,9 @@ installDropNotes();
65
67
  installInlineCatalogue(document);
66
68
  const titleRows = withCatalogueHeads(readTitleRows(document));
67
69
  installTitleManifests(titleRows);
70
+ // SA33 to SA35, the page half: a released page adds the cells the API placed after its build (its channel's signed placement file) to the
71
+ // catalogue before anything reads the grid; `enterPage` waits for it (3 s at most), and any failure keeps the build's grid.
72
+ const placedCells = learnPlacedCellsOnce();
68
73
  // G727 / I9: Settings' "Download everything"; the prefetch loads only when the player opens or presses it
69
74
  installOfflineDownload({
70
75
  size: async owner => (await import('@wildshard/engine/game/grid/prefetch')).remainingDownloadBytes(owner),
@@ -98,13 +103,31 @@ function serverSites(): Promise<readonly { readonly site: string | null | undefi
98
103
  const late = new Promise<undefined>(resolve => { entryScope.timeout(SERVER_SITES_MS, () => { resolve(undefined); }); });
99
104
  return Promise.race([read, late]).catch(() => undefined);
100
105
  }
106
+ /** The page's placement file read, started at once; it never rejects and settles inside `PLACED_DEADLINE_MS` (3 s) of the entry's
107
+ * start, chunk import included. Past that the boot goes on with the build's grid and a late answer installs nothing. A page with no
108
+ * world (preview, solo) reads none. */
109
+ function learnPlacedCellsOnce(): Promise<void> {
110
+ const late = new AbortController();
111
+ const read = (async (): Promise<void> => {
112
+ try {
113
+ const { learnPlacedCells, placementsOf } = await import('@wildshard/engine/game/grid/placedCells');
114
+ const url = placementsOf(globalThis as { __WS_WORLD__?: unknown; __WS_PLACEMENTS__?: unknown });
115
+ if (url === null || late.signal.aborted) return;
116
+ const answer = await bootTask('app:placed-cells', () => learnPlacedCells(url, { signal: late.signal }));
117
+ if ('kept' in answer) console.info(`[grid] build's grid kept: ${answer.kept}`);
118
+ else console.info(`[grid] placement serial ${String(answer.serial)}: ${answer.added.map(cell => `${cell.instance} at (${cell.cell.join(',')})`).join(', ') || 'no new cell'}${answer.carded.length === 0 ? '' : `; carded from the catalogue ${answer.carded.join(', ')}`}${answer.left.length === 0 ? '' : `; left out ${answer.left.join('; ')}`}`);
119
+ } catch (error) { console.warn('[grid] placement file not read:', error); }
120
+ })();
121
+ const deadline = new Promise<void>(resolve => { entryScope.timeout(PLACED_DEADLINE_MS, () => { late.abort(); resolve(); }); });
122
+ return Promise.race([read, deadline]);
123
+ }
101
124
  async function enterPage(): Promise<unknown> {
125
+ await placedCells;
102
126
  const requested = search.get('chunk');
103
- // SA36: a `/slug/<slug>` link opens that one shard's page; its PLAY leaves for `/?chunk=<slug>`, so a world never boots here
104
- // Preview only until SA37 (a build with no world: the worker serves any navigation the cached page, so the Worker's gate alone
105
- // would open it on staging and production to a returning player)
127
+ // SA36: a `/slug/<slug>` link opens that one shard's page; its PLAY leaves for `/?chunk=<slug>`, so a world never boots here.
128
+ // SA37: on every host, a world build too: PLAY's `/?chunk=` page enters the world's grid at the shard's cell (GO7 below)
106
129
  const slugged = slugOfPath(location.pathname);
107
- if (slugged !== null && requested === null && (globalThis as { __WS_WORLD__?: unknown }).__WS_WORLD__ === undefined) return showSlugPage(slugged);
130
+ if (slugged !== null && requested === null) return showSlugPage(slugged);
108
131
  // An embedded author product has its own admission. A game URL must name a
109
132
  // listed world before any discovery, tables or renderer can be prepared.
110
133
  if (requested !== null && document.getElementById('ws-shardfile') === null && findTitleManifest(requested) === undefined) {
@@ -197,7 +220,10 @@ async function enterPage(): Promise<unknown> {
197
220
  import('@wildshard/engine/game/grid/menu'), import('@wildshard/engine/game/boot/spawnDownload')]));
198
221
  await tier.initializeTier();
199
222
  const slug = search.get('chunk');
200
- if (typeof slug === 'string') {
223
+ // SA43: a page that owns its inline shard (`wildshard dev`, `wildshard prepare` at `?chunk=`) has no catalogue download
224
+ // for it: that shard's spawn set isn't its download (as startSelected's `authored`)
225
+ const inlineShard = (menu.DEVSERVER || menu.PREPARATION_ONLY) && document.getElementById('ws-shardfile') !== null;
226
+ if (typeof slug === 'string' && !inlineShard) {
201
227
  const mode = menu.gridMode(menu.DEVSERVER), flow = pageGridRecovery() !== null || pendingGridEntry(slug) ? 'grid' : 'client';
202
228
  spawn.setSpawnPacks(runtimePacksOn());
203
229
  // LD2 (J208): a Start read this download holds (selected discovery behind the warm check) is named from the tap
@@ -348,7 +374,7 @@ async function startSelected(): Promise<void> {
348
374
  const moduleRows: unknown = moduleText === undefined ? undefined : JSON.parse(moduleText);
349
375
  const gridEntryModule = import('@wildshard/engine/game/grid/pageEntry');
350
376
  const gridMenuModule = import('@wildshard/engine/game/grid/menu');
351
- const [gridSelection, { gridMode, DEVSERVER }] = await Promise.all([gridEntryModule, gridMenuModule]);
377
+ const [gridSelection, { gridMode, DEVSERVER, PREPARATION_ONLY }] = await Promise.all([gridEntryModule, gridMenuModule]);
352
378
  const earlyPath = gridSelection.pageGridRecovery() !== null || gridSelection.pendingGridEntry(arrival.slug)
353
379
  ? 'grid' : 'shardfile';
354
380
  // MF4: one spawn manifest per shard / tier / flow (grid: per menu mode) is the whole download; the bar reads only it and
@@ -358,8 +384,9 @@ async function startSelected(): Promise<void> {
358
384
  setSpawnPacks(runtimePacksOn()); // DL16: Debug ▸ Loading & memory ▸ Level download
359
385
  // DL21: a read the whole-set hold stalls is named on the card as the spawn download, in its step
360
386
  observeSpawnHolds((held, path) => waitFor('Spawn download', held, 'file', `spawn-download:${path}`));
361
- // SA15: `wildshard dev`'s page carries the author's shard inline; the catalogue shard's spawn set isn't its download
362
- const authored = DEVSERVER && document.getElementById('ws-shardfile') !== null;
387
+ // SA15: `wildshard dev`'s page carries the author's shard inline; the catalogue shard's spawn set isn't its download.
388
+ // SA43: so does `wildshard prepare`'s, a preparation-only production build; only those two builds own an inline shard
389
+ const inlineOwner = DEVSERVER || PREPARATION_ONLY, authored = inlineOwner && document.getElementById('ws-shardfile') !== null;
363
390
  const spawnMode = gridMode(DEVSERVER), spawnJob = authored ? null : startSpawnDownload(arrival.slug, earlyPath === 'grid' ? 'grid' : 'client', TIER,
364
391
  `${Number(spawnMode.developer)}${Number(spawnMode.devserver)}${Number(spawnMode.nineDragon)}`);
365
392
  if (spawnJob !== null) void loading.setDownloadSource(spawnJob);
@@ -413,7 +440,7 @@ async function startSelected(): Promise<void> {
413
440
  try {
414
441
  imports.check();
415
442
  loading.setPrefetchSource(gridPrefetchStatus);
416
- const source = pageGridRecovery() === null ? await bootTask('app:product-source-and-read', () => configuredShardfile(document, browserShardfileOptions(document.baseURI, DEVSERVER))) : null;
443
+ const source = pageGridRecovery() === null ? await bootTask('app:product-source-and-read', () => configuredShardfile(document, browserShardfileOptions(document.baseURI, inlineOwner))) : null;
417
444
  page = preparePageResidency(arrival, source?.identity.slug);
418
445
  // The script memory bank, sized by route: each reserve can cost JSC a full GC (e472f34069), so a grid page reserves
419
446
  // the full-ALL route's demand for its cell activations in play, and a standalone page, which builds its one world under
@@ -453,7 +480,7 @@ async function startSelected(): Promise<void> {
453
480
  if (spawnJob !== null) await waitFor('Spawn download', spawnJob.listed ?? spawnJob.ready, 'file');
454
481
  const manifest = await bootAwait('app:product-admission', source === null
455
482
  ? installManifestShardfile(arrival, { ...browserShardfileOptions(document.baseURI, true), memory: page.memory, progress: (progress) => { loading.paintAdmission(progress); } }, bindings, imports.ready)
456
- : installShardfileProduct(source, { ...browserShardfileOptions(document.baseURI, DEVSERVER), memory: page.memory, progress: (progress) => { loading.paintAdmission(progress); } }, bindings, imports.ready));
483
+ : installShardfileProduct(source, { ...browserShardfileOptions(document.baseURI, inlineOwner), memory: page.memory, progress: (progress) => { loading.paintAdmission(progress); } }, bindings, imports.ready));
457
484
  // Keep the seam out of code and descriptor admission; world construction
458
485
  // can overlap this read and retains its original full-geometry barrier.
459
486
  if (page.mode === 'grid') gridSelection.startGridEntryContent(page.instance ?? pageGridRecovery()?.instance ?? gridSelection.gridHome().instance);
@@ -1,29 +1,89 @@
1
- /** Private worker transfer format: bounded JSON token pages, never a cloned
1
+ /** Private worker transfer format: binary tokens decoded in bounded steps, never a cloned
2
2
  * descriptor tree. Admission still runs on the completely reconstructed tree. */
3
- /** Native fatal UTF-8/JSON semantics, then bounded live-parser transfer pages. */
3
+ /** Native fatal UTF-8/JSON semantics, then the live parser's binary token transfer. */
4
4
  export function parseJsonPages(bytes: Uint8Array): Uint8Array {
5
5
  const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
6
6
  return encodeParsedPages(value);
7
7
  }
8
8
 
9
- type Token = readonly ['o' | 'a', number] | readonly ['s', string, boolean]
10
- | readonly ['n', string] | readonly ['v', boolean | null];
9
+ /* PZ23 (WILDSHARD-GAME-8G): binary tokens, so a number crosses as a float64 and the page thread makes no string for it
10
+ * (the JSON token pages before made a token array and two strings a number: ~400 bytes of garbage, ~211 MB in the
11
+ * first minute on Driftwood). Little-endian, after one version byte:
12
+ * OBJECT u32 count · ARRAY u32 count · NUMBER f64 · NULL · FALSE · TRUE
13
+ * UTF8 u8 last, u32 bytes, UTF-8 · UTF16 u8 last, u32 units, UTF-16 units (a string that is not well formed: a lone
14
+ * surrogate survives JSON.parse, never UTF-8). A string goes in parts of at most PART code units.
15
+ * REF u32 index: a short string sent before (at most SHORT code units: keys, names, kinds), the index-th such string in
16
+ * send order, so a repeated key costs the page thread no view and no decode. */
17
+ const VERSION = 0x57, OBJECT = 1, ARRAY = 2, UTF8 = 3, UTF16 = 4, NUMBER = 5, NULL = 6, FALSE = 7, TRUE = 8, REF = 9;
18
+ const SHORT = 64;
19
+ /** A string part's code units, and a decode step's bounds: at most STEP_TOKENS tokens or STEP_BYTES transfer bytes. */
20
+ const PART = 4096, STEP_TOKENS = 32, STEP_BYTES = 16_384;
11
21
 
12
- function* tokens(input: unknown): Generator<Token> {
13
- const pending: unknown[] = [input];
22
+ class Writer {
23
+ bytes = new Uint8Array(65_536);
24
+ view = new DataView(this.bytes.buffer);
25
+ at = 0;
26
+ private readonly encoder = new TextEncoder();
27
+ private readonly short = new Map<string, number>();
28
+ room(n: number): void {
29
+ if (this.at + n <= this.bytes.length) return;
30
+ let size = this.bytes.length * 2;
31
+ while (size < this.at + n) size *= 2;
32
+ const next = new Uint8Array(size); next.set(this.bytes.subarray(0, this.at));
33
+ this.bytes = next; this.view = new DataView(next.buffer);
34
+ }
35
+ tag(tag: number): void { this.room(1); this.bytes[this.at++] = tag; }
36
+ count(tag: number, n: number): void { this.room(5); this.bytes[this.at] = tag; this.view.setUint32(this.at + 1, n, true); this.at += 5; }
37
+ number(value: number): void { this.room(9); this.bytes[this.at] = NUMBER; this.view.setFloat64(this.at + 1, value, true); this.at += 9; }
38
+ string(value: string): void {
39
+ if (value.length <= SHORT) {
40
+ const index = this.short.get(value);
41
+ if (index !== undefined) { this.count(REF, index); return; }
42
+ this.short.set(value, this.short.size);
43
+ }
44
+ // in a Unicode-mode class a whole pair is one code point, so only a lone surrogate matches
45
+ const utf8 = !/[\uD800-\uDFFF]/u.test(value);
46
+ if (value.length === 0) { this.part(UTF8, 1, 0); return; }
47
+ for (let from = 0; from < value.length;) {
48
+ let to = Math.min(value.length, from + PART);
49
+ // never split a surrogate pair across UTF-8 parts
50
+ if (utf8 && to < value.length && (value.codePointAt(to - 1) ?? 0) > 0xffff) to--;
51
+ const last = to >= value.length ? 1 : 0;
52
+ if (utf8) {
53
+ this.room(6 + (to - from) * 3);
54
+ const { written } = this.encoder.encodeInto(value.slice(from, to), this.bytes.subarray(this.at + 6));
55
+ this.part(UTF8, last, written); this.at += written;
56
+ } else {
57
+ this.room(6 + (to - from) * 2);
58
+ this.part(UTF16, last, to - from);
59
+ // oxlint-disable-next-line unicorn/prefer-code-point -- UTF-16 units, not code points: a lone surrogate crosses as it is
60
+ for (let i = from; i < to; i++, this.at += 2) this.view.setUint16(this.at, value.charCodeAt(i), true);
61
+ }
62
+ from = to;
63
+ }
64
+ }
65
+ /** A string part's head; its body follows at `at`. */
66
+ private part(tag: number, last: number, length: number): void {
67
+ this.room(6); this.bytes[this.at] = tag; this.bytes[this.at + 1] = last; this.view.setUint32(this.at + 2, length, true); this.at += 6;
68
+ }
69
+ }
70
+
71
+ /** Called only on the worker's native JSON.parse result. */
72
+ export function encodeParsedPages(input: unknown): Uint8Array {
73
+ const out = new Writer(), pending: unknown[] = [input];
74
+ out.tag(VERSION);
14
75
  while (pending.length > 0) {
15
76
  const value = pending.pop();
16
- if (typeof value === 'string') {
17
- if (value.length === 0) yield ['s', '', true];
18
- for (let at = 0; at < value.length; at += 256) yield ['s', value.slice(at, at + 256), at + 256 >= value.length];
19
- } else if (typeof value === 'number') yield ['n', Object.is(value, -0) ? '-0' : String(value)];
20
- else if (value === null || typeof value === 'boolean') yield ['v', value];
77
+ if (typeof value === 'string') out.string(value);
78
+ else if (typeof value === 'number') out.number(value);
79
+ else if (value === null) out.tag(NULL);
80
+ else if (typeof value === 'boolean') out.tag(value ? TRUE : FALSE);
21
81
  else if (Array.isArray(value)) {
22
- yield ['a', value.length];
82
+ out.count(ARRAY, value.length);
23
83
  for (let at = value.length - 1; at >= 0; at--) pending.push(value[at]);
24
84
  } else if (typeof value === 'object') {
25
85
  const entries = Object.entries(value);
26
- yield ['o', entries.length];
86
+ out.count(OBJECT, entries.length);
27
87
  for (let at = entries.length - 1; at >= 0; at--) {
28
88
  const entry = entries[at];
29
89
  if (entry === undefined) throw new Error('Missing parsed entry');
@@ -31,38 +91,21 @@ function* tokens(input: unknown): Generator<Token> {
31
91
  }
32
92
  } else throw new TypeError('Invalid parsed value');
33
93
  }
94
+ return out.bytes.slice(0, out.at);
34
95
  }
35
96
 
36
- /** Called only on the worker's native JSON.parse result. */
37
- export function encodeParsedPages(value: unknown): Uint8Array {
38
- const encoder = new TextEncoder(), pages: Uint8Array[] = [];
39
- let page: string[] = [], characters = 0, bytes = 0;
40
- const flush = (): void => {
41
- if (page.length === 0) return;
42
- const encoded = encoder.encode(`[${page.join(',')}]`);
43
- pages.push(encoded); bytes += 4 + encoded.length; page = []; characters = 0;
44
- };
45
- for (const token of tokens(value)) {
46
- const text = JSON.stringify(token);
47
- if (page.length >= 32 || characters + text.length > 4096) flush();
48
- page.push(text); characters += text.length + 1;
49
- }
50
- flush();
51
- const output = new Uint8Array(bytes), view = new DataView(output.buffer);
52
- let at = 0;
53
- for (const part of pages) { view.setUint32(at, part.length, true); output.set(part, at + 4); at += 4 + part.length; }
54
- return output;
55
- }
56
-
57
- type Frame = {readonly value: unknown[]; remaining: number}
97
+ type Frame = {readonly value: unknown[]; remaining: number; next: number}
58
98
  | {readonly value: Record<string, unknown>; remaining: number; key: string | undefined};
59
99
 
60
- /** Yield between every bounded native decode/parse and tree-construction page.
100
+ /** Yield before every bounded decode step (at most 32 tokens or 16 KiB of transfer) and once at the end.
61
101
  * Nothing caller-visible is published until the entire transfer is checked. */
62
102
  export async function decodeParsedPages(bytes: Uint8Array, pause: () => Promise<void>): Promise<unknown> {
63
- const frames: Frame[] = [], decoder = new TextDecoder('utf-8', {fatal: true});
103
+ // ignoreBOM: each part is decoded alone, and a string may start with U+FEFF
104
+ const frames: Frame[] = [], decoder = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true});
105
+ let slots = 0;
64
106
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
65
107
  let root: unknown, hasRoot = false, string: string | undefined;
108
+ const short: string[] = [];
66
109
  const put = (value: unknown): void => {
67
110
  const frame = frames.at(-1);
68
111
  if (frame === undefined) {
@@ -76,35 +119,61 @@ export async function decodeParsedPages(bytes: Uint8Array, pause: () => Promise<
76
119
  if (Object.hasOwn(frame.value, frame.key)) throw new Error('Duplicate parsed key');
77
120
  Object.defineProperty(frame.value, frame.key, {value, writable: true, enumerable: true, configurable: true});
78
121
  frame.key = undefined; frame.remaining--;
79
- } else { frame.value.push(value); frame.remaining--; }
122
+ } else { frame.value[frame.next++] = value; frame.remaining--; }
80
123
  };
81
124
  const complete = (): void => { while (frames.at(-1)?.remaining === 0) frames.pop(); };
82
- for (let at = 0; at < bytes.length;) {
125
+ const need = (at: number, n: number): void => { if (n > bytes.length - at) throw new Error('Incomplete parsed token'); };
126
+ if (bytes.length === 0 || bytes[0] !== VERSION) throw new Error('Invalid parsed transfer');
127
+ for (let at = 1; at < bytes.length;) {
83
128
  await pause();
84
- if (at + 4 > bytes.length) throw new Error('Incomplete parsed page');
85
- const length = view.getUint32(at, true); at += 4;
86
- if (length === 0 || length > 16_384 || length > bytes.length - at) throw new Error('Invalid parsed page');
87
- const page: unknown = JSON.parse(decoder.decode(bytes.subarray(at, at + length))); at += length;
88
- if (!Array.isArray(page) || page.length === 0 || page.length > 32) throw new Error('Invalid parsed tokens');
89
- for (const token of page) {
90
- if (!Array.isArray(token)) throw new Error('Invalid parsed token');
91
- const [kind, value, last] = token;
92
- if (kind === 's' && token.length === 3 && typeof value === 'string' && value.length <= 256 && typeof last === 'boolean') {
93
- string = (string ?? '') + value;
94
- if (last) { put(string); string = undefined; complete(); }
129
+ const stepEnd = at + STEP_BYTES;
130
+ for (let tokens = 0; tokens < STEP_TOKENS && at < bytes.length && at < stepEnd; tokens++) {
131
+ const tag = bytes[at++];
132
+ if (tag === UTF8 || tag === UTF16) {
133
+ need(at, 5);
134
+ const last = bytes[at], length = view.getUint32(at + 1, true); at += 5;
135
+ if ((last !== 0 && last !== 1) || length > (tag === UTF8 ? PART * 3 : PART)) throw new Error('Invalid parsed string');
136
+ const size = tag === UTF8 ? length : length * 2;
137
+ need(at, size);
138
+ let part = '';
139
+ if (tag === UTF8) part = decoder.decode(bytes.subarray(at, at + size));
140
+ // oxlint-disable-next-line unicorn/prefer-code-point -- UTF-16 units, not code points: a lone surrogate crosses as it is
141
+ else for (let i = 0; i < length; i++) part += String.fromCharCode(view.getUint16(at + i * 2, true));
142
+ at += size;
143
+ string = string === undefined ? part : string + part;
144
+ if (last === 1) { if (string.length <= SHORT) short.push(string); put(string); string = undefined; complete(); }
95
145
  continue;
96
146
  }
97
- if (string !== undefined || token.length !== 2) throw new Error('Incomplete parsed string');
98
- if ((kind === 'o' || kind === 'a') && typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
99
- if (kind === 'a') {
100
- const container: unknown[] = []; put(container);
101
- if (value > 0) frames.push({value: container, remaining: value});
147
+ if (string !== undefined) throw new Error('Incomplete parsed string');
148
+ if (tag === REF) {
149
+ need(at, 4);
150
+ const value = short[view.getUint32(at, true)]; at += 4;
151
+ if (value === undefined) throw new Error('Invalid parsed reference');
152
+ put(value); complete(); continue;
153
+ }
154
+ if (tag === OBJECT || tag === ARRAY) {
155
+ need(at, 4);
156
+ const count = view.getUint32(at, true); at += 4;
157
+ // every element or entry takes at least one more byte, so no count, nor all of them together, sizes past the transfer
158
+ slots += count;
159
+ if (count > bytes.length - at || slots > bytes.length) throw new Error('Invalid parsed count');
160
+ if (tag === ARRAY) {
161
+ // sized once: a pushed array regrows and leaves its old backing stores behind
162
+ // oxlint-disable-next-line unicorn/no-new-array -- a length: the decode fills every slot before anything is published
163
+ const container: unknown[] = new Array<unknown>(count); put(container);
164
+ if (count > 0) frames.push({value: container, remaining: count, next: 0});
102
165
  } else {
103
166
  const container: Record<string, unknown> = {}; put(container);
104
- if (value > 0) frames.push({value: container, remaining: value, key: undefined});
167
+ if (count > 0) frames.push({value: container, remaining: count, key: undefined});
105
168
  }
106
- } else if (kind === 'n' && typeof value === 'string' && (value === '-0' || String(Number(value)) === value)) put(Number(value));
107
- else if (kind === 'v' && (value === null || typeof value === 'boolean')) put(value);
169
+ } else if (tag === NUMBER) {
170
+ need(at, 8);
171
+ const value = view.getFloat64(at, true); at += 8;
172
+ if (Number.isNaN(value)) throw new Error('Invalid parsed number');
173
+ put(value);
174
+ } else if (tag === NULL) put(null);
175
+ else if (tag === FALSE) put(false);
176
+ else if (tag === TRUE) put(true);
108
177
  else throw new Error('Invalid parsed token');
109
178
  complete();
110
179
  }
@@ -1,2 +1,4 @@
1
1
  /** Vite's compiled author-dev mode. Production/native builds always substitute false. */
2
2
  declare const __DEVSERVER__: boolean;
3
+ /** SHARD-AUTHORING SA43: a `WILDSHARD_PREPARATION_ONLY` production build, the client `wildshard prepare` records in. */
4
+ declare const __PREPARATION_ONLY__: boolean;
@@ -1222,6 +1222,24 @@ export class Game {
1222
1222
  }
1223
1223
  }
1224
1224
 
1225
+ /**
1226
+ * RP4: link the road (exterior) variants of an entered grid cell's content, as the boot's entry roots' are
1227
+ * (`warmDeferredEntryRoots`: nearest first, spaced by drawn frames, dropped once `owner` leaves). Past its sky layer's half
1228
+ * weight the road draws the cell with the page's own environment (none on a grid page), not the cell's PMREM: without
1229
+ * these, every program of the cell linked in one frame 2 m before its edge (Driftwood's west edge: about 17 links, 2.5 to
1230
+ * 4.3 s in Chromium). `roots` are not registered exterior roots (those are left out of the road's variants).
1231
+ */
1232
+ async warmExteriorRoots(owner: Scope, roots: readonly THREE.Object3D[], current: () => boolean): Promise<void> {
1233
+ this.deferredEntryRoots.push({ owner, roots });
1234
+ if (this.frameCount === 0) return; // the boot's own in-play warm-up takes it (finish.ts)
1235
+ // one loop at a time: a second entry joins the queue behind the first, never a parallel warm-up in the same frames
1236
+ const run = this.exteriorWarm.catch(() => undefined).then(() => this.warmDeferredEntryRoots(current));
1237
+ this.exteriorWarm = run;
1238
+ await run;
1239
+ }
1240
+ /** RP4: the running road-variant warm-up (`warmExteriorRoots`), which the next one waits behind */
1241
+ private exteriorWarm: Promise<void> = Promise.resolve();
1242
+
1225
1243
  /**
1226
1244
  * D188 (G815): after an arrival's reveal, what it left (`rest`, gated out of live draws) is linked and first-drawn
1227
1245
  * nearest the player first: the whole remaining program inventory under the live slice budget, then the rest's 1×1