@wildshard/engine 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/index.html +157 -11
- package/lint/engine-sides.json +16 -0
- package/lint/host-register.json +496 -0
- package/lint/ratchet.json +2 -2
- package/lint/shard-imports.d.mts +1 -0
- package/lint/shard-imports.mjs +56 -8
- package/lint/wildshard-plugin.js +22 -4
- package/package.json +16 -5
- package/scripts/app-build/buildIdentity.d.mts +3 -1
- package/scripts/app-build/buildIdentity.mjs +25 -5
- package/scripts/app-build/builtAt.d.mts +4 -0
- package/scripts/app-build/builtAt.mjs +21 -0
- package/scripts/app-build/serviceWorker.ts +16 -2
- package/scripts/app-build/versionFiles.ts +2 -1
- package/scripts/app-build-pipeline.mjs +4 -1
- package/scripts/audio-download-proof.mjs +843 -0
- package/scripts/build-app.mjs +4 -0
- package/scripts/build-mirror.d.mts +2 -0
- package/scripts/build-mirror.mjs +5 -4
- package/scripts/built-product.mjs +3 -3
- package/scripts/cell-mem/metrics-preload.mjs +65 -0
- package/scripts/cell-mem-bench.mjs +130 -0
- package/scripts/check-chunks.mjs +2 -1
- package/scripts/devserver-client.d.mts +5 -0
- package/scripts/devserver-client.mjs +68 -0
- package/scripts/engine-ci-budget.ts +7 -1
- package/scripts/format-lock.mjs +20 -11
- package/scripts/generate-title-launch.mjs +3 -2
- package/scripts/grid-crossing-walk-proof.mjs +16 -8
- package/scripts/heavy-lane.py +25 -1
- package/scripts/host-ruler/register-migrate.mjs +242 -0
- package/scripts/host-ruler/register.d.mts +36 -0
- package/scripts/host-ruler/register.mjs +116 -0
- package/scripts/host-ruler/roots.d.mts +29 -0
- package/scripts/host-ruler/roots.mjs +333 -0
- package/scripts/host-ruler/server-roots.d.mts +23 -0
- package/scripts/host-ruler/server-roots.mjs +272 -0
- package/scripts/main-watch.d.mts +1 -1
- package/scripts/main-watch.mjs +10 -6
- package/scripts/map-hash.mjs +3 -6
- package/scripts/mmo-bots.mjs +2 -2
- package/scripts/offline-proof-rules.d.mts +1 -0
- package/scripts/offline-proof-rules.mjs +22 -1
- package/scripts/online-rig.mjs +4 -4
- package/scripts/page-release/flow.d.mts +1 -0
- package/scripts/page-release/flow.mjs +6 -2
- package/scripts/page-release.mjs +5 -1
- package/scripts/physics-route.json +0 -71
- package/scripts/pins-catalogue.ts +103 -0
- package/scripts/pins-reuse.mjs +3 -1
- package/scripts/pins.ts +22 -14
- package/scripts/preview-grid.ts +203 -0
- package/scripts/road-preload-proof.mjs +167 -0
- package/scripts/server-release/publish.mjs +2 -2
- package/scripts/server-release/served-slug.d.mts +2 -0
- package/scripts/server-release/served-slug.mjs +10 -0
- package/scripts/server-release/sign.d.mts +1 -0
- package/scripts/server-release/sign.mjs +3 -7
- package/scripts/shard-components.mjs +0 -2
- package/scripts/shard-outputs.d.mts +8 -0
- package/scripts/shard-outputs.mjs +45 -11
- package/scripts/side-parity.d.mts +2 -1
- package/scripts/side-parity.mjs +25 -4
- package/scripts/test-amber.d.mts +1 -0
- package/scripts/test-amber.mjs +10 -0
- package/scripts/test-products.json +3 -3
- package/scripts/tracked-public.d.mts +1 -0
- package/scripts/tracked-public.mjs +17 -0
- package/src/cli/engine.mjs +8 -0
- package/src/client/app/bootRoute.ts +4 -1
- package/src/client/app/dropModal.ts +15 -2
- package/src/client/app/entry.ts +67 -11
- package/src/client/app/slugPath.ts +5 -0
- package/src/client/engine/audio/Audio.ts +20 -2
- package/src/client/engine/boot/bakedTextures.ts +3 -2
- package/src/client/engine/boot/bootTrace.ts +6 -1
- package/src/client/engine/boot/bytes.ts +4 -3
- package/src/client/engine/boot/clearDownloads.ts +1 -1
- package/src/client/engine/boot/contentRead.ts +4 -0
- package/src/client/engine/boot/dropNotice.ts +20 -6
- package/src/client/engine/boot/gpuFiles.ts +25 -2
- package/src/client/engine/boot/lastEnd.ts +8 -2
- package/src/client/engine/boot/shardPrefetch.ts +7 -1
- package/src/client/engine/boot/sw.ts +19 -0
- package/src/client/engine/core/Game.ts +11 -3
- package/src/client/engine/core/GpuRecovery.ts +7 -0
- package/src/client/engine/core/Volumetrics.ts +5 -0
- package/src/client/engine/core/assets.ts +27 -20
- package/src/client/engine/core/bootstrap.ts +1 -2
- package/src/client/engine/core/ktx2.ts +84 -11
- package/src/client/engine/explore/Compare.ts +2 -2
- package/src/client/engine/explore/TouchFly.ts +3 -5
- package/src/client/engine/input/dom.ts +12 -0
- package/src/client/engine/net/predictor.ts +6 -2
- package/src/client/engine/player/Player.ts +10 -2
- package/src/client/engine/player/TouchControls.ts +12 -4
- package/src/client/engine/pwa/sw.js +47 -8
- package/src/client/engine/render/drawCheck.ts +96 -0
- package/src/client/engine/saves/staleBuildNote.ts +46 -0
- package/src/client/engine/telemetry/browserErrors.ts +157 -20
- package/src/client/engine/telemetry/screenOutbox.ts +61 -0
- package/src/client/engine/telemetry/staleBuildReport.ts +12 -0
- package/src/client/engine/ui/DeathFade.ts +99 -11
- package/src/client/engine/ui/ErrorModal.ts +13 -6
- package/src/client/engine/ui/Feedback.ts +2 -1
- package/src/client/engine/ui/Loading.ts +10 -6
- package/src/client/engine/ui/Map.ts +2 -1
- package/src/client/engine/ui/WeaponStrip.ts +2 -1
- package/src/client/engine/ui/backGuard.ts +104 -0
- package/src/client/engine/ui/hudAdapters.ts +30 -4
- package/src/client/engine/ui/loading.css +17 -0
- package/src/client/engine/ui/namePrompt.ts +6 -5
- package/src/client/engine/ui/styles/combat.css +12 -0
- package/src/client/engine/ui/styles/namePrompt.css +4 -2
- package/src/client/game/boot/audio.generated.ts +0 -294
- package/src/client/game/boot/bytes.generated.ts +0 -11
- package/src/client/game/boot/versions.generated.ts +0 -11
- package/src/client/game/compendium/keepsakes.ts +16 -6
- package/src/client/game/grapple/tool.ts +10 -7
- package/src/client/game/grid/cellLoading.ts +23 -12
- package/src/client/game/grid/cellScreens.ts +39 -74
- package/src/client/game/grid/liveSession.ts +40 -7
- package/src/client/game/grid/nearPlaceholderPlan.ts +8 -0
- package/src/client/game/grid/nearPlaceholderView.ts +9 -3
- package/src/client/game/grid/oneWayIn.ts +92 -27
- package/src/client/game/grid/pageEntry.ts +19 -0
- package/src/client/game/grid/pageShell.ts +1 -1
- package/src/client/game/grid/plotAudio.ts +114 -0
- package/src/client/game/grid/products.ts +55 -5
- package/src/client/game/grid/roadLookPlatform.ts +2 -2
- package/src/client/game/grid/session.ts +38 -22
- package/src/client/game/grid/spawnGround.ts +68 -0
- package/src/client/game/grid/voidLook.ts +29 -23
- package/src/client/game/loot/runtime.ts +3 -1
- package/src/client/game/mainMenu.ts +14 -6
- package/src/client/game/riding/hud.ts +6 -4
- package/src/client/game/session/finish.ts +17 -3
- package/src/client/game/session/play.ts +8 -2
- package/src/client/game/session/session.ts +4 -1
- package/src/client/game/shardfile/clientWorker.ts +41 -12
- package/src/client/game/shardfile/serverRoute.ts +10 -22
- package/src/client/game/slugPage.css +11 -0
- package/src/client/game/slugPage.ts +84 -0
- package/src/client/game/systems/viewmodel/heldView.ts +6 -3
- package/src/client/game/titleDeck.ts +55 -32
- package/src/client/host/online/doctor.ts +7 -6
- package/src/client/host/online/linkScreens.ts +16 -0
- package/src/client/host/online/release.ts +51 -5
- package/src/client/host/online/shell.ts +48 -27
- package/src/client/host/standalone/shell.ts +7 -3
- package/src/cook/game/audioReport.ts +57 -0
- package/src/cook/game/entryTotals.ts +26 -6
- package/src/cook/game/installedRuntimeReads.ts +3 -0
- package/src/server/engine/sim/respawn.ts +6 -1
- package/src/server/engine/sim.ts +3 -0
- package/src/server/game/grid/simulation.ts +35 -0
- package/src/server/game/loot/harvest.ts +2 -0
- package/src/server/game/loot/keepsakeProgression.ts +40 -0
- package/src/server/game/loot/playerOwned.ts +5 -1
- package/src/server/game/plugin/simulation.ts +4 -0
- package/src/server/game/population/nativeBake.ts +2 -1
- package/src/server/game/quest/chapterRecords.ts +2 -0
- package/src/server/game/quest/serverChapters.ts +4 -0
- package/src/server/game/quest/serverDoors.ts +11 -5
- package/src/server/game/roomRespawn.ts +4 -0
- package/src/server/game/shardfile/installedSides.ts +18 -0
- package/src/server/game/shardfile/nativeAssemblyHosts.ts +19 -10
- package/src/server/game/shardfile/nativeAssemblyInput.ts +1 -4
- package/src/server/host/bake/headlessWorker.ts +5 -1
- package/src/server/host/dedicated/cellHost.ts +98 -29
- package/src/server/host/dedicated/cellProtocol.ts +11 -1
- package/src/server/host/dedicated/cellWorker.ts +9 -3
- package/src/server/host/dedicated/crossing.ts +6 -2
- package/src/server/host/dedicated/dedicatedRoom.ts +21 -8
- package/src/server/host/dedicated/gridCells.ts +52 -9
- package/src/server/host/dedicated/main.ts +31 -12
- package/src/server/host/dedicated/placementFile.ts +72 -0
- package/src/server/host/dedicated/releaseFile.ts +17 -10
- package/src/server/host/dedicated/roadRoom.ts +21 -5
- package/src/server/host/dedicated/workerTable.ts +13 -1
- package/src/server/host/dedicated/world.ts +81 -9
- package/src/server/host/headlessRuntime.ts +10 -5
- package/src/server/host/installers.ts +62 -0
- package/src/server/host/openWorld.ts +59 -0
- package/src/server/host/ropeDecks.ts +2 -0
- package/src/server/host/standalone/cellWorld.ts +25 -19
- package/src/server/host/standalone/fallFloor.ts +2 -2
- package/src/server/host/standalone/gridServer.ts +7 -4
- package/src/server/host/standalone/roadWorld.ts +41 -4
- package/src/shared/engine/audio/bootAudio.ts +33 -0
- package/src/shared/engine/level/spec.ts +3 -3
- package/src/shared/engine/net/acts.ts +3 -0
- package/src/shared/engine/physics/query.ts +27 -0
- package/src/shared/engine/physics/terrain.ts +19 -28
- package/src/shared/engine/saves/saves.lock.json +15 -0
- package/src/shared/engine/sim/actRoutes.ts +2 -0
- package/src/shared/game/compendium/keepsakeProgression.ts +24 -0
- package/src/shared/game/grid/catalogue.ts +12 -5
- package/src/shared/game/grid/catalogueSlot.ts +11 -0
- package/src/shared/game/grid/farProxy.ts +6 -5
- package/src/shared/game/grid/pageMode.ts +1 -1
- package/src/shared/game/grid/roadLayout.ts +26 -3
- package/src/shared/game/grid/singleplayer.json +0 -13
- package/src/shared/game/grid/voidFloor.ts +122 -0
- package/src/shared/game/strings.ts +15 -0
- package/src/shared/host/standalone/netInput.ts +2 -1
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// AUDIO AU14 (meta docs/plans/AUDIO-PLAN.md, J299/J303/J304): the proof that audio downloads at DOWNLOAD and LOAD never asks
|
|
3
|
+
// the network for it, on staging and on a staging-like local build.
|
|
4
|
+
//
|
|
5
|
+
// Per entry (shard and route), one fresh persistent headless WebKit profile (402x874, touch, iPhone UA), two visits:
|
|
6
|
+
// warm the player's path on a normal link (the profile is fresh, so this visit fills the worker's caches)
|
|
7
|
+
// slow the same profile again on a 0.7 Mbit/s, 300 ms link
|
|
8
|
+
// Routes: `grid` is the deck entry (Shard select, ENTER WORLD: the `<shard>-grid-phone` spawn manifest); `client` is the
|
|
9
|
+
// one-shard page, the deep link `?chunk=<slug>&skipintro` with Developer on (the `-client-phone` manifest). Open Plots have no deck
|
|
10
|
+
// card, so they take `client`. The warm visit must fetch its route's own phone manifest; a later visit may read it from the
|
|
11
|
+
// page's store and fetch none, so it is judged against the manifest its warm visit fetched.
|
|
12
|
+
// `cross` (preview only) is a player's way into an Open Plot: Shard select, its deck neighbour (CROSS_IN), ENTER WORLD, then a
|
|
13
|
+
// walk across the road into the plot through the in-page server. Staging can't cross (`WORLD_CROSSING` is unset there) and the
|
|
14
|
+
// local build's world door refuses it, so only preview runs it. Its sound window is the first 10 s after the crossing, and the
|
|
15
|
+
// plot's own score must become the music's score in it; its manifest is the neighbour's grid one.
|
|
16
|
+
//
|
|
17
|
+
// The link: WebKit has no CDP, so `Network.emulateNetworkConditions` (the offline audits' shaping, scripts/offline-proof.mjs)
|
|
18
|
+
// can't run. Every byte instead goes through this script's own forward proxy (Playwright's `proxy`, loopback included):
|
|
19
|
+
// CONNECT tunnels for https/wss, plain forwarding for the local build's http. In slow mode each direction is a 87,500 B/s
|
|
20
|
+
// link (0.7 Mbit/s) and each piece lands 150 ms after it leaves the link (300 ms round trip). No request is routed with
|
|
21
|
+
// Playwright (a route makes the service worker skip its cache, AU2's finding), so the worker's caches behave as on a phone.
|
|
22
|
+
// Phases come from the page itself: a MutationObserver stamps each change of the card's phase and step, and each request takes
|
|
23
|
+
// the phase in force when the proof saw it.
|
|
24
|
+
//
|
|
25
|
+
// Red (exit 1), per visit:
|
|
26
|
+
// load-audio a page request for `/assets/{music,sfx}/**`, `blobs/audio/**` or a spawn part that packs audio, while the
|
|
27
|
+
// card's phase is LOAD (served by the worker or the network alike: either way LOAD asked for it), or, on the
|
|
28
|
+
// local build where the proxy sees every http URL, any network fetch of one during LOAD (the service
|
|
29
|
+
// worker's own included; on staging the worker's own fetches are TLS the proxy can't read)
|
|
30
|
+
// download-short the route's spawn manifest totals under the shard's audio MB from AU6, or its own audio rows do
|
|
31
|
+
// route the warm visit fetched no `<shard>-<route>-phone` manifest
|
|
32
|
+
// no-load the card never reached LOAD, so there was nothing to judge
|
|
33
|
+
// link-blind on the local build, no http read went through the proxy
|
|
34
|
+
// silent on a visit that reaches play: the music bus or the sound-effects bus stays silent (peak under -60 dBFS)
|
|
35
|
+
// for the first 10 s of play; the proof walks and jumps in that window so footsteps play
|
|
36
|
+
// (not on a `&skipintro` deep link: that bench path never runs ENTER WORLD, so it never starts the music
|
|
37
|
+
// or unhushes the world; its peaks are in the receipt, the bar is the deck entries')
|
|
38
|
+
// no-cross a `cross` visit that reached play never stood inside the plot
|
|
39
|
+
// plot-score a `cross` visit crossed in, but the music's score never became the plot's own in the 10 s after
|
|
40
|
+
// cross-audio a `cross` visit fetched audio from the network on the road, between leaving the neighbour and standing in
|
|
41
|
+
// the plot (the download should hold it all). Once in the plot, its own takes and loops are a play-time
|
|
42
|
+
// read (AU20: never in LOAD, and the neighbour's DOWNLOAD keeps only its own audio): reported, not red
|
|
43
|
+
// no-play the warm visit doesn't reach play (a slow visit or a bench deep link that stops short of play is reported,
|
|
44
|
+
// not red: its LOAD is still judged).
|
|
45
|
+
// On the local build rooms-staging refuses the loopback origin's socket, so its load ends at the seat (LOAD
|
|
46
|
+
// step `server`, `seat-wait`, as in offline-proof.mjs): LOAD and DOWNLOAD are judged there, audibility on staging
|
|
47
|
+
// The buses are found by an init script that watches `AudioNode.connect`: the mixer's master is the gain that feeds a low-pass
|
|
48
|
+
// that feeds the compressor (engine Audio.ts `graph()`); its first input is the `world` bus, whose first input is `sfx`; any
|
|
49
|
+
// later input to the master is music (Music.ts's duck gain, or `bus('music')`). Each gets an AnalyserNode beside it.
|
|
50
|
+
//
|
|
51
|
+
// scripts/browser-lane.sh node scripts/audio-download-proof.mjs [--target=staging|local|preview|both|all] [--base=<served build>]
|
|
52
|
+
// [--entry=<slug>:<grid|client|cross>[,…]] [--jobs=<n>] [--out=<dir>]
|
|
53
|
+
// `preview` is the same served build with no world (the solo page): its deep links take the one-shard `client` manifest,
|
|
54
|
+
// which a world build no longer uses (OF2), and reach play. `both` is staging and local, `all` adds preview.
|
|
55
|
+
// `--target=local` or `preview` with no `--base` builds this working tree with scripts/serve-build.sh and stops that server at the end.
|
|
56
|
+
// The local origin stamps every document with staging's world (as offline-proof.mjs does), and its world door is the real
|
|
57
|
+
// rooms-staging, which refuses it (see no-play above). Staging is joined for real; prod is never touched.
|
|
58
|
+
// CI never runs this (no browser proof in pre-push or CI).
|
|
59
|
+
import { spawnSync } from 'node:child_process';
|
|
60
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
61
|
+
import { createServer, request as httpRequest } from 'node:http';
|
|
62
|
+
import { connect as netConnect } from 'node:net';
|
|
63
|
+
import { join, resolve as resolvePath } from 'node:path';
|
|
64
|
+
import { webkit } from 'playwright';
|
|
65
|
+
import { saveFixture } from './debug-settings.mjs';
|
|
66
|
+
import { CHANNELS, RELEASE_PUBLIC_KEY } from './page-release/flow.mjs';
|
|
67
|
+
|
|
68
|
+
const ROOT = resolvePath(import.meta.dirname, '..');
|
|
69
|
+
const argv = process.argv.slice(2);
|
|
70
|
+
/** @param {string} name */
|
|
71
|
+
const option = name => argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
|
|
72
|
+
const targetArg = option('target') ?? 'staging';
|
|
73
|
+
if (!['staging', 'local', 'preview', 'both', 'all'].includes(targetArg)) throw new Error(`--target is staging, local, preview, both or all, not ${targetArg}`);
|
|
74
|
+
/** AU6's phone audio MB per shard (engine 42f0a8f1's cook report over the pinned products); an Open Plot is 1.22 to 1.49. */
|
|
75
|
+
const AU6_AUDIO_MB = /** @type {Record<string, number>} */ ({ 'driftwood-isle': 3.62, 'pine-hollow': 4.73, 'nalati-grasslands': 5.47, 'nine-dragon-stack': 2.60, 'open-plot-*': 1.22 });
|
|
76
|
+
/** Deck card names (scripts/offline-proof-rules.mjs DECK_SHARDS). */
|
|
77
|
+
const CARDS = /** @type {Record<string, string>} */ ({ 'driftwood-isle': 'Driftwood Isle', 'nalati-grasslands': 'Nalati Grasslands', 'pine-hollow': 'Pine Hollow', 'nine-dragon-stack': 'Nine Dragon Stack' });
|
|
78
|
+
/**
|
|
79
|
+
* The Open Plots a `cross` entry walks into: the deck neighbour it starts in, the cell's instance in the pinned catalogue
|
|
80
|
+
* (test/pins/catalogue.json grid.cells), the plot's music id (its `audio.music.id`), and the walk (world frame, metres; the
|
|
81
|
+
* last legs are inside the plot). opus-sa34b's and opus-rel16's Pine → (0, 2) walk.
|
|
82
|
+
* @type {Record<string, { from: string, instance: string, musicId: string, legs: [number, number][] }>}
|
|
83
|
+
*/
|
|
84
|
+
const CROSS_IN = {
|
|
85
|
+
'open-plot-saltwind-lighthouse': { from: 'pine-hollow', instance: 'open-plot-2-4', musicId: 'saltwind-lighthouse',
|
|
86
|
+
legs: [[0, 761], [0, 852], [0, 924], [-149, 975], [-150, 1022], [-0.5, 1300]] },
|
|
87
|
+
};
|
|
88
|
+
const DEFAULT_ENTRIES = 'driftwood-isle:grid,driftwood-isle:client,nalati-grasslands:grid,nine-dragon-stack:grid,pine-hollow:grid,open-plot-thin-ice:client';
|
|
89
|
+
/** @typedef {'grid' | 'client' | 'cross'} Route */
|
|
90
|
+
/** @type {{ slug: string, route: Route }[]} */
|
|
91
|
+
const entries = (option('entry') ?? DEFAULT_ENTRIES).split(',').map(spec => {
|
|
92
|
+
const [slug = '', route = 'grid'] = spec.split(':');
|
|
93
|
+
if (route !== 'grid' && route !== 'client' && route !== 'cross') throw new Error(`route is grid, client or cross, not ${route}`);
|
|
94
|
+
if (route === 'grid' && CARDS[slug] === undefined) throw new Error(`${slug} has no deck card: use ${slug}:client`);
|
|
95
|
+
if (route === 'cross' && CROSS_IN[slug] === undefined) throw new Error(`${slug} has no cross-in walk (CROSS_IN: ${Object.keys(CROSS_IN).join(', ')})`);
|
|
96
|
+
return { slug, route: route === 'grid' ? 'grid' : route === 'cross' ? 'cross' : 'client' };
|
|
97
|
+
});
|
|
98
|
+
const jobs = Number(option('jobs') ?? 2);
|
|
99
|
+
if (!Number.isInteger(jobs) || jobs < 1) throw new Error(`--jobs is a whole number from 1, not ${String(option('jobs'))}`);
|
|
100
|
+
const out = resolvePath(ROOT, option('out') ?? join('tmp', 'audio-download-proof', new Date().toISOString().replaceAll(/[:.]/gu, '-')));
|
|
101
|
+
mkdirSync(out, { recursive: true });
|
|
102
|
+
const STAGING = CHANNELS.staging;
|
|
103
|
+
const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1';
|
|
104
|
+
const AUDIO = /\/assets\/(?:music|sfx)\/|\/blobs\/audio\//u;
|
|
105
|
+
const SPAWN = /\/assets\/spawn\/([^/]+)-(grid|client)-(phone|desktop)-[0-9a-f]+\.json$/u;
|
|
106
|
+
/** -60 dBFS: a bus whose peak stays under it in the window is silent. */
|
|
107
|
+
const AUDIBLE_PEAK = 0.001;
|
|
108
|
+
const PLAY_WINDOW_MS = 10_000;
|
|
109
|
+
/** A crossing is watched this long (its verdict is on the first PLAY_WINDOW_MS). */
|
|
110
|
+
const CROSS_WATCH_MS = 30_000;
|
|
111
|
+
/** A deep link takes the bench path `&skipintro`, except preview's deep link to a shard with a deck card. Without the flag a
|
|
112
|
+
* world build's deep link stops at the title, and a solo page loads the shard and then lands on the title, where the proof
|
|
113
|
+
* goes on by Shard select (checked 2026-11-13); an Open Plot has no card to go on by.
|
|
114
|
+
* @param {string} target @param {Route} route @param {string} slug */
|
|
115
|
+
const benchEntry = (target, route, slug) => route === 'client' && (target !== 'preview' || CARDS[slug] === undefined);
|
|
116
|
+
/** The deck shard a visit picks: a `cross` entry starts in its neighbour. @param {string} slug @param {Route} route */
|
|
117
|
+
const deckShard = (slug, route) => route === 'cross' ? CROSS_IN[slug]?.from ?? slug : slug;
|
|
118
|
+
/** @param {number} ms */
|
|
119
|
+
const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
|
|
120
|
+
/** @template T @param {Promise<T>} work @param {number} ms @returns {Promise<T | undefined>} */
|
|
121
|
+
const bounded = (work, ms) => Promise.race([work.catch(() => undefined), sleep(ms).then(() => undefined)]);
|
|
122
|
+
const t0 = Date.now();
|
|
123
|
+
/** @param {...unknown} parts */
|
|
124
|
+
const log = (...parts) => { console.log(`[${((Date.now() - t0) / 1000).toFixed(0).padStart(4)} s]`, ...parts); };
|
|
125
|
+
|
|
126
|
+
// ---- the link: a forward proxy, optionally shaped ---------------------------------------------------------------------
|
|
127
|
+
/**
|
|
128
|
+
* One shaped direction: a serial link at `rate` bytes/s, each piece delivered `delay` ms after it leaves the link. One FIFO
|
|
129
|
+
* drained by one timer, so pieces (and the empty end markers behind them) land in the order they were sent.
|
|
130
|
+
* @param {number} rate @param {number} delay
|
|
131
|
+
*/
|
|
132
|
+
function lane(rate, delay) {
|
|
133
|
+
let freeAt = 0;
|
|
134
|
+
/** @type {{ at: number, piece: Buffer, deliver: (piece: Buffer) => void }[]} */
|
|
135
|
+
const queue = [];
|
|
136
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
137
|
+
let timer;
|
|
138
|
+
const drain = () => {
|
|
139
|
+
timer = undefined;
|
|
140
|
+
while (queue.length > 0 && (queue[0]?.at ?? 0) <= Date.now()) {
|
|
141
|
+
const head = queue.shift();
|
|
142
|
+
try { head?.deliver(head.piece); } catch { /* a socket that went away */ }
|
|
143
|
+
}
|
|
144
|
+
if (queue.length > 0) timer = setTimeout(drain, Math.max(0, (queue[0]?.at ?? 0) - Date.now()));
|
|
145
|
+
};
|
|
146
|
+
/** @param {Buffer} chunk @param {(piece: Buffer) => void} deliver */
|
|
147
|
+
const send = (chunk, deliver) => {
|
|
148
|
+
if (rate === 0) { deliver(chunk); return; }
|
|
149
|
+
const now = Date.now();
|
|
150
|
+
// an empty chunk is a marker (an end, a request's go): it lands right after everything already on the link
|
|
151
|
+
if (chunk.length === 0) queue.push({ at: Math.max(now, freeAt) + delay, piece: chunk, deliver });
|
|
152
|
+
for (let at = 0; at < chunk.length; at += 16_384) {
|
|
153
|
+
const piece = chunk.subarray(at, at + 16_384);
|
|
154
|
+
freeAt = Math.max(now, freeAt) + piece.length / rate * 1000;
|
|
155
|
+
queue.push({ at: freeAt + delay, piece, deliver });
|
|
156
|
+
}
|
|
157
|
+
timer ??= setTimeout(drain, Math.max(0, (queue[0]?.at ?? 0) - Date.now()));
|
|
158
|
+
};
|
|
159
|
+
return Object.assign(send, { stop: () => { if (timer !== undefined) clearTimeout(timer); queue.length = 0; } });
|
|
160
|
+
}
|
|
161
|
+
/** A forward proxy for one browser; `slow` shapes it (each direction 0.7 Mbit/s, 150 ms one way). Logs every http URL and https
|
|
162
|
+
* host it carries, with the time. @param {boolean} slow */
|
|
163
|
+
async function startLink(slow) {
|
|
164
|
+
const down = lane(slow ? 87_500 : 0, slow ? 150 : 0), up = lane(slow ? 87_500 : 0, slow ? 150 : 0);
|
|
165
|
+
/** @type {{ t: number, url: string }[]} */
|
|
166
|
+
const seen = [];
|
|
167
|
+
/** @type {Set<import('node:stream').Duplex>} */
|
|
168
|
+
const sockets = new Set();
|
|
169
|
+
let closed = false;
|
|
170
|
+
const server = createServer((request, response) => {
|
|
171
|
+
seen.push({ t: Date.now(), url: request.url ?? '' });
|
|
172
|
+
/** @type {Buffer[]} */
|
|
173
|
+
const body = [];
|
|
174
|
+
request.on('data', chunk => { body.push(Buffer.from(chunk)); });
|
|
175
|
+
request.on('end', () => {
|
|
176
|
+
// the request line and headers (about 300 bytes) and its body cross the link before it reaches the server
|
|
177
|
+
up(Buffer.concat([Buffer.alloc(300), ...body]), () => undefined);
|
|
178
|
+
up(Buffer.alloc(0), () => {
|
|
179
|
+
if (closed || response.destroyed) return;
|
|
180
|
+
let target;
|
|
181
|
+
try { target = new URL(request.url ?? ''); } catch { response.writeHead(400).end(); return; }
|
|
182
|
+
const headers = { ...request.headers };
|
|
183
|
+
Reflect.deleteProperty(headers, 'proxy-connection');
|
|
184
|
+
const upstream = httpRequest({ host: target.hostname, port: target.port || 80, path: `${target.pathname}${target.search}`, method: request.method, headers }, answer => {
|
|
185
|
+
let started = false;
|
|
186
|
+
const begin = () => { if (!started && !response.destroyed) { started = true; response.writeHead(answer.statusCode ?? 502, answer.headers); } };
|
|
187
|
+
down(Buffer.alloc(400), () => { begin(); });
|
|
188
|
+
answer.on('data', chunk => { down(chunk, piece => { begin(); if (!response.destroyed) response.write(piece); }); });
|
|
189
|
+
answer.on('end', () => { down(Buffer.alloc(0), () => { begin(); if (!response.destroyed) response.end(); }); });
|
|
190
|
+
answer.on('error', () => { down(Buffer.alloc(0), () => { response.destroy(); }); });
|
|
191
|
+
});
|
|
192
|
+
// a request the browser dropped stops using the link; a failure after the headers is a cut body, never a short one
|
|
193
|
+
response.on('close', () => { if (!response.writableFinished) upstream.destroy(); });
|
|
194
|
+
upstream.on('error', () => { if (!response.headersSent) response.writeHead(502).end(); else response.destroy(); });
|
|
195
|
+
upstream.end(Buffer.concat(body));
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
server.on('connect', (request, client, head) => {
|
|
200
|
+
seen.push({ t: Date.now(), url: `connect://${request.url ?? ''}` });
|
|
201
|
+
const [host = '', port = '443'] = (request.url ?? '').split(':');
|
|
202
|
+
const upstream = netConnect({ port: Number(port), host, allowHalfOpen: true }, () => {
|
|
203
|
+
down(Buffer.from('HTTP/1.1 200 Connection Established\r\n\r\n'), piece => { client.write(piece); });
|
|
204
|
+
if (head.length > 0) up(head, piece => { if (!upstream.destroyed) upstream.write(piece); });
|
|
205
|
+
upstream.on('data', chunk => { down(chunk, piece => { if (!client.destroyed) client.write(piece); }); });
|
|
206
|
+
client.on('data', chunk => { up(chunk, piece => { if (!upstream.destroyed) upstream.write(piece); }); });
|
|
207
|
+
});
|
|
208
|
+
sockets.add(client); sockets.add(upstream);
|
|
209
|
+
upstream.on('close', () => { sockets.delete(upstream); });
|
|
210
|
+
// the server's end or failure lands after the bytes still on the down link; the browser's goes at once
|
|
211
|
+
upstream.on('end', () => { down(Buffer.alloc(0), () => { if (!client.destroyed) client.end(); }); });
|
|
212
|
+
upstream.on('error', () => { down(Buffer.alloc(0), () => { client.destroy(); }); });
|
|
213
|
+
client.on('end', () => { up(Buffer.alloc(0), () => { if (!upstream.destroyed) upstream.end(); }); });
|
|
214
|
+
client.on('error', () => { client.destroy(); upstream.destroy(); });
|
|
215
|
+
});
|
|
216
|
+
server.on('connection', socket => { sockets.add(socket); socket.on('close', () => { sockets.delete(socket); }); });
|
|
217
|
+
await new Promise(resolve => { server.listen(0, '127.0.0.1', () => { resolve(null); }); });
|
|
218
|
+
const address = server.address();
|
|
219
|
+
if (address === null || typeof address === 'string') throw new Error('audio-download-proof: the link has no port');
|
|
220
|
+
return { port: address.port, seen, close: () => { closed = true; down.stop(); up.stop(); for (const socket of sockets) socket.destroy(); server.close(); } };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---- the local staging-like origin ------------------------------------------------------------------------------------
|
|
224
|
+
let builtPort = '';
|
|
225
|
+
/** @type {import('node:http').Server | undefined} */
|
|
226
|
+
let stamper;
|
|
227
|
+
/** @type {string | undefined} */
|
|
228
|
+
let builtBase;
|
|
229
|
+
/** The served build: `--base`, else this working tree built once with scripts/serve-build.sh. */
|
|
230
|
+
function servedBuild() {
|
|
231
|
+
let base = option('base') ?? builtBase;
|
|
232
|
+
if (base === undefined) {
|
|
233
|
+
log('building this working tree (scripts/serve-build.sh)');
|
|
234
|
+
const built = spawnSync('bash', ['scripts/serve-build.sh', '--name', 'audio-proof', '--hours', '2', '--shard', [...new Set(entries.map(entry => entry.slug))].join(',')],
|
|
235
|
+
{ cwd: ROOT, encoding: 'utf8', env: { ...process.env, SERVE_OWNER: process.env.SERVE_OWNER ?? 'audio-download-proof' }, stdio: ['ignore', 'pipe', 'inherit'] });
|
|
236
|
+
const url = /http:\/\/127\.0\.0\.1:(\d+)\//u.exec(built.stdout ?? '');
|
|
237
|
+
if (built.status !== 0 || url === null) throw new Error('audio-download-proof: the build or its server failed (scripts/serve-build.sh)');
|
|
238
|
+
base = url[0].slice(0, -1); builtPort = url[1] ?? ''; builtBase = base;
|
|
239
|
+
}
|
|
240
|
+
return base;
|
|
241
|
+
}
|
|
242
|
+
/** The served build as built: no world stamp, the in-page solo server (preview.wildshard.io's shape). */
|
|
243
|
+
function previewOrigin() { return new URL(servedBuild()).origin; }
|
|
244
|
+
/** The served build's origin, behind a stamper that gives every document staging's world (offline-proof.mjs's stamp). */
|
|
245
|
+
async function localOrigin() {
|
|
246
|
+
const upstream = new URL(servedBuild());
|
|
247
|
+
const release = fetch(STAGING.release, { cache: 'no-store' }).then(answer => { if (!answer.ok) throw new Error(`staging release ${String(answer.status)}`); return answer.text(); });
|
|
248
|
+
release.catch(() => undefined); // a failed read fails the page's release request, never the whole run
|
|
249
|
+
const RELEASE_PATH = '/__audio-proof/staging.json';
|
|
250
|
+
let stamp = '';
|
|
251
|
+
stamper = createServer((request, response) => {
|
|
252
|
+
void (async () => {
|
|
253
|
+
try {
|
|
254
|
+
if (request.url === RELEASE_PATH) { response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'access-control-allow-origin': '*' }).end(await release); return; }
|
|
255
|
+
/** @type {Record<string, string>} */
|
|
256
|
+
const headers = {};
|
|
257
|
+
for (const [name, value] of Object.entries(request.headers)) if (typeof value === 'string' && name !== 'host' && name !== 'connection') headers[name] = value;
|
|
258
|
+
/** @type {Buffer[]} */
|
|
259
|
+
const parts = [];
|
|
260
|
+
for await (const part of request) parts.push(Buffer.from(/** @type {Uint8Array} */ (part)));
|
|
261
|
+
const sending = request.method === 'GET' || request.method === 'HEAD' ? {} : { body: Buffer.concat(parts) };
|
|
262
|
+
const answer = await fetch(new URL(request.url ?? '/', upstream), { method: request.method, headers, redirect: 'manual', ...sending });
|
|
263
|
+
const body = Buffer.from(await answer.arrayBuffer());
|
|
264
|
+
/** @type {Record<string, string>} */
|
|
265
|
+
const sent = {};
|
|
266
|
+
answer.headers.forEach((value, name) => { if (!['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'content-encoding'].includes(name)) sent[name] = value; });
|
|
267
|
+
const html = (answer.headers.get('content-type') ?? '').includes('text/html');
|
|
268
|
+
if (html || new URL(request.url ?? '/', upstream).pathname.startsWith('/sw-core/')) {
|
|
269
|
+
const text = body.toString('utf8');
|
|
270
|
+
if (!text.includes('globalThis.__WS_BUILD_ID__=')) { response.writeHead(500).end('audio-download-proof: a document without the build stamp'); return; }
|
|
271
|
+
const stamped = Buffer.from(text.replace('globalThis.__WS_BUILD_ID__=', `${html ? stamp : JSON.stringify(stamp).slice(1, -1)}globalThis.__WS_BUILD_ID__=`));
|
|
272
|
+
for (const name of ['etag', 'last-modified']) Reflect.deleteProperty(sent, name);
|
|
273
|
+
response.writeHead(answer.status, { ...sent, 'content-length': String(stamped.length) }).end(stamped);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
response.writeHead(answer.status, { ...sent, 'content-length': String(body.length) }).end(body);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (!response.headersSent) response.writeHead(502);
|
|
279
|
+
response.end(String(error));
|
|
280
|
+
}
|
|
281
|
+
})();
|
|
282
|
+
});
|
|
283
|
+
// a fixed port per build port: the origin keys the profile's worker and caches
|
|
284
|
+
const port = 7100 + Number(upstream.port || '80') % 1000;
|
|
285
|
+
await new Promise((resolve, reject) => { stamper?.once('error', reject); stamper?.listen(port, '127.0.0.1', () => { resolve(null); }); });
|
|
286
|
+
const origin = `http://127.0.0.1:${String(port)}`;
|
|
287
|
+
stamp = `globalThis.__WS_WORLD__=${JSON.stringify({ release: `${origin}${RELEASE_PATH}`, key: RELEASE_PUBLIC_KEY })};`;
|
|
288
|
+
return origin;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// ---- the page side ----------------------------------------------------------------------------------------------------
|
|
292
|
+
/** Init script: an analyser beside the mixer's buses (see the header), sampled every 100 ms into `__au14.samples`. */
|
|
293
|
+
function tapBuses() {
|
|
294
|
+
const P = AudioNode.prototype;
|
|
295
|
+
/** @type {(this: AudioNode, ...args: unknown[]) => unknown} */
|
|
296
|
+
const plain = /** @type {(this: AudioNode, ...args: unknown[]) => unknown} */ (/** @type {unknown} */ (Reflect.get(P, 'connect')));
|
|
297
|
+
/** @type {WeakMap<AudioNode, Set<AudioNode>>} */
|
|
298
|
+
const outs = new WeakMap();
|
|
299
|
+
/** @type {WeakMap<AudioNode, string>} */
|
|
300
|
+
const role = new WeakMap();
|
|
301
|
+
/** @type {WeakMap<AudioNode, number>} */
|
|
302
|
+
const inputs = new WeakMap();
|
|
303
|
+
/** @type {WeakMap<BaseAudioContext, GainNode>} */
|
|
304
|
+
const sinks = new WeakMap();
|
|
305
|
+
/** @type {{ kind: string, node: AnalyserNode, data: Float32Array }[]} */
|
|
306
|
+
const taps = [];
|
|
307
|
+
/** @type {{ t: number, peaks: Record<string, number> }[]} */
|
|
308
|
+
const samples = [];
|
|
309
|
+
const state = { samples, taps: /** @type {string[]} */ ([]), contexts: 0 };
|
|
310
|
+
Reflect.set(globalThis, '__au14', state);
|
|
311
|
+
const outsOf = (/** @type {AudioNode} */ node) => [...outs.get(node) ?? []];
|
|
312
|
+
const isMaster = (/** @type {AudioNode} */ node) => node instanceof GainNode && outsOf(node).some(low => low instanceof BiquadFilterNode && outsOf(low).some(comp => comp instanceof DynamicsCompressorNode));
|
|
313
|
+
const tap = (/** @type {AudioNode} */ node, /** @type {string} */ kind) => {
|
|
314
|
+
if (role.has(node) || !(node.context instanceof AudioContext)) return;
|
|
315
|
+
role.set(node, kind);
|
|
316
|
+
const context = node.context;
|
|
317
|
+
let sink = sinks.get(context);
|
|
318
|
+
if (sink === undefined) { sink = context.createGain(); sink.gain.value = 0; plain.call(sink, context.destination); sinks.set(context, sink); state.contexts++; }
|
|
319
|
+
// 32768 frames (about 680 ms at 48 kHz) per 100 ms read: no short footstep falls between two reads
|
|
320
|
+
const analyser = context.createAnalyser(); analyser.fftSize = 32_768;
|
|
321
|
+
plain.call(node, analyser); plain.call(analyser, sink);
|
|
322
|
+
taps.push({ kind, node: analyser, data: new Float32Array(analyser.fftSize) }); state.taps.push(kind);
|
|
323
|
+
};
|
|
324
|
+
P.connect = /** @type {typeof P.connect} */ (/** @this {AudioNode} @param {AudioNode | AudioParam} destination @param {...number} rest */ function connect(destination, ...rest) {
|
|
325
|
+
const result = Reflect.apply(plain, this, [destination, ...rest]);
|
|
326
|
+
try {
|
|
327
|
+
if (destination instanceof AudioNode) {
|
|
328
|
+
const set = outs.get(this) ?? new Set(); set.add(destination); outs.set(this, set);
|
|
329
|
+
if (destination === this.context.destination && this instanceof DynamicsCompressorNode) tap(this, 'out');
|
|
330
|
+
else if (isMaster(destination)) {
|
|
331
|
+
const n = inputs.get(destination) ?? 0; inputs.set(destination, n + 1);
|
|
332
|
+
if (!role.has(this)) { if (n === 0) role.set(this, 'world'); else tap(this, 'music'); }
|
|
333
|
+
} else if (role.get(destination) === 'world') {
|
|
334
|
+
const n = inputs.get(destination) ?? 0; inputs.set(destination, n + 1);
|
|
335
|
+
if (n === 0) tap(this, 'sfx'); else if (n === 1) tap(this, 'ambience');
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
} catch { /* the proof's tap never breaks the game */ }
|
|
339
|
+
return result;
|
|
340
|
+
});
|
|
341
|
+
setInterval(() => {
|
|
342
|
+
/** @type {Record<string, number>} */
|
|
343
|
+
const peaks = {};
|
|
344
|
+
for (const one of taps) {
|
|
345
|
+
one.node.getFloatTimeDomainData(/** @type {Float32Array<ArrayBuffer>} */ (one.data));
|
|
346
|
+
let peak = 0; for (const value of one.data) peak = Math.max(peak, Math.abs(value));
|
|
347
|
+
peaks[one.kind] = Math.max(peaks[one.kind] ?? 0, peak);
|
|
348
|
+
}
|
|
349
|
+
samples.push({ t: performance.now(), peaks });
|
|
350
|
+
if (samples.length > 3000) samples.shift();
|
|
351
|
+
}, 100);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Init script: every change of the card's phase or step, stamped in the page as it happens (a MutationObserver, so a busy
|
|
355
|
+
* main thread can't make it late the way a poll is), sent to the proof by its `__au14phase` binding. */
|
|
356
|
+
function logPhases() {
|
|
357
|
+
let last = '';
|
|
358
|
+
const read = () => {
|
|
359
|
+
const load = document.querySelector('.ws-load');
|
|
360
|
+
const card = load instanceof HTMLElement && !load.classList.contains('hide') && !load.hidden;
|
|
361
|
+
const on = load?.querySelector('.ws-load-phase[data-state="on"]');
|
|
362
|
+
const phase = card ? (on instanceof HTMLElement ? on.dataset.phase ?? 'none' : 'none') : 'page';
|
|
363
|
+
const step = load instanceof HTMLElement ? load.dataset.step ?? '' : '';
|
|
364
|
+
if (`${phase}/${step}` === last) return;
|
|
365
|
+
last = `${phase}/${step}`;
|
|
366
|
+
const send = Reflect.get(globalThis, '__au14phase');
|
|
367
|
+
if (typeof send === 'function') void send({ t: Date.now(), phase, step });
|
|
368
|
+
};
|
|
369
|
+
new MutationObserver(read).observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ['data-state', 'data-step', 'data-phase', 'class', 'hidden'] });
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** The device's last-end records go before each document, so a deck entry lands on the title and not on a resume. */
|
|
373
|
+
function clearLastEnd() {
|
|
374
|
+
try {
|
|
375
|
+
const name = 'wildshard.save.v2@1.device', doc = JSON.parse(localStorage.getItem(name) ?? '{"keys":{}}');
|
|
376
|
+
for (const key of Object.keys(doc.keys ?? {})) if (key.startsWith('life.')) Reflect.deleteProperty(doc.keys, key);
|
|
377
|
+
localStorage.setItem(name, JSON.stringify(doc));
|
|
378
|
+
} catch { /* opaque origin */ }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The screen: the card's phase and step, the title, the player (offline-proof.mjs's reading). */
|
|
382
|
+
const readScreen = () => {
|
|
383
|
+
const load = document.querySelector('.ws-load');
|
|
384
|
+
const card = load instanceof HTMLElement && !load.classList.contains('hide') && !load.hidden && getComputedStyle(load).display !== 'none';
|
|
385
|
+
const on = load?.querySelector('.ws-load-phase[data-state="on"]');
|
|
386
|
+
const main = document.querySelector('.ws-main');
|
|
387
|
+
const title = main instanceof HTMLElement && main.offsetParent !== null;
|
|
388
|
+
const world = /** @type {{ __wildshard?: { world?: { player?: unknown } } }} */ (/** @type {unknown} */ (window)).__wildshard?.world;
|
|
389
|
+
return {
|
|
390
|
+
// in play: a player, no card, and past ENTER WORLD (the HUD drops its `intro` class then)
|
|
391
|
+
card, title: title && !card, intro: document.getElementById('hud')?.classList.contains('intro') === true,
|
|
392
|
+
player: world?.player !== undefined && world.player !== null && !card && document.getElementById('hud')?.classList.contains('intro') !== true,
|
|
393
|
+
phase: card ? (on instanceof HTMLElement ? on.dataset.phase ?? 'none' : 'none') : title ? 'title' : 'page',
|
|
394
|
+
step: load instanceof HTMLElement ? load.dataset.step ?? '' : '',
|
|
395
|
+
error: (document.querySelector('.ws-load-error')?.textContent ?? '').replaceAll(/\s+/gu, ' ').slice(0, 300),
|
|
396
|
+
// oxlint-disable-next-line unicorn/prefer-dom-node-text-content -- the text a player sees
|
|
397
|
+
text: (load instanceof HTMLElement ? load.innerText : '').replaceAll(/\s+/gu, ' ').slice(0, 600), now: performance.now(),
|
|
398
|
+
};
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
/** Shard select, the shard's card, ENTER WORLD. @param {import('playwright').Page} page @param {string} slug @param {string} mode */
|
|
402
|
+
async function pickFromDeck(page, slug, mode) {
|
|
403
|
+
const select = page.locator('.ws-main-select');
|
|
404
|
+
await select.waitFor({ state: 'visible', timeout: mode === 'slow' ? 180_000 : 60_000 });
|
|
405
|
+
let opened = false;
|
|
406
|
+
for (let i = 0; i < 8 && !opened; i++) {
|
|
407
|
+
if (await page.locator('#wsdrop').isVisible().catch(() => false)) await page.locator('#wsdrop button.dismiss').click({ timeout: 3000 }).catch(() => undefined);
|
|
408
|
+
opened = await select.click({ timeout: 4000 }).then(() => true, () => false);
|
|
409
|
+
}
|
|
410
|
+
if (!opened) throw new Error('could not open Shard select');
|
|
411
|
+
await page.locator('.ws-menu-card b').first().waitFor({ state: 'attached', timeout: 30_000 });
|
|
412
|
+
const names = await page.locator('.ws-menu-card b').allTextContents();
|
|
413
|
+
const index = names.findIndex(name => name.trim().toLowerCase() === (CARDS[slug] ?? '').toLowerCase());
|
|
414
|
+
if (index === -1) throw new Error(`no deck card "${CARDS[slug] ?? ''}" (deck: ${names.join(', ')})`);
|
|
415
|
+
await page.locator(`.ws-menu-dots i[data-i="${String(index)}"]`).click();
|
|
416
|
+
await page.locator('.ws-menu-play').click();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** One reading of the grid and the music: the cell the feet stand in (and its slug), the cell whose runtime plays (the live
|
|
420
|
+
* grid's `current`) and whether its gameplay is ready, the music's score and slot. */
|
|
421
|
+
const readCrossing = () => {
|
|
422
|
+
const handle = /** @type {{ shard?: { grid?: { state(): { inside?: string | null, feet?: { x: number, z: number }, cells?: { instance: string, slug: string }[],
|
|
423
|
+
live?: { live?: { current?: string | null, gameplayReady?: boolean, issues?: Record<string, unknown> } } | null } } },
|
|
424
|
+
world?: { player?: { yaw: number, position: { y: number } }, music?: { scoreId?: string, isPlaying?: boolean, stems?: { slot?: string, source?: string } } } } | undefined} */ (Reflect.get(globalThis, '__wildshard'));
|
|
425
|
+
const grid = handle?.shard?.grid?.state(), music = handle?.world?.music;
|
|
426
|
+
const inside = grid?.inside ?? null;
|
|
427
|
+
return { t: performance.now(), x: grid?.feet?.x ?? Number.NaN, z: grid?.feet?.z ?? Number.NaN, inside,
|
|
428
|
+
slug: grid?.cells?.find(cell => cell.instance === inside)?.slug ?? null, score: music?.scoreId ?? null, slot: music?.stems?.slot ?? null,
|
|
429
|
+
source: music?.stems?.source ?? null, playing: music?.isPlaying ?? null, current: grid?.live?.live?.current ?? null,
|
|
430
|
+
ready: grid?.live?.live?.gameplayReady ?? null, issues: JSON.stringify(grid?.live?.live?.issues ?? {}).slice(0, 300) };
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Walk from the neighbour's spawn across the road into the plot (CROSS_IN's legs: sprint, the yaw set toward each point, a jump
|
|
435
|
+
* when stuck), then on inside it until 30 s after the crossing (the verdict is on the first 10 s; the rest says when, or
|
|
436
|
+
* whether, a late score starts). `at` is the page clock's ms when the feet first stood in the
|
|
437
|
+
* plot's cell, `ts` the proof's, `leftTs` when the feet first left the neighbour's cell; `track` holds every reading at which the cell or the music's score or slot changed.
|
|
438
|
+
* @param {import('playwright').Page} page @param {(typeof CROSS_IN)[string]} plan
|
|
439
|
+
*/
|
|
440
|
+
async function crossIn(page, plan) {
|
|
441
|
+
/** @type {ReturnType<typeof readCrossing>[]} */
|
|
442
|
+
const track = [];
|
|
443
|
+
/** @type {number | undefined} */
|
|
444
|
+
let at;
|
|
445
|
+
/** @type {number | undefined} */
|
|
446
|
+
let ts;
|
|
447
|
+
/** @type {number | undefined} */
|
|
448
|
+
let leftTs;
|
|
449
|
+
/** @type {string | null | undefined} the cell the walk starts in */
|
|
450
|
+
let from;
|
|
451
|
+
let last = '';
|
|
452
|
+
const read = async () => {
|
|
453
|
+
const now = await bounded(page.evaluate(readCrossing), 5000);
|
|
454
|
+
if (now === undefined) return undefined;
|
|
455
|
+
const key = JSON.stringify([now.inside, now.current, now.ready, now.issues, now.score, now.slot, now.source, now.playing]);
|
|
456
|
+
if (key !== last) { last = key; track.push(now); }
|
|
457
|
+
// the start cell is the first one the feet stand in (a resumed visit can start on the road)
|
|
458
|
+
if (from === undefined || from === null) from = now.inside;
|
|
459
|
+
else if (leftTs === undefined && now.inside !== from) leftTs = Date.now();
|
|
460
|
+
// a visit that resumes inside the plot never crossed: it stays `no-cross`
|
|
461
|
+
if (at === undefined && from !== plan.instance && now.inside === plan.instance) { at = now.t; ts = Date.now(); }
|
|
462
|
+
return now;
|
|
463
|
+
};
|
|
464
|
+
// one deadline for the whole walk (each leg also stops at 120 s)
|
|
465
|
+
const startTs = Date.now(), walkEnds = startTs + 300_000;
|
|
466
|
+
await page.keyboard.down('ShiftLeft');
|
|
467
|
+
try {
|
|
468
|
+
for (const [x, z] of plan.legs) {
|
|
469
|
+
if (ts !== undefined && Date.now() - ts > CROSS_WATCH_MS) break;
|
|
470
|
+
await page.keyboard.down('KeyW');
|
|
471
|
+
let near = Number.POSITIVE_INFINITY, stuck = 0, before = await read();
|
|
472
|
+
for (const ends = Math.min(Date.now() + 120_000, walkEnds); Date.now() < ends && near > 4; await sleep(250)) {
|
|
473
|
+
const now = await read();
|
|
474
|
+
if (now === undefined) continue;
|
|
475
|
+
near = Math.hypot(now.x - x, now.z - z);
|
|
476
|
+
await bounded(page.evaluate(yaw => { const player = /** @type {{ world?: { player?: { yaw: number } } } | undefined} */ (Reflect.get(globalThis, '__wildshard'))?.world?.player; if (player !== undefined) player.yaw = yaw; }, Math.atan2(now.x - x, now.z - z)), 5000);
|
|
477
|
+
if (before !== undefined && Math.hypot(now.x - before.x, now.z - before.z) >= 0.15) stuck = 0; else if (++stuck % 6 === 0) await page.keyboard.press('Space');
|
|
478
|
+
before = now;
|
|
479
|
+
if (ts !== undefined && Date.now() - ts > CROSS_WATCH_MS) break;
|
|
480
|
+
}
|
|
481
|
+
await page.keyboard.up('KeyW');
|
|
482
|
+
}
|
|
483
|
+
// the legs ran out before 10 s inside: keep walking and jumping in place
|
|
484
|
+
for (const ends = ts === undefined ? 0 : ts + CROSS_WATCH_MS; Date.now() <= ends; await sleep(400)) { await page.keyboard.press('Space'); await read(); }
|
|
485
|
+
} finally {
|
|
486
|
+
await page.keyboard.up('KeyW').catch(() => undefined); await page.keyboard.up('ShiftLeft').catch(() => undefined);
|
|
487
|
+
}
|
|
488
|
+
await read();
|
|
489
|
+
return { at, ts, leftTs, startTs, track };
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* One visit in one browser.
|
|
494
|
+
* @param {{ origin: string, target: string, profile: string, slug: string, route: Route, mode: 'warm' | 'slow', label: string }} run
|
|
495
|
+
*/
|
|
496
|
+
async function visit(run) {
|
|
497
|
+
const { profile } = run;
|
|
498
|
+
const link = await startLink(run.mode === 'slow');
|
|
499
|
+
/** @type {import('playwright').BrowserContext | undefined} */
|
|
500
|
+
let context;
|
|
501
|
+
try {
|
|
502
|
+
// `<-loopback>`: loopback goes through the link too (checked: the local origin's http reads reach the proxy's log)
|
|
503
|
+
context = await webkit.launchPersistentContext(profile, {
|
|
504
|
+
headless: true, viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, hasTouch: true, isMobile: true, userAgent: IPHONE,
|
|
505
|
+
serviceWorkers: 'allow', proxy: { server: `http://127.0.0.1:${String(link.port)}`, bypass: '<-loopback>' },
|
|
506
|
+
});
|
|
507
|
+
return await drive(run, context, link);
|
|
508
|
+
} finally {
|
|
509
|
+
await bounded(context?.close() ?? Promise.resolve(), 30_000);
|
|
510
|
+
link.close();
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* @param {Parameters<typeof visit>[0]} run @param {import('playwright').BrowserContext} context
|
|
516
|
+
* @param {Awaited<ReturnType<typeof startLink>>} link
|
|
517
|
+
*/
|
|
518
|
+
async function drive(run, context, link) {
|
|
519
|
+
const { origin, slug, route, mode, label } = run;
|
|
520
|
+
let phase = 'title', step = '';
|
|
521
|
+
const started = Date.now(), at = () => Date.now() - started;
|
|
522
|
+
/** @type {{ t: number, ts: number, url: string, phase: string, step: string, fromSW: boolean | null, status: number }[]} */
|
|
523
|
+
const rows = [];
|
|
524
|
+
/** @type {{ t: number, phase: string, step: string }[]} the page's own phase log (absolute ms) */
|
|
525
|
+
const pagePhases = [];
|
|
526
|
+
/** @type {string[]} */
|
|
527
|
+
const consoleLines = [];
|
|
528
|
+
/** @type {{ t: number, phase: string, step: string }[]} */
|
|
529
|
+
const phases = [];
|
|
530
|
+
let outcome = 'stalled', downloadCardMB = 0, playAt = 0, proofError = '';
|
|
531
|
+
/** @type {Record<string, number>} */
|
|
532
|
+
let windowPeaks = {};
|
|
533
|
+
/** @type {Record<string, number>} */
|
|
534
|
+
let firstHeard = {};
|
|
535
|
+
let taps = /** @type {string[]} */ ([]);
|
|
536
|
+
/** @type {Awaited<ReturnType<typeof crossIn>> | null} */
|
|
537
|
+
let crossing = null;
|
|
538
|
+
/** @type {Record<string, number>} on a crossing: ms after the plot's score took over that each bus was first over the floor */
|
|
539
|
+
let afterScore = {};
|
|
540
|
+
{
|
|
541
|
+
await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
|
|
542
|
+
await saveFixture(context, { scope: 'device', key: 'nameAsked', data: true });
|
|
543
|
+
await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
|
|
544
|
+
await context.exposeBinding('__au14phase', (_source, /** @type {{ t: number, phase: string, step: string }} */ row) => { pagePhases.push(row); });
|
|
545
|
+
await context.addInitScript(clearLastEnd);
|
|
546
|
+
await context.addInitScript(tapBuses);
|
|
547
|
+
await context.addInitScript(logPhases);
|
|
548
|
+
/** @type {Map<import('playwright').Request, (typeof rows)[number]>} */
|
|
549
|
+
const byRequest = new Map();
|
|
550
|
+
context.on('request', request => { const row = { t: at(), ts: Date.now(), url: request.url(), phase, step, fromSW: null, status: 0 }; byRequest.set(request, row); rows.push(row); });
|
|
551
|
+
context.on('response', response => { const row = byRequest.get(response.request()); if (row !== undefined) { row.status = response.status(); row.fromSW = response.fromServiceWorker(); } });
|
|
552
|
+
const page = context.pages()[0] ?? await context.newPage();
|
|
553
|
+
page.on('console', line => { if (line.type() === 'error') consoleLines.push(`${String(at())} ${line.text().slice(0, 300)}`); });
|
|
554
|
+
page.on('pageerror', error => { consoleLines.push(`${String(at())} pageerror ${error.message.slice(0, 300)}`); });
|
|
555
|
+
page.on('dialog', dialog => { void dialog.dismiss().catch(() => undefined); });
|
|
556
|
+
/** @type {ReturnType<typeof readScreen> | undefined} */
|
|
557
|
+
let last;
|
|
558
|
+
let polling = false;
|
|
559
|
+
const poller = setInterval(() => {
|
|
560
|
+
if (polling) return;
|
|
561
|
+
polling = true;
|
|
562
|
+
void bounded(page.evaluate(readScreen), 5000).then(screen => {
|
|
563
|
+
polling = false;
|
|
564
|
+
if (screen === undefined) return undefined;
|
|
565
|
+
last = screen; phase = screen.phase; step = screen.step;
|
|
566
|
+
if (phases.at(-1)?.phase !== phase || phases.at(-1)?.step !== step) phases.push({ t: at(), phase, step });
|
|
567
|
+
const total = /DOWNLOAD [\d.]+ of ([\d.]+) MB/u.exec(screen.text)?.[1];
|
|
568
|
+
if (total !== undefined) downloadCardMB = Math.max(downloadCardMB, Number(total));
|
|
569
|
+
return undefined;
|
|
570
|
+
});
|
|
571
|
+
}, 200);
|
|
572
|
+
const timeout = mode === 'slow' ? 240_000 : 120_000;
|
|
573
|
+
try {
|
|
574
|
+
if (route === 'cross') {
|
|
575
|
+
await page.goto(new URL('/', origin).href, { waitUntil: 'commit', timeout: 120_000 });
|
|
576
|
+
await pickFromDeck(page, deckShard(slug, route), mode);
|
|
577
|
+
phase = 'none';
|
|
578
|
+
} else if (route === 'client') {
|
|
579
|
+
phase = 'none';
|
|
580
|
+
// `&skipintro` (offline-proof.mjs's Open Plot entry) is the bench path (play.ts `markEntered`): it never runs ENTER
|
|
581
|
+
// WORLD, so the music never starts on a one-shard page and the world bus stays hushed on a grid page. Its LOAD and
|
|
582
|
+
// DOWNLOAD are judged; its sound is reported, not judged (see `silent`).
|
|
583
|
+
await page.goto(new URL(`/?chunk=${slug}${benchEntry(run.target, route, slug) ? '&skipintro' : ''}`, origin).href, { waitUntil: 'commit', timeout: 120_000 });
|
|
584
|
+
} else {
|
|
585
|
+
await page.goto(new URL('/', origin).href, { waitUntil: 'commit', timeout: 120_000 });
|
|
586
|
+
await pickFromDeck(page, slug, mode);
|
|
587
|
+
phase = 'none';
|
|
588
|
+
}
|
|
589
|
+
let key = '', changed = Date.now(), stepKey = '', stepSince = Date.now(), cardSeen = false, picked = false;
|
|
590
|
+
for (;;) {
|
|
591
|
+
await sleep(400);
|
|
592
|
+
if (at() > timeout) { outcome = 'stalled'; break; }
|
|
593
|
+
const screen = last;
|
|
594
|
+
if (screen === undefined) continue;
|
|
595
|
+
if (await page.locator('.ws-load-play').isVisible().catch(() => false)) await page.locator('.ws-load-play').click({ timeout: 3000 }).catch(() => undefined);
|
|
596
|
+
cardSeen ||= screen.card;
|
|
597
|
+
// preview's deep link without the bench flag loads the shard, then lands on the title: the player's next step is
|
|
598
|
+
// Shard select, its card, ENTER WORLD (the resident shard enters at once, HUD `enterNow`)
|
|
599
|
+
if (route === 'client' && !benchEntry(run.target, route, slug) && cardSeen && screen.title && !picked) { picked = true; await pickFromDeck(page, slug, mode); }
|
|
600
|
+
const now = JSON.stringify([screen.phase, screen.step, screen.error, screen.text.slice(0, 200)]);
|
|
601
|
+
if (now !== key) { key = now; changed = Date.now(); }
|
|
602
|
+
// the card's clock ticks in its text, so the seat wait is timed on the phase and step alone
|
|
603
|
+
if (`${screen.phase}/${screen.step}` !== stepKey) { stepKey = `${screen.phase}/${screen.step}`; stepSince = Date.now(); }
|
|
604
|
+
if (screen.player) { outcome = 'play'; playAt = screen.now; break; }
|
|
605
|
+
if (screen.error !== '') { outcome = 'error'; break; }
|
|
606
|
+
// the local build's world door: rooms-staging refuses a loopback origin, so a staging-like load ends at the seat
|
|
607
|
+
// (offline-proof.mjs's seat-wait); LOAD's reads before it are what this target judges
|
|
608
|
+
if (run.target === 'local' && screen.phase === 'load' && screen.step === 'server' && Date.now() - stepSince > 10_000) { outcome = 'seat-wait'; break; }
|
|
609
|
+
if (Date.now() - changed > (mode === 'slow' ? 90_000 : 45_000) || at() > timeout) { outcome = 'stalled'; break; }
|
|
610
|
+
}
|
|
611
|
+
await page.screenshot({ path: join(out, `${label}-${outcome}.png`), timeout: 10_000 }).catch(() => undefined);
|
|
612
|
+
if (outcome === 'play') {
|
|
613
|
+
// the first 10 s of play: a tap (the first gesture, if the entry had none), then walk and jump so footsteps play
|
|
614
|
+
const box = page.viewportSize() ?? { width: 402, height: 874 };
|
|
615
|
+
await page.mouse.click(box.width / 2, box.height * 0.4).catch(() => undefined);
|
|
616
|
+
const walk = async (/** @type {number} */ ms) => {
|
|
617
|
+
const until = Date.now() + ms - 600;
|
|
618
|
+
for (let turn = 0; Date.now() < until; turn++) {
|
|
619
|
+
const held = ['w', 'a', 'w', 'd'][turn % 4] ?? 'w';
|
|
620
|
+
await page.keyboard.down(held); await sleep(1200); await page.keyboard.press('Space').catch(() => undefined); await sleep(600); await page.keyboard.up(held);
|
|
621
|
+
}
|
|
622
|
+
await sleep(Math.max(0, until + 600 - Date.now()));
|
|
623
|
+
};
|
|
624
|
+
const heard = (start = playAt, scoreStart = Number.POSITIVE_INFINITY) => bounded(page.evaluate(([from, floor, scoreAt]) => {
|
|
625
|
+
const state = /** @type {{ samples: { t: number, peaks: Record<string, number> }[], taps: string[] } | undefined} */ (Reflect.get(globalThis, '__au14'));
|
|
626
|
+
/** @type {Record<string, number>} the loudest peak in the first 10 s */
|
|
627
|
+
const peaks = {};
|
|
628
|
+
/** @type {Record<string, number>} ms after play that each bus was first over the floor */
|
|
629
|
+
const first = {};
|
|
630
|
+
/** @type {Record<string, number>} ms after `scoreAt` (a crossing's score change) that each bus was first over the floor */
|
|
631
|
+
const heardAfterScore = {};
|
|
632
|
+
for (const sample of state?.samples ?? []) {
|
|
633
|
+
if (sample.t < from) continue;
|
|
634
|
+
for (const [kind, peak] of Object.entries(sample.peaks)) {
|
|
635
|
+
if (sample.t <= from + 10_000) peaks[kind] = Math.max(peaks[kind] ?? 0, peak);
|
|
636
|
+
if (peak >= floor && first[kind] === undefined) first[kind] = Math.round(sample.t - from);
|
|
637
|
+
if (peak >= floor && sample.t >= scoreAt && heardAfterScore[kind] === undefined) heardAfterScore[kind] = Math.round(sample.t - scoreAt);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return { peaks, first, afterScore: heardAfterScore, taps: state?.taps ?? [] };
|
|
641
|
+
}, [start, AUDIBLE_PEAK, scoreStart]), 10_000);
|
|
642
|
+
if (route === 'cross') {
|
|
643
|
+
// the walk into the plot; the window is the first 10 s after the crossing
|
|
644
|
+
const plan = CROSS_IN[slug];
|
|
645
|
+
if (plan === undefined) throw new Error(`${slug} has no cross-in walk`);
|
|
646
|
+
crossing = await crossIn(page, plan);
|
|
647
|
+
await page.screenshot({ path: join(out, `${label}-crossed.png`), timeout: 10_000 }).catch(() => undefined);
|
|
648
|
+
if (crossing.at !== undefined) {
|
|
649
|
+
const crossedAt = crossing.at;
|
|
650
|
+
const scoreAt = crossing.track.find(reading => reading.t >= crossedAt - 1000 && reading.score === plan.musicId)?.t ?? Number.POSITIVE_INFINITY;
|
|
651
|
+
const audio = await heard(crossedAt, scoreAt);
|
|
652
|
+
windowPeaks = audio?.peaks ?? {}; firstHeard = audio?.first ?? {}; afterScore = audio?.afterScore ?? {}; taps = audio?.taps ?? [];
|
|
653
|
+
}
|
|
654
|
+
clearInterval(poller);
|
|
655
|
+
return { rows, phases, pagePhases, consoleLines, outcome, ms: at(), playAt, downloadCardMB, windowPeaks, firstHeard, taps, proofError, network: link.seen, crossing, afterScore };
|
|
656
|
+
}
|
|
657
|
+
await walk(PLAY_WINDOW_MS);
|
|
658
|
+
let audio = await heard();
|
|
659
|
+
await page.screenshot({ path: join(out, `${label}-after-10s.png`), timeout: 10_000 }).catch(() => undefined);
|
|
660
|
+
// a bus silent in the window: keep playing to 30 s, so the receipt says when (or whether) it starts
|
|
661
|
+
if ((audio?.peaks.music ?? 0) < AUDIBLE_PEAK || (audio?.peaks.sfx ?? 0) < AUDIBLE_PEAK) { await walk(20_000); audio = await heard() ?? audio; }
|
|
662
|
+
windowPeaks = audio?.peaks ?? {}; firstHeard = audio?.first ?? {}; taps = audio?.taps ?? [];
|
|
663
|
+
}
|
|
664
|
+
} catch (error) {
|
|
665
|
+
outcome = 'error'; proofError = String(error).slice(0, 300); consoleLines.push(`proof ${proofError}`);
|
|
666
|
+
await page.screenshot({ path: join(out, `${label}-error.png`), timeout: 10_000 }).catch(() => undefined);
|
|
667
|
+
}
|
|
668
|
+
clearInterval(poller);
|
|
669
|
+
return { rows, phases, pagePhases, consoleLines, outcome, ms: at(), playAt, downloadCardMB, windowPeaks, firstHeard, taps, proofError, network: link.seen, crossing, afterScore };
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** The spawn manifest a visit read: its flow, its DOWNLOAD total and its audio on the wire. @param {string} url */
|
|
674
|
+
async function manifestOf(url) {
|
|
675
|
+
const manifest = /** @type {{ flow?: string, wireBytes?: number, totalBytes: number, files: { url: string, bytes: number, wireBytes?: number }[],
|
|
676
|
+
parts?: { url: string, members: [number, number][] }[] }} */ (await (await fetch(url)).json());
|
|
677
|
+
const audio = manifest.files.filter(file => AUDIO.test(file.url));
|
|
678
|
+
// the packed parts that carry audio: reading one in LOAD is reading audio from the network too
|
|
679
|
+
const audioParts = new Set((manifest.parts ?? []).filter(part => part.members.some(([at]) => AUDIO.test(manifest.files[at]?.url ?? ''))).map(part => new URL(part.url, url).pathname));
|
|
680
|
+
return { flow: manifest.flow ?? SPAWN.exec(new URL(url).pathname)?.[2] ?? '', downloadMB: (manifest.wireBytes ?? manifest.totalBytes) / 1e6, audioRows: audio.length,
|
|
681
|
+
audioMB: audio.reduce((sum, file) => sum + (file.wireBytes ?? file.bytes), 0) / 1e6, audioParts };
|
|
682
|
+
}
|
|
683
|
+
/** The card's phase at an absolute time, from the page's own log; `fallback` (the poll's reading) when the log is empty.
|
|
684
|
+
* @param {{ t: number, phase: string, step: string }[]} changes @param {number} t @param {{ phase: string, step: string }} fallback */
|
|
685
|
+
function phaseAt(changes, t, fallback) {
|
|
686
|
+
let found;
|
|
687
|
+
for (const change of changes) { if (change.t <= t) found = change; else break; }
|
|
688
|
+
return found ?? (changes.length === 0 ? fallback : { phase: 'title', step: '' });
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Judge one visit and keep its logs.
|
|
693
|
+
* @param {string} target @param {{ slug: string, route: Route }} entry @param {'warm' | 'slow'} mode
|
|
694
|
+
* @param {Awaited<ReturnType<typeof visit>>} result @param {string | undefined} earlier the warm visit's manifest URL
|
|
695
|
+
*/
|
|
696
|
+
async function judge(target, entry, mode, result, earlier) {
|
|
697
|
+
const label = `${target}-${entry.slug}-${entry.route}-${mode}`;
|
|
698
|
+
// every request takes the phase the page's own log had when the proof saw it (the event comes after the request left, so a
|
|
699
|
+
// read at the DOWNLOAD/LOAD edge counts as LOAD: the strict side)
|
|
700
|
+
for (const row of result.rows) { const at = phaseAt(result.pagePhases, row.ts, row); row.phase = at.phase; row.step = at.step; }
|
|
701
|
+
const network = result.network.map(row => ({ ...row, phase: phaseAt(result.pagePhases, row.t, { phase: '?', step: '' }).phase }));
|
|
702
|
+
writeFileSync(join(out, `${label}-requests.json`), JSON.stringify({ rows: result.rows, network, phases: result.phases, pagePhases: result.pagePhases, console: result.consoleLines }));
|
|
703
|
+
/** @type {{ rule: string, detail: string }[]} */
|
|
704
|
+
const failures = [];
|
|
705
|
+
// the route's own manifest; a later visit can read it from the page's store and fetch none, so it falls back to the
|
|
706
|
+
// manifest the profile's earlier visit fetched for this route
|
|
707
|
+
// a crossing starts in its deck neighbour, so its manifest is the neighbour's grid one
|
|
708
|
+
const shard = deckShard(entry.slug, entry.route), route = entry.route === 'cross' ? 'grid' : entry.route;
|
|
709
|
+
const read = result.rows.map(row => ({ url: row.url, match: SPAWN.exec(new URL(row.url).pathname) })).filter(row => row.match?.[1] === shard);
|
|
710
|
+
// a world build sends a deep link the grid way too (OFFLINE OF2: world builds never take the solo route), so a deep link's
|
|
711
|
+
// manifest is whichever phone manifest it fetched, the one-shard `client` one first
|
|
712
|
+
const phone = read.filter(row => row.match?.[3] === 'phone');
|
|
713
|
+
const own = (phone.find(row => row.match?.[2] === route) ?? (route === 'client' ? phone[0] : undefined))?.url;
|
|
714
|
+
const spawnUrl = own ?? earlier;
|
|
715
|
+
const manifest = spawnUrl === undefined ? undefined : await manifestOf(spawnUrl).catch(() => undefined);
|
|
716
|
+
const isAudio = (/** @type {string} */ url) => { const path = new URL(url).pathname; return AUDIO.test(path) || manifest?.audioParts.has(path) === true; };
|
|
717
|
+
const audioRows = result.rows.filter(row => isAudio(row.url));
|
|
718
|
+
const loadAudio = audioRows.filter(row => row.phase === 'load');
|
|
719
|
+
const served = (/** @type {boolean | null} */ fromSW) => fromSW === true ? 'worker' : fromSW === false ? 'network' : 'no response';
|
|
720
|
+
for (const row of loadAudio.slice(0, 5)) failures.push({ rule: 'load-audio', detail: `${row.url} (${served(row.fromSW)}, step ${row.step})` });
|
|
721
|
+
if (loadAudio.length > 5) failures.push({ rule: 'load-audio', detail: `… ${String(loadAudio.length - 5)} more` });
|
|
722
|
+
const netAudio = network.filter(row => !row.url.startsWith('connect://') && isAudio(row.url));
|
|
723
|
+
const netLoadAudio = netAudio.filter(row => row.phase === 'load');
|
|
724
|
+
for (const row of netLoadAudio.slice(0, 5)) failures.push({ rule: 'load-audio', detail: `network fetch ${row.url}` });
|
|
725
|
+
/** @type {Record<string, number>} */
|
|
726
|
+
const audioByPhase = {};
|
|
727
|
+
for (const row of audioRows) audioByPhase[row.phase] = (audioByPhase[row.phase] ?? 0) + 1;
|
|
728
|
+
// the local build's reads must reach the link, or its network check proves nothing
|
|
729
|
+
if (target === 'local' && !network.some(row => row.url.startsWith('http://127.0.0.1'))) failures.push({ rule: 'link-blind', detail: 'no local http read went through the proxy' });
|
|
730
|
+
if (mode === 'warm' && own === undefined) failures.push({ rule: 'route', detail: `no ${shard} ${route === 'grid' ? 'grid' : ''} phone manifest fetched (fetched: ${read.map(row => row.match?.[0] ?? '').join(', ') || 'none'})` });
|
|
731
|
+
if (!result.pagePhases.some(row => row.phase === 'load')) failures.push({ rule: 'no-load', detail: `the card never reached LOAD (${result.outcome})` });
|
|
732
|
+
const au6 = AU6_AUDIO_MB[shard] ?? (shard.startsWith('open-plot-') ? AU6_AUDIO_MB['open-plot-*'] ?? 0 : 0);
|
|
733
|
+
if (manifest === undefined) failures.push({ rule: 'download-short', detail: `no ${shard}-${route}-phone spawn manifest to read` });
|
|
734
|
+
else {
|
|
735
|
+
if (!(manifest.downloadMB >= au6)) failures.push({ rule: 'download-short', detail: `DOWNLOAD ${manifest.downloadMB.toFixed(2)} MB < AU6 audio ${au6.toFixed(2)} MB` });
|
|
736
|
+
// the download's own audio, not only its total: AU6 measured the same manifests' audio rows (2 decimals)
|
|
737
|
+
if (!(manifest.audioMB >= au6 - 0.005)) failures.push({ rule: 'download-short', detail: `the download's audio ${manifest.audioMB.toFixed(2)} MB < AU6 ${au6.toFixed(2)} MB (${String(manifest.audioRows)} rows)` });
|
|
738
|
+
}
|
|
739
|
+
const peaks = result.windowPeaks;
|
|
740
|
+
const audible = { music: (peaks.music ?? 0) >= AUDIBLE_PEAK, sfx: (peaks.sfx ?? 0) >= AUDIBLE_PEAK };
|
|
741
|
+
const bench = benchEntry(target, entry.route, entry.slug);
|
|
742
|
+
// a crossing: the plot's cell, its score, and the audio the page read on the way (from the walk's start)
|
|
743
|
+
const crossing = result.crossing, plan = CROSS_IN[entry.slug];
|
|
744
|
+
const crossed = crossing?.at !== undefined;
|
|
745
|
+
const scoreRow = crossing === null || crossing.at === undefined ? undefined : crossing.track.find(row => row.t >= (crossing.at ?? 0) - 1000 && row.score === plan?.musicId);
|
|
746
|
+
// the crossing starts where the feet leave the neighbour's cell; reads before it are the neighbour's own play
|
|
747
|
+
const leftAt = crossing?.leftTs ?? crossing?.startTs ?? Number.POSITIVE_INFINITY;
|
|
748
|
+
const crossAudio = crossing === null ? [] : audioRows.filter(row => row.ts >= leftAt);
|
|
749
|
+
// AU20: from the moment the feet stand in the plot, its scene reads its own bank at play time (reported, not judged)
|
|
750
|
+
const inPlotAt = crossing?.ts ?? Number.POSITIVE_INFINITY;
|
|
751
|
+
const crossNetAudio = crossing === null ? [] : netAudio.filter(row => row.t >= leftAt && row.t < inPlotAt);
|
|
752
|
+
const plotNetAudio = crossing === null ? [] : netAudio.filter(row => row.t >= inPlotAt);
|
|
753
|
+
const walkNetAudio = crossing === null ? [] : netAudio.filter(row => row.t >= crossing.startTs && row.t < leftAt);
|
|
754
|
+
/** @type {Record<string, number>} the crossing's audio reads by who served them */
|
|
755
|
+
const bySource = {};
|
|
756
|
+
for (const row of crossAudio) { const key = served(row.fromSW); bySource[key] = (bySource[key] ?? 0) + 1; }
|
|
757
|
+
if (entry.route === 'cross' && result.outcome === 'play') {
|
|
758
|
+
if (!crossed) failures.push({ rule: 'no-cross', detail: `never inside ${plan?.instance ?? ''}; last ${JSON.stringify(crossing?.track.at(-1) ?? null)}` });
|
|
759
|
+
else if (scoreRow === undefined || scoreRow.t > (crossing?.at ?? 0) + PLAY_WINDOW_MS) failures.push({ rule: 'plot-score', detail: `the score never became ${plan?.musicId ?? ''} in 10 s: ${JSON.stringify(crossing?.track.map(row => [Math.round(row.t - (crossing.at ?? 0)), row.inside, row.score, row.slot, row.source]))}` });
|
|
760
|
+
for (const row of crossNetAudio.slice(0, 5)) failures.push({ rule: 'cross-audio', detail: `network fetch on the crossing ${row.url}` });
|
|
761
|
+
if (crossNetAudio.length > 5) failures.push({ rule: 'cross-audio', detail: `… ${String(crossNetAudio.length - 5)} more` });
|
|
762
|
+
}
|
|
763
|
+
if (result.outcome === 'play' && !bench && (entry.route !== 'cross' || crossed) && !(audible.music && audible.sfx)) failures.push({ rule: 'silent', detail: `first 10 s of ${entry.route === 'cross' ? 'the plot' : 'play'}: ${JSON.stringify(peaks)}, first heard (ms after ${entry.route === 'cross' ? 'the crossing' : 'play, 30 s watched'}) ${JSON.stringify(result.firstHeard)} (taps ${result.taps.join(',') || 'none'})` });
|
|
764
|
+
// the bench deep link is not a player's entry: on a world build Driftwood's lands on the title after its LOAD (seen on staging
|
|
765
|
+
// 6d11b137), so it needs LOAD (no-load) but not play
|
|
766
|
+
if (result.outcome !== 'play' && !(target === 'local' && result.outcome === 'seat-wait') && !bench && mode === 'warm') failures.push({ rule: 'no-play', detail: `${result.outcome} at ${result.phases.at(-1)?.phase ?? ''}/${result.phases.at(-1)?.step ?? ''} ${result.proofError}` });
|
|
767
|
+
const row = {
|
|
768
|
+
entry: bench ? 'deep link, skipintro (bench path: sound not judged)' : entry.route === 'grid' ? 'Shard select, ENTER WORLD'
|
|
769
|
+
: entry.route === 'cross' ? `Shard select, ${CARDS[shard] ?? shard}, ENTER WORLD, walked into ${plan?.instance ?? ''}` : 'deep link, ENTER WORLD',
|
|
770
|
+
target, shard: entry.slug, route: entry.route, flowRead: manifest?.flow ?? '', manifest: spawnUrl === undefined ? null : new URL(spawnUrl).pathname,
|
|
771
|
+
manifestsFetched: read.map(one => new URL(one.url).pathname.split('/').pop() ?? ''), mode, outcome: result.outcome, seconds: Math.round(result.ms / 100) / 10,
|
|
772
|
+
loadAudioRequests: loadAudio.length, loadAudioNetworkFetches: netLoadAudio.length, audioRequestsByPhase: audioByPhase, networkAudioFetches: netAudio.length,
|
|
773
|
+
linkSeen: network.filter(one => !one.url.startsWith('connect://')).length,
|
|
774
|
+
downloadMB: manifest === undefined ? null : Number(manifest.downloadMB.toFixed(2)), downloadCardMB: result.downloadCardMB || null,
|
|
775
|
+
manifestAudioMB: manifest === undefined ? null : Number(manifest.audioMB.toFixed(2)), manifestAudioRows: manifest?.audioRows ?? 0, au6AudioMB: au6,
|
|
776
|
+
peaksFirst10s: Object.fromEntries(Object.entries(peaks).map(([kind, peak]) => [kind, Number(peak.toFixed(4))])), firstHeardMs: result.firstHeard, audible,
|
|
777
|
+
crossing: crossing === null ? null : {
|
|
778
|
+
crossedMsAfterPlay: crossing.at === undefined ? null : Math.round(crossing.at - result.playAt), walkSeconds: crossing.at === undefined || crossing.ts === undefined ? null : Math.round((crossing.ts - crossing.startTs) / 100) / 10,
|
|
779
|
+
plotScore: plan?.musicId ?? null, scoreMsAfterCrossing: scoreRow === undefined || crossing.at === undefined ? null : Math.round(scoreRow.t - crossing.at), heardMsAfterScore: result.afterScore,
|
|
780
|
+
audioRequests: crossAudio.length, audioBySource: bySource,
|
|
781
|
+
networkAudioFetches: crossNetAudio.length, plotPlayNetworkAudio: plotNetAudio.map(one => new URL(one.url).pathname), audioUrls: crossAudio.map(one => new URL(one.url).pathname).slice(0, 30),
|
|
782
|
+
neighbourPlayNetworkAudio: walkNetAudio.map(one => new URL(one.url).pathname),
|
|
783
|
+
track: crossing.track.map(({ t, ...reading }) => Object.assign(reading, { ms: Math.round(t - (crossing.at ?? result.playAt)) })),
|
|
784
|
+
},
|
|
785
|
+
failures,
|
|
786
|
+
};
|
|
787
|
+
log(`${failures.length === 0 ? 'ok ' : 'RED'} ${label}: ${result.outcome} in ${String(row.seconds)} s, flow ${row.flowRead}, LOAD audio ${String(row.loadAudioRequests)}, `
|
|
788
|
+
+ `DOWNLOAD ${String(row.downloadMB)} MB (audio ${String(row.manifestAudioMB)} MB, AU6 ${String(au6)}), peaks ${JSON.stringify(row.peaksFirst10s)}`);
|
|
789
|
+
for (const failure of failures) log(` ${failure.rule} ${failure.detail}`);
|
|
790
|
+
if (row.crossing !== null) log(` crossing ${JSON.stringify({ ...row.crossing, track: row.crossing.track.length })}`);
|
|
791
|
+
return row;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** @type {Awaited<ReturnType<typeof judge>>[]} */
|
|
795
|
+
const results = [];
|
|
796
|
+
let code = 1;
|
|
797
|
+
try {
|
|
798
|
+
/** @type {{ target: string, origin: string }[]} */
|
|
799
|
+
const targets = [];
|
|
800
|
+
if (['staging', 'both', 'all'].includes(targetArg)) targets.push({ target: 'staging', origin: STAGING.origin });
|
|
801
|
+
if (['local', 'both', 'all'].includes(targetArg)) targets.push({ target: 'local', origin: await localOrigin() });
|
|
802
|
+
// the same build as served, no world: the solo page, where a deep link takes the one-shard `client` manifest
|
|
803
|
+
if (['preview', 'all'].includes(targetArg)) targets.push({ target: 'preview', origin: previewOrigin() });
|
|
804
|
+
/** @type {Record<string, string>} */
|
|
805
|
+
const builds = {};
|
|
806
|
+
for (const { target, origin } of targets) {
|
|
807
|
+
builds[target] = /** @type {{ build: string }} */ (await (await fetch(new URL('/version.json', origin))).json()).build;
|
|
808
|
+
log(target, origin, 'build', builds[target]);
|
|
809
|
+
// preview has no world and no deck route to judge: only the deep links and the crossings
|
|
810
|
+
// a crossing needs the in-page server, so it runs on preview alone
|
|
811
|
+
const queue = entries.filter(entry => target === 'preview' ? entry.route !== 'grid' : entry.route !== 'cross');
|
|
812
|
+
const worker = async () => {
|
|
813
|
+
for (let entry = queue.shift(); entry !== undefined; entry = queue.shift()) {
|
|
814
|
+
const profile = join(out, `profile-${target}-${entry.slug}-${entry.route}`);
|
|
815
|
+
rmSync(profile, { recursive: true, force: true });
|
|
816
|
+
/** @type {string | undefined} */
|
|
817
|
+
let earlier;
|
|
818
|
+
for (const mode of /** @type {const} */ (['warm', 'slow'])) {
|
|
819
|
+
const label = `${target}-${entry.slug}-${entry.route}-${mode}`;
|
|
820
|
+
log(label);
|
|
821
|
+
try {
|
|
822
|
+
const row = await judge(target, entry, mode, await visit({ origin, target, profile, slug: entry.slug, route: entry.route, mode, label }), earlier);
|
|
823
|
+
if (row.manifest !== null) earlier = new URL(row.manifest, origin).href;
|
|
824
|
+
results.push(row);
|
|
825
|
+
}
|
|
826
|
+
catch (error) { log(`${label} broke: ${String(error)}`); results.push({ entry: 'proof error', target, shard: entry.slug, route: entry.route, flowRead: '', manifest: null, manifestsFetched: [], mode, outcome: 'error', seconds: 0, loadAudioRequests: 0, loadAudioNetworkFetches: 0, audioRequestsByPhase: {}, networkAudioFetches: 0, linkSeen: 0, downloadMB: null, downloadCardMB: null, manifestAudioMB: null, manifestAudioRows: 0, au6AudioMB: 0, peaksFirst10s: {}, firstHeardMs: {}, audible: { music: false, sfx: false }, crossing: null, failures: [{ rule: 'proof-error', detail: String(error).slice(0, 300) }] }); }
|
|
827
|
+
}
|
|
828
|
+
rmSync(profile, { recursive: true, force: true });
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
await Promise.all(Array.from({ length: Math.min(jobs, queue.length) }, () => worker()));
|
|
832
|
+
}
|
|
833
|
+
const failing = results.filter(row => row.failures.length > 0).map(row => `${row.target}:${row.shard}:${row.route}:${row.mode}`);
|
|
834
|
+
code = failing.length === 0 ? 0 : 1;
|
|
835
|
+
const receipt = { proof: 'audio-download-proof.mjs (AUDIO AU14)', browser: `webkit ${webkit.name()} headless 402x874`, link: 'own forward proxy; slow = 0.7 Mbit/s shared, 150 ms each way',
|
|
836
|
+
builds, started: new Date(t0).toISOString(), seconds: Math.round((Date.now() - t0) / 1000), red: code !== 0, failing, results };
|
|
837
|
+
writeFileSync(join(out, 'receipt.json'), `${JSON.stringify(receipt, null, 1)}\n`);
|
|
838
|
+
log(code === 0 ? 'GREEN' : `RED: ${failing.join(', ')}`, '| receipt in', out);
|
|
839
|
+
} finally {
|
|
840
|
+
stamper?.close();
|
|
841
|
+
if (builtPort !== '') spawnSync('bash', ['scripts/serve-build.sh', 'stop', builtPort], { cwd: ROOT, stdio: 'ignore', env: { ...process.env, SERVE_OWNER: process.env.SERVE_OWNER ?? 'audio-download-proof' } });
|
|
842
|
+
}
|
|
843
|
+
process.exit(code);
|