@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,333 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// HOST-RULER HR1 (meta docs/plans/HOST-RULER-PLAN.md): the page and section roots one built product reaches.
|
|
3
|
+
// Not a revival of shard-platform.mjs: its roots walked src/shards/ and pre-J122 paths. A product reaches engine code
|
|
4
|
+
// only through what it declares: its `client/plan` kinds and its section names. A kind roots the import() targets of
|
|
5
|
+
// its one CLIENT_FEATURES entry (never the whole table); a section roots its row in SECTION_HOSTS. clientPlan.ts's own
|
|
6
|
+
// static imports are one shared root, `@client-plan`, reached by every product with a `client/plan`.
|
|
7
|
+
// Usage: node scripts/host-ruler/roots.mjs <product-dir>... (a dir holding shard.json, e.g. shard-x/out/<slug>)
|
|
8
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
10
|
+
import { parseSync } from 'vite';
|
|
11
|
+
|
|
12
|
+
export const ENGINE_ROOT = resolve(import.meta.dirname, '../..');
|
|
13
|
+
export const CLIENT_PLAN = 'src/client/game/shardfile/clientPlan.ts';
|
|
14
|
+
export const CLIENT_PLAN_ROOT = '@client-plan';
|
|
15
|
+
|
|
16
|
+
/** Section name -> the host bindings that execute it, side-first (J122). `@wildshard/format/x` resolves through the
|
|
17
|
+
* pinned format package's exports map. An empty row is metadata read by another section's host: it roots nothing.
|
|
18
|
+
* Moved from shard-platform-hosts.mjs (old `<layer>/<side>/x` selectors -> `src/<side>/<layer>/x.ts`). Fixed there:
|
|
19
|
+
* `game/server/shardfile/items` -> src/shared/game/shardfile/items.ts; `game/shardfile/directorClient` is gone, its
|
|
20
|
+
* rows run in bindShardfileSim's DirectorStageLane. `client/plan` no longer roots `clientPlan#installClientPhase` (the
|
|
21
|
+
* whole dispatch table, HA0 a) or `declaredEntry#declaredRuntimeEntry` (gone): it roots `@client-plan` and its kinds. */
|
|
22
|
+
export const SECTION_HOSTS = Object.freeze({
|
|
23
|
+
'explore/catalogue': ['src/client/game/models/explorerCatalogue.ts#explorerRoster'],
|
|
24
|
+
'collections/displays': ['src/client/game/models/collectionDisplay.ts#CollectionCatalogue'],
|
|
25
|
+
'models/island-library': ['src/client/game/models/islandLibrary.ts#IslandLibrary'],
|
|
26
|
+
'world/trees': ['src/client/game/models/treeSet.ts#productTreeSet', 'src/client/game/shardfile/forestPage.ts#placeForestPageModels'],
|
|
27
|
+
'look/rigged-hulls': ['src/client/game/looks/riggedHulls.ts#productRiggedHulls'],
|
|
28
|
+
'look/hull-book': ['src/client/game/looks/speciesBook.ts#productHullBook'],
|
|
29
|
+
'look/painted': ['src/client/game/looks/paintedLook.ts#productPaintedLook'],
|
|
30
|
+
'look/colour-functions': ['src/client/engine/render/graph/colourFunction.ts#materialColourGraph'],
|
|
31
|
+
'look/toon': ['src/client/game/looks/toonLook.ts#toonLook'],
|
|
32
|
+
'client/plan': [CLIENT_PLAN_ROOT],
|
|
33
|
+
'world/tiles': ['src/client/game/shardfile/clientViews.ts#clientTileViews'],
|
|
34
|
+
'world/terrain': ['src/shared/game/shardfile/clientGround.ts#clientGround'],
|
|
35
|
+
'world/edge': ['src/shared/game/shardfile/portalTraversal.ts#createPortalTraversal'],
|
|
36
|
+
'world/collision': ['src/shared/game/shardfile/collisionBindings.ts#installShardfileColliders'],
|
|
37
|
+
'world/navigation': ['src/client/game/shardfile/productNavigation.ts#installProductNavigation'],
|
|
38
|
+
'world/props': ['src/shared/game/shardfile/props.ts#propColliderDescriptors'],
|
|
39
|
+
'world/water': ['src/client/game/shardfile/clientWater.ts#installClientWater', 'src/client/game/shardfile/water.ts#shardfileWater'],
|
|
40
|
+
'world/movers': ['src/server/game/plugin/mover.ts#createComposedMoverHost', 'src/client/game/shardfile/clientMoverOwners.ts#installClientMoverOwners'],
|
|
41
|
+
'world/traversal': ['src/shared/game/shardfile/portalTraversal.ts#createPortalTraversal'],
|
|
42
|
+
'world/spawn': [], // Level admission metadata.
|
|
43
|
+
'world/physics': [], // Handed to the runtime's explicitly imported native host.
|
|
44
|
+
'world/days': ['src/shared/game/shard/declaredRows.ts#declaredDay'],
|
|
45
|
+
'world/weather': ['src/shared/game/shard/declaredRows.ts#declaredWeather'],
|
|
46
|
+
'look/look': ['src/client/game/shardfile/look.ts#shardfileLook'],
|
|
47
|
+
'look/map': ['src/client/game/shardfile/mapImage.ts#reserveMapImage'],
|
|
48
|
+
'look/materials': ['src/client/game/shardfile/clientMaterials.ts#clientMaterials'],
|
|
49
|
+
'look/keyed-sky': ['src/client/game/looks/keyedSky.ts#keyedSkyBackdrop'],
|
|
50
|
+
'actors/spawn-scripts': ['src/server/game/population/spawnScript.ts#SpawnScript', '@wildshard/format/spawnScripts#parseSpawnScript'],
|
|
51
|
+
'player/stealth': ['src/client/game/stealth/controller.ts#StealthController', '@wildshard/format/stealth#StealthRowsSchema'],
|
|
52
|
+
'view/modules': ['@wildshard/format/scriptContract#ViewModulesSchema', '@wildshard/format/scriptContract#admitScriptContract'],
|
|
53
|
+
'actors/return-scripts': ['src/shared/game/population/returnProgram.ts#ReturnProgram', '@wildshard/format/decisionScripts#parseDecisionScripts'],
|
|
54
|
+
'actors/moves': ['src/server/engine/ai/moves.ts#ActorMoveRunner', '@wildshard/format/actorMoves#parseActorMoves'],
|
|
55
|
+
'actors/creatures': ['src/server/game/shardfile/brainRuntime.ts#installDeclaredBrains'],
|
|
56
|
+
'actors/crowds': ['src/shared/game/shardfile/crowdRuntime.ts#prepareDeclaredCrowds'],
|
|
57
|
+
'actors/npcs': ['src/server/game/plugin/simulation.ts#installDeclaredQuestHost'],
|
|
58
|
+
'actors/species': ['src/server/game/plugin/brain.ts#speciesResolver', 'src/client/game/shardfile/clientRecipes.ts#clientSpeciesLooks'],
|
|
59
|
+
'actors/spawns': ['src/server/game/shardfile/brainRuntime.ts#installDeclaredBrains'],
|
|
60
|
+
'actors/strikes': [], // Consumed by the runtime's explicitly imported creature host.
|
|
61
|
+
'actors/species-programs': [], // Metadata lent to existing page/native species and hunt owners.
|
|
62
|
+
'held/arms': ['src/client/game/loadout/claims.ts#HeldClaims', 'src/client/game/systems/viewmodel/heldView.ts#HeldView'],
|
|
63
|
+
'held/equipment': ['src/client/game/plugin/heldEquipment.ts#HeldEquipment'],
|
|
64
|
+
'held/loadout': ['src/client/game/loadout/held.ts#installHeldLoadout'],
|
|
65
|
+
'held/finishes': ['src/client/game/loadout/finishes.ts#HeldFinishes'],
|
|
66
|
+
'held/gear': ['src/client/game/models/heldGear.ts#heldGear'],
|
|
67
|
+
'combat/items': ['src/shared/game/shardfile/items.ts#installDeclaredItems'],
|
|
68
|
+
'combat/encounters': ['src/server/game/plugin/simulation.ts#createShardfileSim'],
|
|
69
|
+
'combat/strikes': ['src/server/game/plugin/simulation.ts#createShardfileSim'],
|
|
70
|
+
'quests/quests': ['src/shared/game/quest/declared.ts#DeclaredQuests'],
|
|
71
|
+
'quests/host': ['src/server/game/plugin/simulation.ts#installDeclaredQuestHost'],
|
|
72
|
+
'quests/directors': ['src/shared/game/plugin/director.ts#DirectorStageLane'],
|
|
73
|
+
'economy/ledger': ['src/shared/game/ledger.ts#Ledger', 'src/shared/game/ledger.ts#installLedgerEmitter'],
|
|
74
|
+
'economy/loot': ['src/shared/game/shard/declaredRows.ts#declaredLootPresentation'],
|
|
75
|
+
'state/state': ['src/server/game/shardfile/scripts.ts#numericScriptState'],
|
|
76
|
+
'state/migrations': ['src/shared/game/shardfile/logicalState.ts#logicalStateFromLane'],
|
|
77
|
+
'state/modes': ['src/shared/engine/player/modes.ts#playerModes'],
|
|
78
|
+
'sim/runtime-plan': ['src/server/game/shardfile/nativePlan.ts#prepareProductRuntimePlan'],
|
|
79
|
+
'world/scenes': ['src/client/game/shardfile/worldScenes.ts#installWorldScenes'],
|
|
80
|
+
'world/targets': ['src/shared/game/shardfile/worldTargets.ts#WorldTargetHost'],
|
|
81
|
+
'sim/scripts': ['src/server/engine/script/decision.ts#DecisionHost', '@wildshard/format/decisionScripts#parseDecisionScripts'],
|
|
82
|
+
'sim/bodies': ['src/server/game/quest/bodyOps.ts#DeclaredBodyOps', '@wildshard/format/bodySlots#DeclaredBodyOpsSchema'],
|
|
83
|
+
'sim/sim': ['src/server/game/shardfile/scripts.ts#createShardfileScriptLane'],
|
|
84
|
+
'sim/hooks': ['src/server/game/shardfile/scripts.ts#createShardfileScriptLane'],
|
|
85
|
+
'sim/client-scripts': ['src/client/game/shardfile/clientScripts.ts#createShardfileClientScripts'],
|
|
86
|
+
'sim/client-channels': ['src/client/game/plugin/ui.ts#ClientScriptViews'],
|
|
87
|
+
'sim/plumbing': ['src/client/game/shard/declaredPlumbing.ts#installDeclaredPlumbing'],
|
|
88
|
+
'audio/audio': ['src/client/engine/audio/declared.ts#installDeclaredAudio'],
|
|
89
|
+
'ui/card': [], // Discovery metadata; no per-shard executable implementation.
|
|
90
|
+
'ui/level': [],
|
|
91
|
+
'ui/ui': ['src/client/game/shard/declaredUi.ts#mountDeclaredUi', 'src/client/game/shard/declaredTargets.ts#installDeclaredTargets'],
|
|
92
|
+
'ui/compendium': ['src/shared/game/shard/declaredRows.ts#declaredProductCompendium'],
|
|
93
|
+
'ui/completion': ['src/client/game/complete/declared.ts#installCompletion'],
|
|
94
|
+
'ui/strings': [], // Read by an explicitly imported consumer, not executed.
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const json = (/** @type {string} */ path) => JSON.parse(readFileSync(path, 'utf8'));
|
|
98
|
+
const packages = new Map();
|
|
99
|
+
/** @param {string} root @param {string} name */
|
|
100
|
+
function packageExports(root, name) {
|
|
101
|
+
const key = `${root}\0${name}`;
|
|
102
|
+
if (!packages.has(key)) {
|
|
103
|
+
const dir = name === '@wildshard/engine' ? root : join(root, 'node_modules', name);
|
|
104
|
+
const manifest = json(join(dir, 'package.json'));
|
|
105
|
+
packages.set(key, { dir, exports: manifest.exports ?? {} });
|
|
106
|
+
}
|
|
107
|
+
return packages.get(key);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Resolve one import specifier to a module id: an engine module as its repo path (`src/...ts`), a format module as
|
|
111
|
+
* `@wildshard/format/<package path>` through the pinned package's exports map, any other bare package as `npm:<name>`.
|
|
112
|
+
* @param {string} specifier @param {string} from repo path of the importing file @param {string} [root] */
|
|
113
|
+
export function resolveModule(specifier, from, root = ENGINE_ROOT) {
|
|
114
|
+
if (specifier.startsWith('.')) {
|
|
115
|
+
const base = resolve(root, dirname(from), specifier);
|
|
116
|
+
for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, join(base, 'index.ts')]) {
|
|
117
|
+
if (/\.[cm]?[jt]sx?$/u.test(candidate) && existsSync(candidate)) return relative(root, candidate);
|
|
118
|
+
}
|
|
119
|
+
throw new Error(`Unresolved import ${specifier} from ${from}`);
|
|
120
|
+
}
|
|
121
|
+
for (const name of ['@wildshard/engine', '@wildshard/format']) {
|
|
122
|
+
if (!specifier.startsWith(`${name}/`)) continue;
|
|
123
|
+
const { exports } = packageExports(root, name), target = exports[`./${specifier.slice(name.length + 1)}`];
|
|
124
|
+
if (typeof target !== 'string') throw new Error(`Unresolved import ${specifier} from ${from}: not in ${name} exports`);
|
|
125
|
+
const path = target.replace(/^\.\//u, '');
|
|
126
|
+
return name === '@wildshard/engine' ? path : `${name}/${path}`;
|
|
127
|
+
}
|
|
128
|
+
const bare = specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/');
|
|
129
|
+
return `npm:${bare}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param {any} node @param {(node:any, parent:any)=>void} visit @param {any} [parent] */
|
|
133
|
+
function walk(node, visit, parent = null) {
|
|
134
|
+
if (node === null || typeof node !== 'object') return;
|
|
135
|
+
if (Array.isArray(node)) { for (const child of node) walk(child, visit, parent); return; }
|
|
136
|
+
if (typeof node.type !== 'string') return;
|
|
137
|
+
visit(node, parent);
|
|
138
|
+
for (const [key, value] of Object.entries(node)) if (key !== 'parent' && value !== null && typeof value === 'object') walk(value, visit, node);
|
|
139
|
+
}
|
|
140
|
+
const unwrap = (/** @type {any} */ node) => {
|
|
141
|
+
let inner = node;
|
|
142
|
+
while (inner?.type === 'ParenthesizedExpression' || inner?.type === 'TSAsExpression' || inner?.type === 'TSNonNullExpression') inner = inner.expression;
|
|
143
|
+
return inner;
|
|
144
|
+
};
|
|
145
|
+
const keyName = (/** @type {any} */ key) => key.type === 'Identifier' ? key.name : key.type === 'Literal' ? String(key.value) : null;
|
|
146
|
+
/** @param {any} pattern */
|
|
147
|
+
const patternNames = pattern => {
|
|
148
|
+
if (pattern?.type !== 'ObjectPattern') return null;
|
|
149
|
+
const names = pattern.properties.map((/** @type {any} */ p) => p.type === 'Property' && !p.computed ? keyName(p.key) : null);
|
|
150
|
+
return names.includes(null) ? null : names;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** Read clientPlan.ts statically: its static imports (the shared `@client-plan` root) and, per CLIENT_FEATURES kind,
|
|
154
|
+
* the import() targets of that entry with the bindings it takes. Three shapes are read:
|
|
155
|
+
* `member` `(await import('x')).Y` (the loadFeature form),
|
|
156
|
+
* `destructure` `const { a, b } = await import('x')`,
|
|
157
|
+
* `all` `const [{ a }, { b }] = await Promise.all([import('x'), import('y')])`.
|
|
158
|
+
* Any other import() shape, or an import() outside CLIENT_FEATURES, refuses.
|
|
159
|
+
* @param {string} [root] */
|
|
160
|
+
export function clientPlanRoots(root = ENGINE_ROOT) {
|
|
161
|
+
const source = readFileSync(join(root, CLIENT_PLAN), 'utf8');
|
|
162
|
+
const parsed = parseSync(CLIENT_PLAN, source);
|
|
163
|
+
if (parsed.errors.length > 0) throw new Error(`${CLIENT_PLAN}: parse errors`);
|
|
164
|
+
const shared = parsed.module.staticImports.map((/** @type {any} */ row) => ({
|
|
165
|
+
specifier: row.moduleRequest.value,
|
|
166
|
+
module: resolveModule(row.moduleRequest.value, CLIENT_PLAN, root),
|
|
167
|
+
// Type names never run: a mixed import keeps only its value bindings, and a type-only import roots nothing.
|
|
168
|
+
bindings: row.entries.filter((/** @type {any} */ e) => !e.isType).map((/** @type {any} */ e) => e.importName.kind === 'Name' ? e.importName.name : e.importName.kind === 'Default' ? 'default' : '*').sort(),
|
|
169
|
+
typeOnly: row.entries.length > 0 && row.entries.every((/** @type {any} */ e) => e.isType),
|
|
170
|
+
}));
|
|
171
|
+
/** @type {any} */
|
|
172
|
+
let table = null;
|
|
173
|
+
walk(parsed.program, node => {
|
|
174
|
+
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && node.id.name === 'CLIENT_FEATURES') table = unwrap(node.init);
|
|
175
|
+
});
|
|
176
|
+
if (table?.type !== 'ObjectExpression') throw new Error(`${CLIENT_PLAN}: CLIENT_FEATURES is not an object literal`);
|
|
177
|
+
/** @type {Map<string, Map<string, Set<string>>>} */
|
|
178
|
+
const kinds = new Map();
|
|
179
|
+
const shapes = { member: 0, destructure: 0, all: 0 };
|
|
180
|
+
/** @type {Map<string, Set<'member'|'destructure'|'all'>>} */
|
|
181
|
+
const kindShapes = new Map();
|
|
182
|
+
const inside = new Set();
|
|
183
|
+
for (const property of table.properties) {
|
|
184
|
+
const kind = property.type === 'Property' && !property.computed ? keyName(property.key) : null;
|
|
185
|
+
if (kind === null) throw new Error(`${CLIENT_PLAN}: CLIENT_FEATURES has a non-literal key`);
|
|
186
|
+
/** @type {Map<string, Set<string>>} */
|
|
187
|
+
const targets = new Map(), used = new Set();
|
|
188
|
+
kindShapes.set(kind, used);
|
|
189
|
+
walk(property.value, (node, parent) => {
|
|
190
|
+
node.parent = parent;
|
|
191
|
+
if (node.type !== 'ImportExpression') return;
|
|
192
|
+
inside.add(node.start);
|
|
193
|
+
if (node.source.type !== 'Literal' || typeof node.source.value !== 'string') throw new Error(`${CLIENT_PLAN}: ${kind} has a non-literal import()`);
|
|
194
|
+
const specifier = node.source.value, at = `${kind} import('${specifier}')`;
|
|
195
|
+
/** @type {string[] | null} */
|
|
196
|
+
let names = null;
|
|
197
|
+
let up = node.parent;
|
|
198
|
+
while (up?.type === 'ParenthesizedExpression') up = up.parent;
|
|
199
|
+
if (up?.type === 'AwaitExpression') {
|
|
200
|
+
let user = up.parent;
|
|
201
|
+
while (user?.type === 'ParenthesizedExpression') user = user.parent;
|
|
202
|
+
if (user?.type === 'MemberExpression' && unwrap(user.object) === up && !user.computed) { names = [user.property.name]; shapes.member++; used.add('member'); }
|
|
203
|
+
else if (user?.type === 'VariableDeclarator' && unwrap(user.init) === up) { names = patternNames(user.id); if (names !== null) { shapes.destructure++; used.add('destructure'); } }
|
|
204
|
+
} else if (up?.type === 'ArrayExpression') {
|
|
205
|
+
const call = up.parent, awaited = call?.parent, declarator = awaited?.parent;
|
|
206
|
+
const callee = call?.type === 'CallExpression' ? call.callee : null;
|
|
207
|
+
if (callee?.type === 'MemberExpression' && callee.object.name === 'Promise' && callee.property.name === 'all' && awaited?.type === 'AwaitExpression'
|
|
208
|
+
&& declarator?.type === 'VariableDeclarator' && declarator.id.type === 'ArrayPattern') {
|
|
209
|
+
names = patternNames(declarator.id.elements[up.elements.indexOf(node)]);
|
|
210
|
+
if (names !== null) { shapes.all++; used.add('all'); }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (names === null || names.length === 0) throw new Error(`${CLIENT_PLAN}: unread import() shape at ${at}`);
|
|
214
|
+
const module = resolveModule(specifier, CLIENT_PLAN, root);
|
|
215
|
+
const bindings = targets.get(module) ?? new Set();
|
|
216
|
+
for (const name of names) bindings.add(name);
|
|
217
|
+
targets.set(module, bindings);
|
|
218
|
+
});
|
|
219
|
+
kinds.set(kind, targets);
|
|
220
|
+
}
|
|
221
|
+
const outside = parsed.module.dynamicImports.filter((/** @type {any} */ row) => !inside.has(row.start));
|
|
222
|
+
if (outside.length > 0) throw new Error(`${CLIENT_PLAN}: ${outside.length} import() outside CLIENT_FEATURES`);
|
|
223
|
+
return {
|
|
224
|
+
shared,
|
|
225
|
+
kinds: new Map([...kinds].map(([kind, targets]) => [kind, [...targets].map(([module, names]) => ({ module, bindings: [...names].sort() })).sort((a, b) => a.module.localeCompare(b.module))])),
|
|
226
|
+
kindShapes: new Map([...kindShapes].map(([kind, used]) => [kind, [...used].sort()])),
|
|
227
|
+
shapes,
|
|
228
|
+
dynamicImports: parsed.module.dynamicImports.length,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** @param {string} selector */
|
|
233
|
+
const hostRow = selector => {
|
|
234
|
+
const [module, binding] = selector.split('#');
|
|
235
|
+
return { module: module.startsWith('@wildshard/') ? resolveModule(module, CLIENT_PLAN) : module, binding };
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/** The roots one product reaches, from its parsed shard.json and client plan. An unknown kind or section refuses.
|
|
239
|
+
* @param {{ slug: string, sections: readonly string[], kinds: readonly string[] }} product
|
|
240
|
+
* @param {ReturnType<typeof clientPlanRoots>} [plan] */
|
|
241
|
+
export function productRootsFrom(product, plan = clientPlanRoots()) {
|
|
242
|
+
/** @type {{ from: string, module: string, bindings: string[] }[]} */
|
|
243
|
+
const roots = [];
|
|
244
|
+
if (product.kinds.length > 0 && !product.sections.includes('client/plan')) throw new Error(`${product.slug}: client plan kinds without a client/plan section`);
|
|
245
|
+
for (const name of product.sections) {
|
|
246
|
+
if (!Object.hasOwn(SECTION_HOSTS, name)) throw new Error(`${product.slug}: unknown section ${name}`);
|
|
247
|
+
/** @type {Map<string, Set<string>>} */
|
|
248
|
+
const byModule = new Map();
|
|
249
|
+
for (const selector of /** @type {Record<string, string[]>} */ (SECTION_HOSTS)[name]) {
|
|
250
|
+
if (selector === CLIENT_PLAN_ROOT) {
|
|
251
|
+
for (const row of plan.shared) if (!row.typeOnly) roots.push({ from: CLIENT_PLAN_ROOT, module: row.module, bindings: row.bindings });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const { module, binding } = hostRow(selector);
|
|
255
|
+
byModule.set(module, (byModule.get(module) ?? new Set()).add(binding));
|
|
256
|
+
}
|
|
257
|
+
for (const [module, names] of byModule) roots.push({ from: `section:${name}`, module, bindings: [...names].sort() });
|
|
258
|
+
}
|
|
259
|
+
for (const kind of new Set(product.kinds)) {
|
|
260
|
+
const targets = plan.kinds.get(kind);
|
|
261
|
+
if (targets === undefined) throw new Error(`${product.slug}: unknown client/plan kind ${kind}`);
|
|
262
|
+
for (const target of targets) roots.push({ from: `kind:${kind}`, ...target });
|
|
263
|
+
}
|
|
264
|
+
/** @type {Map<string, Set<string>>} */
|
|
265
|
+
const modules = new Map();
|
|
266
|
+
for (const root of roots) {
|
|
267
|
+
const names = modules.get(root.module) ?? new Set();
|
|
268
|
+
for (const name of root.bindings) names.add(name);
|
|
269
|
+
modules.set(root.module, names);
|
|
270
|
+
}
|
|
271
|
+
return { slug: product.slug, sections: [...product.sections], kinds: [...new Set(product.kinds)], roots,
|
|
272
|
+
modules: [...modules].map(([module, names]) => ({ module, bindings: [...names].sort() })).sort((a, b) => a.module.localeCompare(b.module)) };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The file behind a module id, or null for an npm package.
|
|
276
|
+
* @param {string} module @param {string} [root] */
|
|
277
|
+
export function modulePath(module, root = ENGINE_ROOT) {
|
|
278
|
+
if (module.startsWith('npm:')) return null;
|
|
279
|
+
return module.startsWith('@wildshard/format/') ? join(root, 'node_modules', module) : join(root, module);
|
|
280
|
+
}
|
|
281
|
+
/** @param {string} module @param {string} root @param {Set<string>} [seen] @returns {Set<string>} */
|
|
282
|
+
function exportedNames(module, root, seen = new Set()) {
|
|
283
|
+
const names = new Set(), path = modulePath(module, root);
|
|
284
|
+
if (path === null || seen.has(module)) return names;
|
|
285
|
+
seen.add(module);
|
|
286
|
+
const parsed = parseSync(path, readFileSync(path, 'utf8'));
|
|
287
|
+
for (const row of parsed.module.staticExports) for (const entry of row.entries) {
|
|
288
|
+
if (entry.exportName.kind === 'Name') names.add(entry.exportName.name);
|
|
289
|
+
else if (entry.exportName.kind === 'Default') names.add('default');
|
|
290
|
+
else if (entry.moduleRequest !== null && entry.importName.kind === 'AllButDefault') {
|
|
291
|
+
const from = module.startsWith('@wildshard/format/') ? relative(root, path) : module;
|
|
292
|
+
for (const name of exportedNames(resolveModule(entry.moduleRequest.value, from, root), root, seen)) names.add(name);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return names;
|
|
296
|
+
}
|
|
297
|
+
/** Every root that names a missing module or a binding its module does not export, as `module#binding` strings.
|
|
298
|
+
* @param {readonly { module: string, bindings: readonly string[] }[]} rows @param {string} [root] */
|
|
299
|
+
export function unresolvedRoots(rows, root = ENGINE_ROOT) {
|
|
300
|
+
const missing = [];
|
|
301
|
+
for (const { module, bindings } of rows) {
|
|
302
|
+
const path = modulePath(module, root);
|
|
303
|
+
if (path === null) continue;
|
|
304
|
+
if (!existsSync(path)) { missing.push(module); continue; }
|
|
305
|
+
const names = exportedNames(module, root);
|
|
306
|
+
for (const name of bindings) if (name !== '*' && !names.has(name)) missing.push(`${module}#${name}`);
|
|
307
|
+
}
|
|
308
|
+
return missing;
|
|
309
|
+
}
|
|
310
|
+
/** Every SECTION_HOSTS row as a root, for checking the table itself. */
|
|
311
|
+
export const sectionHostRows = () => Object.values(SECTION_HOSTS).flat().filter(selector => selector !== CLIENT_PLAN_ROOT).map(selector => {
|
|
312
|
+
const { module, binding } = hostRow(selector);
|
|
313
|
+
return { module, bindings: [binding] };
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
/** Read a built product dir (`shard.json`, its `client/plan` section file) and list its roots.
|
|
317
|
+
* @param {string} dir @param {ReturnType<typeof clientPlanRoots>} [plan] */
|
|
318
|
+
export function productRoots(dir, plan = clientPlanRoots()) {
|
|
319
|
+
const shard = json(join(dir, 'shard.json'));
|
|
320
|
+
if (!Array.isArray(shard.sections)) throw new Error(`${dir}: shard.json has no sections list`);
|
|
321
|
+
const sections = shard.sections.map((/** @type {any} */ row) => row.name);
|
|
322
|
+
const planRow = shard.sections.find((/** @type {any} */ row) => row.name === 'client/plan');
|
|
323
|
+
const kinds = planRow === undefined ? [] : json(join(dir, planRow.path)).features.map((/** @type {any} */ row) => row.kind);
|
|
324
|
+
const slug = typeof shard.identity?.slug === 'string' ? shard.identity.slug : basename(resolve(dir));
|
|
325
|
+
return productRootsFrom({ slug, sections, kinds }, plan);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
|
|
329
|
+
const dirs = process.argv.slice(2);
|
|
330
|
+
if (dirs.length === 0) { console.error('usage: node scripts/host-ruler/roots.mjs <product-dir>...'); process.exit(2); }
|
|
331
|
+
const plan = clientPlanRoots();
|
|
332
|
+
console.log(JSON.stringify(dirs.map(dir => productRoots(dir, plan)), null, 2));
|
|
333
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ModuleRoot, ProductRoot } from './roots.mjs';
|
|
2
|
+
|
|
3
|
+
export declare const NATIVE_HOSTS: string;
|
|
4
|
+
export declare const NATIVE_ASSEMBLY: string;
|
|
5
|
+
export declare const NATIVE_ASSEMBLY_ROOT: '@native-assembly';
|
|
6
|
+
export declare const NATIVE_ASSEMBLY_FILE: 'server/native-assembly.json';
|
|
7
|
+
export declare const NATIVE_GATED: Readonly<Record<string, readonly string[]>>;
|
|
8
|
+
export interface NativeAssemblyRoots {
|
|
9
|
+
readonly shared: readonly ModuleRoot[];
|
|
10
|
+
readonly hosts: ReadonlyMap<string, { readonly roots: readonly ModuleRoot[]; readonly unplaced: readonly string[] }>;
|
|
11
|
+
readonly unattributed: readonly string[];
|
|
12
|
+
readonly imports: number;
|
|
13
|
+
}
|
|
14
|
+
export interface ServerRoots {
|
|
15
|
+
readonly slug: string;
|
|
16
|
+
readonly hosts: readonly string[];
|
|
17
|
+
readonly roots: readonly ProductRoot[];
|
|
18
|
+
readonly unmeasured: readonly { readonly host: string; readonly reason: string }[];
|
|
19
|
+
readonly modules: readonly ModuleRoot[];
|
|
20
|
+
}
|
|
21
|
+
export function nativeAssemblyRoots(input?: { readonly root?: string; readonly hosts?: { readonly path: string; readonly source: string }; readonly assembly?: { readonly path: string; readonly source: string } }): NativeAssemblyRoots;
|
|
22
|
+
export function serverRootsFrom(product: { readonly slug: string; readonly hosts: readonly string[] | null }, table?: NativeAssemblyRoots): ServerRoots;
|
|
23
|
+
export function productServerRoots(dir: string, table?: NativeAssemblyRoots): ServerRoots;
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// HOST-RULER HR2 (meta docs/plans/HOST-RULER-PLAN.md): the server roots one built product reaches through its
|
|
3
|
+
// `server/native-assembly.json`. nativeAssemblyHosts.ts has no table: `prepareAssemblyFeature` is one
|
|
4
|
+
// `switch (row.host)` over every native host id, and the file statically imports every host. A product's declared host
|
|
5
|
+
// ids root only the imported bindings their own cases use (directly or through the file's helper functions), never the
|
|
6
|
+
// whole import list. A case the reader cannot attribute (a name it cannot place, or a local that shadows an import or a
|
|
7
|
+
// helper) and a host id with no case print as unmeasured, never as shared.
|
|
8
|
+
// nativeAssembly.ts's own value imports are one shared root, `@native-assembly`, reached by every product with a native
|
|
9
|
+
// assembly, except the bindings it calls only for one declared host id (NATIVE_GATED), which root under that id.
|
|
10
|
+
// Usage: node scripts/host-ruler/server-roots.mjs <product-dir>... (a dir holding shard.json, e.g. shard-x/out/<slug>)
|
|
11
|
+
import { readFileSync } from 'node:fs';
|
|
12
|
+
import { basename, join, resolve } from 'node:path';
|
|
13
|
+
import { parseSync } from 'vite';
|
|
14
|
+
import { ENGINE_ROOT, resolveModule } from './roots.mjs';
|
|
15
|
+
|
|
16
|
+
export const NATIVE_HOSTS = 'src/server/game/shardfile/nativeAssemblyHosts.ts';
|
|
17
|
+
export const NATIVE_ASSEMBLY = 'src/server/game/shardfile/nativeAssembly.ts';
|
|
18
|
+
export const NATIVE_ASSEMBLY_ROOT = '@native-assembly';
|
|
19
|
+
export const NATIVE_ASSEMBLY_FILE = 'server/native-assembly.json';
|
|
20
|
+
/** nativeAssembly.ts bindings called only when the plan declares one host id (`plan.features.find(row => row.host ===
|
|
21
|
+
* 'encounter.patrol')` reads the patrol's encounter intake). The test checks each is a value import there. */
|
|
22
|
+
export const NATIVE_GATED = Object.freeze({ 'encounter.patrol': ['readPatrolIntake', 'readSlotIntake', 'readWindIntake', 'withEncounters'] });
|
|
23
|
+
/** Names a case may use that no file declares. Anything else unplaced makes the case unmeasured. */
|
|
24
|
+
const GLOBALS = new Set(['undefined', 'Error', 'TypeError', 'Promise', 'Map', 'Set', 'Object', 'Array', 'JSON', 'Math', 'Number', 'String',
|
|
25
|
+
'Boolean', 'structuredClone', 'Float32Array', 'Uint8Array', 'TextDecoder', 'Infinity', 'NaN', 'console']);
|
|
26
|
+
const TYPE_KEYS = new Set(['typeAnnotation', 'typeArguments', 'typeParameters', 'returnType', 'superTypeArguments']);
|
|
27
|
+
const VALUE_TS = new Set(['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion', 'TSInstantiationExpression']);
|
|
28
|
+
/** TS nodes that emit runtime code: the reader refuses them rather than skip them as types. */
|
|
29
|
+
const VALUE_DECLARATIONS = new Set(['TSEnumDeclaration', 'TSModuleDeclaration', 'TSImportEqualsDeclaration', 'TSExportAssignment']);
|
|
30
|
+
|
|
31
|
+
/** @param {string} path @param {string} source */
|
|
32
|
+
const parse = (path, source) => {
|
|
33
|
+
const parsed = parseSync(path, source);
|
|
34
|
+
if (parsed.errors.length > 0) throw new Error(`${path}: parse errors`);
|
|
35
|
+
return parsed;
|
|
36
|
+
};
|
|
37
|
+
/** Value imports of one parsed file: local name -> { module, binding }. Type-only names never run.
|
|
38
|
+
* @param {any} parsed @param {string} from @param {string} root */
|
|
39
|
+
function valueImports(parsed, from, root) {
|
|
40
|
+
/** @type {Map<string, { module: string, binding: string }>} */
|
|
41
|
+
const names = new Map();
|
|
42
|
+
for (const row of parsed.module.staticImports) {
|
|
43
|
+
const module = resolveModule(row.moduleRequest.value, from, root);
|
|
44
|
+
if (row.entries.length === 0) throw new Error(`${from}: side-effect import ${row.moduleRequest.value} is no binding a host can be charged`);
|
|
45
|
+
for (const entry of row.entries) {
|
|
46
|
+
if (entry.isType) continue;
|
|
47
|
+
const binding = entry.importName.kind === 'Name' ? entry.importName.name : entry.importName.kind === 'Default' ? 'default' : '*';
|
|
48
|
+
names.set(entry.localName.value, { module, binding });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return names;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Names a binding pattern declares, and the references inside it (defaults, computed keys).
|
|
55
|
+
* @param {any} node @param {Set<string>} decls @param {Set<string>} refs */
|
|
56
|
+
function declare(node, decls, refs) {
|
|
57
|
+
if (node === null || node === undefined) return;
|
|
58
|
+
if (node.type === 'Identifier') decls.add(node.name);
|
|
59
|
+
else if (node.type === 'ObjectPattern') for (const p of node.properties) {
|
|
60
|
+
if (p.type === 'RestElement') declare(p.argument, decls, refs);
|
|
61
|
+
else { if (p.computed) collect(p.key, refs, decls); declare(p.value, decls, refs); }
|
|
62
|
+
}
|
|
63
|
+
else if (node.type === 'ArrayPattern') for (const e of node.elements) declare(e, decls, refs);
|
|
64
|
+
else if (node.type === 'RestElement') declare(node.argument, decls, refs);
|
|
65
|
+
else if (node.type === 'AssignmentPattern') { declare(node.left, decls, refs); collect(node.right, refs, decls); }
|
|
66
|
+
else throw new Error(`unread binding pattern ${node.type}`);
|
|
67
|
+
}
|
|
68
|
+
/** Every identifier a subtree reads (refs) and every name it declares (decls). Type positions are skipped: a type
|
|
69
|
+
* never runs. Scopes are flattened: a declared name anywhere in the subtree counts for all of it.
|
|
70
|
+
* @param {any} node @param {Set<string>} refs @param {Set<string>} decls */
|
|
71
|
+
function collect(node, refs, decls) {
|
|
72
|
+
if (node === null || typeof node !== 'object') return;
|
|
73
|
+
if (Array.isArray(node)) { for (const child of node) collect(child, refs, decls); return; }
|
|
74
|
+
if (typeof node.type !== 'string') return;
|
|
75
|
+
switch (node.type) {
|
|
76
|
+
case 'Identifier': refs.add(node.name); return;
|
|
77
|
+
case 'MemberExpression': collect(node.object, refs, decls); if (node.computed) collect(node.property, refs, decls); return;
|
|
78
|
+
case 'Property': case 'PropertyDefinition': case 'MethodDefinition':
|
|
79
|
+
if (node.computed) collect(node.key, refs, decls); collect(node.value, refs, decls); return;
|
|
80
|
+
case 'VariableDeclarator': declare(node.id, decls, refs); collect(node.init, refs, decls); return;
|
|
81
|
+
case 'FunctionDeclaration': case 'FunctionExpression': case 'ArrowFunctionExpression':
|
|
82
|
+
if (node.id) decls.add(node.id.name);
|
|
83
|
+
for (const param of node.params) declare(param.type === 'TSParameterProperty' ? param.parameter : param, decls, refs);
|
|
84
|
+
collect(node.body, refs, decls); return;
|
|
85
|
+
case 'CatchClause': declare(node.param, decls, refs); collect(node.body, refs, decls); return;
|
|
86
|
+
case 'LabeledStatement': collect(node.body, refs, decls); return;
|
|
87
|
+
case 'BreakStatement': case 'ContinueStatement': return;
|
|
88
|
+
case 'ImportExpression': throw new Error('an import() the reader cannot attribute');
|
|
89
|
+
default:
|
|
90
|
+
}
|
|
91
|
+
if (VALUE_DECLARATIONS.has(node.type)) throw new Error(`a ${node.type} the reader cannot attribute`);
|
|
92
|
+
if (node.type.startsWith('TS')) { if (VALUE_TS.has(node.type)) collect(node.expression, refs, decls); return; }
|
|
93
|
+
for (const [key, value] of Object.entries(node)) if (!TYPE_KEYS.has(key) && value !== null && typeof value === 'object') collect(value, refs, decls);
|
|
94
|
+
}
|
|
95
|
+
/** @param {any} node */
|
|
96
|
+
const scan = node => { const refs = new Set(), decls = new Set(); collect(node, refs, decls); return { refs, decls }; };
|
|
97
|
+
|
|
98
|
+
/** Read nativeAssemblyHosts.ts and nativeAssembly.ts statically: per host id, the imported bindings its case uses.
|
|
99
|
+
* @param {{ root?: string, hosts?: { path: string, source: string }, assembly?: { path: string, source: string } }} [input] */
|
|
100
|
+
export function nativeAssemblyRoots(input = {}) {
|
|
101
|
+
const root = input.root ?? ENGINE_ROOT;
|
|
102
|
+
const hostsPath = input.hosts?.path ?? NATIVE_HOSTS, hostsSource = input.hosts?.source ?? readFileSync(join(root, NATIVE_HOSTS), 'utf8');
|
|
103
|
+
const parsed = parse(hostsPath, hostsSource), imports = valueImports(parsed, hostsPath, root);
|
|
104
|
+
/** @type {Map<string, any>} */
|
|
105
|
+
const helpers = new Map();
|
|
106
|
+
/** @type {any} */
|
|
107
|
+
let dispatcher = null;
|
|
108
|
+
const topLevel = { refs: new Set(), decls: new Set() };
|
|
109
|
+
for (const statement of parsed.program.body) {
|
|
110
|
+
const node = statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration' ? statement.declaration : statement;
|
|
111
|
+
if (node === null || node.type === 'ImportDeclaration') continue;
|
|
112
|
+
if (VALUE_DECLARATIONS.has(node.type)) throw new Error(`${hostsPath}: a top-level ${node.type} the reader cannot attribute`);
|
|
113
|
+
if (node.type.startsWith('TS')) continue;
|
|
114
|
+
if (node.type === 'FunctionDeclaration') {
|
|
115
|
+
if (node.id.name === 'prepareAssemblyFeature') dispatcher = node; else helpers.set(node.id.name, node);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (node.type === 'VariableDeclaration') {
|
|
119
|
+
for (const d of node.declarations) {
|
|
120
|
+
const init = d.init?.type === 'TSAsExpression' || d.init?.type === 'TSSatisfiesExpression' ? d.init.expression : d.init;
|
|
121
|
+
// A named top-level value (function or not) is charged to the cases that read it, like a helper function.
|
|
122
|
+
if (d.id.type === 'Identifier' && init !== null && init !== undefined) helpers.set(d.id.name, init);
|
|
123
|
+
else collect(d, topLevel.refs, topLevel.decls);
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
collect(node, topLevel.refs, topLevel.decls);
|
|
128
|
+
}
|
|
129
|
+
if (dispatcher === null) throw new Error(`${hostsPath}: no prepareAssemblyFeature`);
|
|
130
|
+
const switches = dispatcher.body.body.filter((/** @type {any} */ s) => s.type === 'SwitchStatement');
|
|
131
|
+
const [table] = switches;
|
|
132
|
+
if (switches.length !== 1 || table.discriminant.type !== 'MemberExpression' || table.discriminant.property.name !== 'host') throw new Error(`${hostsPath}: prepareAssemblyFeature has no one switch (row.host)`);
|
|
133
|
+
// Names in scope for every case: the dispatcher's parameters and the statements before its switch.
|
|
134
|
+
const preamble = { refs: new Set(), decls: new Set() };
|
|
135
|
+
for (const param of dispatcher.params) declare(param, preamble.decls, preamble.refs);
|
|
136
|
+
for (const statement of dispatcher.body.body) if (statement !== table) collect(statement, preamble.refs, preamble.decls);
|
|
137
|
+
/** @param {string} name */
|
|
138
|
+
const shadows = name => imports.has(name) || helpers.has(name);
|
|
139
|
+
|
|
140
|
+
/** Per helper: the imports it reaches (through other helpers too), and the names it could not place. */
|
|
141
|
+
/** @type {Map<string, { bindings: Set<string>, unplaced: Set<string> }>} */
|
|
142
|
+
const helperReach = new Map();
|
|
143
|
+
// One object, so the two mutually recursive walkers can name each other.
|
|
144
|
+
const reader = {
|
|
145
|
+
/** @param {string} name @param {Set<string>} stack @returns {{ bindings: Set<string>, unplaced: Set<string> }} */
|
|
146
|
+
helper(name, stack) {
|
|
147
|
+
const known = helperReach.get(name);
|
|
148
|
+
if (known !== undefined) return known;
|
|
149
|
+
// No helper recurses today; a cycle would cache a partial reach, so it refuses.
|
|
150
|
+
if (stack.has(name)) throw new Error(`${hostsPath}: helper ${name} is recursive, the reader cannot attribute it`);
|
|
151
|
+
/** @type {{ bindings: Set<string>, unplaced: Set<string> }} */
|
|
152
|
+
const out = { bindings: new Set(), unplaced: new Set() };
|
|
153
|
+
const own = scan(helpers.get(name));
|
|
154
|
+
stack.add(name);
|
|
155
|
+
for (const decl of own.decls) if (decl !== name && shadows(decl)) out.unplaced.add(`${decl} (shadows an import or helper in ${name})`);
|
|
156
|
+
for (const ref of own.refs) reader.place(ref, own.decls, out, stack);
|
|
157
|
+
stack.delete(name);
|
|
158
|
+
helperReach.set(name, out);
|
|
159
|
+
return out;
|
|
160
|
+
},
|
|
161
|
+
/** @param {string} ref @param {Set<string>} decls @param {{ bindings: Set<string>, unplaced: Set<string> }} out @param {Set<string>} stack */
|
|
162
|
+
place(ref, decls, out, stack) {
|
|
163
|
+
if (imports.has(ref)) out.bindings.add(ref);
|
|
164
|
+
else if (helpers.has(ref)) { const reached = reader.helper(ref, stack); for (const b of reached.bindings) out.bindings.add(b); for (const u of reached.unplaced) out.unplaced.add(u); }
|
|
165
|
+
else if (!decls.has(ref) && !preamble.decls.has(ref) && !topLevel.decls.has(ref) && !GLOBALS.has(ref)) out.unplaced.add(ref);
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
const reachOf = (/** @type {any} */ node, /** @type {Set<string>} */ inScope) => {
|
|
169
|
+
const own = scan(node), out = { bindings: new Set(), unplaced: new Set() };
|
|
170
|
+
for (const decl of own.decls) if (shadows(decl)) out.unplaced.add(`${decl} (shadows an import or helper)`);
|
|
171
|
+
const decls = new Set([...own.decls, ...inScope]);
|
|
172
|
+
for (const ref of own.refs) reader.place(ref, decls, out, new Set());
|
|
173
|
+
return out;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** @type {Map<string, { bindings: Set<string>, unplaced: Set<string> }>} */
|
|
177
|
+
const cases = new Map();
|
|
178
|
+
/** @type {string[]} */
|
|
179
|
+
let pending = [];
|
|
180
|
+
for (const branch of table.cases) {
|
|
181
|
+
if (branch.test === null) { // default: an unknown id throws at prepare time.
|
|
182
|
+
if (pending.length > 0) throw new Error(`${hostsPath}: ${pending.join(', ')} fall through to default`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (branch.test.type !== 'Literal' || typeof branch.test.value !== 'string') throw new Error(`${hostsPath}: a case with a non-literal host id`);
|
|
186
|
+
pending.push(branch.test.value);
|
|
187
|
+
if (branch.consequent.length === 0) continue; // falls through to the next case's body.
|
|
188
|
+
const reach = reachOf(branch.consequent, new Set());
|
|
189
|
+
for (const id of pending) {
|
|
190
|
+
if (cases.has(id)) throw new Error(`${hostsPath}: host id ${id} has two cases`);
|
|
191
|
+
cases.set(id, reach);
|
|
192
|
+
}
|
|
193
|
+
pending = [];
|
|
194
|
+
}
|
|
195
|
+
const sharedHosts = reachOf([...preamble.refs].map(name => ({ type: 'Identifier', name })), new Set());
|
|
196
|
+
for (const ref of topLevel.refs) reader.place(ref, topLevel.decls, sharedHosts, new Set());
|
|
197
|
+
if (sharedHosts.unplaced.size > 0) throw new Error(`${hostsPath}: unplaced names outside the switch: ${[...sharedHosts.unplaced].join(', ')}`);
|
|
198
|
+
|
|
199
|
+
// nativeAssembly.ts: its value imports are the shared root, but for the bindings gated on one host id.
|
|
200
|
+
const assemblyPath = input.assembly?.path ?? NATIVE_ASSEMBLY, assemblySource = input.assembly?.source ?? readFileSync(join(root, NATIVE_ASSEMBLY), 'utf8');
|
|
201
|
+
const assemblyImports = valueImports(parse(assemblyPath, assemblySource), assemblyPath, root);
|
|
202
|
+
/** @type {Map<string, Set<string>>} */
|
|
203
|
+
const gated = new Map();
|
|
204
|
+
for (const [id, names] of Object.entries(NATIVE_GATED)) for (const name of names) {
|
|
205
|
+
if (!assemblyImports.has(name)) throw new Error(`${assemblyPath}: NATIVE_GATED names ${name}, not a value import there`);
|
|
206
|
+
gated.set(name, (gated.get(name) ?? new Set()).add(id));
|
|
207
|
+
}
|
|
208
|
+
/** @param {Map<string, { module: string, binding: string }>} from @param {Iterable<string>} names */
|
|
209
|
+
const group = (from, names) => {
|
|
210
|
+
/** @type {Map<string, Set<string>>} */
|
|
211
|
+
const byModule = new Map();
|
|
212
|
+
for (const name of names) { const { module, binding } = /** @type {{ module: string, binding: string }} */ (from.get(name)); byModule.set(module, (byModule.get(module) ?? new Set()).add(binding)); }
|
|
213
|
+
return [...byModule].map(([module, bindings]) => ({ module, bindings: [...bindings].sort() })).sort((a, b) => a.module.localeCompare(b.module));
|
|
214
|
+
};
|
|
215
|
+
const attributed = new Set([...cases.values()].flatMap(reach => Array.from(reach.bindings)).concat(Array.from(sharedHosts.bindings)));
|
|
216
|
+
return {
|
|
217
|
+
// The dispatcher itself is the table, not a user (HA0 a): its cases are the per-host roots, so it is not shared.
|
|
218
|
+
shared: [...group(assemblyImports, [...assemblyImports.keys()].filter(name => !gated.has(name) && assemblyImports.get(name)?.module !== hostsPath)), ...group(imports, sharedHosts.bindings)],
|
|
219
|
+
hosts: new Map([...cases].sort(([a], [b]) => a.localeCompare(b)).map(([id, reach]) => [id, {
|
|
220
|
+
roots: [...group(imports, reach.bindings), ...group(assemblyImports, [...gated].filter(([, ids]) => ids.has(id)).map(([name]) => name))],
|
|
221
|
+
unplaced: [...reach.unplaced].sort(),
|
|
222
|
+
}])),
|
|
223
|
+
/** Imported value bindings no case, helper or shared code reaches: dead imports, or a use the reader missed. */
|
|
224
|
+
unattributed: [...imports.keys()].filter(name => !attributed.has(name)).sort(),
|
|
225
|
+
imports: imports.size,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The server roots one product reaches from its declared host ids. An id with no case, or a case the reader could not
|
|
230
|
+
* attribute, is listed in `unmeasured` and roots nothing.
|
|
231
|
+
* @param {{ slug: string, hosts: readonly string[] | null }} product @param {ReturnType<typeof nativeAssemblyRoots>} [table] */
|
|
232
|
+
export function serverRootsFrom(product, table = nativeAssemblyRoots()) {
|
|
233
|
+
/** @type {{ from: string, module: string, bindings: string[] }[]} */
|
|
234
|
+
const roots = [];
|
|
235
|
+
/** @type {{ host: string, reason: string }[]} */
|
|
236
|
+
const unmeasured = [];
|
|
237
|
+
const hosts = product.hosts === null ? [] : [...new Set(product.hosts)];
|
|
238
|
+
if (product.hosts !== null) for (const row of table.shared) roots.push({ from: NATIVE_ASSEMBLY_ROOT, ...row, bindings: [...row.bindings] });
|
|
239
|
+
for (const id of hosts) {
|
|
240
|
+
const entry = table.hosts.get(id);
|
|
241
|
+
if (entry === undefined) { unmeasured.push({ host: id, reason: `no case in ${NATIVE_HOSTS}` }); continue; }
|
|
242
|
+
if (entry.unplaced.length > 0) { unmeasured.push({ host: id, reason: `unplaced names: ${entry.unplaced.join(', ')}` }); continue; }
|
|
243
|
+
for (const row of entry.roots) roots.push({ from: `host:${id}`, ...row, bindings: [...row.bindings] });
|
|
244
|
+
}
|
|
245
|
+
/** @type {Map<string, Set<string>>} */
|
|
246
|
+
const modules = new Map();
|
|
247
|
+
for (const row of roots) { const names = modules.get(row.module) ?? new Set(); for (const name of row.bindings) names.add(name); modules.set(row.module, names); }
|
|
248
|
+
return { slug: product.slug, hosts, roots, unmeasured,
|
|
249
|
+
modules: [...modules].map(([module, names]) => ({ module, bindings: [...names].sort() })).sort((a, b) => a.module.localeCompare(b.module)) };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Read a built product dir: shard.json's `admission.server` row named `server/native-assembly.json` (as the engine's
|
|
253
|
+
* product readers do, `productData.ts`), then its features' host ids.
|
|
254
|
+
* A product without one reaches no server roots.
|
|
255
|
+
* @param {string} dir @param {ReturnType<typeof nativeAssemblyRoots>} [table] */
|
|
256
|
+
export function productServerRoots(dir, table = nativeAssemblyRoots()) {
|
|
257
|
+
const shard = JSON.parse(readFileSync(join(dir, 'shard.json'), 'utf8'));
|
|
258
|
+
const slug = typeof shard.identity?.slug === 'string' ? shard.identity.slug : basename(resolve(dir));
|
|
259
|
+
const row = (Array.isArray(shard.admission?.server) ? shard.admission.server : []).find((/** @type {any} */ file) => file.name === NATIVE_ASSEMBLY_FILE);
|
|
260
|
+
if (row === undefined) return serverRootsFrom({ slug, hosts: null }, table);
|
|
261
|
+
const plan = JSON.parse(readFileSync(join(dir, row.path), 'utf8'));
|
|
262
|
+
if (!Array.isArray(plan.features)) throw new Error(`${dir}: ${NATIVE_ASSEMBLY_FILE} has no features list`);
|
|
263
|
+
plan.features.forEach((/** @type {any} */ feature, /** @type {number} */ i) => { if (typeof feature?.host !== 'string') throw new Error(`${dir}: feature ${i} has no host`); });
|
|
264
|
+
return serverRootsFrom({ slug, hosts: plan.features.map((/** @type {any} */ feature) => feature.host) }, table);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
|
|
268
|
+
const dirs = process.argv.slice(2);
|
|
269
|
+
if (dirs.length === 0) { console.error('usage: node scripts/host-ruler/server-roots.mjs <product-dir>...'); process.exit(2); }
|
|
270
|
+
const table = nativeAssemblyRoots();
|
|
271
|
+
console.log(JSON.stringify(dirs.map(dir => productServerRoots(dir, table)), null, 2));
|
|
272
|
+
}
|