castle-web-cli 0.4.229 → 0.4.230
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/dist/agent-prompts.d.ts +2 -0
- package/dist/agent-prompts.js +16 -8
- package/dist/agent.d.ts +2 -0
- package/dist/agent.js +21 -21
- package/dist/api.d.ts +28 -2
- package/dist/api.js +74 -16
- package/dist/castle-host/host.d.ts +91 -0
- package/dist/castle-host/host.js +779 -3
- package/dist/castleJson.d.ts +44 -0
- package/dist/castleJson.js +131 -0
- package/dist/check.js +27 -1
- package/dist/contentPack.d.ts +49 -0
- package/dist/contentPack.js +273 -0
- package/dist/devExperiments.d.ts +21 -0
- package/dist/devExperiments.js +139 -0
- package/dist/devHub.d.ts +55 -0
- package/dist/devHub.js +187 -0
- package/dist/devSessionChild.js +3 -1
- package/dist/devSessionServer.d.ts +14 -1
- package/dist/devSessionServer.js +229 -44
- package/dist/experimentAssignment.d.ts +15 -0
- package/dist/experimentAssignment.js +41 -0
- package/dist/importCheckHook.d.ts +40 -0
- package/dist/importCheckHook.js +171 -0
- package/dist/importRegression.d.ts +15 -0
- package/dist/importRegression.js +100 -0
- package/dist/importTrust.d.ts +2 -0
- package/dist/importTrust.js +27 -0
- package/dist/importUpdateHook.d.ts +18 -0
- package/dist/importUpdateHook.js +31 -8
- package/dist/importUpdateHookRunner.js +19 -7
- package/dist/imports.d.ts +16 -0
- package/dist/imports.js +141 -31
- package/dist/index.js +3 -1
- package/dist/init.d.ts +3 -0
- package/dist/init.js +125 -8
- package/dist/install.js +4 -1
- package/dist/localPaths.js +4 -0
- package/dist/login.js +2 -2
- package/dist/platformDoc.js +3 -8
- package/dist/playPagePolicy.js +3 -1
- package/dist/remix.js +5 -0
- package/dist/routerTaskReport.d.ts +28 -0
- package/dist/routerTaskReport.js +56 -0
- package/dist/save-deck.d.ts +18 -0
- package/dist/save-deck.js +142 -6
- package/dist/serve.d.ts +8 -0
- package/dist/serve.js +94 -13
- package/dist/serverBundle.d.ts +1 -1
- package/dist/serverBundle.js +5 -1
- package/dist/webSourceSync.d.ts +2 -0
- package/dist/webSourceSync.js +2 -0
- package/kits/base/CLAUDE.md +2 -3
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +258 -52
- package/kits/base/sdk/agent.js +4 -4
- package/kits/base/sdk/avatar.d.ts +12 -0
- package/kits/base/sdk/avatar.js +23 -0
- package/kits/base/sdk/castle.d.ts +5 -0
- package/kits/base/sdk/castle.js +3 -0
- package/kits/base/sdk/commands.d.ts +208 -0
- package/kits/base/sdk/commands.js +16 -0
- package/kits/base/sdk/context.d.ts +6 -0
- package/kits/base/sdk/experiments.d.ts +15 -0
- package/kits/base/sdk/experiments.js +83 -0
- package/kits/base/sdk/hub.d.ts +85 -0
- package/kits/base/sdk/hub.js +107 -0
- package/kits/base/sdk/multiplayer.d.ts +45 -1
- package/kits/base/sdk/multiplayer.js +106 -4
- package/kits/base/sdk/server/hub.d.ts +169 -0
- package/kits/base/sdk/server/hub.js +125 -0
- package/kits/base/sdk/server/platformHandle.d.ts +42 -1
- package/kits/base/sdk/server/storage.d.ts +55 -2
- package/kits/base/sdk/server/wrapper.d.ts +32 -2
- package/kits/base/sdk/server/wrapper.js +90 -11
- package/kits/base/sdk/transport.d.ts +2 -1
- package/kits/base/sdk/transport.js +13 -1
- package/kits/hub-game/.prettierrc +5 -0
- package/kits/hub-game/CLAUDE.md +146 -0
- package/kits/hub-game/blueprints/avatar-0.scene +28 -0
- package/kits/hub-game/blueprints/avatar-1.scene +28 -0
- package/kits/hub-game/blueprints/avatar-2.scene +28 -0
- package/kits/hub-game/blueprints/avatar-3.scene +28 -0
- package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
- package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
- package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
- package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
- package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
- package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
- package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
- package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
- package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
- package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
- package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
- package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
- package/kits/hub-game/castle.json +96 -0
- package/kits/hub-game/code/client/attention.js +133 -0
- package/kits/hub-game/code/client/avatar.js +288 -0
- package/kits/hub-game/code/client/cabinets.js +90 -0
- package/kits/hub-game/code/client/chat.js +135 -0
- package/kits/hub-game/code/client/chrome.js +1001 -0
- package/kits/hub-game/code/client/doorFrame.js +15 -0
- package/kits/hub-game/code/client/firstJoin.js +14 -0
- package/kits/hub-game/code/client/grab.js +241 -0
- package/kits/hub-game/code/client/hookLayer.js +230 -0
- package/kits/hub-game/code/client/idle.js +326 -0
- package/kits/hub-game/code/client/keys.js +48 -0
- package/kits/hub-game/code/client/pack.js +232 -0
- package/kits/hub-game/code/client/packFormat.js +397 -0
- package/kits/hub-game/code/client/say.js +127 -0
- package/kits/hub-game/code/client/sha256.js +80 -0
- package/kits/hub-game/code/client/sound.js +147 -0
- package/kits/hub-game/code/client/state.js +131 -0
- package/kits/hub-game/code/client/talk.js +259 -0
- package/kits/hub-game/code/client/together.js +365 -0
- package/kits/hub-game/code/client/wear.js +149 -0
- package/kits/hub-game/code/server/actors.js +627 -0
- package/kits/hub-game/code/server/blocks.js +103 -0
- package/kits/hub-game/code/server/cabinets.js +309 -0
- package/kits/hub-game/code/server/game.js +137 -0
- package/kits/hub-game/code/server/grab.js +247 -0
- package/kits/hub-game/code/server/history.js +96 -0
- package/kits/hub-game/code/server/hub.js +1904 -0
- package/kits/hub-game/code/server/idle.js +412 -0
- package/kits/hub-game/code/server/index.js +64 -0
- package/kits/hub-game/code/server/labels.js +59 -0
- package/kits/hub-game/code/server/manifest.js +527 -0
- package/kits/hub-game/code/server/npcs.js +745 -0
- package/kits/hub-game/code/server/party.js +381 -0
- package/kits/hub-game/code/server/place.js +43 -0
- package/kits/hub-game/code/server/say.js +83 -0
- package/kits/hub-game/code/server/wear.js +142 -0
- package/kits/hub-game/code/systems/hub.js +2230 -0
- package/kits/hub-game/docs/content-pack.md +151 -0
- package/kits/hub-game/docs/contract.md +1139 -0
- package/kits/hub-game/docs/style.md +137 -0
- package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
- package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
- package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
- package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
- package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
- package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
- package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
- package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
- package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
- package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
- package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
- package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
- package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
- package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
- package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
- package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
- package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
- package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
- package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
- package/kits/hub-game/eslint.config.js +20 -0
- package/kits/hub-game/fonts.generated.js +9 -0
- package/kits/hub-game/index.html +22 -0
- package/kits/hub-game/main.jsx +6 -0
- package/kits/hub-game/models/avatar-0.pxmodel +21 -0
- package/kits/hub-game/models/avatar-1.pxmodel +24 -0
- package/kits/hub-game/models/avatar-2.pxmodel +27 -0
- package/kits/hub-game/models/avatar-3.pxmodel +22 -0
- package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
- package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
- package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
- package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
- package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
- package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
- package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
- package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
- package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
- package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
- package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
- package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
- package/kits/hub-game/package-lock.json +365 -0
- package/kits/hub-game/package.json +32 -0
- package/kits/hub-game/scenes/main.scene +318 -0
- package/kits/hub-game/scripts/check.mjs +339 -0
- package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
- package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
- package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
- package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
- package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
- package/kits/hub-game/scripts/pack.mjs +192 -0
- package/kits/hub-game/scripts/test-actors.mjs +666 -0
- package/kits/hub-game/scripts/test-attention.mjs +103 -0
- package/kits/hub-game/scripts/test-avatar.mjs +472 -0
- package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
- package/kits/hub-game/scripts/test-blocks.mjs +351 -0
- package/kits/hub-game/scripts/test-chat.mjs +98 -0
- package/kits/hub-game/scripts/test-classic.mjs +590 -0
- package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
- package/kits/hub-game/scripts/test-door.mjs +56 -0
- package/kits/hub-game/scripts/test-grab.mjs +331 -0
- package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
- package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
- package/kits/hub-game/scripts/test-idle.mjs +518 -0
- package/kits/hub-game/scripts/test-interest.mjs +413 -0
- package/kits/hub-game/scripts/test-keys.mjs +50 -0
- package/kits/hub-game/scripts/test-manifest.mjs +224 -0
- package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
- package/kits/hub-game/scripts/test-npcs.mjs +714 -0
- package/kits/hub-game/scripts/test-pack.mjs +424 -0
- package/kits/hub-game/scripts/test-party.mjs +286 -0
- package/kits/hub-game/scripts/test-say.mjs +149 -0
- package/kits/hub-game/scripts/test-together.mjs +183 -0
- package/kits/hub-game/theme.style +3 -0
- package/kits/multiplayer-3d/castle.json +5 -5
- package/kits/multiplayer-3d/code/client/avatars.js +101 -1
- package/kits/multiplayer-3d/code/server/players.js +4 -1
- package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
- package/kits/multiplayer-3d/code/server/world.js +20 -7
- package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
- package/kits/physics-2d/castle.json +2 -2
- package/kits/physics-2d/engine/art.js +13 -0
- package/kits/physics-2d/engine/assets.js +4 -2
- package/kits/physics-2d/engine/scene.js +25 -5
- package/kits/physics-3d/CLAUDE.md +6 -1
- package/kits/physics-3d/castle.json +3 -3
- package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
- package/kits/physics-3d/engine3d/artobjects.js +2 -2
- package/kits/physics-3d/engine3d/materials.js +29 -1
- package/kits/physics-3d/engine3d/world3d.js +65 -1
- package/kits/physics-3d/systems/physics3d.js +5 -2
- package/kits/real-time/castle.json +2 -2
- package/kits/real-time/code/client/connection.js +77 -7
- package/kits/real-time/code/client/gameHooks.js +63 -3
- package/kits/real-time/code/client/messages.js +7 -0
- package/kits/real-time/code/server/gameHooks.js +24 -0
- package/kits/real-time/code/server/session.js +390 -22
- package/package.json +2 -2
package/dist/devSessionServer.js
CHANGED
|
@@ -11,6 +11,7 @@ import { OutboundFrameMeter } from './devSessionFrameBudget.js';
|
|
|
11
11
|
import { runDevStorageOperation } from './devSessionStorage.js';
|
|
12
12
|
import { rawDataToString } from './rawData.js';
|
|
13
13
|
import { bundleServerModule } from './serverBundle.js';
|
|
14
|
+
import { devDeckCastleJsons, devDeckSessionKey } from './contentPack.js';
|
|
14
15
|
const PROTOCOL_VERSION = 1;
|
|
15
16
|
const MAX_CLIENT_FRAME_BYTES = 16 * 1024;
|
|
16
17
|
// Mirrors the host-agent's server-to-client broadcast cap.
|
|
@@ -22,8 +23,15 @@ const NONCE_TTL_MS = 60_000;
|
|
|
22
23
|
const INVALID_RECONNECT_CLOSE_CODE = 4003;
|
|
23
24
|
const CHILD_READY_TIMEOUT_MS = 15_000;
|
|
24
25
|
const CHILD_STOP_GRACE_MS = 2_000;
|
|
26
|
+
// A named session nobody is connected to is stopped after this long, the way the
|
|
27
|
+
// platform tears down an empty session; its next join starts it fresh.
|
|
28
|
+
const NAMED_SESSION_IDLE_MS = 60_000;
|
|
29
|
+
const DEFAULT_SESSION_ID = 'dev';
|
|
30
|
+
export function devSessionIdFor(key) {
|
|
31
|
+
return key === null ? DEFAULT_SESSION_ID : `${DEFAULT_SESSION_ID}:${key}`;
|
|
32
|
+
}
|
|
25
33
|
export async function startDevSessionServer(opts) {
|
|
26
|
-
const server = new
|
|
34
|
+
const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS);
|
|
27
35
|
try {
|
|
28
36
|
await server.start();
|
|
29
37
|
return server;
|
|
@@ -33,6 +41,112 @@ export async function startDevSessionServer(opts) {
|
|
|
33
41
|
throw error;
|
|
34
42
|
}
|
|
35
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Owns the one port `/__castle/mp` is proxied to, and hands each upgrade to the
|
|
46
|
+
* session that minted its nonce, owns its reconnect token, or spawned the child
|
|
47
|
+
* presenting its boot token. The default session ('dev') always runs; a named
|
|
48
|
+
* key's session runs while anyone is in it.
|
|
49
|
+
*/
|
|
50
|
+
class DevSessionRouter {
|
|
51
|
+
projectDir;
|
|
52
|
+
log;
|
|
53
|
+
idleMs;
|
|
54
|
+
sessionId = DEFAULT_SESSION_ID;
|
|
55
|
+
port = 0;
|
|
56
|
+
server = http.createServer((_req, res) => res.writeHead(404).end());
|
|
57
|
+
defaultSession;
|
|
58
|
+
named = new Map();
|
|
59
|
+
closed = false;
|
|
60
|
+
constructor(projectDir, log, idleMs) {
|
|
61
|
+
this.projectDir = projectDir;
|
|
62
|
+
this.log = log;
|
|
63
|
+
this.idleMs = idleMs;
|
|
64
|
+
this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { });
|
|
65
|
+
this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
|
|
66
|
+
}
|
|
67
|
+
async start() {
|
|
68
|
+
await new Promise((resolve, reject) => {
|
|
69
|
+
this.server.once('error', reject);
|
|
70
|
+
this.server.listen(0, '127.0.0.1', () => {
|
|
71
|
+
this.server.off('error', reject);
|
|
72
|
+
const address = this.server.address();
|
|
73
|
+
if (!address || typeof address === 'string')
|
|
74
|
+
reject(new Error('dev session server has no port'));
|
|
75
|
+
else {
|
|
76
|
+
this.port = address.port;
|
|
77
|
+
resolve();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
await this.defaultSession.start();
|
|
82
|
+
}
|
|
83
|
+
mintNonce(author, key = null, experimentVariants) {
|
|
84
|
+
return this.sessionFor(key).mintNonce(author, experimentVariants);
|
|
85
|
+
}
|
|
86
|
+
sessionIdFor(key) {
|
|
87
|
+
return devSessionIdFor(key);
|
|
88
|
+
}
|
|
89
|
+
handleFilesChanged(message) {
|
|
90
|
+
for (const session of this.sessions())
|
|
91
|
+
session.handleFilesChanged(message);
|
|
92
|
+
}
|
|
93
|
+
async shutdown() {
|
|
94
|
+
if (this.closed)
|
|
95
|
+
return;
|
|
96
|
+
this.closed = true;
|
|
97
|
+
const sessions = this.sessions();
|
|
98
|
+
this.named.clear();
|
|
99
|
+
await Promise.all(sessions.map((session) => session.shutdown()));
|
|
100
|
+
await closeHttpServer(this.server);
|
|
101
|
+
}
|
|
102
|
+
shutdownNow() {
|
|
103
|
+
this.closed = true;
|
|
104
|
+
for (const session of this.sessions())
|
|
105
|
+
session.shutdownNow();
|
|
106
|
+
this.named.clear();
|
|
107
|
+
this.server.close();
|
|
108
|
+
}
|
|
109
|
+
sessions() {
|
|
110
|
+
return [this.defaultSession, ...this.named.values()];
|
|
111
|
+
}
|
|
112
|
+
sessionFor(key) {
|
|
113
|
+
if (key === null || this.closed)
|
|
114
|
+
return this.defaultSession;
|
|
115
|
+
const existing = this.named.get(key);
|
|
116
|
+
if (existing)
|
|
117
|
+
return existing;
|
|
118
|
+
// `deck:<name>/<key>` runs another local deck's server, one this deck lists
|
|
119
|
+
// in `devDecks` (contentPack.ts): a door to a separately built deck.
|
|
120
|
+
const other = devDeckSessionKey(this.projectDir, key);
|
|
121
|
+
const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs);
|
|
122
|
+
this.named.set(key, session);
|
|
123
|
+
session.start().catch((error) => {
|
|
124
|
+
this.log('error', `(${key}) start failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
125
|
+
this.stopIdle(key, session);
|
|
126
|
+
});
|
|
127
|
+
return session;
|
|
128
|
+
}
|
|
129
|
+
stopIdle(key, session) {
|
|
130
|
+
if (this.named.get(key) !== session)
|
|
131
|
+
return;
|
|
132
|
+
this.named.delete(key);
|
|
133
|
+
void session.shutdown();
|
|
134
|
+
}
|
|
135
|
+
handleUpgrade(request, socket, head) {
|
|
136
|
+
let url;
|
|
137
|
+
try {
|
|
138
|
+
url = new URL(request.url ?? '/', 'ws://127.0.0.1');
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
rejectUpgrade(socket, 400);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
// A credential nobody owns falls to the default session, which rejects it
|
|
145
|
+
// exactly as a single-session serve always has.
|
|
146
|
+
const owner = this.sessions().find((session) => session.ownsUpgrade(url));
|
|
147
|
+
(owner ?? this.defaultSession).handleUpgrade(request, socket, head, url);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
36
150
|
function serverDirOf(entry) {
|
|
37
151
|
const slash = entry.lastIndexOf('/');
|
|
38
152
|
return slash < 0 ? '' : entry.slice(0, slash + 1);
|
|
@@ -58,12 +172,16 @@ export function serverRestartNeeded(changes, opts) {
|
|
|
58
172
|
const IMPORTED_SERVER_PATH = /^(imports|forks)\/[^/]+\/(code\/)?server\//;
|
|
59
173
|
// The runtime frames that cost the session a frame of its outbound budget.
|
|
60
174
|
const OUTBOUND_FRAME_TYPES = new Set(['sendTo', 'sendBinary', 'broadcast', 'broadcastBinary']);
|
|
61
|
-
|
|
175
|
+
// One running session: its players, roster, reconnect tokens, frame meter and
|
|
176
|
+
// runtime child. The router owns the listener and hands it its upgrades.
|
|
177
|
+
class DevSessionImpl {
|
|
62
178
|
projectDir;
|
|
63
179
|
log;
|
|
64
|
-
|
|
65
|
-
port
|
|
66
|
-
|
|
180
|
+
key;
|
|
181
|
+
port;
|
|
182
|
+
onIdle;
|
|
183
|
+
idleMs;
|
|
184
|
+
sessionId;
|
|
67
185
|
clientWss = new WebSocketServer({
|
|
68
186
|
noServer: true,
|
|
69
187
|
maxPayload: MAX_CLIENT_FRAME_BYTES,
|
|
@@ -95,34 +213,54 @@ class DevSessionServerImpl {
|
|
|
95
213
|
// Everything beside the entry restarts the server too, wherever it lives.
|
|
96
214
|
serverDir;
|
|
97
215
|
serverSettings;
|
|
98
|
-
|
|
216
|
+
// The first boot, which a join that raced it waits on rather than bouncing.
|
|
217
|
+
starting = null;
|
|
218
|
+
idleTimer = null;
|
|
219
|
+
/**
|
|
220
|
+
* `key` null is the default session, which never idles out. A named one calls
|
|
221
|
+
* `onIdle` once it has had nobody connected for `idleMs`.
|
|
222
|
+
*/
|
|
223
|
+
constructor(projectDir, log, key, port, onIdle, idleMs = NAMED_SESSION_IDLE_MS) {
|
|
99
224
|
this.projectDir = projectDir;
|
|
100
225
|
this.log = log;
|
|
226
|
+
this.key = key;
|
|
227
|
+
this.port = port;
|
|
228
|
+
this.onIdle = onIdle;
|
|
229
|
+
this.idleMs = idleMs;
|
|
230
|
+
this.sessionId = devSessionIdFor(key);
|
|
101
231
|
this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
|
|
102
232
|
this.serverDir = serverDirOf(this.serverEntry);
|
|
103
233
|
this.serverSettings = JSON.stringify(readCastleJson(projectDir)?.server ?? null);
|
|
104
|
-
this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
|
|
105
234
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
});
|
|
120
|
-
await this.restartChild();
|
|
235
|
+
start() {
|
|
236
|
+
// A session started for a nonce nobody redeems still idles out.
|
|
237
|
+
this.updateIdle();
|
|
238
|
+
// The first boot goes through the same queue as file-change restarts, so
|
|
239
|
+
// an edit made while it bundles waits for it instead of racing it.
|
|
240
|
+
const run = this.restartQueue.then(() => this.restartChild());
|
|
241
|
+
this.restartQueue = run.catch(() => undefined);
|
|
242
|
+
this.starting = run;
|
|
243
|
+
const clear = () => {
|
|
244
|
+
this.starting = null;
|
|
245
|
+
};
|
|
246
|
+
this.starting.then(clear, clear);
|
|
247
|
+
return this.starting;
|
|
121
248
|
}
|
|
122
|
-
|
|
249
|
+
/** Whether this upgrade carries a credential this session issued. */
|
|
250
|
+
ownsUpgrade(url) {
|
|
251
|
+
if (url.pathname === '/__castle/platform') {
|
|
252
|
+
return !!this.bootToken && url.searchParams.get('bootToken') === this.bootToken;
|
|
253
|
+
}
|
|
254
|
+
const nonce = url.searchParams.get('nonce');
|
|
255
|
+
if (nonce)
|
|
256
|
+
return this.nonces.has(nonce);
|
|
257
|
+
const reconnect = url.searchParams.get('reconnect');
|
|
258
|
+
return !!reconnect && this.reconnects.has(reconnect);
|
|
259
|
+
}
|
|
260
|
+
mintNonce(author, experimentVariants) {
|
|
123
261
|
this.pruneNonces();
|
|
124
262
|
const nonce = randomUUID();
|
|
125
|
-
this.nonces.set(nonce, { author, mintedAt: Date.now() });
|
|
263
|
+
this.nonces.set(nonce, { author, experimentVariants, mintedAt: Date.now() });
|
|
126
264
|
return nonce;
|
|
127
265
|
}
|
|
128
266
|
handleFilesChanged(message) {
|
|
@@ -150,35 +288,38 @@ class DevSessionServerImpl {
|
|
|
150
288
|
async shutdown() {
|
|
151
289
|
if (this.closed)
|
|
152
290
|
return;
|
|
153
|
-
this.
|
|
154
|
-
if (this.restartTimer)
|
|
155
|
-
clearTimeout(this.restartTimer);
|
|
291
|
+
this.markClosed();
|
|
156
292
|
this.closeClients(1001, 'dev serve stopped');
|
|
293
|
+
// A boot or restart still in flight sees `closed` after its awaits and
|
|
294
|
+
// stops short; wait for it so its child and temp dir are cleaned up here.
|
|
295
|
+
await this.restartQueue.catch(() => undefined);
|
|
157
296
|
await this.stopChild();
|
|
158
297
|
await Promise.all([
|
|
159
298
|
closeWebSocketServer(this.clientWss),
|
|
160
299
|
closeWebSocketServer(this.platformWss),
|
|
161
|
-
closeHttpServer(this.server),
|
|
162
300
|
]);
|
|
163
301
|
this.removeTempDir();
|
|
164
302
|
}
|
|
165
303
|
shutdownNow() {
|
|
166
|
-
this.
|
|
167
|
-
if (this.restartTimer)
|
|
168
|
-
clearTimeout(this.restartTimer);
|
|
304
|
+
this.markClosed();
|
|
169
305
|
this.closeClients(1001, 'dev serve stopped');
|
|
170
306
|
this.platformSocket?.terminate();
|
|
171
307
|
this.child?.kill('SIGKILL');
|
|
172
|
-
this.server.close();
|
|
173
308
|
this.removeTempDir();
|
|
174
309
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
310
|
+
markClosed() {
|
|
311
|
+
this.closed = true;
|
|
312
|
+
if (this.restartTimer)
|
|
313
|
+
clearTimeout(this.restartTimer);
|
|
314
|
+
if (this.idleTimer)
|
|
315
|
+
clearTimeout(this.idleTimer);
|
|
316
|
+
this.idleTimer = null;
|
|
317
|
+
}
|
|
318
|
+
handleUpgrade(request, socket, head, url) {
|
|
319
|
+
// A named session's first join can beat its child's boot; hold it until
|
|
320
|
+
// the runtime is up instead of bouncing it.
|
|
321
|
+
if (url.pathname === '/__castle/mp' && !this.runtimeReady && this.starting) {
|
|
322
|
+
this.starting.then(() => this.handleUpgrade(request, socket, head, url), () => rejectUpgrade(socket, 503));
|
|
182
323
|
return;
|
|
183
324
|
}
|
|
184
325
|
if (url.pathname === '/__castle/platform') {
|
|
@@ -257,7 +398,14 @@ class DevSessionServerImpl {
|
|
|
257
398
|
const identity = isFirstConnection ? auth.record.author : this.nextGuest();
|
|
258
399
|
if (isFirstConnection)
|
|
259
400
|
this.primaryPlayerId = playerId;
|
|
260
|
-
|
|
401
|
+
// A guest is the same page-side user in another tab, so it keeps the arms
|
|
402
|
+
// its page was given.
|
|
403
|
+
player = {
|
|
404
|
+
identity,
|
|
405
|
+
experimentVariants: auth.record.experimentVariants,
|
|
406
|
+
reconnectToken: this.rotateReconnect(playerId),
|
|
407
|
+
socket,
|
|
408
|
+
};
|
|
261
409
|
this.players.set(playerId, player);
|
|
262
410
|
}
|
|
263
411
|
else {
|
|
@@ -295,8 +443,13 @@ class DevSessionServerImpl {
|
|
|
295
443
|
protocolVersion: PROTOCOL_VERSION,
|
|
296
444
|
t: 'playerJoined',
|
|
297
445
|
player: { playerId, ...player.identity },
|
|
446
|
+
// Beside the player, never on it: decks broadcast player objects.
|
|
447
|
+
...(player.experimentVariants && Object.keys(player.experimentVariants).length > 0
|
|
448
|
+
? { experimentVariants: player.experimentVariants }
|
|
449
|
+
: {}),
|
|
298
450
|
});
|
|
299
451
|
this.broadcastRoster();
|
|
452
|
+
this.updateIdle();
|
|
300
453
|
}
|
|
301
454
|
handleClientMessage(playerId, socket, data, isBinary) {
|
|
302
455
|
// Frames queued on the superseded socket must not act as the new player.
|
|
@@ -354,6 +507,7 @@ class DevSessionServerImpl {
|
|
|
354
507
|
this.primaryPlayerId = null;
|
|
355
508
|
}
|
|
356
509
|
this.broadcastRoster();
|
|
510
|
+
this.updateIdle();
|
|
357
511
|
}
|
|
358
512
|
attachPlatform(socket) {
|
|
359
513
|
this.platformSocket = socket;
|
|
@@ -481,7 +635,15 @@ class DevSessionServerImpl {
|
|
|
481
635
|
throw new Error('multiplayer server entry is unavailable');
|
|
482
636
|
this.serverEntry = config.entry;
|
|
483
637
|
this.serverDir = serverDirOf(config.entry);
|
|
484
|
-
|
|
638
|
+
// A deck whose doors lead to other local decks (`devDecks`) gets their
|
|
639
|
+
// castle.json at `import.meta.env.CASTLE_DEV_DECKS`, read when it builds.
|
|
640
|
+
const devDecks = devDeckCastleJsons(this.projectDir);
|
|
641
|
+
const define = Object.keys(devDecks).length
|
|
642
|
+
? { 'import.meta.env.CASTLE_DEV_DECKS': JSON.stringify(devDecks) }
|
|
643
|
+
: {};
|
|
644
|
+
const code = await bundleServerModule(this.projectDir, config, false, define);
|
|
645
|
+
if (this.closed)
|
|
646
|
+
return;
|
|
485
647
|
this.removeTempDir();
|
|
486
648
|
this.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-dev-session-'));
|
|
487
649
|
const bundlePath = path.join(this.tempDir, 'server.mjs');
|
|
@@ -497,7 +659,7 @@ class DevSessionServerImpl {
|
|
|
497
659
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
498
660
|
env: {
|
|
499
661
|
...process.env,
|
|
500
|
-
CASTLE_DEV_SESSION_CHANNEL_URL: `ws://127.0.0.1:${this.port}/__castle/platform`,
|
|
662
|
+
CASTLE_DEV_SESSION_CHANNEL_URL: `ws://127.0.0.1:${this.port()}/__castle/platform`,
|
|
501
663
|
CASTLE_DEV_SESSION_BOOT_TOKEN: this.bootToken,
|
|
502
664
|
CASTLE_DEV_SESSION_BUNDLE_PATH: bundlePath,
|
|
503
665
|
},
|
|
@@ -539,12 +701,16 @@ class DevSessionServerImpl {
|
|
|
539
701
|
}
|
|
540
702
|
}
|
|
541
703
|
currentConfig() {
|
|
542
|
-
|
|
704
|
+
const config = resolveServerConfig(this.projectDir) ?? {
|
|
543
705
|
entry: 'server/index.js',
|
|
544
706
|
tickRate: 20,
|
|
545
707
|
maxPlayers: 8,
|
|
546
708
|
voiceEnabled: true,
|
|
547
|
-
}
|
|
709
|
+
};
|
|
710
|
+
// A load test of a session bigger than any deck may declare (a hub town's
|
|
711
|
+
// 100-bot run) raises the cap for this serve only; production never reads it.
|
|
712
|
+
const loadTest = Number(process.env.CASTLE_DEV_SESSION_MAX_PLAYERS);
|
|
713
|
+
return Number.isInteger(loadTest) && loadTest > 0 ? { ...config, maxPlayers: loadTest } : config;
|
|
548
714
|
}
|
|
549
715
|
sendPlatform(frame) {
|
|
550
716
|
if (this.platformSocket?.readyState === WebSocket.OPEN)
|
|
@@ -593,6 +759,24 @@ class DevSessionServerImpl {
|
|
|
593
759
|
player.socket = undefined;
|
|
594
760
|
socket?.close(code, reason);
|
|
595
761
|
}
|
|
762
|
+
this.updateIdle();
|
|
763
|
+
}
|
|
764
|
+
updateIdle() {
|
|
765
|
+
if (this.key === null || this.closed)
|
|
766
|
+
return;
|
|
767
|
+
if (this.connectedPlayers().length > 0) {
|
|
768
|
+
if (this.idleTimer)
|
|
769
|
+
clearTimeout(this.idleTimer);
|
|
770
|
+
this.idleTimer = null;
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
if (this.idleTimer)
|
|
774
|
+
return;
|
|
775
|
+
this.idleTimer = setTimeout(() => {
|
|
776
|
+
this.idleTimer = null;
|
|
777
|
+
if (this.connectedPlayers().length === 0)
|
|
778
|
+
this.onIdle();
|
|
779
|
+
}, this.idleMs);
|
|
596
780
|
}
|
|
597
781
|
kick(playerId, reason) {
|
|
598
782
|
const player = this.players.get(playerId);
|
|
@@ -607,6 +791,7 @@ class DevSessionServerImpl {
|
|
|
607
791
|
player.socket.close(4002, 'kicked');
|
|
608
792
|
}
|
|
609
793
|
this.broadcastRoster();
|
|
794
|
+
this.updateIdle();
|
|
610
795
|
}
|
|
611
796
|
rotateReconnect(playerId) {
|
|
612
797
|
const token = randomUUID();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface ExperimentAssignmentConfig {
|
|
2
|
+
variants: readonly string[];
|
|
3
|
+
weights?: readonly number[];
|
|
4
|
+
winner?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare const EXPERIMENT_BUCKETS = 1000;
|
|
7
|
+
/** 0 through 999: the first 8 bytes of SHA-256, big-endian, mod 1000. */
|
|
8
|
+
export declare function experimentBucket(userId: string, deckId: string, name: string): number;
|
|
9
|
+
/**
|
|
10
|
+
* The split used when `weights` is omitted: 100 shared equally, the remainder
|
|
11
|
+
* going one point at a time to the earliest variants (three variants are
|
|
12
|
+
* 34, 33, 33).
|
|
13
|
+
*/
|
|
14
|
+
export declare function equalExperimentWeights(count: number): number[];
|
|
15
|
+
export declare function assignExperimentVariant(userId: string, deckId: string, name: string, config: ExperimentAssignmentConfig): string;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Which variant of a deck experiment a player gets. Pure, and the SAME function
|
|
2
|
+
// Castle's server runs (ghost-server): `castle-web serve` answers with it so a
|
|
3
|
+
// deck sees in dev the arm its player would get once published, and the fixed
|
|
4
|
+
// vectors in scripts/tests/experiments.mjs are asserted on both sides. Change
|
|
5
|
+
// one and the other has to change with it.
|
|
6
|
+
//
|
|
7
|
+
// Nothing is stored. The bucket is a hash of the player, the deck and the
|
|
8
|
+
// experiment's name, so it is the same on every load, differs between
|
|
9
|
+
// experiments and between decks, and moves a player only when a change to
|
|
10
|
+
// `variants` or `weights` moves the boundary their bucket sits beside.
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
export const EXPERIMENT_BUCKETS = 1000;
|
|
13
|
+
/** 0 through 999: the first 8 bytes of SHA-256, big-endian, mod 1000. */
|
|
14
|
+
export function experimentBucket(userId, deckId, name) {
|
|
15
|
+
const hex = createHash('sha256').update(`${userId}:${deckId}:${name}`, 'utf8').digest('hex');
|
|
16
|
+
return Number(BigInt(`0x${hex.slice(0, 16)}`) % BigInt(EXPERIMENT_BUCKETS));
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The split used when `weights` is omitted: 100 shared equally, the remainder
|
|
20
|
+
* going one point at a time to the earliest variants (three variants are
|
|
21
|
+
* 34, 33, 33).
|
|
22
|
+
*/
|
|
23
|
+
export function equalExperimentWeights(count) {
|
|
24
|
+
const base = Math.floor(100 / count);
|
|
25
|
+
const extra = 100 - base * count;
|
|
26
|
+
return Array.from({ length: count }, (_, index) => base + (index < extra ? 1 : 0));
|
|
27
|
+
}
|
|
28
|
+
export function assignExperimentVariant(userId, deckId, name, config) {
|
|
29
|
+
if (config.winner !== undefined)
|
|
30
|
+
return config.winner;
|
|
31
|
+
const weights = config.weights ?? equalExperimentWeights(config.variants.length);
|
|
32
|
+
const bucket = experimentBucket(userId, deckId, name);
|
|
33
|
+
let upper = 0;
|
|
34
|
+
for (let index = 0; index < config.variants.length; index += 1) {
|
|
35
|
+
upper += weights[index] * 10;
|
|
36
|
+
if (bucket < upper)
|
|
37
|
+
return config.variants[index];
|
|
38
|
+
}
|
|
39
|
+
// Unreachable for a validated block, whose weights sum to 100.
|
|
40
|
+
return config.variants[config.variants.length - 1];
|
|
41
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type DeckImport } from './castleJson.js';
|
|
2
|
+
/** The alias a deck's OWN `onCheck` is reported under. */
|
|
3
|
+
export declare const SELF_CHECK_ALIAS = "self";
|
|
4
|
+
export interface ImportCheckOutcome {
|
|
5
|
+
alias: string;
|
|
6
|
+
errors: string[];
|
|
7
|
+
warnings: string[];
|
|
8
|
+
}
|
|
9
|
+
export interface ImportChecksResult {
|
|
10
|
+
outcomes: ImportCheckOutcome[];
|
|
11
|
+
/** Every error, each prefixed with the alias whose check raised it. */
|
|
12
|
+
errors: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface CheckTarget {
|
|
15
|
+
alias: string;
|
|
16
|
+
importDir: string;
|
|
17
|
+
declared: string;
|
|
18
|
+
/** The import's pin, or null for the deck's own check. */
|
|
19
|
+
pin: DeckImport | null;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Run every applicable `onCheck`, one at a time, and collect what they found.
|
|
23
|
+
* Warnings are logged here; errors are returned for the caller to refuse on --
|
|
24
|
+
* `check` exits non-zero, `save-deck` publishes nothing.
|
|
25
|
+
*/
|
|
26
|
+
export declare function runImportChecks(deckDir: string, log?: (message: string) => void): Promise<ImportChecksResult>;
|
|
27
|
+
/** The castle.json hooks an import names that run against the deck importing it. */
|
|
28
|
+
export type HookField = 'onCheck' | 'onPack';
|
|
29
|
+
export interface RunnableImportHook {
|
|
30
|
+
target: CheckTarget;
|
|
31
|
+
modulePath: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Every `field` hook that applies to this deck and may run here, in order: each
|
|
35
|
+
* import's, then the deck's own. One that cannot be run from where its pin says
|
|
36
|
+
* it comes from, or is not on the trusted account, is logged and left out.
|
|
37
|
+
*/
|
|
38
|
+
export declare function runnableImportHooks(deckDir: string, field: HookField, log: (message: string) => void): Promise<RunnableImportHook[]>;
|
|
39
|
+
/** The message `check` and `save-deck` refuse with. */
|
|
40
|
+
export declare function importChecksFailedMessage(errors: string[]): string;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Running every import's `onCheck`: the gate a kit adds to `castle-web check`
|
|
2
|
+
// and `save-deck` for the decks built on it.
|
|
3
|
+
//
|
|
4
|
+
// The CLI knows nothing about what a check looks at. An import names a module of
|
|
5
|
+
// its own (castle.json `onCheck`, see castleJson.ts for the contract); the CLI
|
|
6
|
+
// runs it in a child, collects the errors and warnings it returns, and refuses
|
|
7
|
+
// the build when there is an error. Whatever a check knows about scenes,
|
|
8
|
+
// blueprints or a server's shape stays on the other side of that boundary.
|
|
9
|
+
//
|
|
10
|
+
// Unlike `onUpdate` there is no version saved first and nothing to roll back: a
|
|
11
|
+
// check is READ-ONLY by contract. It is still somebody else's code with the
|
|
12
|
+
// deck's files in reach, so it answers to the same account gate an update hook
|
|
13
|
+
// does (importTrust.ts).
|
|
14
|
+
import * as fs from 'fs';
|
|
15
|
+
import * as path from 'path';
|
|
16
|
+
import { IMPORTS_DIR, readCastleJson } from './castleJson.js';
|
|
17
|
+
import { getKitsDir } from './localPaths.js';
|
|
18
|
+
import { execHookModule, failureDetail, HOOK_RESULT_PREFIX, outputLines, resolveFileInside, } from './importUpdateHook.js';
|
|
19
|
+
import { importIsOnTrustedAccount, TRUSTED_IMPORT_ACCOUNT } from './importTrust.js';
|
|
20
|
+
/** The alias a deck's OWN `onCheck` is reported under. */
|
|
21
|
+
export const SELF_CHECK_ALIAS = 'self';
|
|
22
|
+
// Whether `dir` is one of the kits this CLI ships, checked as itself.
|
|
23
|
+
function isShippedKitDir(dir) {
|
|
24
|
+
const kits = path.resolve(getKitsDir());
|
|
25
|
+
const rel = path.relative(kits, path.resolve(dir));
|
|
26
|
+
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel) && !rel.includes(path.sep);
|
|
27
|
+
}
|
|
28
|
+
// The module a target runs, or null when there is none it may run. A builtin
|
|
29
|
+
// pin says "the CLI's own copy of this kit", so the module is taken from that
|
|
30
|
+
// copy -- never from the files in `imports/`, which a pin can name `builtin`
|
|
31
|
+
// while they came from anywhere. The deck's own check runs only for a kit this
|
|
32
|
+
// CLI ships, checked as itself (its `npm run check`): any other deck's own
|
|
33
|
+
// module is code nobody has vouched for.
|
|
34
|
+
function targetModule(target, deckDir, field) {
|
|
35
|
+
if (target.pin === null) {
|
|
36
|
+
return isShippedKitDir(deckDir) ? resolveFileInside(target.importDir, target.declared) : null;
|
|
37
|
+
}
|
|
38
|
+
if (target.pin.source === 'builtin') {
|
|
39
|
+
const kit = typeof target.pin.kit === 'string' ? target.pin.kit : '';
|
|
40
|
+
const kitDir = path.join(getKitsDir(), kit);
|
|
41
|
+
if (!kit || !isShippedKitDir(kitDir) || !fs.existsSync(path.join(kitDir, 'castle.json')))
|
|
42
|
+
return null;
|
|
43
|
+
const declared = readCastleJson(kitDir)?.[field];
|
|
44
|
+
return typeof declared === 'string' && declared.trim() ? resolveFileInside(kitDir, declared) : null;
|
|
45
|
+
}
|
|
46
|
+
return resolveFileInside(target.importDir, target.declared);
|
|
47
|
+
}
|
|
48
|
+
// Every check that applies to this deck: each import that declares one, then
|
|
49
|
+
// the deck's own. The deck's own runs with itself as `importDir` -- that is how
|
|
50
|
+
// a kit's `npm run check` exercises the check it ships, against its own tree.
|
|
51
|
+
function checkTargets(deckDir, field) {
|
|
52
|
+
const config = readCastleJson(deckDir);
|
|
53
|
+
const targets = [];
|
|
54
|
+
for (const [alias, pin] of Object.entries(config?.imports ?? {})) {
|
|
55
|
+
const importDir = path.join(deckDir, IMPORTS_DIR, alias);
|
|
56
|
+
const declared = readCastleJson(importDir)?.[field];
|
|
57
|
+
if (pin && typeof declared === 'string' && declared.trim()) {
|
|
58
|
+
targets.push({ alias, importDir, declared, pin });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const own = config?.[field];
|
|
62
|
+
if (typeof own === 'string' && own.trim()) {
|
|
63
|
+
targets.push({ alias: SELF_CHECK_ALIAS, importDir: deckDir, declared: own, pin: null });
|
|
64
|
+
}
|
|
65
|
+
return targets;
|
|
66
|
+
}
|
|
67
|
+
// A builtin pin is the CLI's own copy of one of its kits, so it is exactly as
|
|
68
|
+
// trusted as the CLI running it. A fetched one asks the account gate, lazily --
|
|
69
|
+
// only an import that actually ships a check pays for the lookup. The deck's
|
|
70
|
+
// own check is the deck's own code, which `check` is already running.
|
|
71
|
+
async function targetIsTrusted(target) {
|
|
72
|
+
if (target.pin === null || target.pin.source === 'builtin')
|
|
73
|
+
return true;
|
|
74
|
+
if (!target.pin.deckId)
|
|
75
|
+
return false;
|
|
76
|
+
return importIsOnTrustedAccount(target.pin.deckId);
|
|
77
|
+
}
|
|
78
|
+
function stringList(value) {
|
|
79
|
+
if (value === undefined)
|
|
80
|
+
return [];
|
|
81
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string'))
|
|
82
|
+
return null;
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
// The verdict the runner printed last. Anything that is not the declared shape
|
|
86
|
+
// is an error in the check itself, reported as one -- a check that cannot say
|
|
87
|
+
// what it found has not passed.
|
|
88
|
+
function parseVerdict(stdout) {
|
|
89
|
+
const line = outputLines(stdout)
|
|
90
|
+
.reverse()
|
|
91
|
+
.find((l) => l.startsWith(HOOK_RESULT_PREFIX));
|
|
92
|
+
let result = null;
|
|
93
|
+
try {
|
|
94
|
+
result = line ? JSON.parse(line.slice(HOOK_RESULT_PREFIX.length)) : null;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
result = null;
|
|
98
|
+
}
|
|
99
|
+
const shape = result && typeof result === 'object' ? result : null;
|
|
100
|
+
const errors = stringList(shape?.errors);
|
|
101
|
+
const warnings = stringList(shape?.warnings);
|
|
102
|
+
if (!shape || !errors || !warnings) {
|
|
103
|
+
return {
|
|
104
|
+
errors: ['its check did not return { errors: string[], warnings: string[] }.'],
|
|
105
|
+
warnings: [],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { errors, warnings };
|
|
109
|
+
}
|
|
110
|
+
async function runOneCheck(deckDir, target, modulePath, log) {
|
|
111
|
+
// `self` is decided here, not from the alias: an import may be added under any
|
|
112
|
+
// name, `self` included.
|
|
113
|
+
const context = { deckDir, importDir: target.importDir, alias: target.alias, self: target.pin === null };
|
|
114
|
+
let output;
|
|
115
|
+
try {
|
|
116
|
+
output = await execHookModule(modulePath, context, deckDir, { reportResult: true });
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
// A throw, a non-zero exit and the clock running out all land here.
|
|
120
|
+
return { alias: target.alias, errors: [`its check failed: ${failureDetail(e)}`], warnings: [] };
|
|
121
|
+
}
|
|
122
|
+
const chatter = [...outputLines(output.stdout), ...outputLines(output.stderr)].filter((line) => !line.startsWith(HOOK_RESULT_PREFIX));
|
|
123
|
+
for (const line of chatter)
|
|
124
|
+
log(`${target.alias} check: ${line}`);
|
|
125
|
+
return { alias: target.alias, ...parseVerdict(output.stdout) };
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Run every applicable `onCheck`, one at a time, and collect what they found.
|
|
129
|
+
* Warnings are logged here; errors are returned for the caller to refuse on --
|
|
130
|
+
* `check` exits non-zero, `save-deck` publishes nothing.
|
|
131
|
+
*/
|
|
132
|
+
export async function runImportChecks(deckDir, log = (message) => console.log(message)) {
|
|
133
|
+
const outcomes = [];
|
|
134
|
+
for (const { target, modulePath } of await runnableImportHooks(deckDir, 'onCheck', log)) {
|
|
135
|
+
const outcome = await runOneCheck(deckDir, target, modulePath, log);
|
|
136
|
+
for (const warning of outcome.warnings)
|
|
137
|
+
log(`Warning (${target.alias}): ${warning}`);
|
|
138
|
+
outcomes.push(outcome);
|
|
139
|
+
}
|
|
140
|
+
const errors = outcomes.flatMap((o) => o.errors.map((error) => `${o.alias}: ${error}`));
|
|
141
|
+
return { outcomes, errors };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Every `field` hook that applies to this deck and may run here, in order: each
|
|
145
|
+
* import's, then the deck's own. One that cannot be run from where its pin says
|
|
146
|
+
* it comes from, or is not on the trusted account, is logged and left out.
|
|
147
|
+
*/
|
|
148
|
+
export async function runnableImportHooks(deckDir, field, log) {
|
|
149
|
+
const runnable = [];
|
|
150
|
+
const noun = field === 'onCheck' ? 'check' : 'content pack exporter';
|
|
151
|
+
for (const target of checkTargets(deckDir, field)) {
|
|
152
|
+
const modulePath = targetModule(target, deckDir, field);
|
|
153
|
+
if (!modulePath) {
|
|
154
|
+
log(target.pin === null
|
|
155
|
+
? `Warning: this deck declares its own ${noun}, which runs only for a kit the CLI ships -- skipped.`
|
|
156
|
+
: `Warning: "${target.alias}" declares a ${noun} at "${target.declared}" that cannot be run from where its pin says it comes from -- skipping it.`);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (!(await targetIsTrusted(target))) {
|
|
160
|
+
log(`Warning: ${target.alias} ships a ${noun}, which only runs for imports on the ` +
|
|
161
|
+
`${TRUSTED_IMPORT_ACCOUNT} account -- skipped.`);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
runnable.push({ target, modulePath });
|
|
165
|
+
}
|
|
166
|
+
return runnable;
|
|
167
|
+
}
|
|
168
|
+
/** The message `check` and `save-deck` refuse with. */
|
|
169
|
+
export function importChecksFailedMessage(errors) {
|
|
170
|
+
return [`Deck check failed:`, ...errors.map((error) => ` - ${error}`)].join('\n');
|
|
171
|
+
}
|